* [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read
@ 2026-11-18 14:04 Rodolfo Giometti
2026-11-18 14:04 ` [RFC PATCH 1/9] KEYS: keycrypt: Add a key type for keys user space never reads Rodolfo Giometti
` (10 more replies)
0 siblings, 11 replies; 14+ messages in thread
From: Rodolfo Giometti @ 2026-11-18 14:04 UTC (permalink / raw)
To: David Howells, Jarkko Sakkinen, keyrings
Cc: Herbert Xu, David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, Rodolfo Giometti
This RFC proposes a key type, "keycrypt", whose material user space can
use for symmetric operations but never read: AES-256-CBC, HMAC-SHA256
and an authenticated AES-256-GCM stream, through a file descriptor that
KEYCTL_CRYPT_OPEN returns for one key and one operation. The key is held
by a backend: the kernel itself (sealed under a trusted key), an OP-TEE
trusted application, or, as a proposal only, the CAAM. I am asking
whether this is a direction the keyrings, crypto and TEE maintainers
would take, before polishing it further.
Patch 9, the authenticated stream, is a proposal on its own and not
needed by the rest of the series: it is a construction of keycrypt's
own, and patches 1-8 do not depend on it, so it can be discussed, or
left out, apart from them. No user-space consumer uses the stream or
HMAC-SHA256 yet: craf (below) uses CBC only. If this direction is found
acceptable, one of the next steps is to bring craf's keycrypt backend
into craf's main line, with the stream and HMAC-SHA256, as long as
doing so does not stand in the way of this RFC or of the series I hope
will follow it.
The problem
-----------
An embedded product that encrypts its own data (a root filesystem
archive, configuration backups, logs) needs a key that does not sit in
the root filesystem and that a compromised user space cannot copy. Today
user space either reads the key (a user or logon key handed to AF_ALG)
or cannot use it at all (a trusted key serves kernel consumers only).
AF_ALG, the one interface that let user space drive a key the kernel
held, has moved away from that use: v7.2 dropped off-CPU cryptography
from it (7524070f26d8, "crypto: af_alg - Drop support for off-CPU
cryptography"), whose message says "If using an off-CPU accelerator
really does turn out to be a win, a new API should be developed that is
actually a good fit for it", and v7.3 restricted it to allowlisted
generic algorithms by default (2f204fe718f5, the af_alg_restrict
sysctl). One exception was let back in, cbc(paes) with a CAAM blob in
place of the key, because "this crypto operation cannot be implemented
in a userspace library" (285d8204638c, v7.2), for privileged users only
(d9506e82ced5, v7.3): the need is acknowledged, for one driver and
one mode. keycrypt is meant to be the API that 7524070f26d8 asks for,
for keys that stay in a TEE or in hardware, whatever the backend.
The interface
-------------
1. A key type, "keycrypt", created with add_key() from "new <alg>
<purposes> [tier=|min-tier=] [backend=]", "load <blob>
[accepted-min-tier=] [purpose=]" or, when allowed, "import <alg>
<purposes> [tier=|min-tier=] [backend=] <hex>". User space states the
protection a key needs, as a tier, and the kernel chooses the backend
that provides it, unless backend= names one. backend= is a constraint
added to the tier, never one in its place: a named backend that does
not meet tier= or min-tier= gives ENODEV, not a weaker key. It is for
a system with more than one backend, an i.MX8 with both the CAAM and
OP-TEE say, where a program must choose which mechanism holds a key
(the cost of each call, what the key is bound to) and not only how
well; the name chooses among mechanisms that meet the tier asked for,
it never lowers a tier asked for (without one, it takes that backend
at the tier it declares, so a program that needs a tier states it).
Its payload read back is a blob that only that backend can open; the
material itself never reaches user space.
2. Each key is bound, when it is made, to one algorithm and to the
purposes it may serve, checked at every open:
a. encrypt and decrypt, for aes256-cbc and aes256-gcm-stream keys:
a key that may only encrypt lets a device write data it cannot
read back, a key that may only decrypt the reverse;
b. mac and verify, for hmac-sha256 keys: "mac" computes a tag over
data, "verify" only checks a tag given by the caller, so a
component holding a verify-only key can authenticate data (a
configuration, an update) but cannot produce a tag that would
pass. VERIFY takes the expected tag at FINAL and answers 0 or
EBADMSG; the tag it computed never leaves the backend. For
example, a server authenticates the commands it sends to a fleet
of devices with HMAC-SHA256, and every device holds the same key,
imported at the factory as verify-only. With a plain HMAC key,
root on one device could extract it and forge commands for the
whole fleet; with a verify-only keycrypt key held by a tee or hsm
backend, a compromised device can still check commands but can
neither read the key nor compute a tag that passes. It comes
close to what a signature gives (everyone verifies, only the
server signs), with a MAC, as long as no device's TEE or HSM is
broken: the key is the fleet's, so the device that breaks forges
for all of it, which a signature would not allow.
3. KEYCTL_CRYPT_OPEN (keyctl 33) opens an operation context on a key and
returns an fd; ioctls on it: KEYCRYPT_IOC_UPDATE, KEYCRYPT_IOC_FINAL,
KEYCRYPT_IOC_SEGMENT (the GCM stream, patch 9) and KEYCRYPT_IOC_INFO,
which tells a program holding only the fd (passed by SCM_RIGHTS, say)
the operation, the minimum tier it was opened with, and the
algorithm, purposes, tier, origin and backend of the key it is using.
Search permission on the key is the right to open it; the caller may
name the lowest tier it accepts (accepted_min_tier), and a key below
it is refused.
4. Policies: kernel.keys.keycrypt_system_tier and
kernel.keys.keycrypt_import (also the boot parameters
keycrypt.system_tier= and keycrypt.import=), one-way, so that a
system can refuse the use of low-tier keys or clear-key import for
good. The system tier is a floor on use only: keys below it can
still be made and loaded, but KEYCTL_CRYPT_OPEN refuses them. Its
starting value is chosen at build time
(CONFIG_KEYCRYPT_SYSTEM_TIER_*), so a signed kernel image carries a
floor its command line cannot lower; likewise, a kernel built
without CONFIG_KEYCRYPT_IMPORT refuses import whatever its command
line or sysctl say.
5. EOPNOTSUPP from KEYCTL_CRYPT_OPEN means "not a keycrypt key", or a
kernel without keycrypt, so a library may fall back to another
interface on it; ENODEV means no backend can run the key.
Tiers and what a compromised kernel can do
------------------------------------------
Each backend declares a tier, and the open path checks it against the
system tier and the caller's accepted minimum:
tier key in clear purpose enforced by who may use the key
in the kernel
kernel yes the kernel the kernel
engine no the kernel the kernel
tee no the TA the kernel
hsm no the HSM the kernel
The last column is the limit of the mechanism: a compromised kernel can
use a tee or hsm key for the purposes it already has, but cannot extract
it or change its purpose. Documentation/security/keys/keycrypt.rst,
"Backend requirements", is the contract a tee or hsm backend must meet.
1. kernel: the keys are in clear in kernel memory while loaded. It is
there so that the same interface works on a system with no TEE and
no suitable hardware, where it still keeps the key out of user space
and out of the root filesystem; its one backend, sw, is off by
default (CONFIG_KEYCRYPT_SW), and a system that has one of the
other tiers should use it, engine at least, and raise the system
tier accordingly. Raising it stops the use of kernel-tier keys, not
their presence: one created or loaded below it is in clear all the
same, as its trusted master is, so a system that must have none
builds without CONFIG_KEYCRYPT_SW.
2. engine: a crypto engine the kernel drives keeps the key, never in
clear in the kernel, but its use is decided by the kernel only. It
comes in patch 6, on its own, so that patches 1-5 stand without a
tier no backend of theirs declares. The CAAM backend of this series
is an engine, since the CAAM does not check what a key is used for;
an ELE backend (below) would start as an engine too, and could move
to hsm once the firmware is confirmed to enforce a key's purpose. If
more such shades appear, a separate property may fit better than
more tiers, and I would welcome an opinion.
3. tee: the OP-TEE backend; the TA re-checks every operation against
the purposes it bound when the key was sealed.
4. hsm: as tee, in dedicated hardware apart from the CPU running the
kernel (a secure element, a security core of its own such as NXP's
EdgeLock Enclave, a crypto engine with its own policy), the place of
Android KeyMint's StrongBox; no backend in this series.
The backends
------------
1. sw, of the kernel tier (no name is both a tier's and a backend's):
keys sealed with AES-256-GCM under a key derived with HMAC-SHA256
from a trusted key (any trusted-key source); HKDF-derived stream
subkeys; lib/crypto AES. Where the trusted key
comes from a TPM, the TPM only unseals that master when a key is
loaded; the data itself is ciphered on the CPU, never by the TPM.
2. OP-TEE: a trusted application, an early TA, REE kernel login only;
it derives its sealing key from OP-TEE's hardware-unique-key
service. The TA is written (ta/keycrypt, one patch to optee_os) and
is the one that ran on the hardware below, but I have not proposed
it to OP-TEE yet: I would first like to know whether this direction
can go on. I can publish it for anyone who wants to try it and is
willing to support the work.
3. CAAM: patches 7 and 8, a proposal and not to be applied as they
are.
They are based on Richard Weinberger's "crypto: caam" series v1 (see
"Base and prerequisites") and never ran on a CAAM. Questions for the
CAAM maintainers:
a. is an internal cbc(paes) taking the caller's key modifier an
acceptable form;
b. can a job generate a key in the CAAM and keep it black without it
crossing kernel memory;
c. can the use of a key be checked by something a compromised kernel
does not drive: trusted descriptors, which would let the CAAM
itself enforce a key's purpose and make the backend hsm, or a job
ring owned by the secure world, which would make it tee;
d. could cbc(paes) take CCM black keys, which are authenticated where
ECB ones are not, once the driver handles their extra length
(Weinberger's series refuses them, so the backend uses ECB).
4. ELE (i.MX9), not in this series: this is an RFC, and I am not an
expert of the enclave, so I would rather know first what NXP thinks
of it, and whether they would be willing to propose an ELE backend
themselves, as an engine or, better, as an hsm. As far as I can see,
the se_if driver in linux-next gives user space a misc device with a
generic send-and-receive ioctl for the enclave's messages, and offers
nothing to other kernel code. A per-operation in-kernel API exported
by that driver (open a key store reserved to the kernel, generate a
key, import a wrapped one, read a key's attributes, delete it,
AES-CBC and MAC in one call) would let a keycrypt backend use the
enclave. Questions for NXP:
a. does the firmware enforce a key's key_usage and permitted_algo on
every operation, min_mac_length when verifying, and never release
a generated key in clear (yes to all three would make the backend
hsm rather than engine);
b. could a key be exported wrapped under a device-unique key and
imported again, so that a keycrypt blob holds the key itself
rather than a reference to the enclave's key store;
c. is the key that wraps an imported key unique per device;
d. the user-space library has a streaming MAC (hsm_mac() with its
INIT, UPDATE_DATA and FINALIZE flags): would the firmware offer
it to the kernel for a key in its key store;
e. can a key_id be reused after a key is deleted (the library's
documentation does not say);
f. would a per-operation API of this kind answer the objection Arnd
Bergmann raised to the generic passthrough
(<2034fb2f-f169-46a5-85e8-fa723ddb0360@app.fastmail.com>).
Base and prerequisites
----------------------
The series is based on mainline v7.4-rc2-92 (067c5c24cef2). Patches
1-6, and patch 9 on top of them, apply on it alone. Patches 7 and 8, the
CAAM proposal, need Richard
Weinberger's "crypto: caam" series v1
(<20260726081504.2182951-1-richard@nod.at>, three patches, listed as
prerequisites below) applied first, for example with:
b4 am -o - 20260726081504.2182951-1-richard@nod.at | git am
Testing
-------
The series comes without its tests. There are KUnit suites for the
core and the sw, OP-TEE and CAAM backends, and a kselftest for the user
ABI, with a case for every reachable row of keycrypt.rst's error
tables; together they are larger than the code they test, so I am
keeping them for the non-RFC series, once the direction is agreed. The
results below that name them come from the series with the tests in it.
Taking them out removed only the tests and the hooks that let them
reach the code's internals (static functions made visible and exported
to KUnit modules): with CONFIG_KUNIT off, the posted patches build for
arm64 to the same instructions as that series.
On that base, with Weinberger's three patches applied: built for arm64
with W=1 (security/keys/keycrypt/ and drivers/crypto/caam/, no
warning), and, with the tests on top, the KUnit suites pass on UML
but for the one case that needs the system tier above kernel (by
Kconfig or boot parameter). Patches 1-6 and 9 alone, on the base without
Weinberger's patches: the same build of security/keys/keycrypt/, no
warning.
The runs below were made on that series at v7.3 on QEMU, and, without
the CAAM code, backported to NXP's 6.18, on QEMU and on hardware:
1. QEMU (qemuarm64-secureboot, OP-TEE 4.9.0, an fTPM as the source of
the trusted master): the KUnit suites and the kselftest passed on
the sw and OP-TEE backends, a case skipped only where its backend
was absent (the CAAM) or where it needs a one-way policy setting;
the TA's unbind and bind; persistence of a blob across a restart.
QEMU proves function, not secrecy: its hardware unique key is a stub.
2. Hardware: the series, backported to NXP's linux-imx lf-6.18.2-1.0.0
(six upstream prerequisites; the two CAAM patches left out), with the
TA built as an early TA into NXP's imx-optee-os 4.8.0, ran on an
i.MX93 board with secure boot closed (AHAB), where OP-TEE derives the
key that seals the TA's key blobs from the EdgeLock Enclave's
hardware unique key. The KUnit suites and the kselftest passed on
the OP-TEE backend, a case skipped only where its backend was absent
(sw, which 6.18 cannot build for lack of the library AES it needs,
and the CAAM, left out) or where it needs a one-way policy setting.
A key generated in OP-TEE and kept as its blob
was loaded back after a reboot and after a full power-off, and
decrypted a file encrypted before them. The same AES-256-CBC key and
IV through AF_ALG (cbc-aes-ce), through keycrypt and through openssl
gave identical ciphertexts.
3. Cost on that board (Cortex-A55), AES-256-CBC, per call on an open
context: keycrypt with the OP-TEE backend 59-62us up to 256 bytes,
~106us at 4KiB, 880-930us at 64KiB (67-71MiB/s); AF_ALG cbc-aes-ce
6-7, 12-14 and 110-138us (454-570MiB/s). Opening a context costs
~500us, against ~9us for an AF_ALG accept on a keyed socket (~25us
for the whole AF_ALG setup). OP-TEE's own benchmark (xtest
--aes-perf, from user space through libteec) on the same board gives
~64us per call plus ~1.5ns per byte. keycrypt's fixed cost matches
that round trip to the secure world; its remaining ~11ns per byte is
spent in this prototype's own data path (buffer allocation and
copies between user space, kernel, shared memory and the TA); which
part dominates is not yet measured, and it is to be reduced.
A user-space consumer exists: craf, the archive tool of crypto-afalg,
has a keycrypt backend on the keycrypt branch of
https://github.com/giometti/crypto-afalg (tag keycrypt-board-5 is the
version that ran on the hardware above). Its enc command, an openssl
enc that takes its key from the keyring, shows what a keycrypt key
carries. A key made once as
k=$(keyctl add keycrypt demo \
"new aes256-cbc encrypt,decrypt min-tier=tee" @u)
is bound there to AES-256-CBC, to encrypting and decrypting, and to a
backend of tier tee at least, chosen by the kernel; so
craf enc -enc-key $k -iv <hex> < plain > cipher
craf enc -d -enc-key $k -iv <hex> < cipher > plain
need nothing else: the open takes no algorithm and no backend, the key
brings them, and its tier is enforced by the kernel against
-enc-min-tier or the system's tier. Any other key goes to AF_ALG, and
the command line must name the cipher. On the board, craf enc with an
imported keycrypt key and openssl enc with the same key bytes and IV
each decrypted what the other encrypted.
While testing the user-space side of this series, craf's test suite hit
the KEYCTL_PKEY_VERIFY regression of cb481e59ea6c, which lets a short
RSA signature verify: it is fixed by Florian Bauckholt's patch [1], and
the reproducer was reported in [2].
[1] https://lore.kernel.org/keyrings/20261111-keyctl-pkey-fixes-v1-1-934ebaa267a7@cispa.de/
[2] https://lore.kernel.org/all/0e20f799-e389-40d2-aaee-2f174748faae@enneenne.com/
Why not AF_ALG or KEYCTL_PKEY_*
-------------------------------
They are the two existing interfaces through which user space uses a
key it does not read, so they are the first alternatives a reviewer
will name; keycrypt.rst has a section on them.
1. AF_ALG takes a trusted key by serial (ALG_SET_KEY_BY_KEY_SERIAL),
but copies its payload into the socket, ties it to no algorithm and
no purpose, and runs it on whatever implementation the socket is
bound to, since v7.2 only on the CPU but for cbc(paes); extending it
would mean adding purposes, tiers and off-CPU backends to what it
has just removed.
2. KEYCTL_PKEY_* already lets user space use a key without reading it,
but for asymmetric keys, one operation per call; a symmetric mode
needs state across calls (the CBC chain, the stream's segments),
which an fd holds naturally.
Whether one of them should be extended instead is the first question I
would like answered.
Known limits
------------
Some are limits of the design, kept on purpose:
1. Only the sw backend is self-contained in the tree; every guarantee
against a compromised kernel is a requirement on the other backends,
which "Backend requirements" in keycrypt.rst sets out.
2. Kernel-tier keys are in clear in kernel memory while loaded: that
tier is there for systems with nothing better, and a system that has
more can refuse it (above).
3. The tier is declared by the backend, not proven: the kernel cannot
check what a TEE or a piece of hardware does, so it records and
enforces what the backend declares.
4. A blob is a bearer credential, and a process that possesses a key
can read its blob: what binds the key is the backend's secret,
unique to the device, and the purposes sealed with it, not the blob.
5. CBC is unauthenticated and is a raw AES oracle for its holder: it is
there for the formats that need it, and the GCM stream is the
authenticated choice. The stream is not key-committing, which a
format trying several keys must handle (keycrypt.rst says how), and
is bounded at 2^32-1 segments, 256TiB at 64KiB each.
The others I plan to address if this direction is taken:
6. Checks happen at open only, so an open context survives a raised
policy or removed Search (revocation closes it): raising a policy
would close the contexts it no longer allows, as revocation does.
Whether Search should be the use permission is among the points
below.
7. import moves a clear key through kernel memory: an encrypted import,
wrapped for the backend, would avoid it. Policies are global: they
could follow namespaces, if that is wanted, and stay one-way.
8. The GCM stream has no seek: decryption could start at a given
segment (keycrypt.rst leaves room for it in the open parameters);
encryption never will, so that no counter is used twice.
9. OP-TEE backend: its control session is not reopened after a TA
panic, the TA's session limit is a build constant, and every context
has shared buffers of its own: the session would be reopened, the
limit made configurable, and the buffers taken from a pool, as part
of the work on the per-byte cost above.
10. No keyutils or man-page support yet: to be added.
Other points I would like opinions on:
1. two KDFs and a stream construction living in security/keys rather
than reusable primitives;
2. Search as the use permission;
3. an rwsem held across sleeping backend calls;
4. whether a KEYCTL_CAPS1_* bit telling a process once that keycrypt
is there would help (not in this series).
Not in this RFC: signatures, ECDH, encrypted import, io_uring, other
modes; ELE code; external secure elements as backends.
How this series was made
------------------------
This work comes from a project to strengthen the secure-boot chain of
embedded Linux systems.
I used an AI coding assistant, Anthropic's Claude (claude-opus-5-5 in
Claude Code), in the sense of
Documentation/process/coding-assistants.rst. However, the way the
problem is solved is mine: a new key type, so that user space can go on
using keys it never reads while AF_ALG drops off-CPU cryptography and
restricts what it allows, built on backends that hold the key and on
tiers that say what a backend protects against, the engine one
included. I directed the design and took its decisions, choosing among
the options the assistant set out or bringing my own. The assistant
surveyed the prior art, set out the design options with a
recommendation at each step, and wrote the code, the KUnit tests, the
selftests (not posted, see Testing) and the documentation under my
direction, in plans I approved, partly through lower-tier Claude models
it dispatched for individual tasks; each plan was followed by an AI
review that I read.
Claude also built and ran the QEMU bench and analysed the hardware run,
which another Claude session carried out with me at the board.
I have reviewed every patch and I am responsible for all of it.
Rodolfo Giometti
Rodolfo Giometti (9):
KEYS: keycrypt: Add a key type for keys user space never reads
KEYS: keycrypt: Add the sw backend
KEYS: keycrypt: Add the OP-TEE backend
docs: keycrypt: document keycrypt keys
MAINTAINERS: add KEYS-KEYCRYPT
KEYS: keycrypt: Add the engine tier
crypto: caam - add an internal cbc(paes) taking the blob's key
modifier
KEYS: keycrypt: Add the CAAM backend
KEYS: keycrypt: Add the aes256-gcm-stream algorithm
.../admin-guide/kernel-parameters.txt | 20 +
Documentation/security/keys/index.rst | 1 +
Documentation/security/keys/keycrypt.rst | 1105 +++++++++++++++++
.../userspace-api/ioctl/ioctl-number.rst | 2 +
MAINTAINERS | 18 +
drivers/crypto/caam/caamalg.c | 89 +-
drivers/crypto/caam/caamalg_desc.c | 3 +-
drivers/crypto/caam/caamalg_desc.h | 1 +
include/keys/keycrypt.h | 161 +++
include/soc/fsl/caam-blob.h | 8 +
include/uapi/linux/keycrypt.h | 182 +++
include/uapi/linux/keyctl.h | 1 +
security/keys/Kconfig | 2 +
security/keys/Makefile | 1 +
security/keys/compat.c | 3 +
security/keys/internal.h | 12 +
security/keys/keycrypt/Kconfig | 153 +++
security/keys/keycrypt/Makefile | 9 +
security/keys/keycrypt/caam.c | 346 ++++++
security/keys/keycrypt/caam.h | 30 +
security/keys/keycrypt/core.c | 1077 ++++++++++++++++
security/keys/keycrypt/ctx.c | 667 ++++++++++
security/keys/keycrypt/keycrypt.h | 180 +++
security/keys/keycrypt/optee.c | 489 ++++++++
security/keys/keycrypt/optee.h | 39 +
security/keys/keycrypt/sw.c | 468 +++++++
security/keys/keycrypt/sw.h | 30 +
security/keys/keyctl.c | 5 +
28 files changed, 5090 insertions(+), 12 deletions(-)
create mode 100644 Documentation/security/keys/keycrypt.rst
create mode 100644 include/keys/keycrypt.h
create mode 100644 include/uapi/linux/keycrypt.h
create mode 100644 security/keys/keycrypt/Kconfig
create mode 100644 security/keys/keycrypt/Makefile
create mode 100644 security/keys/keycrypt/caam.c
create mode 100644 security/keys/keycrypt/caam.h
create mode 100644 security/keys/keycrypt/core.c
create mode 100644 security/keys/keycrypt/ctx.c
create mode 100644 security/keys/keycrypt/keycrypt.h
create mode 100644 security/keys/keycrypt/optee.c
create mode 100644 security/keys/keycrypt/optee.h
create mode 100644 security/keys/keycrypt/sw.c
create mode 100644 security/keys/keycrypt/sw.h
base-commit: 067c5c24cef23d913b67eaaf71ae67e7169a6620
prerequisite-patch-id: 6f1c5a861378c58d6adea4e1745794466a9d73d6
prerequisite-patch-id: e1565dff5540351c42ee04e0308649a6d97e9e09
prerequisite-patch-id: 37ed62269bd4b1fcaeeab38f5feb5b0f63608459
--
2.43.0
^ permalink raw reply [flat|nested] 14+ messages in thread
* [RFC PATCH 1/9] KEYS: keycrypt: Add a key type for keys user space never reads
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
@ 2026-11-18 14:04 ` Rodolfo Giometti
2026-11-18 14:04 ` [RFC PATCH 2/9] KEYS: keycrypt: Add the sw backend Rodolfo Giometti
` (9 subsequent siblings)
10 siblings, 0 replies; 14+ messages in thread
From: Rodolfo Giometti @ 2026-11-18 14:04 UTC (permalink / raw)
To: David Howells, Jarkko Sakkinen, keyrings
Cc: Herbert Xu, David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, Rodolfo Giometti
Programs that encrypt, decrypt or authenticate data with a symmetric
key today hold that key: in a file, in a "user" or "logon" key handed
to AF_ALG, or in memory a compromised process can read. On a device
with a TEE or a crypto engine able to keep keys, nothing lets an
ordinary program use such a key through a kernel interface, with the
key fixed to one algorithm and purpose and never released.
Add the "keycrypt" key type. A key is created by a backend ("new"),
sealed from a key given in clear by CAP_SYS_ADMIN ("import", behind
CONFIG_KEYCRYPT_IMPORT), or re-created from the blob its backend
sealed ("load"); its algorithm (aes256-cbc, hmac-sha256), purpose and
protection tier (kernel, tee, hsm) are fixed at creation and
authenticated in the blob. User space reads only the blob.
This adds a user API: KEYCTL_CRYPT_OPEN opens an operation context on
a key, a file descriptor whose ioctls run the operation in the key's
backend, as the documentation describes. Two system policies come as
sysctls and boot parameters, both one-way: the system tier, a floor on
the use of keys whose starting value is chosen at build time
(CONFIG_KEYCRYPT_SYSTEM_TIER_*), and an import switch.
Backends register through keycrypt_register_backend(); none is added
here, so a well-formed add_key() fails with ENODEV until one is.
Signed-off-by: Rodolfo Giometti <giometti@enneenne.com>
---
.../admin-guide/kernel-parameters.txt | 20 +
.../userspace-api/ioctl/ioctl-number.rst | 2 +
include/keys/keycrypt.h | 150 +++
include/uapi/linux/keycrypt.h | 143 +++
include/uapi/linux/keyctl.h | 1 +
security/keys/Kconfig | 2 +
security/keys/Makefile | 1 +
security/keys/compat.c | 3 +
security/keys/internal.h | 12 +
security/keys/keycrypt/Kconfig | 72 ++
security/keys/keycrypt/Makefile | 3 +
security/keys/keycrypt/core.c | 1070 +++++++++++++++++
security/keys/keycrypt/ctx.c | 530 ++++++++
security/keys/keycrypt/keycrypt.h | 173 +++
security/keys/keyctl.c | 5 +
15 files changed, 2187 insertions(+)
create mode 100644 include/keys/keycrypt.h
create mode 100644 include/uapi/linux/keycrypt.h
create mode 100644 security/keys/keycrypt/Kconfig
create mode 100644 security/keys/keycrypt/Makefile
create mode 100644 security/keys/keycrypt/core.c
create mode 100644 security/keys/keycrypt/ctx.c
create mode 100644 security/keys/keycrypt/keycrypt.h
diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index 0b3c140babd9..62d44a5225e4 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -2935,6 +2935,26 @@ Kernel parameters
for Movable pages. "nn[KMGTPE]", "nn%", and "mirror"
are exclusive, so you cannot specify multiple forms.
+ keycrypt.import= [KEYS] Allow importing clear key material into
+ keycrypt keys (CONFIG_KEYCRYPT_IMPORT).
+ Format: <bool>
+ Default: 1. 0 disables import until reboot; an
+ invalid value, or turning it back on, is
+ ignored, with a kernel warning. The
+ kernel.keys.keycrypt_import sysctl can later
+ turn it off the same way, but never back on.
+
+ keycrypt.system_tier= [KEYS] Lowest protection tier a keycrypt key
+ may be used at; keys of a lower tier can still
+ be created and loaded.
+ Format: { kernel | tee | hsm }
+ Default: the CONFIG_KEYCRYPT_SYSTEM_TIER_*
+ choice, kernel unless set. Can only be raised,
+ here or later through the
+ kernel.keys.keycrypt_system_tier sysctl; an
+ invalid name, or a tier lower than already set,
+ is ignored, with a kernel warning.
+
kfence.burst= [MM,KFENCE] The number of additional successive
allocations to be attempted through KFENCE for each
sample interval.
diff --git a/Documentation/userspace-api/ioctl/ioctl-number.rst b/Documentation/userspace-api/ioctl/ioctl-number.rst
index dbe462040999..efdace54085b 100644
--- a/Documentation/userspace-api/ioctl/ioctl-number.rst
+++ b/Documentation/userspace-api/ioctl/ioctl-number.rst
@@ -387,6 +387,8 @@ Code Seq# Include File Comments
<mailto:linux-hyperv@vger.kernel.org>
0xBA 00-0F uapi/linux/liveupdate.h Pasha Tatashin
<mailto:pasha.tatashin@soleen.com>
+0xBB 00-0F uapi/linux/keycrypt.h keycrypt
+ <mailto:keyrings@vger.kernel.org>
0xC0 00-0F linux/usb/iowarrior.h
0xCA 00-0F uapi/misc/cxl.h Dead since 6.15
0xCA 10-2F uapi/misc/ocxl.h
diff --git a/include/keys/keycrypt.h b/include/keys/keycrypt.h
new file mode 100644
index 000000000000..8aae3d47e697
--- /dev/null
+++ b/include/keys/keycrypt.h
@@ -0,0 +1,150 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * keycrypt - the interface for the backends that hold and use the keys
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
+ */
+
+#ifndef _KEYS_KEYCRYPT_H
+#define _KEYS_KEYCRYPT_H
+
+#include <linux/bits.h>
+#include <linux/types.h>
+#include <uapi/linux/keycrypt.h>
+
+struct module;
+struct keycrypt_handle;
+
+#define KEYCRYPT_ALGS_ALL (BIT(KEYCRYPT_ALG_AES256_CBC) | \
+ BIT(KEYCRYPT_ALG_HMAC_SHA256))
+
+#define KEYCRYPT_BACKEND_DATA_MAX 4096
+
+/*
+ * Header of a blob: "KCR", version, flags, algorithm, purpose (le16),
+ * tier, origin, name length, then the name
+ */
+#define KEYCRYPT_HEADER_FIXED 11
+#define KEYCRYPT_HEADER_MAX (KEYCRYPT_HEADER_FIXED + \
+ KEYCRYPT_BACKEND_NAME_MAX)
+
+/**
+ * struct keycrypt_meta - metadata fixed when a key is created
+ * @alg: KEYCRYPT_ALG_*
+ * @purpose: KEYCRYPT_PURPOSE_* mask
+ * @tier: KEYCRYPT_TIER_* the key was sealed at
+ * @origin: KEYCRYPT_ORIGIN_*
+ * @backend: name of the backend, NUL terminated
+ */
+struct keycrypt_meta {
+ u8 alg;
+ u16 purpose;
+ u8 tier;
+ u8 origin;
+ char backend[KEYCRYPT_BACKEND_NAME_MAX + 1];
+};
+
+/**
+ * struct keycrypt_blob - data a backend creates for a new key
+ * @data: allocated with kmalloc() by the backend, freed by the core on
+ * every path, success or not
+ * @len: 1 to KEYCRYPT_BACKEND_DATA_MAX bytes
+ */
+struct keycrypt_blob {
+ u8 *data;
+ u32 len;
+};
+
+/**
+ * struct keycrypt_key - a key as its backend sees it
+ * @meta: its metadata
+ * @hdr: the header stored in the blob; the backend's data must
+ * authenticate exactly these bytes
+ * @hdr_len: bytes in @hdr
+ * @data: the backend's data, as stored
+ * @data_len: bytes in @data
+ * @priv: the backend's state for this key, set by @load and released by
+ * @destroy
+ */
+struct keycrypt_key {
+ struct keycrypt_meta meta;
+ const u8 *hdr;
+ u32 hdr_len;
+ const u8 *data;
+ u32 data_len;
+ void *priv;
+};
+
+/**
+ * struct keycrypt_backend - a place where keycrypt keys live
+ * @name: [a-z0-9_-], at most KEYCRYPT_BACKEND_NAME_MAX; it names a sealing
+ * domain and is stored in every blob
+ * @tier: KEYCRYPT_TIER_*; _TEE and _HSM declare that the backend meets
+ * Documentation/security/keys/keycrypt.rst, "Backend requirements"
+ * @algs: BIT(KEYCRYPT_ALG_*) mask of what it supports
+ * @owner: module holding the callbacks, pinned by every key
+ * @opts: NULL-terminated list of the option keys it accepts ("master"
+ * for "master=<value>"); the core refuses any other, and duplicates
+ * @generate: create a key; its data must authenticate @hdr
+ * @import: seal a key given in clear, likewise; NULL if not supported
+ * @load: check that @k's data authenticates @k->hdr (-EBADMSG if not) and
+ * set @k->priv if needed, leaving it unset on failure
+ * @destroy: release @k->priv; called at most once per key, and last
+ * @ctx_open: start @op on @k and set *@ctx, releasing what it acquired on
+ * failure; @iv (16 bytes) is the aes256-cbc IV, used as given
+ * @update: process @len bytes from @in to @out, in place allowed; @out is
+ * NULL for MAC and VERIFY
+ * @final: end the context; MAC and VERIFY write the 32-byte tag to @out
+ * and set *@len, the ciphers set it to 0
+ * @verify: end a VERIFY context by comparing the tag with @expected where
+ * the key lives, 0 or -EBADMSG, never the tag. Required of a _TEE or
+ * _HSM backend with context callbacks offering hmac-sha256
+ * @ctx_free: release @ctx, once, however the context ends
+ * @handle: core private
+ *
+ * @opts given to a callback are the "key=value" options the core did not
+ * consume, or NULL. Errors of @generate, @import and @load reach user
+ * space as given for -ENOMEM, -EINVAL, -EBADMSG, -ENOKEY, -EKEYREJECTED,
+ * -EACCES, -EINTR and -ERESTARTSYS, those of the context callbacks only
+ * for -ENOMEM, -EINTR, -ERESTARTSYS and -EBADMSG; any other is -EIO.
+ *
+ * The callbacks may sleep and run concurrently, with the backend's handle
+ * held: they must not call into keycrypt, and must not wait without bound.
+ * The four context callbacks are all given or all NULL; without them the
+ * backend's keys cannot be used (KEYCTL_CRYPT_OPEN gives -ENODEV).
+ */
+struct keycrypt_backend {
+ const char *name;
+ u8 tier;
+ u32 algs;
+ struct module *owner;
+ const char * const *opts;
+
+ int (*generate)(struct keycrypt_backend *b,
+ const struct keycrypt_meta *m, const u8 *hdr,
+ u32 hdr_len, const char *opts,
+ struct keycrypt_blob *out);
+ int (*import)(struct keycrypt_backend *b,
+ const struct keycrypt_meta *m, const u8 *hdr,
+ u32 hdr_len, const char *opts, const u8 *key,
+ size_t keylen, struct keycrypt_blob *out);
+ int (*load)(struct keycrypt_backend *b, struct keycrypt_key *k,
+ const char *opts);
+ void (*destroy)(struct keycrypt_backend *b, struct keycrypt_key *k);
+ int (*ctx_open)(struct keycrypt_backend *b, struct keycrypt_key *k,
+ u32 op, u8 *iv, void **ctx);
+ int (*update)(struct keycrypt_backend *b, void *ctx, const u8 *in,
+ u8 *out, size_t len);
+ int (*final)(struct keycrypt_backend *b, void *ctx, u8 *out,
+ size_t out_size, size_t *len);
+ int (*verify)(struct keycrypt_backend *b, void *ctx,
+ const u8 *expected);
+ void (*ctx_free)(struct keycrypt_backend *b, void *ctx);
+
+ struct keycrypt_handle *handle;
+};
+
+int keycrypt_register_backend(struct keycrypt_backend *b);
+void keycrypt_unregister_backend(struct keycrypt_backend *b);
+
+#endif /* _KEYS_KEYCRYPT_H */
diff --git a/include/uapi/linux/keycrypt.h b/include/uapi/linux/keycrypt.h
new file mode 100644
index 000000000000..c03348579f62
--- /dev/null
+++ b/include/uapi/linux/keycrypt.h
@@ -0,0 +1,143 @@
+/* SPDX-License-Identifier: GPL-2.0-only WITH Linux-syscall-note */
+/*
+ * keycrypt - the user-space API
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
+ */
+
+#ifndef _UAPI_LINUX_KEYCRYPT_H
+#define _UAPI_LINUX_KEYCRYPT_H
+
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+/* Protection tiers, lowest first; the gaps leave room for more */
+#define KEYCRYPT_TIER_KERNEL 10 /* the kernel itself */
+#define KEYCRYPT_TIER_TEE 20 /* a trusted execution environment */
+/* as TEE, in dedicated hardware apart from the CPU running the kernel */
+#define KEYCRYPT_TIER_HSM 30
+
+/*
+ * Operations of KEYCTL_CRYPT_OPEN; which ones a key allows depends on its
+ * algorithm and purposes, see Documentation/security/keys/keycrypt.rst
+ */
+#define KEYCRYPT_OP_ENCRYPT 1
+#define KEYCRYPT_OP_DECRYPT 2
+#define KEYCRYPT_OP_MAC 3
+#define KEYCRYPT_OP_VERIFY 4
+
+/*
+ * KEYCTL_CRYPT_OPEN flags. KEYCRYPT_OPEN_CALLER_IV: encrypt with an IV
+ * the caller gives instead of one the kernel draws, for data formats
+ * that fix or derive the IV themselves; the caller then answers for
+ * its unpredictability. Without it, the kernel draws the IV.
+ */
+#define KEYCRYPT_OPEN_CALLER_IV 0x0001
+
+/* struct keycrypt_info: the key's algorithm */
+#define KEYCRYPT_ALG_AES256_CBC 1
+#define KEYCRYPT_ALG_HMAC_SHA256 2
+
+/* struct keycrypt_info: the key's purpose mask */
+#define KEYCRYPT_PURPOSE_ENCRYPT 0x0001
+#define KEYCRYPT_PURPOSE_DECRYPT 0x0002
+#define KEYCRYPT_PURPOSE_MAC 0x0004
+#define KEYCRYPT_PURPOSE_VERIFY 0x0008
+
+/* struct keycrypt_info: the key's origin */
+#define KEYCRYPT_ORIGIN_GENERATED 1
+#define KEYCRYPT_ORIGIN_IMPORTED 2
+
+/*
+ * A backend's name: at most this many characters, then a NUL (struct
+ * keycrypt_info's @backend has room for more)
+ */
+#define KEYCRYPT_BACKEND_NAME_MAX 16
+
+/**
+ * struct keycrypt_open_params - KEYCTL_CRYPT_OPEN parameters
+ * @op: KEYCRYPT_OP_*
+ * @accepted_min_tier: KEYCRYPT_TIER_*: refuse a key of a lower tier; 0:
+ * no requirement beyond the system tier
+ * @flags: KEYCRYPT_OPEN_*
+ * @__reserved: must be zero
+ * @iv: aes256-cbc: the IV, given for decryption and with
+ * KEYCRYPT_OPEN_CALLER_IV, otherwise written back by the kernel; MAC
+ * and VERIFY: zero
+ *
+ * Extended by size (copy_struct_from_user()); at least
+ * KEYCRYPT_OPEN_PARAMS_SIZE_VER0 bytes.
+ */
+struct keycrypt_open_params {
+ __u32 op;
+ __u32 accepted_min_tier;
+ __u32 flags;
+ __u32 __reserved;
+ __u8 iv[16];
+};
+
+#define KEYCRYPT_OPEN_PARAMS_SIZE_VER0 32
+
+/**
+ * struct keycrypt_update - KEYCRYPT_IOC_UPDATE argument
+ * @in: user pointer to @len input bytes
+ * @out: user pointer to @len output bytes; 0 for MAC and VERIFY
+ * @len: bytes, at most KEYCRYPT_UPDATE_MAX; aes256-cbc: a multiple of 16
+ * @flags: must be zero
+ */
+struct keycrypt_update {
+ __u64 in;
+ __u64 out;
+ __u32 len;
+ __u32 flags;
+};
+
+/**
+ * struct keycrypt_final - KEYCRYPT_IOC_FINAL argument
+ * @out: user pointer; MAC: the tag, written, @len room in, bytes out;
+ * VERIFY: the expected 32-byte tag, read, @len must be 32, 0 back;
+ * aes256-cbc: 0, and @len comes back 0
+ * @len: see @out
+ * @flags: must be zero
+ */
+struct keycrypt_final {
+ __u64 out;
+ __u32 len;
+ __u32 flags;
+};
+
+#define KEYCRYPT_UPDATE_MAX 65536
+#define KEYCRYPT_MAC_LEN 32
+
+/**
+ * struct keycrypt_info - KEYCRYPT_IOC_INFO argument, written by the kernel
+ * @op: KEYCRYPT_OP_* the context was opened for
+ * @alg: KEYCRYPT_ALG_* of the key
+ * @purpose: KEYCRYPT_PURPOSE_* mask of the key
+ * @tier: KEYCRYPT_TIER_* the key was sealed at
+ * @origin: KEYCRYPT_ORIGIN_*
+ * @accepted_min_tier: the KEYCTL_CRYPT_OPEN @accepted_min_tier the
+ * context was opened with, 0 for none
+ * @__reserved: zero; a field added here is zero when the kernel does not
+ * report it, and zero is never one of its values (@accepted_min_tier,
+ * whose 0 means none, is the exception)
+ * @backend: name of the key's backend, NUL terminated, the rest zero
+ */
+struct keycrypt_info {
+ __u32 op;
+ __u32 alg;
+ __u32 purpose;
+ __u32 tier;
+ __u32 origin;
+ __u32 accepted_min_tier;
+ __u32 __reserved[2];
+ char backend[32];
+};
+
+#define KEYCRYPT_IOC_MAGIC 0xBB
+#define KEYCRYPT_IOC_UPDATE _IOW(KEYCRYPT_IOC_MAGIC, 1, struct keycrypt_update)
+#define KEYCRYPT_IOC_FINAL _IOWR(KEYCRYPT_IOC_MAGIC, 2, struct keycrypt_final)
+/* 3: KEYCRYPT_IOC_SEGMENT, with the aes256-gcm-stream algorithm */
+#define KEYCRYPT_IOC_INFO _IOR(KEYCRYPT_IOC_MAGIC, 4, struct keycrypt_info)
+
+#endif /* _UAPI_LINUX_KEYCRYPT_H */
diff --git a/include/uapi/linux/keyctl.h b/include/uapi/linux/keyctl.h
index 00cc0942203e..1532cc76ab38 100644
--- a/include/uapi/linux/keyctl.h
+++ b/include/uapi/linux/keyctl.h
@@ -73,6 +73,7 @@
#define KEYCTL_MOVE 30 /* Move keys between keyrings */
#define KEYCTL_CAPABILITIES 31 /* Find capabilities of keyrings subsystem */
#define KEYCTL_WATCH_KEY 32 /* Watch a key or ring of keys for changes */
+#define KEYCTL_CRYPT_OPEN 33 /* Open a keycrypt operation context */
/* keyctl structures */
struct keyctl_dh_params {
diff --git a/security/keys/Kconfig b/security/keys/Kconfig
index f4510d8cb485..fb0f48f218ef 100644
--- a/security/keys/Kconfig
+++ b/security/keys/Kconfig
@@ -128,4 +128,6 @@ config KEY_NOTIFICATIONS
This makes use of pipes to handle the notification buffer and
provides KEYCTL_WATCH_KEY to enable/disable watches.
+source "security/keys/keycrypt/Kconfig"
+
endif # KEYS
diff --git a/security/keys/Makefile b/security/keys/Makefile
index 5f40807f05b3..82583db1704b 100644
--- a/security/keys/Makefile
+++ b/security/keys/Makefile
@@ -30,3 +30,4 @@ obj-$(CONFIG_ASYMMETRIC_KEY_TYPE) += keyctl_pkey.o
obj-$(CONFIG_BIG_KEYS) += big_key.o
obj-$(CONFIG_TRUSTED_KEYS) += trusted-keys/
obj-$(CONFIG_ENCRYPTED_KEYS) += encrypted-keys/
+obj-$(CONFIG_KEYCRYPT) += keycrypt/
diff --git a/security/keys/compat.c b/security/keys/compat.c
index 1545efdca562..80ea06e59ee2 100644
--- a/security/keys/compat.c
+++ b/security/keys/compat.c
@@ -126,6 +126,9 @@ COMPAT_SYSCALL_DEFINE5(keyctl, u32, option,
case KEYCTL_WATCH_KEY:
return keyctl_watch_key(arg2, arg3, arg4);
+ case KEYCTL_CRYPT_OPEN:
+ return keyctl_crypt_open(arg2, compat_ptr(arg3), arg4, arg5);
+
default:
return -EOPNOTSUPP;
}
diff --git a/security/keys/internal.h b/security/keys/internal.h
index b7b622bc36a1..69de149a0609 100644
--- a/security/keys/internal.h
+++ b/security/keys/internal.h
@@ -358,6 +358,18 @@ static inline long keyctl_watch_key(key_serial_t key_id, int watch_fd, int watch
}
#endif
+#ifdef CONFIG_KEYCRYPT
+extern long keyctl_crypt_open(key_serial_t id, void __user *uparams,
+ size_t usize, unsigned long flags);
+#else
+static inline long keyctl_crypt_open(key_serial_t id,
+ void __user *uparams,
+ size_t usize, unsigned long flags)
+{
+ return -EOPNOTSUPP;
+}
+#endif
+
/*
* Debugging key validation
*/
diff --git a/security/keys/keycrypt/Kconfig b/security/keys/keycrypt/Kconfig
new file mode 100644
index 000000000000..e1d1b8e2a58b
--- /dev/null
+++ b/security/keys/keycrypt/Kconfig
@@ -0,0 +1,72 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+config KEYCRYPT
+ bool "Keys user space uses for cryptography but never reads"
+ select CRYPTO_LIB_UTILS
+ help
+ This option provides the "keycrypt" key type: symmetric keys whose
+ algorithm, purpose and protection tier are fixed when they are
+ created, held by a backend such as dedicated hardware or a
+ trusted execution environment. User space keeps only a blob the
+ backend sealed, and never sees a key the backend created; a key
+ of the kernel tier is in clear in kernel memory while loaded.
+
+ See Documentation/security/keys/keycrypt.rst.
+
+ If you are unsure as to whether this is required, answer N.
+
+config KEYCRYPT_IMPORT
+ bool "Allow keycrypt keys to be imported in clear"
+ depends on KEYCRYPT
+ help
+ Allow a process with CAP_SYS_ADMIN to give a keycrypt backend a
+ key in clear, for the backend to seal it ("import"). Such keys
+ existed outside the backend and are marked "imported". Saying N
+ refuses the import command; blobs of keys imported elsewhere
+ still load.
+
+ If you are unsure as to whether this is required, answer N.
+
+choice
+ prompt "System keycrypt tier at boot"
+ default KEYCRYPT_SYSTEM_TIER_KERNEL
+ depends on KEYCRYPT
+ help
+ The lowest tier a keycrypt key may be used at when the kernel
+ starts: KEYCTL_CRYPT_OPEN refuses a key of a lower tier, which
+ can still be created and loaded. The keycrypt.system_tier= boot
+ parameter and the kernel.keys.keycrypt_system_tier sysctl can
+ only raise it, so a signed kernel image sets a floor its command
+ line cannot lower.
+
+ The default sets no floor: which backends a kernel builds says
+ nothing about which will be present when it runs (a
+ distribution kernel builds them all), so a product that knows
+ its backends raises it here or on its command line.
+
+config KEYCRYPT_SYSTEM_TIER_KERNEL
+ bool "Kernel"
+ help
+ Keys of every tier, the kernel tier included, can be used until
+ the keycrypt.system_tier= boot parameter or the
+ kernel.keys.keycrypt_system_tier sysctl raises the system tier.
+ A system with no backend of the kernel tier built has no key of
+ that tier to use.
+
+config KEYCRYPT_SYSTEM_TIER_TEE
+ bool "TEE"
+ help
+ Keys whose use a trusted execution environment or the hardware
+ checks: keys of the kernel tier are refused at every
+ KEYCTL_CRYPT_OPEN; the tee and hsm tiers can be used. For a
+ system where OP-TEE or an hsm backend holds the keys.
+
+config KEYCRYPT_SYSTEM_TIER_HSM
+ bool "HSM"
+ help
+ Keys whose use dedicated hardware apart from the CPU checks: a
+ key of any tier but hsm is refused at every KEYCTL_CRYPT_OPEN.
+ Choose it only on a system with a backend of the hsm tier, or no
+ keycrypt key can be used at all.
+
+endchoice
diff --git a/security/keys/keycrypt/Makefile b/security/keys/keycrypt/Makefile
new file mode 100644
index 000000000000..8910fb0156e7
--- /dev/null
+++ b/security/keys/keycrypt/Makefile
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+obj-y += core.o ctx.o
diff --git a/security/keys/keycrypt/core.c b/security/keys/keycrypt/core.c
new file mode 100644
index 000000000000..debd0845621e
--- /dev/null
+++ b/security/keys/keycrypt/core.c
@@ -0,0 +1,1070 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * keycrypt - the key type and the backend registry
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
+ */
+
+#define pr_fmt(fmt) "keycrypt: " fmt
+
+#include <linux/capability.h>
+#include <linux/err.h>
+#include <linux/hex.h>
+#include <linux/init.h>
+#include <linux/key-type.h>
+#include <linux/kstrtox.h>
+#include <linux/limits.h>
+#include <linux/minmax.h>
+#include <linux/module.h>
+#include <linux/mutex.h>
+#include <linux/seq_file.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+#include <linux/sysctl.h>
+#include <linux/unaligned.h>
+#include "keycrypt.h"
+
+#define KEYCRYPT_MAGIC "KCR"
+#define KEYCRYPT_MAGIC_LEN 3
+#define KEYCRYPT_VERSION 1
+
+struct keycrypt_name {
+ u8 value;
+ const char *name;
+};
+
+static const struct keycrypt_name keycrypt_algs[] = {
+ { KEYCRYPT_ALG_AES256_CBC, "aes256-cbc" },
+ { KEYCRYPT_ALG_HMAC_SHA256, "hmac-sha256" },
+};
+
+static const struct keycrypt_name keycrypt_tiers[] = {
+ { KEYCRYPT_TIER_KERNEL, "kernel" },
+ { KEYCRYPT_TIER_TEE, "tee" },
+ { KEYCRYPT_TIER_HSM, "hsm" },
+};
+
+static const struct keycrypt_name keycrypt_origins[] = {
+ { KEYCRYPT_ORIGIN_GENERATED, "generated" },
+ { KEYCRYPT_ORIGIN_IMPORTED, "imported" },
+};
+
+static int keycrypt_value(const struct keycrypt_name *t, size_t n,
+ const char *s)
+{
+ size_t i;
+
+ for (i = 0; i < n; i++)
+ if (!strcmp(t[i].name, s))
+ return t[i].value;
+ return -EINVAL;
+}
+
+static const char *keycrypt_name(const struct keycrypt_name *t, size_t n,
+ u8 v)
+{
+ size_t i;
+
+ for (i = 0; i < n; i++)
+ if (t[i].value == v)
+ return t[i].name;
+ return NULL;
+}
+
+#define KEYCRYPT_VALUE(t, s) keycrypt_value(t, sizeof(t) / sizeof((t)[0]), s)
+#define KEYCRYPT_NAME(t, v) keycrypt_name(t, sizeof(t) / sizeof((t)[0]), v)
+
+bool keycrypt_tier_valid(u32 tier)
+{
+ return tier <= U8_MAX && KEYCRYPT_NAME(keycrypt_tiers, tier);
+}
+
+static LIST_HEAD(keycrypt_handles);
+static DEFINE_MUTEX(keycrypt_lock);
+
+static bool keycrypt_purpose_valid(u8 alg, u16 purpose)
+{
+ switch (alg) {
+ case KEYCRYPT_ALG_AES256_CBC:
+ return purpose && !(purpose & ~(KEYCRYPT_PURPOSE_ENCRYPT |
+ KEYCRYPT_PURPOSE_DECRYPT));
+ case KEYCRYPT_ALG_HMAC_SHA256:
+ return purpose && !(purpose & ~(KEYCRYPT_PURPOSE_MAC |
+ KEYCRYPT_PURPOSE_VERIFY));
+ }
+ return false;
+}
+
+/* [a-z0-9_-], ASCII only: islower() also accepts Latin-1 letters */
+static bool keycrypt_name_valid(const char *s, size_t n)
+{
+ size_t i;
+
+ if (!n || n > KEYCRYPT_BACKEND_NAME_MAX)
+ return false;
+ for (i = 0; i < n; i++)
+ if (!((s[i] >= 'a' && s[i] <= 'z') ||
+ (s[i] >= '0' && s[i] <= '9') || s[i] == '-' ||
+ s[i] == '_'))
+ return false;
+ return true;
+}
+
+static char *keycrypt_next_token(char **s)
+{
+ char *t;
+
+ do {
+ t = strsep(s, " \t\n");
+ } while (t && !*t);
+ return t;
+}
+
+static int keycrypt_parse_purpose(char *s, u16 *purpose)
+{
+ char *p;
+
+ *purpose = 0;
+ while ((p = strsep(&s, ",")) != NULL) {
+ u16 bit;
+
+ if (!strcmp(p, "encrypt"))
+ bit = KEYCRYPT_PURPOSE_ENCRYPT;
+ else if (!strcmp(p, "decrypt"))
+ bit = KEYCRYPT_PURPOSE_DECRYPT;
+ else if (!strcmp(p, "mac"))
+ bit = KEYCRYPT_PURPOSE_MAC;
+ else if (!strcmp(p, "verify"))
+ bit = KEYCRYPT_PURPOSE_VERIFY;
+ else
+ return -EINVAL;
+ if (*purpose & bit)
+ return -EINVAL;
+ *purpose |= bit;
+ }
+ return 0;
+}
+
+static int keycrypt_parse_tier(const char *s, u8 *tier)
+{
+ int n;
+
+ if (*tier)
+ return -EINVAL;
+ n = KEYCRYPT_VALUE(keycrypt_tiers, s);
+ if (n < 0)
+ return n;
+ *tier = n;
+ return 0;
+}
+
+static int keycrypt_add_opt(struct keycrypt_req *req, const char *t)
+{
+ size_t len = strlen(req->opts), n = strlen(t);
+
+ if (len + 1 + n + 1 > req->opts_size)
+ return -EINVAL;
+ if (len)
+ req->opts[len++] = ' ';
+ memcpy(req->opts + len, t, n + 1);
+ return 0;
+}
+
+static int keycrypt_parse_option(char *t, struct keycrypt_req *req)
+{
+ char *v = strchr(t, '=');
+ bool load = req->cmd == KEYCRYPT_CMD_LOAD;
+
+ if (v == t || !v[1])
+ return -EINVAL;
+ *v++ = '\0';
+ if (!strcmp(t, "accepted-min-tier"))
+ return load ? keycrypt_parse_tier(v, &req->accepted_min_tier) :
+ -EINVAL;
+ if (!strcmp(t, "backend")) {
+ if (load || *req->backend || !keycrypt_name_valid(v, strlen(v)))
+ return -EINVAL;
+ strscpy(req->backend, v);
+ return 0;
+ }
+ if (!strcmp(t, "min-tier"))
+ return load ? -EINVAL : keycrypt_parse_tier(v, &req->min_tier);
+ if (!strcmp(t, "purpose")) {
+ if (!load || req->want_purpose)
+ return -EINVAL;
+ if (keycrypt_parse_purpose(v, &req->want_purpose))
+ return -EINVAL;
+ if (!keycrypt_purpose_valid(KEYCRYPT_ALG_AES256_CBC,
+ req->want_purpose) &&
+ !keycrypt_purpose_valid(KEYCRYPT_ALG_HMAC_SHA256,
+ req->want_purpose))
+ return -EINVAL;
+ return 0;
+ }
+ if (!strcmp(t, "tier"))
+ return load ? -EINVAL : keycrypt_parse_tier(v, &req->tier);
+ v[-1] = '=';
+ return keycrypt_add_opt(req, t);
+}
+
+/*
+ * "new <alg> <purpose>[,<purpose>...] [<option>=<value>...]"
+ * "import <alg> <purpose>[,<purpose>...] [<option>=<value>...] <hex key>"
+ * "load <hex blob> [<option>=<value>...]"
+ *
+ * req->opts and req->opts_size must be set by the caller.
+ */
+static int keycrypt_parse(char *s, struct keycrypt_req *req)
+{
+ size_t opts_size = req->opts_size;
+ char *opts = req->opts;
+ char *t;
+ int n, ret;
+
+ memset(req, 0, sizeof(*req));
+ req->opts = opts;
+ req->opts_size = opts_size;
+ opts[0] = '\0';
+
+ t = keycrypt_next_token(&s);
+ if (!t)
+ return -EINVAL;
+ if (!strcmp(t, "load")) {
+ req->cmd = KEYCRYPT_CMD_LOAD;
+ req->hex = keycrypt_next_token(&s);
+ if (!req->hex)
+ return -EINVAL;
+ while ((t = keycrypt_next_token(&s)) != NULL) {
+ if (!strchr(t, '='))
+ return -EINVAL;
+ ret = keycrypt_parse_option(t, req);
+ if (ret)
+ return ret;
+ }
+ return 0;
+ }
+ if (!strcmp(t, "new"))
+ req->cmd = KEYCRYPT_CMD_NEW;
+ else if (!strcmp(t, "import"))
+ req->cmd = KEYCRYPT_CMD_IMPORT;
+ else
+ return -EINVAL;
+
+ t = keycrypt_next_token(&s);
+ if (!t)
+ return -EINVAL;
+ n = KEYCRYPT_VALUE(keycrypt_algs, t);
+ if (n < 0)
+ return n;
+ req->alg = n;
+
+ t = keycrypt_next_token(&s);
+ if (!t)
+ return -EINVAL;
+ ret = keycrypt_parse_purpose(t, &req->purpose);
+ if (ret)
+ return ret;
+ if (!keycrypt_purpose_valid(req->alg, req->purpose))
+ return -EINVAL;
+
+ while ((t = keycrypt_next_token(&s)) != NULL) {
+ if (req->hex)
+ return -EINVAL;
+ if (strchr(t, '=')) {
+ ret = keycrypt_parse_option(t, req);
+ if (ret)
+ return ret;
+ continue;
+ }
+ if (req->cmd != KEYCRYPT_CMD_IMPORT)
+ return -EINVAL;
+ req->hex = t;
+ }
+ if (req->tier && req->min_tier)
+ return -EINVAL;
+ if (req->cmd == KEYCRYPT_CMD_IMPORT && !req->hex)
+ return -EINVAL;
+ return 0;
+}
+
+static int keycrypt_meta_header(const struct keycrypt_meta *m,
+ u8 *buf, size_t len)
+{
+ size_t n = strnlen(m->backend, sizeof(m->backend));
+ size_t need = KEYCRYPT_HEADER_FIXED + n;
+
+ if (!keycrypt_name_valid(m->backend, n))
+ return -EINVAL;
+ if (len < need)
+ return -ENOSPC;
+ memcpy(buf, KEYCRYPT_MAGIC, KEYCRYPT_MAGIC_LEN);
+ buf[3] = KEYCRYPT_VERSION;
+ buf[4] = 0;
+ buf[5] = m->alg;
+ put_unaligned_le16(m->purpose, buf + 6);
+ buf[8] = m->tier;
+ buf[9] = m->origin;
+ buf[10] = n;
+ memcpy(buf + KEYCRYPT_HEADER_FIXED, m->backend, n);
+ return need;
+}
+
+static void keycrypt_payload_init(struct keycrypt_payload *p,
+ const struct keycrypt_meta *m,
+ u32 hdr_len, u32 data_len)
+{
+ INIT_LIST_HEAD(&p->node);
+ p->key.meta = *m;
+ p->key.hdr = p->blob;
+ p->key.hdr_len = hdr_len;
+ p->key.data = p->blob + hdr_len + 4;
+ p->key.data_len = data_len;
+ p->blob_len = hdr_len + 4 + data_len;
+}
+
+static int keycrypt_payload_build(const struct keycrypt_meta *m,
+ const u8 *hdr, u32 hdr_len,
+ const u8 *data, u32 len,
+ struct keycrypt_payload **out)
+{
+ struct keycrypt_payload *p;
+
+ if (!data || !len || len > KEYCRYPT_BACKEND_DATA_MAX)
+ return -EIO;
+ p = kzalloc_flex(*p, blob, hdr_len + 4 + len);
+ if (!p)
+ return -ENOMEM;
+ memcpy(p->blob, hdr, hdr_len);
+ put_unaligned_le32(len, p->blob + hdr_len);
+ memcpy(p->blob + hdr_len + 4, data, len);
+ keycrypt_payload_init(p, m, hdr_len, len);
+ *out = p;
+ return 0;
+}
+
+static int keycrypt_payload_parse(const u8 *raw, size_t len,
+ struct keycrypt_payload **out)
+{
+ struct keycrypt_meta m = {};
+ struct keycrypt_payload *p;
+ size_t n, off;
+ u32 dlen;
+
+ if (len < KEYCRYPT_HEADER_FIXED ||
+ memcmp(raw, KEYCRYPT_MAGIC, KEYCRYPT_MAGIC_LEN))
+ return -EBADMSG;
+ if (raw[3] != KEYCRYPT_VERSION || raw[4])
+ return -EOPNOTSUPP;
+ m.alg = raw[5];
+ m.purpose = get_unaligned_le16(raw + 6);
+ m.tier = raw[8];
+ m.origin = raw[9];
+ n = raw[10];
+ if (!keycrypt_purpose_valid(m.alg, m.purpose) ||
+ !keycrypt_tier_valid(m.tier) ||
+ !KEYCRYPT_NAME(keycrypt_origins, m.origin))
+ return -EBADMSG;
+ off = KEYCRYPT_HEADER_FIXED + n;
+ /* The name is read only once the length covers it */
+ if (len < off + 4 ||
+ !keycrypt_name_valid((const char *)raw + KEYCRYPT_HEADER_FIXED, n))
+ return -EBADMSG;
+ memcpy(m.backend, raw + KEYCRYPT_HEADER_FIXED, n);
+ dlen = get_unaligned_le32(raw + off);
+ if (!dlen || dlen > KEYCRYPT_BACKEND_DATA_MAX || len != off + 4 + dlen)
+ return -EBADMSG;
+
+ p = kzalloc_flex(*p, blob, len);
+ if (!p)
+ return -ENOMEM;
+ memcpy(p->blob, raw, len);
+ keycrypt_payload_init(p, &m, off, dlen);
+ *out = p;
+ return 0;
+}
+
+void keycrypt_handle_put(struct keycrypt_handle *h)
+{
+ if (refcount_dec_and_test(&h->ref))
+ kfree(h);
+}
+
+/**
+ * keycrypt_register_backend() - make a backend available to keys
+ * @b: the backend, valid until keycrypt_unregister_backend() returns
+ *
+ * Return: 0, -EINVAL for a malformed @b, -EBUSY for a @b already
+ * registered, -EEXIST for a name in use, -ENOMEM.
+ */
+int keycrypt_register_backend(struct keycrypt_backend *b)
+{
+ struct keycrypt_handle *h, *p;
+ int ret = 0;
+
+ if (!b->name ||
+ !keycrypt_name_valid(b->name,
+ strnlen(b->name,
+ KEYCRYPT_BACKEND_NAME_MAX + 1)) ||
+ !keycrypt_tier_valid(b->tier) ||
+ !b->algs || (b->algs & ~KEYCRYPT_ALGS_ALL) ||
+ !b->generate || !b->load ||
+ ((!!b->ctx_open + !!b->update + !!b->final + !!b->ctx_free) % 4) ||
+ (b->tier >= KEYCRYPT_TIER_TEE &&
+ b->ctx_open &&
+ (b->algs & BIT(KEYCRYPT_ALG_HMAC_SHA256)) && !b->verify))
+ return -EINVAL;
+
+ h = kzalloc_obj(*h);
+ if (!h)
+ return -ENOMEM;
+ refcount_set(&h->ref, 1);
+ init_rwsem(&h->sem);
+ mutex_init(&h->keys_lock);
+ INIT_LIST_HEAD(&h->keys);
+ INIT_LIST_HEAD(&h->ctxs);
+ h->b = b;
+ h->tier = b->tier;
+ strscpy(h->name, b->name);
+
+ mutex_lock(&keycrypt_lock);
+ if (b->handle)
+ ret = -EBUSY;
+ if (!ret)
+ list_for_each_entry(p, &keycrypt_handles, list) {
+ if (!strcmp(p->name, h->name)) {
+ ret = -EEXIST;
+ break;
+ }
+ }
+ if (!ret) {
+ list_add_tail(&h->list, &keycrypt_handles);
+ b->handle = h;
+ }
+ mutex_unlock(&keycrypt_lock);
+ if (ret)
+ kfree(h);
+ return ret;
+}
+EXPORT_SYMBOL_GPL(keycrypt_register_backend);
+
+/*
+ * The one door to @b->destroy: at most once per key, with @p's handle's
+ * sem held for writing (revoke, unregister) or by keycrypt_payload_free()
+ * when nothing else can reach @p, and its keys_lock held.
+ */
+static void keycrypt_payload_destroy(struct keycrypt_backend *b,
+ struct keycrypt_payload *p)
+{
+ if (p->destroyed)
+ return;
+ p->destroyed = true;
+ if (b && b->destroy)
+ b->destroy(b, &p->key);
+}
+
+/**
+ * keycrypt_unregister_backend() - remove a backend
+ * @b: a backend registered earlier
+ *
+ * Waits for the backend calls in progress, calls @b->destroy on every key
+ * still using it, and leaves those keys in place: from then on they fail
+ * with -ENODEV. @b may be freed once this returns.
+ */
+void keycrypt_unregister_backend(struct keycrypt_backend *b)
+{
+ struct keycrypt_handle *h;
+ struct keycrypt_payload *p;
+ struct keycrypt_ctx *c;
+
+ mutex_lock(&keycrypt_lock);
+ h = b->handle;
+ if (WARN_ON_ONCE(!h)) {
+ mutex_unlock(&keycrypt_lock);
+ return;
+ }
+ b->handle = NULL;
+ list_del(&h->list);
+ mutex_unlock(&keycrypt_lock);
+
+ down_write(&h->sem);
+ mutex_lock(&h->keys_lock);
+ /* Contexts before keys, the order keycrypt_payload_revoke() uses */
+ list_for_each_entry(c, &h->ctxs, node)
+ keycrypt_ctx_detach(b, c);
+ list_for_each_entry(p, &h->keys, node)
+ keycrypt_payload_destroy(b, p);
+ mutex_unlock(&h->keys_lock);
+ h->b = NULL;
+ up_write(&h->sem);
+
+ keycrypt_handle_put(h);
+}
+EXPORT_SYMBOL_GPL(keycrypt_unregister_backend);
+
+/*
+ * The best backend for @alg (and, for @import, with an import) meeting
+ * every constraint given: named @name, of tier @tier, of at least
+ * @min_tier; the highest tier wins, the smaller name on a tie. Returned
+ * with a reference.
+ */
+static struct keycrypt_handle *keycrypt_get_handle(const char *name, u8 tier,
+ u8 min_tier, u8 alg,
+ bool import)
+{
+ struct keycrypt_handle *h, *best = NULL;
+
+ mutex_lock(&keycrypt_lock);
+ list_for_each_entry(h, &keycrypt_handles, list) {
+ if (!(h->b->algs & BIT(alg)) || (import && !h->b->import))
+ continue;
+ if (name && strcmp(h->name, name))
+ continue;
+ if ((tier && h->tier != tier) || h->tier < min_tier)
+ continue;
+ if (!best || h->tier > best->tier ||
+ (h->tier == best->tier && strcmp(h->name, best->name) < 0))
+ best = h;
+ }
+ if (best)
+ refcount_inc(&best->ref);
+ mutex_unlock(&keycrypt_lock);
+ return best;
+}
+
+/* What a backend's error becomes for user space */
+int keycrypt_backend_ret(int ret)
+{
+ switch (ret) {
+ case 0:
+ case -ENOMEM:
+ case -EINVAL:
+ case -EBADMSG:
+ case -ENOKEY:
+ case -EKEYREJECTED:
+ case -EACCES:
+ case -EINTR:
+ case -ERESTARTSYS:
+ return ret;
+ }
+ return -EIO;
+}
+
+static const char *keycrypt_opts(const struct keycrypt_req *req)
+{
+ return *req->opts ? req->opts : NULL;
+}
+
+/* Every option in @opts has a key @b declares, and no key comes twice */
+static int keycrypt_check_opts(const struct keycrypt_backend *b,
+ const char *opts)
+{
+ const char *s = opts, *e, *eq;
+ unsigned long seen = 0;
+ size_t i, n;
+
+ if (!opts)
+ return 0;
+ while (*s) {
+ e = strchrnul(s, ' ');
+ eq = strnchr(s, e - s, '=');
+ n = eq ? eq - s : e - s;
+ for (i = 0; b->opts && b->opts[i]; i++)
+ if (strlen(b->opts[i]) == n &&
+ !strncmp(b->opts[i], s, n))
+ break;
+ if (!b->opts || !b->opts[i] || i >= BITS_PER_LONG ||
+ (seen & BIT(i)))
+ return -EINVAL;
+ seen |= BIT(i);
+ s = *e ? e + 1 : e;
+ }
+ return 0;
+}
+
+/*
+ * Let the backend accept @p and link it to @h. Called with @h->sem held
+ * for reading and @h->b set; on success @p keeps the caller's reference
+ * to @h.
+ */
+static int keycrypt_attach(struct keycrypt_handle *h,
+ struct keycrypt_payload *p, const char *opts)
+{
+ struct keycrypt_backend *b = h->b;
+ int ret;
+
+ if (!try_module_get(b->owner))
+ return -ENODEV;
+ ret = keycrypt_backend_ret(b->load(b, &p->key, opts));
+ if (ret) {
+ module_put(b->owner);
+ return ret;
+ }
+ p->handle = h;
+ p->owner = b->owner;
+ mutex_lock(&h->keys_lock);
+ list_add(&p->node, &h->keys);
+ mutex_unlock(&h->keys_lock);
+ return 0;
+}
+
+static void keycrypt_payload_free(struct keycrypt_payload *p)
+{
+ struct keycrypt_handle *h;
+
+ if (!p)
+ return;
+ h = p->handle;
+ if (h) {
+ down_read(&h->sem);
+ mutex_lock(&h->keys_lock);
+ keycrypt_payload_destroy(h->b, p);
+ list_del(&p->node);
+ mutex_unlock(&h->keys_lock);
+ up_read(&h->sem);
+ module_put(p->owner);
+ keycrypt_handle_put(h);
+ }
+ kfree_sensitive(p);
+}
+
+struct keycrypt_policy keycrypt_policy = {
+ .lock = __MUTEX_INITIALIZER(keycrypt_policy.lock),
+ .system_tier = KEYCRYPT_BOOT_SYSTEM_TIER,
+ .import = true,
+};
+
+/* -EINVAL for an unknown tier, -EPERM for a lower one; equal is a no-op */
+static int
+keycrypt_policy_set_system_tier(struct keycrypt_policy *pol, u8 tier)
+{
+ int ret = 0;
+
+ if (!keycrypt_tier_valid(tier))
+ return -EINVAL;
+ mutex_lock(&pol->lock);
+ if (tier < pol->system_tier)
+ ret = -EPERM;
+ else
+ WRITE_ONCE(pol->system_tier, tier);
+ mutex_unlock(&pol->lock);
+ return ret;
+}
+
+/* -EPERM for turning it back on; off twice is a no-op */
+static int keycrypt_policy_set_import(struct keycrypt_policy *pol,
+ bool on)
+{
+ int ret = 0;
+
+ mutex_lock(&pol->lock);
+ if (on && !pol->import)
+ ret = -EPERM;
+ else
+ WRITE_ONCE(pol->import, on);
+ mutex_unlock(&pol->lock);
+ return ret;
+}
+
+u8 keycrypt_policy_system_tier(void)
+{
+ return READ_ONCE(keycrypt_policy.system_tier);
+}
+
+bool keycrypt_policy_import(void)
+{
+ return READ_ONCE(keycrypt_policy.import);
+}
+
+static int keycrypt_create(const struct keycrypt_req *req,
+ struct keycrypt_payload **out)
+{
+ bool import = req->cmd == KEYCRYPT_CMD_IMPORT;
+ const char *opts = keycrypt_opts(req);
+ struct keycrypt_payload *p = NULL;
+ struct keycrypt_blob blob = {};
+ struct keycrypt_meta m = {};
+ u8 hdr[KEYCRYPT_HEADER_MAX];
+ struct keycrypt_handle *h;
+ struct keycrypt_backend *b;
+ size_t keylen = 0;
+ u8 *key = NULL;
+ int hlen, ret;
+
+ if (import) {
+ if (!IS_ENABLED(CONFIG_KEYCRYPT_IMPORT) ||
+ !keycrypt_policy_import() || !capable(CAP_SYS_ADMIN))
+ return -EPERM;
+ keylen = strlen(req->hex);
+ if (keylen % 2)
+ return -EINVAL;
+ keylen /= 2;
+ if (!keycrypt_key_len_valid(req->alg, keylen))
+ return -EINVAL;
+ key = kmalloc(keylen, GFP_KERNEL);
+ if (!key)
+ return -ENOMEM;
+ if (hex2bin(key, req->hex, keylen)) {
+ ret = -EINVAL;
+ goto out;
+ }
+ }
+
+ h = keycrypt_get_handle(*req->backend ? req->backend : NULL, req->tier,
+ req->min_tier, req->alg, import);
+ if (!h) {
+ ret = -ENODEV;
+ goto out;
+ }
+ down_read(&h->sem);
+ b = h->b;
+ if (!b) {
+ ret = -ENODEV;
+ goto unlock;
+ }
+ ret = keycrypt_check_opts(b, opts);
+ if (ret)
+ goto unlock;
+
+ m.alg = req->alg;
+ m.purpose = req->purpose;
+ m.tier = h->tier;
+ m.origin = import ? KEYCRYPT_ORIGIN_IMPORTED :
+ KEYCRYPT_ORIGIN_GENERATED;
+ strscpy(m.backend, h->name);
+ hlen = keycrypt_meta_header(&m, hdr, sizeof(hdr));
+ if (hlen < 0) {
+ ret = hlen;
+ goto unlock;
+ }
+
+ if (import)
+ ret = b->import(b, &m, hdr, hlen, opts, key, keylen, &blob);
+ else
+ ret = b->generate(b, &m, hdr, hlen, opts, &blob);
+ ret = keycrypt_backend_ret(ret);
+ if (!ret)
+ ret = keycrypt_payload_build(&m, hdr, hlen, blob.data, blob.len,
+ &p);
+ kfree_sensitive(blob.data);
+ /* load options come only with "load": none for the new blob */
+ if (!ret)
+ ret = keycrypt_attach(h, p, NULL);
+ if (ret) {
+ kfree_sensitive(p);
+ p = NULL;
+ }
+unlock:
+ up_read(&h->sem);
+ if (ret)
+ keycrypt_handle_put(h);
+ else
+ *out = p;
+out:
+ kfree_sensitive(key);
+ return ret;
+}
+
+static int keycrypt_load(const struct keycrypt_req *req,
+ struct keycrypt_payload **out)
+{
+ size_t len = strlen(req->hex);
+ struct keycrypt_handle *h;
+ struct keycrypt_payload *p;
+ struct keycrypt_meta *m;
+ u8 *raw;
+ int ret;
+
+ if (!len || len % 2 || len / 2 > KEYCRYPT_BLOB_MAX)
+ return -EINVAL;
+ raw = kmalloc(len / 2, GFP_KERNEL);
+ if (!raw)
+ return -ENOMEM;
+ ret = hex2bin(raw, req->hex, len / 2) ? -EINVAL : 0;
+ if (!ret)
+ ret = keycrypt_payload_parse(raw, len / 2, &p);
+ kfree_sensitive(raw);
+ if (ret)
+ return ret;
+
+ m = &p->key.meta;
+ h = keycrypt_get_handle(m->backend, 0, 0, m->alg, false);
+ if (!h) {
+ ret = -ENODEV;
+ goto free;
+ }
+ down_read(&h->sem);
+ if (!h->b)
+ ret = -ENODEV;
+ else if (m->tier > h->tier)
+ ret = -EKEYREJECTED;
+ else if (m->tier < req->accepted_min_tier)
+ ret = -EPERM;
+ else if (req->want_purpose && m->purpose != req->want_purpose)
+ ret = -EKEYREJECTED;
+ else if (keycrypt_check_opts(h->b, keycrypt_opts(req)))
+ ret = -EINVAL;
+ else
+ ret = keycrypt_attach(h, p, keycrypt_opts(req));
+ up_read(&h->sem);
+ if (!ret) {
+ *out = p;
+ return 0;
+ }
+ keycrypt_handle_put(h);
+free:
+ kfree_sensitive(p);
+ return ret;
+}
+
+static int keycrypt_preparse(struct key_preparsed_payload *prep)
+{
+ struct keycrypt_payload *p = NULL;
+ struct keycrypt_req req = {};
+ char *buf, *opts;
+ int ret;
+
+ if (!prep->data || !prep->datalen ||
+ prep->datalen > KEYCRYPT_INPUT_MAX)
+ return -EINVAL;
+ /* A NUL would hide what follows it; a final one is tolerated */
+ if (memchr(prep->data, '\0', prep->datalen - 1))
+ return -EINVAL;
+
+ buf = kmemdup_nul(prep->data, prep->datalen, GFP_KERNEL);
+ opts = kzalloc(prep->datalen + 1, GFP_KERNEL);
+ if (!buf || !opts) {
+ ret = -ENOMEM;
+ goto out;
+ }
+ req.opts = opts;
+ req.opts_size = prep->datalen + 1;
+ ret = keycrypt_parse(buf, &req);
+ if (!ret) {
+ if (req.cmd == KEYCRYPT_CMD_LOAD)
+ ret = keycrypt_load(&req, &p);
+ else
+ ret = keycrypt_create(&req, &p);
+ }
+out:
+ kfree_sensitive(opts);
+ kfree_sensitive(buf); /* it may hold a key in clear */
+ if (ret)
+ return ret;
+ prep->payload.data[0] = p;
+ prep->quotalen = p->blob_len;
+ return 0;
+}
+
+static void keycrypt_free_preparse(struct key_preparsed_payload *prep)
+{
+ keycrypt_payload_free(prep->payload.data[0]);
+}
+
+static void keycrypt_destroy(struct key *key)
+{
+ keycrypt_payload_free(key->payload.data[0]);
+}
+
+/* What "keyctl read" returns: the blob in hex, what "load" takes */
+static long keycrypt_format(const struct keycrypt_payload *p,
+ char *buf, size_t buflen)
+{
+ long len = 2 * p->blob_len;
+ char *txt;
+
+ if (!buf || !buflen)
+ return len;
+ if (buflen >= len) {
+ bin2hex(buf, p->blob, p->blob_len);
+ return len;
+ }
+ txt = kmalloc(len, GFP_KERNEL);
+ if (!txt)
+ return -ENOMEM;
+ bin2hex(txt, p->blob, p->blob_len);
+ memcpy(buf, txt, buflen);
+ kfree(txt);
+ return len;
+}
+
+static long keycrypt_read(const struct key *key, char *buffer, size_t buflen)
+{
+ return keycrypt_format(dereference_key_locked(key), buffer, buflen);
+}
+
+static void keycrypt_purpose_str(u16 purpose, char *buf, size_t len)
+{
+ static const char * const names[] = {
+ "encrypt", "decrypt", "mac", "verify"
+ };
+ size_t i, n = 0;
+
+ buf[0] = '\0';
+ for (i = 0; i < ARRAY_SIZE(names); i++)
+ if (purpose & BIT(i))
+ n += scnprintf(buf + n, len - n, "%s%s", n ? "," : "",
+ names[i]);
+}
+
+/* "<description>: <alg> <purpose> <tier> <backend> <origin>" */
+static void keycrypt_describe(const struct key *key, struct seq_file *m)
+{
+ const struct keycrypt_payload *p;
+ char purpose[24];
+
+ seq_puts(m, key->description);
+ if (!key_is_positive(key))
+ return;
+ p = dereference_key_rcu(key);
+ if (!p)
+ return;
+ keycrypt_purpose_str(p->key.meta.purpose, purpose, sizeof(purpose));
+ seq_printf(m, ": %s %s %s %s %s",
+ KEYCRYPT_NAME(keycrypt_algs, p->key.meta.alg), purpose,
+ KEYCRYPT_NAME(keycrypt_tiers, p->key.meta.tier),
+ p->key.meta.backend,
+ KEYCRYPT_NAME(keycrypt_origins, p->key.meta.origin));
+}
+
+/*
+ * Detach every open context of @key and wipe the backend's state for it.
+ * h->sem is taken for writing so that no backend call is still running on
+ * those contexts; lock order: key->sem, h->sem, h->keys_lock. Safe to call
+ * twice.
+ */
+static void keycrypt_payload_revoke(struct keycrypt_payload *p,
+ struct key *key)
+{
+ struct keycrypt_handle *h;
+
+ if (!p || !p->handle)
+ return;
+ h = p->handle;
+ down_write(&h->sem);
+ mutex_lock(&h->keys_lock);
+ keycrypt_ctx_revoke(h, key); /* detaches c->key == key */
+ keycrypt_payload_destroy(h->b, p);
+ mutex_unlock(&h->keys_lock);
+ up_write(&h->sem);
+}
+
+static void keycrypt_revoke(struct key *key)
+{
+ keycrypt_payload_revoke(dereference_key_locked(key), key);
+}
+
+/*
+ * Never constructed on demand: a request-key helper would instantiate the
+ * key with its own credentials and keyrings, not the requester's. The key
+ * is negated here, so every caller gets -ENOKEY.
+ */
+static int keycrypt_request_key(struct key *authkey, void *aux)
+{
+ complete_request_key(authkey, -ENOKEY);
+ return 0;
+}
+
+/*
+ * No .update: a payload never changes once instantiated, which .revoke and
+ * keyctl_crypt_open() rely on when they read it without key->sem.
+ */
+struct key_type key_type_keycrypt = {
+ .name = "keycrypt",
+ .request_key = keycrypt_request_key,
+ .preparse = keycrypt_preparse,
+ .free_preparse = keycrypt_free_preparse,
+ .instantiate = generic_key_instantiate,
+ .destroy = keycrypt_destroy,
+ .describe = keycrypt_describe,
+ .read = keycrypt_read,
+ .revoke = keycrypt_revoke,
+};
+
+/*
+ * System policies: the kernel.keys sysctls
+ */
+
+static int keycrypt_sysctl_system_tier(const struct ctl_table *table,
+ int write, void *buf, size_t *lenp,
+ loff_t *ppos)
+{
+ unsigned int v = keycrypt_policy_system_tier();
+ const struct ctl_table t = { .data = &v, .maxlen = sizeof(v) };
+ int ret;
+
+ if (write && !capable(CAP_SYS_ADMIN))
+ return -EPERM;
+ ret = proc_douintvec(&t, write, buf, lenp, ppos);
+ if (ret || !write)
+ return ret;
+ return keycrypt_policy_set_system_tier(&keycrypt_policy,
+ v > U8_MAX ? U8_MAX : v);
+}
+
+static int keycrypt_sysctl_import(const struct ctl_table *table, int write,
+ void *buf, size_t *lenp, loff_t *ppos)
+{
+ unsigned int v = keycrypt_policy_import();
+ const struct ctl_table t = { .data = &v, .maxlen = sizeof(v) };
+ int ret;
+
+ if (write && !capable(CAP_SYS_ADMIN))
+ return -EPERM;
+ ret = proc_douintvec(&t, write, buf, lenp, ppos);
+ if (ret || !write)
+ return ret;
+ if (v > 1)
+ return -EINVAL;
+ return keycrypt_policy_set_import(&keycrypt_policy, v);
+}
+
+static const struct ctl_table keycrypt_sysctls[] = {
+ {
+ .procname = "keycrypt_system_tier",
+ .mode = 0644,
+ .proc_handler = keycrypt_sysctl_system_tier,
+ },
+ {
+ .procname = "keycrypt_import",
+ .mode = 0644,
+ .proc_handler = keycrypt_sysctl_import,
+ },
+};
+
+/*
+ * System policies: the boot parameters
+ */
+
+static int __init keycrypt_system_tier_setup(char *s)
+{
+ u8 tier = 0;
+
+ if (keycrypt_parse_tier(s, &tier) ||
+ keycrypt_policy_set_system_tier(&keycrypt_policy, tier))
+ pr_warn("ignoring keycrypt.system_tier=%s\n", s);
+ return 1;
+}
+__setup("keycrypt.system_tier=", keycrypt_system_tier_setup);
+
+static int __init keycrypt_import_setup(char *s)
+{
+ bool on;
+
+ if (kstrtobool(s, &on) ||
+ keycrypt_policy_set_import(&keycrypt_policy, on))
+ pr_warn("ignoring keycrypt.import=%s\n", s);
+ return 1;
+}
+__setup("keycrypt.import=", keycrypt_import_setup);
+
+static int __init keycrypt_init(void)
+{
+ int ret = register_key_type(&key_type_keycrypt);
+
+ if (ret)
+ return ret;
+ /* register_sysctl_init() logs and does not fail: defaults still work */
+ register_sysctl_init("kernel/keys", keycrypt_sysctls);
+ return 0;
+}
+late_initcall(keycrypt_init);
diff --git a/security/keys/keycrypt/ctx.c b/security/keys/keycrypt/ctx.c
new file mode 100644
index 000000000000..ce62ba08479b
--- /dev/null
+++ b/security/keys/keycrypt/ctx.c
@@ -0,0 +1,530 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * keycrypt - the operation context: KEYCTL_CRYPT_OPEN and its fd
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
+ */
+
+#include <crypto/aes.h>
+#include <crypto/utils.h>
+#include <linux/anon_inodes.h>
+#include <linux/build_bug.h>
+#include <linux/err.h>
+#include <linux/file.h>
+#include <linux/fs.h>
+#include <linux/key.h>
+#include <linux/keyctl.h>
+#include <linux/limits.h>
+#include <linux/minmax.h>
+#include <linux/mm.h>
+#include <linux/random.h>
+#include <linux/slab.h>
+#include <linux/stddef.h>
+#include <linux/string.h>
+#include <linux/uaccess.h>
+#include <uapi/linux/keycrypt.h>
+#include "../internal.h"
+#include "keycrypt.h"
+
+static_assert(offsetofend(struct keycrypt_open_params, iv) ==
+ KEYCRYPT_OPEN_PARAMS_SIZE_VER0);
+static_assert(KEYCRYPT_BACKEND_NAME_MAX <
+ sizeof_field(struct keycrypt_info, backend));
+
+static const u16 keycrypt_op_purpose[] = {
+ [KEYCRYPT_OP_ENCRYPT] = KEYCRYPT_PURPOSE_ENCRYPT,
+ [KEYCRYPT_OP_DECRYPT] = KEYCRYPT_PURPOSE_DECRYPT,
+ [KEYCRYPT_OP_MAC] = KEYCRYPT_PURPOSE_MAC,
+ [KEYCRYPT_OP_VERIFY] = KEYCRYPT_PURPOSE_MAC | KEYCRYPT_PURPOSE_VERIFY,
+};
+
+/*
+ * A context callback's error as user space sees it; keycrypt_backend_ret()
+ * is the wider mapping of @generate, @import and @load
+ */
+static int keycrypt_ctx_ret(int ret)
+{
+ switch (ret) {
+ case 0:
+ case -ENOMEM:
+ case -EINTR:
+ case -ERESTARTSYS:
+ case -EBADMSG:
+ return ret;
+ }
+ return -EIO;
+}
+
+/*
+ * Release the backend's state of @c. Called with @c->h->sem held (for
+ * writing by unregister and by revoke, with @b the backend; for reading
+ * otherwise, with @b = @c->h->b) and @c->h->keys_lock held. Leaves @done
+ * untouched: a detached @c with @bctx NULL answers through
+ * keycrypt_ctx_backend() instead of ending.
+ */
+void keycrypt_ctx_detach(struct keycrypt_backend *b, struct keycrypt_ctx *c)
+{
+ if (c->bctx && b)
+ b->ctx_free(b, c->bctx);
+ c->bctx = NULL;
+}
+
+/*
+ * Detach every context of @key: called by key_type_keycrypt.revoke(), with
+ * @h->sem held for writing and @h->keys_lock held. Left in @h->ctxs: only
+ * the fd's release removes a context from the list.
+ */
+void keycrypt_ctx_revoke(struct keycrypt_handle *h, struct key *key)
+{
+ struct keycrypt_ctx *c;
+
+ list_for_each_entry(c, &h->ctxs, node)
+ if (c->key == key)
+ keycrypt_ctx_detach(h->b, c);
+}
+
+/* Detach @c from its backend and from the handle's list */
+static void keycrypt_ctx_drop(struct keycrypt_ctx *c)
+{
+ struct keycrypt_handle *h = c->h;
+
+ down_read(&h->sem);
+ mutex_lock(&h->keys_lock);
+ keycrypt_ctx_detach(h->b, c);
+ list_del_init(&c->node);
+ mutex_unlock(&h->keys_lock);
+ up_read(&h->sem);
+}
+
+static void keycrypt_ctx_free(struct keycrypt_ctx *c)
+{
+ keycrypt_ctx_drop(c);
+ keycrypt_handle_put(c->h);
+ key_put(c->key);
+ kfree(c);
+}
+
+/* The key still usable: neither revoked, invalidated nor expired */
+static int keycrypt_ctx_check(struct keycrypt_ctx *c)
+{
+ int ret = key_validate(c->key);
+
+ return ret == -EKEYREVOKED || ret == -EKEYEXPIRED ? ret :
+ ret ? -EKEYREVOKED : 0;
+}
+
+/*
+ * Under @c->h->sem: the backend to run @c on, or why there is none. A
+ * detached @c (revoked key, removed backend) gives the key's own error,
+ * else -ENODEV, and the context is not ended by it: every later call
+ * gives the same answer.
+ */
+static int keycrypt_ctx_backend(struct keycrypt_ctx *c,
+ struct keycrypt_backend **b)
+{
+ *b = c->h->b;
+ if (*b && c->bctx)
+ return 0;
+ return keycrypt_ctx_check(c) ?: -ENODEV;
+}
+
+/* End @c after FINAL or a failure that may have changed its state */
+static long keycrypt_ctx_end(struct keycrypt_ctx *c, long ret)
+{
+ c->done = true;
+ keycrypt_ctx_drop(c);
+ return ret == -ERESTARTSYS ? -EINTR : ret;
+}
+
+/*
+ * What KEYCRYPT_IOC_INFO reports: @c's operation and accepted minimum
+ * tier, and its key's metadata
+ */
+static void keycrypt_ctx_info(const struct keycrypt_ctx *c,
+ struct keycrypt_info *info)
+{
+ memset(info, 0, sizeof(*info));
+ info->op = c->op;
+ info->alg = c->meta.alg;
+ info->purpose = c->meta.purpose;
+ info->tier = c->meta.tier;
+ info->origin = c->meta.origin;
+ info->accepted_min_tier = c->accepted_min_tier;
+ strscpy(info->backend, c->meta.backend, sizeof(info->backend));
+}
+
+/*
+ * KEYCRYPT_IOC_INFO under @c->lock: the state checks UPDATE with no
+ * data makes, then @info.
+ */
+static long keycrypt_ctx_info_get(struct keycrypt_ctx *c,
+ struct keycrypt_info *info)
+{
+ struct keycrypt_backend *b;
+ long ret;
+
+ ret = mutex_lock_killable(&c->lock);
+ if (ret)
+ return ret;
+ if (c->done) {
+ ret = -EBADFD;
+ goto unlock;
+ }
+ ret = keycrypt_ctx_check(c);
+ if (!ret) {
+ down_read(&c->h->sem);
+ ret = keycrypt_ctx_backend(c, &b);
+ up_read(&c->h->sem);
+ }
+ if (!ret)
+ keycrypt_ctx_info(c, info);
+unlock:
+ mutex_unlock(&c->lock);
+ return ret;
+}
+
+static long keycrypt_ioc_update(struct keycrypt_ctx *c,
+ struct keycrypt_update __user *uarg)
+{
+ bool hmac = c->op == KEYCRYPT_OP_MAC || c->op == KEYCRYPT_OP_VERIFY;
+ struct keycrypt_backend *b;
+ struct keycrypt_update u;
+ u8 *buf = NULL;
+ bool ran = false;
+ long ret;
+
+ if (copy_from_user(&u, uarg, sizeof(u)))
+ return -EFAULT;
+ if (u.flags || (hmac && u.out) || (!hmac && u.len && !u.out) ||
+ (!hmac && u.len % AES_BLOCK_SIZE))
+ return -EINVAL;
+ if (u.len > KEYCRYPT_UPDATE_MAX)
+ return -E2BIG;
+
+ ret = mutex_lock_killable(&c->lock);
+ if (ret)
+ return ret;
+ if (c->done) {
+ ret = -EBADFD;
+ goto unlock;
+ }
+ ret = keycrypt_ctx_check(c);
+ if (ret)
+ goto unlock;
+ if (!u.len) {
+ /* No data to run, but a detached context still answers */
+ down_read(&c->h->sem);
+ ret = keycrypt_ctx_backend(c, &b);
+ up_read(&c->h->sem);
+ goto unlock;
+ }
+ buf = kvmalloc(u.len, GFP_KERNEL_ACCOUNT);
+ if (!buf) {
+ ret = -ENOMEM;
+ goto unlock;
+ }
+ if (copy_from_user(buf, u64_to_user_ptr(u.in), u.len)) {
+ ret = -EFAULT;
+ goto free;
+ }
+ down_read(&c->h->sem);
+ ret = keycrypt_ctx_backend(c, &b);
+ ran = !ret;
+ if (!ret)
+ ret = keycrypt_ctx_ret(b->update(b, c->bctx, buf,
+ hmac ? NULL : buf, u.len));
+ up_read(&c->h->sem);
+ if (!ret && !hmac &&
+ copy_to_user(u64_to_user_ptr(u.out), buf, u.len))
+ ret = -EFAULT;
+ /* A failure past this point leaves the context in no known state */
+ if (ret && ran)
+ ret = keycrypt_ctx_end(c, ret);
+free:
+ kvfree_sensitive(buf, u.len);
+unlock:
+ mutex_unlock(&c->lock);
+ return ret;
+}
+
+static long keycrypt_ioc_final(struct keycrypt_ctx *c,
+ struct keycrypt_final __user *uarg)
+{
+ bool mac = c->op == KEYCRYPT_OP_MAC;
+ bool verify = c->op == KEYCRYPT_OP_VERIFY;
+ u8 tag[KEYCRYPT_MAC_LEN] = {}, expected[KEYCRYPT_MAC_LEN];
+ struct keycrypt_backend *b;
+ struct keycrypt_final f;
+ bool by_backend;
+ size_t len = 0;
+ long ret;
+
+ if (copy_from_user(&f, uarg, sizeof(f)))
+ return -EFAULT;
+ if (f.flags || (!mac && !verify && f.out))
+ return -EINVAL;
+
+ ret = mutex_lock_killable(&c->lock);
+ if (ret)
+ return ret;
+ if (c->done) {
+ ret = -EBADFD;
+ goto unlock;
+ }
+ ret = keycrypt_ctx_check(c);
+ if (ret)
+ goto unlock;
+ if (mac && (f.len < KEYCRYPT_MAC_LEN || !f.out)) {
+ ret = -ENOSPC; /* the context stays usable */
+ goto unlock;
+ }
+ if (verify && (f.len != KEYCRYPT_MAC_LEN || !f.out)) {
+ ret = -EINVAL; /* the context stays usable */
+ goto unlock;
+ }
+ /* The expected tag comes in before the backend's sem is taken */
+ if (verify && copy_from_user(expected, u64_to_user_ptr(f.out),
+ KEYCRYPT_MAC_LEN)) {
+ ret = -EFAULT;
+ goto wipe;
+ }
+ down_read(&c->h->sem);
+ ret = keycrypt_ctx_backend(c, &b);
+ if (ret) {
+ up_read(&c->h->sem);
+ goto wipe;
+ }
+ /* A VERIFY context whose backend compares its own tag: it never
+ * exists outside the backend on this path.
+ */
+ by_backend = verify && b->verify;
+ if (by_backend)
+ ret = keycrypt_ctx_ret(b->verify(b, c->bctx, expected));
+ else
+ ret = keycrypt_ctx_ret(b->final(b, c->bctx, tag, sizeof(tag),
+ &len));
+ up_read(&c->h->sem);
+ ret = keycrypt_ctx_end(c, ret);
+ if (by_backend) {
+ if (!ret && put_user(0U, &uarg->len))
+ ret = -EFAULT;
+ goto wipe;
+ }
+ if (!ret && len != (mac || verify ? KEYCRYPT_MAC_LEN : 0))
+ ret = -EIO;
+ if (!ret && verify && crypto_memneq(tag, expected, KEYCRYPT_MAC_LEN))
+ ret = -EBADMSG; /* the computed tag never leaves */
+ if (!ret && mac && len &&
+ copy_to_user(u64_to_user_ptr(f.out), tag, len))
+ ret = -EFAULT;
+ if (!ret && put_user((u32)(verify ? 0 : len), &uarg->len))
+ ret = -EFAULT;
+wipe:
+ memzero_explicit(tag, sizeof(tag));
+ memzero_explicit(expected, sizeof(expected));
+unlock:
+ mutex_unlock(&c->lock);
+ return ret;
+}
+
+static long keycrypt_ioc_info(struct keycrypt_ctx *c,
+ struct keycrypt_info __user *uarg)
+{
+ struct keycrypt_info info;
+ long ret;
+
+ ret = keycrypt_ctx_info_get(c, &info);
+ if (!ret && copy_to_user(uarg, &info, sizeof(info)))
+ ret = -EFAULT;
+ return ret;
+}
+
+static long keycrypt_ioctl(struct file *file, unsigned int cmd,
+ unsigned long arg)
+{
+ struct keycrypt_ctx *c = file->private_data;
+
+ switch (cmd) {
+ case KEYCRYPT_IOC_UPDATE:
+ return keycrypt_ioc_update(c, (void __user *)arg);
+ case KEYCRYPT_IOC_FINAL:
+ return keycrypt_ioc_final(c, (void __user *)arg);
+ case KEYCRYPT_IOC_INFO:
+ return keycrypt_ioc_info(c, (void __user *)arg);
+ }
+ return -ENOTTY;
+}
+
+static int keycrypt_release(struct inode *inode, struct file *file)
+{
+ keycrypt_ctx_free(file->private_data);
+ return 0;
+}
+
+static const struct file_operations keycrypt_fops = {
+ .owner = THIS_MODULE,
+ .unlocked_ioctl = keycrypt_ioctl,
+ .compat_ioctl = compat_ptr_ioctl,
+ .release = keycrypt_release,
+ .llseek = noop_llseek,
+};
+
+/*
+ * Under @h->sem: the backend to open a context of @p on, or why there
+ * is none.
+ */
+static int keycrypt_open_backend(struct keycrypt_handle *h,
+ const struct keycrypt_payload *p,
+ struct keycrypt_backend **b)
+{
+ *b = h->b;
+ if (!*b)
+ return -ENODEV;
+ if (p->destroyed)
+ return -EKEYREVOKED;
+ if (!(*b)->ctx_open)
+ return -ENODEV;
+ return 0;
+}
+
+/**
+ * keyctl_crypt_open() - KEYCTL_CRYPT_OPEN
+ * @id: the key, which must be of type keycrypt and searchable
+ * @uparams: struct keycrypt_open_params
+ * @usize: its size, for extension
+ * @flags: must be zero
+ *
+ * Return: an O_RDWR | O_CLOEXEC fd bound to the key and the operation,
+ * or a negative error.
+ */
+long keyctl_crypt_open(key_serial_t id, void __user *uparams,
+ size_t usize, unsigned long flags)
+{
+ struct keycrypt_open_params params;
+ struct keycrypt_payload *p;
+ struct keycrypt_handle *h;
+ struct keycrypt_backend *b;
+ struct keycrypt_ctx *c;
+ bool gen_iv = false;
+ key_ref_t kref;
+ struct key *key;
+ long ret;
+ int fd;
+
+ if (flags)
+ return -EINVAL;
+ if (usize > PAGE_SIZE)
+ return -E2BIG;
+ if (usize < KEYCRYPT_OPEN_PARAMS_SIZE_VER0)
+ return -EINVAL;
+ ret = copy_struct_from_user(¶ms, sizeof(params), uparams, usize);
+ if (ret)
+ return ret;
+ if (params.__reserved ||
+ (params.flags & ~KEYCRYPT_OPEN_CALLER_IV) ||
+ params.op < KEYCRYPT_OP_ENCRYPT || params.op > KEYCRYPT_OP_VERIFY ||
+ (params.accepted_min_tier &&
+ !keycrypt_tier_valid(params.accepted_min_tier)) ||
+ ((params.op == KEYCRYPT_OP_MAC || params.op == KEYCRYPT_OP_VERIFY) &&
+ memchr_inv(params.iv, 0, sizeof(params.iv))))
+ return -EINVAL;
+
+ kref = lookup_user_key(id, 0, KEY_NEED_SEARCH);
+ if (IS_ERR(kref))
+ return PTR_ERR(kref);
+ key = key_ref_to_ptr(kref);
+ if (key->type != &key_type_keycrypt) {
+ ret = -EOPNOTSUPP;
+ goto put_key;
+ }
+
+ /*
+ * key_type_keycrypt has no .update, so @p's content is immutable
+ * once instantiated: @p and @p->key.meta stay safe to read below,
+ * after key->sem is released.
+ */
+ down_read(&key->sem);
+ ret = key_validate(key);
+ p = dereference_key_locked(key);
+ if (!ret && !p)
+ ret = -ENOKEY;
+ if (!ret && !(p->key.meta.purpose & keycrypt_op_purpose[params.op]))
+ ret = -EKEYREJECTED;
+ if (!ret && p->key.meta.tier < max(params.accepted_min_tier,
+ keycrypt_policy_system_tier()))
+ ret = -EPERM;
+ if (!ret && (params.flags & KEYCRYPT_OPEN_CALLER_IV) &&
+ (params.op != KEYCRYPT_OP_ENCRYPT ||
+ p->key.meta.alg != KEYCRYPT_ALG_AES256_CBC))
+ ret = -EINVAL;
+ if (!ret && params.op == KEYCRYPT_OP_ENCRYPT &&
+ p->key.meta.alg == KEYCRYPT_ALG_AES256_CBC) {
+ gen_iv = !(params.flags & KEYCRYPT_OPEN_CALLER_IV);
+ if (gen_iv && memchr_inv(params.iv, 0, sizeof(params.iv)))
+ ret = -EINVAL;
+ }
+ h = ret ? NULL : p->handle;
+ if (h)
+ refcount_inc(&h->ref);
+ up_read(&key->sem);
+ if (ret)
+ goto put_key;
+
+ if (gen_iv) {
+ ret = get_random_bytes_wait(params.iv, sizeof(params.iv));
+ if (ret)
+ goto put_handle;
+ }
+
+ c = kzalloc_obj(*c, GFP_KERNEL_ACCOUNT);
+ if (!c) {
+ ret = -ENOMEM;
+ goto put_handle;
+ }
+ mutex_init(&c->lock);
+ INIT_LIST_HEAD(&c->node);
+ c->key = key;
+ c->h = h;
+ c->op = params.op;
+ c->meta = p->key.meta;
+ c->accepted_min_tier = params.accepted_min_tier;
+
+ down_read(&h->sem);
+ ret = keycrypt_open_backend(h, p, &b);
+ if (!ret)
+ ret = keycrypt_ctx_ret(b->ctx_open(b, &p->key, params.op,
+ params.iv, &c->bctx));
+ if (!ret) {
+ mutex_lock(&h->keys_lock);
+ list_add(&c->node, &h->ctxs);
+ mutex_unlock(&h->keys_lock);
+ }
+ up_read(&h->sem);
+ if (ret) {
+ memzero_explicit(params.iv, sizeof(params.iv));
+ kfree(c);
+ goto put_handle;
+ }
+
+ /* The write-back happens before the fd exists: no fd on EFAULT */
+ if (gen_iv &&
+ copy_to_user(((struct keycrypt_open_params __user *)uparams)->iv,
+ params.iv, sizeof(params.iv))) {
+ memzero_explicit(params.iv, sizeof(params.iv));
+ keycrypt_ctx_free(c);
+ return -EFAULT;
+ }
+ memzero_explicit(params.iv, sizeof(params.iv));
+
+ fd = anon_inode_getfd("[keycrypt]", &keycrypt_fops, c,
+ O_RDWR | O_CLOEXEC);
+ if (fd < 0)
+ keycrypt_ctx_free(c);
+ return fd;
+
+put_handle:
+ keycrypt_handle_put(h);
+put_key:
+ key_put(key);
+ return ret;
+}
diff --git a/security/keys/keycrypt/keycrypt.h b/security/keys/keycrypt/keycrypt.h
new file mode 100644
index 000000000000..5a41a68c48fa
--- /dev/null
+++ b/security/keys/keycrypt/keycrypt.h
@@ -0,0 +1,173 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * keycrypt - core-private definitions
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
+ */
+
+#ifndef _SECURITY_KEYS_KEYCRYPT_H
+#define _SECURITY_KEYS_KEYCRYPT_H
+
+#include <linux/list.h>
+#include <linux/mutex.h>
+#include <linux/refcount.h>
+#include <linux/rwsem.h>
+#include <keys/keycrypt.h>
+
+#define KEYCRYPT_BLOB_MAX (KEYCRYPT_HEADER_MAX + 4 + \
+ KEYCRYPT_BACKEND_DATA_MAX)
+#define KEYCRYPT_INPUT_MAX (2 * KEYCRYPT_BLOB_MAX + 256)
+
+#define KEYCRYPT_CMD_NEW 1
+#define KEYCRYPT_CMD_LOAD 2
+#define KEYCRYPT_CMD_IMPORT 3
+
+/**
+ * struct keycrypt_handle - the core's record of a registered backend
+ * @list: in the registry, under keycrypt_lock; unlinked by unregister
+ * @ref: one for the registry, one per key
+ * @sem: held for reading around backend calls, for writing by unregister
+ * and revoke
+ * @b: the backend, NULL once unregistered
+ * @keys_lock: guards @keys and @ctxs
+ * @keys: the payloads of the backend's keys
+ * @ctxs: open contexts, under @keys_lock
+ * @tier: the backend's tier
+ * @name: the backend's name
+ */
+struct keycrypt_handle {
+ struct list_head list;
+ refcount_t ref;
+ struct rw_semaphore sem;
+ struct keycrypt_backend *b;
+ struct mutex keys_lock; /* guards @keys and @ctxs */
+ struct list_head keys;
+ struct list_head ctxs;
+ u8 tier;
+ char name[KEYCRYPT_BACKEND_NAME_MAX + 1];
+};
+
+/**
+ * struct keycrypt_payload - the payload of a keycrypt key
+ * @handle: the backend's handle, NULL until the backend accepted the key
+ * @owner: the backend's module, pinned while the key exists
+ * @node: in @handle->keys
+ * @key: what the backend sees; its hdr and data point into @blob
+ * @destroyed: @key's backend state released; set once, under @handle->sem
+ * held for writing, or by the payload's own free
+ * @blob_len: bytes in @blob
+ * @blob: header, le32 length of the backend data, backend data
+ */
+struct keycrypt_payload {
+ struct keycrypt_handle *handle;
+ struct module *owner;
+ struct list_head node;
+ struct keycrypt_key key;
+ bool destroyed;
+ u32 blob_len;
+ u8 blob[];
+};
+
+/**
+ * struct keycrypt_req - a parsed add_key() payload
+ * @cmd: KEYCRYPT_CMD_*
+ * @alg: KEYCRYPT_ALG_* (new, import)
+ * @purpose: KEYCRYPT_PURPOSE_* mask (new, import)
+ * @want_purpose: "purpose=" of load, or 0
+ * @tier: "tier=" of new and import, or 0
+ * @min_tier: "min-tier=" of new and import, or 0
+ * @accepted_min_tier: "accepted-min-tier=" of load, or 0
+ * @backend: "backend=" of new and import, or empty
+ * @hex: the blob (load) or the key (import), hex encoded
+ * @opts: buffer, given by the caller, receiving the options for the
+ * backend, space separated
+ * @opts_size: size of @opts
+ */
+struct keycrypt_req {
+ int cmd;
+ u8 alg;
+ u16 purpose;
+ u16 want_purpose;
+ u8 tier;
+ u8 min_tier;
+ u8 accepted_min_tier;
+ char backend[KEYCRYPT_BACKEND_NAME_MAX + 1];
+ const char *hex;
+ char *opts;
+ size_t opts_size;
+};
+
+/**
+ * struct keycrypt_ctx - an open operation context
+ * @lock: serialises the calls on the fd
+ * @key: the key, referenced
+ * @h: its backend's handle, referenced
+ * @node: in @h->ctxs, under @h->keys_lock
+ * @bctx: the backend's state; NULL once detached (revoked, unregistered,
+ * or ended by FINAL or a failure)
+ * @op: KEYCRYPT_OP_*
+ * @meta: @key's metadata, copied at open
+ * @accepted_min_tier: the caller's KEYCRYPT_TIER_* at open, or 0
+ * @done: ended by FINAL or by a failure once the backend ran; every later
+ * call gives -EBADFD
+ */
+struct keycrypt_ctx {
+ struct mutex lock; /* serialises the calls on the fd */
+ struct key *key;
+ struct keycrypt_handle *h;
+ struct list_head node;
+ void *bctx;
+ u32 op;
+ struct keycrypt_meta meta;
+ u8 accepted_min_tier;
+ bool done;
+};
+
+/* The key length each algorithm takes; false for an unknown alg */
+static inline bool keycrypt_key_len_valid(u8 alg, size_t len)
+{
+ switch (alg) {
+ case KEYCRYPT_ALG_AES256_CBC:
+ return len == 32;
+ case KEYCRYPT_ALG_HMAC_SHA256:
+ return len >= 1 && len <= 64;
+ }
+ return false;
+}
+
+/* The tiers a key may have, and a tier option may name */
+bool keycrypt_tier_valid(u32 tier);
+
+/* The system tier at boot (Kconfig); it can only be raised */
+#if IS_ENABLED(CONFIG_KEYCRYPT_SYSTEM_TIER_HSM)
+#define KEYCRYPT_BOOT_SYSTEM_TIER KEYCRYPT_TIER_HSM
+#elif IS_ENABLED(CONFIG_KEYCRYPT_SYSTEM_TIER_TEE)
+#define KEYCRYPT_BOOT_SYSTEM_TIER KEYCRYPT_TIER_TEE
+#else
+#define KEYCRYPT_BOOT_SYSTEM_TIER KEYCRYPT_TIER_KERNEL
+#endif
+
+/**
+ * struct keycrypt_policy - system-wide limits, one-way until reboot
+ * @lock: serialises changes
+ * @system_tier: KEYCRYPT_TIER_*: the lowest tier a key may be used at;
+ * can only be raised
+ * @import: import allowed; can only be turned off
+ */
+struct keycrypt_policy {
+ struct mutex lock; /* serialises changes */
+ u8 system_tier;
+ bool import;
+};
+
+extern struct keycrypt_policy keycrypt_policy;
+u8 keycrypt_policy_system_tier(void);
+bool keycrypt_policy_import(void);
+
+extern struct key_type key_type_keycrypt;
+int keycrypt_backend_ret(int ret);
+void keycrypt_handle_put(struct keycrypt_handle *h);
+void keycrypt_ctx_detach(struct keycrypt_backend *b, struct keycrypt_ctx *c);
+void keycrypt_ctx_revoke(struct keycrypt_handle *h, struct key *key);
+
+#endif /* _SECURITY_KEYS_KEYCRYPT_H */
diff --git a/security/keys/keyctl.c b/security/keys/keyctl.c
index d6b10fd67627..d74708b832ea 100644
--- a/security/keys/keyctl.c
+++ b/security/keys/keyctl.c
@@ -2031,6 +2031,11 @@ SYSCALL_DEFINE5(keyctl, int, option, unsigned long, arg2, unsigned long, arg3,
case KEYCTL_WATCH_KEY:
return keyctl_watch_key((key_serial_t)arg2, (int)arg3, (int)arg4);
+ case KEYCTL_CRYPT_OPEN:
+ return keyctl_crypt_open((key_serial_t)arg2,
+ (void __user *)arg3,
+ (size_t)arg4, arg5);
+
default:
return -EOPNOTSUPP;
}
--
2.43.0
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [RFC PATCH 2/9] KEYS: keycrypt: Add the sw backend
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
2026-11-18 14:04 ` [RFC PATCH 1/9] KEYS: keycrypt: Add a key type for keys user space never reads Rodolfo Giometti
@ 2026-11-18 14:04 ` Rodolfo Giometti
2026-11-18 14:04 ` [RFC PATCH 3/9] KEYS: keycrypt: Add the OP-TEE backend Rodolfo Giometti
` (8 subsequent siblings)
10 siblings, 0 replies; 14+ messages in thread
From: Rodolfo Giometti @ 2026-11-18 14:04 UTC (permalink / raw)
To: David Howells, Jarkko Sakkinen, keyrings
Cc: Herbert Xu, David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, Rodolfo Giometti
Systems with neither a TEE nor a crypto engine able to keep keys still
want keys that user space cannot read and that are bound to one
algorithm and purpose, and the same interface on every device.
Add the "sw" backend, of the kernel tier: it seals each key with
AES-256-GCM under a key derived with HMAC-SHA256 from a "trusted" key
named by master=, authenticating the keycrypt header with it, and runs
the operations with the kernel's crypto library. A loaded key is in
clear in kernel memory until revoked or destroyed, which the kernel
log says when the backend registers and when the first key is loaded;
the backend is chosen only by tier=kernel, by backend=sw, or when no
backend of a higher tier is registered, and a system that must not use
it raises the system tier above it (CONFIG_KEYCRYPT_SYSTEM_TIER_*), or
leaves this option off.
In that derivation the trusted key's material is what the HMAC
processes, under a label and a random salt as its key, and not the
other way round: AF_ALG lets user space name a trusted key by its
serial number as the key of an HMAC socket, so with the material as the
key anyone allowed to search the master could recompute the sealing
key of every blob.
It depends on TRUSTED_KEYS and is a module when trusted keys are one.
Signed-off-by: Rodolfo Giometti <giometti@enneenne.com>
---
security/keys/keycrypt/Kconfig | 36 ++-
security/keys/keycrypt/Makefile | 2 +
security/keys/keycrypt/sw.c | 404 ++++++++++++++++++++++++++++++++
security/keys/keycrypt/sw.h | 30 +++
4 files changed, 468 insertions(+), 4 deletions(-)
create mode 100644 security/keys/keycrypt/sw.c
create mode 100644 security/keys/keycrypt/sw.h
diff --git a/security/keys/keycrypt/Kconfig b/security/keys/keycrypt/Kconfig
index e1d1b8e2a58b..50fd4cb3b1d2 100644
--- a/security/keys/keycrypt/Kconfig
+++ b/security/keys/keycrypt/Kconfig
@@ -34,10 +34,13 @@ choice
help
The lowest tier a keycrypt key may be used at when the kernel
starts: KEYCTL_CRYPT_OPEN refuses a key of a lower tier, which
- can still be created and loaded. The keycrypt.system_tier= boot
- parameter and the kernel.keys.keycrypt_system_tier sysctl can
- only raise it, so a signed kernel image sets a floor its command
- line cannot lower.
+ can still be created and loaded. A key of the kernel tier so
+ created or loaded is in clear in kernel memory all the same, as
+ its trusted master is: to have none, build without
+ KEYCRYPT_SW, the in-tree backend of that tier. The
+ keycrypt.system_tier= boot parameter and the
+ kernel.keys.keycrypt_system_tier sysctl can only raise it, so a
+ signed kernel image sets a floor its command line cannot lower.
The default sets no floor: which backends a kernel builds says
nothing about which will be present when it runs (a
@@ -70,3 +73,28 @@ config KEYCRYPT_SYSTEM_TIER_HSM
keycrypt key can be used at all.
endchoice
+
+config KEYCRYPT_SW
+ tristate "The sw keycrypt backend, of the kernel tier"
+ depends on KEYCRYPT && TRUSTED_KEYS
+ select CRYPTO_LIB_AES_GCM
+ select CRYPTO_LIB_AES_CBC
+ select CRYPTO_LIB_SHA256
+ help
+ This option provides the "sw" keycrypt backend: keys sealed
+ with AES-256-GCM under a key derived from a "trusted" key, and
+ used by the kernel itself. While such a key is loaded, it is in
+ clear in kernel memory: this lowers the security of the system,
+ and the kernel says so in its log when the backend registers and
+ when the first such key is loaded. This backend is chosen by
+ tier=kernel or backend=sw, and for a key created with
+ neither a tier option nor backend= whenever no backend of a
+ higher tier is registered.
+
+ It needs trusted keys (TRUSTED_KEYS) to seal and load keys, and
+ is built as a module when trusted keys are one.
+
+ Use trusted keys created with blob authorization or a policy as
+ masters (see the documentation).
+
+ If you are unsure as to whether this is required, answer N.
diff --git a/security/keys/keycrypt/Makefile b/security/keys/keycrypt/Makefile
index 8910fb0156e7..5a2e222a6908 100644
--- a/security/keys/keycrypt/Makefile
+++ b/security/keys/keycrypt/Makefile
@@ -1,3 +1,5 @@
# SPDX-License-Identifier: GPL-2.0-only
obj-y += core.o ctx.o
+obj-$(CONFIG_KEYCRYPT_SW) += keycrypt_sw.o
+keycrypt_sw-y := sw.o
diff --git a/security/keys/keycrypt/sw.c b/security/keys/keycrypt/sw.c
new file mode 100644
index 000000000000..f1ff4de4afc6
--- /dev/null
+++ b/security/keys/keycrypt/sw.c
@@ -0,0 +1,404 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * keycrypt - the sw backend, of the kernel tier: keys sealed under a
+ * trusted key, used by the kernel itself
+ *
+ * The blob's layout and its GCM key are in keycrypt.rst, "The sw
+ * backend".
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
+ */
+
+#include <crypto/aes-cbc.h>
+#include <crypto/aes-gcm.h>
+#include <crypto/sha2.h>
+#include <keys/trusted-type.h>
+#include <linux/err.h>
+#include <linux/init.h>
+#include <linux/key.h>
+#include <linux/module.h>
+#include <linux/random.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+#include "keycrypt.h"
+#include "sw.h"
+
+/* <keys/trusted-type.h> redefines pr_fmt; reassert ours after it */
+#undef pr_fmt
+#define pr_fmt(fmt) "keycrypt: " fmt
+
+#define SW_LABEL "keycrypt kernel-tier v1"
+#define SW_AAD_MAX (KEYCRYPT_HEADER_MAX + 2 + KEYCRYPT_SW_DESC_MAX + \
+ KEYCRYPT_SW_SALT_LEN)
+
+static int sw_prepare(struct aes_gcm_key *gk, const u8 *master, size_t mlen,
+ const u8 *salt)
+{
+ u8 label[sizeof(SW_LABEL) - 1 + KEYCRYPT_SW_SALT_LEN];
+ u8 dk[SHA256_DIGEST_SIZE];
+ int ret;
+
+ memcpy(label, SW_LABEL, sizeof(SW_LABEL) - 1);
+ memcpy(label + sizeof(SW_LABEL) - 1, salt, KEYCRYPT_SW_SALT_LEN);
+ /*
+ * The master is the data, never the key: AF_ALG keys an HMAC with
+ * a trusted key given by serial, so whoever may search the master
+ * could otherwise compute this key.
+ */
+ hmac_sha256_usingrawkey(label, sizeof(label), master, mlen, dk);
+ ret = aes_gcm_preparekey(gk, dk, sizeof(dk), KEYCRYPT_SW_TAG_LEN);
+ memzero_explicit(dk, sizeof(dk));
+ return ret;
+}
+
+static size_t sw_aad(u8 *aad, const u8 *hdr, u32 hdr_len, const u8 *prefix,
+ size_t prefix_len)
+{
+ memcpy(aad, hdr, hdr_len);
+ memcpy(aad + hdr_len, prefix, prefix_len);
+ return hdr_len + prefix_len;
+}
+
+static int keycrypt_sw_seal(const u8 *master, size_t mlen,
+ const u8 *hdr, u32 hdr_len,
+ const char *desc, const u8 *key,
+ size_t klen, struct keycrypt_blob *out)
+{
+ size_t dlen = strlen(desc), prefix_len, alen, len;
+ struct aes_gcm_key gk;
+ u8 aad[SW_AAD_MAX];
+ u8 *p, *salt, *nonce, *ct;
+ int ret;
+
+ if (!dlen || dlen > KEYCRYPT_SW_DESC_MAX ||
+ hdr_len > KEYCRYPT_HEADER_MAX || !klen ||
+ klen > KEYCRYPT_SW_KEY_MAX)
+ return -EINVAL;
+ len = 2 + dlen + KEYCRYPT_SW_SALT_LEN + KEYCRYPT_SW_NONCE_LEN + klen +
+ KEYCRYPT_SW_TAG_LEN;
+ p = kmalloc(len, GFP_KERNEL);
+ if (!p)
+ return -ENOMEM;
+ p[0] = KEYCRYPT_SW_VERSION;
+ p[1] = dlen;
+ memcpy(p + 2, desc, dlen);
+ salt = p + 2 + dlen;
+ nonce = salt + KEYCRYPT_SW_SALT_LEN;
+ ct = nonce + KEYCRYPT_SW_NONCE_LEN;
+ ret = get_random_bytes_wait(salt, KEYCRYPT_SW_SALT_LEN);
+ if (ret) {
+ kfree(p);
+ return ret;
+ }
+ ret = sw_prepare(&gk, master, mlen, salt);
+ if (ret) {
+ kfree(p);
+ return ret;
+ }
+ ret = get_random_bytes_wait(nonce, KEYCRYPT_SW_NONCE_LEN);
+ if (ret) {
+ memzero_explicit(&gk, sizeof(gk));
+ kfree(p);
+ return ret;
+ }
+ prefix_len = 2 + dlen + KEYCRYPT_SW_SALT_LEN;
+ alen = sw_aad(aad, hdr, hdr_len, p, prefix_len);
+ aes_gcm_encrypt(ct, key, klen, ct + klen, aad, alen, nonce, &gk);
+ memzero_explicit(&gk, sizeof(gk));
+ out->data = p;
+ out->len = len;
+ return 0;
+}
+
+static int keycrypt_sw_unseal(const u8 *master, size_t mlen,
+ const u8 *hdr, u32 hdr_len,
+ const u8 *data, u32 len, u8 *key,
+ size_t *klen)
+{
+ const u8 *salt, *nonce, *ct;
+ struct aes_gcm_key gk;
+ size_t dlen, clen, alen, prefix_len;
+ u8 aad[SW_AAD_MAX];
+ int ret;
+
+ if (len < 2 || data[0] != KEYCRYPT_SW_VERSION ||
+ hdr_len > KEYCRYPT_HEADER_MAX)
+ return -EBADMSG;
+ dlen = data[1];
+ if (!dlen ||
+ len < 2 + dlen + KEYCRYPT_SW_SALT_LEN + KEYCRYPT_SW_NONCE_LEN + 1 +
+ KEYCRYPT_SW_TAG_LEN)
+ return -EBADMSG;
+ clen = len - 2 - dlen - KEYCRYPT_SW_SALT_LEN - KEYCRYPT_SW_NONCE_LEN -
+ KEYCRYPT_SW_TAG_LEN;
+ if (clen > KEYCRYPT_SW_KEY_MAX)
+ return -EBADMSG;
+ salt = data + 2 + dlen;
+ nonce = salt + KEYCRYPT_SW_SALT_LEN;
+ ct = nonce + KEYCRYPT_SW_NONCE_LEN;
+ prefix_len = 2 + dlen + KEYCRYPT_SW_SALT_LEN;
+ alen = sw_aad(aad, hdr, hdr_len, data, prefix_len);
+ ret = sw_prepare(&gk, master, mlen, salt);
+ if (ret)
+ return ret;
+ ret = aes_gcm_decrypt(key, ct, clen, ct + clen, aad, alen, nonce, &gk);
+ memzero_explicit(&gk, sizeof(gk));
+ if (ret) {
+ memzero_explicit(key, clen);
+ return -EBADMSG;
+ }
+ *klen = clen;
+ return 0;
+}
+
+/*
+ * Copy the key material of the trusted key @desc that the caller can
+ * search for into @buf (MAX_KEY_SIZE bytes). No callout information, so no
+ * upcall: the key must exist, though it may still be under construction,
+ * and then this waits for it with the backend's handle held: the one wait
+ * without bound in this backend's callbacks. Not request_key_rcu(): it
+ * misses keys that the RCU walk cannot reach, such as those of the user
+ * keyring of a process without a session keyring.
+ */
+static int sw_master(const char *desc, u8 *buf, size_t *len)
+{
+ const struct trusted_key_payload *tp;
+ struct key *mk;
+ int ret;
+
+ mk = request_key(&key_type_trusted, desc, NULL);
+ if (IS_ERR(mk))
+ return PTR_ERR(mk) == -EACCES ? -EACCES : -ENOKEY;
+ down_read(&mk->sem);
+ tp = dereference_key_locked(mk);
+ if (key_validate(mk) || !tp || tp->key_len < MIN_KEY_SIZE ||
+ tp->key_len > MAX_KEY_SIZE) {
+ ret = -ENOKEY;
+ } else {
+ memcpy(buf, tp->key, tp->key_len);
+ *len = tp->key_len;
+ ret = 0;
+ }
+ up_read(&mk->sem);
+ key_put(mk);
+ return ret;
+}
+
+/* The one option of the sw backend: "master=<description>" */
+static int sw_master_opt(const char *opts, const char **desc)
+{
+ if (!opts || strncmp(opts, "master=", 7) || !opts[7])
+ return -EINVAL;
+ *desc = opts + 7;
+ return 0;
+}
+
+static int sw_seal_key(const u8 *hdr, u32 hdr_len, const char *opts,
+ const u8 *key, size_t klen, struct keycrypt_blob *out)
+{
+ u8 master[MAX_KEY_SIZE];
+ const char *desc;
+ size_t mlen;
+ int ret;
+
+ ret = sw_master_opt(opts, &desc);
+ if (ret)
+ return ret;
+ if (strlen(desc) > KEYCRYPT_SW_DESC_MAX)
+ return -EINVAL;
+ ret = sw_master(desc, master, &mlen);
+ if (!ret)
+ ret = keycrypt_sw_seal(master, mlen, hdr, hdr_len, desc, key,
+ klen, out);
+ memzero_explicit(master, sizeof(master));
+ return ret;
+}
+
+static int sw_generate(struct keycrypt_backend *b,
+ const struct keycrypt_meta *m, const u8 *hdr,
+ u32 hdr_len, const char *opts,
+ struct keycrypt_blob *out)
+{
+ u8 key[32];
+ int ret;
+
+ ret = get_random_bytes_wait(key, sizeof(key));
+ if (!ret)
+ ret = sw_seal_key(hdr, hdr_len, opts, key, sizeof(key), out);
+ memzero_explicit(key, sizeof(key));
+ return ret;
+}
+
+static int sw_import(struct keycrypt_backend *b,
+ const struct keycrypt_meta *m, const u8 *hdr,
+ u32 hdr_len, const char *opts, const u8 *key,
+ size_t keylen, struct keycrypt_blob *out)
+{
+ return sw_seal_key(hdr, hdr_len, opts, key, keylen, out);
+}
+
+static int sw_load(struct keycrypt_backend *b, struct keycrypt_key *k,
+ const char *opts)
+{
+ char desc[KEYCRYPT_SW_DESC_MAX + 1];
+ u8 master[MAX_KEY_SIZE];
+ struct keycrypt_sw_key *priv;
+ size_t mlen, dlen;
+ int ret;
+
+ if (opts)
+ return -EINVAL;
+ if (k->data_len < 2 || !k->data[1])
+ return -EBADMSG;
+ dlen = k->data[1];
+ if (k->data_len < 2 + dlen)
+ return -EBADMSG;
+ memcpy(desc, k->data + 2, dlen);
+ desc[dlen] = '\0';
+ if (strlen(desc) != dlen)
+ return -EBADMSG;
+
+ priv = kzalloc_obj(*priv);
+ if (!priv)
+ return -ENOMEM;
+ ret = sw_master(desc, master, &mlen);
+ if (!ret)
+ ret = keycrypt_sw_unseal(master, mlen, k->hdr, k->hdr_len,
+ k->data, k->data_len, priv->key,
+ &priv->len);
+ memzero_explicit(master, sizeof(master));
+ if (!ret && !keycrypt_key_len_valid(k->meta.alg, priv->len))
+ ret = -EBADMSG;
+ if (ret) {
+ kfree_sensitive(priv);
+ return ret;
+ }
+ k->priv = priv;
+ pr_warn_once("a key of the kernel tier is loaded: it is in clear in kernel memory\n");
+ return 0;
+}
+
+static void sw_destroy(struct keycrypt_backend *b, struct keycrypt_key *k)
+{
+ kfree_sensitive(k->priv);
+ k->priv = NULL;
+}
+
+struct sw_ctx {
+ u32 op;
+ union {
+ struct {
+ union {
+ struct aes_key key; /* decrypt */
+ struct aes_enckey enc_key; /* encrypt-only */
+ };
+ u8 iv[AES_BLOCK_SIZE];
+ } cbc;
+ struct hmac_sha256_ctx mac;
+ };
+};
+
+static int sw_ctx_open(struct keycrypt_backend *b, struct keycrypt_key *k,
+ u32 op, u8 *iv, void **ctx)
+{
+ struct keycrypt_sw_key *kk = k->priv;
+ struct sw_ctx *c;
+ int ret;
+
+ if (!kk)
+ return -EIO;
+ c = kzalloc_obj(*c, GFP_KERNEL_ACCOUNT);
+ if (!c)
+ return -ENOMEM;
+ c->op = op;
+ if (op == KEYCRYPT_OP_MAC || op == KEYCRYPT_OP_VERIFY) {
+ hmac_sha256_init_usingrawkey(&c->mac, kk->key, kk->len);
+ } else {
+ ret = op == KEYCRYPT_OP_ENCRYPT ?
+ aes_prepareenckey(&c->cbc.enc_key, kk->key, kk->len) :
+ aes_preparekey(&c->cbc.key, kk->key, kk->len);
+ if (ret) {
+ kfree_sensitive(c);
+ return -EIO;
+ }
+ memcpy(c->cbc.iv, iv, AES_BLOCK_SIZE);
+ }
+ *ctx = c;
+ return 0;
+}
+
+static int sw_update(struct keycrypt_backend *b, void *ctx, const u8 *in,
+ u8 *out, size_t len)
+{
+ struct sw_ctx *c = ctx;
+
+ switch (c->op) {
+ case KEYCRYPT_OP_ENCRYPT:
+ aes_cbc_encrypt(out, in, len, c->cbc.iv, &c->cbc.enc_key);
+ break;
+ case KEYCRYPT_OP_DECRYPT:
+ aes_cbc_decrypt(out, in, len, c->cbc.iv, &c->cbc.key);
+ break;
+ default:
+ hmac_sha256_update(&c->mac, in, len);
+ }
+ return 0;
+}
+
+static int sw_final(struct keycrypt_backend *b, void *ctx, u8 *out,
+ size_t out_size, size_t *len)
+{
+ struct sw_ctx *c = ctx;
+
+ if (c->op == KEYCRYPT_OP_MAC || c->op == KEYCRYPT_OP_VERIFY) {
+ if (out_size < SHA256_DIGEST_SIZE)
+ return -EIO;
+ hmac_sha256_final(&c->mac, out);
+ *len = SHA256_DIGEST_SIZE;
+ } else {
+ *len = 0;
+ }
+ return 0;
+}
+
+static void sw_ctx_free(struct keycrypt_backend *b, void *ctx)
+{
+ kfree_sensitive(ctx);
+}
+
+static const char * const sw_opts[] = { "master", NULL };
+
+static struct keycrypt_backend keycrypt_sw = {
+ .name = "sw",
+ .tier = KEYCRYPT_TIER_KERNEL,
+ .algs = KEYCRYPT_ALGS_ALL,
+ .owner = THIS_MODULE,
+ .opts = sw_opts,
+ .generate = sw_generate,
+ .import = sw_import,
+ .load = sw_load,
+ .destroy = sw_destroy,
+ .ctx_open = sw_ctx_open,
+ .update = sw_update,
+ .final = sw_final,
+ .ctx_free = sw_ctx_free,
+};
+
+static int __init keycrypt_sw_init(void)
+{
+ int ret = keycrypt_register_backend(&keycrypt_sw);
+
+ if (!ret)
+ pr_warn("kernel tier enabled: its keys are in clear in kernel memory while loaded\n");
+ return ret;
+}
+module_init(keycrypt_sw_init);
+
+static void __exit keycrypt_sw_exit(void)
+{
+ keycrypt_unregister_backend(&keycrypt_sw);
+}
+module_exit(keycrypt_sw_exit);
+
+MODULE_DESCRIPTION("keycrypt sw backend, of the kernel tier");
+MODULE_LICENSE("GPL");
diff --git a/security/keys/keycrypt/sw.h b/security/keys/keycrypt/sw.h
new file mode 100644
index 000000000000..30e24fb56ce3
--- /dev/null
+++ b/security/keys/keycrypt/sw.h
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * keycrypt - the sw backend's blob fields and loaded-key state
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
+ */
+
+#ifndef _SECURITY_KEYS_KEYCRYPT_SW_H
+#define _SECURITY_KEYS_KEYCRYPT_SW_H
+
+#include <linux/types.h>
+
+#define KEYCRYPT_SW_VERSION 1
+#define KEYCRYPT_SW_SALT_LEN 32
+#define KEYCRYPT_SW_NONCE_LEN 12
+#define KEYCRYPT_SW_TAG_LEN 16
+#define KEYCRYPT_SW_DESC_MAX 255
+#define KEYCRYPT_SW_KEY_MAX 64
+
+/**
+ * struct keycrypt_sw_key - the sw backend's state for a loaded key
+ * @len: bytes in @key
+ * @key: the key, in clear
+ */
+struct keycrypt_sw_key {
+ size_t len;
+ u8 key[KEYCRYPT_SW_KEY_MAX];
+};
+
+#endif /* _SECURITY_KEYS_KEYCRYPT_SW_H */
--
2.43.0
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [RFC PATCH 3/9] KEYS: keycrypt: Add the OP-TEE backend
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
2026-11-18 14:04 ` [RFC PATCH 1/9] KEYS: keycrypt: Add a key type for keys user space never reads Rodolfo Giometti
2026-11-18 14:04 ` [RFC PATCH 2/9] KEYS: keycrypt: Add the sw backend Rodolfo Giometti
@ 2026-11-18 14:04 ` Rodolfo Giometti
2026-11-18 14:07 ` [RFC PATCH 4/9] docs: keycrypt: document keycrypt keys Rodolfo Giometti
` (7 subsequent siblings)
10 siblings, 0 replies; 14+ messages in thread
From: Rodolfo Giometti @ 2026-11-18 14:04 UTC (permalink / raw)
To: David Howells, Jarkko Sakkinen, keyrings
Cc: Herbert Xu, David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, Rodolfo Giometti
Keys of the kernel tier are in clear in kernel memory while loaded,
and nothing the keycrypt core checks holds against a compromised
kernel. Add "optee", a backend of the tee tier.
One TA session is one operation context. The TA authenticates the
key's header again when the context opens, refuses an operation the
key's purpose does not allow, keeps the CBC chain and the HMAC state,
and compares a tag to verify without returning it: what keycrypt.rst's
"Backend requirements" asks of a backend against a compromised kernel.
The TA accepts only kernel clients. It is ta/keycrypt, written for
OP-TEE and not proposed to OP-TEE yet.
Signed-off-by: Rodolfo Giometti <giometti@enneenne.com>
---
security/keys/keycrypt/Kconfig | 17 ++
security/keys/keycrypt/Makefile | 2 +
security/keys/keycrypt/optee.c | 437 ++++++++++++++++++++++++++++++++
security/keys/keycrypt/optee.h | 37 +++
4 files changed, 493 insertions(+)
create mode 100644 security/keys/keycrypt/optee.c
create mode 100644 security/keys/keycrypt/optee.h
diff --git a/security/keys/keycrypt/Kconfig b/security/keys/keycrypt/Kconfig
index 50fd4cb3b1d2..e61922933bd7 100644
--- a/security/keys/keycrypt/Kconfig
+++ b/security/keys/keycrypt/Kconfig
@@ -98,3 +98,20 @@ config KEYCRYPT_SW
masters (see the documentation).
If you are unsure as to whether this is required, answer N.
+
+config KEYCRYPT_OPTEE
+ tristate "Keycrypt keys held by OP-TEE"
+ depends on KEYCRYPT && TEE
+ help
+ This option provides the "optee" keycrypt backend, of the tee
+ tier: keys sealed by the keycrypt Trusted Application under a
+ key derived from the device's hardware unique key, and used only
+ inside it. The kernel never holds such a key in clear, except
+ one given to it to import. The keys are only as secret as that
+ hardware unique key: with OP-TEE's test value (QEMU, or a board
+ whose key is not provisioned) anyone can unseal them.
+
+ It needs OP-TEE with the keycrypt TA built in as an early TA,
+ which the driver finds on the TEE bus.
+
+ If you are unsure as to whether this is required, answer N.
diff --git a/security/keys/keycrypt/Makefile b/security/keys/keycrypt/Makefile
index 5a2e222a6908..f051050428cd 100644
--- a/security/keys/keycrypt/Makefile
+++ b/security/keys/keycrypt/Makefile
@@ -3,3 +3,5 @@
obj-y += core.o ctx.o
obj-$(CONFIG_KEYCRYPT_SW) += keycrypt_sw.o
keycrypt_sw-y := sw.o
+obj-$(CONFIG_KEYCRYPT_OPTEE) += keycrypt_optee.o
+keycrypt_optee-y := optee.o
diff --git a/security/keys/keycrypt/optee.c b/security/keys/keycrypt/optee.c
new file mode 100644
index 000000000000..5a3ab6f825f1
--- /dev/null
+++ b/security/keys/keycrypt/optee.c
@@ -0,0 +1,437 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * keycrypt - the OP-TEE backend
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
+ */
+
+#include <keys/keycrypt.h>
+#include <linux/err.h>
+#include <linux/module.h>
+#include <linux/mutex.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+#include <linux/tee_drv.h>
+#include <linux/uuid.h>
+#include "optee.h"
+
+#define KC_KEY_MAX 64 /* the longest key, hmac-sha256's */
+
+/*
+ * Offsets in a shared buffer, which carries one call's parameters at a
+ * time: header, blob and imported key for a control call; header, blob
+ * and IV for CTX_OPEN; data and tag for a context's later calls.
+ */
+#define KC_SHM_HDR 0
+#define KC_SHM_BLOB (KC_SHM_HDR + KEYCRYPT_HEADER_MAX)
+#define KC_SHM_KEY (KC_SHM_BLOB + KC_TA_DATA_MAX)
+#define KC_CTL_SIZE (KC_SHM_KEY + KC_KEY_MAX)
+#define KC_SHM_DATA 0
+#define KC_SHM_TAG (KC_SHM_DATA + KEYCRYPT_UPDATE_MAX)
+#define KC_SHM_IV (KC_SHM_TAG + KEYCRYPT_MAC_LEN)
+#define KC_IV_LEN sizeof_field(struct keycrypt_open_params, iv)
+#define KC_CTX_SIZE (KC_SHM_IV + KC_IV_LEN)
+
+static_assert(KC_SHM_BLOB + KC_TA_DATA_MAX <= KC_SHM_TAG);
+static_assert(KEYCRYPT_UPDATE_MAX <= KC_TA_BUF_MAX);
+
+/**
+ * struct kc_optee - the backend's link to the TA
+ * @tee: the TEE context of every session, NULL while no TA device is bound
+ * @uuid: the TA's
+ * @ctl: the control session (GENERATE, IMPORT, CHECK), open while the
+ * backend is registered
+ * @ctl_shm: its shared buffer
+ * @ctl_va: @ctl_shm's kernel address
+ * @ctl_lock: one control call at a time, the one @ctl_shm holds
+ */
+struct kc_optee {
+ struct tee_context *tee;
+ u8 uuid[TEE_IOCTL_UUID_LEN];
+ u32 ctl;
+ struct tee_shm *ctl_shm;
+ u8 *ctl_va;
+ struct mutex ctl_lock; /* serialises the control calls */
+};
+
+/* A context: a TA session of its own, fixed to one operation */
+struct kc_optee_ctx {
+ u32 session;
+ u8 alg;
+ u32 op;
+ struct tee_shm *shm;
+ u8 *va;
+};
+
+static struct kc_optee kc_optee = {
+ .ctl_lock = __MUTEX_INITIALIZER(kc_optee.ctl_lock),
+};
+
+static void kc_memref(struct tee_param *p, u64 attr, struct tee_shm *shm,
+ size_t offs, size_t size)
+{
+ p->attr = attr;
+ p->u.memref.shm = shm;
+ p->u.memref.shm_offs = offs;
+ p->u.memref.size = size;
+}
+
+/*
+ * The TA's answers that reach user space as themselves; any other is
+ * -EIO, as the core narrows a backend's errors anyway.
+ */
+static int kc_errno(u32 res)
+{
+ switch (res) {
+ case KC_TEE_SUCCESS:
+ return 0;
+ case KC_TEE_ERROR_MAC_INVALID:
+ return -EBADMSG;
+ case KC_TEE_ERROR_OUT_OF_MEMORY:
+ return -ENOMEM;
+ default:
+ return -EIO;
+ }
+}
+
+static int kc_invoke(u32 session, u32 func, struct tee_param *p)
+{
+ struct tee_ioctl_invoke_arg arg = {
+ .func = func,
+ .session = session,
+ .num_params = 4,
+ };
+ int ret;
+
+ ret = tee_client_invoke_func(kc_optee.tee, &arg, p);
+ if (ret)
+ return ret == -ENOMEM ? ret : -EIO;
+ return kc_errno(arg.ret);
+}
+
+static int kc_open_session(u32 *session)
+{
+ struct tee_ioctl_open_session_arg arg = {
+ .clnt_login = TEE_IOCTL_LOGIN_REE_KERNEL,
+ };
+ int ret;
+
+ memcpy(arg.uuid, kc_optee.uuid, sizeof(arg.uuid));
+ ret = tee_client_open_session(kc_optee.tee, &arg, NULL);
+ if (ret)
+ return ret == -ENOMEM ? ret : -EIO;
+ ret = kc_errno(arg.ret);
+ if (!ret)
+ *session = arg.session;
+ return ret;
+}
+
+static int kc_seal(u32 func, const u8 *hdr, u32 hdr_len, const u8 *key,
+ size_t keylen, struct keycrypt_blob *out)
+{
+ struct tee_shm *shm = kc_optee.ctl_shm;
+ struct tee_param p[4] = {};
+ size_t len;
+ int n = 0;
+ int ret;
+
+ if (hdr_len > KEYCRYPT_HEADER_MAX || keylen > KC_KEY_MAX)
+ return -EINVAL;
+ mutex_lock(&kc_optee.ctl_lock);
+ memcpy(kc_optee.ctl_va + KC_SHM_HDR, hdr, hdr_len);
+ kc_memref(&p[n++], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT, shm,
+ KC_SHM_HDR, hdr_len);
+ if (key) {
+ memcpy(kc_optee.ctl_va + KC_SHM_KEY, key, keylen);
+ kc_memref(&p[n++], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT, shm,
+ KC_SHM_KEY, keylen);
+ }
+ kc_memref(&p[n], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT, shm,
+ KC_SHM_BLOB, KC_TA_DATA_MAX);
+ ret = kc_invoke(kc_optee.ctl, func, p);
+ len = p[n].u.memref.size;
+ if (!ret && (!len || len > KC_TA_DATA_MAX))
+ ret = -EIO;
+ if (!ret) {
+ out->data = kmemdup(kc_optee.ctl_va + KC_SHM_BLOB, len,
+ GFP_KERNEL);
+ ret = out->data ? 0 : -ENOMEM;
+ out->len = len;
+ }
+ memzero_explicit(kc_optee.ctl_va, KC_CTL_SIZE);
+ mutex_unlock(&kc_optee.ctl_lock);
+ return ret;
+}
+
+static int kc_optee_generate(struct keycrypt_backend *b,
+ const struct keycrypt_meta *m, const u8 *hdr,
+ u32 hdr_len, const char *opts,
+ struct keycrypt_blob *out)
+{
+ return kc_seal(KC_TA_CMD_GENERATE, hdr, hdr_len, NULL, 0, out);
+}
+
+static int kc_optee_import(struct keycrypt_backend *b,
+ const struct keycrypt_meta *m, const u8 *hdr,
+ u32 hdr_len, const char *opts, const u8 *key,
+ size_t keylen, struct keycrypt_blob *out)
+{
+ return kc_seal(KC_TA_CMD_IMPORT, hdr, hdr_len, key, keylen, out);
+}
+
+static int kc_optee_load(struct keycrypt_backend *b, struct keycrypt_key *k,
+ const char *opts)
+{
+ struct tee_shm *shm = kc_optee.ctl_shm;
+ struct tee_param p[4] = {};
+ int ret;
+
+ /* Not the TA's: it would refuse it as not authenticating */
+ if (k->hdr_len > KEYCRYPT_HEADER_MAX || k->data_len > KC_TA_DATA_MAX)
+ return -EBADMSG;
+ mutex_lock(&kc_optee.ctl_lock);
+ memcpy(kc_optee.ctl_va + KC_SHM_HDR, k->hdr, k->hdr_len);
+ memcpy(kc_optee.ctl_va + KC_SHM_BLOB, k->data, k->data_len);
+ kc_memref(&p[0], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT, shm,
+ KC_SHM_HDR, k->hdr_len);
+ kc_memref(&p[1], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT, shm,
+ KC_SHM_BLOB, k->data_len);
+ ret = kc_invoke(kc_optee.ctl, KC_TA_CMD_CHECK, p);
+ memzero_explicit(kc_optee.ctl_va, KC_CTL_SIZE);
+ mutex_unlock(&kc_optee.ctl_lock);
+ return ret;
+}
+
+static void kc_ctx_release(struct kc_optee_ctx *c)
+{
+ memzero_explicit(c->va, KC_CTX_SIZE);
+ tee_shm_free(c->shm);
+ kfree(c);
+}
+
+static int kc_optee_ctx_open(struct keycrypt_backend *b,
+ struct keycrypt_key *k, u32 op, u8 *iv,
+ void **ctx)
+{
+ struct tee_param p[4] = {};
+ struct kc_optee_ctx *c;
+ int ret;
+
+ if (k->hdr_len > KEYCRYPT_HEADER_MAX || k->data_len > KC_TA_DATA_MAX)
+ return -EIO;
+ c = kzalloc_obj(*c, GFP_KERNEL_ACCOUNT);
+ if (!c)
+ return -ENOMEM;
+ /* The session first: a full TA table refuses before any buffer */
+ ret = kc_open_session(&c->session);
+ if (ret)
+ goto free_ctx;
+ c->shm = tee_shm_alloc_kernel_buf(kc_optee.tee, KC_CTX_SIZE);
+ if (IS_ERR(c->shm)) {
+ ret = -ENOMEM;
+ goto close_session;
+ }
+ c->va = tee_shm_get_va(c->shm, 0);
+ if (IS_ERR(c->va)) {
+ ret = -EIO;
+ goto free_shm;
+ }
+
+ memcpy(c->va + KC_SHM_HDR, k->hdr, k->hdr_len);
+ memcpy(c->va + KC_SHM_BLOB, k->data, k->data_len);
+ memcpy(c->va + KC_SHM_IV, iv, KC_IV_LEN);
+ kc_memref(&p[0], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT, c->shm,
+ KC_SHM_HDR, k->hdr_len);
+ kc_memref(&p[1], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT, c->shm,
+ KC_SHM_BLOB, k->data_len);
+ p[2].attr = TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT;
+ p[2].u.value.a = op;
+ kc_memref(&p[3], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT, c->shm,
+ KC_SHM_IV, KC_IV_LEN);
+ ret = kc_invoke(c->session, KC_TA_CMD_CTX_OPEN, p);
+ if (!ret && p[3].u.memref.size != KC_IV_LEN)
+ ret = -EIO;
+ if (ret)
+ goto wipe;
+ memzero_explicit(c->va, KC_CTX_SIZE);
+ c->alg = k->meta.alg;
+ c->op = op;
+ *ctx = c;
+ return 0;
+
+wipe:
+ memzero_explicit(c->va, KC_CTX_SIZE);
+free_shm:
+ tee_shm_free(c->shm);
+close_session:
+ tee_client_close_session(kc_optee.tee, c->session);
+free_ctx:
+ kfree(c);
+ return ret;
+}
+
+static int kc_optee_update(struct keycrypt_backend *b, void *ctx,
+ const u8 *in, u8 *out, size_t len)
+{
+ struct kc_optee_ctx *c = ctx;
+ bool mac = c->alg == KEYCRYPT_ALG_HMAC_SHA256;
+ struct tee_param p[4] = {};
+ int ret;
+
+ if (len > KEYCRYPT_UPDATE_MAX)
+ return -EIO;
+ memcpy(c->va + KC_SHM_DATA, in, len);
+ kc_memref(&p[0], mac ? TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT :
+ TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT, c->shm,
+ KC_SHM_DATA, len);
+ ret = kc_invoke(c->session, KC_TA_CMD_UPDATE, p);
+ if (!ret && !mac && p[0].u.memref.size != len)
+ ret = -EIO;
+ if (!ret && !mac)
+ memcpy(out, c->va + KC_SHM_DATA, len);
+ memzero_explicit(c->va + KC_SHM_DATA, len);
+ return ret;
+}
+
+static int kc_optee_final(struct keycrypt_backend *b, void *ctx, u8 *out,
+ size_t out_size, size_t *len)
+{
+ struct kc_optee_ctx *c = ctx;
+ struct tee_param p[4] = {};
+ bool mac = c->op == KEYCRYPT_OP_MAC;
+ int ret;
+
+ if (mac) {
+ if (out_size < KEYCRYPT_MAC_LEN)
+ return -EIO;
+ kc_memref(&p[0], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_OUTPUT,
+ c->shm, KC_SHM_TAG, KEYCRYPT_MAC_LEN);
+ }
+ ret = kc_invoke(c->session, KC_TA_CMD_FINAL, p);
+ if (!ret && mac && p[0].u.memref.size != KEYCRYPT_MAC_LEN)
+ ret = -EIO;
+ if (!ret && mac)
+ memcpy(out, c->va + KC_SHM_TAG, KEYCRYPT_MAC_LEN);
+ *len = !ret && mac ? KEYCRYPT_MAC_LEN : 0;
+ memzero_explicit(c->va + KC_SHM_TAG, KEYCRYPT_MAC_LEN);
+ return ret;
+}
+
+static int kc_optee_verify(struct keycrypt_backend *b, void *ctx,
+ const u8 *expected)
+{
+ struct kc_optee_ctx *c = ctx;
+ struct tee_param p[4] = {};
+ int ret;
+
+ memcpy(c->va + KC_SHM_TAG, expected, KEYCRYPT_MAC_LEN);
+ kc_memref(&p[0], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT, c->shm,
+ KC_SHM_TAG, KEYCRYPT_MAC_LEN);
+ ret = kc_invoke(c->session, KC_TA_CMD_VERIFY, p);
+ memzero_explicit(c->va + KC_SHM_TAG, KEYCRYPT_MAC_LEN);
+ return ret;
+}
+
+static void kc_optee_ctx_free(struct keycrypt_backend *b, void *ctx)
+{
+ struct kc_optee_ctx *c = ctx;
+
+ tee_client_close_session(kc_optee.tee, c->session);
+ kc_ctx_release(c);
+}
+
+static struct keycrypt_backend keycrypt_optee = {
+ .name = "optee",
+ .tier = KEYCRYPT_TIER_TEE,
+ .algs = KEYCRYPT_ALGS_ALL,
+ .owner = THIS_MODULE,
+ .generate = kc_optee_generate,
+ .import = kc_optee_import,
+ .load = kc_optee_load,
+ .ctx_open = kc_optee_ctx_open,
+ .update = kc_optee_update,
+ .final = kc_optee_final,
+ .verify = kc_optee_verify,
+ .ctx_free = kc_optee_ctx_free,
+};
+
+static int kc_optee_match(struct tee_ioctl_version_data *ver,
+ const void *data)
+{
+ return ver->impl_id == TEE_IMPL_ID_OPTEE;
+}
+
+static int kc_optee_probe(struct tee_client_device *tdev)
+{
+ struct tee_context *tee;
+ int ret;
+
+ /* One backend, so one TA device: a second one is refused untouched */
+ if (kc_optee.tee)
+ return -EBUSY;
+ tee = tee_client_open_context(NULL, kc_optee_match, NULL, NULL);
+ if (IS_ERR(tee))
+ return -ENODEV;
+ kc_optee.tee = tee;
+ memcpy(kc_optee.uuid, tdev->id.uuid.b, TEE_IOCTL_UUID_LEN);
+ kc_optee.ctl_shm = tee_shm_alloc_kernel_buf(kc_optee.tee, KC_CTL_SIZE);
+ if (IS_ERR(kc_optee.ctl_shm)) {
+ ret = PTR_ERR(kc_optee.ctl_shm);
+ goto close_tee;
+ }
+ kc_optee.ctl_va = tee_shm_get_va(kc_optee.ctl_shm, 0);
+ if (IS_ERR(kc_optee.ctl_va)) {
+ ret = PTR_ERR(kc_optee.ctl_va);
+ goto free_shm;
+ }
+ ret = kc_open_session(&kc_optee.ctl);
+ if (ret) {
+ dev_err(&tdev->dev, "cannot open a session to the keycrypt TA: %d\n",
+ ret);
+ goto free_shm;
+ }
+ ret = keycrypt_register_backend(&keycrypt_optee);
+ if (ret)
+ goto close_ctl;
+ return 0;
+
+close_ctl:
+ tee_client_close_session(kc_optee.tee, kc_optee.ctl);
+free_shm:
+ tee_shm_free(kc_optee.ctl_shm);
+close_tee:
+ tee_client_close_context(kc_optee.tee);
+ kc_optee.tee = NULL;
+ return ret;
+}
+
+static void kc_optee_remove(struct tee_client_device *tdev)
+{
+ keycrypt_unregister_backend(&keycrypt_optee);
+ tee_client_close_session(kc_optee.tee, kc_optee.ctl);
+ tee_shm_free(kc_optee.ctl_shm);
+ tee_client_close_context(kc_optee.tee);
+ kc_optee.tee = NULL;
+}
+
+static const struct tee_client_device_id kc_optee_id_table[] = {
+ { UUID_INIT(0x65a0d9f0, 0xf057, 0x414c,
+ 0x9d, 0x5a, 0x9a, 0xac, 0x7c, 0x8b, 0xa4, 0x61) },
+ {}
+};
+MODULE_DEVICE_TABLE(tee, kc_optee_id_table);
+
+static struct tee_client_driver kc_optee_driver = {
+ .probe = kc_optee_probe,
+ .remove = kc_optee_remove,
+ /* Sessions left open would outlive a kexec in the secure world */
+ .shutdown = kc_optee_remove,
+ .id_table = kc_optee_id_table,
+ .driver = {
+ .name = "keycrypt-optee",
+ },
+};
+module_tee_client_driver(kc_optee_driver);
+
+MODULE_DESCRIPTION("keycrypt OP-TEE backend");
+MODULE_LICENSE("GPL");
diff --git a/security/keys/keycrypt/optee.h b/security/keys/keycrypt/optee.h
new file mode 100644
index 000000000000..391eba15b699
--- /dev/null
+++ b/security/keys/keycrypt/optee.h
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * keycrypt - the OP-TEE backend's protocol with the keycrypt TA
+ *
+ * The TA's interface is ta/keycrypt/include/keycrypt_ta.h in OP-TEE: the
+ * command numbers and limits below are its, and neither side changes one
+ * alone. The operation, and the algorithm, purpose and tier in a key's
+ * header, reach the TA as keycrypt's own values, which that file repeats.
+ * The result codes are GlobalPlatform's.
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
+ */
+
+#ifndef _SECURITY_KEYS_KEYCRYPT_OPTEE_H
+#define _SECURITY_KEYS_KEYCRYPT_OPTEE_H
+
+#include <linux/types.h>
+
+#define KC_TA_CMD_GENERATE 0
+#define KC_TA_CMD_IMPORT 1
+#define KC_TA_CMD_CHECK 2
+#define KC_TA_CMD_CTX_OPEN 3
+#define KC_TA_CMD_UPDATE 4
+#define KC_TA_CMD_FINAL 5
+#define KC_TA_CMD_VERIFY 6
+
+#define KC_TA_DATA_MAX 93 /* the TA's data: 1 + 12 + 64 + 16 */
+#define KC_TA_BUF_MAX 65536 /* data of one UPDATE */
+/* The TA's limit, the control session included; not enforced here */
+#define KC_TA_SESSIONS_MAX 32
+
+/* GlobalPlatform TEE result codes */
+#define KC_TEE_SUCCESS 0x00000000
+#define KC_TEE_ERROR_OUT_OF_MEMORY 0xffff000c
+#define KC_TEE_ERROR_MAC_INVALID 0xffff3071
+
+#endif /* _SECURITY_KEYS_KEYCRYPT_OPTEE_H */
--
2.43.0
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [RFC PATCH 4/9] docs: keycrypt: document keycrypt keys
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
` (2 preceding siblings ...)
2026-11-18 14:04 ` [RFC PATCH 3/9] KEYS: keycrypt: Add the OP-TEE backend Rodolfo Giometti
@ 2026-11-18 14:07 ` Rodolfo Giometti
2026-11-18 14:08 ` [RFC PATCH 5/9] MAINTAINERS: add KEYS-KEYCRYPT Rodolfo Giometti
` (6 subsequent siblings)
10 siblings, 0 replies; 14+ messages in thread
From: Rodolfo Giometti @ 2026-11-18 14:07 UTC (permalink / raw)
To: David Howells, Jarkko Sakkinen, keyrings
Cc: Herbert Xu, David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, Rodolfo Giometti
Document the keycrypt key type: its model and tiers, what the core
enforces and what only a tee or hsm backend can guarantee against a
compromised kernel, the add_key() syntax and the blob, the kernel tier,
the OP-TEE backend, the operation context and its ioctls, CBC, MAC and
VERIFY, revocation and permissions, the system policies, why AF_ALG
and KEYCTL_PKEY_* do not cover this, and the errors.
Signed-off-by: Rodolfo Giometti <giometti@enneenne.com>
---
Documentation/security/keys/index.rst | 1 +
Documentation/security/keys/keycrypt.rst | 838 +++++++++++++++++++++++
2 files changed, 839 insertions(+)
create mode 100644 Documentation/security/keys/keycrypt.rst
diff --git a/Documentation/security/keys/index.rst b/Documentation/security/keys/index.rst
index 647d58f2588e..ff44babc7a8f 100644
--- a/Documentation/security/keys/index.rst
+++ b/Documentation/security/keys/index.rst
@@ -7,5 +7,6 @@ Kernel Keys
core
ecryptfs
+ keycrypt
request-key
trusted-encrypted
diff --git a/Documentation/security/keys/keycrypt.rst b/Documentation/security/keys/keycrypt.rst
new file mode 100644
index 000000000000..17af3b041000
--- /dev/null
+++ b/Documentation/security/keys/keycrypt.rst
@@ -0,0 +1,838 @@
+.. SPDX-License-Identifier: GPL-2.0-only
+
+=============
+Keycrypt Keys
+=============
+
+A "keycrypt" key is a symmetric key that user space uses for cryptography
+but never reads. Its algorithm, purpose and protection tier are fixed when
+the key is created; the key itself lives in a *backend*, and user space
+keeps only a blob that the backend sealed and that authenticates that
+metadata.
+
+Tiers and backends
+==================
+
+Two kinds of name appear in this document. A *tier* names a guarantee
+about a key; a *backend* names a mechanism that holds keys; it declares
+one tier when it registers, and gives at least that tier's guarantee.
+No name is both. User space asks for a tier (`Usage`_), and may
+name the backend too; otherwise the kernel chooses the backend that
+provides it. A key stays bound to the backend that sealed it, which
+``/proc/keys`` and ``KEYCRYPT_IOC_INFO`` report.
+
+The tiers, lowest first:
+
+========== =========================================================
+``kernel`` the key is in clear in kernel memory while loaded; the
+ kernel enforces its use
+``tee`` a trusted execution environment keeps the key and checks
+ every use against the purpose it bound (an OP-TEE TA)
+``hsm`` as ``tee``, in dedicated hardware apart from the CPU running
+ the kernel (a secure element, a security core of its own
+ such as NXP's EdgeLock Enclave, a crypto engine with its own
+ policy)
+========== =========================================================
+
+Each tier holds the guarantees of those before it.
+
+The backends of this document: ``sw``, of tier ``kernel``, where the
+kernel's own software uses the key (`The sw backend`_); and ``optee``,
+of tier ``tee`` (`The OP-TEE backend`_).
+
+Every backend, whatever its tier, must seal with a secret that is secret
+and unique to the device: the trusted key the sw backend derives from
+or OP-TEE's hardware unique key. Were that secret known, the blob, which
+user space reads, would be the key itself; were it shared by several
+devices, a blob copied from one would load on another, and its key would
+be used there. Every tier presumes it, and keycrypt cannot check it, nor
+that the hardware is configured so that the secret is secret (an OP-TEE
+whose hardware unique key is provisioned, not OP-TEE's test value):
+whoever builds in or loads a backend for a device declares
+that the device meets it, as a backend declares its tier. For the
+sw backend the secret is the trusted master each key names with
+``master=``, so there the requirement falls on whoever creates that
+master (`The sw backend`_).
+
+A backend of tier ``tee`` or ``hsm`` also declares that it meets
+`Backend requirements`_.
+
+A backend registers with ``keycrypt_register_backend()``
+(``include/keys/keycrypt.h``) under a name that is stored in every blob it
+seals. Its data must authenticate the blob's header, which carries the
+metadata: a blob whose metadata was changed does not load. Each key pins
+the backend's module; a backend that goes away
+(``keycrypt_unregister_backend()``) leaves its keys in place, unusable.
+
+Backend requirements
+====================
+
+The core enforces, from the key's own metadata, the operation against
+the key's purpose and the key's tier against the caller's
+``accepted_min_tier`` and the system tier at every
+``KEYCTL_CRYPT_OPEN`` (`Using a key`_); and, at
+``keycrypt_register_backend()``, that a backend declares a valid tier,
+offers ``generate`` and ``load``, the four context callbacks all or
+none and, for a ``tee`` or ``hsm`` backend with context operations,
+``verify`` for hmac-sha256. None of
+that defends against a *compromised kernel*: the core is kernel code
+too, and a kernel that lies to itself can skip or fake any check it
+runs itself.
+
+A sentence in this document that claims a property of a key's *use*
+against a compromised kernel holds only for a backend of tier ``tee``
+or ``hsm``: declaring one of those tiers is declaring that its secure
+side -- the TEE or the hardware, not its kernel-side callbacks alone --
+itself does what the core has no way to check:
+
+- binds the key's purpose into its own secure-world state when the key
+ is loaded, or re-authenticates the blob's header there at every
+ ``ctx_open``, instead of trusting the core's copy of the metadata;
+- fixes the operation for a context at ``ctx_open`` and holds to it,
+ refusing ``final`` on a context it fixed for VERIFY and ``verify``
+ on any other;
+- fixes the length of a MAC or VERIFY tag.
+
+A backend declares its own tier at ``keycrypt_register_backend()``; the
+core stores and compares it wherever a tier is checked, but never
+confirms that the backend is actually a TEE or hardware rather than
+ordinary kernel code claiming to be one. The ``kernel`` tier meets
+none of the above: its key material is in clear in kernel memory (`The
+sw backend`_), so there every property above is only as strong as the
+kernel itself.
+
+Metadata
+========
+
+========= ======================================================
+algorithm ``aes256-cbc`` or ``hmac-sha256``
+purpose ``encrypt``, ``decrypt`` (aes256-cbc);
+ ``mac``, ``verify``, or both (hmac-sha256)
+tier the backend's, when the key was sealed
+backend its name
+origin ``generated`` (created by the backend: inside it for
+ ``tee`` and ``hsm``) or ``imported``
+========= ======================================================
+
+These are the human-readable forms, as ``keyctl`` and ``/proc/keys``
+show them; ``KEYCRYPT_IOC_INFO`` (`Using a key`_) reports algorithm,
+purpose, tier and origin instead as the numeric ``KEYCRYPT_ALG_*``,
+``KEYCRYPT_PURPOSE_*``, ``KEYCRYPT_TIER_*`` and ``KEYCRYPT_ORIGIN_*``
+values of ``<linux/keycrypt.h>``.
+
+A key cannot be changed: ``keyctl update`` fails (``EACCES`` with the
+default permissions, which give no write permission; ``EOPNOTSUPP``
+otherwise). Adding a key with the same description to the same keyring
+replaces the link with a new key, as for every key type. Nor is a key
+ever constructed on demand: ``request_key()`` for a keycrypt key that
+does not exist fails with ``ENOKEY`` without calling a request-key
+helper, which would create it with its own credentials.
+
+Blob format
+===========
+
+The blob, which ``keyctl read`` gives and ``load`` takes in hex, is a
+header the core writes and the backend authenticates, the length of the
+backend's data, and that data, opaque to the core:
+
+============ ======== ================================================
+field bytes content
+============ ======== ================================================
+magic 3 ``KCR``
+version 1 1
+flags 1 0
+algorithm 1 ``KEYCRYPT_ALG_*``
+purpose 2 ``KEYCRYPT_PURPOSE_*`` mask, little endian
+tier 1 ``KEYCRYPT_TIER_*``
+origin 1 ``KEYCRYPT_ORIGIN_*``
+name length 1 1 to 16
+name variable the backend's name, ``[a-z0-9_-]``
+data length 4 1 to 4096, little endian
+data variable the backend's own
+============ ======== ================================================
+
+``load`` refuses another version, or flags other than 0, with
+``EOPNOTSUPP``, and any other malformed field with ``EBADMSG``; hex
+that does not decode, or a blob longer than the largest possible, gives
+``EINVAL``.
+
+Usage
+=====
+
+::
+
+ keyctl add keycrypt name "new <alg> <purpose>[,<purpose>...] [<option>...]" ring
+ keyctl add keycrypt name "import <alg> <purpose>[,<purpose>...] [<option>...] <hex key>" ring
+ keyctl add keycrypt name "load <hex blob> [<option>...]" ring
+
+Options of ``new`` and ``import``, ``tier=`` and ``min-tier=`` at most
+one of the two:
+
+``tier=<tier>``
+ use a backend of exactly this tier
+``min-tier=<tier>``
+ use the highest tier backend of at least this tier
+``backend=<name>``
+ use the backend registered under this name, which must also meet
+ ``tier=`` or ``min-tier=`` when given
+
+Options of ``load``:
+
+``accepted-min-tier=<tier>``
+ fail with ``EPERM`` if the key's tier is lower
+``purpose=<purpose>[,<purpose>...]``
+ fail with ``EKEYREJECTED`` unless the key has exactly this purpose
+
+Any other ``<option>=<value>`` is passed to the backend; the core refuses
+an option the backend does not declare and an option given twice. The
+one option a backend of this document takes from user space is
+``master=``, the sw backend's: it needs a master to seal its keys, while from
+``tee`` up a backend's own mechanisms protect the key. A command for
+the kernel tier therefore reads ``tier=kernel master=<name>``; the kernel
+tier chosen without ``master=``, or ``master=`` given to a backend of
+another tier, is refused with ``EINVAL``.
+
+With neither a tier option nor ``backend=``, the highest tier backend
+registered at that moment that supports the algorithm (and, for
+``import``, importing) is used, the kernel tier included when no backend
+of a higher tier is; with a tier option, a backend that answers it, or
+``ENODEV`` when none registered does. ``backend=`` leaves one candidate,
+the backend of that name, used if it meets the tier option and has the
+algorithm (and, for ``import``, importing), ``ENODEV`` otherwise.
+Between backends of the same tier, with no ``backend=``, the one with
+the smaller name is used. ``tier=`` pins one tier;
+``min-tier=`` is the form for "this tier or better". Since the choice
+depends on which backends are registered at that moment, ``tier=`` or
+``min-tier=`` is what guarantees a tier: there is no fallback once a
+backend is chosen, but the choice itself can only be as good as what is
+registered. A system that must not use a tier at all
+raises the system tier above it (`System policies`_): keys below it can
+still be created and loaded, but not used.
+
+``tier=`` and ``min-tier=`` state the protection a key needs;
+``backend=`` names the mechanism that provides it, for a system with
+more than one backend where a program must choose which one holds a key
+and not only how well: two backends of one tier, or a difference the
+tier does not express, such as the cost of each call or what a sealed
+key is bound to. It adds to the tier options and never replaces them:
+``backend=optee min-tier=hsm`` fails with ``ENODEV`` rather than make a
+``tee`` key, and so does a name no backend registered, or a backend
+without the algorithm (or, for ``import``, importing). Alone, it takes
+that backend at the tier it declares, so a program that needs a tier
+states it too. A backend's name is not a tier's: ``optee`` holds keys of
+the tier ``tee``, and ``backend=tee`` names no backend; ``/proc/keys``
+and ``KEYCRYPT_IOC_INFO`` give the backend of a key.
+
+A key stays bound to the backend that sealed it, whatever is registered
+later: ``load`` finds that backend by the name in the blob's header,
+and fails with ``ENODEV`` while it is not registered, never trying
+another backend of the same tier, which could not open the blob
+anyway. ``load`` therefore takes no ``backend=``. keycrypt has no
+operation that moves a sealed key to another backend; the same material
+imported again elsewhere is a new key.
+
+``import`` needs CAP_SYS_ADMIN and CONFIG_KEYCRYPT_IMPORT (off by
+default); the key is 32 bytes for aes256-cbc, 1 to 64 bytes for
+hmac-sha256. The core's own copies of it are erased once the
+backend has sealed it. Do not put a key in clear on a command line;
+give the payload on standard input::
+
+ keyctl padd keycrypt name ring < payload
+
+``keyctl read`` returns the blob in hex, which ``load`` takes back; the
+metadata appear in ``/proc/keys``::
+
+ name: aes256-cbc decrypt tee optee imported
+
+The blob is a bearer credential: whoever can read it, from the key or
+from a file, can load a copy of the key into a keyring of their own, and
+any local user can create a blob of their own with the same metadata.
+Protect blob files as secrets, and load them with
+``accepted-min-tier=`` and ``purpose=`` so that a substituted blob of a
+lower tier or of another purpose is refused; a program can give
+``accepted_min_tier`` at open too (`Using a key`_), which refuses a key
+of a lower tier however it was loaded. Without either, ``load`` takes a
+blob of any tier its backend accepts, the kernel tier included, and at
+the default system tier such a key can be used.
+
+``accepted-min-tier=`` and ``purpose=`` do not stop a substitution by a
+blob of the same tier and purpose that its maker kept a copy of: with a
+``mac`` key, the maker's tags then verify. The ``load`` command line, with its
+options, must therefore come from integrity-protected configuration (a
+signed initramfs, a verified root filesystem), like the blobs it names.
+
+The sw backend
+==============
+
+With CONFIG_KEYCRYPT_SW the ``sw`` backend is available,
+built in or as a loadable module: it is a module, ``keycrypt_sw``,
+whenever trusted keys themselves are (CONFIG_KEYCRYPT_SW=m when
+CONFIG_TRUSTED_KEYS=m); load it, e.g. ``modprobe keycrypt_sw``,
+once the trust source is available. Its keys are sealed with AES-256-GCM
+under a key derived from a ``trusted`` key (see trusted-encrypted.rst),
+named at creation::
+
+ keyctl add trusted kmk "new 32 ..." ring
+ keyctl add keycrypt name "new aes256-cbc decrypt tier=kernel master=kmk" ring
+ keyctl add keycrypt name "load <hex blob>" ring
+
+The backend data is the version, the master description's length and the
+description, a 32-byte random salt, a 12-byte nonce, the ciphertext and a
+16-byte tag. The GCM key is derived afresh for every blob as
+HMAC-SHA256 keyed with "keycrypt kernel-tier v1" || salt over the
+master's material, which is never itself the key of a primitive: other
+interfaces, AF_ALG among them, key a primitive with a trusted key given
+by serial, and would then compute the blob's key. The associated
+data is the blob's header followed by every byte that precedes the nonce
+(version, length, description, salt), so a blob whose master description
+or salt was changed does not load.
+
+``load`` looks the master up again in the caller's keyrings by
+description, without calling user space, exactly as ``request_key()``
+does: the description is a name, not an identity, so a trusted key of the
+same description earlier in the caller's search path is used instead of
+the one that sealed the blob. Search permission on the master is all
+that is needed, both to seal a new key under it and, given its blob, to
+load one back: whoever can search a master can seal and load keys under
+it. ``load`` waits, uninterruptibly, while the named master is still
+being created by another process.
+
+Whoever knows the master's material can open every blob sealed under it
+and forge blobs of any metadata. Use as masters only trusted keys
+generated by the kernel or the trust source ("new"), never ones made
+from material someone supplied, such as a CAAM ``pk`` key.
+
+A TPM-backed master is kept as a blob only the TPM can unseal, and
+whoever gets it unsealed can open every key sealed under it. Create it
+with a password (``keyauth=``) or a PCR policy, so that the blob file
+and access to the TPM are not enough.
+
+A loaded key of this tier is in clear in kernel memory until the key is
+revoked or destroyed: the kernel log says so when the backend registers
+and again when the first key of this tier is loaded. Revoking a
+keycrypt key of this tier erases its clear key and the state of every
+context already open on it, at once (`Revocation`_); invalidation and
+expiry do neither: the clear key, and the state of any context already
+open, stay in memory until the key is actually destroyed or that
+context's fd is closed. Looking the master up fails with ``ENOKEY`` when it
+is not found, including when the trusted key type is not registered at
+all, or when the master is revoked or expired, and with ``EACCES`` only
+when the master itself may not be searched. The backend is chosen by
+``tier=kernel`` or ``backend=sw``, or with neither a tier option
+nor ``backend=`` when no backend of a higher tier is registered; a
+system that must not use it raises the system tier above
+it (`System policies`_), or leaves CONFIG_KEYCRYPT_SW off.
+Raising the system tier stops the use of its keys, not their presence: a
+key of this tier loaded below it is in clear in kernel memory all the
+same, as its trusted master is while loaded. It accepts one option,
+``master=``, at creation, and none at ``load``.
+
+Its AES runs through ``lib/crypto``, which uses the CPU's AES
+instructions when it has them and a much slower software implementation
+otherwise: on hardware without them, prefer another backend where one is
+available.
+
+The OP-TEE backend
+==================
+
+With CONFIG_KEYCRYPT_OPTEE the ``optee`` backend, of tier ``tee``, is
+available, built in or as the module ``keycrypt_optee``. Its keys are
+sealed and used by the keycrypt Trusted Application of OP-TEE
+(``ta/keycrypt`` in ``optee_os``), built into OP-TEE as an early TA
+(``CFG_IN_TREE_EARLY_TAS``): OP-TEE then lists it on the TEE bus, the
+driver binds to it (its module loaded for it, if modular), and the
+backend registers::
+
+ keyctl add keycrypt name "new aes256-cbc encrypt,decrypt tier=tee" ring
+
+Built as an ordinary TA loaded from the file system instead, it is not
+listed there and the backend never registers. Until the backend has
+registered, a ``load`` of one of its blobs fails with ``ENODEV``, and so
+do ``backend=optee``, and ``tier=tee`` where no other backend of that
+tier is registered.
+
+The TA accepts only kernel clients (``TEE_LOGIN_REE_KERNEL``): a process
+that opens the TEE device cannot use it to get around keycrypt's
+permissions and policies. OP-TEE's ``xtest`` cannot exercise it for the
+same reason.
+
+The backend data is a version byte, a 12-byte nonce, the key encrypted
+with AES-256-GCM and a 16-byte tag, under a key the TA derives from
+OP-TEE's hardware unique key and its own UUID; the associated data is
+the blob's header followed by the version byte. A blob loads only on a
+device with the same hardware unique key (on a provisioned device, only
+the one that sealed it), and only into this TA. Its keys are only as
+secret as the hardware unique key: on QEMU, and on a board whose key is
+not provisioned, OP-TEE uses a fixed test value and anyone can unseal
+the blobs made there, so such a setup shows that the backend works, not
+that its keys are protected. The UUID is exclusive only on a firmware
+that embeds the TA: a TA with the same UUID, signed with OP-TEE's
+default (public) key and loaded from the file system by another firmware
+on the same device, would open every blob. A product therefore signs
+its TAs with a key of its own, uses OP-TEE's rollback protection, and
+ships no keycrypt ``.ta`` file.
+
+The TA meets `Backend requirements`_: at every ``KEYCTL_CRYPT_OPEN`` it
+authenticates the blob's header again and checks the operation against
+the purpose it reads there; a context is a TA session fixed to one
+operation, refusing ``final`` on a VERIFY context and ``verify`` on any
+other; tags are 32 bytes. An aes256-cbc IV is used as given: to
+encrypt, the core's random one or, with ``KEYCRYPT_OPEN_CALLER_IV``, the
+caller's; to decrypt, the caller's.
+
+Every context holds a TA session and 65,584 bytes of TEE shared memory,
+rounded up to whole pages and physically contiguous (68 KiB with 4 KiB
+pages), until the context ends (``KEYCRYPT_IOC_FINAL``, or a failure),
+its key is revoked, or its fd is closed, whichever comes first. The TA
+refuses a session once 32 are open (``KC_TA_SESSIONS_MAX``), the
+backend's own control session and any other kernel client's session to
+this TA among them: once 31 contexts are open, system wide,
+``KEYCTL_CRYPT_OPEN`` fails with ``ENOMEM``, and any user with Search
+permission on a key of this backend can hold them all. With a static
+shared-memory pool instead of OP-TEE's dynamic shared memory, fewer
+contexts fit, and they take the pool other TEE clients use. On QEMU,
+whose OP-TEE has a 128 KiB core heap, all 31 fit; with a smaller heap,
+or other TAs busy, the TA can run out of memory first and panic. A
+panic ends every context open at that moment (``EIO``); new contexts
+on keys already loaded work, but ``new``, ``import`` and ``load`` give
+``EIO`` until the driver is unbound and bound again::
+
+ cd /sys/bus/tee/drivers/keycrypt-optee
+ echo optee-ta-65a0d9f0-f057-414c-9d5a-9aac7c8ba461 > unbind
+ echo optee-ta-65a0d9f0-f057-414c-9d5a-9aac7c8ba461 > bind
+
+Unbinding unregisters the backend: every key of this backend already in
+a keyring, and every context open on one, gives ``ENODEV`` from then on,
+also after the driver is bound again; once it is, ``load`` each key
+again from its blob.
+
+Using a key
+===========
+
+A key is used through an operation context, a file descriptor opened by
+``keyctl(KEYCTL_CRYPT_OPEN, key, ¶ms, sizeof(params), 0)``
+(``<linux/keycrypt.h>``)::
+
+ struct keycrypt_open_params {
+ __u32 op; /* KEYCRYPT_OP_ENCRYPT, _DECRYPT, _MAC,
+ * _VERIFY
+ */
+ __u32 accepted_min_tier; /* refuse a key of a lower
+ * tier; 0: no requirement
+ */
+ __u32 flags; /* KEYCRYPT_OPEN_CALLER_IV, or 0 */
+ __u32 __reserved; /* must be zero */
+ __u8 iv[16]; /* aes256-cbc: the IV; MAC,
+ * VERIFY: 0
+ */
+ };
+
+``params`` is extended by size (``copy_struct_from_user()``): a caller
+built against a later header may give a larger ``usize`` than this
+kernel knows, which is accepted as long as the excess is zero; a
+``usize`` above ``PAGE_SIZE`` is refused with ``E2BIG``, one below
+``KEYCRYPT_OPEN_PARAMS_SIZE_VER0`` (32 bytes) with ``EINVAL``. That
+floor is the fixed value the uapi header names, not
+``sizeof(struct keycrypt_open_params)`` as this kernel builds it: a
+later kernel may grow the struct without raising the floor an older
+caller, built against this version, must still meet.
+
+The key needs Search permission; its type, the operation against its
+purpose and its tier against the higher of ``accepted_min_tier`` and the
+system tier (`System policies`_) are checked once, at open.
+``accepted_min_tier`` 0 states no requirement of the caller's own,
+leaving the system tier alone; any other value must be a tier.
+Against user space this check is the whole story, at every tier: it
+runs in the core, from the key's own metadata, whatever backend holds
+the key. A backend of tier ``tee`` or ``hsm`` meeting `Backend
+requirements`_ checks the operation again, in the TEE or the hardware,
+against the purpose it bound there rather than the core's copy of it,
+so that a kernel compromised enough to lie about the operation or the
+key's metadata still cannot open, say, an encryption context on a
+decrypt-only key; the sw backend has no such check of its own, since
+a compromised kernel already has that backend's key material in clear
+(`The sw backend`_), and relies on the core's check alone. Across
+every tier it is the kernel, not any backend, that decides who may open
+a context on a key, since Search permission is the core's own check; a
+compromised kernel can
+therefore still open a context on a key of any tier and use it for a
+purpose the key already has, but, for a backend of tier ``tee`` or
+``hsm`` meeting `Backend requirements`_, it can neither read that key
+(an imported one: unless the kernel was already compromised when it
+was imported) nor make it accept an operation outside the purpose its
+secure side bound when the key was sealed. The fd is
+``O_RDWR | O_CLOEXEC`` and holds a reference to the key: passing it to
+another process (``SCM_RIGHTS``) hands over the use of the key (see
+`An fd is a shared stream`_).
+
+For aes256-cbc encryption, ``iv`` must be zero on input unless
+``KEYCRYPT_OPEN_CALLER_IV`` is set: the kernel then draws a random IV
+(``get_random_bytes_wait()``) and writes it back into the caller's
+``params.iv`` before the fd is created, so a failed write-back
+(``EFAULT``) leaves no fd behind. With ``KEYCRYPT_OPEN_CALLER_IV`` the
+caller's IV is used instead, and IV uniqueness becomes the caller's to
+maintain (see `CBC and MAC`_). The flag is valid only together with
+aes256-cbc encryption; any other combination is ``EINVAL``. For
+aes256-cbc decryption ``iv`` is always the caller's.
+
+Data goes through ``ioctl()`` on the fd:
+
+``KEYCRYPT_IOC_UPDATE`` (``struct keycrypt_update``: ``in``, ``out``, ``len``, ``flags``)
+ aes256-cbc and MAC/VERIFY only: process ``len`` bytes, at most
+ ``KEYCRYPT_UPDATE_MAX`` (65536): for aes256-cbc a multiple of 16,
+ written to ``out``, the IV advancing in the context (padding is the
+ caller's); for MAC and VERIFY ``out`` is 0.
+``KEYCRYPT_IOC_FINAL`` (``struct keycrypt_final``: ``out``, ``len``, ``flags``)
+ end the context: for MAC write the 32-byte tag to ``out`` (``len``:
+ room in, bytes written out); for VERIFY ``out`` is the caller's
+ 32-byte expected tag (``len`` must be exactly 32), written back as
+ 0 on a match and left as given on a mismatch; for aes256-cbc
+ ``out`` is 0, nothing is written to it, and ``len`` is written back
+ as 0.
+``KEYCRYPT_IOC_INFO`` (``struct keycrypt_info``: ``op``, ``alg``, ``purpose``, ``tier``, ``origin``, ``accepted_min_tier``, ``backend``)
+ describe the context, whatever its algorithm or operation: the
+ operation it was opened for, the ``accepted_min_tier`` it was opened
+ with (0 for none), and its key's algorithm
+ (``KEYCRYPT_ALG_*``), purpose (``KEYCRYPT_PURPOSE_*``), the tier
+ the key was sealed at (``KEYCRYPT_TIER_*``), origin
+ (``KEYCRYPT_ORIGIN_*``) and backend name, NUL terminated; the
+ reserved words and the name's tail are zero. A program that knows
+ only this interface can record how it encrypted (asking before
+ FINAL, which ends the context), and a process given the fd through
+ ``SCM_RIGHTS`` can tell what it holds (see `An fd is a shared
+ stream`_). On an ended context ``EBADFD``; on a context whose key
+ was revoked, invalidated or expired, or whose backend was removed,
+ the ``EKEYREVOKED``, ``EKEYEXPIRED`` or ``ENODEV`` that UPDATE with
+ no data gives.
+
+VERIFY compares the expected tag against the one computed for it: by
+the core, in constant time (``crypto_memneq()``), for a backend with no
+``verify`` of its own, or by the backend's own ``verify``, where the
+key lives, for one that offers it (required of a ``tee`` or ``hsm``
+backend with context operations that offers hmac-sha256); either way
+the result is 0 on a match, ``EBADMSG`` otherwise, and the computed tag
+itself never leaves
+wherever it was computed. Against a compromised *user space*, the two
+are the same: a device given a ``verify`` key (without ``mac``) can
+check a tag but never forge one, at every tier, since the computed tag
+never reaches the fd either way; see `CBC and
+MAC`_ for why that matters. Against a compromised *kernel* they are
+not: a kernel-tier ``verify`` key is in clear in kernel memory like any
+other kernel-tier key (`The sw backend`_), so a compromised kernel can
+read it and forge, while a ``tee`` or ``hsm`` backend's own ``verify``,
+meeting `Backend requirements`_, keeps the key, and the comparison,
+where a compromised kernel cannot reach either.
+
+Every call checks the key again: a revoked, invalidated or expired key
+gives ``EKEYREVOKED`` or ``EKEYEXPIRED`` (see `Revocation`_). Calls on
+one fd are serialised, and a call blocked on another one's input or
+output copy is killable (only a fatal signal ends the wait). The
+kernel buffers of a call are erased before it returns.
+
+Revocation
+==========
+
+``keyctl revoke`` on a keycrypt key detaches every context already open
+on it (including one held only by another process through a passed fd)
+and releases the backend's state of the key, at once: every later
+call on such a context gives ``EKEYREVOKED``, not the key's own state at
+the time the context was opened. The backend's own ``destroy`` runs
+immediately too, even though the key itself survives, unusable, until it
+is actually garbage collected; for the sw backend this erases the key's
+clear copy in memory immediately as well, together with every detached
+context's own state (see `The sw backend`_). Revoking a key is
+therefore the way to stop every open use of it; removing Search
+permission (below) is not. "At once" has one exception: a kernel-tier
+``load`` or ``new`` in progress on the same backend holds it while it
+looks its master up with ``request_key()``, which can wait for a key
+still under construction; a revocation waits behind it, and so does
+every call that comes after the revocation, the key garbage collector
+included when it frees a key of that backend, which holds up the
+collection of keys of every type until the master's construction ends.
+
+Who can use a key
+=================
+
+Search permission is what lets a process open a context on a key;
+having it is "use" in the sense LSMs check (``key:search``), whatever
+the operation. Whoever can read a key can also copy it: ``keyctl read``
+returns the blob, which ``load`` turns into a key of one's own with the
+same backend state, out of reach of any revocation of the original.
+
+A keycrypt key added without explicit permissions gets the keyrings'
+defaults, as a user or trusted key does: Search, Read and the rest for
+its possessor, only View for its owner. A key added to the user keyring
+(``@u``) is therefore usable only by a process that possesses it, one
+whose session keyring links the user keyring; a login whose session
+keyring does not, as some console logins do not, gets ``EACCES`` from
+``KEYCTL_CRYPT_OPEN`` and from ``keyctl read`` on its own key, until the
+link is made (``keyctl link @u @s``) or the key is added to a keyring
+the session reaches.
+
+Read permission alone does not decide who can read: ``keyctl read``
+also succeeds, whatever the Read bit, for a key the caller possesses,
+that is, one it reaches by Search from its own keyrings. A process that
+possesses a key it can use can therefore always read its blob; clearing
+the possessor's Read bit does not change that. Use without read is
+possible only for a process that does not possess the key: Search
+granted through the user, group or other bits on a key that is not in
+any keyring the process can reach, or, simpler, an operation context fd
+handed to it (`An fd is a shared stream`_), which gives use of the key
+and its description (``KEYCRYPT_IOC_INFO``) without View permission,
+never its blob.
+
+Within one login session, possessor Search is shared by every program
+running as the session keyring's possessor, not only the one that opened
+a context: a setuid helper or a broker handing out access to several
+clients should pass each client an fd of its own (``SCM_RIGHTS``) rather
+than let them ``KEYCTL_CRYPT_OPEN`` a serial number that any possessor
+can open. Removing Search from a keyring stops a *future*
+``KEYCTL_CRYPT_OPEN``; it does not touch a context already open, nor the
+fds already handed out: only `Revocation`_ does.
+
+System policies
+===============
+
+Two sysctls, both under ``kernel.keys.``, bound every key on the system
+rather than one: both are one-way until reboot, readable by anyone, and
+writable only by root (mode ``0644``): a non-root writer gets ``EACCES``
+from opening the file at all, before keycrypt is ever asked, and
+keycrypt's own handler checks CAP_SYS_ADMIN again, before the written
+value is even parsed (``EPERM`` for whoever got the file open but lacks
+the capability); neither touches a context already open at the time
+they change.
+
+``kernel.keys.keycrypt_system_tier`` is the system tier, the lowest tier
+a key may be used at: one of ``10`` (``kernel``), ``20`` (``tee``)
+or ``30`` (``hsm``), the same values as
+``KEYCRYPT_TIER_*`` (`Tiers and backends`_). It can only be raised,
+never lowered (``EPERM`` on a lower value, ``EINVAL`` on anything
+else). It applies to use only: ``KEYCTL_CRYPT_OPEN`` refuses a key
+below it with ``EPERM``, whatever ``accepted_min_tier`` the caller
+gave, while ``new``, ``import`` and ``load`` of such a key succeed, so
+that blobs can be made and kept for a system where it is lower. It is
+checked once, at open: raising it does not touch a context already
+open, nor unload a key; `Revocation`_ is how to actually remove a key
+still in use. It starts at the tier chosen at build time,
+``CONFIG_KEYCRYPT_SYSTEM_TIER_*`` (``kernel`` unless set): neither the
+boot parameter below nor the sysctl can go under it, so a signed kernel
+image fixes a floor its command line cannot lower.
+
+``kernel.keys.keycrypt_import`` goes from ``1`` to ``0`` only (``EPERM``
+on turning it back on). Once it is ``0``, ``add_key``'s ``import``
+command fails with ``EPERM``, on top of the existing
+``CONFIG_KEYCRYPT_IMPORT`` and ``CAP_SYS_ADMIN`` checks that command
+already has. It stops only that command: neither ``load`` of a blob the
+backend already sealed (whatever its origin) nor the use of a key
+already loaded is affected, imported or not. With
+``CONFIG_KEYCRYPT_IMPORT=n`` the sysctl still reads back its default,
+``1``, and ``import`` is refused regardless, for the config reason
+rather than this one.
+
+Each has a boot parameter setting its starting value before either sysctl
+is ever written: ``keycrypt.system_tier=`` (``kernel``, ``tee`` or
+``hsm``) and ``keycrypt.import=`` (a boolean). An invalid
+value, or one that would lower what is already set, is ignored, with a
+kernel warning, rather than failing the boot. An administrator who
+wants either policy fixed from the very start, before any user-space
+program can run, uses the boot parameter rather than a sysctl written
+from ``sysctl.conf`` or similar, which runs only after early user space.
+Without CONFIG_SYSCTL neither sysctl exists at all; only the boot
+parameters remain.
+
+An fd is a shared stream
+========================
+
+The fd from ``KEYCTL_CRYPT_OPEN`` carries the context's state (the IV,
+the running hash) outside the key itself: after ``SCM_RIGHTS`` or
+``fork()``, every holder of a copy of the fd shares that state with
+every other, and an ``ioctl()`` from any of them advances it for all.
+Close the sending side's copy once sent, and receive with
+``MSG_CMSG_CLOEXEC`` so an unrelated child does not inherit it; the same
+holds for a fd that outlives an ``exec()`` without ``O_CLOEXEC`` (keycrypt
+sets it, but a caller that duplicates the fd without ``FD_CLOEXEC``
+keeps the duplicate across ``exec()``, and so hands the context to the
+program it runs).
+
+CBC and MAC
+===========
+
+aes256-cbc decryption is not an integrity boundary: given a decryption
+key, chosen ciphertext and a chosen IV can be made to decrypt to a
+chosen plaintext (a CBC padding/relay style attack, "CBC-R"); encrypted
+data must be authenticated (MAC or VERIFY) before it is trusted, and the
+MAC or VERIFY must be checked *before* the plaintext is used
+(encrypt-then-MAC), never after. Encryption without
+``KEYCRYPT_OPEN_CALLER_IV`` gets a kernel-chosen random IV, so a repeat
+is improbable, not impossible; with the flag, the caller's IV must be
+unpredictable to whoever supplies the plaintext, not merely unique (a
+counter is unique and still breaks CBC under chosen plaintext). A
+reused IV with the same key shows whether two messages share a
+plaintext prefix, not the XOR of them: equal first plaintext blocks
+XORed with the same IV give the same input to the block cipher, and so
+the same first ciphertext block. The IV is returned at
+``KEYCTL_CRYPT_OPEN``, and each later block's IV is the previous
+ciphertext block, so an encryption context is also a raw AES oracle for
+whoever holds its fd: inherent to CBC, not a keycrypt defect.
+
+A ``mac`` key can both compute and check a tag, so a program that only
+needs to check one can also forge one if compromised; give a verifier a
+``verify`` key instead of a ``mac`` key wherever possible (`Using a
+key`_), and keep ``mac`` for whatever actually produces tags. Importing
+the same key material twice, once with ``mac`` and once with
+``verify``, under the *same* algorithm is exactly how to give a
+producer and a verifier that pairing. Never import the same key
+material under two different *algorithms*, though: each uses the bytes
+differently (an aes256-cbc encryption context is a raw AES oracle on
+the key, above), and every new pairing of algorithms would need its own
+analysis that nothing here does.
+
+Why not AF_ALG or KEYCTL_PKEY_*
+================================
+
+``AF_ALG`` can take a key from a keyring by serial number
+(``ALG_SET_KEY_BY_KEY_SERIAL``), from a ``user``, ``logon``,
+``encrypted`` or ``trusted`` key. Of those a ``trusted`` key is the
+right comparison: like a keycrypt key, it is sealed at rest and never
+read back in clear by user space. ``AF_ALG`` keeps and chains the IV
+in the kernel too: a skcipher socket's IV buffer lives in the socket
+and is advanced in place as the cipher mode chains across calls, the
+same state keycrypt keeps in its context. The difference is that
+``AF_ALG`` never *chooses* an IV itself: it is always the caller's,
+zero by default and otherwise set with ``ALG_SET_IV``; keycrypt
+instead draws a random IV itself at ``KEYCTL_CRYPT_OPEN`` unless the
+caller asks for its own
+(``KEYCRYPT_OPEN_CALLER_IV``, aes256-cbc encryption only). ``AF_ALG``
+also copies the key's payload into the socket and applies whatever
+algorithm the socket was set up for, with nothing tying the key to
+that algorithm or to a purpose; keycrypt instead binds a key to one
+algorithm and purpose when it is created, and lets a backend of tier
+``tee`` or ``hsm`` run in a TEE or in hardware, where a key the backend
+created is never in kernel memory at all (an imported one passes
+through it once, to be sealed).
+``ALG_SET_KEY_BY_KEY_SERIAL`` refuses a keycrypt key
+(``ENOPROTOOPT``), as it does any key type it does not take.
+``KEYCTL_PKEY_*`` covers asymmetric keys only, a different problem.
+
+Errors of KEYCTL_CRYPT_OPEN and of the ioctls
+=============================================
+
+============ ==============================================================
+ENOKEY the key does not exist, or (KEYCTL_CRYPT_OPEN only) is
+ invalidated; an already open context instead gives
+ ``EKEYREVOKED`` for an invalidated key (see `Revocation`_)
+EACCES no Search permission on the key
+EOPNOTSUPP not a keycrypt key, or a kernel without KEYCTL_CRYPT_OPEN
+EKEYREJECTED the operation is not in the key's purpose; VERIFY needs
+ ``mac`` or ``verify``, MAC needs ``mac``
+EPERM the key's tier is below ``accepted_min_tier``, or below the
+ system tier, ``kernel.keys.keycrypt_system_tier``
+EINVAL ``__reserved`` or flags not zero, an unknown operation, an
+ ``accepted_min_tier`` that is neither 0 nor a tier, an IV
+ given for MAC or VERIFY, a non-zero IV given
+ for CBC encryption without ``KEYCRYPT_OPEN_CALLER_IV``,
+ or that flag with anything but CBC encryption; a CBC length
+ not a multiple of 16, an ``out`` given for MAC or for
+ aes256-cbc FINAL, or missing for CBC UPDATE; VERIFY FINAL
+ with ``len`` other than 32; a ``usize`` below
+ ``KEYCRYPT_OPEN_PARAMS_SIZE_VER0``
+E2BIG ``usize`` above ``PAGE_SIZE``, or a non-zero byte in its
+ excess over this kernel's ``struct keycrypt_open_params``;
+ a ``len`` above ``KEYCRYPT_UPDATE_MAX``
+ENOSPC MAC FINAL with ``out`` 0, or less than 32 bytes of room for
+ the tag (the context stays usable)
+EBADMSG VERIFY FINAL whose tag does not match (the context ends);
+ a backend's own
+ ``EBADMSG`` from ``KEYCTL_CRYPT_OPEN`` (no fd is created)
+ or from ``KEYCRYPT_IOC_UPDATE`` (the context ends)
+EKEYREVOKED the key was revoked, its type removed, or (an already
+ open context only) invalidated, or (``KEYCTL_CRYPT_OPEN``
+ only) the key's backend state already released by a
+ revoke that raced the open; a context detached this way
+ repeats the same answer on every later call, without
+ ending (see `Revocation`_)
+EKEYEXPIRED the key expired
+ENODEV the key's backend was removed (for ``optee``, its driver
+ unbound: `The OP-TEE backend`_), or (``KEYCTL_CRYPT_OPEN``
+ only) the key's backend offers no context operations;
+ either is permanent for the key, since a backend
+ registered again does not take back the keys of the one
+ removed (``load`` each key again); a context already open
+ on a backend later removed repeats the same answer on
+ every later call, without ending
+ENOMEM out of memory, including (``KEYCTL_CRYPT_OPEN``) a backend
+ with no room for another context, as ``optee`` once 31 are
+ open (`The OP-TEE backend`_)
+EIO a backend failure, including one refusing at
+ ``KEYCTL_CRYPT_OPEN`` itself: a backend's ``ENOMEM``,
+ ``EINTR`` and ``EBADMSG`` pass unchanged (a restart it
+ asks for restarts the call), any other error becomes
+ ``EIO`` (no fd is created either way)
+EBADFD a call on a context that already ended: after
+ FINAL, or after a failure once the backend had been
+ called for this call (``EBADMSG``, ``EIO``, an
+ ``EFAULT`` on the output copy, or ``EINTR`` from an
+ interrupted backend). Every other error leaves the
+ context usable too: ``EINVAL``, ``E2BIG``, ``ENOSPC``,
+ an ``EFAULT`` on the input copy or on
+ ``KEYCRYPT_IOC_INFO``'s output copy, ``ENOMEM`` before
+ the backend ran, ``EKEYREVOKED``, ``EKEYEXPIRED`` and
+ ``ENODEV`` (repeated instead, above), and ``EINTR`` while
+ waiting to acquire the context's lock
+============ ==============================================================
+
+KEYCTL_CRYPT_OPEN checks its parameters, then looks the key up, then
+looks at its type: a key that is not a keycrypt key gives
+``EOPNOTSUPP`` only once the parameters are accepted and the lookup
+has succeeded, and the lookup's own errors come first, such as
+``ENOKEY`` (a negative key included), ``EKEYREVOKED``, ``EKEYEXPIRED``
+and ``EACCES``. A kernel without KEYCTL_CRYPT_OPEN answers
+``EOPNOTSUPP`` too, so user space that falls back to another interface
+for a key of another type does so on ``EOPNOTSUPP`` alone.
+
+Errors of add_key
+=================
+
+============ ==========================================================
+EINVAL malformed options or input (an embedded NUL included), a
+ blob that is not hex or too long, algorithm and purpose not
+ matching, ``tier=`` with ``min-tier=``, a tier option of
+ the other commands (``accepted-min-tier=`` at ``new`` or
+ ``import``, ``tier=``, ``min-tier=`` or ``backend=`` at
+ ``load``), ``backend=`` twice or not a backend name
+ (``[a-z0-9_-]``, at most 16 characters), an option the
+ backend does not know, the kernel tier chosen without
+ ``master=``, a key of the wrong length
+ENODEV no backend for the request (none registered for the
+ algorithm, none of the tier ``tier=`` or ``min-tier=`` asks
+ for, or ``backend=`` naming no registered backend, or one
+ that does not meet ``tier=``/``min-tier=``, the algorithm
+ or, for ``import``, importing), or the blob's backend is not
+ registered
+ENOKEY the master key of a kernel-tier key was not found,
+ including when the trusted key type is not registered
+ or the master is revoked or expired
+EPERM a blob below ``accepted-min-tier=``; import disabled
+ (``kernel.keys.keycrypt_import``) or without
+ CAP_SYS_ADMIN
+EOPNOTSUPP a blob of an unknown format version, or with a non-zero
+ header flags byte
+EKEYREJECTED a blob claiming a tier above its backend's, or not of the
+ purpose ``load`` asked for
+EBADMSG a blob that is malformed, altered, or not the backend's
+EIO a backend failure
+============ ==========================================================
+
+An altered blob may be refused before its backend sees it, with
+``EOPNOTSUPP``, ``ENODEV``, ``EKEYREJECTED`` or ``EPERM``, rather than
+``EBADMSG``; past those checks ``optee`` answers ``EBADMSG`` for any
+altered byte. For the kernel tier, an altered master description gives
+``ENOKEY`` only when the altered name exists nowhere in the caller's
+search path; found there, it gives ``EACCES`` if the caller may not
+search that key, or, found and searchable but not the master that
+sealed the blob, ``EBADMSG`` once unsealing it fails to authenticate
+the header.
+
+A backend may also report ``ENOMEM``, ``EINVAL``, ``EBADMSG``, ``ENOKEY``,
+``EKEYREJECTED``, ``EACCES`` or ``EINTR`` (a restart it asks for restarts
+the call); any other backend error is reported as ``EIO``.
--
2.43.0
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [RFC PATCH 5/9] MAINTAINERS: add KEYS-KEYCRYPT
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
` (3 preceding siblings ...)
2026-11-18 14:07 ` [RFC PATCH 4/9] docs: keycrypt: document keycrypt keys Rodolfo Giometti
@ 2026-11-18 14:08 ` Rodolfo Giometti
2026-11-18 14:09 ` [RFC PATCH 6/9] KEYS: keycrypt: Add the engine tier Rodolfo Giometti
` (5 subsequent siblings)
10 siblings, 0 replies; 14+ messages in thread
From: Rodolfo Giometti @ 2026-11-18 14:08 UTC (permalink / raw)
To: David Howells, Jarkko Sakkinen, keyrings
Cc: Herbert Xu, David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, Rodolfo Giometti
Add an entry for the keycrypt key type, its sw backend and its
documentation, and one for its OP-TEE backend, so that changes to the
backend also reach the OP-TEE list.
Signed-off-by: Rodolfo Giometti <giometti@enneenne.com>
---
MAINTAINERS | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
diff --git a/MAINTAINERS b/MAINTAINERS
index 222b7fc2c3aa..41dc8fe1fb36 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -14813,6 +14813,24 @@ F: Documentation/security/keys/trusted-encrypted.rst
F: include/keys/encrypted-type.h
F: security/keys/encrypted-keys/
+KEYS-KEYCRYPT
+M: Rodolfo Giometti <giometti@enneenne.com>
+L: keyrings@vger.kernel.org
+L: linux-crypto@vger.kernel.org
+L: linux-integrity@vger.kernel.org
+S: Maintained
+F: Documentation/security/keys/keycrypt.rst
+F: include/keys/keycrypt.h
+F: include/uapi/linux/keycrypt.h
+F: security/keys/keycrypt/
+
+KEYS-KEYCRYPT OP-TEE BACKEND
+M: Rodolfo Giometti <giometti@enneenne.com>
+L: keyrings@vger.kernel.org
+L: op-tee@lists.trustedfirmware.org (moderated for non-subscribers)
+S: Maintained
+F: security/keys/keycrypt/optee*
+
KEYS-TRUSTED
M: James Bottomley <James.Bottomley@HansenPartnership.com>
M: Jarkko Sakkinen <jarkko@kernel.org>
--
2.43.0
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [RFC PATCH 6/9] KEYS: keycrypt: Add the engine tier
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
` (4 preceding siblings ...)
2026-11-18 14:08 ` [RFC PATCH 5/9] MAINTAINERS: add KEYS-KEYCRYPT Rodolfo Giometti
@ 2026-11-18 14:09 ` Rodolfo Giometti
2026-11-18 14:10 ` [RFC PATCH 7/9] crypto: caam - add an internal cbc(paes) taking the blob's key modifier Rodolfo Giometti
` (4 subsequent siblings)
10 siblings, 0 replies; 14+ messages in thread
From: Rodolfo Giometti @ 2026-11-18 14:09 UTC (permalink / raw)
To: David Howells, Jarkko Sakkinen, keyrings
Cc: Herbert Xu, David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, Rodolfo Giometti
Some crypto engines hold a key so that the kernel never reads it once
sealed, yet run whatever operation the kernel asks of it: the CAAM's
black keys are of this kind. A key there is better kept than in
kernel memory, but its use is no more checked than the kernel
tier's.
Add the engine tier, 15, between kernel and tee, for such backends:
tier=engine and min-tier=engine choose them, accepted-min-tier=engine
and KEYCTL_CRYPT_OPEN's accepted_min_tier take them, and
CONFIG_KEYCRYPT_SYSTEM_TIER_ENGINE makes it the system tier at boot.
The core warns in the kernel log when a backend registers at it, since
the protection its name may suggest stops short of the use of the key.
No backend in the kernel declares this tier yet; the keycrypt CAAM
backend proposed with it does.
Signed-off-by: Rodolfo Giometti <giometti@enneenne.com>
---
.../admin-guide/kernel-parameters.txt | 2 +-
Documentation/security/keys/keycrypt.rst | 42 ++++++++++++-------
include/uapi/linux/keycrypt.h | 2 +
security/keys/keycrypt/Kconfig | 11 ++++-
security/keys/keycrypt/core.c | 4 ++
security/keys/keycrypt/keycrypt.h | 2 +
6 files changed, 46 insertions(+), 17 deletions(-)
diff --git a/Documentation/admin-guide/kernel-parameters.txt b/Documentation/admin-guide/kernel-parameters.txt
index 62d44a5225e4..0cacb7d1ca1d 100644
--- a/Documentation/admin-guide/kernel-parameters.txt
+++ b/Documentation/admin-guide/kernel-parameters.txt
@@ -2947,7 +2947,7 @@ Kernel parameters
keycrypt.system_tier= [KEYS] Lowest protection tier a keycrypt key
may be used at; keys of a lower tier can still
be created and loaded.
- Format: { kernel | tee | hsm }
+ Format: { kernel | engine | tee | hsm }
Default: the CONFIG_KEYCRYPT_SYSTEM_TIER_*
choice, kernel unless set. Can only be raised,
here or later through the
diff --git a/Documentation/security/keys/keycrypt.rst b/Documentation/security/keys/keycrypt.rst
index 17af3b041000..ac393a0bc97d 100644
--- a/Documentation/security/keys/keycrypt.rst
+++ b/Documentation/security/keys/keycrypt.rst
@@ -26,6 +26,10 @@ The tiers, lowest first:
========== =========================================================
``kernel`` the key is in clear in kernel memory while loaded; the
kernel enforces its use
+``engine`` a crypto engine the kernel drives keeps the key, never in
+ clear in the kernel once sealed; the kernel decides its use
+ (a secure element that does not check a key's use is an
+ engine too)
``tee`` a trusted execution environment keeps the key and checks
every use against the purpose it bound (an OP-TEE TA)
``hsm`` as ``tee``, in dedicated hardware apart from the CPU running
@@ -34,7 +38,9 @@ The tiers, lowest first:
policy)
========== =========================================================
-Each tier holds the guarantees of those before it.
+Each tier holds the guarantees of those before it. Keys of the ``engine``
+tier, such as the CAAM's protected keys, are used by the kernel, which
+cannot read them once sealed.
The backends of this document: ``sw``, of tier ``kernel``, where the
kernel's own software uses the key (`The sw backend`_); and ``optee``,
@@ -55,7 +61,9 @@ sw backend the secret is the trusted master each key names with
master (`The sw backend`_).
A backend of tier ``tee`` or ``hsm`` also declares that it meets
-`Backend requirements`_.
+`Backend requirements`_; one that keeps a sealed key out of the kernel's
+reading but leaves its use to the kernel is ``engine``. The core says
+so in the kernel log when an ``engine`` backend registers.
A backend registers with ``keycrypt_register_backend()``
(``include/keys/keycrypt.h``) under a name that is stored in every blob it
@@ -96,10 +104,13 @@ itself does what the core has no way to check:
A backend declares its own tier at ``keycrypt_register_backend()``; the
core stores and compares it wherever a tier is checked, but never
confirms that the backend is actually a TEE or hardware rather than
-ordinary kernel code claiming to be one. The ``kernel`` tier meets
-none of the above: its key material is in clear in kernel memory (`The
-sw backend`_), so there every property above is only as strong as the
-kernel itself.
+ordinary kernel code claiming to be one. The ``engine`` and ``kernel``
+tiers meet none of the above: an ``engine`` backend leaves the key's
+use to the kernel, and the kernel tier's key material is in clear in
+kernel memory (`The sw backend`_), so there every property above is
+only as strong as the kernel itself. What an ``engine`` backend keeps
+against a compromised kernel is only that a sealed key is not in clear
+in kernel memory, as far as its hardware's own properties hold.
Metadata
========
@@ -187,7 +198,7 @@ Any other ``<option>=<value>`` is passed to the backend; the core refuses
an option the backend does not declare and an option given twice. The
one option a backend of this document takes from user space is
``master=``, the sw backend's: it needs a master to seal its keys, while from
-``tee`` up a backend's own mechanisms protect the key. A command for
+``engine`` up a backend's own mechanisms protect the key. A command for
the kernel tier therefore reads ``tier=kernel master=<name>``; the kernel
tier chosen without ``master=``, or ``master=`` given to a backend of
another tier, is refused with ``EINVAL``.
@@ -451,10 +462,11 @@ so that a kernel compromised enough to lie about the operation or the
key's metadata still cannot open, say, an encryption context on a
decrypt-only key; the sw backend has no such check of its own, since
a compromised kernel already has that backend's key material in clear
-(`The sw backend`_), and relies on the core's check alone. Across
-every tier it is the kernel, not any backend, that decides who may open
-a context on a key, since Search permission is the core's own check; a
-compromised kernel can
+(`The sw backend`_), and relies on the core's check alone; neither
+does an ``engine`` backend, whose key's use the kernel decides
+(`Tiers and backends`_). Across every tier it is the kernel, not any
+backend, that decides who may open a context on a key, since Search
+permission is the core's own check; a compromised kernel can
therefore still open a context on a key of any tier and use it for a
purpose the key already has, but, for a backend of tier ``tee`` or
``hsm`` meeting `Backend requirements`_, it can neither read that key
@@ -603,8 +615,8 @@ the capability); neither touches a context already open at the time
they change.
``kernel.keys.keycrypt_system_tier`` is the system tier, the lowest tier
-a key may be used at: one of ``10`` (``kernel``), ``20`` (``tee``)
-or ``30`` (``hsm``), the same values as
+a key may be used at: one of ``10`` (``kernel``), ``15`` (``engine``),
+``20`` (``tee``) or ``30`` (``hsm``), the same values as
``KEYCRYPT_TIER_*`` (`Tiers and backends`_). It can only be raised,
never lowered (``EPERM`` on a lower value, ``EINVAL`` on anything
else). It applies to use only: ``KEYCTL_CRYPT_OPEN`` refuses a key
@@ -630,8 +642,8 @@ already loaded is affected, imported or not. With
rather than this one.
Each has a boot parameter setting its starting value before either sysctl
-is ever written: ``keycrypt.system_tier=`` (``kernel``, ``tee`` or
-``hsm``) and ``keycrypt.import=`` (a boolean). An invalid
+is ever written: ``keycrypt.system_tier=`` (``kernel``, ``engine``,
+``tee`` or ``hsm``) and ``keycrypt.import=`` (a boolean). An invalid
value, or one that would lower what is already set, is ignored, with a
kernel warning, rather than failing the boot. An administrator who
wants either policy fixed from the very start, before any user-space
diff --git a/include/uapi/linux/keycrypt.h b/include/uapi/linux/keycrypt.h
index c03348579f62..71209a08c924 100644
--- a/include/uapi/linux/keycrypt.h
+++ b/include/uapi/linux/keycrypt.h
@@ -13,6 +13,8 @@
/* Protection tiers, lowest first; the gaps leave room for more */
#define KEYCRYPT_TIER_KERNEL 10 /* the kernel itself */
+/* a crypto engine the kernel drives; the kernel decides its use */
+#define KEYCRYPT_TIER_ENGINE 15
#define KEYCRYPT_TIER_TEE 20 /* a trusted execution environment */
/* as TEE, in dedicated hardware apart from the CPU running the kernel */
#define KEYCRYPT_TIER_HSM 30
diff --git a/security/keys/keycrypt/Kconfig b/security/keys/keycrypt/Kconfig
index e61922933bd7..a6d8a0fa6d29 100644
--- a/security/keys/keycrypt/Kconfig
+++ b/security/keys/keycrypt/Kconfig
@@ -56,11 +56,20 @@ config KEYCRYPT_SYSTEM_TIER_KERNEL
A system with no backend of the kernel tier built has no key of
that tier to use.
+config KEYCRYPT_SYSTEM_TIER_ENGINE
+ bool "Engine"
+ help
+ Only keys whose backend declares them never in clear in the
+ kernel once sealed can be used: a key of the kernel tier is
+ refused at every KEYCTL_CRYPT_OPEN; the engine, tee and hsm tiers
+ can be used. For a system that must never use a key held in clear
+ by the kernel.
+
config KEYCRYPT_SYSTEM_TIER_TEE
bool "TEE"
help
Keys whose use a trusted execution environment or the hardware
- checks: keys of the kernel tier are refused at every
+ checks: keys of the kernel and engine tiers are refused at every
KEYCTL_CRYPT_OPEN; the tee and hsm tiers can be used. For a
system where OP-TEE or an hsm backend holds the keys.
diff --git a/security/keys/keycrypt/core.c b/security/keys/keycrypt/core.c
index debd0845621e..4a2609c6830f 100644
--- a/security/keys/keycrypt/core.c
+++ b/security/keys/keycrypt/core.c
@@ -40,6 +40,7 @@ static const struct keycrypt_name keycrypt_algs[] = {
static const struct keycrypt_name keycrypt_tiers[] = {
{ KEYCRYPT_TIER_KERNEL, "kernel" },
+ { KEYCRYPT_TIER_ENGINE, "engine" },
{ KEYCRYPT_TIER_TEE, "tee" },
{ KEYCRYPT_TIER_HSM, "hsm" },
};
@@ -441,6 +442,9 @@ int keycrypt_register_backend(struct keycrypt_backend *b)
b->handle = h;
}
mutex_unlock(&keycrypt_lock);
+ if (!ret && b->tier == KEYCRYPT_TIER_ENGINE)
+ pr_warn("backend %s registered at tier engine: the use of its keys is checked by the kernel only\n",
+ b->name);
if (ret)
kfree(h);
return ret;
diff --git a/security/keys/keycrypt/keycrypt.h b/security/keys/keycrypt/keycrypt.h
index 5a41a68c48fa..40487eb3e139 100644
--- a/security/keys/keycrypt/keycrypt.h
+++ b/security/keys/keycrypt/keycrypt.h
@@ -143,6 +143,8 @@ bool keycrypt_tier_valid(u32 tier);
#define KEYCRYPT_BOOT_SYSTEM_TIER KEYCRYPT_TIER_HSM
#elif IS_ENABLED(CONFIG_KEYCRYPT_SYSTEM_TIER_TEE)
#define KEYCRYPT_BOOT_SYSTEM_TIER KEYCRYPT_TIER_TEE
+#elif IS_ENABLED(CONFIG_KEYCRYPT_SYSTEM_TIER_ENGINE)
+#define KEYCRYPT_BOOT_SYSTEM_TIER KEYCRYPT_TIER_ENGINE
#else
#define KEYCRYPT_BOOT_SYSTEM_TIER KEYCRYPT_TIER_KERNEL
#endif
--
2.43.0
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [RFC PATCH 7/9] crypto: caam - add an internal cbc(paes) taking the blob's key modifier
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
` (5 preceding siblings ...)
2026-11-18 14:09 ` [RFC PATCH 6/9] KEYS: keycrypt: Add the engine tier Rodolfo Giometti
@ 2026-11-18 14:10 ` Rodolfo Giometti
2026-11-18 14:11 ` [RFC PATCH 8/9] KEYS: keycrypt: Add the CAAM backend Rodolfo Giometti
` (3 subsequent siblings)
10 siblings, 0 replies; 14+ messages in thread
From: Rodolfo Giometti @ 2026-11-18 14:10 UTC (permalink / raw)
To: David Howells, Jarkko Sakkinen, keyrings
Cc: Herbert Xu, David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, Rodolfo Giometti
cbc(paes) decapsulates every blob with the fixed key modifier
"SECURE_KEY", the one trusted keys use for their "pk" keys, and is
reachable from AF_ALG: a blob made for either can be used through the
other by whoever holds CAP_NET_ADMIN or CAP_SYS_ADMIN (with AF_ALG's
default restriction), for whatever operation they choose. A kernel
user that wants its blobs bound to something of its own, such as the
metadata of the key they protect, has no way to say so.
Add a second cbc(paes), cbc-paes-km-caam, flagged CRYPTO_ALG_INTERNAL
so that only kernel code asking for that flag can allocate it, as the
DCP's paes is, which trusted keys allocate by driver name with that
flag; its key names the key modifier to decapsulate with.
caam_encap_blob() already takes a caller's key modifier, so a kernel
user can now bind its blobs to a value of its own.
Its only user is the keycrypt CAAM backend, which is a proposal, and
so is this.
Signed-off-by: Rodolfo Giometti <giometti@enneenne.com>
---
drivers/crypto/caam/caamalg.c | 89 ++++++++++++++++++++++++++----
drivers/crypto/caam/caamalg_desc.c | 3 +-
drivers/crypto/caam/caamalg_desc.h | 1 +
include/soc/fsl/caam-blob.h | 8 +++
4 files changed, 89 insertions(+), 12 deletions(-)
diff --git a/drivers/crypto/caam/caamalg.c b/drivers/crypto/caam/caamalg.c
index d00caa9cdf8e..f34717f312b8 100644
--- a/drivers/crypto/caam/caamalg.c
+++ b/drivers/crypto/caam/caamalg.c
@@ -125,6 +125,8 @@ struct caam_ctx {
dma_addr_t key_dma;
u8 protected_key[CAAM_MAX_KEY_SIZE];
dma_addr_t protected_key_dma;
+ u8 key_mod[CAAM_BLOB_KEYMOD_LENGTH];
+ unsigned int key_mod_len;
enum dma_data_direction dir;
struct device *jrdev;
struct alginfo adata;
@@ -784,18 +786,19 @@ static int skcipher_setkey(struct crypto_skcipher *skcipher, const u8 *key,
return 0;
}
-static int paes_skcipher_setkey(struct crypto_skcipher *skcipher,
- const u8 *key,
- unsigned int keylen)
+static int paes_set_blob(struct crypto_skcipher *skcipher,
+ const struct caam_pkey_info *pkey_info,
+ const u8 *blob, unsigned int keylen,
+ const u8 *key_mod, unsigned int key_mod_len)
{
- struct caam_pkey_info *pkey_info = (struct caam_pkey_info *)key;
struct caam_ctx *ctx = crypto_skcipher_ctx_dma(skcipher);
struct device *jrdev = ctx->jrdev;
int err;
- ctx->cdata.key_inline = false;
+ if (WARN_ON(key_mod_len > CAAM_BLOB_KEYMOD_LENGTH))
+ return -EINVAL;
- keylen = keylen - CAAM_PKEY_HEADER;
+ ctx->cdata.key_inline = false;
if (pkey_info->is_pkey != 1) {
dev_dbg(jrdev, "not a protected key\n");
@@ -842,19 +845,52 @@ static int paes_skcipher_setkey(struct crypto_skcipher *skcipher,
/* Retrieve the length of blob*/
ctx->cdata.keylen = keylen;
- /* Retrieve the address of the blob */
- ctx->cdata.key_virt = pkey_info->key_buf;
-
/* set command option */
ctx->cdata.key_cmd_opt = KEY_ENC;
- memcpy(ctx->key, ctx->cdata.key_virt, keylen);
+ /* The key modifier the blob is decapsulated with, at every job */
+ memcpy(ctx->key_mod, key_mod, key_mod_len);
+ ctx->key_mod_len = key_mod_len;
+
+ /* Retrieve the address of the blob */
+ memcpy(ctx->key, blob, keylen);
+ ctx->cdata.key_virt = ctx->key;
dma_sync_single_for_device(jrdev, ctx->key_dma, keylen, DMA_TO_DEVICE);
ctx->cdata.key_dma = ctx->key_dma;
return 0;
}
+static int paes_skcipher_setkey(struct crypto_skcipher *skcipher,
+ const u8 *key,
+ unsigned int keylen)
+{
+ const struct caam_pkey_info *pkey_info =
+ (const struct caam_pkey_info *)key;
+
+ return paes_set_blob(skcipher, pkey_info, pkey_info->key_buf,
+ keylen - CAAM_PKEY_HEADER, KEYMOD,
+ sizeof(KEYMOD) - 1);
+}
+
+/*
+ * The internal cbc(paes): the blob comes with the key modifier it was
+ * encapsulated with, which only kernel code can choose; a caller that
+ * picks a modifier of its own keeps its blobs apart from those of
+ * cbc(paes) and of trusted "pk" keys
+ */
+static int paes_km_skcipher_setkey(struct crypto_skcipher *skcipher,
+ const u8 *key,
+ unsigned int keylen)
+{
+ const struct caam_pkey_info *pkey_info =
+ (const struct caam_pkey_info *)key;
+
+ return paes_set_blob(skcipher, pkey_info, key + CAAM_PKEY_KM_HEADER,
+ keylen - CAAM_PKEY_KM_HEADER,
+ key + CAAM_PKEY_HEADER, CAAM_BLOB_KEYMOD_LENGTH);
+}
+
static int aes_skcipher_setkey(struct crypto_skcipher *skcipher,
const u8 *key, unsigned int keylen)
{
@@ -1398,7 +1434,9 @@ static int init_skcipher_job(struct skcipher_request *req,
edesc->desc_dma = desc_dma;
edesc->desc_dma_bytes = desc_bytes(desc);
- cnstr_desc_protected_blob_decap(edesc->hw_desc, &ctx->cdata, desc_dma);
+ cnstr_desc_protected_blob_decap(edesc->hw_desc, &ctx->cdata,
+ ctx->key_mod, ctx->key_mod_len,
+ desc_dma);
} else {
sh_desc = encrypt ? ctx->sh_desc_enc : ctx->sh_desc_dec;
ptr = encrypt ? ctx->sh_desc_enc_dma : ctx->sh_desc_dec_dma;
@@ -2031,6 +2069,30 @@ static struct caam_skcipher_alg driver_algs[] = {
.caam.class1_alg_type = OP_ALG_ALGSEL_AES | OP_ALG_AAI_CBC,
.caam.is_paes = true,
},
+ {
+ .skcipher.base = {
+ .base = {
+ .cra_name = "cbc(paes)",
+ .cra_driver_name = "cbc-paes-km-caam",
+ .cra_blocksize = AES_BLOCK_SIZE,
+ /* kernel users only: never from AF_ALG */
+ .cra_flags = CRYPTO_ALG_INTERNAL,
+ },
+ .setkey = paes_km_skcipher_setkey,
+ .encrypt = skcipher_encrypt,
+ .decrypt = skcipher_decrypt,
+ .min_keysize = AES_MIN_KEY_SIZE + CAAM_BLOB_OVERHEAD +
+ CAAM_PKEY_KM_HEADER,
+ .max_keysize = AES_MAX_KEY_SIZE + CAAM_BLOB_OVERHEAD +
+ CAAM_PKEY_KM_HEADER,
+ .ivsize = AES_BLOCK_SIZE,
+ },
+ .skcipher.op = {
+ .do_one_request = skcipher_do_one_req,
+ },
+ .caam.class1_alg_type = OP_ALG_ALGSEL_AES | OP_ALG_AAI_CBC,
+ .caam.is_paes = true,
+ },
{
.skcipher.base = {
.base = {
@@ -3812,6 +3874,11 @@ static int caam_cra_init(struct crypto_skcipher *tfm)
* AF_ALG refuses ALG_SET_KEY once an op socket exists, so
* concurrent jobs all decapsulate the same blob into the same
* black key.
+ * In-kernel users of the internal cbc(paes) set the key once,
+ * before any request, as well. It also relies on the black
+ * key being decapsulated identically by every job, which ECB
+ * black keys are; CCM ones, with their random nonce, would
+ * need a buffer per request.
*/
ctx->protected_key_dma = dma_map_single(ctx->jrdev,
ctx->protected_key,
diff --git a/drivers/crypto/caam/caamalg_desc.c b/drivers/crypto/caam/caamalg_desc.c
index 04c1105eb1f5..db3bbba67c8b 100644
--- a/drivers/crypto/caam/caamalg_desc.c
+++ b/drivers/crypto/caam/caamalg_desc.c
@@ -1410,6 +1410,7 @@ void cnstr_desc_skcipher_enc_dec(u32 * const desc, struct alginfo *cdata,
EXPORT_SYMBOL(cnstr_desc_skcipher_enc_dec);
void cnstr_desc_protected_blob_decap(u32 * const desc, struct alginfo *cdata,
+ const u8 *key_mod, unsigned int key_mod_len,
dma_addr_t next_desc_addr)
{
u32 protected_store;
@@ -1417,7 +1418,7 @@ void cnstr_desc_protected_blob_decap(u32 * const desc, struct alginfo *cdata,
init_job_desc(desc, 0);
/* Load key modifier */
- append_load_as_imm(desc, KEYMOD, sizeof(KEYMOD) - 1,
+ append_load_as_imm(desc, key_mod, key_mod_len,
LDST_CLASS_2_CCB | LDST_SRCDST_BYTE_KEY);
append_seq_in_ptr_intlen(desc, cdata->key_dma,
diff --git a/drivers/crypto/caam/caamalg_desc.h b/drivers/crypto/caam/caamalg_desc.h
index 323490a4a756..ae673b596a6d 100644
--- a/drivers/crypto/caam/caamalg_desc.h
+++ b/drivers/crypto/caam/caamalg_desc.h
@@ -117,6 +117,7 @@ void cnstr_shdsc_xts_skcipher_encap(u32 * const desc, struct alginfo *cdata);
void cnstr_shdsc_xts_skcipher_decap(u32 * const desc, struct alginfo *cdata);
void cnstr_desc_protected_blob_decap(u32 * const desc, struct alginfo *cdata,
+ const u8 *key_mod, unsigned int key_mod_len,
dma_addr_t next_desc);
void cnstr_desc_skcipher_enc_dec(u32 * const desc, struct alginfo *cdata,
diff --git a/include/soc/fsl/caam-blob.h b/include/soc/fsl/caam-blob.h
index 922f7ec3e231..13c21c7e4c2e 100644
--- a/include/soc/fsl/caam-blob.h
+++ b/include/soc/fsl/caam-blob.h
@@ -38,6 +38,14 @@ struct caam_pkey_info {
/* sizeof struct caam_pkey_info */
#define CAAM_PKEY_HEADER 4
+/*
+ * A key of the CAAM's internal cbc(paes): struct caam_pkey_info, the
+ * CAAM_BLOB_KEYMOD_LENGTH-byte key modifier the blob was encapsulated
+ * with, then the blob
+ */
+#define CAAM_PKEY_KM_HEADER (CAAM_PKEY_HEADER + \
+ CAAM_BLOB_KEYMOD_LENGTH)
+
/**
* struct caam_blob_info - information for CAAM blobbing
* @pkey_info: pointer to keep protected key information
--
2.43.0
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [RFC PATCH 8/9] KEYS: keycrypt: Add the CAAM backend
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
` (6 preceding siblings ...)
2026-11-18 14:10 ` [RFC PATCH 7/9] crypto: caam - add an internal cbc(paes) taking the blob's key modifier Rodolfo Giometti
@ 2026-11-18 14:11 ` Rodolfo Giometti
2026-11-18 14:12 ` [RFC PATCH 9/9] KEYS: keycrypt: Add the aes256-gcm-stream algorithm Rodolfo Giometti
` (2 subsequent siblings)
10 siblings, 0 replies; 14+ messages in thread
From: Rodolfo Giometti @ 2026-11-18 14:11 UTC (permalink / raw)
To: David Howells, Jarkko Sakkinen, keyrings
Cc: Herbert Xu, David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, Rodolfo Giometti
Add "caam", a backend of the engine tier for NXP SoCs with a CAAM:
once sealed, its keys exist outside the CAAM only as black blobs and
black keys, used through the CAAM's internal cbc(paes); a new key is
drawn in kernel memory and sealed at once. Each blob is encapsulated
with a key modifier derived from the blob's header, so a blob whose
metadata was changed does not open, and the blobs of the public
cbc(paes) and of trusted "pk" keys, made with another key modifier, do
not load.
This is a proposal for owners of CAAM hardware to try, not to be
applied as is: it has not been run on hardware, and the CAAM does not
check what a key is used for, which is why its tier is engine. Only
aes256-cbc is offered, with ECB-encrypted black keys, since the
driver's cbc(paes), with Richard Weinberger's paes fixes, refuses
CCM ones.
With it comes its section of the documentation.
Signed-off-by: Rodolfo Giometti <giometti@enneenne.com>
---
Documentation/security/keys/keycrypt.rst | 97 ++++++-
security/keys/keycrypt/Kconfig | 27 ++
security/keys/keycrypt/Makefile | 2 +
security/keys/keycrypt/caam.c | 346 +++++++++++++++++++++++
security/keys/keycrypt/caam.h | 30 ++
5 files changed, 491 insertions(+), 11 deletions(-)
create mode 100644 security/keys/keycrypt/caam.c
create mode 100644 security/keys/keycrypt/caam.h
diff --git a/Documentation/security/keys/keycrypt.rst b/Documentation/security/keys/keycrypt.rst
index ac393a0bc97d..e2ee5f75d9f4 100644
--- a/Documentation/security/keys/keycrypt.rst
+++ b/Documentation/security/keys/keycrypt.rst
@@ -43,18 +43,21 @@ tier, such as the CAAM's protected keys, are used by the kernel, which
cannot read them once sealed.
The backends of this document: ``sw``, of tier ``kernel``, where the
-kernel's own software uses the key (`The sw backend`_); and ``optee``,
-of tier ``tee`` (`The OP-TEE backend`_).
+kernel's own software uses the key (`The sw backend`_); ``optee``,
+of tier ``tee`` (`The OP-TEE backend`_); and ``caam``, of tier
+``engine``, ``hsm`` only if the CAAM enforced a key's use
+(`The CAAM backend`_).
Every backend, whatever its tier, must seal with a secret that is secret
-and unique to the device: the trusted key the sw backend derives from
-or OP-TEE's hardware unique key. Were that secret known, the blob, which
-user space reads, would be the key itself; were it shared by several
-devices, a blob copied from one would load on another, and its key would
-be used there. Every tier presumes it, and keycrypt cannot check it, nor
-that the hardware is configured so that the secret is secret (an OP-TEE
-whose hardware unique key is provisioned, not OP-TEE's test value):
-whoever builds in or loads a backend for a device declares
+and unique to the device: the trusted key the sw backend derives from,
+OP-TEE's hardware unique key, the CAAM's master key. Were that secret
+known, the blob, which user space reads, would be the key itself; were
+it shared by several devices, a blob copied from one would load on
+another, and its key would be used there. Every tier presumes it, and
+keycrypt cannot check it, nor that the hardware is configured so that
+the secret is secret (a CAAM with secure boot enabled, an OP-TEE whose
+hardware unique key is provisioned; not a CAAM test key, nor OP-TEE's
+test value): whoever builds in or loads a backend for a device declares
that the device meets it, as a backend declares its tier. For the
sw backend the secret is the trusted master each key names with
``master=``, so there the requirement falls on whoever creates that
@@ -417,6 +420,76 @@ a keyring, and every context open on one, gives ``ENODEV`` from then on,
also after the driver is bound again; once it is, ``load`` each key
again from its blob.
+The CAAM backend
+================
+
+With CONFIG_KEYCRYPT_CAAM the ``caam`` backend, of tier ``engine``, is
+available, built in or as the module ``keycrypt_caam``, for NXP SoCs
+with a CAAM. It has not been run on hardware: it is offered for owners
+of such boards to try.
+
+Its keys are AES-256 keys for ``aes256-cbc`` only. A new key is drawn
+with the kernel's random number generator and sealed at once; an
+imported one is sealed as given. Sealing makes the CAAM store the key as
+a black key (encrypted under a key that never leaves the CAAM, with ECB:
+the CAAM driver's ``cbc(paes)`` refuses CCM black keys) inside a CAAM
+blob whose key modifier is derived from the blob's header::
+
+ key modifier = first 16 bytes of SHA-256("keycrypt caam v1" || header)
+
+The backend data is a version byte, the black key's encoding, the key
+size (le16) and the 80-byte blob. A blob whose header was changed, or,
+on a CAAM in secure or trusted mode, a blob of another device, does not
+open: past the core's own checks, ``load`` fails with ``EBADMSG``. Of
+the CAAM driver's algorithms, only its internal ``cbc(paes)``, which
+AF_ALG cannot allocate, opens such a blob. The blobs of the public
+``cbc(paes)`` and of trusted keys with the ``pk`` option use the key
+modifier "SECURE_KEY", so neither kind opens as the other; a trusted
+``pk`` load copies any blob without opening it, so a keycrypt blob given
+to one is accepted there and fails when the key is used.
+
+The key is in clear in kernel memory only while a new one is drawn or
+one given to import is sealed, apart from the CAAM driver's limits
+below. After that the kernel holds the blob and, in the CAAM driver's
+state, the black key, which protect the key as far as the CAAM's own
+properties do: a black blob must not open as a red one, nor a black key
+be exported, and this backend does not check either when it runs.
+The use of a key is decided by the
+kernel: the CAAM runs whatever job the kernel submits, so the core's
+checks at ``KEYCTL_CRYPT_OPEN`` are the only ones, and a compromised
+kernel can encrypt with a decrypt-only key. That is the ``engine``
+tier. Where OP-TEE runs on the same SoC (OP-TEE derives its hardware
+unique key from the CAAM), the ``optee`` backend keeps the purpose in
+the secure world, and ``new`` with no option, or with
+``min-tier=engine``, chooses it over ``caam``; a program that wants the
+CAAM there all the same, for instance to avoid a call into the secure
+world at every operation, names it::
+
+ keyctl add keycrypt name "new aes256-cbc encrypt,decrypt backend=caam" ring
+
+The CAAM driver adds limits of its own:
+
+- On a CAAM in neither secure nor trusted mode (no closed secure boot),
+ blobs are sealed with a test key, protected by nothing, and the
+ driver writes "using insecure test key" to the kernel log at every
+ seal, which any local user can provoke with ``new``. A blob that
+ fails to open may make the driver log a job error.
+- With the driver's debug output enabled (CONFIG_CRYPTO_DEV_FSL_CAAM_DEBUG
+ or dynamic debug of the CAAM driver), it writes the key being sealed
+ to the kernel log.
+- Where its DMA goes through bounce buffers, copies of the data and,
+ when a seal fails, of the key may remain in them.
+- Unbinding the CAAM's job ring while ``keycrypt_caam`` is loaded leaves
+ the backend using freed state: do not.
+
+Every context holds a 64 KiB physically contiguous buffer, and every
+loaded key a CAAM transform; each update is one CAAM job, which opens
+the blob again. Load the module once the CAAM has probed: it registers
+only if a job ring with blob support and the CAAM's internal
+``cbc(paes)`` are there when it loads, and stays loaded but
+unregistered otherwise, saying why in the kernel log; built in, a CAAM
+whose probe was deferred leaves it unregistered.
+
Using a key
===========
@@ -838,7 +911,9 @@ EIO a backend failure
An altered blob may be refused before its backend sees it, with
``EOPNOTSUPP``, ``ENODEV``, ``EKEYREJECTED`` or ``EPERM``, rather than
``EBADMSG``; past those checks ``optee`` answers ``EBADMSG`` for any
-altered byte. For the kernel tier, an altered master description gives
+altered byte. For the caam backend, ``EBADMSG`` from ``load`` can also
+be a CAAM job error it cannot tell apart from a blob that does not
+open. For the sw backend, an altered master description gives
``ENOKEY`` only when the altered name exists nowhere in the caller's
search path; found there, it gives ``EACCES`` if the caller may not
search that key, or, found and searchable but not the master that
diff --git a/security/keys/keycrypt/Kconfig b/security/keys/keycrypt/Kconfig
index a6d8a0fa6d29..f661c8952142 100644
--- a/security/keys/keycrypt/Kconfig
+++ b/security/keys/keycrypt/Kconfig
@@ -124,3 +124,30 @@ config KEYCRYPT_OPTEE
which the driver finds on the TEE bus.
If you are unsure as to whether this is required, answer N.
+
+config KEYCRYPT_CAAM
+ tristate "Keycrypt keys held by the CAAM"
+ depends on KEYCRYPT && CRYPTO_DEV_FSL_CAAM_JR
+ depends on CRYPTO_DEV_FSL_CAAM_CRYPTO_API
+ select CRYPTO_DEV_FSL_CAAM_BLOB_GEN
+ select CRYPTO_LIB_SHA256
+ select CRYPTO_SKCIPHER
+ help
+ This option provides the "caam" keycrypt backend, of the engine
+ tier, for NXP SoCs with a CAAM: AES-256 keys sealed as CAAM black
+ blobs bound to their metadata, and used as black keys inside the
+ CAAM, so that the kernel holds a key in clear only while a new
+ one is drawn or one given to import is sealed (the documentation
+ lists the CAAM driver's exceptions). The CAAM does not check
+ what a key is used for: the keycrypt core does, so a
+ compromised kernel can use a decrypt-only key to encrypt. Where
+ OP-TEE runs, prefer the "optee" backend. Without secure boot the
+ CAAM seals with a test key, and such keys are protected by
+ nothing.
+
+ Build it as a module and load it once the CAAM has probed: it
+ registers only if a job ring with blob support and the CAAM's
+ internal cbc(paes) are there when it loads, and stays loaded but
+ unregistered otherwise, saying why in the kernel log.
+
+ If you are unsure as to whether this is required, answer N.
diff --git a/security/keys/keycrypt/Makefile b/security/keys/keycrypt/Makefile
index f051050428cd..4e2087fcaee8 100644
--- a/security/keys/keycrypt/Makefile
+++ b/security/keys/keycrypt/Makefile
@@ -5,3 +5,5 @@ obj-$(CONFIG_KEYCRYPT_SW) += keycrypt_sw.o
keycrypt_sw-y := sw.o
obj-$(CONFIG_KEYCRYPT_OPTEE) += keycrypt_optee.o
keycrypt_optee-y := optee.o
+obj-$(CONFIG_KEYCRYPT_CAAM) += keycrypt_caam.o
+keycrypt_caam-y := caam.o
diff --git a/security/keys/keycrypt/caam.c b/security/keys/keycrypt/caam.c
new file mode 100644
index 000000000000..d985cc38fe70
--- /dev/null
+++ b/security/keys/keycrypt/caam.c
@@ -0,0 +1,346 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * keycrypt - the CAAM backend: AES-256 keys sealed as CAAM black blobs,
+ * bound to the blob's header by their key modifier, and used as black
+ * keys through the CAAM's internal cbc(paes)
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
+ */
+
+#define pr_fmt(fmt) "keycrypt: " fmt
+
+#include <crypto/aes.h>
+#include <crypto/sha2.h>
+#include <crypto/skcipher.h>
+#include <keys/keycrypt.h>
+#include <linux/err.h>
+#include <linux/module.h>
+#include <linux/random.h>
+#include <linux/scatterlist.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+#include <linux/unaligned.h>
+#include "caam.h"
+
+/* The job ring blobs are sealed on, while the backend is registered */
+static struct caam_blob_priv *kc_caam_blob;
+
+/**
+ * struct kc_caam_ctx - a context
+ * @tfm: the key's, which outlives the context
+ * @iv: the CBC chain, advanced by every update
+ * @enc: encrypting, else decrypting
+ * @buf: KEYCRYPT_UPDATE_MAX bytes the CAAM reaches by DMA, which the
+ * core's kvmalloc()ed buffers may not allow
+ */
+struct kc_caam_ctx {
+ struct crypto_skcipher *tfm;
+ u8 iv[AES_BLOCK_SIZE];
+ bool enc;
+ u8 *buf;
+};
+
+/* The key modifier of a blob bound to @hdr: SHA-256(label || @hdr), cut */
+static void kc_caam_key_mod(const u8 *hdr, u32 hdr_len,
+ u8 km[CAAM_BLOB_KEYMOD_LENGTH])
+{
+ u8 d[SHA256_DIGEST_SIZE];
+ struct sha256_ctx ctx;
+
+ sha256_init(&ctx);
+ sha256_update(&ctx, (const u8 *)KC_CAAM_LABEL,
+ sizeof(KC_CAAM_LABEL) - 1);
+ sha256_update(&ctx, hdr, hdr_len);
+ sha256_final(&ctx, d);
+ memcpy(km, d, CAAM_BLOB_KEYMOD_LENGTH);
+ memzero_explicit(d, sizeof(d));
+}
+
+/* Seal @key, or a random key if NULL, as a black blob bound to @hdr */
+static int kc_caam_seal(const u8 *hdr, u32 hdr_len, const u8 *key,
+ struct keycrypt_blob *out)
+{
+ struct caam_blob_info info = {
+ .pkey_info = {
+ .is_pkey = 1,
+ .key_enc_algo = CAAM_ENC_ALGO_ECB,
+ .plain_key_sz = KC_CAAM_KEY_LEN,
+ },
+ .input_len = KC_CAAM_KEY_LEN,
+ .output_len = KC_CAAM_BLOB_LEN,
+ .key_mod_len = CAAM_BLOB_KEYMOD_LENGTH,
+ };
+ u8 km[CAAM_BLOB_KEYMOD_LENGTH];
+ u8 *in, *blob, *data;
+ int ret = -ENOMEM;
+
+ /* The CAAM reaches the first two by DMA: not on the stack */
+ in = kmalloc(KC_CAAM_KEY_LEN, GFP_KERNEL);
+ blob = kmalloc(KC_CAAM_BLOB_LEN, GFP_KERNEL);
+ data = kmalloc(KC_CAAM_DATA_LEN, GFP_KERNEL);
+ if (!in || !blob || !data)
+ goto out;
+ if (key) {
+ memcpy(in, key, KC_CAAM_KEY_LEN);
+ } else {
+ ret = get_random_bytes_wait(in, KC_CAAM_KEY_LEN);
+ if (ret)
+ goto out;
+ }
+ kc_caam_key_mod(hdr, hdr_len, km);
+ info.input = in;
+ info.output = blob;
+ info.key_mod = km;
+ ret = caam_encap_blob(kc_caam_blob, &info);
+ if (!ret && info.output_len != KC_CAAM_BLOB_LEN)
+ ret = -EIO;
+ if (ret) {
+ ret = ret == -ENOMEM ? ret : -EIO;
+ goto out;
+ }
+ data[KC_CAAM_OFF_VER] = KC_CAAM_VERSION;
+ data[KC_CAAM_OFF_ENC] = CAAM_ENC_ALGO_ECB;
+ put_unaligned_le16(KC_CAAM_KEY_LEN, data + KC_CAAM_OFF_SZ);
+ memcpy(data + KC_CAAM_OFF_BLOB, blob, KC_CAAM_BLOB_LEN);
+ out->data = data;
+ out->len = KC_CAAM_DATA_LEN;
+ data = NULL;
+out:
+ /* The key in clear, or the black key the CAAM wrote over it */
+ kfree_sensitive(in);
+ kfree(blob);
+ kfree(data);
+ return ret;
+}
+
+static int kc_caam_generate(struct keycrypt_backend *b,
+ const struct keycrypt_meta *m, const u8 *hdr,
+ u32 hdr_len, const char *opts,
+ struct keycrypt_blob *out)
+{
+ return kc_caam_seal(hdr, hdr_len, NULL, out);
+}
+
+static int kc_caam_import(struct keycrypt_backend *b,
+ const struct keycrypt_meta *m, const u8 *hdr,
+ u32 hdr_len, const char *opts, const u8 *key,
+ size_t keylen, struct keycrypt_blob *out)
+{
+ if (keylen != KC_CAAM_KEY_LEN)
+ return -EINVAL;
+ return kc_caam_seal(hdr, hdr_len, key, out);
+}
+
+/*
+ * One request on @tfm, in place on @buf (kmalloc()ed), waited for without
+ * a timeout: only the CAAM's own watchdog bounds it
+ */
+static int kc_caam_crypt(struct crypto_skcipher *tfm, u8 *iv, u8 *buf,
+ unsigned int len, bool enc)
+{
+ struct skcipher_request *req;
+ DECLARE_CRYPTO_WAIT(wait);
+ struct scatterlist sg;
+ int ret;
+
+ req = skcipher_request_alloc(tfm, GFP_KERNEL);
+ if (!req)
+ return -ENOMEM;
+ sg_init_one(&sg, buf, len);
+ skcipher_request_set_callback(req, CRYPTO_TFM_REQ_MAY_BACKLOG |
+ CRYPTO_TFM_REQ_MAY_SLEEP,
+ crypto_req_done, &wait);
+ skcipher_request_set_crypt(req, &sg, &sg, len, iv);
+ ret = crypto_wait_req(enc ? crypto_skcipher_encrypt(req) :
+ crypto_skcipher_decrypt(req), &wait);
+ skcipher_request_free(req);
+ return ret;
+}
+
+static int kc_caam_load(struct keycrypt_backend *b, struct keycrypt_key *k,
+ const char *opts)
+{
+ struct caam_pkey_info pi = {
+ .is_pkey = 1,
+ .key_enc_algo = CAAM_ENC_ALGO_ECB,
+ .plain_key_sz = KC_CAAM_KEY_LEN,
+ };
+ u8 iv[AES_BLOCK_SIZE] = {};
+ struct crypto_skcipher *tfm;
+ u8 *key = NULL, *probe = NULL;
+ int ret;
+
+ /* Not the CAAM's: the blob is all it authenticates */
+ if (k->data_len != KC_CAAM_DATA_LEN ||
+ k->data[KC_CAAM_OFF_VER] != KC_CAAM_VERSION ||
+ k->data[KC_CAAM_OFF_ENC] != CAAM_ENC_ALGO_ECB ||
+ get_unaligned_le16(k->data + KC_CAAM_OFF_SZ) != KC_CAAM_KEY_LEN)
+ return -EBADMSG;
+
+ tfm = crypto_alloc_skcipher(KC_CAAM_ALG, CRYPTO_ALG_INTERNAL,
+ CRYPTO_ALG_INTERNAL);
+ if (IS_ERR(tfm))
+ return PTR_ERR(tfm) == -ENOMEM ? -ENOMEM : -EIO;
+
+ ret = -ENOMEM;
+ key = kmalloc(CAAM_PKEY_KM_HEADER + KC_CAAM_BLOB_LEN, GFP_KERNEL);
+ probe = kzalloc(AES_BLOCK_SIZE, GFP_KERNEL);
+ if (!key || !probe)
+ goto out;
+ memcpy(key, &pi, CAAM_PKEY_HEADER);
+ kc_caam_key_mod(k->hdr, k->hdr_len, key + CAAM_PKEY_HEADER);
+ memcpy(key + CAAM_PKEY_KM_HEADER, k->data + KC_CAAM_OFF_BLOB,
+ KC_CAAM_BLOB_LEN);
+ ret = crypto_skcipher_setkey(tfm, key,
+ CAAM_PKEY_KM_HEADER + KC_CAAM_BLOB_LEN);
+ if (ret) {
+ ret = -EIO;
+ goto out;
+ }
+ ret = kc_caam_crypt(tfm, iv, probe, AES_BLOCK_SIZE, true);
+ /*
+ * A CAAM job status (-EBADMSG for an ICV failure, -EINVAL otherwise)
+ * is taken as a blob that does not open with this header's key
+ * modifier; a failure to submit the job is not
+ */
+ if (ret == -EINVAL)
+ ret = -EBADMSG;
+ else if (ret && ret != -EBADMSG && ret != -ENOMEM)
+ ret = -EIO;
+out:
+ kfree(key);
+ /* E_K(0): not secret */
+ kfree(probe);
+ if (ret) {
+ crypto_free_skcipher(tfm);
+ return ret;
+ }
+ k->priv = tfm;
+ return 0;
+}
+
+static void kc_caam_destroy(struct keycrypt_backend *b,
+ struct keycrypt_key *k)
+{
+ crypto_free_skcipher(k->priv);
+ k->priv = NULL;
+}
+
+static int kc_caam_ctx_open(struct keycrypt_backend *b,
+ struct keycrypt_key *k, u32 op, u8 *iv,
+ void **ctx)
+{
+ struct kc_caam_ctx *c;
+
+ if (op != KEYCRYPT_OP_ENCRYPT && op != KEYCRYPT_OP_DECRYPT)
+ return -EIO;
+ c = kzalloc_obj(*c, GFP_KERNEL_ACCOUNT);
+ if (!c)
+ return -ENOMEM;
+ c->buf = kmalloc(KEYCRYPT_UPDATE_MAX,
+ GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
+ if (!c->buf) {
+ kfree(c);
+ return -ENOMEM;
+ }
+ c->tfm = k->priv;
+ memcpy(c->iv, iv, AES_BLOCK_SIZE);
+ c->enc = op == KEYCRYPT_OP_ENCRYPT;
+ *ctx = c;
+ return 0;
+}
+
+static int kc_caam_update(struct keycrypt_backend *b, void *ctx,
+ const u8 *in, u8 *out, size_t len)
+{
+ struct kc_caam_ctx *c = ctx;
+ int ret;
+
+ if (len > KEYCRYPT_UPDATE_MAX || len % AES_BLOCK_SIZE)
+ return -EIO;
+ if (!len)
+ return 0;
+ memcpy(c->buf, in, len);
+ ret = kc_caam_crypt(c->tfm, c->iv, c->buf, len, c->enc);
+ if (!ret)
+ memcpy(out, c->buf, len);
+ memzero_explicit(c->buf, len);
+ return ret;
+}
+
+static int kc_caam_final(struct keycrypt_backend *b, void *ctx, u8 *out,
+ size_t out_size, size_t *len)
+{
+ *len = 0;
+ return 0;
+}
+
+static void kc_caam_ctx_free(struct keycrypt_backend *b, void *ctx)
+{
+ struct kc_caam_ctx *c = ctx;
+
+ kfree(c->buf); /* wiped after every update */
+ kfree_sensitive(c);
+}
+
+static struct keycrypt_backend keycrypt_caam = {
+ .name = "caam",
+ .tier = KEYCRYPT_TIER_ENGINE,
+ .algs = BIT(KEYCRYPT_ALG_AES256_CBC),
+ .owner = THIS_MODULE,
+ .generate = kc_caam_generate,
+ .import = kc_caam_import,
+ .load = kc_caam_load,
+ .destroy = kc_caam_destroy,
+ .ctx_open = kc_caam_ctx_open,
+ .update = kc_caam_update,
+ .final = kc_caam_final,
+ .ctx_free = kc_caam_ctx_free,
+};
+
+/*
+ * Without a CAAM the module stays loaded with the backend unregistered,
+ * and says why in the log
+ */
+static int __init kc_caam_init(void)
+{
+ struct caam_blob_priv *blob;
+ int ret;
+
+ blob = caam_blob_gen_init();
+ if (IS_ERR(blob)) {
+ pr_info("caam backend not registered: no CAAM job ring with blob support\n");
+ return 0;
+ }
+ if (!crypto_has_skcipher(KC_CAAM_ALG, CRYPTO_ALG_INTERNAL,
+ CRYPTO_ALG_INTERNAL)) {
+ pr_info("caam backend not registered: no %s\n", KC_CAAM_ALG);
+ caam_blob_gen_exit(blob);
+ return 0;
+ }
+ kc_caam_blob = blob;
+ ret = keycrypt_register_backend(&keycrypt_caam);
+ if (ret) {
+ kc_caam_blob = NULL;
+ caam_blob_gen_exit(blob);
+ }
+ return ret;
+}
+
+/*
+ * Built in: after the job-ring driver registered; a CAAM whose probe was
+ * deferred is not there yet
+ */
+late_initcall(kc_caam_init);
+
+static void __exit kc_caam_exit(void)
+{
+ if (!kc_caam_blob)
+ return;
+ keycrypt_unregister_backend(&keycrypt_caam);
+ caam_blob_gen_exit(kc_caam_blob);
+}
+module_exit(kc_caam_exit);
+
+MODULE_DESCRIPTION("keycrypt CAAM backend");
+MODULE_LICENSE("GPL");
diff --git a/security/keys/keycrypt/caam.h b/security/keys/keycrypt/caam.h
new file mode 100644
index 000000000000..ebefa1dcff2e
--- /dev/null
+++ b/security/keys/keycrypt/caam.h
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * keycrypt - the CAAM backend's data layout
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
+ */
+
+#ifndef _SECURITY_KEYS_KEYCRYPT_CAAM_H
+#define _SECURITY_KEYS_KEYCRYPT_CAAM_H
+
+#include <soc/fsl/caam-blob.h>
+
+/* Hashed with the header into the key modifier; "v1" names this layout */
+#define KC_CAAM_LABEL "keycrypt caam v1"
+
+/* The CAAM's internal cbc(paes), which takes the blob's key modifier */
+#define KC_CAAM_ALG "cbc-paes-km-caam"
+
+#define KC_CAAM_VERSION 1
+#define KC_CAAM_KEY_LEN 32 /* AES-256 */
+#define KC_CAAM_BLOB_LEN (KC_CAAM_KEY_LEN + CAAM_BLOB_OVERHEAD)
+
+/* The backend's data: version, key encoding, key size (le16), black blob */
+#define KC_CAAM_OFF_VER 0
+#define KC_CAAM_OFF_ENC 1
+#define KC_CAAM_OFF_SZ 2
+#define KC_CAAM_OFF_BLOB 4
+#define KC_CAAM_DATA_LEN (KC_CAAM_OFF_BLOB + KC_CAAM_BLOB_LEN)
+
+#endif /* _SECURITY_KEYS_KEYCRYPT_CAAM_H */
--
2.43.0
^ permalink raw reply related [flat|nested] 14+ messages in thread
* [RFC PATCH 9/9] KEYS: keycrypt: Add the aes256-gcm-stream algorithm
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
` (7 preceding siblings ...)
2026-11-18 14:11 ` [RFC PATCH 8/9] KEYS: keycrypt: Add the CAAM backend Rodolfo Giometti
@ 2026-11-18 14:12 ` Rodolfo Giometti
2026-11-18 14:31 ` [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Jarkko Sakkinen
2026-11-18 14:57 ` Marco Felsch
10 siblings, 0 replies; 14+ messages in thread
From: Rodolfo Giometti @ 2026-11-18 14:12 UTC (permalink / raw)
To: David Howells, Jarkko Sakkinen, keyrings
Cc: Herbert Xu, David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, Rodolfo Giometti
This patch is a proposal on its own: nothing before it needs it, so it
can be discussed, or left out, apart from the rest.
aes256-cbc does not authenticate what it decrypts, and a file or a
transfer longer than one call cannot be sealed with a single AES-GCM
invocation without buffering all of it, nor decrypted without
releasing plaintext before its tag is checked.
Add aes256-gcm-stream: the STREAM construction (Hoang, Reyhanitabar,
Rogaway, Vizar) over AES-256-GCM. A message is split into segments
of up to 64 KiB, each sealed with its own tag under a subkey derived
with HKDF-SHA256 from the key and a 16-byte salt drawn at
KEYCTL_CRYPT_OPEN; the nonce carries the segment's position and a
last-segment flag, and the counter lives in the kernel, so segments
can be neither reordered nor dropped from the end unnoticed. The
segments go through a new ioctl, KEYCRYPT_IOC_SEGMENT, and
KEYCRYPT_IOC_FINAL reports a stream whose last segment never came.
A tee or hsm backend draws the salt and keeps the counter in its
secure side; the sw and optee backends implement it.
With it comes its section of the documentation, with a file format
built on it.
No user-space consumer uses it yet.
Signed-off-by: Rodolfo Giometti <giometti@enneenne.com>
---
Documentation/security/keys/keycrypt.rst | 244 ++++++++++++++++++++---
include/keys/keycrypt.h | 15 +-
include/uapi/linux/keycrypt.h | 43 +++-
security/keys/keycrypt/core.c | 3 +
security/keys/keycrypt/ctx.c | 139 ++++++++++++-
security/keys/keycrypt/keycrypt.h | 5 +
security/keys/keycrypt/optee.c | 70 ++++++-
security/keys/keycrypt/optee.h | 4 +-
security/keys/keycrypt/sw.c | 68 ++++++-
9 files changed, 541 insertions(+), 50 deletions(-)
diff --git a/Documentation/security/keys/keycrypt.rst b/Documentation/security/keys/keycrypt.rst
index e2ee5f75d9f4..02b5e82f355c 100644
--- a/Documentation/security/keys/keycrypt.rst
+++ b/Documentation/security/keys/keycrypt.rst
@@ -84,8 +84,8 @@ the key's purpose and the key's tier against the caller's
``KEYCTL_CRYPT_OPEN`` (`Using a key`_); and, at
``keycrypt_register_backend()``, that a backend declares a valid tier,
offers ``generate`` and ``load``, the four context callbacks all or
-none and, for a ``tee`` or ``hsm`` backend with context operations,
-``verify`` for hmac-sha256. None of
+none, ``aead`` for aes256-gcm-stream and, for a ``tee`` or ``hsm``
+backend with context operations, ``verify`` for hmac-sha256. None of
that defends against a *compromised kernel*: the core is kernel code
too, and a kernel that lies to itself can skip or fake any check it
runs itself.
@@ -102,7 +102,11 @@ itself does what the core has no way to check:
- fixes the operation for a context at ``ctx_open`` and holds to it,
refusing ``final`` on a context it fixed for VERIFY and ``verify``
on any other;
-- fixes the length of a MAC or VERIFY tag.
+- fixes the length of a MAC or VERIFY tag;
+- keeps the aes256-gcm-stream segment counter and whether the last
+ segment was seen in the secure world rather than trusting them from
+ the caller, and draws there the salt to encrypt;
+- zeroes its output when a tag fails to verify.
A backend declares its own tier at ``keycrypt_register_backend()``; the
core stores and compares it wherever a tier is checked, but never
@@ -119,8 +123,8 @@ Metadata
========
========= ======================================================
-algorithm ``aes256-cbc`` or ``hmac-sha256``
-purpose ``encrypt``, ``decrypt`` (aes256-cbc);
+algorithm ``aes256-cbc``, ``aes256-gcm-stream`` or ``hmac-sha256``
+purpose ``encrypt``, ``decrypt`` (aes256-cbc, aes256-gcm-stream);
``mac``, ``verify``, or both (hmac-sha256)
tier the backend's, when the key was sealed
backend its name
@@ -134,6 +138,12 @@ purpose, tier and origin instead as the numeric ``KEYCRYPT_ALG_*``,
``KEYCRYPT_PURPOSE_*``, ``KEYCRYPT_TIER_*`` and ``KEYCRYPT_ORIGIN_*``
values of ``<linux/keycrypt.h>``.
+``aes256-gcm-stream`` names keycrypt's own STREAM construction over
+AES-256-GCM, run under a per-stream subkey derived with HKDF
+(`Authenticated streams (aes256-gcm-stream)`_); it is not interoperable
+with a plain AES-GCM implementation, and a different construction, even
+one also built on AES-256-GCM, gets a different name.
+
A key cannot be changed: ``keyctl update`` fails (``EACCES`` with the
default permissions, which give no write permission; ``EOPNOTSUPP``
otherwise). Adding a key with the same description to the same keyring
@@ -246,8 +256,8 @@ operation that moves a sealed key to another backend; the same material
imported again elsewhere is a new key.
``import`` needs CAP_SYS_ADMIN and CONFIG_KEYCRYPT_IMPORT (off by
-default); the key is 32 bytes for aes256-cbc, 1 to 64 bytes for
-hmac-sha256. The core's own copies of it are erased once the
+default); the key is 32 bytes for aes256-cbc and aes256-gcm-stream, 1 to
+64 bytes for hmac-sha256. The core's own copies of it are erased once the
backend has sealed it. Do not put a key in clear on a command line;
give the payload on standard input::
@@ -390,12 +400,15 @@ The TA meets `Backend requirements`_: at every ``KEYCTL_CRYPT_OPEN`` it
authenticates the blob's header again and checks the operation against
the purpose it reads there; a context is a TA session fixed to one
operation, refusing ``final`` on a VERIFY context and ``verify`` on any
-other; tags are 32 bytes. An aes256-cbc IV is used as given: to
+other; tags are 32 bytes for HMAC and 16 for the stream; the stream's
+salt to encrypt is drawn in the TA, its subkey derived there, and its
+segment counter and last segment kept there; a segment that fails to
+verify comes back zeroed. An aes256-cbc IV is used as given: to
encrypt, the core's random one or, with ``KEYCRYPT_OPEN_CALLER_IV``, the
caller's; to decrypt, the caller's.
-Every context holds a TA session and 65,584 bytes of TEE shared memory,
-rounded up to whole pages and physically contiguous (68 KiB with 4 KiB
+Every context holds a TA session and 69,680 bytes of TEE shared memory,
+rounded up to whole pages and physically contiguous (72 KiB with 4 KiB
pages), until the context ends (``KEYCRYPT_IOC_FINAL``, or a failure),
its key is revoked, or its fd is closed, whichever comes first. The TA
refuses a session once 32 are open (``KC_TA_SESSIONS_MAX``), the
@@ -506,9 +519,15 @@ A key is used through an operation context, a file descriptor opened by
*/
__u32 flags; /* KEYCRYPT_OPEN_CALLER_IV, or 0 */
__u32 __reserved; /* must be zero */
- __u8 iv[16]; /* aes256-cbc: the IV; MAC,
- * VERIFY: 0
- */
+ union {
+ __u8 iv[16]; /* aes256-cbc: the IV; MAC,
+ * VERIFY: 0
+ */
+ __u8 salt[16]; /* aes256-gcm-stream: the
+ * 16-byte stream salt; an
+ * alias of iv
+ */
+ };
};
``params`` is extended by size (``copy_struct_from_user()``): a caller
@@ -560,20 +579,38 @@ maintain (see `CBC and MAC`_). The flag is valid only together with
aes256-cbc encryption; any other combination is ``EINVAL``. For
aes256-cbc decryption ``iv`` is always the caller's.
+For aes256-gcm-stream, ``salt`` must be zero on input for encryption: the
+kernel draws a random 16-byte salt, or leaves whatever a backend that
+must draw its own has written there, and writes it back the same way as
+the aes256-cbc IV; whichever drew it, a salt that comes out all zero is
+refused with ``EIO`` and no fd is created (see `Authenticated streams
+(aes256-gcm-stream)`_). A ``tee`` or ``hsm`` backend must not leave the
+salt it draws itself all zero; the sw backend never touches ``salt`` at
+all, so there the same check instead guards against the core's own
+random draw coming out all zero, true with probability 2^-128.
+Decryption takes the salt the encryption side returned.
+
Data goes through ``ioctl()`` on the fd:
``KEYCRYPT_IOC_UPDATE`` (``struct keycrypt_update``: ``in``, ``out``, ``len``, ``flags``)
aes256-cbc and MAC/VERIFY only: process ``len`` bytes, at most
``KEYCRYPT_UPDATE_MAX`` (65536): for aes256-cbc a multiple of 16,
written to ``out``, the IV advancing in the context (padding is the
- caller's); for MAC and VERIFY ``out`` is 0.
+ caller's); for MAC and VERIFY ``out`` is 0. ``EINVAL`` on an
+ aes256-gcm-stream context.
``KEYCRYPT_IOC_FINAL`` (``struct keycrypt_final``: ``out``, ``len``, ``flags``)
end the context: for MAC write the 32-byte tag to ``out`` (``len``:
room in, bytes written out); for VERIFY ``out`` is the caller's
32-byte expected tag (``len`` must be exactly 32), written back as
- 0 on a match and left as given on a mismatch; for aes256-cbc
- ``out`` is 0, nothing is written to it, and ``len`` is written back
- as 0.
+ 0 on a match and left as given on a mismatch; for aes256-cbc and
+ aes256-gcm-stream ``out`` is 0, nothing is written to it, and
+ ``len`` is written back as 0; for aes256-gcm-stream, ``EBADMSG`` if
+ the stream's last segment was never processed (see `Authenticated
+ streams (aes256-gcm-stream)`_), 0 otherwise.
+``KEYCRYPT_IOC_SEGMENT`` (``struct keycrypt_segment``: ``in``, ``out``, ``aad``, ``tag``, ``len``, ``aad_len``, ``flags``)
+ aes256-gcm-stream only: process one authenticated segment of the
+ stream; ``EINVAL`` on any other context (see `Authenticated
+ streams (aes256-gcm-stream)`_).
``KEYCRYPT_IOC_INFO`` (``struct keycrypt_info``: ``op``, ``alg``, ``purpose``, ``tier``, ``origin``, ``accepted_min_tier``, ``backend``)
describe the context, whatever its algorithm or operation: the
operation it was opened for, the ``accepted_min_tier`` it was opened
@@ -587,8 +624,7 @@ Data goes through ``ioctl()`` on the fd:
``SCM_RIGHTS`` can tell what it holds (see `An fd is a shared
stream`_). On an ended context ``EBADFD``; on a context whose key
was revoked, invalidated or expired, or whose backend was removed,
- the ``EKEYREVOKED``, ``EKEYEXPIRED`` or ``ENODEV`` that UPDATE with
- no data gives.
+ ``EKEYREVOKED``, ``EKEYEXPIRED`` or ``ENODEV``.
VERIFY compares the expected tag against the one computed for it: by
the core, in constant time (``crypto_memneq()``), for a backend with no
@@ -729,7 +765,8 @@ An fd is a shared stream
========================
The fd from ``KEYCTL_CRYPT_OPEN`` carries the context's state (the IV,
-the running hash) outside the key itself: after ``SCM_RIGHTS`` or
+the running hash, a stream's salt and segment counter) outside the key
+itself: after ``SCM_RIGHTS`` or
``fork()``, every holder of a copy of the fd shares that state with
every other, and an ``ioctl()`` from any of them advances it for all.
Close the sending side's copy once sent, and receive with
@@ -772,6 +809,129 @@ differently (an aes256-cbc encryption context is a raw AES oracle on
the key, above), and every new pairing of algorithms would need its own
analysis that nothing here does.
+Authenticated streams (aes256-gcm-stream)
+=========================================
+
+An aes256-gcm-stream context runs the STREAM construction: a message is split
+into segments, each authenticated on its own, with a running counter and
+a per-segment flag standing in for the position that a single big
+AES-GCM invocation would get from encrypting the whole message at once.
+Every segment of a context runs under a per-stream subkey
+
+::
+
+ K_s = HKDF-SHA256(key, salt, "keycrypt aes256-gcm stream v1")
+
+derived from the key and the 16-byte salt returned at
+``KEYCTL_CRYPT_OPEN`` (`Using a key`_); the construction is keycrypt's
+own, the same in every backend, though each backend builds the nonce
+itself. ``KEYCRYPT_IOC_SEGMENT`` (``struct keycrypt_segment``) processes
+one segment: ``in``/``out`` are the plaintext and ciphertext (``len``
+bytes, at most ``KEYCRYPT_SEGMENT_MAX``), ``aad``/``aad_len`` is this
+segment's associated data (at most ``KEYCRYPT_AAD_MAX``), and ``tag`` is
+the ``KEYCRYPT_AEAD_TAG_LEN``-byte (16) tag: written by encryption, read
+by decryption. Segment *i*, counting from 0, is encrypted or decrypted
+under ``K_s`` and the nonce::
+
+ 0^7 || be32(i) || last
+
+``last`` is one byte, 1 for the segment flagged
+``KEYCRYPT_SEGMENT_LAST``, 0 otherwise. The counter lives in the
+kernel, advances by exactly one per accepted segment and is never
+exposed or settable by user space, so segments cannot be reordered or
+replayed against a decrypting context: decrypting segment *i* out of
+order fails its tag, since the nonce the kernel computes no longer
+matches the one encryption used at that position.
+
+Decryption never releases a segment's plaintext until its tag verifies:
+on ``EBADMSG`` the output buffer the kernel used is zeroed before the
+copy that never happens, and the context ends (every later call gives
+``EBADFD``). No segment is accepted after the one flagged LAST
+(``EBADFD``), but unlike the cases above this does not end the context:
+``KEYCRYPT_IOC_FINAL`` still works and ends it, itself detecting
+truncation: ``EBADMSG`` if no segment flagged LAST was ever processed, 0
+otherwise. The counter is 32 bits and runs from 0: segment number
+2^32-1, which would need to leave the counter at 2^32, gets
+``EOVERFLOW`` instead of silently wrapping it back to 0.
+``KEYCRYPT_IOC_UPDATE`` is ``EINVAL`` on an
+aes256-gcm-stream context, as is ``KEYCRYPT_IOC_SEGMENT`` on any other
+one.
+
+A fresh encryption context draws a fresh random 16-byte salt (`Using a
+key`_), unless its backend is of tier ``tee`` or ``hsm`` and meets
+`Backend requirements`_: such a backend draws the salt itself,
+overwriting whatever the core drew, and tracks the segment counter and
+whether the last segment was seen in the TEE or the hardware rather
+than the caller's, refusing a segment out of order or past the last
+one, so that a compromised kernel cannot make it reuse a nonce. The
+core itself, uncompromised, never calls a backend with such
+a segment: the counter lives in the kernel and is never set by user
+space, so this guards only against a compromised kernel, not a
+condition an ordinary caller can reach, and its refusal would reach
+user space as ``EIO`` like any other backend failure mid-context (see
+`Using a key`_), never as the backend's own internal error. A backend
+that drew the same salt for every stream instead of a fresh random one
+would reuse every nonce of every stream it opens; the core refuses a
+salt that comes out all zero, with ``EIO`` (`Using a key`_), which at
+least catches that case. Two streams under one key otherwise collide
+only if their salts do: about q^2/2^129 for q streams under that key,
+counting every device holding a copy of the key's blob; such a
+collision would reuse every nonce of the two streams. The salt needs no
+authentication of its own: a wrong salt derives the wrong subkey, which
+fails segment 0's tag.
+
+A decrypt-only aes256-gcm-stream key cannot be made to forge, unlike an
+aes256-cbc decryption key (`CBC and MAC`_), which is what an
+update-bundle verifier relies on: the property holds against a
+compromised device's own user space. It does not extend to a
+kernel-tier key shared across a fleet: that key is in clear in kernel
+memory on every device, so a compromised kernel on any one device can
+forge for the whole fleet. A fleet that must survive a compromised
+device wants a ``tee`` or ``hsm`` key, or signatures, instead: a
+``tee``/``hsm`` backend meeting `Backend requirements`_ surviving a
+compromised kernel is exactly why it checks the operation, in the TEE
+or the hardware, against the key's own purpose bound there, rather
+than trusting the kernel's copy of it (`Using a key`_).
+
+The stream is not key-committing: a segment's tag does not prove which
+key, among several a format might try, produced it. A format that may
+try several keys must pick the right one another way (e.g. a key
+identifier in the header) and never rely on a tag for that choice.
+
+The backend, not the core, builds the nonce: for a ``tee`` or ``hsm``
+backend, both the salt and the segment ordering are the backend's own
+(above); a backend of a lower tier, ``engine`` or ``kernel`` (the sw
+backend), draws neither itself and relies on the core's randomness and
+counter instead. The fd shares the salt and the counter
+between its holders (`An fd is a shared stream`_), safely, since calls
+on one fd are serialised.
+
+A file format built on it
+--------------------------
+
+An application such as an archive tool or an update bundle installer
+can build a file format directly on ``KEYCRYPT_IOC_SEGMENT``,
+informatively: the format is written and read in order, segment by
+segment; the counter cannot be set by encryption, by design, nor by
+decryption, for now (a decrypt-side seek could come later through
+``__reserved`` and a flag). A fixed header (a magic value per format,
+a format version or anti-rollback field the application checks, the
+segment size, the 16-byte salt, plus whatever metadata the format
+needs) is given as the associated data of segment 0, authenticating it
+without encrypting it, and cannot be patched afterwards; the rest of
+the file is segments of ``ciphertext || tag``, in order, the last one
+flagged. No header field but those needed to find segment 0 should be
+acted on before segment 0 verifies, and one key should never serve two
+formats, so that a blob valid for one cannot be replayed as another's.
+
+Decryption streams while reading: each segment's plaintext is usable as
+soon as its tag verifies, with no need to buffer the whole file first.
+Whatever the application does with a segment's plaintext before the
+stream's last segment verifies must be undoable: a file truncated by a
+failed write or a cut transfer is caught only at
+``KEYCRYPT_IOC_FINAL`` (0 once the last segment has verified), and
+closing the fd without calling it detects nothing.
+
Why not AF_ALG or KEYCTL_PKEY_*
================================
@@ -784,9 +944,10 @@ in the kernel too: a skcipher socket's IV buffer lives in the socket
and is advanced in place as the cipher mode chains across calls, the
same state keycrypt keeps in its context. The difference is that
``AF_ALG`` never *chooses* an IV itself: it is always the caller's,
-zero by default and otherwise set with ``ALG_SET_IV``; keycrypt
-instead draws a random IV itself at ``KEYCTL_CRYPT_OPEN`` unless the
-caller asks for its own
+zero by default and otherwise set with ``ALG_SET_IV``, and an AEAD
+socket takes the caller's nonce on every request rather than drawing
+one; keycrypt instead draws a random IV or salt itself at
+``KEYCTL_CRYPT_OPEN`` unless the caller asks for its own
(``KEYCRYPT_OPEN_CALLER_IV``, aes256-cbc encryption only). ``AF_ALG``
also copies the key's payload into the socket and applies whatever
algorithm the socket was set up for, with nothing tying the key to
@@ -816,18 +977,32 @@ EINVAL ``__reserved`` or flags not zero, an unknown operation, an
``accepted_min_tier`` that is neither 0 nor a tier, an IV
given for MAC or VERIFY, a non-zero IV given
for CBC encryption without ``KEYCRYPT_OPEN_CALLER_IV``,
- or that flag with anything but CBC encryption; a CBC length
- not a multiple of 16, an ``out`` given for MAC or for
- aes256-cbc FINAL, or missing for CBC UPDATE; VERIFY FINAL
- with ``len`` other than 32; a ``usize`` below
+ that flag with anything but CBC encryption, or a non-zero
+ salt for aes256-gcm-stream encryption; a CBC length not a
+ multiple of 16, an ``out`` given for MAC or for
+ aes256-cbc or aes256-gcm-stream FINAL, or missing for CBC
+ UPDATE; VERIFY FINAL with ``len`` other than 32;
+ ``KEYCRYPT_IOC_UPDATE`` on an aes256-gcm-stream context,
+ or ``KEYCRYPT_IOC_SEGMENT`` on any other one; a segment's
+ flags other than ``KEYCRYPT_SEGMENT_LAST``, its
+ ``__reserved`` non-zero, its ``aad_len`` above
+ ``KEYCRYPT_AAD_MAX``, a ``tag`` of 0, a ``len`` given
+ without ``in`` or ``out``, or an ``aad_len`` given
+ without ``aad``; a ``usize`` below
``KEYCRYPT_OPEN_PARAMS_SIZE_VER0``
E2BIG ``usize`` above ``PAGE_SIZE``, or a non-zero byte in its
excess over this kernel's ``struct keycrypt_open_params``;
- a ``len`` above ``KEYCRYPT_UPDATE_MAX``
+ a ``len`` above ``KEYCRYPT_UPDATE_MAX`` (UPDATE) or
+ ``KEYCRYPT_SEGMENT_MAX`` (SEGMENT)
+EOVERFLOW the aes256-gcm-stream segment counter would wrap: segment
+ number 2^32-1 on this context
ENOSPC MAC FINAL with ``out`` 0, or less than 32 bytes of room for
the tag (the context stays usable)
EBADMSG VERIFY FINAL whose tag does not match (the context ends);
- a backend's own
+ an aes256-gcm-stream segment whose tag does not match
+ (nothing is released, the context ends); aes256-gcm-stream
+ FINAL without a segment flagged ``KEYCRYPT_SEGMENT_LAST``
+ (truncation; the context ends); a backend's own
``EBADMSG`` from ``KEYCTL_CRYPT_OPEN`` (no fd is created)
or from ``KEYCRYPT_IOC_UPDATE`` (the context ends)
EKEYREVOKED the key was revoked, its type removed, or (an already
@@ -852,14 +1027,19 @@ EIO a backend failure, including one refusing at
``KEYCTL_CRYPT_OPEN`` itself: a backend's ``ENOMEM``,
``EINTR`` and ``EBADMSG`` pass unchanged (a restart it
asks for restarts the call), any other error becomes
- ``EIO`` (no fd is created either way)
-EBADFD a call on a context that already ended: after
+ ``EIO`` (no fd is created either way); or
+ (``KEYCTL_CRYPT_OPEN``, aes256-gcm-stream encryption
+ only) a salt that comes out all zero, whatever the
+ backend's tier
+EBADFD a segment past the one flagged ``KEYCRYPT_SEGMENT_LAST``,
+ which the context survives (``KEYCRYPT_IOC_FINAL`` still
+ works); or a call on a context that already ended: after
FINAL, or after a failure once the backend had been
called for this call (``EBADMSG``, ``EIO``, an
``EFAULT`` on the output copy, or ``EINTR`` from an
interrupted backend). Every other error leaves the
context usable too: ``EINVAL``, ``E2BIG``, ``ENOSPC``,
- an ``EFAULT`` on the input copy or on
+ ``EOVERFLOW``, an ``EFAULT`` on the input copy or on
``KEYCRYPT_IOC_INFO``'s output copy, ``ENOMEM`` before
the backend ran, ``EKEYREVOKED``, ``EKEYEXPIRED`` and
``ENODEV`` (repeated instead, above), and ``EINTR`` while
diff --git a/include/keys/keycrypt.h b/include/keys/keycrypt.h
index 8aae3d47e697..eae6010c678c 100644
--- a/include/keys/keycrypt.h
+++ b/include/keys/keycrypt.h
@@ -16,7 +16,8 @@ struct module;
struct keycrypt_handle;
#define KEYCRYPT_ALGS_ALL (BIT(KEYCRYPT_ALG_AES256_CBC) | \
- BIT(KEYCRYPT_ALG_HMAC_SHA256))
+ BIT(KEYCRYPT_ALG_HMAC_SHA256) | \
+ BIT(KEYCRYPT_ALG_AES256_GCM_STREAM))
#define KEYCRYPT_BACKEND_DATA_MAX 4096
@@ -75,6 +76,9 @@ struct keycrypt_key {
void *priv;
};
+/* The STREAM subkey's HKDF info string, fixed by the protocol */
+#define KEYCRYPT_STREAM_INFO "keycrypt aes256-gcm stream v1"
+
/**
* struct keycrypt_backend - a place where keycrypt keys live
* @name: [a-z0-9_-], at most KEYCRYPT_BACKEND_NAME_MAX; it names a sealing
@@ -91,7 +95,8 @@ struct keycrypt_key {
* set @k->priv if needed, leaving it unset on failure
* @destroy: release @k->priv; called at most once per key, and last
* @ctx_open: start @op on @k and set *@ctx, releasing what it acquired on
- * failure; @iv (16 bytes) is the aes256-cbc IV, used as given
+ * failure; @iv (16 bytes) is the aes256-cbc IV, used as given, or the
+ * aes256-gcm-stream salt, which a backend drawing its own may overwrite
* @update: process @len bytes from @in to @out, in place allowed; @out is
* NULL for MAC and VERIFY
* @final: end the context; MAC and VERIFY write the 32-byte tag to @out
@@ -100,6 +105,9 @@ struct keycrypt_key {
* the key lives, 0 or -EBADMSG, never the tag. Required of a _TEE or
* _HSM backend with context callbacks offering hmac-sha256
* @ctx_free: release @ctx, once, however the context ends
+ * @aead: seal or open segment @seq of an aes256-gcm-stream (@last for the
+ * final one) as keycrypt.rst describes, writing or checking @tag;
+ * -EBADMSG leaves @out zeroed. Required for aes256-gcm-stream
* @handle: core private
*
* @opts given to a callback are the "key=value" options the core did not
@@ -140,6 +148,9 @@ struct keycrypt_backend {
int (*verify)(struct keycrypt_backend *b, void *ctx,
const u8 *expected);
void (*ctx_free)(struct keycrypt_backend *b, void *ctx);
+ int (*aead)(struct keycrypt_backend *b, void *ctx, u32 seq, bool last,
+ const u8 *aad, size_t aad_len, const u8 *in, u8 *out,
+ size_t len, u8 *tag);
struct keycrypt_handle *handle;
};
diff --git a/include/uapi/linux/keycrypt.h b/include/uapi/linux/keycrypt.h
index 71209a08c924..3d5716b2147e 100644
--- a/include/uapi/linux/keycrypt.h
+++ b/include/uapi/linux/keycrypt.h
@@ -39,6 +39,7 @@
/* struct keycrypt_info: the key's algorithm */
#define KEYCRYPT_ALG_AES256_CBC 1
#define KEYCRYPT_ALG_HMAC_SHA256 2
+#define KEYCRYPT_ALG_AES256_GCM_STREAM 3
/* struct keycrypt_info: the key's purpose mask */
#define KEYCRYPT_PURPOSE_ENCRYPT 0x0001
@@ -66,6 +67,9 @@
* @iv: aes256-cbc: the IV, given for decryption and with
* KEYCRYPT_OPEN_CALLER_IV, otherwise written back by the kernel; MAC
* and VERIFY: zero
+ * @salt: aes256-gcm-stream: the stream's KEYCRYPT_STREAM_SALT_LEN-byte
+ * salt, given for decryption, written back for encryption; an alias
+ * of @iv (one 16-byte field, named for the algorithm it is used with)
*
* Extended by size (copy_struct_from_user()); at least
* KEYCRYPT_OPEN_PARAMS_SIZE_VER0 bytes.
@@ -75,7 +79,10 @@ struct keycrypt_open_params {
__u32 accepted_min_tier;
__u32 flags;
__u32 __reserved;
- __u8 iv[16];
+ union {
+ __u8 iv[16]; /* aes256-cbc */
+ __u8 salt[16]; /* aes256-gcm-stream */
+ };
};
#define KEYCRYPT_OPEN_PARAMS_SIZE_VER0 32
@@ -98,7 +105,7 @@ struct keycrypt_update {
* struct keycrypt_final - KEYCRYPT_IOC_FINAL argument
* @out: user pointer; MAC: the tag, written, @len room in, bytes out;
* VERIFY: the expected 32-byte tag, read, @len must be 32, 0 back;
- * aes256-cbc: 0, and @len comes back 0
+ * aes256-cbc and aes256-gcm-stream: 0, and @len comes back 0
* @len: see @out
* @flags: must be zero
*/
@@ -111,6 +118,36 @@ struct keycrypt_final {
#define KEYCRYPT_UPDATE_MAX 65536
#define KEYCRYPT_MAC_LEN 32
+/**
+ * struct keycrypt_segment - KEYCRYPT_IOC_SEGMENT argument (aes256-gcm-stream)
+ * @in: user pointer to @len input bytes
+ * @out: user pointer to @len output bytes
+ * @aad: user pointer to @aad_len bytes of associated data, or 0
+ * @tag: user pointer to the KEYCRYPT_AEAD_TAG_LEN-byte tag: written when
+ * encrypting, read when decrypting
+ * @len: bytes, at most KEYCRYPT_SEGMENT_MAX
+ * @aad_len: bytes, at most KEYCRYPT_AAD_MAX
+ * @flags: KEYCRYPT_SEGMENT_LAST for the stream's last segment
+ * @__reserved: must be zero
+ */
+struct keycrypt_segment {
+ __u64 in;
+ __u64 out;
+ __u64 aad;
+ __u64 tag;
+ __u32 len;
+ __u32 aad_len;
+ __u32 flags;
+ __u32 __reserved;
+};
+
+#define KEYCRYPT_SEGMENT_LAST 0x0001
+
+#define KEYCRYPT_SEGMENT_MAX 65536
+#define KEYCRYPT_AAD_MAX 4096
+#define KEYCRYPT_AEAD_TAG_LEN 16
+#define KEYCRYPT_STREAM_SALT_LEN 16
+
/**
* struct keycrypt_info - KEYCRYPT_IOC_INFO argument, written by the kernel
* @op: KEYCRYPT_OP_* the context was opened for
@@ -139,7 +176,7 @@ struct keycrypt_info {
#define KEYCRYPT_IOC_MAGIC 0xBB
#define KEYCRYPT_IOC_UPDATE _IOW(KEYCRYPT_IOC_MAGIC, 1, struct keycrypt_update)
#define KEYCRYPT_IOC_FINAL _IOWR(KEYCRYPT_IOC_MAGIC, 2, struct keycrypt_final)
-/* 3: KEYCRYPT_IOC_SEGMENT, with the aes256-gcm-stream algorithm */
+#define KEYCRYPT_IOC_SEGMENT _IOW(KEYCRYPT_IOC_MAGIC, 3, struct keycrypt_segment)
#define KEYCRYPT_IOC_INFO _IOR(KEYCRYPT_IOC_MAGIC, 4, struct keycrypt_info)
#endif /* _UAPI_LINUX_KEYCRYPT_H */
diff --git a/security/keys/keycrypt/core.c b/security/keys/keycrypt/core.c
index 4a2609c6830f..916fa329293d 100644
--- a/security/keys/keycrypt/core.c
+++ b/security/keys/keycrypt/core.c
@@ -36,6 +36,7 @@ struct keycrypt_name {
static const struct keycrypt_name keycrypt_algs[] = {
{ KEYCRYPT_ALG_AES256_CBC, "aes256-cbc" },
{ KEYCRYPT_ALG_HMAC_SHA256, "hmac-sha256" },
+ { KEYCRYPT_ALG_AES256_GCM_STREAM, "aes256-gcm-stream" },
};
static const struct keycrypt_name keycrypt_tiers[] = {
@@ -87,6 +88,7 @@ static bool keycrypt_purpose_valid(u8 alg, u16 purpose)
{
switch (alg) {
case KEYCRYPT_ALG_AES256_CBC:
+ case KEYCRYPT_ALG_AES256_GCM_STREAM:
return purpose && !(purpose & ~(KEYCRYPT_PURPOSE_ENCRYPT |
KEYCRYPT_PURPOSE_DECRYPT));
case KEYCRYPT_ALG_HMAC_SHA256:
@@ -410,6 +412,7 @@ int keycrypt_register_backend(struct keycrypt_backend *b)
!b->algs || (b->algs & ~KEYCRYPT_ALGS_ALL) ||
!b->generate || !b->load ||
((!!b->ctx_open + !!b->update + !!b->final + !!b->ctx_free) % 4) ||
+ ((b->algs & BIT(KEYCRYPT_ALG_AES256_GCM_STREAM)) && !b->aead) ||
(b->tier >= KEYCRYPT_TIER_TEE &&
b->ctx_open &&
(b->algs & BIT(KEYCRYPT_ALG_HMAC_SHA256)) && !b->verify))
diff --git a/security/keys/keycrypt/ctx.c b/security/keys/keycrypt/ctx.c
index ce62ba08479b..7addd0e75628 100644
--- a/security/keys/keycrypt/ctx.c
+++ b/security/keys/keycrypt/ctx.c
@@ -26,8 +26,12 @@
#include "../internal.h"
#include "keycrypt.h"
+static_assert(KEYCRYPT_STREAM_SALT_LEN ==
+ sizeof_field(struct keycrypt_open_params, salt));
static_assert(offsetofend(struct keycrypt_open_params, iv) ==
KEYCRYPT_OPEN_PARAMS_SIZE_VER0);
+static_assert(sizeof_field(struct keycrypt_open_params, iv) ==
+ sizeof_field(struct keycrypt_open_params, salt));
static_assert(KEYCRYPT_BACKEND_NAME_MAX <
sizeof_field(struct keycrypt_info, backend));
@@ -193,6 +197,8 @@ static long keycrypt_ioc_update(struct keycrypt_ctx *c,
bool ran = false;
long ret;
+ if (c->meta.alg == KEYCRYPT_ALG_AES256_GCM_STREAM)
+ return -EINVAL;
if (copy_from_user(&u, uarg, sizeof(u)))
return -EFAULT;
if (u.flags || (hmac && u.out) || (!hmac && u.len && !u.out) ||
@@ -310,6 +316,8 @@ static long keycrypt_ioc_final(struct keycrypt_ctx *c,
ret = -EFAULT;
goto wipe;
}
+ if (!ret && c->meta.alg == KEYCRYPT_ALG_AES256_GCM_STREAM)
+ ret = c->last_seen ? 0 : -EBADMSG;
if (!ret && len != (mac || verify ? KEYCRYPT_MAC_LEN : 0))
ret = -EIO;
if (!ret && verify && crypto_memneq(tag, expected, KEYCRYPT_MAC_LEN))
@@ -327,6 +335,111 @@ static long keycrypt_ioc_final(struct keycrypt_ctx *c,
return ret;
}
+/*
+ * Segment @seq of the stream; the backend derives the nonce. Encryption
+ * writes the ciphertext and its tag; decryption decrypts into a kernel
+ * buffer and copies it out only once the tag verifies. Nothing after the
+ * segment flagged LAST is accepted; aes256-gcm-stream only.
+ */
+static long keycrypt_ioc_segment(struct keycrypt_ctx *c,
+ struct keycrypt_segment __user *uarg)
+{
+ bool enc = c->op == KEYCRYPT_OP_ENCRYPT;
+ u8 tag[KEYCRYPT_AEAD_TAG_LEN];
+ u8 *in = NULL, *out = NULL, *aad = NULL;
+ struct keycrypt_backend *b;
+ struct keycrypt_segment s;
+ bool last, ran = false;
+ long ret;
+
+ if (c->meta.alg != KEYCRYPT_ALG_AES256_GCM_STREAM)
+ return -EINVAL;
+ if (copy_from_user(&s, uarg, sizeof(s)))
+ return -EFAULT;
+ if (s.__reserved || (s.flags & ~KEYCRYPT_SEGMENT_LAST) ||
+ s.aad_len > KEYCRYPT_AAD_MAX)
+ return -EINVAL;
+ if (s.len > KEYCRYPT_SEGMENT_MAX)
+ return -E2BIG;
+ if (!s.tag || (s.len && (!s.in || !s.out)) ||
+ (s.aad_len && !s.aad))
+ return -EINVAL;
+ last = s.flags & KEYCRYPT_SEGMENT_LAST;
+
+ ret = mutex_lock_killable(&c->lock);
+ if (ret)
+ return ret;
+ if (c->done || c->last_seen) {
+ ret = -EBADFD;
+ goto unlock;
+ }
+ ret = keycrypt_ctx_check(c);
+ if (ret)
+ goto unlock;
+ if (c->seq == U32_MAX) {
+ ret = -EOVERFLOW;
+ goto unlock;
+ }
+
+ if (s.len) {
+ in = kvmalloc(s.len, GFP_KERNEL_ACCOUNT);
+ out = kvmalloc(s.len, GFP_KERNEL_ACCOUNT);
+ if (!in || !out) {
+ ret = -ENOMEM;
+ goto free;
+ }
+ if (copy_from_user(in, u64_to_user_ptr(s.in), s.len)) {
+ ret = -EFAULT;
+ goto free;
+ }
+ }
+ if (s.aad_len) {
+ aad = kvmalloc(s.aad_len, GFP_KERNEL_ACCOUNT);
+ if (!aad) {
+ ret = -ENOMEM;
+ goto free;
+ }
+ if (copy_from_user(aad, u64_to_user_ptr(s.aad), s.aad_len)) {
+ ret = -EFAULT;
+ goto free;
+ }
+ }
+ if (!enc && copy_from_user(tag, u64_to_user_ptr(s.tag),
+ sizeof(tag))) {
+ ret = -EFAULT;
+ goto free;
+ }
+
+ down_read(&c->h->sem);
+ ret = keycrypt_ctx_backend(c, &b);
+ ran = !ret;
+ if (!ret)
+ ret = keycrypt_ctx_ret(b->aead(b, c->bctx, c->seq, last, aad,
+ s.aad_len, in, out, s.len,
+ tag));
+ up_read(&c->h->sem);
+
+ if (!ret && s.len && copy_to_user(u64_to_user_ptr(s.out), out, s.len))
+ ret = -EFAULT;
+ if (!ret && enc && copy_to_user(u64_to_user_ptr(s.tag), tag,
+ sizeof(tag)))
+ ret = -EFAULT;
+ if (!ret) {
+ c->seq++;
+ c->last_seen = last;
+ } else if (ran) {
+ ret = keycrypt_ctx_end(c, ret);
+ }
+free:
+ kvfree_sensitive(in, s.len);
+ kvfree_sensitive(out, s.len);
+ kvfree_sensitive(aad, s.aad_len);
+ memzero_explicit(tag, sizeof(tag));
+unlock:
+ mutex_unlock(&c->lock);
+ return ret;
+}
+
static long keycrypt_ioc_info(struct keycrypt_ctx *c,
struct keycrypt_info __user *uarg)
{
@@ -349,6 +462,8 @@ static long keycrypt_ioctl(struct file *file, unsigned int cmd,
return keycrypt_ioc_update(c, (void __user *)arg);
case KEYCRYPT_IOC_FINAL:
return keycrypt_ioc_final(c, (void __user *)arg);
+ case KEYCRYPT_IOC_SEGMENT:
+ return keycrypt_ioc_segment(c, (void __user *)arg);
case KEYCRYPT_IOC_INFO:
return keycrypt_ioc_info(c, (void __user *)arg);
}
@@ -375,6 +490,7 @@ static const struct file_operations keycrypt_fops = {
*/
static int keycrypt_open_backend(struct keycrypt_handle *h,
const struct keycrypt_payload *p,
+ u8 alg,
struct keycrypt_backend **b)
{
*b = h->b;
@@ -384,6 +500,8 @@ static int keycrypt_open_backend(struct keycrypt_handle *h,
return -EKEYREVOKED;
if (!(*b)->ctx_open)
return -ENODEV;
+ if (WARN_ON_ONCE(alg == KEYCRYPT_ALG_AES256_GCM_STREAM && !(*b)->aead))
+ return -EIO; /* registration refuses such a backend */
return 0;
}
@@ -463,6 +581,12 @@ long keyctl_crypt_open(key_serial_t id, void __user *uparams,
if (gen_iv && memchr_inv(params.iv, 0, sizeof(params.iv)))
ret = -EINVAL;
}
+ if (!ret && p->key.meta.alg == KEYCRYPT_ALG_AES256_GCM_STREAM &&
+ params.op == KEYCRYPT_OP_ENCRYPT) {
+ gen_iv = true;
+ if (memchr_inv(params.salt, 0, sizeof(params.salt)))
+ ret = -EINVAL;
+ }
h = ret ? NULL : p->handle;
if (h)
refcount_inc(&h->ref);
@@ -490,7 +614,7 @@ long keyctl_crypt_open(key_serial_t id, void __user *uparams,
c->accepted_min_tier = params.accepted_min_tier;
down_read(&h->sem);
- ret = keycrypt_open_backend(h, p, &b);
+ ret = keycrypt_open_backend(h, p, c->meta.alg, &b);
if (!ret)
ret = keycrypt_ctx_ret(b->ctx_open(b, &p->key, params.op,
params.iv, &c->bctx));
@@ -506,6 +630,19 @@ long keyctl_crypt_open(key_serial_t id, void __user *uparams,
goto put_handle;
}
+ /*
+ * An all-zero salt would make every stream reuse the same nonces: refuse
+ * it, whether a backend drawing its own salt wrote it or the core's
+ * random bytes came out so
+ */
+ if (c->meta.alg == KEYCRYPT_ALG_AES256_GCM_STREAM &&
+ c->op == KEYCRYPT_OP_ENCRYPT &&
+ !memchr_inv(params.salt, 0, sizeof(params.salt))) {
+ memzero_explicit(params.salt, sizeof(params.salt));
+ keycrypt_ctx_free(c);
+ return -EIO;
+ }
+
/* The write-back happens before the fd exists: no fd on EFAULT */
if (gen_iv &&
copy_to_user(((struct keycrypt_open_params __user *)uparams)->iv,
diff --git a/security/keys/keycrypt/keycrypt.h b/security/keys/keycrypt/keycrypt.h
index 40487eb3e139..1d16217d93f7 100644
--- a/security/keys/keycrypt/keycrypt.h
+++ b/security/keys/keycrypt/keycrypt.h
@@ -110,6 +110,8 @@ struct keycrypt_req {
* @accepted_min_tier: the caller's KEYCRYPT_TIER_* at open, or 0
* @done: ended by FINAL or by a failure once the backend ran; every later
* call gives -EBADFD
+ * @seq: aes256-gcm-stream: the next segment's counter
+ * @last_seen: aes256-gcm-stream: a segment flagged LAST was processed
*/
struct keycrypt_ctx {
struct mutex lock; /* serialises the calls on the fd */
@@ -121,6 +123,8 @@ struct keycrypt_ctx {
struct keycrypt_meta meta;
u8 accepted_min_tier;
bool done;
+ u32 seq;
+ bool last_seen;
};
/* The key length each algorithm takes; false for an unknown alg */
@@ -128,6 +132,7 @@ static inline bool keycrypt_key_len_valid(u8 alg, size_t len)
{
switch (alg) {
case KEYCRYPT_ALG_AES256_CBC:
+ case KEYCRYPT_ALG_AES256_GCM_STREAM:
return len == 32;
case KEYCRYPT_ALG_HMAC_SHA256:
return len >= 1 && len <= 64;
diff --git a/security/keys/keycrypt/optee.c b/security/keys/keycrypt/optee.c
index 5a3ab6f825f1..b616d77acef1 100644
--- a/security/keys/keycrypt/optee.c
+++ b/security/keys/keycrypt/optee.c
@@ -20,20 +20,22 @@
/*
* Offsets in a shared buffer, which carries one call's parameters at a
* time: header, blob and imported key for a control call; header, blob
- * and IV for CTX_OPEN; data and tag for a context's later calls.
+ * and IV for CTX_OPEN; data, AAD and tag for a context's later calls.
*/
#define KC_SHM_HDR 0
#define KC_SHM_BLOB (KC_SHM_HDR + KEYCRYPT_HEADER_MAX)
#define KC_SHM_KEY (KC_SHM_BLOB + KC_TA_DATA_MAX)
#define KC_CTL_SIZE (KC_SHM_KEY + KC_KEY_MAX)
#define KC_SHM_DATA 0
-#define KC_SHM_TAG (KC_SHM_DATA + KEYCRYPT_UPDATE_MAX)
+#define KC_SHM_AAD (KC_SHM_DATA + KEYCRYPT_SEGMENT_MAX)
+#define KC_SHM_TAG (KC_SHM_AAD + KEYCRYPT_AAD_MAX)
#define KC_SHM_IV (KC_SHM_TAG + KEYCRYPT_MAC_LEN)
-#define KC_IV_LEN sizeof_field(struct keycrypt_open_params, iv)
-#define KC_CTX_SIZE (KC_SHM_IV + KC_IV_LEN)
+#define KC_CTX_SIZE (KC_SHM_IV + KEYCRYPT_STREAM_SALT_LEN)
-static_assert(KC_SHM_BLOB + KC_TA_DATA_MAX <= KC_SHM_TAG);
-static_assert(KEYCRYPT_UPDATE_MAX <= KC_TA_BUF_MAX);
+static_assert(KEYCRYPT_UPDATE_MAX <= KEYCRYPT_SEGMENT_MAX);
+static_assert(KC_SHM_BLOB + KC_TA_DATA_MAX <= KC_SHM_AAD);
+static_assert(KEYCRYPT_SEGMENT_MAX <= KC_TA_BUF_MAX);
+static_assert(KEYCRYPT_AAD_MAX <= KC_TA_AAD_MAX);
/**
* struct kc_optee - the backend's link to the TA
@@ -239,7 +241,7 @@ static int kc_optee_ctx_open(struct keycrypt_backend *b,
memcpy(c->va + KC_SHM_HDR, k->hdr, k->hdr_len);
memcpy(c->va + KC_SHM_BLOB, k->data, k->data_len);
- memcpy(c->va + KC_SHM_IV, iv, KC_IV_LEN);
+ memcpy(c->va + KC_SHM_IV, iv, KEYCRYPT_STREAM_SALT_LEN);
kc_memref(&p[0], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT, c->shm,
KC_SHM_HDR, k->hdr_len);
kc_memref(&p[1], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT, c->shm,
@@ -247,12 +249,16 @@ static int kc_optee_ctx_open(struct keycrypt_backend *b,
p[2].attr = TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT;
p[2].u.value.a = op;
kc_memref(&p[3], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT, c->shm,
- KC_SHM_IV, KC_IV_LEN);
+ KC_SHM_IV, KEYCRYPT_STREAM_SALT_LEN);
ret = kc_invoke(c->session, KC_TA_CMD_CTX_OPEN, p);
- if (!ret && p[3].u.memref.size != KC_IV_LEN)
+ if (!ret && p[3].u.memref.size != KEYCRYPT_STREAM_SALT_LEN)
ret = -EIO;
if (ret)
goto wipe;
+ /* The TA drew the salt of a stream to encrypt: the caller gets it */
+ if (k->meta.alg == KEYCRYPT_ALG_AES256_GCM_STREAM &&
+ op == KEYCRYPT_OP_ENCRYPT)
+ memcpy(iv, c->va + KC_SHM_IV, KEYCRYPT_STREAM_SALT_LEN);
memzero_explicit(c->va, KC_CTX_SIZE);
c->alg = k->meta.alg;
c->op = op;
@@ -332,6 +338,51 @@ static int kc_optee_verify(struct keycrypt_backend *b, void *ctx,
return ret;
}
+static int kc_optee_aead(struct keycrypt_backend *b, void *ctx, u32 seq,
+ bool last, const u8 *aad, size_t aad_len,
+ const u8 *in, u8 *out, size_t len, u8 *tag)
+{
+ struct kc_optee_ctx *c = ctx;
+ bool enc = c->op == KEYCRYPT_OP_ENCRYPT;
+ struct tee_param p[4] = {};
+ int ret;
+
+ if (len > KEYCRYPT_SEGMENT_MAX || aad_len > KEYCRYPT_AAD_MAX)
+ return -EIO;
+ if (len) {
+ memcpy(c->va + KC_SHM_DATA, in, len);
+ kc_memref(&p[0], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT, c->shm,
+ KC_SHM_DATA, len);
+ }
+ if (aad_len) {
+ memcpy(c->va + KC_SHM_AAD, aad, aad_len);
+ kc_memref(&p[1], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INPUT, c->shm,
+ KC_SHM_AAD, aad_len);
+ }
+ if (!enc)
+ memcpy(c->va + KC_SHM_TAG, tag, KEYCRYPT_AEAD_TAG_LEN);
+ kc_memref(&p[2], TEE_IOCTL_PARAM_ATTR_TYPE_MEMREF_INOUT, c->shm,
+ KC_SHM_TAG, KEYCRYPT_AEAD_TAG_LEN);
+ p[3].attr = TEE_IOCTL_PARAM_ATTR_TYPE_VALUE_INPUT;
+ p[3].u.value.a = seq;
+ p[3].u.value.b = last;
+ ret = kc_invoke(c->session, KC_TA_CMD_SEGMENT, p);
+ if (!ret && ((len && p[0].u.memref.size != len) ||
+ (enc && p[2].u.memref.size != KEYCRYPT_AEAD_TAG_LEN)))
+ ret = -EIO;
+ /* An empty segment comes with no buffers (@in and @out NULL) */
+ if (!ret && len)
+ memcpy(out, c->va + KC_SHM_DATA, len);
+ if (!ret && enc)
+ memcpy(tag, c->va + KC_SHM_TAG, KEYCRYPT_AEAD_TAG_LEN);
+ if (ret && len)
+ memset(out, 0, len);
+ memzero_explicit(c->va + KC_SHM_DATA, len);
+ memzero_explicit(c->va + KC_SHM_AAD, aad_len);
+ memzero_explicit(c->va + KC_SHM_TAG, KEYCRYPT_AEAD_TAG_LEN);
+ return ret;
+}
+
static void kc_optee_ctx_free(struct keycrypt_backend *b, void *ctx)
{
struct kc_optee_ctx *c = ctx;
@@ -353,6 +404,7 @@ static struct keycrypt_backend keycrypt_optee = {
.final = kc_optee_final,
.verify = kc_optee_verify,
.ctx_free = kc_optee_ctx_free,
+ .aead = kc_optee_aead,
};
static int kc_optee_match(struct tee_ioctl_version_data *ver,
diff --git a/security/keys/keycrypt/optee.h b/security/keys/keycrypt/optee.h
index 391eba15b699..546c1665fc5f 100644
--- a/security/keys/keycrypt/optee.h
+++ b/security/keys/keycrypt/optee.h
@@ -23,9 +23,11 @@
#define KC_TA_CMD_UPDATE 4
#define KC_TA_CMD_FINAL 5
#define KC_TA_CMD_VERIFY 6
+#define KC_TA_CMD_SEGMENT 7
#define KC_TA_DATA_MAX 93 /* the TA's data: 1 + 12 + 64 + 16 */
-#define KC_TA_BUF_MAX 65536 /* data of one UPDATE */
+#define KC_TA_BUF_MAX 65536 /* data of one UPDATE or SEGMENT */
+#define KC_TA_AAD_MAX 4096 /* associated data of one SEGMENT */
/* The TA's limit, the control session included; not enforced here */
#define KC_TA_SESSIONS_MAX 32
diff --git a/security/keys/keycrypt/sw.c b/security/keys/keycrypt/sw.c
index f1ff4de4afc6..28cc7188d587 100644
--- a/security/keys/keycrypt/sw.c
+++ b/security/keys/keycrypt/sw.c
@@ -4,7 +4,9 @@
* trusted key, used by the kernel itself
*
* The blob's layout and its GCM key are in keycrypt.rst, "The sw
- * backend".
+ * backend". That GCM use seals the key at rest only: an aes256-gcm-stream
+ * key's own stream segments run under a separate per-stream subkey,
+ * derived by sw_ctx_open() from the salt the core passes in.
*
* Copyright (C) 2026 Rodolfo Giometti <giometti@enneenne.com>
*/
@@ -20,6 +22,7 @@
#include <linux/random.h>
#include <linux/slab.h>
#include <linux/string.h>
+#include <linux/unaligned.h>
#include "keycrypt.h"
#include "sw.h"
@@ -151,6 +154,28 @@ static int keycrypt_sw_unseal(const u8 *master, size_t mlen,
return 0;
}
+/*
+ * HKDF-SHA256 (RFC 5869) with one block of output: extract with @salt,
+ * expand with @info, 32 bytes to @out.
+ */
+static void sw_hkdf_sha256(const u8 *ikm, size_t ikm_len,
+ const u8 *salt, size_t salt_len,
+ const u8 *info, size_t info_len,
+ u8 *out)
+{
+ static const u8 one = 1;
+ struct hmac_sha256_ctx ctx;
+ u8 prk[SHA256_DIGEST_SIZE];
+
+ hmac_sha256_usingrawkey(salt, salt_len, ikm, ikm_len, prk);
+ hmac_sha256_init_usingrawkey(&ctx, prk, sizeof(prk));
+ hmac_sha256_update(&ctx, info, info_len);
+ hmac_sha256_update(&ctx, &one, 1);
+ hmac_sha256_final(&ctx, out);
+ memzero_explicit(prk, sizeof(prk));
+ memzero_explicit(&ctx, sizeof(ctx));
+}
+
/*
* Copy the key material of the trusted key @desc that the caller can
* search for into @buf (MAX_KEY_SIZE bytes). No callout information, so no
@@ -286,6 +311,7 @@ static void sw_destroy(struct keycrypt_backend *b, struct keycrypt_key *k)
struct sw_ctx {
u32 op;
+ bool enc; /* aes256-gcm-stream only: encryption, not decryption */
union {
struct {
union {
@@ -295,6 +321,7 @@ struct sw_ctx {
u8 iv[AES_BLOCK_SIZE];
} cbc;
struct hmac_sha256_ctx mac;
+ struct aes_gcm_key gcm;
};
};
@@ -311,7 +338,21 @@ static int sw_ctx_open(struct keycrypt_backend *b, struct keycrypt_key *k,
if (!c)
return -ENOMEM;
c->op = op;
- if (op == KEYCRYPT_OP_MAC || op == KEYCRYPT_OP_VERIFY) {
+ if (k->meta.alg == KEYCRYPT_ALG_AES256_GCM_STREAM) {
+ u8 sk[SHA256_DIGEST_SIZE];
+
+ c->enc = op == KEYCRYPT_OP_ENCRYPT;
+ sw_hkdf_sha256(kk->key, kk->len, iv, KEYCRYPT_STREAM_SALT_LEN,
+ KEYCRYPT_STREAM_INFO,
+ sizeof(KEYCRYPT_STREAM_INFO) - 1, sk);
+ ret = aes_gcm_preparekey(&c->gcm, sk, sizeof(sk),
+ KEYCRYPT_AEAD_TAG_LEN);
+ memzero_explicit(sk, sizeof(sk));
+ if (ret) {
+ kfree_sensitive(c);
+ return -EIO;
+ }
+ } else if (op == KEYCRYPT_OP_MAC || op == KEYCRYPT_OP_VERIFY) {
hmac_sha256_init_usingrawkey(&c->mac, kk->key, kk->len);
} else {
ret = op == KEYCRYPT_OP_ENCRYPT ?
@@ -327,6 +368,28 @@ static int sw_ctx_open(struct keycrypt_backend *b, struct keycrypt_key *k,
return 0;
}
+static int sw_aead(struct keycrypt_backend *b, void *ctx, u32 seq, bool last,
+ const u8 *aad, size_t aad_len, const u8 *in, u8 *out,
+ size_t len, u8 *tag)
+{
+ struct sw_ctx *c = ctx;
+ u8 nonce[12] = {};
+
+ put_unaligned_be32(seq, nonce + 7);
+ nonce[11] = last;
+
+ if (c->enc) {
+ aes_gcm_encrypt(out, in, len, tag, aad, aad_len, nonce,
+ &c->gcm);
+ return 0;
+ }
+ if (aes_gcm_decrypt(out, in, len, tag, aad, aad_len, nonce, &c->gcm)) {
+ memzero_explicit(out, len);
+ return -EBADMSG;
+ }
+ return 0;
+}
+
static int sw_update(struct keycrypt_backend *b, void *ctx, const u8 *in,
u8 *out, size_t len)
{
@@ -382,6 +445,7 @@ static struct keycrypt_backend keycrypt_sw = {
.update = sw_update,
.final = sw_final,
.ctx_free = sw_ctx_free,
+ .aead = sw_aead,
};
static int __init keycrypt_sw_init(void)
--
2.43.0
^ permalink raw reply related [flat|nested] 14+ messages in thread
* Re: [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
` (8 preceding siblings ...)
2026-11-18 14:12 ` [RFC PATCH 9/9] KEYS: keycrypt: Add the aes256-gcm-stream algorithm Rodolfo Giometti
@ 2026-11-18 14:31 ` Jarkko Sakkinen
2026-11-18 14:39 ` Jarkko Sakkinen
2026-11-18 14:57 ` Marco Felsch
10 siblings, 1 reply; 14+ messages in thread
From: Jarkko Sakkinen @ 2026-11-18 14:31 UTC (permalink / raw)
To: Rodolfo Giometti
Cc: David Howells, keyrings, Herbert Xu, David S. Miller,
Jens Wiklander, Sumit Garg, op-tee, Horia Geantă,
Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum, Richard Weinberger,
Christophe Leroy (CS GROUP), Eric Biggers, Demi Marie Obenour,
Arnd Bergmann, Paul Moore, James Morris, Serge E. Hallyn,
Jonathan Corbet, Shuah Khan, Randy Dunlap, linux-crypto,
linux-integrity, linux-security-module, linux-kselftest,
linux-doc, linux-api, linux-arm-kernel, linuxppc-dev,
linux-kernel
On Wed, Nov 18, 2026 at 03:04:12PM +0100, Rodolfo Giometti wrote:
> This RFC proposes a key type, "keycrypt", whose material user space can
> use for symmetric operations but never read: AES-256-CBC, HMAC-SHA256
> and an authenticated AES-256-GCM stream, through a file descriptor that
> KEYCTL_CRYPT_OPEN returns for one key and one operation. The key is held
> by a backend: the kernel itself (sealed under a trusted key), an OP-TEE
> trusted application, or, as a proposal only, the CAAM. I am asking
> whether this is a direction the keyrings, crypto and TEE maintainers
> would take, before polishing it further.
>
> Patch 9, the authenticated stream, is a proposal on its own and not
> needed by the rest of the series: it is a construction of keycrypt's
> own, and patches 1-8 do not depend on it, so it can be discussed, or
> left out, apart from them. No user-space consumer uses the stream or
> HMAC-SHA256 yet: craf (below) uses CBC only. If this direction is found
> acceptable, one of the next steps is to bring craf's keycrypt backend
> into craf's main line, with the stream and HMAC-SHA256, as long as
> doing so does not stand in the way of this RFC or of the series I hope
> will follow it.
>
> The problem
> -----------
>
> An embedded product that encrypts its own data (a root filesystem
> archive, configuration backups, logs) needs a key that does not sit in
> the root filesystem and that a compromised user space cannot copy. Today
> user space either reads the key (a user or logon key handed to AF_ALG)
> or cannot use it at all (a trusted key serves kernel consumers only).
> AF_ALG, the one interface that let user space drive a key the kernel
> held, has moved away from that use: v7.2 dropped off-CPU cryptography
> from it (7524070f26d8, "crypto: af_alg - Drop support for off-CPU
> cryptography"), whose message says "If using an off-CPU accelerator
> really does turn out to be a win, a new API should be developed that is
> actually a good fit for it", and v7.3 restricted it to allowlisted
> generic algorithms by default (2f204fe718f5, the af_alg_restrict
> sysctl). One exception was let back in, cbc(paes) with a CAAM blob in
> place of the key, because "this crypto operation cannot be implemented
> in a userspace library" (285d8204638c, v7.2), for privileged users only
> (d9506e82ced5, v7.3): the need is acknowledged, for one driver and
> one mode. keycrypt is meant to be the API that 7524070f26d8 asks for,
> for keys that stay in a TEE or in hardware, whatever the backend.
>
> The interface
> -------------
>
> 1. A key type, "keycrypt", created with add_key() from "new <alg>
> <purposes> [tier=|min-tier=] [backend=]", "load <blob>
> [accepted-min-tier=] [purpose=]" or, when allowed, "import <alg>
> <purposes> [tier=|min-tier=] [backend=] <hex>". User space states the
> protection a key needs, as a tier, and the kernel chooses the backend
> that provides it, unless backend= names one. backend= is a constraint
> added to the tier, never one in its place: a named backend that does
> not meet tier= or min-tier= gives ENODEV, not a weaker key. It is for
> a system with more than one backend, an i.MX8 with both the CAAM and
> OP-TEE say, where a program must choose which mechanism holds a key
> (the cost of each call, what the key is bound to) and not only how
> well; the name chooses among mechanisms that meet the tier asked for,
> it never lowers a tier asked for (without one, it takes that backend
> at the tier it declares, so a program that needs a tier states it).
> Its payload read back is a blob that only that backend can open; the
> material itself never reaches user space.
> 2. Each key is bound, when it is made, to one algorithm and to the
> purposes it may serve, checked at every open:
> a. encrypt and decrypt, for aes256-cbc and aes256-gcm-stream keys:
> a key that may only encrypt lets a device write data it cannot
> read back, a key that may only decrypt the reverse;
> b. mac and verify, for hmac-sha256 keys: "mac" computes a tag over
> data, "verify" only checks a tag given by the caller, so a
> component holding a verify-only key can authenticate data (a
> configuration, an update) but cannot produce a tag that would
> pass. VERIFY takes the expected tag at FINAL and answers 0 or
> EBADMSG; the tag it computed never leaves the backend. For
> example, a server authenticates the commands it sends to a fleet
> of devices with HMAC-SHA256, and every device holds the same key,
> imported at the factory as verify-only. With a plain HMAC key,
> root on one device could extract it and forge commands for the
> whole fleet; with a verify-only keycrypt key held by a tee or hsm
> backend, a compromised device can still check commands but can
> neither read the key nor compute a tag that passes. It comes
> close to what a signature gives (everyone verifies, only the
> server signs), with a MAC, as long as no device's TEE or HSM is
> broken: the key is the fleet's, so the device that breaks forges
> for all of it, which a signature would not allow.
> 3. KEYCTL_CRYPT_OPEN (keyctl 33) opens an operation context on a key and
> returns an fd; ioctls on it: KEYCRYPT_IOC_UPDATE, KEYCRYPT_IOC_FINAL,
> KEYCRYPT_IOC_SEGMENT (the GCM stream, patch 9) and KEYCRYPT_IOC_INFO,
> which tells a program holding only the fd (passed by SCM_RIGHTS, say)
> the operation, the minimum tier it was opened with, and the
> algorithm, purposes, tier, origin and backend of the key it is using.
> Search permission on the key is the right to open it; the caller may
> name the lowest tier it accepts (accepted_min_tier), and a key below
> it is refused.
> 4. Policies: kernel.keys.keycrypt_system_tier and
> kernel.keys.keycrypt_import (also the boot parameters
> keycrypt.system_tier= and keycrypt.import=), one-way, so that a
> system can refuse the use of low-tier keys or clear-key import for
> good. The system tier is a floor on use only: keys below it can
> still be made and loaded, but KEYCTL_CRYPT_OPEN refuses them. Its
> starting value is chosen at build time
> (CONFIG_KEYCRYPT_SYSTEM_TIER_*), so a signed kernel image carries a
> floor its command line cannot lower; likewise, a kernel built
> without CONFIG_KEYCRYPT_IMPORT refuses import whatever its command
> line or sysctl say.
> 5. EOPNOTSUPP from KEYCTL_CRYPT_OPEN means "not a keycrypt key", or a
> kernel without keycrypt, so a library may fall back to another
> interface on it; ENODEV means no backend can run the key.
>
> Tiers and what a compromised kernel can do
> ------------------------------------------
>
> Each backend declares a tier, and the open path checks it against the
> system tier and the caller's accepted minimum:
>
> tier key in clear purpose enforced by who may use the key
> in the kernel
> kernel yes the kernel the kernel
> engine no the kernel the kernel
> tee no the TA the kernel
> hsm no the HSM the kernel
>
> The last column is the limit of the mechanism: a compromised kernel can
> use a tee or hsm key for the purposes it already has, but cannot extract
> it or change its purpose. Documentation/security/keys/keycrypt.rst,
> "Backend requirements", is the contract a tee or hsm backend must meet.
>
> 1. kernel: the keys are in clear in kernel memory while loaded. It is
> there so that the same interface works on a system with no TEE and
> no suitable hardware, where it still keeps the key out of user space
> and out of the root filesystem; its one backend, sw, is off by
> default (CONFIG_KEYCRYPT_SW), and a system that has one of the
> other tiers should use it, engine at least, and raise the system
> tier accordingly. Raising it stops the use of kernel-tier keys, not
> their presence: one created or loaded below it is in clear all the
> same, as its trusted master is, so a system that must have none
> builds without CONFIG_KEYCRYPT_SW.
> 2. engine: a crypto engine the kernel drives keeps the key, never in
> clear in the kernel, but its use is decided by the kernel only. It
> comes in patch 6, on its own, so that patches 1-5 stand without a
> tier no backend of theirs declares. The CAAM backend of this series
> is an engine, since the CAAM does not check what a key is used for;
> an ELE backend (below) would start as an engine too, and could move
> to hsm once the firmware is confirmed to enforce a key's purpose. If
> more such shades appear, a separate property may fit better than
> more tiers, and I would welcome an opinion.
> 3. tee: the OP-TEE backend; the TA re-checks every operation against
> the purposes it bound when the key was sealed.
> 4. hsm: as tee, in dedicated hardware apart from the CPU running the
> kernel (a secure element, a security core of its own such as NXP's
> EdgeLock Enclave, a crypto engine with its own policy), the place of
> Android KeyMint's StrongBox; no backend in this series.
>
> The backends
> ------------
>
> 1. sw, of the kernel tier (no name is both a tier's and a backend's):
> keys sealed with AES-256-GCM under a key derived with HMAC-SHA256
> from a trusted key (any trusted-key source); HKDF-derived stream
> subkeys; lib/crypto AES. Where the trusted key
> comes from a TPM, the TPM only unseals that master when a key is
> loaded; the data itself is ciphered on the CPU, never by the TPM.
> 2. OP-TEE: a trusted application, an early TA, REE kernel login only;
> it derives its sealing key from OP-TEE's hardware-unique-key
> service. The TA is written (ta/keycrypt, one patch to optee_os) and
> is the one that ran on the hardware below, but I have not proposed
> it to OP-TEE yet: I would first like to know whether this direction
> can go on. I can publish it for anyone who wants to try it and is
> willing to support the work.
> 3. CAAM: patches 7 and 8, a proposal and not to be applied as they
> are.
> They are based on Richard Weinberger's "crypto: caam" series v1 (see
> "Base and prerequisites") and never ran on a CAAM. Questions for the
> CAAM maintainers:
> a. is an internal cbc(paes) taking the caller's key modifier an
> acceptable form;
> b. can a job generate a key in the CAAM and keep it black without it
> crossing kernel memory;
> c. can the use of a key be checked by something a compromised kernel
> does not drive: trusted descriptors, which would let the CAAM
> itself enforce a key's purpose and make the backend hsm, or a job
> ring owned by the secure world, which would make it tee;
> d. could cbc(paes) take CCM black keys, which are authenticated where
> ECB ones are not, once the driver handles their extra length
> (Weinberger's series refuses them, so the backend uses ECB).
> 4. ELE (i.MX9), not in this series: this is an RFC, and I am not an
> expert of the enclave, so I would rather know first what NXP thinks
> of it, and whether they would be willing to propose an ELE backend
> themselves, as an engine or, better, as an hsm. As far as I can see,
> the se_if driver in linux-next gives user space a misc device with a
> generic send-and-receive ioctl for the enclave's messages, and offers
> nothing to other kernel code. A per-operation in-kernel API exported
> by that driver (open a key store reserved to the kernel, generate a
> key, import a wrapped one, read a key's attributes, delete it,
> AES-CBC and MAC in one call) would let a keycrypt backend use the
> enclave. Questions for NXP:
> a. does the firmware enforce a key's key_usage and permitted_algo on
> every operation, min_mac_length when verifying, and never release
> a generated key in clear (yes to all three would make the backend
> hsm rather than engine);
> b. could a key be exported wrapped under a device-unique key and
> imported again, so that a keycrypt blob holds the key itself
> rather than a reference to the enclave's key store;
> c. is the key that wraps an imported key unique per device;
> d. the user-space library has a streaming MAC (hsm_mac() with its
> INIT, UPDATE_DATA and FINALIZE flags): would the firmware offer
> it to the kernel for a key in its key store;
> e. can a key_id be reused after a key is deleted (the library's
> documentation does not say);
> f. would a per-operation API of this kind answer the objection Arnd
> Bergmann raised to the generic passthrough
> (<2034fb2f-f169-46a5-85e8-fa723ddb0360@app.fastmail.com>).
>
> Base and prerequisites
> ----------------------
>
> The series is based on mainline v7.4-rc2-92 (067c5c24cef2). Patches
> 1-6, and patch 9 on top of them, apply on it alone. Patches 7 and 8, the
> CAAM proposal, need Richard
> Weinberger's "crypto: caam" series v1
> (<20260726081504.2182951-1-richard@nod.at>, three patches, listed as
> prerequisites below) applied first, for example with:
>
> b4 am -o - 20260726081504.2182951-1-richard@nod.at | git am
>
> Testing
> -------
>
> The series comes without its tests. There are KUnit suites for the
> core and the sw, OP-TEE and CAAM backends, and a kselftest for the user
> ABI, with a case for every reachable row of keycrypt.rst's error
> tables; together they are larger than the code they test, so I am
> keeping them for the non-RFC series, once the direction is agreed. The
> results below that name them come from the series with the tests in it.
> Taking them out removed only the tests and the hooks that let them
> reach the code's internals (static functions made visible and exported
> to KUnit modules): with CONFIG_KUNIT off, the posted patches build for
> arm64 to the same instructions as that series.
>
> On that base, with Weinberger's three patches applied: built for arm64
> with W=1 (security/keys/keycrypt/ and drivers/crypto/caam/, no
> warning), and, with the tests on top, the KUnit suites pass on UML
> but for the one case that needs the system tier above kernel (by
> Kconfig or boot parameter). Patches 1-6 and 9 alone, on the base without
> Weinberger's patches: the same build of security/keys/keycrypt/, no
> warning.
> The runs below were made on that series at v7.3 on QEMU, and, without
> the CAAM code, backported to NXP's 6.18, on QEMU and on hardware:
>
> 1. QEMU (qemuarm64-secureboot, OP-TEE 4.9.0, an fTPM as the source of
> the trusted master): the KUnit suites and the kselftest passed on
> the sw and OP-TEE backends, a case skipped only where its backend
> was absent (the CAAM) or where it needs a one-way policy setting;
> the TA's unbind and bind; persistence of a blob across a restart.
> QEMU proves function, not secrecy: its hardware unique key is a stub.
> 2. Hardware: the series, backported to NXP's linux-imx lf-6.18.2-1.0.0
> (six upstream prerequisites; the two CAAM patches left out), with the
> TA built as an early TA into NXP's imx-optee-os 4.8.0, ran on an
> i.MX93 board with secure boot closed (AHAB), where OP-TEE derives the
> key that seals the TA's key blobs from the EdgeLock Enclave's
> hardware unique key. The KUnit suites and the kselftest passed on
> the OP-TEE backend, a case skipped only where its backend was absent
> (sw, which 6.18 cannot build for lack of the library AES it needs,
> and the CAAM, left out) or where it needs a one-way policy setting.
> A key generated in OP-TEE and kept as its blob
> was loaded back after a reboot and after a full power-off, and
> decrypted a file encrypted before them. The same AES-256-CBC key and
> IV through AF_ALG (cbc-aes-ce), through keycrypt and through openssl
> gave identical ciphertexts.
> 3. Cost on that board (Cortex-A55), AES-256-CBC, per call on an open
> context: keycrypt with the OP-TEE backend 59-62us up to 256 bytes,
> ~106us at 4KiB, 880-930us at 64KiB (67-71MiB/s); AF_ALG cbc-aes-ce
> 6-7, 12-14 and 110-138us (454-570MiB/s). Opening a context costs
> ~500us, against ~9us for an AF_ALG accept on a keyed socket (~25us
> for the whole AF_ALG setup). OP-TEE's own benchmark (xtest
> --aes-perf, from user space through libteec) on the same board gives
> ~64us per call plus ~1.5ns per byte. keycrypt's fixed cost matches
> that round trip to the secure world; its remaining ~11ns per byte is
> spent in this prototype's own data path (buffer allocation and
> copies between user space, kernel, shared memory and the TA); which
> part dominates is not yet measured, and it is to be reduced.
>
> A user-space consumer exists: craf, the archive tool of crypto-afalg,
> has a keycrypt backend on the keycrypt branch of
> https://github.com/giometti/crypto-afalg (tag keycrypt-board-5 is the
> version that ran on the hardware above). Its enc command, an openssl
> enc that takes its key from the keyring, shows what a keycrypt key
> carries. A key made once as
>
> k=$(keyctl add keycrypt demo \
> "new aes256-cbc encrypt,decrypt min-tier=tee" @u)
>
> is bound there to AES-256-CBC, to encrypting and decrypting, and to a
> backend of tier tee at least, chosen by the kernel; so
>
> craf enc -enc-key $k -iv <hex> < plain > cipher
> craf enc -d -enc-key $k -iv <hex> < cipher > plain
>
> need nothing else: the open takes no algorithm and no backend, the key
> brings them, and its tier is enforced by the kernel against
> -enc-min-tier or the system's tier. Any other key goes to AF_ALG, and
> the command line must name the cipher. On the board, craf enc with an
> imported keycrypt key and openssl enc with the same key bytes and IV
> each decrypted what the other encrypted.
>
> While testing the user-space side of this series, craf's test suite hit
> the KEYCTL_PKEY_VERIFY regression of cb481e59ea6c, which lets a short
> RSA signature verify: it is fixed by Florian Bauckholt's patch [1], and
> the reproducer was reported in [2].
I likely have never time to read this. Thus, NAK.
Br, Jarkko
^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read
2026-11-18 14:31 ` [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Jarkko Sakkinen
@ 2026-11-18 14:39 ` Jarkko Sakkinen
0 siblings, 0 replies; 14+ messages in thread
From: Jarkko Sakkinen @ 2026-11-18 14:39 UTC (permalink / raw)
To: Rodolfo Giometti
Cc: David Howells, keyrings, Herbert Xu, David S. Miller,
Jens Wiklander, Sumit Garg, op-tee, Horia Geantă,
Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum, Richard Weinberger,
Christophe Leroy (CS GROUP), Eric Biggers, Demi Marie Obenour,
Arnd Bergmann, Paul Moore, James Morris, Serge E. Hallyn,
Jonathan Corbet, Shuah Khan, Randy Dunlap, linux-crypto,
linux-integrity, linux-security-module, linux-kselftest,
linux-doc, linux-api, linux-arm-kernel, linuxppc-dev,
linux-kernel
On Wed, Nov 18, 2026 at 04:31:22PM +0200, Jarkko Sakkinen wrote:
> On Wed, Nov 18, 2026 at 03:04:12PM +0100, Rodolfo Giometti wrote:
> > This RFC proposes a key type, "keycrypt", whose material user space can
> > use for symmetric operations but never read: AES-256-CBC, HMAC-SHA256
> > and an authenticated AES-256-GCM stream, through a file descriptor that
> > KEYCTL_CRYPT_OPEN returns for one key and one operation. The key is held
> > by a backend: the kernel itself (sealed under a trusted key), an OP-TEE
> > trusted application, or, as a proposal only, the CAAM. I am asking
> > whether this is a direction the keyrings, crypto and TEE maintainers
> > would take, before polishing it further.
> >
> > Patch 9, the authenticated stream, is a proposal on its own and not
> > needed by the rest of the series: it is a construction of keycrypt's
> > own, and patches 1-8 do not depend on it, so it can be discussed, or
> > left out, apart from them. No user-space consumer uses the stream or
> > HMAC-SHA256 yet: craf (below) uses CBC only. If this direction is found
> > acceptable, one of the next steps is to bring craf's keycrypt backend
> > into craf's main line, with the stream and HMAC-SHA256, as long as
> > doing so does not stand in the way of this RFC or of the series I hope
> > will follow it.
> >
> > The problem
> > -----------
> >
> > An embedded product that encrypts its own data (a root filesystem
> > archive, configuration backups, logs) needs a key that does not sit in
> > the root filesystem and that a compromised user space cannot copy. Today
> > user space either reads the key (a user or logon key handed to AF_ALG)
> > or cannot use it at all (a trusted key serves kernel consumers only).
> > AF_ALG, the one interface that let user space drive a key the kernel
> > held, has moved away from that use: v7.2 dropped off-CPU cryptography
> > from it (7524070f26d8, "crypto: af_alg - Drop support for off-CPU
> > cryptography"), whose message says "If using an off-CPU accelerator
> > really does turn out to be a win, a new API should be developed that is
> > actually a good fit for it", and v7.3 restricted it to allowlisted
> > generic algorithms by default (2f204fe718f5, the af_alg_restrict
> > sysctl). One exception was let back in, cbc(paes) with a CAAM blob in
> > place of the key, because "this crypto operation cannot be implemented
> > in a userspace library" (285d8204638c, v7.2), for privileged users only
> > (d9506e82ced5, v7.3): the need is acknowledged, for one driver and
> > one mode. keycrypt is meant to be the API that 7524070f26d8 asks for,
> > for keys that stay in a TEE or in hardware, whatever the backend.
> >
> > The interface
> > -------------
> >
> > 1. A key type, "keycrypt", created with add_key() from "new <alg>
> > <purposes> [tier=|min-tier=] [backend=]", "load <blob>
> > [accepted-min-tier=] [purpose=]" or, when allowed, "import <alg>
> > <purposes> [tier=|min-tier=] [backend=] <hex>". User space states the
> > protection a key needs, as a tier, and the kernel chooses the backend
> > that provides it, unless backend= names one. backend= is a constraint
> > added to the tier, never one in its place: a named backend that does
> > not meet tier= or min-tier= gives ENODEV, not a weaker key. It is for
> > a system with more than one backend, an i.MX8 with both the CAAM and
> > OP-TEE say, where a program must choose which mechanism holds a key
> > (the cost of each call, what the key is bound to) and not only how
> > well; the name chooses among mechanisms that meet the tier asked for,
> > it never lowers a tier asked for (without one, it takes that backend
> > at the tier it declares, so a program that needs a tier states it).
> > Its payload read back is a blob that only that backend can open; the
> > material itself never reaches user space.
> > 2. Each key is bound, when it is made, to one algorithm and to the
> > purposes it may serve, checked at every open:
> > a. encrypt and decrypt, for aes256-cbc and aes256-gcm-stream keys:
> > a key that may only encrypt lets a device write data it cannot
> > read back, a key that may only decrypt the reverse;
> > b. mac and verify, for hmac-sha256 keys: "mac" computes a tag over
> > data, "verify" only checks a tag given by the caller, so a
> > component holding a verify-only key can authenticate data (a
> > configuration, an update) but cannot produce a tag that would
> > pass. VERIFY takes the expected tag at FINAL and answers 0 or
> > EBADMSG; the tag it computed never leaves the backend. For
> > example, a server authenticates the commands it sends to a fleet
> > of devices with HMAC-SHA256, and every device holds the same key,
> > imported at the factory as verify-only. With a plain HMAC key,
> > root on one device could extract it and forge commands for the
> > whole fleet; with a verify-only keycrypt key held by a tee or hsm
> > backend, a compromised device can still check commands but can
> > neither read the key nor compute a tag that passes. It comes
> > close to what a signature gives (everyone verifies, only the
> > server signs), with a MAC, as long as no device's TEE or HSM is
> > broken: the key is the fleet's, so the device that breaks forges
> > for all of it, which a signature would not allow.
> > 3. KEYCTL_CRYPT_OPEN (keyctl 33) opens an operation context on a key and
> > returns an fd; ioctls on it: KEYCRYPT_IOC_UPDATE, KEYCRYPT_IOC_FINAL,
> > KEYCRYPT_IOC_SEGMENT (the GCM stream, patch 9) and KEYCRYPT_IOC_INFO,
> > which tells a program holding only the fd (passed by SCM_RIGHTS, say)
> > the operation, the minimum tier it was opened with, and the
> > algorithm, purposes, tier, origin and backend of the key it is using.
> > Search permission on the key is the right to open it; the caller may
> > name the lowest tier it accepts (accepted_min_tier), and a key below
> > it is refused.
> > 4. Policies: kernel.keys.keycrypt_system_tier and
> > kernel.keys.keycrypt_import (also the boot parameters
> > keycrypt.system_tier= and keycrypt.import=), one-way, so that a
> > system can refuse the use of low-tier keys or clear-key import for
> > good. The system tier is a floor on use only: keys below it can
> > still be made and loaded, but KEYCTL_CRYPT_OPEN refuses them. Its
> > starting value is chosen at build time
> > (CONFIG_KEYCRYPT_SYSTEM_TIER_*), so a signed kernel image carries a
> > floor its command line cannot lower; likewise, a kernel built
> > without CONFIG_KEYCRYPT_IMPORT refuses import whatever its command
> > line or sysctl say.
> > 5. EOPNOTSUPP from KEYCTL_CRYPT_OPEN means "not a keycrypt key", or a
> > kernel without keycrypt, so a library may fall back to another
> > interface on it; ENODEV means no backend can run the key.
> >
> > Tiers and what a compromised kernel can do
> > ------------------------------------------
> >
> > Each backend declares a tier, and the open path checks it against the
> > system tier and the caller's accepted minimum:
> >
> > tier key in clear purpose enforced by who may use the key
> > in the kernel
> > kernel yes the kernel the kernel
> > engine no the kernel the kernel
> > tee no the TA the kernel
> > hsm no the HSM the kernel
> >
> > The last column is the limit of the mechanism: a compromised kernel can
> > use a tee or hsm key for the purposes it already has, but cannot extract
> > it or change its purpose. Documentation/security/keys/keycrypt.rst,
> > "Backend requirements", is the contract a tee or hsm backend must meet.
> >
> > 1. kernel: the keys are in clear in kernel memory while loaded. It is
> > there so that the same interface works on a system with no TEE and
> > no suitable hardware, where it still keeps the key out of user space
> > and out of the root filesystem; its one backend, sw, is off by
> > default (CONFIG_KEYCRYPT_SW), and a system that has one of the
> > other tiers should use it, engine at least, and raise the system
> > tier accordingly. Raising it stops the use of kernel-tier keys, not
> > their presence: one created or loaded below it is in clear all the
> > same, as its trusted master is, so a system that must have none
> > builds without CONFIG_KEYCRYPT_SW.
> > 2. engine: a crypto engine the kernel drives keeps the key, never in
> > clear in the kernel, but its use is decided by the kernel only. It
> > comes in patch 6, on its own, so that patches 1-5 stand without a
> > tier no backend of theirs declares. The CAAM backend of this series
> > is an engine, since the CAAM does not check what a key is used for;
> > an ELE backend (below) would start as an engine too, and could move
> > to hsm once the firmware is confirmed to enforce a key's purpose. If
> > more such shades appear, a separate property may fit better than
> > more tiers, and I would welcome an opinion.
> > 3. tee: the OP-TEE backend; the TA re-checks every operation against
> > the purposes it bound when the key was sealed.
> > 4. hsm: as tee, in dedicated hardware apart from the CPU running the
> > kernel (a secure element, a security core of its own such as NXP's
> > EdgeLock Enclave, a crypto engine with its own policy), the place of
> > Android KeyMint's StrongBox; no backend in this series.
> >
> > The backends
> > ------------
> >
> > 1. sw, of the kernel tier (no name is both a tier's and a backend's):
> > keys sealed with AES-256-GCM under a key derived with HMAC-SHA256
> > from a trusted key (any trusted-key source); HKDF-derived stream
> > subkeys; lib/crypto AES. Where the trusted key
> > comes from a TPM, the TPM only unseals that master when a key is
> > loaded; the data itself is ciphered on the CPU, never by the TPM.
> > 2. OP-TEE: a trusted application, an early TA, REE kernel login only;
> > it derives its sealing key from OP-TEE's hardware-unique-key
> > service. The TA is written (ta/keycrypt, one patch to optee_os) and
> > is the one that ran on the hardware below, but I have not proposed
> > it to OP-TEE yet: I would first like to know whether this direction
> > can go on. I can publish it for anyone who wants to try it and is
> > willing to support the work.
> > 3. CAAM: patches 7 and 8, a proposal and not to be applied as they
> > are.
> > They are based on Richard Weinberger's "crypto: caam" series v1 (see
> > "Base and prerequisites") and never ran on a CAAM. Questions for the
> > CAAM maintainers:
> > a. is an internal cbc(paes) taking the caller's key modifier an
> > acceptable form;
> > b. can a job generate a key in the CAAM and keep it black without it
> > crossing kernel memory;
> > c. can the use of a key be checked by something a compromised kernel
> > does not drive: trusted descriptors, which would let the CAAM
> > itself enforce a key's purpose and make the backend hsm, or a job
> > ring owned by the secure world, which would make it tee;
> > d. could cbc(paes) take CCM black keys, which are authenticated where
> > ECB ones are not, once the driver handles their extra length
> > (Weinberger's series refuses them, so the backend uses ECB).
> > 4. ELE (i.MX9), not in this series: this is an RFC, and I am not an
> > expert of the enclave, so I would rather know first what NXP thinks
> > of it, and whether they would be willing to propose an ELE backend
> > themselves, as an engine or, better, as an hsm. As far as I can see,
> > the se_if driver in linux-next gives user space a misc device with a
> > generic send-and-receive ioctl for the enclave's messages, and offers
> > nothing to other kernel code. A per-operation in-kernel API exported
> > by that driver (open a key store reserved to the kernel, generate a
> > key, import a wrapped one, read a key's attributes, delete it,
> > AES-CBC and MAC in one call) would let a keycrypt backend use the
> > enclave. Questions for NXP:
> > a. does the firmware enforce a key's key_usage and permitted_algo on
> > every operation, min_mac_length when verifying, and never release
> > a generated key in clear (yes to all three would make the backend
> > hsm rather than engine);
> > b. could a key be exported wrapped under a device-unique key and
> > imported again, so that a keycrypt blob holds the key itself
> > rather than a reference to the enclave's key store;
> > c. is the key that wraps an imported key unique per device;
> > d. the user-space library has a streaming MAC (hsm_mac() with its
> > INIT, UPDATE_DATA and FINALIZE flags): would the firmware offer
> > it to the kernel for a key in its key store;
> > e. can a key_id be reused after a key is deleted (the library's
> > documentation does not say);
> > f. would a per-operation API of this kind answer the objection Arnd
> > Bergmann raised to the generic passthrough
> > (<2034fb2f-f169-46a5-85e8-fa723ddb0360@app.fastmail.com>).
> >
> > Base and prerequisites
> > ----------------------
> >
> > The series is based on mainline v7.4-rc2-92 (067c5c24cef2). Patches
> > 1-6, and patch 9 on top of them, apply on it alone. Patches 7 and 8, the
> > CAAM proposal, need Richard
> > Weinberger's "crypto: caam" series v1
> > (<20260726081504.2182951-1-richard@nod.at>, three patches, listed as
> > prerequisites below) applied first, for example with:
> >
> > b4 am -o - 20260726081504.2182951-1-richard@nod.at | git am
> >
> > Testing
> > -------
> >
> > The series comes without its tests. There are KUnit suites for the
> > core and the sw, OP-TEE and CAAM backends, and a kselftest for the user
> > ABI, with a case for every reachable row of keycrypt.rst's error
> > tables; together they are larger than the code they test, so I am
> > keeping them for the non-RFC series, once the direction is agreed. The
> > results below that name them come from the series with the tests in it.
> > Taking them out removed only the tests and the hooks that let them
> > reach the code's internals (static functions made visible and exported
> > to KUnit modules): with CONFIG_KUNIT off, the posted patches build for
> > arm64 to the same instructions as that series.
> >
> > On that base, with Weinberger's three patches applied: built for arm64
> > with W=1 (security/keys/keycrypt/ and drivers/crypto/caam/, no
> > warning), and, with the tests on top, the KUnit suites pass on UML
> > but for the one case that needs the system tier above kernel (by
> > Kconfig or boot parameter). Patches 1-6 and 9 alone, on the base without
> > Weinberger's patches: the same build of security/keys/keycrypt/, no
> > warning.
> > The runs below were made on that series at v7.3 on QEMU, and, without
> > the CAAM code, backported to NXP's 6.18, on QEMU and on hardware:
> >
> > 1. QEMU (qemuarm64-secureboot, OP-TEE 4.9.0, an fTPM as the source of
> > the trusted master): the KUnit suites and the kselftest passed on
> > the sw and OP-TEE backends, a case skipped only where its backend
> > was absent (the CAAM) or where it needs a one-way policy setting;
> > the TA's unbind and bind; persistence of a blob across a restart.
> > QEMU proves function, not secrecy: its hardware unique key is a stub.
> > 2. Hardware: the series, backported to NXP's linux-imx lf-6.18.2-1.0.0
> > (six upstream prerequisites; the two CAAM patches left out), with the
> > TA built as an early TA into NXP's imx-optee-os 4.8.0, ran on an
> > i.MX93 board with secure boot closed (AHAB), where OP-TEE derives the
> > key that seals the TA's key blobs from the EdgeLock Enclave's
> > hardware unique key. The KUnit suites and the kselftest passed on
> > the OP-TEE backend, a case skipped only where its backend was absent
> > (sw, which 6.18 cannot build for lack of the library AES it needs,
> > and the CAAM, left out) or where it needs a one-way policy setting.
> > A key generated in OP-TEE and kept as its blob
> > was loaded back after a reboot and after a full power-off, and
> > decrypted a file encrypted before them. The same AES-256-CBC key and
> > IV through AF_ALG (cbc-aes-ce), through keycrypt and through openssl
> > gave identical ciphertexts.
> > 3. Cost on that board (Cortex-A55), AES-256-CBC, per call on an open
> > context: keycrypt with the OP-TEE backend 59-62us up to 256 bytes,
> > ~106us at 4KiB, 880-930us at 64KiB (67-71MiB/s); AF_ALG cbc-aes-ce
> > 6-7, 12-14 and 110-138us (454-570MiB/s). Opening a context costs
> > ~500us, against ~9us for an AF_ALG accept on a keyed socket (~25us
> > for the whole AF_ALG setup). OP-TEE's own benchmark (xtest
> > --aes-perf, from user space through libteec) on the same board gives
> > ~64us per call plus ~1.5ns per byte. keycrypt's fixed cost matches
> > that round trip to the secure world; its remaining ~11ns per byte is
> > spent in this prototype's own data path (buffer allocation and
> > copies between user space, kernel, shared memory and the TA); which
> > part dominates is not yet measured, and it is to be reduced.
> >
> > A user-space consumer exists: craf, the archive tool of crypto-afalg,
> > has a keycrypt backend on the keycrypt branch of
> > https://github.com/giometti/crypto-afalg (tag keycrypt-board-5 is the
> > version that ran on the hardware above). Its enc command, an openssl
> > enc that takes its key from the keyring, shows what a keycrypt key
> > carries. A key made once as
> >
> > k=$(keyctl add keycrypt demo \
> > "new aes256-cbc encrypt,decrypt min-tier=tee" @u)
> >
> > is bound there to AES-256-CBC, to encrypting and decrypting, and to a
> > backend of tier tee at least, chosen by the kernel; so
> >
> > craf enc -enc-key $k -iv <hex> < plain > cipher
> > craf enc -d -enc-key $k -iv <hex> < cipher > plain
> >
> > need nothing else: the open takes no algorithm and no backend, the key
> > brings them, and its tier is enforced by the kernel against
> > -enc-min-tier or the system's tier. Any other key goes to AF_ALG, and
> > the command line must name the cipher. On the board, craf enc with an
> > imported keycrypt key and openssl enc with the same key bytes and IV
> > each decrypted what the other encrypted.
> >
> > While testing the user-space side of this series, craf's test suite hit
> > the KEYCTL_PKEY_VERIFY regression of cb481e59ea6c, which lets a short
> > RSA signature verify: it is fixed by Florian Bauckholt's patch [1], and
> > the reproducer was reported in [2].
>
> I likely have never time to read this. Thus, NAK.
Would you yourself enjoy reading the above? Have you read it word by word?
It fails on projecting "extraordinary to ordinary". That makes this
random code with no context.
Br, Jarkko
^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
` (9 preceding siblings ...)
2026-11-18 14:31 ` [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Jarkko Sakkinen
@ 2026-11-18 14:57 ` Marco Felsch
2026-11-18 15:07 ` Jarkko Sakkinen
10 siblings, 1 reply; 14+ messages in thread
From: Marco Felsch @ 2026-11-18 14:57 UTC (permalink / raw)
To: Rodolfo Giometti
Cc: David Howells, Jarkko Sakkinen, keyrings, Herbert Xu,
David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, kernel
Hi Rodolfo,
thanks for the RFC and bringing this up. Please see my comments below.
On 26-11-18 15:04, Rodolfo Giometti wrote:
> This RFC proposes a key type, "keycrypt", whose material user space can
Albeit I'm not against a new key-type we already have plenty types.
Furthermore the keyctl API is very open, lacks a common API. E.g. for the
'trusted-key' keytype userspace needs to know the actual used backend
because each backend handles it differently.
Therefore I wouldn't add further keytypes till we have a common API
which the userspace can rely on.
> use for symmetric operations but never read: AES-256-CBC, HMAC-SHA256
> and an authenticated AES-256-GCM stream, through a file descriptor that
> KEYCTL_CRYPT_OPEN returns for one key and one operation. The key is held
> by a backend: the kernel itself (sealed under a trusted key), an OP-TEE
> trusted application, or, as a proposal only, the CAAM. I am asking
> whether this is a direction the keyrings, crypto and TEE maintainers
> would take, before polishing it further.
So it's not a new keytype but a new mechanism to handle trusted-keys
from userspace?
> Patch 9, the authenticated stream, is a proposal on its own and not
> needed by the rest of the series: it is a construction of keycrypt's
> own, and patches 1-8 do not depend on it, so it can be discussed, or
> left out, apart from them. No user-space consumer uses the stream or
> HMAC-SHA256 yet: craf (below) uses CBC only. If this direction is found
> acceptable, one of the next steps is to bring craf's keycrypt backend
> into craf's main line, with the stream and HMAC-SHA256, as long as
> doing so does not stand in the way of this RFC or of the series I hope
> will follow it.
>
> The problem
> -----------
>
> An embedded product that encrypts its own data (a root filesystem
> archive, configuration backups, logs) needs a key that does not sit in
> the root filesystem and that a compromised user space cannot copy. Today
^
What exactly do you mean by copy?
If you're using the standard LUKS2 scheme, the (volume)key never sits
inside encrypted device. The key is part of the LUKS2 header. Maybe I
didn't got your use-case, can you please elaborate a bit more?
> user space either reads the key (a user or logon key handed to AF_ALG)
> or cannot use it at all (a trusted key serves kernel consumers only).
> AF_ALG, the one interface that let user space drive a key the kernel
> held, has moved away from that use: v7.2 dropped off-CPU cryptography
> from it (7524070f26d8, "crypto: af_alg - Drop support for off-CPU
> cryptography"), whose message says "If using an off-CPU accelerator
> really does turn out to be a win, a new API should be developed that is
> actually a good fit for it", and v7.3 restricted it to allowlisted
> generic algorithms by default (2f204fe718f5, the af_alg_restrict
> sysctl). One exception was let back in, cbc(paes) with a CAAM blob in
> place of the key, because "this crypto operation cannot be implemented
> in a userspace library" (285d8204638c, v7.2), for privileged users only
> (d9506e82ced5, v7.3): the need is acknowledged, for one driver and
> one mode. keycrypt is meant to be the API that 7524070f26d8 asks for,
> for keys that stay in a TEE or in hardware, whatever the backend.
Above you mentioned trusted-keys, but trusted-keys don't let the key
stay inside the TEE. Albeit the key is only reachable kernel (EL1) it is
always reachable from normal world. So a kernel CVE could leak the key
as well. This is different compared to protected keys like
p(rotected)aes. Here the keys always stay within firmware/secure-world.
I didn't get your problem from your above description, sorry and
therefore I'm asking.
Do you want to use trusted-keys for partition (rootfs, data, ...)
encryption? In such case I've developed another idea which I'm about to
post as RFC.
> The interface
> -------------
>
> 1. A key type, "keycrypt", created with add_key() from "new <alg>
> <purposes> [tier=|min-tier=] [backend=]", "load <blob>
> [accepted-min-tier=] [purpose=]" or, when allowed, "import <alg>
> <purposes> [tier=|min-tier=] [backend=] <hex>". User space states the
This is exactly what I meant at the begining. I'm not a maintainer, but
this string parsing "API" is very error-prone. Furthermore, how can a
userspace enum available backends? Instead of try and error I would like
to see a query/enum phase and later on userspace can decide which
backend and tier to use.
> protection a key needs, as a tier, and the kernel chooses the backend
> that provides it, unless backend= names one. backend= is a constraint
> added to the tier, never one in its place: a named backend that does
> not meet tier= or min-tier= gives ENODEV, not a weaker key. It is for
> a system with more than one backend, an i.MX8 with both the CAAM and
> OP-TEE say, where a program must choose which mechanism holds a key
> (the cost of each call, what the key is bound to) and not only how
> well; the name chooses among mechanisms that meet the tier asked for,
> it never lowers a tier asked for (without one, it takes that backend
> at the tier it declares, so a program that needs a tier states it).
> Its payload read back is a blob that only that backend can open; the
> material itself never reaches user space.
> 2. Each key is bound, when it is made, to one algorithm and to the
> purposes it may serve, checked at every open:
> a. encrypt and decrypt, for aes256-cbc and aes256-gcm-stream keys:
> a key that may only encrypt lets a device write data it cannot
> read back, a key that may only decrypt the reverse;
> b. mac and verify, for hmac-sha256 keys: "mac" computes a tag over
> data, "verify" only checks a tag given by the caller, so a
> component holding a verify-only key can authenticate data (a
> configuration, an update) but cannot produce a tag that would
> pass. VERIFY takes the expected tag at FINAL and answers 0 or
> EBADMSG; the tag it computed never leaves the backend. For
> example, a server authenticates the commands it sends to a fleet
> of devices with HMAC-SHA256, and every device holds the same key,
> imported at the factory as verify-only. With a plain HMAC key,
> root on one device could extract it and forge commands for the
> whole fleet; with a verify-only keycrypt key held by a tee or hsm
> backend, a compromised device can still check commands but can
> neither read the key nor compute a tag that passes. It comes
> close to what a signature gives (everyone verifies, only the
> server signs), with a MAC, as long as no device's TEE or HSM is
> broken: the key is the fleet's, so the device that breaks forges
> for all of it, which a signature would not allow.
> 3. KEYCTL_CRYPT_OPEN (keyctl 33) opens an operation context on a key and
> returns an fd; ioctls on it: KEYCRYPT_IOC_UPDATE, KEYCRYPT_IOC_FINAL,
> KEYCRYPT_IOC_SEGMENT (the GCM stream, patch 9) and KEYCRYPT_IOC_INFO,
> which tells a program holding only the fd (passed by SCM_RIGHTS, say)
> the operation, the minimum tier it was opened with, and the
> algorithm, purposes, tier, origin and backend of the key it is using.
> Search permission on the key is the right to open it; the caller may
> name the lowest tier it accepts (accepted_min_tier), and a key below
> it is refused.
> 4. Policies: kernel.keys.keycrypt_system_tier and
> kernel.keys.keycrypt_import (also the boot parameters
> keycrypt.system_tier= and keycrypt.import=), one-way, so that a
> system can refuse the use of low-tier keys or clear-key import for
> good. The system tier is a floor on use only: keys below it can
> still be made and loaded, but KEYCTL_CRYPT_OPEN refuses them. Its
> starting value is chosen at build time
> (CONFIG_KEYCRYPT_SYSTEM_TIER_*), so a signed kernel image carries a
> floor its command line cannot lower; likewise, a kernel built
> without CONFIG_KEYCRYPT_IMPORT refuses import whatever its command
> line or sysctl say.
> 5. EOPNOTSUPP from KEYCTL_CRYPT_OPEN means "not a keycrypt key", or a
> kernel without keycrypt, so a library may fall back to another
> interface on it; ENODEV means no backend can run the key.
>
> Tiers and what a compromised kernel can do
> ------------------------------------------
>
> Each backend declares a tier, and the open path checks it against the
> system tier and the caller's accepted minimum:
>
> tier key in clear purpose enforced by who may use the key
> in the kernel
> kernel yes the kernel the kernel
These are basically the trusted-key purpose.
> engine no the kernel the kernel
> tee no the TA the kernel
> hsm no the HSM the kernel
These are protected keys which we have already (see S390, CAAM, DCP,
Zynqmp, ...).
I don't see what you want to solve with your approach. Do you want to
have a common interface for generating/loading protected keys?
That beeing said, loading protected keys can already be done by just
specifying the correct key-cipher. Generating the key is platform
specific and would need a common API.
Thanks for sharing your ideas :)
Regards,
Marco
> The last column is the limit of the mechanism: a compromised kernel can
> use a tee or hsm key for the purposes it already has, but cannot extract
> it or change its purpose. Documentation/security/keys/keycrypt.rst,
> "Backend requirements", is the contract a tee or hsm backend must meet.
>
> 1. kernel: the keys are in clear in kernel memory while loaded. It is
> there so that the same interface works on a system with no TEE and
> no suitable hardware, where it still keeps the key out of user space
> and out of the root filesystem; its one backend, sw, is off by
> default (CONFIG_KEYCRYPT_SW), and a system that has one of the
> other tiers should use it, engine at least, and raise the system
> tier accordingly. Raising it stops the use of kernel-tier keys, not
> their presence: one created or loaded below it is in clear all the
> same, as its trusted master is, so a system that must have none
> builds without CONFIG_KEYCRYPT_SW.
> 2. engine: a crypto engine the kernel drives keeps the key, never in
> clear in the kernel, but its use is decided by the kernel only. It
> comes in patch 6, on its own, so that patches 1-5 stand without a
> tier no backend of theirs declares. The CAAM backend of this series
> is an engine, since the CAAM does not check what a key is used for;
> an ELE backend (below) would start as an engine too, and could move
> to hsm once the firmware is confirmed to enforce a key's purpose. If
> more such shades appear, a separate property may fit better than
> more tiers, and I would welcome an opinion.
> 3. tee: the OP-TEE backend; the TA re-checks every operation against
> the purposes it bound when the key was sealed.
> 4. hsm: as tee, in dedicated hardware apart from the CPU running the
> kernel (a secure element, a security core of its own such as NXP's
> EdgeLock Enclave, a crypto engine with its own policy), the place of
> Android KeyMint's StrongBox; no backend in this series.
>
> The backends
> ------------
>
> 1. sw, of the kernel tier (no name is both a tier's and a backend's):
> keys sealed with AES-256-GCM under a key derived with HMAC-SHA256
> from a trusted key (any trusted-key source); HKDF-derived stream
> subkeys; lib/crypto AES. Where the trusted key
> comes from a TPM, the TPM only unseals that master when a key is
> loaded; the data itself is ciphered on the CPU, never by the TPM.
> 2. OP-TEE: a trusted application, an early TA, REE kernel login only;
> it derives its sealing key from OP-TEE's hardware-unique-key
> service. The TA is written (ta/keycrypt, one patch to optee_os) and
> is the one that ran on the hardware below, but I have not proposed
> it to OP-TEE yet: I would first like to know whether this direction
> can go on. I can publish it for anyone who wants to try it and is
> willing to support the work.
> 3. CAAM: patches 7 and 8, a proposal and not to be applied as they
> are.
> They are based on Richard Weinberger's "crypto: caam" series v1 (see
> "Base and prerequisites") and never ran on a CAAM. Questions for the
> CAAM maintainers:
> a. is an internal cbc(paes) taking the caller's key modifier an
> acceptable form;
> b. can a job generate a key in the CAAM and keep it black without it
> crossing kernel memory;
> c. can the use of a key be checked by something a compromised kernel
> does not drive: trusted descriptors, which would let the CAAM
> itself enforce a key's purpose and make the backend hsm, or a job
> ring owned by the secure world, which would make it tee;
> d. could cbc(paes) take CCM black keys, which are authenticated where
> ECB ones are not, once the driver handles their extra length
> (Weinberger's series refuses them, so the backend uses ECB).
> 4. ELE (i.MX9), not in this series: this is an RFC, and I am not an
> expert of the enclave, so I would rather know first what NXP thinks
> of it, and whether they would be willing to propose an ELE backend
> themselves, as an engine or, better, as an hsm. As far as I can see,
> the se_if driver in linux-next gives user space a misc device with a
> generic send-and-receive ioctl for the enclave's messages, and offers
> nothing to other kernel code. A per-operation in-kernel API exported
> by that driver (open a key store reserved to the kernel, generate a
> key, import a wrapped one, read a key's attributes, delete it,
> AES-CBC and MAC in one call) would let a keycrypt backend use the
> enclave. Questions for NXP:
> a. does the firmware enforce a key's key_usage and permitted_algo on
> every operation, min_mac_length when verifying, and never release
> a generated key in clear (yes to all three would make the backend
> hsm rather than engine);
> b. could a key be exported wrapped under a device-unique key and
> imported again, so that a keycrypt blob holds the key itself
> rather than a reference to the enclave's key store;
> c. is the key that wraps an imported key unique per device;
> d. the user-space library has a streaming MAC (hsm_mac() with its
> INIT, UPDATE_DATA and FINALIZE flags): would the firmware offer
> it to the kernel for a key in its key store;
> e. can a key_id be reused after a key is deleted (the library's
> documentation does not say);
> f. would a per-operation API of this kind answer the objection Arnd
> Bergmann raised to the generic passthrough
> (<2034fb2f-f169-46a5-85e8-fa723ddb0360@app.fastmail.com>).
>
> Base and prerequisites
> ----------------------
>
> The series is based on mainline v7.4-rc2-92 (067c5c24cef2). Patches
> 1-6, and patch 9 on top of them, apply on it alone. Patches 7 and 8, the
> CAAM proposal, need Richard
> Weinberger's "crypto: caam" series v1
> (<20260726081504.2182951-1-richard@nod.at>, three patches, listed as
> prerequisites below) applied first, for example with:
>
> b4 am -o - 20260726081504.2182951-1-richard@nod.at | git am
>
> Testing
> -------
>
> The series comes without its tests. There are KUnit suites for the
> core and the sw, OP-TEE and CAAM backends, and a kselftest for the user
> ABI, with a case for every reachable row of keycrypt.rst's error
> tables; together they are larger than the code they test, so I am
> keeping them for the non-RFC series, once the direction is agreed. The
> results below that name them come from the series with the tests in it.
> Taking them out removed only the tests and the hooks that let them
> reach the code's internals (static functions made visible and exported
> to KUnit modules): with CONFIG_KUNIT off, the posted patches build for
> arm64 to the same instructions as that series.
>
> On that base, with Weinberger's three patches applied: built for arm64
> with W=1 (security/keys/keycrypt/ and drivers/crypto/caam/, no
> warning), and, with the tests on top, the KUnit suites pass on UML
> but for the one case that needs the system tier above kernel (by
> Kconfig or boot parameter). Patches 1-6 and 9 alone, on the base without
> Weinberger's patches: the same build of security/keys/keycrypt/, no
> warning.
> The runs below were made on that series at v7.3 on QEMU, and, without
> the CAAM code, backported to NXP's 6.18, on QEMU and on hardware:
>
> 1. QEMU (qemuarm64-secureboot, OP-TEE 4.9.0, an fTPM as the source of
> the trusted master): the KUnit suites and the kselftest passed on
> the sw and OP-TEE backends, a case skipped only where its backend
> was absent (the CAAM) or where it needs a one-way policy setting;
> the TA's unbind and bind; persistence of a blob across a restart.
> QEMU proves function, not secrecy: its hardware unique key is a stub.
> 2. Hardware: the series, backported to NXP's linux-imx lf-6.18.2-1.0.0
> (six upstream prerequisites; the two CAAM patches left out), with the
> TA built as an early TA into NXP's imx-optee-os 4.8.0, ran on an
> i.MX93 board with secure boot closed (AHAB), where OP-TEE derives the
> key that seals the TA's key blobs from the EdgeLock Enclave's
> hardware unique key. The KUnit suites and the kselftest passed on
> the OP-TEE backend, a case skipped only where its backend was absent
> (sw, which 6.18 cannot build for lack of the library AES it needs,
> and the CAAM, left out) or where it needs a one-way policy setting.
> A key generated in OP-TEE and kept as its blob
> was loaded back after a reboot and after a full power-off, and
> decrypted a file encrypted before them. The same AES-256-CBC key and
> IV through AF_ALG (cbc-aes-ce), through keycrypt and through openssl
> gave identical ciphertexts.
> 3. Cost on that board (Cortex-A55), AES-256-CBC, per call on an open
> context: keycrypt with the OP-TEE backend 59-62us up to 256 bytes,
> ~106us at 4KiB, 880-930us at 64KiB (67-71MiB/s); AF_ALG cbc-aes-ce
> 6-7, 12-14 and 110-138us (454-570MiB/s). Opening a context costs
> ~500us, against ~9us for an AF_ALG accept on a keyed socket (~25us
> for the whole AF_ALG setup). OP-TEE's own benchmark (xtest
> --aes-perf, from user space through libteec) on the same board gives
> ~64us per call plus ~1.5ns per byte. keycrypt's fixed cost matches
> that round trip to the secure world; its remaining ~11ns per byte is
> spent in this prototype's own data path (buffer allocation and
> copies between user space, kernel, shared memory and the TA); which
> part dominates is not yet measured, and it is to be reduced.
>
> A user-space consumer exists: craf, the archive tool of crypto-afalg,
> has a keycrypt backend on the keycrypt branch of
> https://github.com/giometti/crypto-afalg (tag keycrypt-board-5 is the
> version that ran on the hardware above). Its enc command, an openssl
> enc that takes its key from the keyring, shows what a keycrypt key
> carries. A key made once as
>
> k=$(keyctl add keycrypt demo \
> "new aes256-cbc encrypt,decrypt min-tier=tee" @u)
>
> is bound there to AES-256-CBC, to encrypting and decrypting, and to a
> backend of tier tee at least, chosen by the kernel; so
>
> craf enc -enc-key $k -iv <hex> < plain > cipher
> craf enc -d -enc-key $k -iv <hex> < cipher > plain
>
> need nothing else: the open takes no algorithm and no backend, the key
> brings them, and its tier is enforced by the kernel against
> -enc-min-tier or the system's tier. Any other key goes to AF_ALG, and
> the command line must name the cipher. On the board, craf enc with an
> imported keycrypt key and openssl enc with the same key bytes and IV
> each decrypted what the other encrypted.
>
> While testing the user-space side of this series, craf's test suite hit
> the KEYCTL_PKEY_VERIFY regression of cb481e59ea6c, which lets a short
> RSA signature verify: it is fixed by Florian Bauckholt's patch [1], and
> the reproducer was reported in [2].
>
> [1] https://lore.kernel.org/keyrings/20261111-keyctl-pkey-fixes-v1-1-934ebaa267a7@cispa.de/
> [2] https://lore.kernel.org/all/0e20f799-e389-40d2-aaee-2f174748faae@enneenne.com/
>
> Why not AF_ALG or KEYCTL_PKEY_*
> -------------------------------
>
> They are the two existing interfaces through which user space uses a
> key it does not read, so they are the first alternatives a reviewer
> will name; keycrypt.rst has a section on them.
>
> 1. AF_ALG takes a trusted key by serial (ALG_SET_KEY_BY_KEY_SERIAL),
> but copies its payload into the socket, ties it to no algorithm and
> no purpose, and runs it on whatever implementation the socket is
> bound to, since v7.2 only on the CPU but for cbc(paes); extending it
> would mean adding purposes, tiers and off-CPU backends to what it
> has just removed.
> 2. KEYCTL_PKEY_* already lets user space use a key without reading it,
> but for asymmetric keys, one operation per call; a symmetric mode
> needs state across calls (the CBC chain, the stream's segments),
> which an fd holds naturally.
>
> Whether one of them should be extended instead is the first question I
> would like answered.
>
> Known limits
> ------------
>
> Some are limits of the design, kept on purpose:
>
> 1. Only the sw backend is self-contained in the tree; every guarantee
> against a compromised kernel is a requirement on the other backends,
> which "Backend requirements" in keycrypt.rst sets out.
> 2. Kernel-tier keys are in clear in kernel memory while loaded: that
> tier is there for systems with nothing better, and a system that has
> more can refuse it (above).
> 3. The tier is declared by the backend, not proven: the kernel cannot
> check what a TEE or a piece of hardware does, so it records and
> enforces what the backend declares.
> 4. A blob is a bearer credential, and a process that possesses a key
> can read its blob: what binds the key is the backend's secret,
> unique to the device, and the purposes sealed with it, not the blob.
> 5. CBC is unauthenticated and is a raw AES oracle for its holder: it is
> there for the formats that need it, and the GCM stream is the
> authenticated choice. The stream is not key-committing, which a
> format trying several keys must handle (keycrypt.rst says how), and
> is bounded at 2^32-1 segments, 256TiB at 64KiB each.
>
> The others I plan to address if this direction is taken:
>
> 6. Checks happen at open only, so an open context survives a raised
> policy or removed Search (revocation closes it): raising a policy
> would close the contexts it no longer allows, as revocation does.
> Whether Search should be the use permission is among the points
> below.
> 7. import moves a clear key through kernel memory: an encrypted import,
> wrapped for the backend, would avoid it. Policies are global: they
> could follow namespaces, if that is wanted, and stay one-way.
> 8. The GCM stream has no seek: decryption could start at a given
> segment (keycrypt.rst leaves room for it in the open parameters);
> encryption never will, so that no counter is used twice.
> 9. OP-TEE backend: its control session is not reopened after a TA
> panic, the TA's session limit is a build constant, and every context
> has shared buffers of its own: the session would be reopened, the
> limit made configurable, and the buffers taken from a pool, as part
> of the work on the per-byte cost above.
> 10. No keyutils or man-page support yet: to be added.
>
> Other points I would like opinions on:
>
> 1. two KDFs and a stream construction living in security/keys rather
> than reusable primitives;
> 2. Search as the use permission;
> 3. an rwsem held across sleeping backend calls;
> 4. whether a KEYCTL_CAPS1_* bit telling a process once that keycrypt
> is there would help (not in this series).
>
> Not in this RFC: signatures, ECDH, encrypted import, io_uring, other
> modes; ELE code; external secure elements as backends.
>
> How this series was made
> ------------------------
>
> This work comes from a project to strengthen the secure-boot chain of
> embedded Linux systems.
>
> I used an AI coding assistant, Anthropic's Claude (claude-opus-5-5 in
> Claude Code), in the sense of
> Documentation/process/coding-assistants.rst. However, the way the
> problem is solved is mine: a new key type, so that user space can go on
> using keys it never reads while AF_ALG drops off-CPU cryptography and
> restricts what it allows, built on backends that hold the key and on
> tiers that say what a backend protects against, the engine one
> included. I directed the design and took its decisions, choosing among
> the options the assistant set out or bringing my own. The assistant
> surveyed the prior art, set out the design options with a
> recommendation at each step, and wrote the code, the KUnit tests, the
> selftests (not posted, see Testing) and the documentation under my
> direction, in plans I approved, partly through lower-tier Claude models
> it dispatched for individual tasks; each plan was followed by an AI
> review that I read.
> Claude also built and ran the QEMU bench and analysed the hardware run,
> which another Claude session carried out with me at the board.
>
> I have reviewed every patch and I am responsible for all of it.
>
> Rodolfo Giometti
>
> Rodolfo Giometti (9):
> KEYS: keycrypt: Add a key type for keys user space never reads
> KEYS: keycrypt: Add the sw backend
> KEYS: keycrypt: Add the OP-TEE backend
> docs: keycrypt: document keycrypt keys
> MAINTAINERS: add KEYS-KEYCRYPT
> KEYS: keycrypt: Add the engine tier
> crypto: caam - add an internal cbc(paes) taking the blob's key
> modifier
> KEYS: keycrypt: Add the CAAM backend
> KEYS: keycrypt: Add the aes256-gcm-stream algorithm
>
> .../admin-guide/kernel-parameters.txt | 20 +
> Documentation/security/keys/index.rst | 1 +
> Documentation/security/keys/keycrypt.rst | 1105 +++++++++++++++++
> .../userspace-api/ioctl/ioctl-number.rst | 2 +
> MAINTAINERS | 18 +
> drivers/crypto/caam/caamalg.c | 89 +-
> drivers/crypto/caam/caamalg_desc.c | 3 +-
> drivers/crypto/caam/caamalg_desc.h | 1 +
> include/keys/keycrypt.h | 161 +++
> include/soc/fsl/caam-blob.h | 8 +
> include/uapi/linux/keycrypt.h | 182 +++
> include/uapi/linux/keyctl.h | 1 +
> security/keys/Kconfig | 2 +
> security/keys/Makefile | 1 +
> security/keys/compat.c | 3 +
> security/keys/internal.h | 12 +
> security/keys/keycrypt/Kconfig | 153 +++
> security/keys/keycrypt/Makefile | 9 +
> security/keys/keycrypt/caam.c | 346 ++++++
> security/keys/keycrypt/caam.h | 30 +
> security/keys/keycrypt/core.c | 1077 ++++++++++++++++
> security/keys/keycrypt/ctx.c | 667 ++++++++++
> security/keys/keycrypt/keycrypt.h | 180 +++
> security/keys/keycrypt/optee.c | 489 ++++++++
> security/keys/keycrypt/optee.h | 39 +
> security/keys/keycrypt/sw.c | 468 +++++++
> security/keys/keycrypt/sw.h | 30 +
> security/keys/keyctl.c | 5 +
> 28 files changed, 5090 insertions(+), 12 deletions(-)
> create mode 100644 Documentation/security/keys/keycrypt.rst
> create mode 100644 include/keys/keycrypt.h
> create mode 100644 include/uapi/linux/keycrypt.h
> create mode 100644 security/keys/keycrypt/Kconfig
> create mode 100644 security/keys/keycrypt/Makefile
> create mode 100644 security/keys/keycrypt/caam.c
> create mode 100644 security/keys/keycrypt/caam.h
> create mode 100644 security/keys/keycrypt/core.c
> create mode 100644 security/keys/keycrypt/ctx.c
> create mode 100644 security/keys/keycrypt/keycrypt.h
> create mode 100644 security/keys/keycrypt/optee.c
> create mode 100644 security/keys/keycrypt/optee.h
> create mode 100644 security/keys/keycrypt/sw.c
> create mode 100644 security/keys/keycrypt/sw.h
>
>
> base-commit: 067c5c24cef23d913b67eaaf71ae67e7169a6620
> prerequisite-patch-id: 6f1c5a861378c58d6adea4e1745794466a9d73d6
> prerequisite-patch-id: e1565dff5540351c42ee04e0308649a6d97e9e09
> prerequisite-patch-id: 37ed62269bd4b1fcaeeab38f5feb5b0f63608459
> --
> 2.43.0
>
^ permalink raw reply [flat|nested] 14+ messages in thread
* Re: [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read
2026-11-18 14:57 ` Marco Felsch
@ 2026-11-18 15:07 ` Jarkko Sakkinen
0 siblings, 0 replies; 14+ messages in thread
From: Jarkko Sakkinen @ 2026-11-18 15:07 UTC (permalink / raw)
To: Marco Felsch
Cc: Rodolfo Giometti, David Howells, keyrings, Herbert Xu,
David S. Miller, Jens Wiklander, Sumit Garg, op-tee,
Horia Geantă, Pankaj Gupta, Sahil Malhotra, Ahmad Fatoum,
Richard Weinberger, Christophe Leroy (CS GROUP), Eric Biggers,
Demi Marie Obenour, Arnd Bergmann, Paul Moore, James Morris,
Serge E. Hallyn, Jonathan Corbet, Shuah Khan, Randy Dunlap,
linux-crypto, linux-integrity, linux-security-module,
linux-kselftest, linux-doc, linux-api, linux-arm-kernel,
linuxppc-dev, linux-kernel, kernel
On Wed, Nov 18, 2026 at 03:57:27PM +0100, Marco Felsch wrote:
> These are basically the trusted-key purpose.
This is it.
If I was adding something like this, I would at least:
1. Discuss the solution that would extend trusted keys to the level
that makes it crystal clear that this is won't work out too
well.
2. Then show how the new thing addresses all of this.
If there is any gist this should not require whole a lot of text
dump.
AI assistance should not be really even mentioned the cover letters in
my opinion. It's equal to text editor; or smoke signals. It does not
level down anything i.e., I'm equally dissatified however this was
produced :-)
Br, Jarkko
^ permalink raw reply [flat|nested] 14+ messages in thread
end of thread, other threads:[~2026-11-18 15:08 UTC | newest]
Thread overview: 14+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-18 14:04 [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Rodolfo Giometti
2026-11-18 14:04 ` [RFC PATCH 1/9] KEYS: keycrypt: Add a key type for keys user space never reads Rodolfo Giometti
2026-11-18 14:04 ` [RFC PATCH 2/9] KEYS: keycrypt: Add the sw backend Rodolfo Giometti
2026-11-18 14:04 ` [RFC PATCH 3/9] KEYS: keycrypt: Add the OP-TEE backend Rodolfo Giometti
2026-11-18 14:07 ` [RFC PATCH 4/9] docs: keycrypt: document keycrypt keys Rodolfo Giometti
2026-11-18 14:08 ` [RFC PATCH 5/9] MAINTAINERS: add KEYS-KEYCRYPT Rodolfo Giometti
2026-11-18 14:09 ` [RFC PATCH 6/9] KEYS: keycrypt: Add the engine tier Rodolfo Giometti
2026-11-18 14:10 ` [RFC PATCH 7/9] crypto: caam - add an internal cbc(paes) taking the blob's key modifier Rodolfo Giometti
2026-11-18 14:11 ` [RFC PATCH 8/9] KEYS: keycrypt: Add the CAAM backend Rodolfo Giometti
2026-11-18 14:12 ` [RFC PATCH 9/9] KEYS: keycrypt: Add the aes256-gcm-stream algorithm Rodolfo Giometti
2026-11-18 14:31 ` [RFC PATCH 0/9] KEYS: keycrypt: keys that user space can use but never read Jarkko Sakkinen
2026-11-18 14:39 ` Jarkko Sakkinen
2026-11-18 14:57 ` Marco Felsch
2026-11-18 15:07 ` Jarkko Sakkinen
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox