Skip to contentSkip to conversation

KEYS: keycrypt: keys that user space can use but never read

RFC PATCH In review Rodolfo Giometti 5 participants 35 messages Nov 18 – Nov 19

Subsystems (9)
lore
Share & tools
lore
#0 lore raw

cover KEYS: keycrypt: keys that user space can use but never read

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 (<[email protected]>).

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 (<[email protected]>, three patches, listed as prerequisites below) applied first, for example with:

b4 am -o - [email protected] | 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/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

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

Signature · 1 line
2.43.0
#1 lore raw

RFC PATCH 1/9 KEYS: keycrypt: Add a key type for keys user space never reads

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.

---
 .../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
Documentation/admin-guide/kernel-parameters.txt +20 -0
index 0b3c140babd9..62d44a5225e4 100644
@@ -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.
Documentation/userspace-api/ioctl/ioctl-number.rst +2 -0
index dbe462040999..efdace54085b 100644
@@ -387,6 +387,8 @@ Code  Seq#    Include File                                             Comments
                                                                        <mailto:[email protected]>
 0xBA  00-0F  uapi/linux/liveupdate.h                                   Pasha Tatashin
                                                                        <mailto:[email protected]>
+0xBB  00-0F  uapi/linux/keycrypt.h                                     keycrypt
+                                                                       <mailto:[email protected]>
 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
include/keys/keycrypt.h new file +150 -0

150 lines not on this page · raw message

include/uapi/linux/keycrypt.h new file +143 -0

143 lines not on this page · raw message

include/uapi/linux/keyctl.h +1 -0
index 00cc0942203e..1532cc76ab38 100644
@@ -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 {
security/keys/Kconfig +2 -0
index f4510d8cb485..fb0f48f218ef 100644
@@ -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
security/keys/Makefile +1 -0
index 5f40807f05b3..82583db1704b 100644
@@ -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/
security/keys/compat.c +3 -0
index 1545efdca562..80ea06e59ee2 100644
@@ -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;
 	}
security/keys/internal.h +12 -0
index b7b622bc36a1..69de149a0609 100644
@@ -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
  */
security/keys/keycrypt/Kconfig new file +72 -0

72 lines not on this page · raw message

security/keys/keycrypt/Makefile new file +3 -0
new file mode 100644
index 000000000000..8910fb0156e7
@@ -0,0 +1,3 @@
+# SPDX-License-Identifier: GPL-2.0-only
+
+obj-y += core.o ctx.o
security/keys/keycrypt/core.c new file +1070 -0

1,070 lines not on this page · raw message

security/keys/keycrypt/ctx.c new file +530 -0

530 lines not on this page · raw message

security/keys/keycrypt/keycrypt.h new file +173 -0

173 lines not on this page · raw message

security/keys/keyctl.c +5 -0
index d6b10fd67627..d74708b832ea 100644
@@ -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;
 	}
Signature · 1 line
2.43.0
#2 lore raw

Re: [RFC PATCH 1/9] KEYS: keycrypt: Add a key type for keys user space never reads

Sashiko has reviewed this patch and found no issues.
Quoted 21 lines

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.

Quoted 4 lines

Backends register through keycrypt_register_backend(); none is added here, so a well-formed add_key() fails with ENODEV until one is.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
#3 lore raw

RFC PATCH 2/9 KEYS: keycrypt: Add the sw backend

In reply to 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.

---
 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
security/keys/keycrypt/Kconfig +32 -4
index e1d1b8e2a58b..50fd4cb3b1d2 100644
@@ -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.
security/keys/keycrypt/Makefile +2 -0
index 8910fb0156e7..5a2e222a6908 100644
@@ -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
security/keys/keycrypt/sw.c new file +404 -0

404 lines not on this page · raw message

security/keys/keycrypt/sw.h new file +30 -0
new file mode 100644
index 000000000000..30e24fb56ce3
@@ -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 <[email protected]>
+ */
+
+#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 */
Signature · 1 line
2.43.0
#4 lore raw

Re: [RFC PATCH 2/9] KEYS: keycrypt: Add the sw backend

Sashiko has reviewed this patch and found no issues.
Quoted 22 lines

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.

Quoted 3 lines

It depends on TRUSTED_KEYS and is a module when trusted keys are one.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#5 lore raw

RFC PATCH 3/9 KEYS: keycrypt: Add the OP-TEE backend

In reply to 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.

---
 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
security/keys/keycrypt/Kconfig +17 -0
index 50fd4cb3b1d2..e61922933bd7 100644
@@ -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.
security/keys/keycrypt/Makefile +2 -0
index 5a2e222a6908..f051050428cd 100644
@@ -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
security/keys/keycrypt/optee.c new file +437 -0

437 lines not on this page · raw message

security/keys/keycrypt/optee.h new file +37 -0
new file mode 100644
index 000000000000..391eba15b699
@@ -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 <[email protected]>
+ */
+
+#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 */
Signature · 1 line
2.43.0
#6 lore raw

Re: [RFC PATCH 3/9] KEYS: keycrypt: Add the OP-TEE backend

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [High] keys: keycrypt: NULL dereference in kc_optee_remove() after shutdown --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [High] keys: keycrypt: NULL dereference in kc_optee_remove() after shutdown
--

