Skip to contentSkip to conversation

binman: Add HSM signing support to pre-load entry type

PATCH RESEND In review yan wang 2 participants 9 messages Nov 17 – Nov 19

lore
Share & tools
lore

yan wang

author
#0 lore raw

v3 cover binman: Add HSM signing support to pre-load entry type

The pre-load entry type currently only supports signing with a key file on disk. This series lets it sign through a Hardware Security Module (HSM) using PKCS#11, so that the private key never has to leave the token.

The pkcs11_tool bintool gains a sign() method which drives pkcs11-tool (RSA with PKCS#1 v1.5 or PSS, and ECDSA). The pre-load entry selects the HSM with a single hsm-key property holding a PKCS#11 URI (RFC 7512), as is done for FIT signing, e.g.:

   hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";

The PKCS#11 library and the PIN are not stored in the devicetree. They are passed with -a pre-load-hsm-library and -a pre-load-hsm-pin (the PIN may also come from PKCS11_SIGN_PIN). The library can also be given by the module-path attribute of the URI.

The PIN is forwarded to pkcs11-tool with '--pin env:BINMAN_PKCS11_PIN', which requires OpenSC 0.15.0 or later. A version check is added to the bintool and an informative error is raised if an older release is found.

The functional tests use SoftHSM.

Changes in v3:
- Swap the order of patches 2 and 3: HSM signing support (pre_load) now comes before the key-name/integer-size fix patch. The HSM patch already needs to touch ReadNode() for URI parsing, so grouping the key-name check there with the HSM validation (in the following patch) is cleaner
- Add opensc_version() and _check_opensc_version() to pkcs11_tool; refuse to sign with OpenSC older than 0.15.0 (the first release that accepts 'env:' for --pin); older versions would take 'env:BINMAN_PKCS11_PIN' literally as the PIN and silently fail or lock the token
- Make output_file a required argument of sign() so the caller controls the path; removes the temp-file management from inside the bintool
- When tools.get_env_with_path() returns None, fall back to os.environ so PATH is always inherited by the tool subprocess
- Add _BuildHeader(sign) to pre_load.py, a shared helper that takes a sign() closure; refactor _CreateHeaderRsa() and _CreateHeaderEcdsa() to use it, removing the duplicated struct.pack() and padding logic
- Pre-compute hsm_hash_name, hsm_sign_name, hsm_padding and hsm_sig_size in ReadNode() so _SignHsmData() does not re-parse algo_name on every call
- Use state.GetEntryArg() directly for pre-load-hsm-pin to prevent the PIN from being silently read from a DT property
- Remove the hsm-library DT property from __init__(); the library path is only set by the entry arg or the URI module-path= attribute
- Move the key-name check into the else branch of 'if self.hsm_key_uri:' in ReadNode() so it is validated early, consistently with HSM validation
- Extend the bintool unit tests: OpenSC version parsing and refusal, env handling in run_cmd_result(), PIN passed only through the environment, token serial lookup and resolution

yan wang (4):
binman: bintool: Add PKCS#11 HSM signing support
binman: pre_load: Add HSM signing support
binman: pre_load: Require key-name for file-based signing and fix integer division
binman: Add functional test for pre-load HSM signing

 tools/binman/bintool.py                       |  10 +-
 tools/binman/bintool_test.py                  | 650 ++++++++++++++++++
 tools/binman/btool/pkcs11_tool.py             | 379 +++++++++-
 tools/binman/etype/pre_load.py                | 323 +++++++--
 tools/binman/ftest.py                         | 268 ++++++++
 tools/binman/test/security/pre_load_hsm.dts   |  21 +
 .../test/security/pre_load_hsm_dt_pin.dts     |  22 +
 .../test/security/pre_load_hsm_ecdsa.dts      |  21 +
 .../security/pre_load_hsm_invalid_algo.dts    |  21 +
 .../security/pre_load_hsm_invalid_padding.dts |  22 +
 .../security/pre_load_hsm_invalid_sha.dts     |  21 +
 .../security/pre_load_hsm_invalid_uri.dts     |  21 +
 .../security/pre_load_hsm_module_path.dts     |  21 +
 .../test/security/pre_load_hsm_sign_pss.dts   |  22 +
 .../security/pre_load_missing_key_name.dts    |  20 +
 15 files changed, 1761 insertions(+), 81 deletions(-)
 create mode 100644 tools/binman/test/security/pre_load_hsm.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_dt_pin.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_ecdsa.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_invalid_algo.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_invalid_padding.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_invalid_sha.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_invalid_uri.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_module_path.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_sign_pss.dts
 create mode 100644 tools/binman/test/security/pre_load_missing_key_name.dts
Signature · 1 line
2.43.0
author
#1 lore raw

PATCH RESEND v3 1/4 binman: bintool: Add PKCS#11 HSM signing support

Implement signing through pkcs11-tool using the PKCS#11 interface, allowing binman to use private keys held by an HSM.

bintool.py:
- Add an env keyword argument to Bintool.run_cmd_result(). The given variables are merged into the environment of the tool. When tools.get_env_with_path() returns None, start from os.environ.

btool/pkcs11_tool.py:
- Add _build_mechanism() to map hash, signing algorithm and padding to a PKCS#11 mechanism name and rejects unknown hashes, unsupported algorithm families and names that cannot be parsed.
- Add _verify_mechanism() to check the mechanism against the token's list from --list-mechanisms, selecting the token by slot index or label. It is skipped with a log message if the tool is unavailable, exits non-zero or its output cannot be parsed.
- Add the public method find_slot_by_serial() to resolve an HSM token serial number to its slot index;
- Add sign(input_file, module, output_file, ...). output_file is a required argument, the path where pkcs11-tool writes the signature. sign() accepts token_label, token_serial, slot_index, key_label, key_id, pin, hash_algo, sign_algo and padding. It:
- requires a token identifier, a key identifier, a module path and a

    module that exists;
  - resolves token_serial to a slot index before verification;
  - falls back for ECDSA to hashing on the host and signing the digest
    with raw ECDSA when the token has no combined mechanism;

- requires a PIN. It passes --pin env:BINMAN_PKCS11_PIN with --login and sets BINMAN_PKCS11_PIN in the tool's environment, so the PIN is never on the command line;
- raises RuntimeError when the tool is missing, fails, or writes no signature.
- Add opensc_version() to read the OpenSC version from the 'Library' line of --show-info. It is a best-effort check.
- Add _check_opensc_version(), which refuses to sign with OpenSC older than 0.15.0, the first release that accepts 'env:' for --pin.

bintool_test.py:
- Import hashlib and add a _CmdResult namedtuple for mocking run_cmd_result().
- Add helpers _make_module_path(), _make_output_path() and _make_input_file().
- Add tests for mechanism building, mechanism verification, slot lookup by serial, sign() argument validation and failures, successful signing with slot index, key id and PIN, ECDSA with HSM and host hashing, the no-mechanism and no-PIN cases, OpenSC version parsing and refusal, PIN passed only via environment, env handling in run_cmd_result(), and token serial lookup and resolution.

---
Changes in v3:
- Make output_file a required argument of sign(). The caller now controls the path; the bintool no longer creates or removes a temporary output file, simplifying cleanup and letting the caller keep the file for debugging
- Add opensc_version() to parse the OpenSC version from the 'Library' line of --show-info. It is a best-effort check (returns None on any failure)
- Add _check_opensc_version() which refuses to sign with OpenSC older than 0.15.0, the first release that accepts 'env:' for --pin. Older versions take 'env:BINMAN_PKCS11_PIN' literally, silently fail or lock the token
- When tools.get_env_with_path() returns None, fall back to os.environ so that the subprocess always inherits a usable PATH
- Add tests for: OpenSC version parsing (valid and malformed strings), version refusal (< 0.15.0 raises ValueError), PIN passed only via the environment, env keyword argument in run_cmd_result(), and token serial lookup with resolution through find_slot_by_serial()

 tools/binman/bintool.py           |  10 +-
 tools/binman/bintool_test.py      | 650 ++++++++++++++++++++++++++++++
 tools/binman/btool/pkcs11_tool.py | 379 ++++++++++++++++-
 3 files changed, 1032 insertions(+), 7 deletions(-)
tools/binman/bintool.py +7 -3
index 4cf8d5b165b..afc19fe35d8 100644
@@ -273,7 +273,7 @@ class Bintool:
                 show_status(col.RED, 'Failures', status[FAIL])
         return not status[FAIL]
 
-    def run_cmd_result(self, *args, binary=False, raise_on_error=True):
+    def run_cmd_result(self, *args, binary=False, raise_on_error=True, env=None):
         """Run the bintool using command-line arguments
 
         Args:
@@ -282,6 +282,8 @@ class Bintool:
             binary (bool): True to return output as bytes instead of str
             raise_on_error (bool): True to raise a ValueError exception if the
                 tool returns a non-zero return code
+            env (dict or None): a dict of extra environment variables to set when
+            running the tool, or None for no additions
 
         Returns:
             CommandResult: Resulting output from the bintool, or None if the
@@ -291,10 +293,12 @@ class Bintool:
             return None
         name = os.path.expanduser(self.name)  # Expand paths containing ~
         all_args = (name,) + args
-        env = tools.get_env_with_path()
+        run_env = tools.get_env_with_path() or dict(os.environ)
+        if env:
+            run_env.update(env)
         tout.debug(f"bintool: {' '.join(all_args)}")
         result = command.run_pipe(
-            [all_args], capture=True, capture_stderr=True, env=env,
+            [all_args], capture=True, capture_stderr=True, env=run_env,
             raise_on_error=False, binary=binary)
 
         if result.return_code:
tools/binman/bintool_test.py +650 -0

674 lines not on this page · raw message

tools/binman/btool/pkcs11_tool.py +375 -4

398 lines not on this page · raw message

Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH v3 1/4 RESEND] binman: bintool: Add PKCS#11 HSM signing support

Quoted 37 lines

Implement signing through pkcs11-tool using the PKCS#11 interface, allowing binman to use private keys held by an HSM.

bintool.py:
- Add an env keyword argument to Bintool.run_cmd_result(). The given variables are merged into the environment of the tool. When tools.get_env_with_path() returns None, start from os.environ.

btool/pkcs11_tool.py:
- Add _build_mechanism() to map hash, signing algorithm and padding to a PKCS#11 mechanism name and rejects unknown hashes, unsupported algorithm families and names that cannot be parsed.
- Add _verify_mechanism() to check the mechanism against the token's list from --list-mechanisms, selecting the token by slot index or label. It is skipped with a log message if the tool is unavailable, exits non-zero or its output cannot be parsed.
- Add the public method find_slot_by_serial() to resolve an HSM token serial number to its slot index;
- Add sign(input_file, module, output_file, ...). output_file is a required argument, the path where pkcs11-tool writes the signature. sign() accepts token_label, token_serial, slot_index, key_label, key_id, pin, hash_algo, sign_algo and padding. It:
- requires a token identifier, a key identifier, a module path and a

    module that exists;
  - resolves token_serial to a slot index before verification;
  - falls back for ECDSA to hashing on the host and signing the digest
    with raw ECDSA when the token has no combined mechanism;

- requires a PIN. It passes --pin env:BINMAN_PKCS11_PIN with --login and sets BINMAN_PKCS11_PIN in the tool's environment, so the PIN is never on the command line;
- raises RuntimeError when the tool is missing, fails, or writes no signature.
- Add opensc_version() to read the OpenSC version from the 'Library' line of --show-info. It is a best-effort check.
- Add _check_opensc_version(), which refuses to sign with OpenSC older than 0.15.0, the first release that accepts 'env:' for --pin.

Quoted 11 lines

bintool_test.py:
- Import hashlib and add a _CmdResult namedtuple for mocking run_cmd_result().
- Add helpers _make_module_path(), _make_output_path() and _make_input_file().
- Add tests for mechanism building, mechanism verification, slot lookup by serial, sign() argument validation and failures, successful signing with slot index, key id and PIN, ECDSA with HSM and host hashing, the no-mechanism and no-PIN cases, OpenSC version parsing and refusal, PIN passed only via environment, env handling in run_cmd_result(), and token serial lookup and resolution.

This is a really long list of things done in a single patch. That is a sign that we are trying to do too much in a single patch. Can we please split this up in to smaller logical patches?

Quoted 20 lines

---
Changes in v3:
- Make output_file a required argument of sign(). The caller now controls the path; the bintool no longer creates or removes a temporary output file, simplifying cleanup and letting the caller keep the file for debugging
- Add opensc_version() to parse the OpenSC version from the 'Library' line of --show-info. It is a best-effort check (returns None on any failure)
- Add _check_opensc_version() which refuses to sign with OpenSC older than 0.15.0, the first release that accepts 'env:' for --pin. Older versions take 'env:BINMAN_PKCS11_PIN' literally, silently fail or lock the token
- When tools.get_env_with_path() returns None, fall back to os.environ so that the subprocess always inherits a usable PATH
- Add tests for: OpenSC version parsing (valid and malformed strings), version refusal (< 0.15.0 raises ValueError), PIN passed only via the environment, env keyword argument in run_cmd_result(), and token serial lookup with resolution through find_slot_by_serial()

Quoted 4 lines
 tools/binman/bintool.py           |  10 +-
 tools/binman/bintool_test.py      | 650 ++++++++++++++++++++++++++++++
 tools/binman/btool/pkcs11_tool.py | 379 ++++++++++++++++-
 3 files changed, 1032 insertions(+), 7 deletions(-)

And > 500 lines changed in one patch is really hard to review. This is twice that. So another reason to split this up.

Signature · 1 line
David Lechner <[email protected]>
author
#3 lore raw

PATCH RESEND v3 2/4 binman: pre_load: Add HSM signing support

In reply to yan wang

Signing the pre-load header currently needs the private key as a file on the build machine. Add support for signing through a hardware security module (HSM) over PKCS#11, so that the private key never has to leave the token. The signing is done by the pkcs11_tool bintool added earlier in this series.

The HSM is selected with a new hsm-key property holding a PKCS#11 URI (RFC 7512), in line with FIT signing, for example:

   hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";

The URI can identify the token with token=, serial= or slot-id= and the key with object= and/or id=. When hsm-key is present, it is used instead of key-name. Both RSA (PKCS#1 v1.5 or PSS) and ECDSA are supported.

Host-specific and secret values are kept out of the devicetree and are passed as entry arguments:

- pre-load-hsm-library: path to the PKCS#11 module (.so). If it is not given, the module-path= query attribute of the hsm-key URI is used;
- pre-load-hsm-pin: pin for the token. If it is not given, the PKCS11_SIGN_PIN environment variable is used. The pin is passed to pkcs11-tool as '--pin env:...', which requires OpenSC 0.15.0 or later.

For example:

  binman build ... \
        -a pre-load-hsm-library=/usr/lib/softhsm/libsofthsm2.so \
        -a pre-load-hsm-pin=<pin>

The HSM configuration is validated in ReadNode(): parse and validate hsm-key early, including the hash, the signing algorithm (RSA or ECDSA) and the padding scheme (pss or pkcs-1.5), and record the expected signature size.

Add _BuildHeader(sign) as a shared helper that calls a sign() closure twice — once for the image and once for the first header — and assembles the padded header.

Add _SignHsmData() to write data to a file, call pkcs11_tool.sign() with the pre-computed HSM parameters, verify the signature length, and record a missing bintool if pkcs11-tool is absent.

Update _CreateHeader() to dispatch to _SignHsmData() via _BuildHeader() when hsm-key is set, returning a dummy zero header if the tool is missing.

Refactor _CreateHeaderRsa() and _CreateHeaderEcdsa() to pass a sign() closure to _BuildHeader(). The RSA PSS salt length is calculated from the hash digest size. The behaviour is unchanged.

---
Changes in v3:
- Move to position 2/4 (was 3/4 in v2); the HSM signing support now comes before the key-name/integer-size fix so that the key-name check can be added in the next patch to the else branch of 'if self.hsm_key_uri:' in ReadNode(), together with the integer-division fixes
- Add _BuildHeader(sign): a shared helper that takes a sign() closure, calls it for the image and then for the first header, and builds the padded header bytes. Refactor _CreateHeaderRsa() and _CreateHeaderEcdsa() to pass a sign() closure to _BuildHeader() instead of duplicating the struct.pack() and padding code in each function
- Pre-compute self.hsm_hash_name, self.hsm_sign_name, self.hsm_padding and self.hsm_sig_size in ReadNode() so _SignHsmData() reads them directly and does not re-parse algo_name and padding_name on every ProcessContents() call
- Use state.GetEntryArg('pre-load-hsm-pin') directly instead of GetEntryArgsOrProps(), to prevent the PIN from being silently read from a 'pre-load-hsm-pin' DT property
- Remove the hsm-library DT property read from __init__(); self.hsm_library is now initialised to None and set only by the entry arg or the URI module-path= attribute in ReadNode()
- Pass output_file explicitly to pkcs11_tool.sign() now that it is a required argument; use a well-known name in the output directory so the signature file is available for post-mortem inspection
- Remove the key-name check added in v2 patch 0002; it is placed in the following patch where it sits naturally in the else branch of 'if self.hsm_key_uri:' in ReadNode()

 tools/binman/etype/pre_load.py | 308 +++++++++++++++++++++++++--------
 1 file changed, 240 insertions(+), 68 deletions(-)
tools/binman/etype/pre_load.py +240 -68
index 7890c1c62a8..f264146d62f 100644
@@ -7,9 +7,11 @@
 
 import os
 import struct
+from urllib.parse import unquote
 from dtoc import fdt_util
 from u_boot_pylib import tools
 
+from binman import state
 from binman.entry import Entry
 from binman.etype.collection import Entry_collection
 from binman.entry import EntryArg
@@ -21,6 +23,34 @@ from Cryptodome.Signature import pkcs1_15
 from Cryptodome.Signature import pss
 from Cryptodome.Signature import DSS
 
+def _parse_pkcs11_uri(uri):
+    """Parse a PKCS#11 URI (RFC 7512) into a dict of path and query attributes.
+
+    Path attributes (e.g. token=, object=, serial=, slot-id=) are separated by
+    semicolons. Query attributes (e.g. module-path=) follow '?' and are
+    separated by ampersands.
+
+    Args:
+        uri (str): PKCS#11 URI string starting with 'pkcs11:'
+
+    Returns:
+        dict: Mapping of attribute name to percent-decoded value
+
+    Raises:
+        ValueError: If the string does not start with 'pkcs11:'
+    """
+    if not uri.startswith('pkcs11:'):
+        raise ValueError(f'Not a PKCS#11 URI: {uri!r}')
+    rest = uri[7:]
+    path_part, _, query_part = rest.partition('?')
+    attrs = {}
+    for part in (path_part.split(';') + (query_part.split('&') if query_part else [])):
+        if '=' in part:
+            k, v = part.split('=', 1)
+            attrs[k.strip()] = unquote(v.strip())
+    return attrs
+
+
 PRE_LOAD_MAGIC = b'UBSH'
 
 RSAS = {
@@ -53,9 +83,38 @@ class Entry_pre_load(Entry_collection):
         - key-name: Filename of the private key to sign
         - header-size: Total size of the header
         - version: Version of the header
-
-    This entry creates a pre-load header that contains a global
-    image signature.
+        - pre-load-hsm-library: Path to the PKCS#11 module (.so). This is a
+          host-specific detail that varies by distribution and should not be
+          committed to the board DTS. Pass it at build time with
+          -a pre-load-hsm-library=... . It may also be embedded in the
+          hsm-key URI as the module-path= query attribute.
+        - pre-load-hsm-pin: PIN/passphrase to unlock the PKCS#11 token. Must
+          NOT be stored in the DT. May also be read from the PKCS11_SIGN_PIN
+          environment variable, mirroring how mkimage reads MKIMAGE_SIGN_PIN
+          for FIT signing. The PIN is handed to pkcs11-tool through an
+          environment variable ('--pin env:...'), which requires OpenSC 0.15.0
+          or later. Older versions take 'env:...' literally as the PIN, so each
+          build counts as a failed login and can lock the token.
+
+    HSM Signing Properties (optional):
+        When hsm-key is present, signing is done via a PKCS#11 token instead
+        of a key file, following the same convention as FIT signing.
+
+        - hsm-key: PKCS#11 URI (RFC 7512) identifying the token and private
+          key. Supported path attributes: token=, serial=, slot-id=, object=,
+          id=. The module-path= query attribute may embed the library path in
+          the URI as an alternative to the pre-load-hsm-library entry arg.
+          Examples::
+
+              hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";
+              hsm-key = "pkcs11:serial=abc123;object=uboot-key";
+              hsm-key = "pkcs11:slot-id=0;object=uboot-key";
+
+    This entry creates a pre-load header that contains a global image
+    signature. The signature can be created using either a traditional
+    key file (key-name) or a Hardware Security Module (HSM) via PKCS#11
+    (hsm-key), enabling production keys to remain on the HSM and never touch
+    the build machine's filesystem.
 
     For example, this creates an image with a pre-load header and a binary::
 
@@ -77,6 +136,28 @@ class Entry_pre_load(Entry_collection):
                 };
             };
         };
+
+    Example with HSM signing::
+
+        binman {
+            pre-load {
+                content = <&image>;
+                algo-name = "sha256,rsa2048";
+                padding-name = "pss";
+                header-size = <4096>;
+                version = <1>;
+                hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";
+            };
+
+            image: blob-ext {
+                filename = "sandbox.itb";
+            };
+        };
+
+    Invoke binman with::
+
+        binman ... -a pre-load-hsm-library=/usr/lib/softhsm/libsofthsm2.so \
+                   -a pre-load-hsm-pin=<pin>
     """
 
     def __init__(self, section, etype, node):
@@ -87,6 +168,22 @@ class Entry_pre_load(Entry_collection):
         self.header_size = fdt_util.GetInt(self._node, 'header-size')
         self.version = fdt_util.GetInt(self._node, 'version')
 
+        # HSM properties (optional); populated from hsm-key URI in ReadNode()
+        self.hsm_key_uri = fdt_util.GetString(self._node, 'hsm-key')
+        self.hsm_library = None
+        self.hsm_token_label = None
+        self.hsm_token_serial = None
+        self.hsm_slot_index = None
+        self.hsm_key_label = None
+        self.hsm_key_id = None
+        self.hsm_pin = None
+        self.hsm_hash_name = None
+        self.hsm_sign_name = None
+        self.hsm_padding = None
+        self.hsm_sig_size = None
+
+        self.pkcs11_tool = None
+
     def ReadNode(self):
         super().ReadNode()
         self.key_path, = self.GetEntryArgsOrProps(
@@ -94,6 +191,91 @@ class Entry_pre_load(Entry_collection):
         if self.key_path is None:
             self.key_path = ''
 
+        # The PKCS#11 library may be supplied as an entry arg so the
+        # host-specific library path is not committed to the board DTS.
+        hsm_lib_arg, = self.GetEntryArgsOrProps(
+            [EntryArg('pre-load-hsm-library', str)])
+        if hsm_lib_arg:
+            self.hsm_library = hsm_lib_arg
+
+        # PIN from entry arg or environment variable, NOT from the DT. Use
+        # state.GetEntryArg() directly, since GetEntryArgsOrProps() would fall
+        # back to reading a 'pre-load-hsm-pin' property from the node.
+        pin_arg = state.GetEntryArg('pre-load-hsm-pin')
+        self.hsm_pin = pin_arg or os.environ.get('PKCS11_SIGN_PIN')
+
+        # Validate HSM config early, before any tool is loaded, so a bad DT
+        # fails immediately regardless of whether pkcs11-tool is installed.
+        if self.hsm_key_uri:
+            try:
+                uri_attrs = _parse_pkcs11_uri(self.hsm_key_uri)
+            except ValueError as e:
+                self.Raise(str(e))
+            self.hsm_token_label = uri_attrs.get('token')
+            self.hsm_token_serial = uri_attrs.get('serial')
+            self.hsm_slot_index = uri_attrs.get('slot-id')
+            self.hsm_key_label = uri_attrs.get('object')
+            self.hsm_key_id = uri_attrs.get('id')
+            # module-path query attribute may carry the library path; the
+            # pre-load-hsm-library entry arg (already applied above) takes
+            # priority since it is more explicit.
+            if 'module-path' in uri_attrs and not self.hsm_library:
+                self.hsm_library = uri_attrs['module-path']
+
+            # Work out the signing parameters once, for _SignHsmData()
+            hash_name, sign_name = self.algo_name.split(',')
+            if hash_name not in SHAS:
+                self.Raise(f'{hash_name} is not supported')
+            if sign_name in RSAS:
+                self.hsm_sig_size = RSAS[sign_name]
+            elif sign_name in ECDSAS:
+                self.hsm_sig_size = ECDSAS[sign_name]
+            else:
+                self.Raise(f'{sign_name} is not supported')
+            padding_name = self.padding_name or 'pkcs-1.5'
+            padding = {'pss': 'pss', 'pkcs-1.5': 'pkcs1v15'}.get(padding_name)
+            if padding is None:
+                self.Raise(f'Unsupported padding scheme: {padding_name}')
+            self.hsm_hash_name = hash_name
+            self.hsm_sign_name = sign_name
+            self.hsm_padding = padding
+
+    def AddBintools(self, btools):
+        """Register pkcs11-tool if HSM signing is requested"""
+        super().AddBintools(btools)
+        if self.hsm_key_uri:
+            self.pkcs11_tool = self.AddBintool(btools, 'pkcs11_tool')
+
+    def _BuildHeader(self, sign):
+        """Build the pre-load header, signing with the given function
+
+        Args:
+            sign (function): Takes the bytes to sign and returns the signature
+                (bytes), or None if signing is not possible (e.g. a missing
+                tool). Only the first call is checked, since a tool cannot go
+                missing between the two calls
+
+        Returns:
+            bytes: Header padded to header-size, or None if signing failed
+        """
+        img_sig = sign(self.image)
+        if img_sig is None:
+            return None
+        hash_sig = SHA256.new(img_sig)
+
+        flags = 0
+        reserved0 = 0
+        reserved1 = 0
+        first_header = struct.pack('>4sIIIIIII32s', PRE_LOAD_MAGIC,
+                                   self.version, self.header_size,
+                                   len(self.image), 64 + len(img_sig), flags,
+                                   reserved0, reserved1, hash_sig.digest())
+
+        hdr_sig = sign(first_header)
+
+        data = first_header + hdr_sig + img_sig
+        return data + bytearray(self.header_size - len(data))
+
     def _CreateHeaderRsa(self, hash_name, sign_name, padding_name, key_name):
         # Check hash and signature name/type
         if hash_name not in SHAS:
@@ -106,51 +288,24 @@ class Entry_pre_load(Entry_collection):
         if key.size_in_bytes() != RSAS[sign_name]:
             self.Raise("The key " + self.key_name + " doesn't have the expected size")
 
-        # Compute the hash
-        hash_image = SHAS[hash_name].new()
-        hash_image.update(self.image)
-
-        # Compute the signature
         if padding_name is None:
             padding_name = "pkcs-1.5"
         padding = None
-        padding_args = None
+        padding_args = {}
         if padding_name == "pss":
-            salt_len = key.size_in_bytes() - hash_image.digest_size - 2
+            digest_size = SHAS[hash_name].new().digest_size
             padding = pss
-            padding_args = {'salt_bytes': salt_len}
+            padding_args = {'salt_bytes': key.size_in_bytes() - digest_size - 2}
         elif padding_name == "pkcs-1.5":
             padding = pkcs1_15
-            padding_args = {}
         else:
             self.Raise(padding_name + " is not supported")
 
-        sig = padding.new(key, **padding_args).sign(hash_image)
-
-        hash_sig = SHA256.new()
-        hash_sig.update(sig)
-
-        version = self.version
-        header_size = self.header_size
-        image_size = len(self.image)
-        ofs_img_sig = 64 + len(sig)
-        flags = 0
-        reserved0 = 0
-        reserved1 = 0
-
-        first_header = struct.pack('>4sIIIIIII32s', PRE_LOAD_MAGIC,
-                                   version, header_size, image_size,
-                                   ofs_img_sig, flags, reserved0,
-                                   reserved1, hash_sig.digest())
-
-        hash_first_header = SHAS[hash_name].new()
-        hash_first_header.update(first_header)
-        sig_first_header = padding.new(key, **padding_args).sign(hash_first_header)
+        def sign(data):
+            hash_data = SHAS[hash_name].new(data)
+            return padding.new(key, **padding_args).sign(hash_data)
 
-        data = first_header + sig_first_header + sig
-        pad  = bytearray(self.header_size - len(data))
-
-        return data + pad
+        return self._BuildHeader(sign)
 
     def _CreateHeaderEcdsa(self, hash_name, sign_name, key_name):
         # Check hash and signature name/type
@@ -164,41 +319,58 @@ class Entry_pre_load(Entry_collection):
         if key.pointQ.size_in_bytes() * 2 != ECDSAS[sign_name]:
             self.Raise("The key " + self.key_name + " doesn't have the expected size")
 
-        # Compute the hash
-        hash_image = SHAS[hash_name].new()
-        hash_image.update(self.image)
-
-        # Compute the signature
         signer = DSS.new(key, 'fips-186-3')
-        sig = signer.sign(hash_image)
-
-        hash_sig = SHA256.new()
-        hash_sig.update(sig)
-
-        version = self.version
-        header_size = self.header_size
-        image_size = len(self.image)
-        ofs_img_sig = 64 + len(sig)
-        flags = 0
-        reserved0 = 0
-        reserved1 = 0
-
-        first_header = struct.pack('>4sIIIIIII32s', PRE_LOAD_MAGIC,
-                                   version, header_size, image_size,
-                                   ofs_img_sig, flags, reserved0,
-                                   reserved1, hash_sig.digest())
-
-        hash_first_header = SHAS[hash_name].new()
-        hash_first_header.update(first_header)
-        sig_first_header = signer.sign(hash_first_header)
-
-        data = first_header + sig_first_header + sig
-        pad  = bytearray(self.header_size - len(data))
 
-        return data + pad
+        def sign(data):
+            return signer.sign(SHAS[hash_name].new(data))
+
+        return self._BuildHeader(sign)
+
+    def _SignHsmData(self, data):
+        """Sign data with the configured HSM via PKCS#11."""
+        if not self.pkcs11_tool.is_present():
+            self.record_missing_bintool(self.pkcs11_tool)
+            return None
+
+        input_fname = tools.get_output_filename(
+            f'{self.GetUniqueName()}_hsm_input.bin')
+        tools.write_file(input_fname, data)
+        output_fname = tools.get_output_filename(
+            f'{self.GetUniqueName()}_hsm_output.sig')
+
+        try:
+            signature = self.pkcs11_tool.sign(
+                input_file=input_fname,
+                output_file=output_fname,
+                module=self.hsm_library,
+                token_label=self.hsm_token_label,
+                token_serial=self.hsm_token_serial,
+                slot_index=self.hsm_slot_index,
+                key_label=self.hsm_key_label,
+                key_id=self.hsm_key_id,
+                pin=self.hsm_pin,
+                hash_algo=self.hsm_hash_name,
+                sign_algo=self.hsm_sign_name,
+                padding=self.hsm_padding)
+        except (ValueError, RuntimeError) as e:
+            self.Raise(f'HSM signing failed: {e}')
+
+        if len(signature) != self.hsm_sig_size:
+            self.Raise(
+                f'HSM returned {len(signature)}-byte signature but '
+                f'{self.hsm_sign_name} requires {self.hsm_sig_size} bytes')
+        return signature
 
     def _CreateHeader(self):
-        """Create a pre load header"""
+        """Create a pre-load header"""
+        if self.hsm_key_uri:
+            data = self._BuildHeader(self._SignHsmData)
+            if data is None:
+                # pkcs11-tool is missing; return a dummy header
+                return tools.get_bytes(0, self.header_size)
+            return data
+
+        # File-based path: dispatch on signing algorithm
         hash_name, sign_name = self.algo_name.split(',')
         padding_name = self.padding_name
         key_name = os.path.join(self.key_path, self.key_name)
Signature · 1 line
2.43.0
#4 lore raw

Re: [PATCH v3 2/4 RESEND] binman: pre_load: Add HSM signing support

Quoted 44 lines

Signing the pre-load header currently needs the private key as a file on the build machine. Add support for signing through a hardware security module (HSM) over PKCS#11, so that the private key never has to leave the token. The signing is done by the pkcs11_tool bintool added earlier in this series.

The HSM is selected with a new hsm-key property holding a PKCS#11 URI (RFC 7512), in line with FIT signing, for example:

   hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";

The URI can identify the token with token=, serial= or slot-id= and the key with object= and/or id=. When hsm-key is present, it is used instead of key-name. Both RSA (PKCS#1 v1.5 or PSS) and ECDSA are supported.

Host-specific and secret values are kept out of the devicetree and are passed as entry arguments:

- pre-load-hsm-library: path to the PKCS#11 module (.so). If it is not given, the module-path= query attribute of the hsm-key URI is used;
- pre-load-hsm-pin: pin for the token. If it is not given, the PKCS11_SIGN_PIN environment variable is used. The pin is passed to pkcs11-tool as '--pin env:...', which requires OpenSC 0.15.0 or later.

For example:

  binman build ... \
        -a pre-load-hsm-library=/usr/lib/softhsm/libsofthsm2.so \
        -a pre-load-hsm-pin=<pin>

The HSM configuration is validated in ReadNode(): parse and validate hsm-key early, including the hash, the signing algorithm (RSA or ECDSA) and the padding scheme (pss or pkcs-1.5), and record the expected signature size.

Add _BuildHeader(sign) as a shared helper that calls a sign() closure twice — once for the image and once for the first header — and assembles the padded header.

Add _SignHsmData() to write data to a file, call pkcs11_tool.sign() with the pre-computed HSM parameters, verify the signature length, and record a missing bintool if pkcs11-tool is absent.

Quoted 7 lines

Update _CreateHeader() to dispatch to _SignHsmData() via _BuildHeader() when hsm-key is set, returning a dummy zero header if the tool is missing.

Refactor _CreateHeaderRsa() and _CreateHeaderEcdsa() to pass a sign() closure to _BuildHeader(). The RSA PSS salt length is calculated from the hash digest size. The behaviour is unchanged.

If I understand correctly, the previous review asked for adding _BuildHeader() and doing the refactor as a "no functional change" separate patch. That seems reasonable to me to not mix it up with the HSM stuff this patch is actually about.

Quoted 15 lines
tools/binman/etype/pre_load.py +11 -0
@@ -77,6 +136,28 @@ class Entry_pre_load(Entry_collection):
                 };
             };
         };
+
+    Example with HSM signing::
+
+        binman {
+            pre-load {
+                content = <&image>;
+                algo-name = "sha256,rsa2048";
+                padding-name = "pss";
+                header-size = <4096>;
+                version = <1>;
+                hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";

tools/binman/etype/pre_load.py class Entry_pre_load(Entry_collection): · line 159

Quoted 10 lines
tools/binman/etype/pre_load.py +10 -0
+            };
+
+            image: blob-ext {
+                filename = "sandbox.itb";
+            };
+        };
+
+    Invoke binman with::
+
+        binman ... -a pre-load-hsm-library=/usr/lib/softhsm/libsofthsm2.so \

Need to escape \ here or make the doc comment a raw string.

Quoted 28 lines
tools/binman/etype/pre_load.py +17 -0
+                   -a pre-load-hsm-pin=<pin>
     """
 
     def __init__(self, section, etype, node):
@@ -87,6 +168,22 @@ class Entry_pre_load(Entry_collection):
         self.header_size = fdt_util.GetInt(self._node, 'header-size')
         self.version = fdt_util.GetInt(self._node, 'version')
 
+        # HSM properties (optional); populated from hsm-key URI in ReadNode()
+        self.hsm_key_uri = fdt_util.GetString(self._node, 'hsm-key')
+        self.hsm_library = None
+        self.hsm_token_label = None
+        self.hsm_token_serial = None
+        self.hsm_slot_index = None
+        self.hsm_key_label = None
+        self.hsm_key_id = None
+        self.hsm_pin = None
+        self.hsm_hash_name = None
+        self.hsm_sign_name = None
+        self.hsm_padding = None
+        self.hsm_sig_size = None
+
+        self.pkcs11_tool = None
+
     def ReadNode(self):
         super().ReadNode()
         self.key_path, = self.GetEntryArgsOrProps(

tools/binman/etype/pre_load.py class Entry_pre_load(Entry_collection): · line 197

Quoted 7 lines
tools/binman/etype/pre_load.py +4 -0
@@ -94,6 +191,91 @@ class Entry_pre_load(Entry_collection):
         if self.key_path is None:
             self.key_path = ''
 
+        # The PKCS#11 library may be supplied as an entry arg so the
+        # host-specific library path is not committed to the board DTS.
+        hsm_lib_arg, = self.GetEntryArgsOrProps(
+            [EntryArg('pre-load-hsm-library', str)])

The documentation says that pre-load-hsm-library should not be in the devicetree but this still uses GetEntryArgsOrProps() which would allow it.

Quoted 9 lines
tools/binman/etype/pre_load.py +9 -0
+        if hsm_lib_arg:
+            self.hsm_library = hsm_lib_arg
+
+        # PIN from entry arg or environment variable, NOT from the DT. Use
+        # state.GetEntryArg() directly, since GetEntryArgsOrProps() would fall
+        # back to reading a 'pre-load-hsm-pin' property from the node.
+        pin_arg = state.GetEntryArg('pre-load-hsm-pin')
+        self.hsm_pin = pin_arg or os.environ.get('PKCS11_SIGN_PIN')
+

tools/binman/etype/pre_load.py class Entry_pre_load(Entry_collection): · line 216

Quoted 10 lines
tools/binman/etype/pre_load.py +10 -0
+        # Validate HSM config early, before any tool is loaded, so a bad DT
+        # fails immediately regardless of whether pkcs11-tool is installed.
+        if self.hsm_key_uri:
+            try:
+                uri_attrs = _parse_pkcs11_uri(self.hsm_key_uri)
+            except ValueError as e:
+                self.Raise(str(e))
+            self.hsm_token_label = uri_attrs.get('token')
+            self.hsm_token_serial = uri_attrs.get('serial')
+            self.hsm_slot_index = uri_attrs.get('slot-id')

RFC 7512 slot-id is the decimal CK_SLOT_ID, not the slot index. pkcs11-tool takes the ID with --slot and the index with --slot-index. With SoftHSM, slot IDs look like 598648507, so a valid "slot-id=598648507" fails here and "slot-id=0" picks the first slot. Please pass it through as a slot ID and use --slot.

https://www.rfc-editor.org/rfc/rfc7512#section-2.3

tools/binman/etype/pre_load.py class Entry_pre_load(Entry_collection): · line 218

Quoted 2 lines
tools/binman/etype/pre_load.py +2 -0
+            self.hsm_key_label = uri_attrs.get('object')
+            self.hsm_key_id = uri_attrs.get('id')

RFC 7512 id is the CKA_ID as percent-encoded bytes (e.g. id=%01%02). unquote() turns that into the str '\x01\x02', but pkcs11-tool --id expects hex ("0102"). Something like urllib.parse.unquote_to_bytes(v).hex() is needed.

Signature · 1 line
David Lechner <[email protected]>
author
#5 lore raw

PATCH RESEND v3 3/4 binman: pre_load: Require key-name for file-based signing and fix integer division

In reply to yan wang

Without a key-name property, os.path.join() is called with None and binman fails with a TypeError traceback rather than a useful message. Report a clear error instead when file-based signing is used without key-name.

Use integer division for the RSA and ECDSA signature sizes. Using // gives an int result as semantically expected for byte-count tables.

---
Changes in v3:
- Move to position 3/4 (was 2/4 in v2), after the HSM signing patch
- Place the key-name check in the else branch of 'if self.hsm_key_uri:' in ReadNode() instead of at the top of _CreateHeader(). This is both earlier (validation happens at node-read time, before any signing) and
clearer: the else branch makes explicit that the check only applies to the file-based path

 tools/binman/etype/pre_load.py                | 15 ++++++++------
 tools/binman/ftest.py                         | 11 ++++++++++
 .../security/pre_load_missing_key_name.dts    | 20 +++++++++++++++++++
 3 files changed, 40 insertions(+), 6 deletions(-)
 create mode 100644 tools/binman/test/security/pre_load_missing_key_name.dts
tools/binman/etype/pre_load.py +9 -6
index f264146d62f..32aa10bc057 100644
@@ -54,15 +54,15 @@ def _parse_pkcs11_uri(uri):
 PRE_LOAD_MAGIC = b'UBSH'
 
 RSAS = {
-    'rsa1024': 1024 / 8,
-    'rsa2048': 2048 / 8,
-    'rsa4096': 4096 / 8
+    'rsa1024': 1024 // 8,
+    'rsa2048': 2048 // 8,
+    'rsa4096': 4096 // 8
 }
 
 ECDSAS = {
-    'ecdsa256': 256 / 8 * 2,
-    'ecdsa384': 384 / 8 * 2,
-    'ecdsa521': (521 + 7) / 8 * 2
+    'ecdsa256': 256 // 8 * 2,
+    'ecdsa384': 384 // 8 * 2,
+    'ecdsa521': (521 + 7) // 8 * 2
 }
 
 SHAS = {
@@ -239,6 +239,9 @@ class Entry_pre_load(Entry_collection):
             self.hsm_hash_name = hash_name
             self.hsm_sign_name = sign_name
             self.hsm_padding = padding
+        else:
+            if not self.key_name:
+                self.Raise('key-name is required for file-based signing')
 
     def AddBintools(self, btools):
         """Register pkcs11-tool if HSM signing is requested"""
tools/binman/ftest.py +11 -0
index 8caf275d466..d4522e905e0 100644
@@ -5981,6 +5981,17 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
         self.assertIn("Node '/binman/pre-load': The key ecdsa521.pem doesn't have the expected size",
                       str(exc.exception))
 
+    def testPreLoadMissingKeyName(self):
+        """Test file-based signing with missing key-name property"""
+        entry_args = {
+            'pre-load-key-path': os.path.join(self._binman_dir, 'test'),
+        }
+        with self.assertRaises(ValueError) as exc:
+            self._DoReadFileDtb('security/pre_load_missing_key_name.dts',
+                                entry_args=entry_args)
+        self.assertIn('key-name is required for file-based signing',
+                      str(exc.exception))
+
     def _CheckSafeUniqueNames(self, *images):
         """Check all entries of given images for unsafe unique names"""
         for image in images:
tools/binman/test/security/pre_load_missing_key_name.dts new file +20 -0
new file mode 100644
index 00000000000..262219fb6ab
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		pre-load {
+			content = <&image>;
+			algo-name = "sha256,rsa2048";
+			header-size = <4096>;
+			version = <0x11223344>;
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
Signature · 1 line
2.43.0
#6 lore raw

Re: [PATCH v3 3/4 RESEND] binman: pre_load: Require key-name for file-based signing and fix integer division

Quoted 7 lines

Without a key-name property, os.path.join() is called with None and binman fails with a TypeError traceback rather than a useful message. Report a clear error instead when file-based signing is used without key-name.

Use integer division for the RSA and ECDSA signature sizes. Using // gives an int result as semantically expected for byte-count tables.

This also looks like two separate changes in one patch that should be split.

And since patch 2 depends on the // change, this should come first in the series, not last.

Quoted 81 lines

---
Changes in v3:
- Move to position 3/4 (was 2/4 in v2), after the HSM signing patch
- Place the key-name check in the else branch of 'if self.hsm_key_uri:' in ReadNode() instead of at the top of _CreateHeader(). This is both earlier (validation happens at node-read time, before any signing) and
clearer: the else branch makes explicit that the check only applies to the file-based path

 tools/binman/etype/pre_load.py                | 15 ++++++++------
 tools/binman/ftest.py                         | 11 ++++++++++
 .../security/pre_load_missing_key_name.dts    | 20 +++++++++++++++++++
 3 files changed, 40 insertions(+), 6 deletions(-)
 create mode 100644 tools/binman/test/security/pre_load_missing_key_name.dts
tools/binman/etype/pre_load.py +9 -6
index c550de1efc7..1bcf48dfb36 100644
@@ -54,15 +54,15 @@ def _parse_pkcs11_uri(uri):
 PRE_LOAD_MAGIC = b'UBSH'
 
 RSAS = {
-    'rsa1024': 1024 / 8,
-    'rsa2048': 2048 / 8,
-    'rsa4096': 4096 / 8
+    'rsa1024': 1024 // 8,
+    'rsa2048': 2048 // 8,
+    'rsa4096': 4096 // 8
 }
 
 ECDSAS = {
-    'ecdsa256': 256 / 8 * 2,
-    'ecdsa384': 384 / 8 * 2,
-    'ecdsa521': (521 + 7) / 8 * 2
+    'ecdsa256': 256 // 8 * 2,
+    'ecdsa384': 384 // 8 * 2,
+    'ecdsa521': (521 + 7) // 8 * 2
 }
 
 SHAS = {
@@ -239,6 +239,9 @@ class Entry_pre_load(Entry_collection):
             self.hsm_hash_name = hash_name
             self.hsm_sign_name = sign_name
             self.hsm_padding = padding
+        else:
+            if not self.key_name:
+                self.Raise('key-name is required for file-based signing')
 
     def AddBintools(self, btools):
         """Register pkcs11-tool if HSM signing is requested"""
tools/binman/ftest.py +11 -0
index 8caf275d466..d4522e905e0 100644
@@ -5981,6 +5981,17 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
         self.assertIn("Node '/binman/pre-load': The key ecdsa521.pem doesn't have the expected size",
                       str(exc.exception))
 
+    def testPreLoadMissingKeyName(self):
+        """Test file-based signing with missing key-name property"""
+        entry_args = {
+            'pre-load-key-path': os.path.join(self._binman_dir, 'test'),
+        }
+        with self.assertRaises(ValueError) as exc:
+            self._DoReadFileDtb('security/pre_load_missing_key_name.dts',
+                                entry_args=entry_args)
+        self.assertIn('key-name is required for file-based signing',
+                      str(exc.exception))
+
     def _CheckSafeUniqueNames(self, *images):
         """Check all entries of given images for unsafe unique names"""
         for image in images:
tools/binman/test/security/pre_load_missing_key_name.dts new file +0 -0
new file mode 100644
index 00000000000..262219fb6ab

tools/binman/test/security/pre_load_missing_key_name.dts line 1

Quoted 1 line
tools/binman/test/security/pre_load_missing_key_name.dts new file +1 -0
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: GPL-2.0+

nit: GPL-2.0+ form is deprecated use GPL-2.0-or-later instead.

Signature · 1 line
David Lechner <[email protected]>
author
#7 lore raw

PATCH RESEND v3 4/4 binman: Add functional test for pre-load HSM signing

In reply to yan wang

Add end-to-end functional test for HSM-based signing of pre-load headers. The test verifies that binman can use PKCS#11 libraries to sign data via hardware security modules and can generate pre-load headers with HSM signatures.

The tests create a SoftHSM v2 token, generate RSA and ECDSA key pairs on it with pkcs11-tool, and verify the resulting pre-load header signatures. RSA signatures are checked with preload_check_sign; ECDSA signatures are checked with Cryptodome because preload_check_sign needs the private key.

- Add _MakePreLoadHsmToken() to set up the SoftHSM configuration from fit/softhsm2.conf, locate the library through p11-kit, initialise the token, generate a key pair and export the public key in DER format.
- Add testPreLoadHsmSign, which generates an RSA-2048 key pair and checks the header, for both pkcs-1.5 and PSS padding, with preload_check_sign using the public key exported from the token
- Add testPreLoadHsmEcdsaSign, which generates an ECDSA key pair and verifies the signatures with Cryptodome, since preload_check_sign needs the private key for ECDSA, which an HSM never exposes
- Add testPreLoadHsmModulePath to check that module-path= in the URI sets the library.
- Add _GetPreLoadHsmPins() to collect the PIN passed to each sign() call.
- Add PIN tests that check the PIN source order: the pin entry arg, the environment variable, the entry arg taking precedence over the environment variable, no PIN at all, and a PIN in the device tree being ignored.
- Add testPreLoadHsmBadSignatureLength to check that a signature of the wrong length is rejected.

Error-path tests, which do not need SoftHSM, cover an invalid padding scheme, an unsupported hash, an unsupported signature algorithm, an invalid PKCS#11 URI, a missing pkcs11-tool and a signing failure reported by pkcs11-tool.

---
Changes in v3:
- Extract _MakePreLoadHsmToken() helper (SoftHSM setup, key generation and public-key export) from testPreLoadHsmSign and testPreLoadHsmEcdsaSign, removing the duplicated token-setup code
- testPreLoadHsmSign now uses pre_load_hsm.dts (the shared DTS that was also used by the error-path tests) instead of a dedicated pre_load_hsm_sign.dts; drop pre_load_hsm_sign.dts
- Move the SOFTHSM2_CONF environment mock to wrap only the signing part of testPreLoadHsmSign, not the token setup, which already patches the env inside _MakePreLoadHsmToken()
- Add _GetPreLoadHsmPins() helper: patches is_present() and sign() and returns the list of PIN values received across both sign() calls
- Add five PIN-source tests:
- testPreLoadHsmPinEntryArg: pre-load-hsm-pin entry arg reaches sign()
- testPreLoadHsmPinEnvVar: PKCS11_SIGN_PIN is used when there is no arg
- testPreLoadHsmPinEntryArgWins: entry arg overrides PKCS11_SIGN_PIN
- testPreLoadHsmNoPin: None is passed when no PIN is configured
- testPreLoadHsmPinInDtIgnored: a 'pre-load-hsm-pin' DT property is never read; the entry arg and env variable still take effect
- Add pre_load_hsm_dt_pin.dts for testPreLoadHsmPinInDtIgnored
- Drop testPreLoadHsmSignDataChecks: _SignHsmData() no longer re-validates the algorithm and padding scheme; that validation was moved to ReadNode() in the previous patch, so the test would need to bypass ReadNode() to reach the error paths and is no longer meaningful
- Drop testPreLoadHsmHeaderSignMissing: the dummy-header path when the tool disappears between the two sign() calls is now handled by _BuildHeader() returning None, which _CreateHeader() maps to the dummy bytes; the case is implicitly covered by testPreLoadHsmMissingTool

 tools/binman/ftest.py                         | 257 ++++++++++++++++++
 tools/binman/test/security/pre_load_hsm.dts   |  21 ++
 .../test/security/pre_load_hsm_dt_pin.dts     |  22 ++
 .../test/security/pre_load_hsm_ecdsa.dts      |  21 ++
 .../security/pre_load_hsm_invalid_algo.dts    |  21 ++
 .../security/pre_load_hsm_invalid_padding.dts |  22 ++
 .../security/pre_load_hsm_invalid_sha.dts     |  21 ++
 .../security/pre_load_hsm_invalid_uri.dts     |  21 ++
 .../security/pre_load_hsm_module_path.dts     |  21 ++
 .../test/security/pre_load_hsm_sign_pss.dts   |  22 ++
 10 files changed, 449 insertions(+)
 create mode 100644 tools/binman/test/security/pre_load_hsm.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_dt_pin.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_ecdsa.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_invalid_algo.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_invalid_padding.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_invalid_sha.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_invalid_uri.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_module_path.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_sign_pss.dts
tools/binman/ftest.py +257 -0
index d4522e905e0..0ddc282ac30 100644
@@ -22,10 +22,15 @@ import unittest
 import unittest.mock
 import urllib.error
 
+from Cryptodome.Hash import SHA256
+from Cryptodome.PublicKey import ECC
+from Cryptodome.Signature import DSS
+
 from binman import bintool
 from binman import cbfs_util
 from binman import cmdline
 from binman import control
+from binman.btool import pkcs11_tool as pkcs11_tool_btool
 from binman import elf
 from binman import elf_test
 from binman import fip_util
@@ -5992,6 +5997,258 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
         self.assertIn('key-name is required for file-based signing',
                       str(exc.exception))
 
+    def _MakePreLoadHsmToken(self, prefix, key_type, label):
+        """Create a SoftHSM token holding a new key pair
+
+        Args:
+            prefix (str): Prefix for the files created in the input directory
+            key_type (str): Key type for pkcs11-tool, e.g. 'rsa:2048'
+            label (str): Label of the key pair on the token
+
+        Returns:
+            tuple:
+                str: SOFTHSM2_CONF file to set while using the token
+                str: Path to the SoftHSM2 shared library
+                str: Path to the public key, in DER format
+        """
+        softhsm2_util = bintool.Bintool.create('softhsm2_util')
+        self._CheckBintool(softhsm2_util)
+
+        pkcs11_tool = bintool.Bintool.create('pkcs11-tool')
+        self._CheckBintool(pkcs11_tool)
+
+        p11_kit = bintool.Bintool.create('p11-kit')
+        self._CheckBintool(p11_kit)
+
+        # Configure SoftHSMv2
+        softhsm2_data = tools.read_file(self.TestFile('fit/softhsm2.conf'))
+        softhsm2_conf = self._MakeInputFile(f'{prefix}softhsm2.conf',
+                                            softhsm2_data)
+        softhsm2_tokens_dir = self._MakeInputDir(f'{prefix}softhsm2.tokens')
+        with open(softhsm2_conf, 'a') as f:
+            f.write(f'directories.tokendir = {softhsm2_tokens_dir}\n')
+
+        # Locate the SoftHSM2 shared library via p11-kit
+        p11_kit_config = configparser.ConfigParser()
+        p11_kit_config.read_string(p11_kit.run_cmd('print-config'))
+        softhsm2_lib = p11_kit_config.get('softhsm2', 'module', fallback=None)
+        self.assertIsNotNone(softhsm2_lib,
+                             'softhsm2 module not found in p11-kit config')
+
+        pubkey_der = os.path.join(self._indir, f'{prefix}pubkey.der')
+        with unittest.mock.patch.dict('os.environ',
+                                      {'SOFTHSM2_CONF': softhsm2_conf}):
+            softhsm2_util.run_cmd('--init-token', '--free', '--label',
+                                  'uboot-hsm', '--pin', '1234',
+                                  '--so-pin', '1234')
+            pkcs11_tool.run_cmd('--module', softhsm2_lib,
+                                '--keypairgen', '--key-type', key_type,
+                                '--label', label, '--login', '--pin', '1234')
+            pkcs11_tool.run_cmd('--module', softhsm2_lib,
+                                '--read-object', '--type', 'pubkey',
+                                '--label', label, '--login',
+                                '--pin', '1234', '--output-file', pubkey_der)
+        return softhsm2_conf, softhsm2_lib, pubkey_der
+
+    def testPreLoadHsmSign(self):
+        """Test pre-load header signed by SoftHSM via PKCS#11 (pkcs-1.5 and PSS)
+
+        Sets up a SoftHSM v2 token, generates an RSA-2048 key pair on it, and
+        builds two pre-load images (one with pkcs-1.5, one with PSS). Both are
+        verified with preload_check_sign using the public key extracted from the
+        token.
+        """
+        openssl = bintool.Bintool.create('openssl')
+        self._CheckBintool(openssl)
+
+        softhsm2_conf, softhsm2_lib, pubkey_der = self._MakePreLoadHsmToken(
+            'testPreLoadHsmSign.', 'rsa:2048', 'uboot-key')
+        pubkey_pem = os.path.join(self._indir, 'pubkey.pem')
+        openssl.run_cmd_result('rsa', '-pubin', '-inform', 'DER',
+                               '-in', pubkey_der, '-out', pubkey_pem)
+
+        with unittest.mock.patch.dict('os.environ',
+                                      {'SOFTHSM2_CONF': softhsm2_conf}):
+            entry_args = {
+                'pre-load-hsm-library': softhsm2_lib,
+                'pre-load-hsm-pin': '1234',
+            }
+
+            # pkcs-1.5 (default padding)
+            data = self._DoReadFileDtb('security/pre_load_hsm.dts',
+                                       entry_args=entry_args)[0]
+            image_fname = tools.get_output_filename('image.bin')
+            self.assertEqual(PRE_LOAD_MAGIC, data[:len(PRE_LOAD_MAGIC)])
+            self.assertEqual(PRE_LOAD_VERSION, data[4:4 + len(PRE_LOAD_VERSION)])
+            self.assertEqual(PRE_LOAD_HDR_SIZE,
+                             data[8:8 + len(PRE_LOAD_HDR_SIZE)])
+            self.assertTrue(self._CheckPreload(image_fname, pubkey_pem))
+
+            # PSS padding
+            data = self._DoReadFileDtb('security/pre_load_hsm_sign_pss.dts',
+                                       entry_args=entry_args)[0]
+            image_fname = tools.get_output_filename('image.bin')
+            self.assertEqual(PRE_LOAD_MAGIC, data[:len(PRE_LOAD_MAGIC)])
+            self.assertTrue(
+                self._CheckPreload(image_fname, pubkey_pem, padding='pss'))
+
+    def testPreLoadHsmEcdsaSign(self):
+        """Test pre-load header signed by SoftHSM with ECDSA."""
+        softhsm2_conf, softhsm2_lib, pubkey_der = self._MakePreLoadHsmToken(
+            'testPreLoadHsmEcdsaSign.', 'EC:prime256v1', 'uboot-ecdsa')
+
+        with unittest.mock.patch.dict('os.environ',
+                                      {'SOFTHSM2_CONF': softhsm2_conf}):
+            args = {'pre-load-hsm-library': softhsm2_lib,
+                    'pre-load-hsm-pin': '1234'}
+            data = self._DoReadFileDtb('security/pre_load_hsm_ecdsa.dts',
+                                       entry_args=args)[0]
+        self.assertEqual(PRE_LOAD_MAGIC, data[:len(PRE_LOAD_MAGIC)])
+
+        # preload_check_sign needs the private key for ECDSA, which an HSM
+        # never exports, so verify with the public key read from the token.
+        # Layout: header (64 bytes), header signature (64 bytes), image
+        # signature (64 bytes), then padding up to the 4096-byte header.
+        pub = ECC.import_key(tools.read_file(pubkey_der))
+        first_header = data[:64]
+        hdr_sig = data[64:128]
+        img_sig = data[128:192]
+        image = data[4096:]
+        self.assertEqual(SHA256.new(img_sig).digest(), first_header[32:64])
+        DSS.new(pub, 'fips-186-3').verify(SHA256.new(image), img_sig)
+        DSS.new(pub, 'fips-186-3').verify(SHA256.new(first_header), hdr_sig)
+
+    def testPreLoadHsmInvalidPadding(self):
+        """Test HSM signing with invalid padding-name (validated before tool check)"""
+        with self.assertRaises(ValueError) as exc:
+            self._DoReadFile('security/pre_load_hsm_invalid_padding.dts')
+        self.assertIn('Unsupported padding scheme', str(exc.exception))
+
+    def testPreLoadHsmMissingTool(self):
+        """Test that binman still produces an image if pkcs11-tool is missing"""
+        with terminal.capture() as (_, stderr):
+            self._DoTestFile('security/pre_load_hsm.dts',
+                             force_missing_bintools='pkcs11-tool')
+        err = stderr.getvalue()
+        self.assertRegex(err, "Image 'image'.*missing bintools.*: pkcs11-tool")
+
+    def testPreLoadHsmSignError(self):
+        """Test HSM signing when sign() raises ValueError or RuntimeError"""
+        Btool = pkcs11_tool_btool.Bintoolpkcs11_tool
+        for exc_type in (ValueError, RuntimeError):
+            with unittest.mock.patch.object(Btool, 'is_present',
+                                            return_value=True), \
+                 unittest.mock.patch.object(Btool, 'sign',
+                                            side_effect=exc_type('Mock HSM error')):
+                with self.assertRaises(ValueError) as exc:
+                    self._DoReadFile('security/pre_load_hsm.dts')
+                self.assertIn('HSM signing failed', str(exc.exception))
+
+    def testPreLoadHsmInvalidUri(self):
+        """Test HSM signing with a hsm-key that is not a PKCS#11 URI"""
+        with self.assertRaises(ValueError) as exc:
+            self._DoReadFile('security/pre_load_hsm_invalid_uri.dts')
+        self.assertIn('Not a PKCS#11 URI', str(exc.exception))
+
+    def testPreLoadHsmInvalidSha(self):
+        """Test HSM signing with an unsupported hash algorithm"""
+        with self.assertRaises(ValueError) as exc:
+            self._DoReadFile('security/pre_load_hsm_invalid_sha.dts')
+        self.assertIn('sha1 is not supported', str(exc.exception))
+
+    def testPreLoadHsmInvalidAlgo(self):
+        """Test HSM signing with an unsupported signing algorithm"""
+        with self.assertRaises(ValueError) as exc:
+            self._DoReadFile('security/pre_load_hsm_invalid_algo.dts')
+        self.assertIn('rsa1234 is not supported', str(exc.exception))
+
+    def testPreLoadHsmModulePath(self):
+        """Test that module-path in the hsm-key URI sets the HSM library"""
+        self._DoTestFile('security/pre_load_hsm_module_path.dts',
+                         force_missing_bintools='pkcs11-tool')
+        entry = control.images['image'].GetEntries()['pre-load']
+        self.assertEqual('/no/lib.so', entry.hsm_library)
+
+    def _GetPreLoadHsmPins(self, entry_args, env,
+                           dts='security/pre_load_hsm.dts'):
+        """Run the pre-load HSM test file and collect the PINs given to sign()
+
+        Args:
+            entry_args (dict or None): Entry args to pass to binman
+            env (dict): Environment to use (PKCS11_SIGN_PIN is cleared first)
+            dts (str): Devicetree file to use
+
+        Returns:
+            list of str: 'pin' argument of each sign() call
+        """
+        Btool = pkcs11_tool_btool.Bintoolpkcs11_tool
+        pins = []
+
+        def fake_sign(_self, *args, **kwargs):
+            pins.append(kwargs.get('pin'))
+            return bytes(256)
+
+        clean = {k: v for k, v in os.environ.items()
+                 if k != 'PKCS11_SIGN_PIN'}
+        clean.update(env)
+        with unittest.mock.patch.dict(os.environ, clean, clear=True), \
+             unittest.mock.patch.object(Btool, 'is_present',
+                                        return_value=True), \
+             unittest.mock.patch.object(Btool, 'sign', autospec=True,
+                                        side_effect=fake_sign):
+            self._DoReadFileDtb(dts, entry_args=entry_args)
+        return pins
+
+    def testPreLoadHsmPinEntryArg(self):
+        """Test that pre-load-hsm-pin reaches sign() for both signatures"""
+        pins = self._GetPreLoadHsmPins({'pre-load-hsm-pin': '1234'}, {})
+        self.assertTrue(pins, 'sign() was never called')
+        self.assertEqual(['1234'] * len(pins), pins)
+
+    def testPreLoadHsmPinEnvVar(self):
+        """Test that PKCS11_SIGN_PIN is used when there is no entry arg"""
+        pins = self._GetPreLoadHsmPins(None, {'PKCS11_SIGN_PIN': 'envpin'})
+        self.assertTrue(pins, 'sign() was never called')
+        self.assertEqual(['envpin'] * len(pins), pins)
+
+    def testPreLoadHsmPinEntryArgWins(self):
+        """Test that pre-load-hsm-pin takes priority over PKCS11_SIGN_PIN"""
+        pins = self._GetPreLoadHsmPins({'pre-load-hsm-pin': '1234'},
+                                       {'PKCS11_SIGN_PIN': 'envpin'})
+        self.assertTrue(pins, 'sign() was never called')
+        self.assertEqual(['1234'] * len(pins), pins)
+
+    def testPreLoadHsmNoPin(self):
+        """Test that no PIN is passed to sign() when none is configured"""
+        pins = self._GetPreLoadHsmPins(None, {})
+        self.assertTrue(pins, 'sign() was never called')
+        self.assertEqual([None] * len(pins), pins)
+
+    def testPreLoadHsmPinInDtIgnored(self):
+        """Test that a pre-load-hsm-pin property in the DT is never used"""
+        dts = 'security/pre_load_hsm_dt_pin.dts'
+        pins = self._GetPreLoadHsmPins(None, {}, dts)
+        self.assertTrue(pins, 'sign() was never called')
+        self.assertEqual([None] * len(pins), pins)
+
+        # The entry arg and environment variable still take effect
+        pins = self._GetPreLoadHsmPins({'pre-load-hsm-pin': '1234'}, {}, dts)
+        self.assertEqual(['1234'] * len(pins), pins)
+        pins = self._GetPreLoadHsmPins(None, {'PKCS11_SIGN_PIN': 'envpin'},
+                                       dts)
+        self.assertEqual(['envpin'] * len(pins), pins)
+
+    def testPreLoadHsmBadSignatureLength(self):
+        """Test HSM signing when the returned signature has the wrong size"""
+        Btool = pkcs11_tool_btool.Bintoolpkcs11_tool
+        with unittest.mock.patch.object(Btool, 'is_present',
+                                        return_value=True), \
+             unittest.mock.patch.object(Btool, 'sign',
+                                        return_value=b'short'):
+            with self.assertRaises(ValueError) as exc:
+                self._DoReadFile('security/pre_load_hsm.dts')
+        self.assertIn('HSM returned 5-byte signature', str(exc.exception))
+
     def _CheckSafeUniqueNames(self, *images):
         """Check all entries of given images for unsafe unique names"""
         for image in images:
tools/binman/test/security/pre_load_hsm.dts new file +21 -0
new file mode 100644
index 00000000000..5671559c838
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		pre-load {
+			content = <&image>;
+			algo-name = "sha256,rsa2048";
+			header-size = <4096>;
+			version = <0x11223344>;
+			hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_hsm_dt_pin.dts new file +22 -0
new file mode 100644
index 00000000000..84cdf4291a1
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		pre-load {
+			content = <&image>;
+			algo-name = "sha256,rsa2048";
+			header-size = <4096>;
+			version = <0x11223344>;
+			hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";
+			pre-load-hsm-pin = "dtpin";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_hsm_ecdsa.dts new file +21 -0
new file mode 100644
index 00000000000..5b00ed8d69d
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		pre-load {
+			content = <&image>;
+			algo-name = "sha256,ecdsa256";
+			header-size = <4096>;
+			version = <0x11223344>;
+			hsm-key = "pkcs11:token=uboot-hsm;object=uboot-ecdsa";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_hsm_invalid_algo.dts new file +21 -0
new file mode 100644
index 00000000000..49d1c18f478
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		pre-load {
+			content = <&image>;
+			algo-name = "sha256,rsa1234";
+			header-size = <4096>;
+			version = <0x11223344>;
+			hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_hsm_invalid_padding.dts new file +22 -0
new file mode 100644
index 00000000000..6ef11a59bb1
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		pre-load {
+			content = <&image>;
+			algo-name = "sha256,rsa2048";
+			padding-name = "invalid";
+			header-size = <4096>;
+			version = <0x11223344>;
+			hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_hsm_invalid_sha.dts new file +21 -0
new file mode 100644
index 00000000000..e6c693e4954
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		pre-load {
+			content = <&image>;
+			algo-name = "sha1,rsa2048";
+			header-size = <4096>;
+			version = <0x11223344>;
+			hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_hsm_invalid_uri.dts new file +21 -0
new file mode 100644
index 00000000000..17838935f61
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		pre-load {
+			content = <&image>;
+			algo-name = "sha256,rsa2048";
+			header-size = <4096>;
+			version = <0x11223344>;
+			hsm-key = "http://not-a-pkcs11-uri";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_hsm_module_path.dts new file +21 -0
new file mode 100644
index 00000000000..ae25d63b53d
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		pre-load {
+			content = <&image>;
+			algo-name = "sha256,rsa2048";
+			header-size = <4096>;
+			version = <0x11223344>;
+			hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key?module-path=/no/lib.so";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_hsm_sign_pss.dts new file +22 -0
new file mode 100644
index 00000000000..452f9f6d8a6
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		pre-load {
+			content = <&image>;
+			algo-name = "sha256,rsa2048";
+			padding-name = "pss";
+			header-size = <4096>;
+			version = <0x11223344>;
+			hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
Signature · 1 line
2.43.0
#8 lore raw

Re: [PATCH v3 4/4 RESEND] binman: Add functional test for pre-load HSM signing

Quoted 4 lines

Add end-to-end functional test for HSM-based signing of pre-load headers. The test verifies that binman can use PKCS#11 libraries to sign data via hardware security modules and can generate pre-load headers with HSM signatures.

I see mocks in some of the tests, so that tells me we might not actually be doing full end-to-end testing in all cases. Is it possible to write the tests without the mocks?

And I think we might need to add opensc to the CI Docker image so that the tests actually run on CI.

Quoted 26 lines

The tests create a SoftHSM v2 token, generate RSA and ECDSA key pairs on it with pkcs11-tool, and verify the resulting pre-load header signatures. RSA signatures are checked with preload_check_sign; ECDSA signatures are checked with Cryptodome because preload_check_sign needs the private key.

- Add _MakePreLoadHsmToken() to set up the SoftHSM configuration from fit/softhsm2.conf, locate the library through p11-kit, initialise the token, generate a key pair and export the public key in DER format.
- Add testPreLoadHsmSign, which generates an RSA-2048 key pair and checks the header, for both pkcs-1.5 and PSS padding, with preload_check_sign using the public key exported from the token
- Add testPreLoadHsmEcdsaSign, which generates an ECDSA key pair and verifies the signatures with Cryptodome, since preload_check_sign needs the private key for ECDSA, which an HSM never exposes
- Add testPreLoadHsmModulePath to check that module-path= in the URI sets the library.
- Add _GetPreLoadHsmPins() to collect the PIN passed to each sign() call.
- Add PIN tests that check the PIN source order: the pin entry arg, the environment variable, the entry arg taking precedence over the environment variable, no PIN at all, and a PIN in the device tree being ignored.
- Add testPreLoadHsmBadSignatureLength to check that a signature of the wrong length is rejected.

Quoted 4 lines

Error-path tests, which do not need SoftHSM, cover an invalid padding scheme, an unsupported hash, an unsupported signature algorithm, an invalid PKCS#11 URI, a missing pkcs11-tool and a signing failure reported by pkcs11-tool.

Please add SoftHSM cases for serial=, slot-id= and id=. They would have caught the two URI mapping bugs in patch 2.

tools/binman/test/security/pre_load_hsm.dts line 1

Quoted 7 lines
tools/binman/test/security/pre_load_hsm.dts new file +1 -0
new file mode 100644
index 00000000000..5671559c838
@@ -0,0 +1,21 @@
+// SPDX-License-Identifier: GPL-2.0+

nit: GPL-2.0+ form is deprecated use GPL-2.0-or-later instead.

Signature · 1 line
David Lechner <[email protected]>