binman: add PKCS#11/HSM signing support for X509 certificates
v5 cover binman: add PKCS#11/HSM signing support for X509 certificates
Motivation
----------
TI K3 secure boot requires X509 certificates to be signed with a private key at build time. Until now, binman expected this key to be present as a plain PEM file on the build host. For production use, however, private keys should never exist unprotected on a build machine — they belong inside a Hardware Security Module (HSM) that enforces access control and keeps the key material unexportable.
This series adds support for signing X509 certificates via any PKCS#11- capable HSM (YubiKey, TPM, network HSM, SoftHSM2 for development, etc.).
Design
------
The 'keyfile' entry argument of x509_cert (and its TI K3 subclasses) now accepts either a filesystem path to a PEM key, as before, or a PKCS#11 URI referring to a key stored in an HSM. The URI is forwarded as-is to 'openssl -key', which resolves it via the pkcs11 provider (or engine) configured externally through OPENSSL_CONF. This keeps binman itself free of any PKCS#11-specific knowledge.
A new make variable, BINMAN_X509_KEY_URI, overrides the 'keyfile' entry argument for all x509 certificate signing operations:
make BINMAN_X509_KEY_URI="pkcs11:token=mytk;object=mykey;type=private" \
OPENSSL_CONF=/path/to/openssl.cnfThe recommended way to deliver the PIN for non-interactive signing is to configure pkcs11-module-token-pin in openssl.cnf under the pkcs11 provider section. As a convenience fallback, the PKCS11_PIN environment variable can be set; its value is appended to the URI as a percent- encoded ?pin-value=<pin> (per RFC 7512) so the PIN does not have to be embedded in BINMAN_X509_KEY_URI.
Two URI forms are supported on OpenSSL 3.x:
- Provider path (recommended), via the pkcs11-provider package
- Engine path, prefixed with org.openssl.engine:<engine_name>: so OpenSSL 3.x's STORE API routes it to the engine
Testing
-------
Tested on a Toradex Verdin AM62 (verdin-am62_a53_defconfig) board with both the engine path and the pkcs11 provider path, using SoftHSM2 and YubiKey 5 NFC.
A SoftHSM2-based integration test (testX509CertPkcs11) exercises the full signing path end-to-end against an in-tree test key; it skips cleanly when the OpenSSL pkcs11 provider is not installed. A unit test (testX509CertBuildPkcs11Key) covers the URI/PIN combiner including percent-encoding of reserved characters.
Changes in v5:
- Split the Entry_x509_cert docstring expansion into a separate preparatory commit (Simon)
- Unify URI support under the existing 'keyfile' entry argument rather than introducing a new 'x509-key-uri' arg; drop the Entry_x509_cert state and override logic that v4 added (Quentin)
- Percent-encode the PIN before appending to the URI using urllib.parse.quote(), per RFC 7512, and add a unit test covering PINs with reserved characters (Simon)
- Detect the OpenSSL pkcs11 provider via
'openssl list -providers -provider pkcs11' rather than discovering the provider .so path manually; drops the 'openssl version -m' MODULESDIR lookup (Quentin)
- Drop the 'p11-kit print-config' / softhsm2 .so discovery from the test; the simpler openssl.cnf relies on softhsm2 being registered with p11-kit globally (Quentin). As a side effect this also fixes the test on Ubuntu 22.04, where 'p11-kit print-config' is not a valid subcommand
- Move the test openssl.cnf in-tree as tools/binman/test/fit/openssl_provider.conf and trim it to the minimum needed (no 'module = ', no 'pkcs11-module-path = ') (Quentin)
- Replace 'pkcs11-tool --keypairgen' with 'softhsm2-util --import' of tools/binman/test/fit/rsa2048.key so the test runs faster and drops the pkcs11-tool dependency (Quentin)
- Recommend pkcs11-module-token-pin in openssl.cnf as the primary way to deliver the PIN; PKCS11_PIN env var is now documented as the convenience fallback (Quentin)
- Drop the incorrect claim that PKCS11_PIN keeps the PIN out of shell history (Quentin)
- Rephrase the URI intro in binman.rst and clarify that 'pkcs11-provider' is a Debian package name, not a path (Quentin)
- Drop the inheritance notes added to Entry_ti_secure and Entry_ti_secure_rom in v4; with the v5 keyfile unification the original motivation (an inherited x509-key-uri property) no longer applies
Changes in v4:
- Drop the v3 bintool extra_env commit entirely; binman no longer sets any PKCS#11-related environment variables (Quentin)
- Drop BINMAN_PKCS11_MODULE / pkcs11-module entry argument; the PKCS#11 module path must be configured externally via openssl.cnf (Quentin)
- Drop provider/engine auto-detection (_pkcs11_use_provider, _build_key_args, _run_cmd_pkcs11) along with the threading.Lock; the user selects provider or engine via OPENSSL_CONF and the URI form (Quentin)
- Rename the v3 BINMAN_PKCS11_URI / pkcs11-uri to BINMAN_X509_KEY_URI / x509-key-uri to scope the names to x509 certificate entries without locking them to a specific URI scheme (Quentin)
- Document that the engine path is supported on OpenSSL 3.x by prefixing the URI with org.openssl.engine:<engine_name>: (Quentin)
- Replace the mocked openssl test with a real SoftHSM2-based integration test using the provider path and OPENSSL_CONF (Quentin)
- Use 'p11-kit print-config' to locate the softhsm2 library at test time instead of hardcoding a distro-specific path (Quentin)
- Use 'openssl version -m' (MODULESDIR) to locate the OpenSSL pkcs11 provider .so file, so multiarch paths like /usr/lib/x86_64-linux-gnu/ossl-modules on Debian/Ubuntu are handled correctly
- Generate the test RSA keypair with pkcs11-tool; softhsm2-util has no key-generation action (only --import) and silently exits 0 on an unknown --generate-keypair option, which would leave the token empty and make the openssl step fail with 'Could not read private key'
- Add self._CheckBintool() to all PKCS#11 test paths so tests skip cleanly when bintools are missing (Quentin)
- Extract the URI/PIN combiner into Entry_x509_cert._build_pkcs11_key() and add a unit test for it
- Document that PKCS11_PIN keeps the PIN out of the make command line but is still visible in 'ps' output via the openssl invocation; for improved isolation, configure the PIN in openssl.cnf
- Document all Entry_x509_cert properties (content, keyfile, x509-key-uri, cert-ca, cert-revision-int, sw-rev) in its docstring (Quentin)
- Add inheritance notes to Entry_ti_secure and Entry_ti_secure_rom docstrings, pointing out that they extend Entry_x509_cert via super() and therefore accept its properties (notably x509-key-uri) (Quentin)
Changes in v3:
- Split into two patches: bintool infrastructure (1/2) and x509_cert feature (2/2)
- Fix global environment mutation: _run_cmd_pkcs11() no longer writes to os.environ directly; it now uses the new extra_env parameter so module paths are scoped to the subprocess only, which is both cleaner and safe under concurrent execution
- Add module-level threading.Lock to serialise concurrent PKCS#11 signing calls and fix intermittent login failures caused by binman's ThreadPoolExecutor
- Fix URI query string separator: use '&' when the URI already contains '?' (e.g. module-path already present), '?' otherwise
- Test cases updated
Changes in v2:
- Add tests for _build_key_args() (PEM path, PKCS#11 provider, PKCS#11 engine, PIN appending), _pkcs11_use_provider() (caching), _run_cmd_pkcs11() (with and without module path), and end-to-end x509_cert signing with a PKCS#11 URI (testX509CertPkcs11), ensuring btool/openssl.py and etype/x509_cert.py have 100% test coverage
Sergio Prado (2):
binman: x509_cert: document Entry_x509_cert properties
binman: x509_cert: support PKCS#11 URI in keyfile for HSM signing
Makefile | 1 + tools/binman/binman.rst | 55 ++++++++++++ tools/binman/etype/x509_cert.py | 45 ++++++++-- tools/binman/ftest.py | 92 +++++++++++++++++++++ tools/binman/test/fit/openssl_provider.conf | 14 ++++ 5 files changed, 202 insertions(+), 5 deletions(-) create mode 100644 tools/binman/test/fit/openssl_provider.conf
Signature · 1 line
2.34.1
PATCH v5 1/2 binman: x509_cert: document Entry_x509_cert properties
The Entry_x509_cert class only listed 'content' in its 'Properties / Entry arguments' section, even though 'keyfile', 'cert-ca', 'cert-revision-int' and 'sw-rev' are also read from the entry node and passed through to openssl.
Expand the docstring so the binman documentation generated from it matches the actual behavior of the entry.
No functional change.
--- tools/binman/etype/x509_cert.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)
tools/binman/etype/x509_cert.py +9 -1
@@ -18,7 +18,15 @@ class Entry_x509_cert(Entry_collection): """An entry which contains an X509 certificate Properties / Entry arguments: - - content: List of phandles to entries to sign + - content: List of phandles to entries to sign. + - keyfile: Filename of the PEM key file used to sign the binary. + - cert-ca: Common Name (CN) embedded in the certificate. Used when + generating a generic x509 certificate. + - cert-revision-int: Integer certificate revision number. Used when + generating a generic x509 certificate. Defaults to 0. + - sw-rev: Software revision number embedded in the certificate by + the sysfw/rom variants used by the TI K3 secure boot subclasses. + Defaults to 1. Output files: - input.<unique_name> - input file passed to openssl
Signature · 1 line
2.34.1
Re: [PATCH v5 1/2] binman: x509_cert: document Entry_x509_cert properties
Quoted 10 lines · Sergio Prado
binman:
x509_cert: documentEntry_x509_certpropertiesThe
Entry_x509_certclass only listed 'content' in its 'Properties / Entry arguments' section, even though 'keyfile', 'cert-ca', 'cert-revision-int' and 'sw-rev' are also read from the entry node and passed through to openssl.Expand the docstring so the binman documentation generated from it matches the actual behavior of the entry.
Quoted 6 lines
No functional change.
Signed-off-by Sergio Prado <[email protected]>
tools/binman/etype/x509_cert.py| 10 +++++++++-1 file changed, 9 insertions(+), 1 deletion(-)
Re: [PATCH v5 1/2] binman: x509_cert: document Entry_x509_cert properties
In reply to Sergio PradoHi Sergio,
Quoted 20 lines · Sergio Prado
The
Entry_x509_certclass only listed 'content' in its 'Properties / Entry arguments' section, even though 'keyfile', 'cert-ca', 'cert-revision-int' and 'sw-rev' are also read from the entry node and passed through to openssl.Expand the docstring so the binman documentation generated from it matches the actual behavior of the entry.
No functional change.
Signed-off-by Sergio Prado <[email protected]>--- tools/binman/etype/x509_cert.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-)tools/binman/etype/x509_cert.py +0
-0
tools/binman/etype/x509_cert.py class Entry_x509_cert(Entry_collection): · line 24
Quoted 8 lines
tools/binman/etype/x509_cert.py +4
-1@@ -18,7 +18,15 @@ class Entry_x509_cert(Entry_collection): """An entry which contains an X509 certificate Properties / Entry arguments: - - content: List of phandles to entries to sign + - content: List of phandles to entries to sign. + - keyfile: Filename of the PEM key file used to sign the binary. + - cert-ca: Common Name (CN) embedded in the certificate. Used when + generating a generic x509 certificate.
You know what's funny? This isn't used at all. Parsed and passed to the openssl bintool, and it does nothing with it. I bet
CN = {cert_fname}
should actually be
CN = {cn}
and we probably should add a test to whatever's using tools/binman/test/security/x509_cert.dts to actually test the CN is the expected one.
tools/binman/etype/x509_cert.py class Entry_x509_cert(Entry_collection): · line 30
Quoted 6 lines
tools/binman/etype/x509_cert.py +5
-0+ - cert-revision-int: Integer certificate revision number. Used when + generating a generic x509 certificate. Defaults to 0. + - sw-rev: Software revision number embedded in the certificate by + the sysfw/rom variants used by the TI K3 secure boot subclasses. + Defaults to 1.
Sigh.. It seems like cert-revision-int and sw-rev are actually used for the same thing, just with a different default value.
It'd be nice to send a follow-up commit either fixing the non-use of cert-ca, or remove it entirely. Not necessary for this patch series though.
Thanks!
Quentin
PATCH v5 2/2 binman: x509_cert: support PKCS#11 URI in keyfile for HSM signing
In reply to Sergio PradoAllow x509 certificate entries to be signed using a key stored in an HSM by accepting a PKCS#11 URI (RFC 7512) as the value of the 'keyfile' entry argument, instead of a path to a PEM key file on disk. The URI is forwarded as-is to openssl '-key', which resolves it via the pkcs11 provider configured externally through OPENSSL_CONF.
A new make variable BINMAN_X509_KEY_URI is introduced. When set, it overrides the 'keyfile' entry argument for all x509 certificate signing operations:
make BINMAN_X509_KEY_URI="pkcs11:token=mytk;object=mykey;type=private" \
OPENSSL_CONF=/path/to/openssl.cnfTwo URI forms are supported on OpenSSL 3.x:
- Provider path: pkcs11:token=...;object=...;type=private
- Engine path: org.openssl.engine:pkcs11:pkcs11:token=...;...
In both cases the user is responsible for configuring OpenSSL externally, as binman simply passes the URI to 'openssl -key'.
The recommended way to deliver the PIN for non-interactive signing is to configure pkcs11-module-token-pin in openssl.cnf under the pkcs11 provider section. As a convenience fallback, the PKCS11_PIN environment variable can be set; its value is appended to the URI as ?pin-value=<pin> (or &pin-value=<pin> if the URI already contains a '?'), percent-encoded per RFC 7512, so the PIN does not have to be embedded in BINMAN_X509_KEY_URI.
The PIN-rewriting step in GetCertificate() uses a local variable rather than mutating self.key_fname, because ProcessContents() calls GetCertificate() a second time on the same entry; an in-place rewrite would double-append the PIN on the second call.
Existing behavior is unchanged when keyfile is a filesystem path and BINMAN_X509_KEY_URI is not set.
Tested with SoftHSM2 and Yubikey on OpenSSL 3.x using the verdin-am62_a53_defconfig configuration. The new testX509CertPkcs11 test exercises the full path end-to-end against a SoftHSM2 token; it skips cleanly when the OpenSSL pkcs11 provider is not installed.
--- Makefile | 1 + tools/binman/binman.rst | 55 ++++++++++++ tools/binman/etype/x509_cert.py | 37 +++++++-- tools/binman/ftest.py | 92 +++++++++++++++++++++ tools/binman/test/fit/openssl_provider.conf | 14 ++++ 5 files changed, 194 insertions(+), 5 deletions(-) create mode 100644 tools/binman/test/fit/openssl_provider.conf
Makefile +1 -0
@@ -1704,6 +1704,7 @@ cmd_binman = $(srctree)/tools/binman/binman $(if $(BINMAN_DEBUG),-D) \ -a vpl-dtb=$(CONFIG_VPL_OF_REAL) \ -a pre-load-key-path=${PRE_LOAD_KEY_PATH} \ -a of-spl-remove-props=$(CONFIG_OF_SPL_REMOVE_PROPS) \ + $(if $(BINMAN_X509_KEY_URI),-a keyfile="$(BINMAN_X509_KEY_URI)") \ $(BINMAN_$(@F)) OBJCOPYFLAGS_u-boot.ldr.hex := -I binary -O ihex
tools/binman/binman.rst +55 -0
61 lines not on this page · raw message
tools/binman/etype/x509_cert.py +32 -5
@@ -7,6 +7,7 @@ from collections import OrderedDict import os +import urllib.parse from binman.entry import EntryArg from binman.etype.collection import Entry_collection
@@ -19,7 +20,11 @@ class Entry_x509_cert(Entry_collection): Properties / Entry arguments: - content: List of phandles to entries to sign. - - keyfile: Filename of the PEM key file used to sign the binary. + - keyfile: Filename of the PEM key file used to sign the binary, or + a PKCS#11 URI (RFC 7512) referring to a key stored in an HSM, + e.g. ``pkcs11:token=mytoken;object=mykey;type=private``. See + ``BINMAN_X509_KEY_URI`` in the binman documentation for the + full setup. - cert-ca: Common Name (CN) embedded in the certificate. Used when generating a generic x509 certificate. - cert-revision-int: Integer certificate revision number. Used when
@@ -88,6 +93,15 @@ class Entry_x509_cert(Entry_collection): if input_data is None: return None + # When keyfile is a PKCS#11 URI and PKCS11_PIN is set, append the + # PIN to the URI so signing runs non-interactively. The preferred + # way to deliver a PIN is to configure pkcs11-module-token-pin in + # openssl.cnf; PKCS11_PIN is the convenience fallback. + key_fname = self.key_fname + pin = os.environ.get('PKCS11_PIN') + if pin and 'pkcs11:' in key_fname: + key_fname = self._build_pkcs11_key(key_fname, pin) + uniq = self.GetUniqueName() output_fname = tools.get_output_filename('cert.%s' % uniq) input_fname = tools.get_output_filename('input.%s' % uniq)
@@ -98,7 +112,7 @@ class Entry_x509_cert(Entry_collection): stdout = self.openssl.x509_cert( cert_fname=output_fname, input_fname=input_fname, - key_fname=self.key_fname, + key_fname=key_fname, cn=self._cert_ca, revision=self._cert_rev, config_fname=config_fname)
@@ -106,7 +120,7 @@ class Entry_x509_cert(Entry_collection): stdout = self.openssl.x509_cert_sysfw( cert_fname=output_fname, input_fname=input_fname, - key_fname=self.key_fname, + key_fname=key_fname, config_fname=config_fname, sw_rev=self.sw_rev, req_dist_name_dict=self.req_dist_name,
@@ -115,7 +129,7 @@ class Entry_x509_cert(Entry_collection): stdout = self.openssl.x509_cert_rom( cert_fname=output_fname, input_fname=input_fname, - key_fname=self.key_fname, + key_fname=key_fname, config_fname=config_fname, sw_rev=self.sw_rev, req_dist_name_dict=self.req_dist_name,
@@ -130,7 +144,7 @@ class Entry_x509_cert(Entry_collection): stdout = self.openssl.x509_cert_rom_combined( cert_fname=output_fname, input_fname=input_fname, - key_fname=self.key_fname, + key_fname=key_fname, config_fname=config_fname, sw_rev=self.sw_rev, req_dist_name_dict=self.req_dist_name,
@@ -176,3 +190,16 @@ class Entry_x509_cert(Entry_collection): def AddBintools(self, btools): super().AddBintools(btools) self.openssl = self.AddBintool(btools, 'openssl') + + @staticmethod + def _build_pkcs11_key(uri, pin): + """Append pin-value to a PKCS#11 URI when a PIN is provided. + + The PIN is percent-encoded per RFC 7512. Uses '&' as separator if + the URI already contains '?', else '?'. Returns the URI unchanged + when pin is None or empty. + """ + if not pin: + return uri + sep = '&' if '?' in uri else '?' + return f'{uri}{sep}pin-value={urllib.parse.quote(pin, safe="")}'
tools/binman/ftest.py +92 -0
104 lines not on this page · raw message
tools/binman/test/fit/openssl_provider.conf new file +14 -0
@@ -0,0 +1,14 @@ +openssl_conf = openssl_init + +[openssl_init] +providers = providers_section + +[providers_section] +default = default_provider +pkcs11 = pkcs11_provider + +[default_provider] +activate = 1 + +[pkcs11_provider] +activate = 1
Signature · 1 line
2.34.1
Re: [PATCH v5 2/2] binman: x509_cert: support PKCS#11 URI in keyfile for HSM signing
Hi Sergio,
Quoted 31 lines · Sergio Prado
binman:
x509_cert: support PKCS#11 URI in keyfile for HSM signingAllow x509 certificate entries to be signed using a key stored in an HSM by accepting a PKCS#11 URI (RFC 7512) as the value of the 'keyfile' entry argument, instead of a path to a PEM key file on disk. The URI is forwarded as-is to openssl '-key', which resolves it via the pkcs11 provider configured externally through
OPENSSL_CONF.A new make variable
BINMAN_X509_KEY_URIis introduced. When set, it overrides the 'keyfile' entry argument for all x509 certificate signing operations:make BINMAN_X509_KEY_URI="pkcs11:token=mytk;object=mykey;type=private" \ OPENSSL_CONF=/path/to/openssl.cnfTwo URI forms are supported on OpenSSL 3.x:
- Provider path: pkcs11:token=...;object=...;type=private
- Engine path: org.openssl.engine:pkcs11:pkcs11:token=...;...[...]
Makefile| 1 +tools/binman/binman.rst | 55 +++++++++++++++++ tools/binman/etype/x509_cert.py | 37 ++++++++++-- tools/binman/ftest.py | 92 +++++++++++++++++++++++++++++ tools/binman/test/fit/openssl_provider.conf | 14 +++++ 5 files changed, 194 insertions(+), 5 deletions(-)
tools/binman/etype/x509_cert.py class Entry_x509_cert(Entry_collection): · line 100
Quoted 8 lines
tools/binman/etype/x509_cert.py +8
-0@@ -88,6 +93,15 @@ class Entry_x509_cert(Entry_collection): + # When keyfile is a PKCS#11 URI and PKCS11_PIN is set, append the + # PIN to the URI so signing runs non-interactively. The preferred + # way to deliver a PIN is to configure pkcs11-module-token-pin in + # openssl.cnf; PKCS11_PIN is the convenience fallback. + key_fname = self.key_fname + pin = os.environ.get('PKCS11_PIN') + if pin and 'pkcs11:' in key_fname: + key_fname = self._build_pkcs11_key(key_fname, pin)
nit: the 'pkcs11:' substring test is loose - a filesystem path containing that token would be treated as a URI. Please use key_fname.startswith(('pkcs11:', 'org.openssl.engine:')) instead.
Also, the commit message says the URI is forwarded as-is to openssl -key, which isn't quite true once PKCS11_PIN is appended. Please reword to match the code.
tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 6907
Quoted 4 lines
tools/binman/ftest.py +2
-0@@ -6905,6 +6906,97 @@ fdt fdtmap Extract the devicetree blob from the fdtmap + def testX509CertPkcs11(self): + """Test X509 certificate signing via a PKCS#11 URI in keyfile"""
The test only exercises the provider form; the engine prefix is documented as supported but not covered. A small extra case in testX509CertBuildPkcs11Key for an engine-prefixed URI would catch regressions in the combiner without needing libengine-pkcs11-openssl installed.
Regards,
Simon
Re: [PATCH v5 2/2] binman: x509_cert: support PKCS#11 URI in keyfile for HSM signing
Hi Simon,
Em dom., 14 de jun. de 2026 às 13:01, Simon Glass <[email protected]> escreveu:
[...]
Quoted 3 lines
nit: the 'pkcs11:' substring test is loose - a filesystem path containing that token would be treated as a URI. Please use
key_fname.startswith(('pkcs11:', 'org.openssl.engine:'))instead.
Will fix it in v6. I'll make it slightly stricter than suggested, startswith(('pkcs11:',
'org.openssl.engine:pkcs11:')), so that a non-pkcs11 engine key (e.g. org.openssl.engine:tpm2tss:...) doesn't get a pin-value attribute appended to it.
Quoted 3 lines
Also, the commit message says the URI is forwarded as-is to openssl -key, which isn't quite true once
PKCS11_PINis appended. Please reword to match the code.
Will reword in v6.
Quoted 5 lines
The test only exercises the provider form; the engine prefix is documented as supported but not covered. A small extra case in testX509CertBuildPkcs11Key for an engine-prefixed URI would catch regressions in the combiner without needing libengine-pkcs11-openssl installed.
Good idea, will add it in v6.
Thanks for the review!
Sergio Prado
Re: [PATCH v5 2/2] binman: x509_cert: support PKCS#11 URI in keyfile for HSM signing
In reply to Sergio PradoHi Sergio,
Thanks for your patience!
I think this could be split in multiple commits. I could identify the following unrelated changes:
1) documentation on how to use PKCS11 signing (+ test for it). I believe PKCS11 is already supported via OPENSSL_CONF for the provider, with a pkcs11 uri in keyfile property in DT + additionally the pin either in OPENSSL_CONF or in the keyfile property directly, I haven't tested though so maybe I'm wrong
2) support for PKCS11_PIN environment variable to pass the pin, (+ test for it)
3) support for overriding the keyfile property via a make variable (BINMAN_X509_KEY_URI), (+ test for it)
Do you agree with this split?
There's quite a few comments below, but I don't think they require big changes.
On 5/25/26 3:28 PM, Sergio Prado wrote:
[...]
Quoted 5 lines
The PIN-rewriting step in
GetCertificate()uses a local variable rather than mutating self.key_fname, becauseProcessContents()callsGetCertificate()a second time on the same entry; an in-place rewrite would double-append the PIN on the second call.
Should we rather move this logic to ReadNode() instead then? Hopefully that is run only once? What made you chose GetCertificate() for this logic? Maybe I'm missing some clue.
[...]
tools/binman/binman.rst BINMAN_INDIRS · line 2169
Quoted 6 lines
tools/binman/binman.rst +6
-0+BINMAN_X509_KEY_URI + URI of a key used to sign x509 certificate entries via an HSM instead of a + PEM key file on disk. When set, it is passed as ``-a keyfile=<uri>`` to + binman, which overrides the ``keyfile`` entry argument for all x509 + certificate signing operations. +
This isn't specific to HSMI/PKCS11 though, is it? So it's just a way to override the keyfile entry argument by an environment variable. Yes, the typical usecase is to use it for an HSM but nothing forces you to use it for an HSM?
[...]
tools/binman/binman.rst BINMAN_INDIRS · line 2177
Quoted 5 lines
tools/binman/binman.rst +5
-0+ + URIs currently supported: + + - PKCS#11 URI (RFC 7512) +
Aren't we missing "local PEM key file" here?
Quoted 1 line
+ PKCS#11 signing requires OpenSSL 3.x. The provider or engine and the
Is it requiring OpenSSL 3.x though or did you only test on OpenSSL 3.x? Since engines were supported in OpenSSL 1.x, I would assume PKCS11 signing also worked back then? Are you aware of a limitation? Also, does it NOT work with OpenSSL 4.x (which distro will slowly start to migrate to)?
What I'm trying to figure out is whether we should reword this to "PKCS11 signing is only tested on OpenSSL 3.x".
Quoted 6 lines
tools/binman/binman.rst +6
-0+ PKCS#11 module must be configured externally via an ``openssl.cnf`` file. + Either rely on the system default (``/etc/ssl/openssl.cnf``) or point to a + custom file via ``OPENSSL_CONF``. + + Two URI forms are supported on OpenSSL 3.x: +
tools/binman/binman.rst BINMAN_INDIRS · line 2194
Quoted 10 lines
tools/binman/binman.rst +10
-0+ 1. Provider path (recommended) — requires the pkcs11 provider, e.g. via + the ``pkcs11-provider`` package:: + + make BINMAN_X509_KEY_URI="pkcs11:token=mytoken;object=mykey;type=private" \ + OPENSSL_CONF=/path/to/openssl.cnf + + 2. Engine path — for setups where only an OpenSSL engine is available + (e.g. ``libengine-pkcs11-openssl``). Prefix the URI with + ``org.openssl.engine:<engine_name>:`` so OpenSSL 3.x's STORE API + routes it to the engine without requiring ``-engine``/``-keyform``
Ah yes, now I remember why it's OpenSSL 3+ only! Mmmmm then wondering what to do for OpenSSL 4.x, any chance you can test whether it works with OpenSSL 4? If not, then keep the previous paragraph as is and ignore my comment.
[...]
tools/binman/binman.rst BINMAN_INDIRS · line 2202
Quoted 3 lines
tools/binman/binman.rst +3
-0+ OpenSSL 1.x engine usage is not supported transparently; users on + OpenSSL 1.x need to provide the engine flags through other means. +
Yeah, or just say "OpenSSL 1.x is not supported." and be done with it :)
[...]
tools/binman/binman.rst BINMAN_INDIRS · line 2212
Quoted 3 lines
tools/binman/binman.rst +3
-0+ PKCS11_PIN=1234 make BINMAN_X509_KEY_URI="pkcs11:..." \ + OPENSSL_CONF=/path/to/openssl.cnf +
question: why suddenly the variable before make? All the others are after so it seems like an odd choice to me.
tools/binman/binman.rst BINMAN_INDIRS · line 2218
Quoted 6 lines
tools/binman/binman.rst +6
-0+ Note: ``PKCS11_PIN`` keeps the PIN out of the ``BINMAN_X509_KEY_URI`` + value itself, but the PIN is still passed to ``openssl`` as part of its + command line, where it is visible via ``ps`` and may appear in verbose + build logs. For stronger isolation, configure the PIN inside + ``openssl.cnf`` as described above. +
The third option is to have the pin in the URI directly (which is equally bad, but is possible no?).
I'm wondering if we should support replacing the PIN inside the URI if there's one in it and we also have PKCS11_PIN.
Side question, what happens if we have a pin set in openssl.cnf and also via PKCS11_PIN/pin in the URI?
Trying to figure out if we should explicitly document those incompatibilities (if they exist!) or test them if we want to support those cases.
[...]
tools/binman/etype/x509_cert.py class Entry_x509_cert(Entry_collection): · line 102
Quoted 11 lines
tools/binman/etype/x509_cert.py +7
-0@@ -88,6 +93,15 @@ class Entry_x509_cert(Entry_collection): if input_data is None: return None + # When keyfile is a PKCS#11 URI and PKCS11_PIN is set, append the + # PIN to the URI so signing runs non-interactively. The preferred + # way to deliver a PIN is to configure pkcs11-module-token-pin in + # openssl.cnf; PKCS11_PIN is the convenience fallback. + key_fname = self.key_fname + pin = os.environ.get('PKCS11_PIN') + if pin and 'pkcs11:' in key_fname:
I agree with Simon here, we need to check the key starts with pkcs11: (and if we want to support OpenSSL engines with OpenSSL 3.x like we document if in here, then also org.openssl.engine:pkcs11:).
[...]
Quoted 20 lines
tools/binman/ftest.py +5
-0@@ -35,6 +35,7 @@ from dtoc import fdt from dtoc import fdt_util from binman.etype import fdtmap from binman.etype import image_header +from binman.etype.x509_cert import Entry_x509_cert from binman.image import Image from u_boot_pylib import command from u_boot_pylib import terminal@@ -6905,6 +6906,97 @@ fdt fdtmap Extract the devicetree blob from the fdtmap err = stderr.getvalue() self.assertRegex(err, "Image 'image'.*missing bintools.*: openssl") + def testX509CertPkcs11(self): + """Test X509 certificate signing via a PKCS#11 URI in keyfile""" + openssl = bintool.Bintool.create('openssl') + self._CheckBintool(openssl)
tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 6922
Quoted 10 lines
tools/binman/ftest.py +10
-0+ + # Detect the OpenSSL pkcs11 provider. -provider asks OpenSSL to load + # the named provider, so the command succeeds only when the provider + # module is installed; this works regardless of OPENSSL_CONF state. + result = openssl.run_cmd_result('list', '-providers', + '-provider', 'pkcs11', + raise_on_error=False) + if result is None or result.return_code != 0: + self.skipTest('OpenSSL pkcs11 provider not available') +
Idly wondering if we shouldn't do a simple try:except and let raise_on_error to True and skip in the except.
[...]
tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 6954
Quoted 4 lines
tools/binman/ftest.py +4
-0+ with unittest.mock.patch.dict('os.environ', + {'SOFTHSM2_CONF': softhsm2_conf, + 'OPENSSL_CONF': openssl_conf, + 'PKCS11_PIN': pin}):
Please add a test for when the pin is passed via the URI directly (as I assume this is supported) and not through the env variable.
Quoted 8 lines
tools/binman/ftest.py +8
-0+ softhsm2_util.run_cmd('--init-token', '--free', '--label', token, + '--pin', pin, '--so-pin', '000000') + softhsm2_util.run_cmd('--import', private_key, '--token', token, + '--label', key_label, '--id', '01', + '--pin', pin) + + uri = f'pkcs11:token={token};object={key_label};type=private' + entry_args = {
tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 6972
Quoted 10 lines
tools/binman/ftest.py +10
-0+ # 'keyfile' is set to a PKCS#11 URI rather than a filesystem + # path. binman forwards it to 'openssl -key', which resolves + # it via the pkcs11 provider configured in OPENSSL_CONF. + # PKCS11_PIN is appended to the URI by Entry_x509_cert before + # the openssl invocation, exercising _build_pkcs11_key(). + 'keyfile': uri, + } + data = self._DoReadFileDtb('security/x509_cert.dts', + entry_args=entry_args)[0] + self.assertEqual(U_BOOT_DATA, data[-4:])
We should add a keyfile property in the test device tree to make sure we override it with the entryarg.
I'm also surprised tools/binman/test/security/x509_cert.dts doesn't have a keyfile property, isn't it marked as required in tools/binman/etype/x509_cert.py? AH! It seems like we pass it via an entryarg in testX509Cert and testX509CertMissing.
It'd be nice to check the engine works as well with the prefix. Not sure how to properly test this, if it's easier, I would be fine with checking we pass the key with the org.openssl.engine: prefix, at that point if it fails it's an openssl issue and we've already checked with the provider the code path is correct so that'd be an okay compromise to avoid testing the whole code path.
Cheers,
Quentin
Re: [PATCH v5 2/2] binman: x509_cert: support PKCS#11 URI in keyfile for HSM signing
Hi Quentin,
Em qui., 18 de jun. de 2026 às 14:42, Quentin Schulz < [email protected]> escreveu:
Quoted 3 lines
I think this could be split in multiple commits. I could identify the following unrelated changes:
[...]
Quoted 1 line
Do you agree with this split?
Yes, that's a fair split, will do in v6. And you're right on 1): the plain PKCS#11 URI case already works today without any code change, since binman passes keyfile through to 'openssl -key' unchanged and the provider configured via OPENSSL_CONF resolves it (with the PIN coming from openssl.cnf or a pin-value attribute in the URI). So the first patch of the split will be docs plus a test exercising exactly that.
Quoted 3 lines
Should we rather move this logic to
ReadNode()instead then? Hopefully that is run only once? What made you choseGetCertificate()for this logic? Maybe I'm missing some clue.
I wanted to avoid mutating entry state given the double GetCertificate() call, hence the local variable. But ReadNode() runs once, so moving the logic there is simpler; will do in v6. I'll also make the helper skip appending when the URI already carries a pin-value attribute, so it becomes idempotent either way.
Quoted 4 lines
This isn't specific to HSMI/PKCS11 though, is it? So it's just a way to override the keyfile entry argument by an environment variable. Yes, the typical usecase is to use it for an HSM but nothing forces you to use it for an HSM?
Correct, it's a generic override. I'll reword the documentation and rename the variable to BINMAN_X509_KEYFILE in v6 so the name matches the entry argument it overrides (it can carry a plain key file path just as well as a URI). Shout if you prefer the old name or a different one.
Quoted 1 line
Aren't we missing "local PEM key file" here?
Indeed, will restructure the list as the accepted forms of 'keyfile': local key file (default), PKCS#11 URI via provider, engine-prefixed URI.
Quoted 4 lines
Is it requiring OpenSSL 3.x though or did you only test on OpenSSL 3.x? Since engines were supported in OpenSSL 1.x, I would assume PKCS11 signing also worked back then? Are you aware of a limitation? Also, does it NOT work with OpenSSL 4.x (which distro will slowly start to migrate
to)?
It is a hard requirement, and it follows from the design we settled on in the v3 review: binman never passes -engine/-keyform itself (the v3 auto-detection
machinery that could have done so was dropped on your suggestion), so the key must be resolvable through a bare 'openssl -key <uri>'. That only works with the provider API or the org.openssl.engine: STORE scheme, both introduced in OpenSSL 3.0. On 1.x there is no transparent path, hence "OpenSSL 1.x is not supported."
As for OpenSSL 4.x: the ENGINE API was removed entirely in OpenSSL 4.0 [1], so the engine-prefixed form is OpenSSL 3.x only; the provider path is the way forward and expected to work unchanged on 4.x. I'll reword the docs to state all of this explicitly.
[1] https://openssl-library.org/post/2025-12-18-remove-engines/
Quoted 1 line
Yeah, or just say "OpenSSL 1.x is not supported." and be done with it :)
Will do :)
Quoted 2 lines
question: why suddenly the variable before
make? All the others are after so it seems like an odd choice to me.
It was deliberate: PKCS11_PIN is an environment variable read by binman itself (via os.environ), not a make variable interpreted by the build system. In practice make PKCS11_PIN=1234 also works since make exports command-line variables to recipes. I'll add a sentence making that explicit.
Quoted 2 lines
The third option is to have the pin in the URI directly (which is equally bad, but is possible no?).
Yes, that works today (it's the "no code change" case above); I'll document it.
Quoted 2 lines
I'm wondering if we should support replacing the PIN inside the URI if there's one in it and we also have
PKCS11_PIN.
I'd rather define PKCS11_PIN strictly as a fallback: if the URI already contains
a pin-value attribute, the URI wins and PKCS11_PIN is ignored (right now the code would blindly append a second pin-value, which RFC 7512 doesn't allow). Will implement, document and unit-test that precedence in v6. Silently replacing would be surprising, IMO.
Quoted 2 lines
Side question, what happens if we have a pin set in openssl.cnf and also via PKCS11_PIN/pin in the URI?
I'll test this with softhsm2 and document the observed precedence in v6. I expect the URI pin-value to take precedence over pkcs11-module-token-pin, but I want to confirm before writing it down.
Quoted 2 lines
Idly wondering if we shouldn't do a simple try:except and let
raise_on_errorto True and skip in the except.
I have a mild preference for the explicit return-code check, since a missing provider is an expected outcome rather than an error. But I don't feel strongly, happy to change it if you do.
Quoted 2 lines
Please add a test for when the pin is passed via the URI directly (as I assume this is supported) and not through the env variable.
Will do.
Quoted 2 lines
We should add a keyfile property in the test device tree to make sure we override it with the entryarg.
Will do. I confirmed entry arguments take precedence over the device tree property (Entry.GetArg() checks entry args first).
Quoted 1 line
It'd be nice to check the engine works as well with the prefix. [...]
Simon suggested the same compromise; I'll add a unit test that the PIN combiner leaves the org.openssl.engine:pkcs11: prefix intact, plus a check that the prefixed URI reaches the openssl invocation unchanged.
I am going on vacation and will be back in a few weeks, so I'll address all of the above and send v6 once I return. In the meantime, if you have any additional comments before I prepare v6, please let me know.
Thanks a lot for the thorough review!
Sergio Prado
Hi Simon, Quentin,
Do you have any feedback on the v5 series?
Best regards,
Sergio Prado
Em seg., 25 de mai. de 2026 às 10:29, Sergio Prado < [email protected]> escreveu:
Quoted 172 lines
Motivation
----------TI K3 secure boot requires X509 certificates to be signed with a private key at build time. Until now, binman expected this key to be present as a plain PEM file on the build host. For production use, however, private keys should never exist unprotected on a build machine — they belong inside a Hardware Security Module (HSM) that enforces access control and keeps the key material unexportable.
This series adds support for signing X509 certificates via any PKCS#11- capable HSM (YubiKey, TPM, network HSM, SoftHSM2 for development, etc.).
Design
------The 'keyfile' entry argument of
x509_cert(and its TI K3 subclasses) now accepts either a filesystem path to a PEM key, as before, or a PKCS#11 URI referring to a key stored in an HSM. The URI is forwarded as-is to 'openssl -key', which resolves it via the pkcs11 provider (or engine) configured externally throughOPENSSL_CONF. This keeps binman itself free of any PKCS#11-specific knowledge.A new make variable,
BINMAN_X509_KEY_URI, overrides the 'keyfile' entry argument for all x509 certificate signing operations:make BINMAN_X509_KEY_URI="pkcs11:token=mytk;object=mykey;type=private"
\
OPENSSL_CONF=/path/to/openssl.cnfThe recommended way to deliver the PIN for non-interactive signing is to configure pkcs11-module-token-pin in openssl.cnf under the pkcs11 provider section. As a convenience fallback, the
PKCS11_PINenvironment variable can be set; its value is appended to the URI as a percent- encoded ?pin-value=<pin> (per RFC 7512) so the PIN does not have to be embedded inBINMAN_X509_KEY_URI.Two URI forms are supported on OpenSSL 3.x:
- Provider path (recommended), via the pkcs11-provider package
- Engine path, prefixed with org.openssl.engine:<engine_name>: so OpenSSL 3.x's STORE API routes it to the engineTesting
-------Tested on a Toradex Verdin AM62 (verdin-am62_a53_defconfig) board with both the engine path and the pkcs11 provider path, using SoftHSM2 and YubiKey 5 NFC.
A SoftHSM2-based integration test (testX509CertPkcs11) exercises the full signing path end-to-end against an in-tree test key; it skips cleanly when the OpenSSL pkcs11 provider is not installed. A unit test (testX509CertBuildPkcs11Key) covers the URI/PIN combiner including percent-encoding of reserved characters.
Changes in v5:
- Split theEntry_x509_certdocstring expansion into a separate preparatory commit (Simon)
- Unify URI support under the existing 'keyfile' entry argument rather than introducing a new 'x509-key-uri' arg; drop theEntry_x509_certstate and override logic that v4 added (Quentin)
- Percent-encode the PIN before appending to the URI usingurllib.parse.quote(), per RFC 7512, and add a unit test covering PINs with reserved characters (Simon)
- Detect the OpenSSL pkcs11 provider via
'openssl list -providers -provider pkcs11' rather than discovering the provider .so path manually; drops the 'openssl version -m' MODULESDIR lookup (Quentin)
- Drop the 'p11-kit print-config' / softhsm2 .so discovery from the test; the simpler openssl.cnf relies on softhsm2 being registered with p11-kit globally (Quentin). As a side effect this also fixes the test on Ubuntu 22.04, where 'p11-kit print-config' is not a valid subcommand
- Move the test openssl.cnf in-tree astools/binman/test/fit/openssl_provider.confand trim it to the minimum needed (no 'module = ', no 'pkcs11-module-path = ') (Quentin)
- Replace 'pkcs11-tool --keypairgen' with 'softhsm2-util --import' oftools/binman/test/fit/rsa2048.keyso the test runs faster and drops the pkcs11-tool dependency (Quentin)
- Recommend pkcs11-module-token-pin in openssl.cnf as the primary way to deliver the PIN;PKCS11_PINenv var is now documented as the convenience fallback (Quentin)
- Drop the incorrect claim thatPKCS11_PINkeeps the PIN out of shell history (Quentin)
- Rephrase the URI intro inbinman.rstand clarify that 'pkcs11-provider' is a Debian package name, not a path (Quentin)
- Drop the inheritance notes added toEntry_ti_secureandEntry_ti_secure_romin v4; with the v5 keyfile unification the original motivation (an inherited x509-key-uri property) no longer appliesChanges in v4:
- Drop the v3 bintoolextra_envcommit entirely; binman no longer sets any PKCS#11-related environment variables (Quentin)
- DropBINMAN_PKCS11_MODULE/ pkcs11-module entry argument; the PKCS#11 module path must be configured externally via openssl.cnf (Quentin)
- Drop provider/engine auto-detection (_pkcs11_use_provider,_build_key_args,_run_cmd_pkcs11) along with the threading.Lock; the user selects provider or engine viaOPENSSL_CONFand the URI form (Quentin)
- Rename the v3BINMAN_PKCS11_URI/ pkcs11-uri toBINMAN_X509_KEY_URI/ x509-key-uri to scope the names to x509 certificate entries without locking them to a specific URI scheme (Quentin)
- Document that the engine path is supported on OpenSSL 3.x by prefixing the URI with org.openssl.engine:<engine_name>: (Quentin)
- Replace the mocked openssl test with a real SoftHSM2-based integration test using the provider path andOPENSSL_CONF(Quentin)
- Use 'p11-kit print-config' to locate the softhsm2 library at test time instead of hardcoding a distro-specific path (Quentin)
- Use 'openssl version -m' (MODULESDIR) to locate the OpenSSL pkcs11 provider .so file, so multiarch paths like/usr/lib/x86_64-linux-gnu/ossl-moduleson Debian/Ubuntu are handled correctly
- Generate the test RSA keypair with pkcs11-tool; softhsm2-util has no key-generation action (only --import) and silently exits 0 on an unknown --generate-keypair option, which would leave the token empty and make the openssl step fail with 'Could not read private key'
- Addself._CheckBintool()to all PKCS#11 test paths so tests skip cleanly when bintools are missing (Quentin)
- Extract the URI/PIN combiner intoEntry_x509_cert._build_pkcs11_key()and add a unit test for it
- Document thatPKCS11_PINkeeps the PIN out of the make command line but is still visible in 'ps' output via the openssl invocation; for improved isolation, configure the PIN in openssl.cnf
- Document allEntry_x509_certproperties (content, keyfile, x509-key-uri, cert-ca, cert-revision-int, sw-rev) in its docstring (Quentin)
- Add inheritance notes toEntry_ti_secureandEntry_ti_secure_romdocstrings, pointing out that they extendEntry_x509_certviasuper()and therefore accept its properties (notably x509-key-uri) (Quentin)Changes in v3:
- Split into two patches: bintool infrastructure (1/2) andx509_certfeature (2/2)
- Fix global environment mutation:_run_cmd_pkcs11()no longer writes to os.environ directly; it now uses the newextra_envparameter so module paths are scoped to the subprocess only, which is both cleaner and safe under concurrent execution
- Add module-level threading.Lock to serialise concurrent PKCS#11 signing calls and fix intermittent login failures caused by binman's ThreadPoolExecutor
- Fix URI query string separator: use '&' when the URI already contains '?' (e.g. module-path already present), '?' otherwise
- Test cases updatedChanges in v2:
- Add tests for_build_key_args()(PEM path, PKCS#11 provider, PKCS#11 engine, PIN appending),_pkcs11_use_provider()(caching),_run_cmd_pkcs11()(with and without module path), and end-to-endx509_certsigning with a PKCS#11 URI (testX509CertPkcs11), ensuringbtool/openssl.pyandetype/x509_cert.pyhave 100% test coverageSergio Prado (2):
binman:x509_cert: documentEntry_x509_certproperties
binman:x509_cert: support PKCS#11 URI in keyfile for HSM signingMakefile | 1 + tools/binman/binman.rst | 55 ++++++++++++ tools/binman/etype/x509_cert.py | 45 ++++++++-- tools/binman/ftest.py | 92 +++++++++++++++++++++ tools/binman/test/fit/openssl_provider.conf | 14 ++++ 5 files changed, 202 insertions(+), 5 deletions(-) create mode 100644 tools/binman/test/fit/openssl_provider.conf--
2.34.1
Hi Sergio,
Quoted 4 lines · Sergio Prado
Hi Simon, Quentin,
Do you have any feedback on the v5 series?
I'm sorry, I'm currently drowning at work handling CVEs and I don't have time to allocate to review this for now. I am hopeful I will be able to carve out some time the week after next, this should be hopefully still in good timing for the 2026.10 merge window.
Thank you for your patience.
Cheers,
Quentin
Hi,
Quoted 9 lines · Quentin Schulz
Hi Sergio,
Quoted 4 lines · Sergio Prado
Hi Simon, Quentin,
Do you have any feedback on the v5 series?
Quoted 6 lines
I'm sorry, I'm currently drowning at work handling CVEs and I don't have time to allocate to review this for now. I am hopeful I will be able to carve out some time the week after next, this should be hopefully still in good timing for the 2026.10 merge window.
Thank you for your patience.
I am going to let Quentin handle the review on this one, as my feedback is already addressed.
Regards,
Simon