commit 8da0e0d8cf01260109b52bb935a051203beb3758
Author: Rodolfo Giometti <[email protected]>

KEYS: keycrypt: Add the OP-TEE backend

This commit adds the "optee" keycrypt backend driver for the tee tier, using sessions to the keycrypt OP-TEE Trusted Application to seal, load, and run operations on keys.

Quoted 5 lines
security/keys/keycrypt/optee.c new file +0 -0
new file mode 100644
index 0000000000000..5a3ab6f825f17

[ ... ]

Quoted 11 lines
security/keys/keycrypt/optee.c new file +11 -0
+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,

security/keys/keycrypt/optee.c line 428

Quoted 10 lines
security/keys/keycrypt/optee.c new file +10 -0
+		    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,

[Severity: High]
Can kc_optee_remove() run a second time when .remove is called after .shutdown?

device_shutdown() invokes .shutdown without unbinding the driver. On Arm FF-A OP-TEE platforms, device_shutdown() first calls tee_client_device_shutdown() -> kc_optee_remove() on the TA child device, setting kc_optee.tee to NULL, and then reaches the parent FF-A device whose .shutdown callback (ffa_remove() -> ... -> optee_unregister_devices()) unregisters the TA device and calls tee_client_device_remove() -> kc_optee_remove() again.

The second call hits WARN_ON_ONCE(!h) in keycrypt_unregister_backend(), dereferences NULL kc_optee.tee in tee_client_close_session() and tee_client_close_context(), and double frees kc_optee.ctl_shm.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#7 lore raw

RFC PATCH 4/9 docs: keycrypt: document keycrypt keys

In reply to 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.

---
 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
Documentation/security/keys/index.rst +1 -0
index 647d58f2588e..ff44babc7a8f 100644
@@ -7,5 +7,6 @@ Kernel Keys
 
    core
    ecryptfs
+   keycrypt
    request-key
    trusted-encrypted
Documentation/security/keys/keycrypt.rst new file +838 -0

838 lines not on this page · raw message

Signature · 1 line
2.43.0
#8 lore raw

Re: [RFC PATCH 4/9] docs: keycrypt: document keycrypt keys

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

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.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#9 lore raw

RFC PATCH 5/9 MAINTAINERS: add KEYS-KEYCRYPT

In reply to 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.

---
 MAINTAINERS | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
MAINTAINERS +18 -0
index 222b7fc2c3aa..41dc8fe1fb36 100644
@@ -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 <[email protected]>
+L:	[email protected]
+L:	[email protected]
+L:	[email protected]
+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 <[email protected]>
+L:	[email protected]
+L:	[email protected] (moderated for non-subscribers)
+S:	Maintained
+F:	security/keys/keycrypt/optee*
+
 KEYS-TRUSTED
 M:	James Bottomley <[email protected]>
 M:	Jarkko Sakkinen <[email protected]>
Signature · 1 line
2.43.0
#10 lore raw

RFC PATCH 6/9 KEYS: keycrypt: Add the engine tier

In reply to 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.

---
 .../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(-)
Documentation/admin-guide/kernel-parameters.txt +1 -1
index 62d44a5225e4..0cacb7d1ca1d 100644
@@ -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
Documentation/security/keys/keycrypt.rst +27 -15

90 lines not on this page · raw message

include/uapi/linux/keycrypt.h +2 -0
index c03348579f62..71209a08c924 100644
@@ -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
security/keys/keycrypt/Kconfig +10 -1
index e61922933bd7..a6d8a0fa6d29 100644
@@ -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.
 
security/keys/keycrypt/core.c +4 -0
index debd0845621e..4a2609c6830f 100644
@@ -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;
security/keys/keycrypt/keycrypt.h +2 -0
index 5a41a68c48fa..40487eb3e139 100644
@@ -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
Signature · 1 line
2.43.0
#11 lore raw

Re: [RFC PATCH 6/9] KEYS: keycrypt: Add the engine tier

Sashiko has reviewed this patch and found no issues.
Quoted 13 lines

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.

Quoted 4 lines

No backend in the kernel declares this tier yet; the keycrypt CAAM backend proposed with it does.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
#12 lore raw

RFC PATCH 7/9 crypto: caam - add an internal cbc(paes) taking the blob's key modifier

In reply to 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.

---
 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(-)
drivers/crypto/caam/caamalg.c +78 -11
index d00caa9cdf8e..f34717f312b8 100644
@@ -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,
drivers/crypto/caam/caamalg_desc.c +2 -1
index 04c1105eb1f5..db3bbba67c8b 100644
@@ -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,
drivers/crypto/caam/caamalg_desc.h +1 -0
index 323490a4a756..ae673b596a6d 100644
@@ -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,
include/soc/fsl/caam-blob.h +8 -0
index 922f7ec3e231..13c21c7e4c2e 100644
@@ -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
Signature · 1 line
2.43.0
#13 lore raw

Re: [RFC PATCH 7/9] crypto: caam - add an internal cbc(paes) taking the blob's key modifier

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

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.

Quoted 4 lines

Its only user is the keycrypt CAAM backend, which is a proposal, and so is this.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
#14 lore raw

RFC PATCH 8/9 KEYS: keycrypt: Add the CAAM backend

In reply to 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.

---
 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
Documentation/security/keys/keycrypt.rst +86 -11
index ac393a0bc97d..e2ee5f75d9f4 100644
@@ -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
security/keys/keycrypt/Kconfig +27 -0
index a6d8a0fa6d29..f661c8952142 100644
@@ -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.
security/keys/keycrypt/Makefile +2 -0
index f051050428cd..4e2087fcaee8 100644
@@ -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
security/keys/keycrypt/caam.c new file +346 -0

346 lines not on this page · raw message

security/keys/keycrypt/caam.h new file +30 -0
new file mode 100644
index 000000000000..ebefa1dcff2e
@@ -0,0 +1,30 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/*
+ * keycrypt - the CAAM backend's data layout
+ *
+ * Copyright (C) 2026 Rodolfo Giometti <[email protected]>
+ */
+
+#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 */
Signature · 1 line
2.43.0
#15 lore raw

Re: [RFC PATCH 8/9] KEYS: keycrypt: Add the CAAM backend

Sashiko has reviewed this patch and found no issues.
Quoted 16 lines

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.

Quoted 3 lines

With it comes its section of the documentation.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
#16 lore raw

RFC PATCH 9/9 KEYS: keycrypt: Add the aes256-gcm-stream algorithm

In reply to 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.

---
 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(-)
Documentation/security/keys/keycrypt.rst +212 -32
index e2ee5f75d9f4..02b5e82f355c 100644
@@ -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
include/keys/keycrypt.h +13 -2
index 8aae3d47e697..eae6010c678c 100644
@@ -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;
 };
include/uapi/linux/keycrypt.h +40 -3

79 lines not on this page · raw message

security/keys/keycrypt/core.c +3 -0
index 4a2609c6830f..916fa329293d 100644
@@ -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))
security/keys/keycrypt/ctx.c +138 -1

201 lines not on this page · raw message

security/keys/keycrypt/keycrypt.h +5 -0
index 40487eb3e139..1d16217d93f7 100644
@@ -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;
security/keys/keycrypt/optee.c +61 -9

112 lines not on this page · raw message

security/keys/keycrypt/optee.h +3 -1
index 391eba15b699..546c1665fc5f 100644
@@ -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
 
security/keys/keycrypt/sw.c +66 -2

116 lines not on this page · raw message

Signature · 1 line
2.43.0
#17 lore raw

Re: [RFC PATCH 9/9] KEYS: keycrypt: Add the aes256-gcm-stream algorithm

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

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.

Quoted 6 lines

With it comes its section of the documentation, with a file format built on it.

No user-space consumer uses it yet.

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
#18 lore raw

Re: [RFC PATCH 9/9] KEYS: keycrypt: Add the aes256-gcm-stream algorithm

In reply to Rodolfo Giometti
Quoted 8 lines · 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.

Quoted 11 lines

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.

Please use Cobblestone-128 or Cobblestone-256 instead.
https://c2sp.org/chunked-encryption has the spec, and you can check against the implementation in pyca/cryptography or (for Cobblestone-128) the Go package filippo.io/cobblestone. This assumes your CPU has AES and GCM instructions; if not, you should see about using one that does or work with a cryptographer to standardize an alternative that doesn't need them.

Nonstandard constructions like this one are to be avoided.

Signature · 2 lines
Sincerely,
Demi Marie Obenour (she/her/hers)
maintainer
#19 lore raw

Re: [RFC PATCH 9/9] KEYS: keycrypt: Add the aes256-gcm-stream algorithm

Quoted 3 lines · Demi Marie Obenour
Quoted 2 lines · 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.

If there is no one who needs this, this is literally throwing a dice with Claude.

Quoted 26 lines
Quoted 6 lines

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.

Quoted 11 lines

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.

Please use Cobblestone-128 or Cobblestone-256 instead.
https://c2sp.org/chunked-encryption has the spec, and you can check against the implementation in pyca/cryptography or (for Cobblestone-128) the Go package filippo.io/cobblestone. This assumes your CPU has AES and GCM instructions; if not, you should see about using one that does or work with a cryptographer to standardize an alternative that doesn't need them.

Quoted 1 line

Nonstandard constructions like this one are to be avoided.

The wider problem in crypto without a use case there is nothing to protect.

Quoted 3 lines
Signature · 2 lines
Sincerely,
Demi Marie Obenour (she/her/hers)

Br, Jarkko

maintainer
#20 lore raw
In reply to Rodolfo Giometti
Quoted 302 lines · 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 (<[email protected]>).

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 (<[email protected]>, three patches, listed as prerequisites below) applied first, for example with:

b4 am -o - [email protected] | 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.

Quoted 4 lines

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

maintainer
#21 lore raw
Quoted 303 lines · Jarkko Sakkinen
Quoted 302 lines · 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 (<[email protected]>).

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 (<[email protected]>, three patches, listed as prerequisites below) applied first, for example with:

b4 am -o - [email protected] | 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.

Quoted 6 lines
Quoted 4 lines

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

#22 lore raw
In reply to Rodolfo Giometti

Hi Rodolfo,

thanks for the RFC and bringing this up. Please see my comments below.

Quoted 1 line · Rodolfo Giometti

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.

Quoted 7 lines

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?

Quoted 10 lines

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.

Quoted 6 lines

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?

Quoted 7 lines

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

Quoted 8 lines

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.

Quoted 7 lines

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.

Quoted 61 lines

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
------------------------------------------

Quoted 6 lines

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.

Quoted 3 lines
  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

Quoted 359 lines

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 (<[email protected]>).

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 (<[email protected]>, three patches, listed as prerequisites below) applied first, for example with:

b4 am -o - [email protected] | 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/[email protected]/
[2] https://lore.kernel.org/all/[email protected]/

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

Signature · 1 line
2.43.0
maintainer
#23 lore raw
Quoted 1 line · Marco Felsch

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

#24 lore raw
In reply to Marco Felsch
Quoted 1 line · Marco Felsch

Hi Rodolfo,

Hi.

Quoted 1 line

thanks for the RFC and bringing this up. Please see my comments below.

Thanks to you for reading it!

Quoted 11 lines · Rodolfo Giometti
Quoted 1 line

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.

I agree that a common API is missing. keycrypt is meant to be one, for keys that user space uses but never reads: the same ioctls on the fd for every backend, and the same add_key() strings but for the sw backend's master=, so user space does not need to know which backend holds the key (unless it asks for one with backend=). What is missing is a way to ask which backends and algorithms exist (see below).

[snip]

Quoted 2 lines

So it's not a new keytype but a new mechanism to handle trusted-keys from userspace?

No, a keycrypt key is not a trusted key. Only the sw backend uses a trusted key, as the master that seals its blobs; the OP-TEE and CAAM backends use none. Also, an ELE backend, not written yet, would use none, and it could be the first hsm backend!

[snip]

Quoted 9 lines
Quoted 3 lines

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?

By copy I mean getting the key's bytes to use them elsewhere. A user key can be read back; a logon key cannot, but its bytes come from user space at every boot, so they sit in a file. A trusted or encrypted key fixes that, and the cover letter was wrong there: AF_ALG can use one from user space. But, as you note below, once unsealed its bytes are in kernel memory, so it falls with the kernel, and nothing binds it to an algorithm or a purpose.

My use case is not a block device: it is files that an application encrypts itself (an archive of the root filesystem, configuration backups, logs), with a key that must not be readable on the device and that ideally may only encrypt, or only decrypt.

You can see keycrypt keys as the symmetric counterpart of the asymmetric keys that KEYCTL_PKEY_* already lets user space use without reading them. The difference is that a symmetric mode keeps state across calls (the CBC chain, a stream's segments), hence an fd instead of one keyctl call per operation. And, as for KEYCTL_PKEY_*, the open could become a key_type operation, so that keyctl knows no key type.

[snip]

Quoted 5 lines

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.

Yes. With the OP-TEE backend a generated key never leaves the TA, which runs the operation, and the kernel only holds a blob it cannot open, so even a compromised kernel can only use the key, and only for what it was sealed for. An hsm backend, as ELE could become, would do the same in dedicated hardware.

Quoted 5 lines

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.

No, file encryption from user space, as above. In one sentence:
keycrypt gives the keyring keys that user space can use but never read, bound to one algorithm and purpose; with a TEE backend they are never in clear in the kernel either, and they work from a minimal initramfs, before any user-space crypto stack exists.

That last part matters a lot on embedded systems. The initramfs usually sits in the FIT image that the secure-boot chain must authenticate, and often decrypt, before running it, so it must be as small as possible (on our i.MX93 boards this runs at about 2.4MiB/s through ELE). In such an initramfs, OP-TEE's PKCS#11 TA would also need secure storage set up before the root filesystem (tee-supplicant with a writable filesystem, or a provisioned RPMB); keycrypt's OP-TEE backend needs no storage and no daemon, just the keyctl syscall and a small tool driving the fd.

[snip]

Quoted 10 lines
Quoted 4 lines

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.

The strings follow what trusted and encrypted keys already take in add_key(), but I'm open to another form, such as a versioned binary struct like the one KEYCTL_CRYPT_OPEN already takes with copy_struct_from_user().

On the enumeration you're right, there is none: a key's line in /proc/keys and KEYCRYPT_IOC_INFO on an open fd tell its backend and tier only after the fact. A list of the backends, with their tier and algorithms, would be easy to add, and it is needed since algorithms differ per backend (the CAAM one does aes256-cbc only): would a keyctl or a file under /proc be what you have in mind?

[snip]

Quoted 5 lines
Quoted 3 lines

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.

Yes, the kernel tier gives the protection of a trusted key, and it does not meet the goal above. It is there only so that the same interface works on systems with nothing better; its only backend, sw, is optional and off by default, and it can go if it is considered wrong.

Quoted 9 lines
Quoted 3 lines
  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?

Yes, and for using them from user space, with a purpose bound to each key (encrypt-only, decrypt-only, verify-only) that the TA, or an HSM, enforces. keycrypt does not replace the protected keys you name: a backend is where such a key lives.

Quoted 3 lines

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.

For user space that means AF_ALG with cbc(paes) only (the CAAM, CryptoCell and s390 register one AF_ALG can reach; DCP's is internal), each driver with its own key format, and since v7.3 privileged by default (d9506e82ced5). Generating is what "new" does in keycrypt:
with OP-TEE the TA generates the key itself. The CAAM patches are only a prototype there: they still generate the key in kernel memory, and the aim is to have the CAAM generate it and keep it black (one of the questions to the CAAM maintainers in the cover letter).

Quoted 1 line

Thanks for sharing your ideas :)

:)

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail: [email protected]
Linux Device Driver                          [email protected]
Embedded Systems                     phone:  +39 349 2432127
UNIX programming
#25 lore raw
In reply to Rodolfo Giometti
Quoted 4 lines · 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.

I haven't looked at the API, but from a cryptographic perspective, this encourages very poor practices. AES-GCM even allows userspace to extract the secret authentication key.

AES-256-CBC isn't a suitable mode on its own, unless it's combined with a MAC in encrypt-then-MAC. Even then, it has a 2^64 birthday bound, so it should only be used 2^48 times with a single key unless the key is ephemeral.

AES-GCM is not a suitable algorithm either. If you allow encrypting with a key loaded from persistent storage, there is no way for the API to ensure it is only used with a unique nonce. Nonce reuse leaks the authentication key and allows forgeries. Using random nonces isn't good enough either: NIST only allows 2^32 encryptions in this case, and the API can't enforce that limit.

For long-term keys, all of the following are much safer choices. They have 192-bit nonces, which means that one can generate them at random for each encryption without any problems.

- XAES-256-GCM
- XChaCha20-Poly1305
- AEGIS-256

AES-GCM-SIV is also okay, provided that you are fine with occasionally leaking if two plaintexts are equal. This happens whenever there is a nonce collision, so with probability 2^-32 after 2^32 encryptions.

Signature · 2 lines
Sincerely,
Demi Marie Obenour (she/her/hers)
maintainer
#26 lore raw
Quoted 26 lines · Demi Marie Obenour
Quoted 4 lines · 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.

I haven't looked at the API, but from a cryptographic perspective, this encourages very poor practices. AES-GCM even allows userspace to extract the secret authentication key.

AES-256-CBC isn't a suitable mode on its own, unless it's combined with a MAC in encrypt-then-MAC. Even then, it has a 2^64 birthday bound, so it should only be used 2^48 times with a single key unless the key is ephemeral.

AES-GCM is not a suitable algorithm either. If you allow encrypting with a key loaded from persistent storage, there is no way for the API to ensure it is only used with a unique nonce. Nonce reuse leaks the authentication key and allows forgeries. Using random nonces isn't good enough either: NIST only allows 2^32 encryptions in this case, and the API can't enforce that limit.

For long-term keys, all of the following are much safer choices. They have 192-bit nonces, which means that one can generate them at random for each encryption without any problems.

Quoted 7 lines

- XAES-256-GCM
- XChaCha20-Poly1305
- AEGIS-256

AES-GCM-SIV is also okay, provided that you are fine with occasionally leaking if two plaintexts are equal. This happens whenever there is a nonce collision, so with probability 2^-32 after 2^32 encryptions.

The exitential problem here is that KEYCTL_CRYPT_OPEN creates a circular relationship between the keyrings API and a specific key type.

At hardware level I did not see any support for TPM, which narrows down the potential user base.

The remaining potential user base is further reduced by those that use trusted keys; leaving out those who need to solve the assumed problem that only this patch set can presumebly sort out.

And we don't really know at this point that cut. This is pretty much the break down of what is wrong here.

If there is/was a problem to sort out, it should be so constrained that it should be as quick to describe as stepping over a nail really.

These are the main topics what I would focus on.

Quoted 3 lines
Signature · 2 lines
Sincerely,
Demi Marie Obenour (she/her/hers)

Br, Jarkko

#27 lore raw
Quoted 45 lines · Jarkko Sakkinen
Quoted 26 lines · Demi Marie Obenour
Quoted 4 lines · 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.

I haven't looked at the API, but from a cryptographic perspective, this encourages very poor practices. AES-GCM even allows userspace to extract the secret authentication key.

AES-256-CBC isn't a suitable mode on its own, unless it's combined with a MAC in encrypt-then-MAC. Even then, it has a 2^64 birthday bound, so it should only be used 2^48 times with a single key unless the key is ephemeral.

AES-GCM is not a suitable algorithm either. If you allow encrypting with a key loaded from persistent storage, there is no way for the API to ensure it is only used with a unique nonce. Nonce reuse leaks the authentication key and allows forgeries. Using random nonces isn't good enough either: NIST only allows 2^32 encryptions in this case, and the API can't enforce that limit.

For long-term keys, all of the following are much safer choices. They have 192-bit nonces, which means that one can generate them at random for each encryption without any problems.

Quoted 7 lines

- XAES-256-GCM
- XChaCha20-Poly1305
- AEGIS-256

AES-GCM-SIV is also okay, provided that you are fine with occasionally leaking if two plaintexts are equal. This happens whenever there is a nonce collision, so with probability 2^-32 after 2^32 encryptions.

The exitential problem here is that KEYCTL_CRYPT_OPEN creates a circular relationship between the keyrings API and a specific key type.

At hardware level I did not see any support for TPM, which narrows down the potential user base.

The remaining potential user base is further reduced by those that use trusted keys; leaving out those who need to solve the assumed problem that only this patch set can presumebly sort out.

Quoted 7 lines

And we don't really know at this point that cut. This is pretty much the break down of what is wrong here.

If there is/was a problem to sort out, it should be so constrained that it should be as quick to describe as stepping over a nail really.

These are the main topics what I would focus on.

This whole patchset looks like a solution looking for a problem.

The usual solution to something like this is a userspace service like ssh-agent. Then you can do whatever key management you want. That doesn't protect against root, but if someone can get root you have bigger problems.

Signature · 2 lines
Sincerely,
Demi Marie Obenour (she/her/hers)
maintainer
#28 lore raw
Quoted 52 lines · Demi Marie Obenour
Quoted 51 lines · Jarkko Sakkinen
Quoted 26 lines · Demi Marie Obenour
Quoted 4 lines · 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.

I haven't looked at the API, but from a cryptographic perspective, this encourages very poor practices. AES-GCM even allows userspace to extract the secret authentication key.

AES-256-CBC isn't a suitable mode on its own, unless it's combined with a MAC in encrypt-then-MAC. Even then, it has a 2^64 birthday bound, so it should only be used 2^48 times with a single key unless the key is ephemeral.

AES-GCM is not a suitable algorithm either. If you allow encrypting with a key loaded from persistent storage, there is no way for the API to ensure it is only used with a unique nonce. Nonce reuse leaks the authentication key and allows forgeries. Using random nonces isn't good enough either: NIST only allows 2^32 encryptions in this case, and the API can't enforce that limit.

For long-term keys, all of the following are much safer choices. They have 192-bit nonces, which means that one can generate them at random for each encryption without any problems.

Quoted 7 lines

- XAES-256-GCM
- XChaCha20-Poly1305
- AEGIS-256

AES-GCM-SIV is also okay, provided that you are fine with occasionally leaking if two plaintexts are equal. This happens whenever there is a nonce collision, so with probability 2^-32 after 2^32 encryptions.

The exitential problem here is that KEYCTL_CRYPT_OPEN creates a circular relationship between the keyrings API and a specific key type.

At hardware level I did not see any support for TPM, which narrows down the potential user base.

The remaining potential user base is further reduced by those that use trusted keys; leaving out those who need to solve the assumed problem that only this patch set can presumebly sort out.

And we don't really know at this point that cut. This is pretty much the break down of what is wrong here.

If there is/was a problem to sort out, it should be so constrained that it should be as quick to describe as stepping over a nail really.

Quoted 8 lines
Quoted 1 line

These are the main topics what I would focus on.

This whole patchset looks like a solution looking for a problem.

The usual solution to something like this is a userspace service like ssh-agent. Then you can do whatever key management you want. That doesn't protect against root, but if someone can get root you have bigger problems.

This is true. Even if the code was like it is BUT it had a clear motivation, I would likely suggest to the author how to resolve the problem more properly.

I.e. bar is not too high in initial code quality but it is steep from the get go in the "utility value".

Quoted 3 lines
Signature · 2 lines
Sincerely,
Demi Marie Obenour (she/her/hers)

Br, Jarkko

#29 lore raw
In reply to Demi Marie Obenour
Quoted 52 lines · Demi Marie Obenour
Quoted 51 lines · Jarkko Sakkinen
Quoted 26 lines · Demi Marie Obenour
Quoted 4 lines · 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.

I haven't looked at the API, but from a cryptographic perspective, this encourages very poor practices. AES-GCM even allows userspace to extract the secret authentication key.

AES-256-CBC isn't a suitable mode on its own, unless it's combined with a MAC in encrypt-then-MAC. Even then, it has a 2^64 birthday bound, so it should only be used 2^48 times with a single key unless the key is ephemeral.

AES-GCM is not a suitable algorithm either. If you allow encrypting with a key loaded from persistent storage, there is no way for the API to ensure it is only used with a unique nonce. Nonce reuse leaks the authentication key and allows forgeries. Using random nonces isn't good enough either: NIST only allows 2^32 encryptions in this case, and the API can't enforce that limit.

For long-term keys, all of the following are much safer choices. They have 192-bit nonces, which means that one can generate them at random for each encryption without any problems.

Quoted 7 lines

- XAES-256-GCM
- XChaCha20-Poly1305
- AEGIS-256

AES-GCM-SIV is also okay, provided that you are fine with occasionally leaking if two plaintexts are equal. This happens whenever there is a nonce collision, so with probability 2^-32 after 2^32 encryptions.

The exitential problem here is that KEYCTL_CRYPT_OPEN creates a circular relationship between the keyrings API and a specific key type.

At hardware level I did not see any support for TPM, which narrows down the potential user base.

The remaining potential user base is further reduced by those that use trusted keys; leaving out those who need to solve the assumed problem that only this patch set can presumebly sort out.

And we don't really know at this point that cut. This is pretty much the break down of what is wrong here.

If there is/was a problem to sort out, it should be so constrained that it should be as quick to describe as stepping over a nail really.

Quoted 8 lines
Quoted 1 line

These are the main topics what I would focus on.

This whole patchset looks like a solution looking for a problem.

The usual solution to something like this is a userspace service like ssh-agent. Then you can do whatever key management you want. That doesn't protect against root, but if someone can get root you have bigger problems.

Also, if you need keys stored in hardware for some reason (compliance, time-limited exfiltration), you can use a userspace library or daemon that abstracts over whatever the hardware-specific API is.

Signature · 2 lines
Sincerely,
Demi Marie Obenour (she/her/hers)
maintainer
#30 lore raw
Quoted 57 lines · Demi Marie Obenour
Quoted 56 lines · Demi Marie Obenour
Quoted 45 lines · Jarkko Sakkinen
Quoted 26 lines · Demi Marie Obenour
Quoted 4 lines · 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.

I haven't looked at the API, but from a cryptographic perspective, this encourages very poor practices. AES-GCM even allows userspace to extract the secret authentication key.

AES-256-CBC isn't a suitable mode on its own, unless it's combined with a MAC in encrypt-then-MAC. Even then, it has a 2^64 birthday bound, so it should only be used 2^48 times with a single key unless the key is ephemeral.

AES-GCM is not a suitable algorithm either. If you allow encrypting with a key loaded from persistent storage, there is no way for the API to ensure it is only used with a unique nonce. Nonce reuse leaks the authentication key and allows forgeries. Using random nonces isn't good enough either: NIST only allows 2^32 encryptions in this case, and the API can't enforce that limit.

For long-term keys, all of the following are much safer choices. They have 192-bit nonces, which means that one can generate them at random for each encryption without any problems.

Quoted 7 lines

- XAES-256-GCM
- XChaCha20-Poly1305
- AEGIS-256

AES-GCM-SIV is also okay, provided that you are fine with occasionally leaking if two plaintexts are equal. This happens whenever there is a nonce collision, so with probability 2^-32 after 2^32 encryptions.

The exitential problem here is that KEYCTL_CRYPT_OPEN creates a circular relationship between the keyrings API and a specific key type.

At hardware level I did not see any support for TPM, which narrows down the potential user base.

The remaining potential user base is further reduced by those that use trusted keys; leaving out those who need to solve the assumed problem that only this patch set can presumebly sort out.

Quoted 7 lines

And we don't really know at this point that cut. This is pretty much the break down of what is wrong here.

If there is/was a problem to sort out, it should be so constrained that it should be as quick to describe as stepping over a nail really.

These are the main topics what I would focus on.

This whole patchset looks like a solution looking for a problem.

Quoted 8 lines
Quoted 4 lines

The usual solution to something like this is a userspace service like ssh-agent. Then you can do whatever key management you want. That doesn't protect against root, but if someone can get root you have bigger problems.

Also, if you need keys stored in hardware for some reason (compliance, time-limited exfiltration), you can use a userspace library or daemon that abstracts over whatever the hardware-specific API is.

Pro-bab-ly but I'm not a huge fan of generalization ;-)

But when looking only at HSMs that is at least 99,999% true as they appear as PKCS#11 providing smart cards with a possible prorietary API. Other than generic smart card driver they ought not to require any special kernel support.

Quoted 3 lines
Signature · 2 lines
Sincerely,
Demi Marie Obenour (she/her/hers)

Br, Jarkko

#31 lore raw
In reply to Demi Marie Obenour
Quoted 7 lines · Demi Marie Obenour
Quoted 6 lines · Demi Marie Obenour
Quoted 5 lines · Jarkko Sakkinen
Quoted 4 lines · Demi Marie Obenour

AES-256-CBC isn't a suitable mode on its own, unless it's combined with a MAC in encrypt-then-MAC. Even then, it has a 2^64 birthday bound, so it should only be used 2^48 times with a single key unless the key is ephemeral.

CBC is there for existing formats (craf writes files that openssl enc can read) and because the CAAM path is CBC only. I take your points on it.

Quoted 6 lines
Quoted 6 lines
Quoted 6 lines
Quoted 6 lines

AES-GCM is not a suitable algorithm either. If you allow encrypting with a key loaded from persistent storage, there is no way for the API to ensure it is only used with a unique nonce. Nonce reuse leaks the authentication key and allows forgeries. Using random nonces isn't good enough either: NIST only allows 2^32 encryptions in this case, and the API can't enforce that limit.

You are right that a construction of our own is the wrong choice:
patch 9, the only GCM in the series, has no user yet and can go.

[snip]

Quoted 4 lines
Quoted 4 lines

The usual solution to something like this is a userspace service like ssh-agent. Then you can do whatever key management you want. That doesn't protect against root, but if someone can get root you have bigger problems.

The threat here is root, on devices where root eventually falls: a key root can copy decrypts that device's data offline and forever. A service that holds the key in its memory gives that away. keycrypt with the OP-TEE backend does not: the TA keeps the key and checks the purpose sealed with it at every use, so even a compromised kernel can only use it on that device, and only for that purpose.

Quoted 3 lines

Also, if you need keys stored in hardware for some reason (compliance, time-limited exfiltration), you can use a userspace library or daemon that abstracts over whatever the hardware-specific API is.

Yes, that is the case I mean, and a daemon over a TEE would not give the key away either. What it costs here is, for OP-TEE's PKCS#11 TA, secure storage before the root filesystem exists; for the CAAM, the only user-space path is AF_ALG cbc(paes), the one off-CPU exception left in an interface the kernel documents as deprecated, privileged by default, with a key format per driver and no purpose.

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail: [email protected]
Linux Device Driver                          [email protected]
Embedded Systems                     phone:  +39 349 2432127
UNIX programming
#32 lore raw
In reply to Jarkko Sakkinen

On 19/11/2026 01:37, Jarkko Sakkinen wrote:

[snip]

Quoted 2 lines

The exitential problem here is that KEYCTL_CRYPT_OPEN creates a circular relationship between the keyrings API and a specific key type.

Agreed: it should be a key_type operation, dispatched the way KEYCTL_PKEY_* dispatches to asym_eds_op, so that keyctl knows no key type.

Quoted 2 lines

At hardware level I did not see any support for TPM, which narrows down the potential user base.

On a TPM system the sw backend can take its master from a TPM-sealed trusted key, but there keycrypt adds little over a trusted key. The users are SoCs with a TEE and often no TPM, OP-TEE on i.MX for one.

Quoted 9 lines

The remaining potential user base is further reduced by those that use trusted keys; leaving out those who need to solve the assumed problem that only this patch set can presumebly sort out.

And we don't really know at this point that cut. This is pretty much the break down of what is wrong here.

If there is/was a problem to sort out, it should be so constrained that it should be as quick to describe as stepping over a nail really.

The nail: a device must encrypt and decrypt its own files, also from a minimal initramfs, with a key that root or a kernel exploit can use on the device but never copy off it. Trusted keys hand their users the key's bytes (dm-crypt, encrypted keys and AF_ALG read them). CAAM's "pk" option is the one exception, but even there a new key is drawn in kernel memory before the CAAM wraps it, and user space reaches it only through AF_ALG, which the kernel calls insecure and deprecated (Documentation/crypto/userspace-if.rst, and "Userspace interface (deprecated)" in crypto/Kconfig), privileged by default, with no purpose bound to the key. The i.MX93 has no CAAM at all: there the key can live in OP-TEE, and keycrypt lets the keyring use it without it ever leaving the TA.

The stream of patch 9 has no user yet and can go.

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail: [email protected]
Linux Device Driver                          [email protected]
Embedded Systems                     phone:  +39 349 2432127
UNIX programming
maintainer
#33 lore raw
In reply to Jarkko Sakkinen
Quoted 10 lines · Jarkko Sakkinen

The exitential problem here is that KEYCTL_CRYPT_OPEN creates a circular relationship between the keyrings API and a specific key type.

At hardware level I did not see any support for TPM, which narrows down the potential user base.

The remaining potential user base is further reduced by those that use trusted keys; leaving out those who need to solve the assumed problem that only this patch set can presumebly sort out.

Quoted 7 lines

And we don't really know at this point that cut. This is pretty much the break down of what is wrong here.

If there is/was a problem to sort out, it should be so constrained that it should be as quick to describe as stepping over a nail really.

These are the main topics what I would focus on.

I'm not disregarding that there might be something; and neither disregarding e.g., the use of Claude. Throwing a dice can apply as well human made code as for me code is just code. Perhaps using Claude, people just tend to have just a itchier trigger finger :-)

The place where *in my personal opinion* anyone who uses agents would be better to do manual work is the commit message. It enforces to use cognitive abilities even more so than writing code, if you with absolutely no self-deception, read it all through and write with your own words what the heck it does.

Usually when hitting the wall doing that leads into better code because of the healthy reality check. I'm not a medical doctor but I believe at least that thinking more stuff like this is also great for long-term health and cognitive abilities.

AI is for mental health as a car is for physical health; for better or worse.

Code quality is also over-rated although best effort should be done but that's all. If you get it, then it is done. It's harder than it sounds without self-deception part.

And yeah, we don't have projected problems. I.e. "no users" is always NAK. You have to step on the nail at first.

Just need to clear my thoughts on overall the topic :-) This is I guess where I stand now. Hope you find these helpful.

Br, Jarkko

#34 lore raw

On 19/11/2026 15:33, Jarkko Sakkinen wrote:

[snip]

Quoted 2 lines

And yeah, we don't have projected problems. I.e. "no users" is always NAK. You have to step on the nail at first.

A customer of mine stepped on it. Their product, on i.MX6, encrypts its rootfs with dm-crypt and a CAAM black key, never in clear. Its backups, though, are encrypted in user space with a key kept as a CAAM blob; to use it, the blob is opened and the key handed to user space in clear.

The next generation is on i.MX93, and the customer now wants the backups and other encrypted archives protected like the rootfs: the key must never be in clear outside a secure world. The i.MX93 has no CAAM. OP-TEE can hold the key, but every way the mainline keyring offers to use it (a trusted key, through dm-crypt or AF_ALG) unseals its bytes into kernel memory, and AF_ALG no longer reaches hardware drivers. keycrypt's OP-TEE backend does not unseal it: a key it generates leaves the TA only sealed.

Ciao,

Rodolfo

Signature · 4 lines
GNU/Linux Solutions                  e-mail: [email protected]
Linux Device Driver                          [email protected]
Embedded Systems                     phone:  +39 349 2432127
UNIX programming