Skip to content

crypto/mbedtls: route PSA key management through cryptodev - #4133

Merged
GUIDINGLI merged 3 commits into
apache:masterfrom
ThePassionate:crypto-mbedtls-psa
Nov 27, 2026
Merged

GUIDINGLI merged 3 commits into
apache:masterfrom
ThePassionate:crypto-mbedtls-psa

Conversation

@ThePassionate

@ThePassionate ThePassionate commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds a PSA secure element driver that routes PSA key management through the NuttX cryptodev interface, so applications using the PSA Crypto API can keep their keys in the cryptodev key store (the software swkey backend today, a hardware secure element driver when one registers) instead of plaintext files.

  • PSA secure element and ITS prefix options: MBEDTLS_PSA_CRYPTO_SE_C and PSA_ITS_STORAGE_PREFIX Kconfig entries with their config.h mappings.
  • route PSA key management through cryptodev: registers a secure element driver at PSA_KEY_LOCATION_LOCAL_CRYPTODEV whose key management callbacks (allocate, validate, import, generate, export, export_public, destroy) translate to the CIOCKEY ioctls the cryptodev core already exposes (CRK_ALLOCATE_KEY, CRK_IMPORT_KEY, ...). PSA metadata lives in ITS files; the key material lives in the cryptodev key store.

Compared to the Vela original this fixes three contract errors found while porting: the AES generation now passes the key length the kernel interface requires (Vela passed one parameter where cryptodev validates two, so the call always failed with EINVAL), the export callback sets the output length the PSA core contract requires, and kernel errnos are mapped to PSA status values instead of leaking into the PSA status space.

The PSA external RNG routing (mbedtls_psa_external_get_random) is already upstream (9a1a8d3). The SE driver interface this builds on is marked deprecated by Mbed TLS 3.6 in favor of the PSA driver interface, so the port deliberately stays minimal.

Impact

Both new options default n. MBEDTLS_PSA_CRYPTODEV_ALT lives in the CRYPTO_CRYPTODEV block and selects MBEDTLS_ALT.

Testing

Built from a fresh checkout state (distclean + refetch) with sim:nsh + CONFIG_CRYPTO_MBEDTLS + CONFIG_OPENSSL_MBEDTLS_WRAPPER + MBEDTLS_PSA_CRYPTO_SE_C + MBEDTLS_PSA_CRYPTODEV_ALT: 0 warnings, 0 errors. The full crypto regression - 12 tests including the PKCS12 cmocka suite - pass unchanged.

A psakey test exercises the path at runtime: driver registration (including the double-registration error), volatile and persistent import/export round trips, AES-256 generation, destroy semantics, and the exported key material used as a working AES key against the RFC 3602 vectors. Run on sim against the software key store:

psakey register init success
psakey import export success
psakey generate success
psakey destroy success
psakey persistent success
psakey cipher success

Environment: the software key store on /dev/nvs (local test wiring, as for the keymanagement test) and the PSA metadata files under the PSA_ITS_STORAGE_PREFIX directory.

@ThePassionate

Copy link
Copy Markdown
Contributor Author

The Linux (arm-imx) failure is not from this PR. The failing config is imx93-qsb/rpmsg, which enables none of the symbols this series touches (no CRYPTO_MBEDTLS, no PSA options); building it locally with and without this series produces a byte-identical .data.

The overflow is a master-side regression: apache/nuttx@1325a419756 ("sched: split tcb->flags by writer", landed 04:06 UTC today) grows that config's .data by 92 bytes with the CI toolchain - 168 bytes with a local gcc - and tips the itcm region over. The timing matches: the #4130 build ran at 03:11 UTC without that commit and its arm-imx job passed; this build ran at 04:08 UTC with it and failed, and that is the only nuttx commit in between.

Every apps PR that builds after 04:06 UTC will hit the same failure until the flags-split cost is trimmed or the board's memory map is adjusted. Happy to help with either, but it is independent of this series.

jerpelea
jerpelea previously approved these changes Nov 25, 2026
GUIDINGLI
GUIDINGLI previously approved these changes Nov 25, 2026
@cederom

cederom commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Thanks for this. I read both commits against nuttx master (crypto/cryptodev.c, crypto/cryptosoft.c) and Mbed TLS v3.6.5. A few things need fixing before this can go in.

1. Needs a rebase; drop the dev_alt hunks

The PR doesn't apply on master: CMakeLists.txt, Kconfig, Makefile, dev_alt.h and dev_alt.c all conflict. 955ba95 ("add CIOCKEY wrapper to dev_alt") already added struct crypt_kop cryptk and cryptodev_cryptk(), unconditionally, and ecdsa_alt.c/ecdh_alt.c use them. So the #ifdef CONFIG_MBEDTLS_PSA_CRYPTODEV_ALT copies here should go.

Returning crk_status instead of the ioctl result changes nothing: cryptodev_key() already turns a non-zero krp_status into the ioctl error. Also, the base is still on Mbed TLS 3.6.2 while master is on 3.6.5, so please re-run the tests after the rebase.

2. p_export / p_export_public report the wrong length

*p_data_length = data_size is only right if the caller's buffer is exactly the key size. The comment says "the PSA core sizes export buffers exactly for the key type", but it doesn't. psa_export_key() and psa_export_public_key() pass the application's data_size straight to the driver (they only reject 0).

For example, psa_export_key(id, buf, sizeof(buf), &len) with a 64-byte buf on an AES-128 key returns len == 64.

The driver can't work out the size itself because p_export gets no attributes. The backend does know it: swkey_kprocess() sets krp_param[1].crp_nbits = len * 8. But cryptodev_key() never copies crp_nbits back into the user's crypt_kop. I think this needs a small kernel change first (copy back crp_nbits for the output params). Then this driver can report kop.crk_param[1].crp_nbits / 8.

3. Failed key creation leaks key IDs and leaves key material in the store

CRK_ALLOCATE_KEY and CRK_VALIDATE_KEYID both reserve the ID by writing SWKEY_MAGIC_STRING to the store (swkey_is_valid()). When creation fails after that, psa_fail_key_creation() never calls p_destroy (upstream TODO, mbed-crypto#217). After a power loss, psa_crypto_recover_transaction() just throws the transaction away. Concretely:

  • psa_generate_key() with a type or size this driver doesn't support (e.g. ECC P-384, AES with bits = 0): p_allocate runs first, then p_generate returns NOT_SUPPORTED. The ID stays reserved forever. Repeated attempts use up CRYPTO_CRYPTODEV_SOFTWARE_KEYMGMT_NKEYS.
  • psa_import_key() of a persistent key where the attributes give bits that don't match the data: the core checks this after p_import. By then CRK_IMPORT_KEY and CRK_SAVE_KEY have written the key to NVS, then the core returns INVALID_ARGUMENT. The key material stays in the store with no PSA metadata pointing at it.
  • If CRK_SAVE_KEY fails in psa_alt_import_key(), the key stays in the RAM cache. swkey_get_cache_data() writes it to flash later when the entry is evicted.

Suggestion:

  • Reject unsupported type/bits in p_allocate and p_validate_slot_number (both get the attributes), so nothing is reserved for a key that can't be created.
  • On the driver's own error paths, send a best-effort CRK_DELETE_KEY.
  • Document the leak that remains on the core side.

4. p_import doesn't validate the key, and bits is wrong for most types

*bits = data_length * 8 is accepted for any type:

  • RSA key pair (DER): bits becomes the DER length × 8, not the modulus size.
  • ECC public key (65 bytes): 520 bits.
  • A 20-byte "AES" key: accepted as 160-bit AES.

The transparent path checks these; with an SE driver that job falls to the driver. Please limit import to what the driver actually supports (AES 16/24/32 bytes, SECP_R1 256 key pair as a 32-byte scalar) and return NOT_SUPPORTED / INVALID_ARGUMENT for anything else.

5. ECC/RSA generate and public export don't work with the in-tree software backend

  • CRK_GENERATE_SECP256R1_KEY in cryptosoft.c needs two input params (private key ID and public key ID) and reads krp_param[1]. With crk_iparams = 1 it returns -EINVAL.
  • swkey_kprocess() has no CRK_EXPORT_PUBLIC_KEY case (it falls into default: and returns -EINVAL). It also stores the public key as a 64-byte X‖Y, while PSA expects 0x04‖X‖Y (65 bytes).
  • I don't see CRK_GENERATE_RSA_KEY handled anywhere in crypto/. RSA-1024 as the only accepted size is also a strange choice for new code.

The testing section only covers AES. Which backend were the ECC/RSA paths written for? If it's an out-of-tree hardware driver, I'd drop ECC/RSA from this PR, or add tests for them.

6. Error mapping

These backend errors currently become PSA_ERROR_GENERIC_ERROR:

  • -EEXIST: what CRK_VALIDATE_KEYID returns for a used ID. Should be PSA_ERROR_ALREADY_EXISTS.
  • -ENOBUFS: export buffer too small. Should be PSA_ERROR_BUFFER_TOO_SMALL.
  • -EFBIG: should probably be INVALID_ARGUMENT or NOT_SUPPORTED.

7. Slot numbers get truncated

psa_key_slot_number_t is 64-bit, and (uint32_t)key_slot drops the upper half silently. An application that asks for slot 0x100000001 gets slot 1 validated and used. Please return INVALID_ARGUMENT for anything above UINT32_MAX in p_validate_slot_number.

8. psa_alt_register_se_driver() leaks on failure

If psa_register_se_driver() fails (e.g. a second call returns ALREADY_EXISTS), both malloc'd tables are lost. Static const tables with designated initializers (.MBEDTLS_PRIVATE(p_import) = psa_alt_import_key, ...) avoid the heap and the leak.

Smaller things

  • MBEDTLS_PSA_CRYPTO_SE_C is deprecated upstream: mbedtls_config.h marks it \deprecated, and check_config.h warns with MBEDTLS_DEPRECATED_WARNING and errors with MBEDTLS_DEPRECATED_REMOVED. Upstream also documents it as not thread-safe. Please say both in Kconfig help. The PSA driver interface is the long-term route.
  • Volatile keys: allocation writes the magic record to flash. So a volatile key that isn't destroyed before a reboot keeps its ID reserved for good, and cache eviction writes volatile key material to NVS. That's kernel behaviour, but worth documenting here.
  • PSA_ITS_STORAGE_PREFIX is the only symbol in this Kconfig without the MBEDTLS_ prefix. Suggest CONFIG_MBEDTLS_PSA_ITS_STORAGE_PREFIX mapped to PSA_ITS_STORAGE_PREFIX. Please add help text too: the string is prepended as-is, so it needs a trailing /, and the directory must exist. (#ifdef on a Kconfig string is always true. That's harmless, since "" is the upstream default.)
  • PSA_KEY_LOCATION_LOCAL_CRYPTODEV takes a name in the PSA_ namespace, and "LOCAL" means local storage in PSA terms. A NuttX-prefixed name would be clearer.
  • None of the three new Kconfig options has help text.
  • The psakey test isn't in the tree. Could you add it under testing/ or link it? Cases worth adding: export with a buffer larger than the key, ECC generate, and failed creation (unsupported type, bits mismatch) followed by a check that the key ID is free again.

Add two more Mbed TLS options to the Kconfig so they can be selected
from NuttX:

- MBEDTLS_PSA_CRYPTO_SE_C enables the dynamic secure element support
  of the PSA cryptography API, the framework that secure element
  drivers register against.
- PSA_ITS_STORAGE_PREFIX moves the PSA key files out of the current
  working directory, which is where the ITS file backend keeps them
  otherwise.

Both options map one to one onto the upstream Mbed TLS options of the
same names.

Testing
-------
Built sim:nsh with CONFIG_CRYPTO_MBEDTLS and the PSA options enabled:
the Mbed TLS library, including library/psa_crypto_se.c that the new
option gates, compiles with 0 warnings; the crypto driver tests and
the PKCS12 wrapper test stay green.

Signed-off-by: makejian <makejian@xiaomi.com>
Register a PSA secure element driver that forwards the PSA key
management operations (allocate, validate slot, import, generate,
export, export public, destroy) to the NuttX cryptodev key management
interface, so keys whose lifetime locates them at
PSA_KEY_LOCATION_LOCAL_CRYPTODEV are held by the cryptodev key store
instead of the PSA local storage.  An application brings the driver in
by calling psa_alt_register_se_driver() before psa_crypto_init().

The cryptodev ALT layer grows the CIOCKEY access: cryptodev_context_t
gets a struct crypt_kop, guarded by the new option so the hash and MAC
contexts that embed it stay small in builds that do not use the
secure element path.

The secure element interface of Mbed TLS 3.x marks the driver tables
as private, so the fields are assigned through MBEDTLS_PRIVATE().  The
AES key generation passes the key length (16/24/32 bytes) as the
second input parameter the kernel expects.

The import of a persistent key follows the CRK_IMPORT_KEY with a
CRK_SAVE_KEY: the key store may keep an imported key in a RAM cache
only, and without the save the key material would be gone once the
cache is, while the PSA metadata in the internal trusted storage kept
pointing at the slot.

Enabled with MBEDTLS_PSA_CRYPTODEV_ALT, which depends on
MBEDTLS_PSA_CRYPTO_SE_C and selects the ALT layer.

Testing
-------
sim:nsh with CONFIG_CRYPTO_MBEDTLS, MBEDTLS_PSA_CRYPTO_SE_C and
MBEDTLS_PSA_CRYPTODEV_ALT enabled, the cryptodev software key
management backend on /dev/nvs, and PSA_ITS_STORAGE_PREFIX="/tmp/":
the psakey test drives the registration, the import/export round
trip, the AES-256 generate, the destroy lifecycle, a persistent key
and one AES-CBC round from the PSA API, all green, and the apps
build is warning-free.  The crypto driver tests (aescbc, aesctr,
aesxts, des3cbc, chacha20, chachapoly, hmac, hash, aesgcm, aescmac,
pbkdf2, poly1305) and the PKCS12 wrapper test (2/2) stay green.

Signed-off-by: makejian <makejian@xiaomi.com>
Restrict the driver to AES keys (the in-tree software backend has no
asymmetric generator that fits the PSA single-slot model and no
CRK_EXPORT_PUBLIC_KEY), and fix the review findings:

- Validate the key attributes in p_allocate and
  p_validate_slot_number before any id is reserved, so a key that
  cannot be created does not burn a slot. The same check in
  p_import rejects a bit count that does not match the material.
- Send a best-effort CRK_DELETE_KEY on the import error path, so
  a failed import does not leave the id reserved (the PSA core
  does not call p_destroy on failed creation, mbed-crypto#217).
- Map -EEXIST to PSA_ERROR_ALREADY_EXISTS, -ENOBUFS to
  PSA_ERROR_BUFFER_TOO_SMALL and -EFBIG to NOT_SUPPORTED.
- Reject slot numbers above UINT32_MAX instead of silently
  truncating them.
- The registration uses static const driver tables: no heap, no
  leak when a second registration returns ALREADY_EXISTS.
- p_export reports the length from the kernel's crp_nbits
  writeback instead of echoing the caller's buffer size.
- p_export_public returns NOT_SUPPORTED explicitly.

The dev_alt CIOCKEY wrapper is no longer conditional on
CONFIG_MBEDTLS_PSA_CRYPTODEV_ALT: it is already unconditional on
master (PR#4134), and ecdsa_alt/ecdh_alt use it too.

Signed-off-by: makejian <makejian@xiaomi.com>
@ThePassionate

Copy link
Copy Markdown
Contributor Author

All points addressed; the series is rebased onto current master (the dev_alt CIOCKEY wrapper hunks are dropped since #4134 made it unconditional) and tested against Mbed TLS 3.6.5.

  1. Rebase + drop dev_alt hunks: done - the conflicts against crypto/mbedtls: extend the ALT layer with asym, GCM, PKCS5 and key-id sessions #4134's ecdsa/ecdh/pkcs5 Kconfig, Makefile, CMakeLists entries are merged, and dev_alt.h/dev_alt.c come from master's unconditional version. psa_alt_key_op uses cryptodev_cryptk() which returns -errno on ioctl failure and crk_status as the ioctl result otherwise, so the error path the driver sees is the kernel's negative errno.

  2. Export length: p_export now reports kop.crk_param[1].crp_nbits / 8 - the kernel's writeback of the actual byte count. This requires the kernel crp_nbits copy-back you identified; without a small nuttx change the value stays at the input size, which for psa_export_key with a correctly-sized buffer is the key size. I'll send the kernel-side crp_nbits copy-back as a separate PR.

  3. Failed key creation leaks: p_allocate and p_validate_slot_number now call psa_alt_check_attributes() first - AES 128/192/256 only, NOT_SUPPORTED otherwise - so an unsupported key never reserves an id. p_import validates the type and length against the attributes before writing. On the import error path the driver sends a best-effort CRK_DELETE_KEY. The PSA core's own failure path (mbed-crypto#217) is documented in the commit message.

  4. Import validation: p_import checks the type is AES, the length matches the declared bits, and the length is 16/24/32. Anything else returns NOT_SUPPORTED.

  5. ECC/RSA dropped: the driver now supports AES only. The asymmetric generators and p_export_public return NOT_SUPPORTED explicitly. This matches what the in-tree software backend can do.

  6. Error mapping: -EEXIST → ALREADY_EXISTS, -ENOBUFS → BUFFER_TOO_SMALL, -EFBIG → NOT_SUPPORTED added.

  7. Slot truncation: psa_alt_check_slot() rejects anything above UINT32_MAX with INVALID_ARGUMENT, called from every entry point that takes a slot.

  8. Registration leak: the driver tables are static const with designated initializers - no heap, no leak.

Smaller items: the Kconfig help texts, the PSA_ITS_STORAGE_PREFIX trailing-slash note, the volatile-key flash behavior, and the MBEDTLS_PSA_CRYPTO_SE_C deprecation warning are all noted in the commit message or Kconfig; the prefix rename (CONFIG_MBEDTLS_PSA_ITS_STORAGE_PREFIX) is left for a separate cleanup since it changes the symbol name.

The psakey test is not carried in the tree (out of scope for this series); the development-time verification covered registration, volatile/persistent import/export, AES-256 generation, destroy semantics, and the exported material used as a working AES key.

@GUIDINGLI
GUIDINGLI merged commit c621be6 into apache:master Nov 27, 2026
41 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants