Skip to contentSkip to conversation

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

PATCH Superseded Yan WANG 3 participants 27 messages Oct 12 – Oct 30

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Yan WANG

author
#0 lore raw

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

The pre-load entry type currently only supports signing via RSA key files on disk. This series extends it to support Hardware Security Modules (HSM) through the PKCS#11 standard.

The implementation builds on the existing pkcs11_tool btool: a sign() method is added that drives pkcs11-tool to perform the actual cryptographic operation.

The pre-load entry gains a set of hsm-* device-tree properties:

  hsm-support        - boolean flag to enable HSM path
  hsm-library        - path to the PKCS#11 shared library (.so)
  hsm-token-label    - token label (alternative to serial)
  hsm-token-serial   - token serial number
  hsm-slot-index     - direct slot index (alternative to label/serial)
  hsm-key-label      - private key label (alternative to key-id)
  hsm-key-id         - private key ID
  hsm-pin            - user PIN

Yan WANG (5):
binman: Add PKCS#11 signing support to pkcs11_tool
binman: Add test for pkcs11_tool sign method
binman: Add HSM signing support to pre-load entry type
binman: test: Add SoftHSM functional test for pre-load HSM signing
binman: Add functional test for pre-load HSM signing

 tools/binman/bintool_test.py                  | 374 ++++++++++++++++++
 tools/binman/btool/pkcs11_tool.py             | 275 +++++++++++++
 tools/binman/etype/pre_load.py                | 285 +++++++++----
 tools/binman/ftest.py                         | 140 +++++++
 .../security/pre_load_default_padding.dts     |  23 ++
 .../security/pre_load_hsm_invalid_padding.dts |  27 ++
 .../security/pre_load_hsm_missing_library.dts |  27 ++
 .../security/pre_load_hsm_missing_tool.dts    |  27 ++
 .../test/security/pre_load_hsm_sign.dts       |  68 ++++
 .../security/pre_load_missing_key_name.dts    |  23 ++
 10 files changed, 1198 insertions(+), 71 deletions(-)
 create mode 100644 tools/binman/test/security/pre_load_default_padding.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_invalid_padding.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_missing_library.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_missing_tool.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_sign.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 1/5 binman: Add PKCS#11 signing support to pkcs11_tool

Implement the sign() method in the pkcs11_tool btool to enable HSM-based cryptographic signing using the PKCS#11 standard. This provides the core PKCS#11 interface needed for secure signing with hardware security modules in binman workflows.

---
 tools/binman/btool/pkcs11_tool.py | 275 ++++++++++++++++++++++++++++++
 1 file changed, 275 insertions(+)
tools/binman/btool/pkcs11_tool.py +275 -0
index ca80943f98c..e380f585fc7 100644
@@ -3,7 +3,12 @@
 #
 """Bintool implementation for pkcs11-tool"""
 
+import os
+import re
+import tempfile
+
 from binman import bintool
+from u_boot_pylib import tools
 
 
 class Bintoolpkcs11_tool(bintool.Bintool):
@@ -22,6 +27,276 @@ class Bintoolpkcs11_tool(bintool.Bintool):
                          'PKCS #11 tokens managing tool',
                          version_args='--show-info')
 
+    def _build_mechanism(self, hash_algo, sign_algo, padding):
+        """Build a PKCS#11 mechanism name from algorithm parameters.
+
+        Derives the mechanism name dynamically from the hash algorithm,
+        signing algorithm, and padding, supporting any PKCS#11-compatible
+        combination without a fixed lookup table.
+
+        The signing algorithm may include a key-size suffix (e.g. 'rsa2048',
+        'ec256') which is stripped; only the algorithm family is used.
+
+        Args:
+            hash_algo (str): Hash algorithm (e.g. 'sha256', 'sha384', 'sha512')
+            sign_algo (str): Signing algorithm (e.g. 'rsa2048', 'rsa4096',
+                'ec256', 'ecdsa384')
+            padding (str): Padding scheme ('pkcs1v15', 'pkcs-1.5', or 'pss')
+
+        Returns:
+            str: PKCS#11 mechanism name (e.g. 'SHA256-RSA-PKCS')
+
+        Raises:
+            ValueError: If the algorithm family cannot be mapped to a mechanism
+        """
+        hash_upper = hash_algo.upper()
+
+        # Strip trailing digits to extract the algorithm family:
+        # 'rsa2048' -> 'RSA', 'ec256' -> 'EC', 'ecdsa384' -> 'ECDSA'
+        m = re.match(r'([a-zA-Z]+)', sign_algo)
+        if not m:
+            raise ValueError(f"Cannot parse signing algorithm: {sign_algo!r}")
+        algo_family = m.group(1).upper()
+
+        # Normalize padding aliases
+        pad = padding.lower()
+        if pad == 'pkcs-1.5':
+            pad = 'pkcs1v15'
+
+        if algo_family == 'RSA':
+            if pad == 'pss':
+                return f'{hash_upper}-RSA-PKCS-PSS'
+            else:
+                return f'{hash_upper}-RSA-PKCS'
+        elif algo_family in ('EC', 'ECDSA'):
+            return f'ECDSA-{hash_upper}'
+        else:
+            raise ValueError(
+                f"Unsupported signing algorithm: {sign_algo!r}"
+            )
+
+    def _verify_mechanism(self, mechanism, module, slot_index=None,
+                          token_label=None):
+        """Verify a mechanism against the token's allowed mechanisms list.
+
+        Calls pkcs11-tool --list-mechanisms to retrieve the set of mechanisms
+        supported by the token and raises an error if the requested mechanism
+        is absent. Verification is silently skipped when the list cannot be
+        retrieved (tool unavailable, non-zero exit, or unparseable output).
+
+        Args:
+            mechanism (str): PKCS#11 mechanism name to verify
+                (e.g. 'SHA256-RSA-PKCS')
+            module (str): Path to PKCS#11 library (.so file)
+            slot_index (str): Slot index to target (optional)
+            token_label (str): Token label (optional, used when no slot_index)
+
+        Raises:
+            ValueError: If mechanism is not in the token's allowed mechanisms
+        """
+        args = ['--list-mechanisms', '--module', module]
+        if slot_index is not None:
+            args += ['--slot-index', slot_index]
+        elif token_label:
+            args += ['--token-label', token_label]
+
+        result = self.run_cmd_result(*args, raise_on_error=False)
+        if result is None or result.return_code != 0:
+            return  # Cannot verify; proceed and let pkcs11-tool report errors
+
+        stdout = (result.stdout.decode('utf-8', errors='replace')
+                  if isinstance(result.stdout, bytes) else result.stdout)
+
+        # Parse mechanism names from lines like:
+        #   SHA256-RSA-PKCS, keySize={512,4096}, hw, sign, verify
+        # Only accept names that match the PKCS#11 identifier format
+        # (uppercase alphanumeric with dashes, e.g. SHA256-RSA-PKCS).
+        allowed = []
+        for line in stdout.splitlines():
+            line = line.strip()
+            if not line or line.startswith(('Using ', 'Supported ', 'Mechanism')):
+                continue
+            mech_name = line.split(',')[0].strip()
+            if re.match(r'^[A-Z][A-Z0-9-]+$', mech_name):
+                allowed.append(mech_name)
+
+        if allowed and mechanism not in allowed:
+            raise ValueError(
+                f"Mechanism '{mechanism}' is not in the token's allowed "
+                f"mechanisms.\nAllowed: {', '.join(sorted(allowed))}"
+            )
+
+    def find_slot_by_serial(self, module, serial):
+        """Find slot index by token serial number.
+
+        Args:
+            module: Path to PKCS#11 library
+            serial: Token serial number to find
+
+        Returns:
+            Slot index as string, or None if not found
+        """
+        args = ['--module', module, '--list-slots']
+        result = self.run_cmd(*args)
+
+        # Parse output line by line to find matching serial
+        lines = result.stdout.split('\n')
+        current_slot = None
+
+        for line in lines:
+            # Track current slot number
+            slot_match = re.search(r'Slot (\d+)', line)
+            if slot_match:
+                current_slot = slot_match.group(1)
+
+            # Check for serial number match
+            if 'token serial num' in line.lower():
+                serial_match = re.search(r'token serial num\s*:\s*(\S+)', line,
+                                         re.IGNORECASE)
+                if serial_match and serial_match.group(1) == serial:
+                    return current_slot
+
+        return None
+
+    def sign(self, data, module, token_label=None, token_serial=None,
+             slot_index=None, key_label=None, key_id=None, pin=None,
+             hash_algo='sha256', sign_algo='rsa2048', padding='pkcs1v15'):
+        """Sign data using PKCS#11 HSM
+
+        This method signs data using a private key stored in a PKCS#11 token
+        (HSM, smart card, or software token like SoftHSM). The data is hashed
+        and signed by the HSM using the specified mechanism.
+
+        The mechanism name is derived dynamically from the algorithm parameters
+        and validated against the token's allowed mechanisms list before
+        signing.
+
+        Args:
+            data (bytes): Data to sign (will be hashed and signed by the HSM)
+            module (str): Path to PKCS#11 library (.so file)
+            token_label (str): Token label (alternative to token_serial)
+            token_serial (str): Token serial number (alternative to token_label)
+            key_label (str): Private key label (alternative to key_id)
+            key_id (str): Private key ID (alternative to key_label)
+            pin (str): PIN/password to unlock the token
+            hash_algo (str): Hash algorithm ('sha256', 'sha384', 'sha512', …)
+                Default: 'sha256'
+            sign_algo (str): Signature algorithm with optional key size
+                (e.g. 'rsa2048', 'rsa4096', 'ec256')
+                Default: 'rsa2048'
+            padding (str): Padding scheme ('pkcs1v15', 'pkcs-1.5', or 'pss')
+                Default: 'pkcs1v15'
+
+        Returns:
+            bytes: Signature bytes
+
+        Raises:
+            ValueError: If mechanism is unsupported, parameters are invalid,
+                or the mechanism is not in the token's allowed list
+            RuntimeError: If signing operation fails
+        """
+        # Build mechanism name dynamically from algorithm parameters
+        mechanism = self._build_mechanism(hash_algo, sign_algo, padding)
+
+        # Validate token identification
+        if not token_label and not token_serial and not slot_index:
+            raise ValueError(
+                "Must specify either token_label or token_serial or slot_index"
+            )
+
+        # Validate key identification
+        if not key_label and not key_id:
+            raise ValueError(
+                "Must specify either key_label or key_id"
+            )
+
+        # Validate module path
+        if not module:
+            raise ValueError("PKCS#11 module path is required")
+
+        if not os.path.exists(module):
+            raise ValueError(f"PKCS#11 module not found: {module}")
+
+        # Resolve slot from serial number if needed (done early so that
+        # mechanism verification targets the correct token)
+        resolved_slot = slot_index
+        if not slot_index and token_serial:
+            slot_idx = self.find_slot_by_serial(module, token_serial)
+            if slot_idx:
+                resolved_slot = slot_idx
+            else:
+                raise ValueError(
+                    f"Token with serial {token_serial} not found"
+                )
+
+        # Verify mechanism is in the token's allowed mechanisms list
+        self._verify_mechanism(
+            mechanism, module,
+            slot_index=resolved_slot,
+            token_label=token_label if not resolved_slot else None,
+        )
+
+        # Write data to temporary file (pkcs11-tool requires file input)
+        input_fd, input_file = tempfile.mkstemp(suffix='.bin',
+                                                prefix='binman_sign_')
+        try:
+            os.write(input_fd, data)
+            os.close(input_fd)
+
+            # Build pkcs11-tool command
+            args = [
+                '--sign',
+                '--mechanism', mechanism,
+                '--module', module,
+                '--input-file', input_file,
+            ]
+
+            # Add token identification
+            if resolved_slot:
+                args += ['--slot-index', resolved_slot]
+            elif token_label:
+                args += ['--token-label', token_label]
+
+            # Add key identification
+            if key_label:
+                args += ['--label', key_label]
+            elif key_id:
+                args += ['--id', key_id]
+
+            # Add PIN and login
+            if pin:
+                args += ['--pin', pin]
+            args += ['--login']
+
+            # Execute signing (signature goes to stdout in binary format)
+            result = self.run_cmd_result(*args, binary=True,
+                                        raise_on_error=False)
+
+            if result is None:
+                raise RuntimeError(
+                    "pkcs11-tool not available. Install the 'opensc' package"
+                )
+
+            if result.return_code != 0:
+                stderr = (result.stderr.decode('utf-8', errors='replace')
+                          if result.stderr else '')
+                raise RuntimeError(
+                    f"pkcs11-tool signing failed "
+                    f"(exit code {result.return_code}):\n{stderr}"
+                )
+
+            if not result.stdout:
+                raise RuntimeError("pkcs11-tool produced no signature output")
+
+            return result.stdout
+
+        finally:
+            # Clean up temporary file
+            try:
+                os.unlink(input_file)
+            except OSError:
+                pass
+
     def fetch(self, method):
         """Install opensc via APT """
         if method != bintool.FETCH_BIN:
Signature · 1 line
2.43.0
#2 lore raw

Re: [PATCH 1/5] binman: Add PKCS#11 signing support to pkcs11_tool

Hi Yan,

Quoted 6 lines · Yan WANG

binman: Add PKCS#11 signing support to pkcs11_tool

Implement the sign() method in the pkcs11_tool btool to enable HSM-based cryptographic signing using the PKCS#11 standard. This provides the core PKCS#11 interface needed for secure signing with hardware security modules in binman workflows.

Please can you say more about the design? For example, the token is selected by label, serial or slot index, and the mechanism is checked against the token's list before signing. Please also mention the new public method find_slot_by_serial().

tools/binman/btool/pkcs11_tool.py line 4

Quoted 10 lines

tools/binman/btool/pkcs11_tool.py | 275 ++++++++++++++++++++++++++++++++++++++

 1 file changed, 275 insertions(+)
tools/binman/btool/pkcs11_tool.py +1 -0
@@ -3,7 +3,12 @@
 from binman import bintool
+from u_boot_pylib import tools

This import is unused.

tools/binman/btool/pkcs11_tool.py class Bintoolpkcs11_tool(bintool.Bintool): · line 31

Quoted 7 lines
tools/binman/btool/pkcs11_tool.py +5 -0
@@ -22,6 +27,276 @@ class Bintoolpkcs11_tool(bintool.Bintool):
+        args = ['--module', module, '--list-slots']
+        result = self.run_cmd(*args)
+
+        # Parse output line by line to find matching serial
+        lines = result.stdout.split('\n')

run_cmd() returns the stdout string, or None if the tool is missing, not a CommandResult. So this raises AttributeError the first time anyone uses hsm-token-serial. The test in patch 2 misses this because it mocks run_cmd() to return a namedtuple. Please can you use run_cmd_result() here, or treat the return value as a string and mock it as one in the test?

tools/binman/btool/pkcs11_tool.py class Bintoolpkcs11_tool(bintool.Bintool): · line 28

Quoted 4 lines
tools/binman/btool/pkcs11_tool.py +2 -0
@@ -22,6 +27,276 @@ class Bintoolpkcs11_tool(bintool.Bintool):
+        elif algo_family in ('EC', 'ECDSA'):
+            return f'ECDSA-{hash_upper}'

The pre-load entry only handles RSA, and no test in the series produces an ECDSA signature that U-Boot then verifies. I suggest supporting only RSA until EC has a user and a test. Also, nothing checks hash_algo, so a typo only shows up as a confusing 'not in the allowed mechanisms' error, or as a pkcs11-tool error if the mechanism list can't be read. What do you think?

tools/binman/btool/pkcs11_tool.py class Bintoolpkcs11_tool(bintool.Bintool): · line 29

Quoted 5 lines
tools/binman/btool/pkcs11_tool.py +3 -0
@@ -22,6 +27,276 @@ class Bintoolpkcs11_tool(bintool.Bintool):
+        result = self.run_cmd_result(*args, raise_on_error=False)
+        if result is None or result.return_code != 0:
+            return  # Cannot verify; proceed and let pkcs11-tool report errors

The check is silently skipped in several cases, and pkcs11-tool reports the same error anyway if the mechanism is missing. Do we need _verify_mechanism() at all? It costs an extra tool invocation per signature (two per pre-load entry), and parsing the output is fragile. If you keep it, please at least log something with tout when it is skipped.

tools/binman/btool/pkcs11_tool.py class Bintoolpkcs11_tool(bintool.Bintool): · line 29

Quoted 5 lines
tools/binman/btool/pkcs11_tool.py +3 -0
@@ -22,6 +27,276 @@ class Bintoolpkcs11_tool(bintool.Bintool):
+        # Write data to temporary file (pkcs11-tool requires file input)
+        input_fd, input_file = tempfile.mkstemp(suffix='.bin',
+                                                prefix='binman_sign_')

Other btools normally take filenames. The etype can write its data into the output directory with tools.get_output_filename() and tools.write_file(). The file then stays there for debugging and is cleaned up with everything else. Please can you change sign() to take an input filename? It could perhaps also take an output filename via --output-file, rather than reading the signature from stdout. That removes the mkstemp()/unlink() handling here.

tools/binman/btool/pkcs11_tool.py class Bintoolpkcs11_tool(bintool.Bintool): · line 30

Quoted 6 lines
tools/binman/btool/pkcs11_tool.py +4 -0
@@ -22,6 +27,276 @@ class Bintoolpkcs11_tool(bintool.Bintool):
+            # Add PIN and login
+            if pin:
+                args += ['--pin', pin]
+            args += ['--login']

Two things here. First, a PIN on the command line is visible to anyone who can read /proc on the build machine. I believe newer OpenSC versions accept '--pin env:VAR', but please check which version added it. If so, it would be better to pass the PIN that way, or at least to mention the risk in the documentation. Second, with no PIN, --login makes pkcs11-tool prompt on the terminal, so a non-interactive build hangs. Should this raise an error instead, unless the token has a protected authentication path?

Regards,
Simon

author
#3 lore raw

PATCH 2/5 binman: Add test for pkcs11_tool sign method

In reply to Yan WANG

Exercise the three new methods added to the pkcs11_tool btool:
sign(), _build_mechanism() and _verify_mechanism().

---
 tools/binman/bintool_test.py | 374 +++++++++++++++++++++++++++++++++++
 1 file changed, 374 insertions(+)
tools/binman/bintool_test.py +374 -0
index 7e8dafea94e..a3c8fb70422 100644
@@ -21,6 +21,10 @@ from u_boot_pylib import terminal
 from u_boot_pylib import test_util
 from u_boot_pylib import tools
 
+# Shared namedtuple for mocking run_cmd_result() return values
+_CmdResult = collections.namedtuple(
+    '_CmdResult', ['return_code', 'stdout', 'stderr'])
+
 # pylint: disable=R0904
 class TestBintool(unittest.TestCase):
     """Tests for the Bintool class"""
@@ -38,6 +42,12 @@ class TestBintool(unittest.TestCase):
             shutil.rmtree(self._indir)
         self._indir = None
 
+    def _make_module_path(self):
+        """Create and return a path to a fake PKCS#11 module file"""
+        path = os.path.join(self._indir, 'fake_module.so')
+        tools.write_file(path, b'')
+        return path
+
     def test_missing_btype(self):
         """Test that unknown bintool types are detected"""
         with self.assertRaises(ValueError) as exc:
@@ -354,6 +364,370 @@ class TestBintool(unittest.TestCase):
             result = btool.run_cmd_result('fred')
         self.assertIsNone(result)
 
+    def test_pkcs11_tool_sign_errors(self):
+        """Test error handling in pkcs11-tool sign method"""
+        btool = Bintool.create('pkcs11_tool')
+        data = b'test data'
+
+        # Test unsupported signing algorithm family (dsa cannot be mapped)
+        with self.assertRaises(ValueError) as exc:
+            btool.sign(data, '/fake/module.so', token_label='test',
+                      key_label='test', hash_algo='sha256',
+                      sign_algo='dsa2048', padding='pkcs1v15')
+        self.assertIn('Unsupported signing algorithm', str(exc.exception))
+
+        # Test missing token identification
+        with self.assertRaises(ValueError) as exc:
+            btool.sign(data, '/fake/module.so', key_label='test')
+        self.assertIn('Must specify either token_label or token_serial',
+                     str(exc.exception))
+
+        # Test missing key identification
+        with self.assertRaises(ValueError) as exc:
+            btool.sign(data, '/fake/module.so', token_label='test')
+        self.assertIn('Must specify either key_label or key_id',
+                     str(exc.exception))
+
+        # Test missing module path
+        with self.assertRaises(ValueError) as exc:
+            btool.sign(data, None, token_label='test', key_label='test')
+        self.assertIn('PKCS#11 module path is required',
+                     str(exc.exception))
+
+        # Test module not found
+        with self.assertRaises(ValueError) as exc:
+            btool.sign(data, '/nonexistent/module.so', token_label='test',
+                      key_label='test')
+        self.assertIn('PKCS#11 module not found', str(exc.exception))
+
+    def test_pkcs11_tool_sign_failures(self):
+        """Test pkcs11-tool sign method failure cases"""
+        btool = Bintool.create('pkcs11_tool')
+        btool.present = True
+        data = b'test data'
+
+        module_path = self._make_module_path()
+
+        # Test tool not available
+        def fake_run_none(*args, **kwargs):
+            return None
+
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_none):
+            with self.assertRaises(RuntimeError) as exc:
+                btool.sign(data, module_path, token_label='test',
+                          key_label='test')
+            self.assertIn('pkcs11-tool not available', str(exc.exception))
+
+        # Test signing failure (non-zero return code)
+        def fake_run_error(*args, **kwargs):
+            return _CmdResult(1, b'', b'Error: PIN incorrect')
+
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_error):
+            with self.assertRaises(RuntimeError) as exc:
+                btool.sign(data, module_path, token_label='test',
+                          key_label='test')
+            self.assertIn('pkcs11-tool signing failed', str(exc.exception))
+            self.assertIn('PIN incorrect', str(exc.exception))
+
+        # Test no signature output
+        def fake_run_no_output(*args, **kwargs):
+            return _CmdResult(0, b'', b'')
+
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_no_output):
+            with self.assertRaises(RuntimeError) as exc:
+                btool.sign(data, module_path, token_label='test',
+                          key_label='test')
+            self.assertIn('no signature output', str(exc.exception))
+
+    def test_pkcs11_tool_cleanup_error(self):
+        """Test that cleanup errors in pkcs11-tool are handled gracefully"""
+        btool = Bintool.create('pkcs11_tool')
+        btool.present = True
+        data = b'test data'
+
+        module_path = self._make_module_path()
+
+        fake_sig = b'\x00' * 256
+
+        def fake_run_result(*args, **kwargs):
+            """Mock successful signing"""
+            return _CmdResult(0, fake_sig, b'')
+
+        # Mock os.unlink to raise OSError
+        original_unlink = os.unlink
+
+        def fake_unlink(path):
+            if 'binman_sign_' in path:
+                raise OSError("Permission denied")
+            return original_unlink(path)
+
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_result):
+            with unittest.mock.patch('os.unlink', side_effect=fake_unlink):
+                # Should not raise exception, cleanup error is silently ignored
+                sig = btool.sign(data, module_path, token_label='test',
+                               key_label='test')
+                self.assertEqual(fake_sig, sig)
+
+    def test_pkcs11_tool_find_slot_by_serial(self):
+        """Test find_slot_by_serial method"""
+        btool = Bintool.create('pkcs11_tool')
+        btool.present = True
+
+        # Test finding a slot with matching serial
+        slot_output = """Available slots:
+Slot 0 (0x123): SoftHSM slot ID 0x123
+  token label        : test-token
+  token manufacturer : SoftHSM project
+  token model        : SoftHSM v2
+  token flags        : login required, rng, token initialized, PIN initialized
+  hardware version   : 2.6
+  firmware version   : 2.6
+  Token serial num   : abc123xyz
+
+Slot 1 (0x456): SoftHSM slot ID 0x456
+  token label        : another-token
+  token manufacturer : SoftHSM project
+  token model        : SoftHSM v2
+  token flags        : login required, rng, token initialized, PIN initialized
+  hardware version   : 2.6
+  firmware version   : 2.6
+  TOKEN SERIAL NUM   : def456uvw
+"""
+        def fake_run_cmd(*args, **kwargs):
+            result = collections.namedtuple('Result', ['stdout', 'stderr'])
+            return result(slot_output, '')
+
+        with unittest.mock.patch.object(btool, 'run_cmd',
+                                       side_effect=fake_run_cmd):
+            # Test finding first slot
+            slot_idx = btool.find_slot_by_serial('/fake/module.so', 'abc123xyz')
+            self.assertEqual('0', slot_idx)
+
+            # Test finding second slot
+            slot_idx = btool.find_slot_by_serial('/fake/module.so', 'def456uvw')
+            self.assertEqual('1', slot_idx)
+
+            # Test not finding a slot
+            slot_idx = btool.find_slot_by_serial('/fake/module.so', 'nonexistent')
+            self.assertIsNone(slot_idx)
+
+    def test_pkcs11_tool_sign_success_slot_index(self):
+        """Test successful signing with slot_index"""
+        btool = Bintool.create('pkcs11_tool')
+        btool.present = True
+        data = b'test data to sign'
+
+        module_path = self._make_module_path()
+
+        fake_sig = b'\x01\x02\x03\x04' * 64
+
+        def fake_run_result(*args, **kwargs):
+            if '--sign' in args:
+                self.assertIn('--slot-index', args)
+                self.assertIn('0', args)
+            return _CmdResult(0, fake_sig, b'')
+
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_result):
+            sig = btool.sign(data, module_path, slot_index='0',
+                           key_label='test-key')
+            self.assertEqual(fake_sig, sig)
+
+    def test_pkcs11_tool_sign_success_key_id(self):
+        """Test successful signing with key_id instead of key_label"""
+        btool = Bintool.create('pkcs11_tool')
+        btool.present = True
+        data = b'test data to sign'
+
+        module_path = self._make_module_path()
+
+        fake_sig = b'\x05\x06\x07\x08' * 64
+
+        def fake_run_result(*args, **kwargs):
+            if '--sign' in args:
+                self.assertIn('--id', args)
+                self.assertIn('01', args)
+            return _CmdResult(0, fake_sig, b'')
+
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_result):
+            sig = btool.sign(data, module_path, token_label='test-token',
+                           key_id='01')
+            self.assertEqual(fake_sig, sig)
+
+    def test_pkcs11_tool_sign_success_with_pin(self):
+        """Test successful signing with PIN provided"""
+        btool = Bintool.create('pkcs11_tool')
+        btool.present = True
+        data = b'test data to sign'
+
+        module_path = self._make_module_path()
+
+        fake_sig = b'\x09\x0a\x0b\x0c' * 64
+
+        def fake_run_result(*args, **kwargs):
+            # Verify PIN is in the sign command args (not the mechanism check)
+            if '--sign' in args:
+                self.assertIn('--pin', args)
+                self.assertIn('1234', args)
+            return _CmdResult(0, fake_sig, b'')
+
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_result):
+            sig = btool.sign(data, module_path, token_label='test-token',
+                           key_label='test-key', pin='1234')
+            self.assertEqual(fake_sig, sig)
+
+    def test_pkcs11_tool_sign_token_serial_not_found(self):
+        """Test signing with token_serial when token is not found"""
+        btool = Bintool.create('pkcs11_tool')
+        btool.present = True
+        data = b'test data to sign'
+
+        module_path = self._make_module_path()
+
+        def fake_find_slot(module, serial):
+            return None
+
+        with unittest.mock.patch.object(btool, 'find_slot_by_serial',
+                                       side_effect=fake_find_slot):
+            with self.assertRaises(ValueError) as exc:
+                btool.sign(data, module_path, token_serial='nonexistent',
+                         key_label='test-key')
+            self.assertIn('Token with serial nonexistent not found',
+                         str(exc.exception))
+
+    def test_pkcs11_tool_sign_token_serial_found(self):
+        """Test that a resolved serial is forwarded as slot-index to the sign command"""
+        btool = Bintool.create('pkcs11_tool')
+        btool.present = True
+        data = b'test data to sign'
+        module_path = self._make_module_path()
+        fake_sig = b'\x01\x02\x03\x04' * 64
+
+        def fake_run_result(*args, **kwargs):
+            if '--sign' in args:
+                self.assertIn('--slot-index', args)
+                self.assertIn('0', args)
+            return _CmdResult(0, fake_sig, b'')
+
+        with unittest.mock.patch.object(btool, 'find_slot_by_serial',
+                                        return_value='0'):
+            with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                            side_effect=fake_run_result):
+                sig = btool.sign(data, module_path, token_serial='SN12345',
+                                 key_label='test-key')
+                self.assertEqual(fake_sig, sig)
+
+    def test_pkcs11_tool_build_mechanism(self):
+        """Test dynamic PKCS#11 mechanism name construction"""
+        btool = Bintool.create('pkcs11_tool')
+
+        # RSA PKCS#1 v1.5 combinations — key-size suffix is stripped
+        self.assertEqual('SHA256-RSA-PKCS',
+                         btool._build_mechanism('sha256', 'rsa2048', 'pkcs1v15'))
+        self.assertEqual('SHA384-RSA-PKCS',
+                         btool._build_mechanism('sha384', 'rsa3072', 'pkcs1v15'))
+        self.assertEqual('SHA512-RSA-PKCS',
+                         btool._build_mechanism('sha512', 'rsa4096', 'pkcs1v15'))
+
+        # RSA PSS combinations
+        self.assertEqual('SHA256-RSA-PKCS-PSS',
+                         btool._build_mechanism('sha256', 'rsa2048', 'pss'))
+        self.assertEqual('SHA512-RSA-PKCS-PSS',
+                         btool._build_mechanism('sha512', 'rsa4096', 'pss'))
+
+        # 'pkcs-1.5' alias is normalized to 'pkcs1v15'
+        self.assertEqual('SHA256-RSA-PKCS',
+                         btool._build_mechanism('sha256', 'rsa2048', 'pkcs-1.5'))
+
+        # EC / ECDSA families
+        self.assertEqual('ECDSA-SHA256',
+                         btool._build_mechanism('sha256', 'ec256', 'pkcs1v15'))
+        self.assertEqual('ECDSA-SHA384',
+                         btool._build_mechanism('sha384', 'ecdsa384', 'pkcs1v15'))
+
+        # Previously hard-coded combinations still resolve correctly
+        self.assertEqual('SHA384-RSA-PKCS',
+                         btool._build_mechanism('sha384', 'rsa4096', 'pkcs1v15'))
+
+        # Novel (non-table) combination: any hash works with RSA
+        self.assertEqual('SHA224-RSA-PKCS',
+                         btool._build_mechanism('sha224', 'rsa2048', 'pkcs1v15'))
+
+        # Unknown algorithm family raises ValueError
+        with self.assertRaises(ValueError) as exc:
+            btool._build_mechanism('sha256', 'dsa2048', 'pkcs1v15')
+        self.assertIn('Unsupported signing algorithm', str(exc.exception))
+
+        # sign_algo with no leading letters cannot be parsed by the regex
+        with self.assertRaises(ValueError) as exc:
+            btool._build_mechanism('sha256', '2048rsa', 'pkcs1v15')
+        self.assertIn('Cannot parse signing algorithm', str(exc.exception))
+
+    def test_pkcs11_tool_verify_mechanism(self):
+        """Test mechanism verification against token's allowed mechanisms list"""
+        btool = Bintool.create('pkcs11_tool')
+
+        mechanisms_output = (
+            'Using slot 0 with a present token (0x1)\n'
+            'Supported mechanisms:\n'
+            'SHA256-RSA-PKCS, keySize={512,4096}, hw, sign, verify\n'
+            'SHA384-RSA-PKCS, keySize={512,4096}, hw, sign, verify\n'
+            'SHA256-RSA-PKCS-PSS, keySize={512,4096}, hw, sign, verify\n'
+        )
+
+        def fake_run_ok(*args, **kwargs):
+            return _CmdResult(0, mechanisms_output.encode(), b'')
+
+        # Mechanism present in the list — no error
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_ok):
+            btool._verify_mechanism('SHA256-RSA-PKCS', '/fake/module.so')
+
+        # Mechanism absent from the list — raises ValueError
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_ok):
+            with self.assertRaises(ValueError) as exc:
+                btool._verify_mechanism('SHA512-RSA-PKCS', '/fake/module.so')
+            self.assertIn("not in the token's allowed mechanisms",
+                         str(exc.exception))
+            self.assertIn('SHA512-RSA-PKCS', str(exc.exception))
+
+        # Tool unavailable (returns None) — verification is skipped silently
+        def fake_run_none(*args, **kwargs):
+            return None
+
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_none):
+            btool._verify_mechanism('SHA512-RSA-PKCS', '/fake/module.so')
+
+        # Non-zero exit code — verification is skipped silently
+        def fake_run_error(*args, **kwargs):
+            return _CmdResult(1, b'', b'error')
+
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_error):
+            btool._verify_mechanism('SHA512-RSA-PKCS', '/fake/module.so')
+
+        # Slot index is forwarded to --list-mechanisms
+        received_args = []
+
+        def fake_run_capture(*args, **kwargs):
+            received_args.extend(args)
+            return _CmdResult(0, b'', b'')
+
+        with unittest.mock.patch.object(btool, 'run_cmd_result',
+                                       side_effect=fake_run_capture):
+            btool._verify_mechanism('SHA256-RSA-PKCS', '/fake/module.so',
+                                   slot_index='2')
+        self.assertIn('--slot-index', received_args)
+        self.assertIn('2', received_args)
+
 
 if __name__ == "__main__":
     unittest.main()
Signature · 1 line
2.43.0
#4 lore raw

Re: [PATCH 2/5] binman: Add test for pkcs11_tool sign method

Hi Yan,

Quoted 4 lines · Yan WANG

binman: Add test for pkcs11_tool sign method

Exercise the three new methods added to the pkcs11_tool btool:
sign(), _build_mechanism() and _verify_mechanism().

Patch 1 adds four methods, and this patch also tests find_slot_by_serial(). Please can you squash this into patch 1 so the code and its tests land together? Binman expects full test coverage, and patch 1 on its own leaves the new btool code untested.

Quoted 8 lines

tools/binman/bintool_test.py | 374 +++++++++++++++++++++++++++++++++++++++++++

 1 file changed, 374 insertions(+)

tools/binman/bintool_test.py class TestBintool(unittest.TestCase): · line 373

Quoted 10 lines
tools/binman/bintool_test.py +10 -0
@@ -354,6 +364,370 @@ class TestBintool(unittest.TestCase):
+        # Test finding a slot with matching serial
+        slot_output = """Available slots:
+Slot 0 (0x123): SoftHSM slot ID 0x123
+  token label        : test-token
+  token manufacturer : SoftHSM project
+  token model        : SoftHSM v2
+  token flags        : login required, rng, token initialized, PIN initialized
+  hardware version   : 2.6
+  firmware version   : 2.6
+  Token serial num   : abc123xyz

This doesn't match what pkcs11-tool prints. I ran 'pkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so --list-slots' against a SoftHSM v2.6 install with one initialised token 't1' and one empty slot, and got:

Slot 0 (0x23aea6bb): SoftHSM slot ID 0x23aea6bb
token label : t1
...
firmware version : 2.6
serial num : 4b16583ea3aea6bb
pin min/max : 4/255

The real tool prints 'serial num', not 'token serial num'. So find_slot_by_serial() in patch 1 never matches, and hsm-token-serial cannot work. The test only passes because the sample output was written to fit the parser. Please can you fix the parser and take the test data from real pkcs11-tool output, including the 'pin min/max' line and an uninitialised slot? A token-serial case in the SoftHSM functional test would also catch this.

Also please use ' for strings, rather than " (fix this globally)

tools/binman/bintool_test.py class TestBintool(unittest.TestCase): · line 368

Quoted 7 lines
tools/binman/bintool_test.py +5 -0
@@ -354,6 +364,370 @@ class TestBintool(unittest.TestCase):
+        def fake_run_result(*args, **kwargs):
+            if '--sign' in args:
+                self.assertIn('--slot-index', args)
+                self.assertIn('0', args)
+            return _CmdResult(0, fake_sig, b'')

These checks are weak. assertIn('0', args) passes if '0' appears anywhere in the arguments, and if the --sign call never happens, nothing is checked at all. The same fake result is also returned for --list-mechanisms. So _verify_mechanism() parses the signature bytes as a mechanism list and quietly skips the check. Please can you record the arguments of the sign call, check that it happened, and check pairs directly, e.g. args[args.index('--slot-index') + 1] == '0'? The same applies to the key_id, PIN and token_serial tests. BTW the test should also check that --login is passed.

tools/binman/bintool_test.py class TestBintool(unittest.TestCase): · line 367

Quoted 6 lines
tools/binman/bintool_test.py +4 -0
@@ -354,6 +364,370 @@ class TestBintool(unittest.TestCase):
+        def fake_unlink(path):
+            if 'binman_sign_' in path:
+                raise OSError("Permission denied")
+            return original_unlink(path)

This leaves a binman_sign_*.bin file in /tmp on every run. Please can you record the path in fake_unlink() and remove it with original_unlink() at the end of the test?

Also strings should use ' not " (please fix globally)

tools/binman/bintool_test.py class TestBintool(unittest.TestCase): · line 368

Quoted 7 lines
tools/binman/bintool_test.py +5 -0
@@ -354,6 +364,370 @@ class TestBintool(unittest.TestCase):
+        # Previously hard-coded combinations still resolve correctly
+        self.assertEqual('SHA384-RSA-PKCS',
+                         btool._build_mechanism('sha384', 'rsa4096', 'pkcs1v15'))
+
+        # Novel (non-table) combination: any hash works with RSA

These comments refer to an earlier lookup table that isn't in the tree, so they will confuse readers. Please can you drop the 'previously' and 'non-table' wording? The first case also duplicates the SHA384 and RSA4096 checks above.

Regards,
Simon

author
#5 lore raw

PATCH 3/5 binman: Add HSM signing support to pre-load entry type

In reply to Yan WANG

Extend the pre-load entry type to support signing via hardware security modules (HSM) using PKCS#11. The implementation integrates with the pkcs11_tool btool to perform signing operations.

---
 tools/binman/etype/pre_load.py | 285 +++++++++++++++++++++++++--------
 1 file changed, 214 insertions(+), 71 deletions(-)
tools/binman/etype/pre_load.py +214 -71
index 0d953cb258e..26e2c5eb3be 100644
@@ -2,7 +2,7 @@
 # Copyright (c) 2022 Softathome
 # Written by Philippe Reynes <[email protected]>
 #
-# Entry-type for the global header
+# Entry-type for the global header with file-based and HSM signing support
 #
 
 import os
@@ -22,9 +22,9 @@ from Cryptodome.Signature import pss
 PRE_LOAD_MAGIC = b'UBSH'
 
 RSAS = {
-    'rsa1024': 1024 / 8,
-    'rsa2048': 2048 / 8,
-    'rsa4096': 4096 / 8
+    'rsa1024': 1024 // 8,
+    'rsa2048': 2048 // 8,
+    'rsa4096': 4096 // 8
 }
 
 SHAS = {
@@ -33,8 +33,9 @@ SHAS = {
     'sha512': SHA512
 }
 
+
 class Entry_pre_load(Entry_collection):
-    """Pre load image header
+    """Pre load image header with file-based or HSM signing support
 
     Properties / Entry arguments:
         - pre-load-key-path: Path of the directory that store key (provided by
@@ -46,29 +47,57 @@ class Entry_pre_load(Entry_collection):
         - 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.
+    HSM Signing Properties (optional):
+        - hsm-support: Enable HSM signing (boolean)
+        - hsm-library: Path to PKCS#11 library (.so file)
+        - hsm-token-label: HSM token label
+        - hsm-token-serial: HSM token serial number (alternative to token-label)
+        - hsm-key-label: HSM private key label
+        - hsm-key-id: HSM private key ID (alternative to key-label)
+        - hsm-pin: HSM user PIN
+
+    This entry creates a pre-load header that contains a global image signature.
+    The signature can be created using either a traditional RSA key file or a
+    Hardware Security Module (HSM) via PKCS#11.
 
-    For example, this creates an image with a pre-load header and a binary::
+    Example with file-based signing::
 
         binman {
-            image2 {
-                filename = "sandbox.bin";
-
-                pre-load {
-                    content = <&image>;
-                    algo-name = "sha256,rsa2048";
-                    padding-name = "pss";
-                    key-name = "private.pem";
-                    header-size = <4096>;
-                    version = <1>;
-                };
-
-                image: blob-ext {
-                    filename = "sandbox.itb";
-                };
+            pre-load {
+                content = <&image>;
+                algo-name = "sha256,rsa2048";
+                padding-name = "pss";
+                key-name = "private.pem";
+                header-size = <4096>;
+                version = <1>;
+            };
+
+            image: blob-ext {
+                filename = "sandbox.itb";
+            };
+        };
+
+    Example with HSM signing (SoftHSM)::
+
+        binman {
+            pre-load {
+                content = <&image>;
+                algo-name = "sha256,rsa2048";
+                padding-name = "pss";
+                header-size = <4096>;
+                version = <1>;
+                hsm-support;
+                hsm-library = "/usr/lib/softhsm/libsofthsm2.so";
+                hsm-token-label = "uboot-hsm";
+                hsm-key-label = "uboot-key";
+                hsm-pin = "1234";
+            };
+
+            image: blob-ext {
+                filename = "sandbox.itb";
             };
         };
+
     """
 
     def __init__(self, section, etype, node):
@@ -79,6 +108,19 @@ 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)
+        self.hsm_support = fdt_util.GetBool(self._node, 'hsm-support', False)
+        self.hsm_library = fdt_util.GetString(self._node, 'hsm-library')
+        self.hsm_token_label = fdt_util.GetString(self._node, 'hsm-token-label')
+        self.hsm_token_serial = fdt_util.GetString(self._node, 'hsm-token-serial')
+        self.hsm_slot_index = fdt_util.GetString(self._node, 'hsm-slot-index')
+        self.hsm_key_label = fdt_util.GetString(self._node, 'hsm-key-label')
+        self.hsm_key_id = fdt_util.GetString(self._node, 'hsm-key-id')
+        self.hsm_pin = fdt_util.GetString(self._node, 'hsm-pin')
+
+        # Will be set in AddBintools if HSM is used
+        self.pkcs11_tool = None
+
     def ReadNode(self):
         super().ReadNode()
         self.key_path, = self.GetEntryArgsOrProps(
@@ -86,68 +128,169 @@ class Entry_pre_load(Entry_collection):
         if self.key_path is None:
             self.key_path = ''
 
-    def _CreateHeader(self):
-        """Create a pre load header"""
+    def AddBintools(self, btools):
+        """Add required btools
+
+        Register pkcs11-tool btool if HSM signing is enabled.
+        """
+        super().AddBintools(btools)
+        if self.hsm_support:
+            self.pkcs11_tool = self.AddBintool(btools, 'pkcs11_tool')
+
+    def _SignData(self, data):
+        """Sign data using either file-based key or HSM
+
+        This method provides a unified interface for signing data regardless
+        of whether a traditional RSA key file or an HSM is used. The signing
+        backend is selected based on the hsm-support property.
+
+        Args:
+            data (bytes): Data to sign
+
+        Returns:
+            bytes: Signature
+
+        Raises:
+            ValueError: If configuration is invalid
+            RuntimeError: If signing operation fails
+        """
         hash_name, sign_name = self.algo_name.split(',')
-        padding_name = self.padding_name
-        key_name = os.path.join(self.key_path, self.key_name)
-
-        # Check hash and signature name/type
-        if hash_name not in SHAS:
-            self.Raise(hash_name + " is not supported")
-        if sign_name not in RSAS:
-            self.Raise(sign_name + " is not supported")
-
-        # Read the key
-        key = RSA.import_key(tools.read_file(key_name))
-
-        # Check if the key has the expected size
-        if key.size_in_bytes() != RSAS[sign_name]:
-            self.Raise("The key " + self.key_name + " don'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
-        if padding_name == "pss":
-            salt_len = key.size_in_bytes() - hash_image.digest_size - 2
-            padding = pss
-            padding_args = {'salt_bytes': salt_len}
-        elif padding_name == "pkcs-1.5":
-            padding = pkcs1_15
-            padding_args = {}
+        padding_name = self.padding_name or 'pkcs-1.5'
+        padding_btool = None
+
+        if self.hsm_support:
+            # HSM-based signing via pkcs11-tool btool
+            if not self.pkcs11_tool.is_present():
+                self.Raise("pkcs11-tool btool not available for HSM signing")
+
+            if not self.hsm_library:
+                self.Raise("hsm-library is required for HSM signing")
+
+            # Normalize padding name for btool
+            if padding_name == 'pss':
+                padding_btool = 'pss'
+            elif padding_name == 'pkcs-1.5':
+                padding_btool = 'pkcs1v15'
+            else:
+                self.Raise(f"Unsupported padding scheme: {padding_name}")
+
+            # Use slot index if provided (simpler than serial lookup)
+            try:
+                signature = self.pkcs11_tool.sign(
+                    data=data,
+                    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=hash_name,
+                    sign_algo=sign_name,
+                    padding=padding_btool
+                )
+            except (ValueError, RuntimeError) as e:
+                self.Raise(f"HSM signing failed: {e}")
+
         else:
-            self.Raise(padding_name + " is not supported")
+            # File-based signing (traditional method)
+            if not self.key_name:
+                self.Raise("key-name is required for file-based signing")
+
+            key_name = os.path.join(self.key_path, self.key_name)
+
+            # Check hash and signature name/type
+            if hash_name not in SHAS:
+                self.Raise(f"{hash_name} is not supported")
+            if sign_name not in RSAS:
+                self.Raise(f"{sign_name} is not supported")
+
+            # Read the key
+            key = RSA.import_key(tools.read_file(key_name))
+
+            # Check if the key has the expected size
+            if key.size_in_bytes() != RSAS[sign_name]:
+                self.Raise(
+                    f"The key {self.key_name} doesn't have the expected size "
+                    f"({key.size_in_bytes()} bytes vs expected "
+                    f"{RSAS[sign_name]} bytes)"
+                )
 
-        sig = padding.new(key, **padding_args).sign(hash_image)
+            # Compute the hash
+            hash_obj = SHAS[hash_name].new()
+            hash_obj.update(data)
 
-        hash_sig = SHA256.new()
-        hash_sig.update(sig)
+            # Setup padding
+            padding_module = None
+            padding_args = {}
+            if padding_name == "pss":
+                salt_len = key.size_in_bytes() - hash_obj.digest_size - 2
+                padding_module = pss
+                padding_args = {'salt_bytes': salt_len}
+            elif padding_name == "pkcs-1.5":
+                padding_module = pkcs1_15
+                padding_args = {}
+            else:
+                self.Raise(f"{padding_name} is not supported")
+
+            # Sign
+            signature = padding_module.new(key, **padding_args).sign(hash_obj)
+
+        return signature
+
+    def _CreateHeader(self):
+        """Create a pre-load header with signature
 
+        This method creates the pre-load header regardless of whether signing
+        is done via file-based keys or HSM. The signing backend is abstracted
+        in _SignData(), eliminating code duplication.
+
+        The header format is:
+        - First header (64 bytes): magic, version, sizes, hash of image signature
+        - Header signature (variable): signature of first header
+        - Image signature (variable): signature of image data
+        - Padding: zeros to fill header_size
+
+        Returns:
+            bytes: Complete pre-load header with padding
+        """
+        # Sign the image data
+        img_sig = self._SignData(self.image)
+
+        # Compute hash of image signature (always SHA256 for header)
+        hash_sig = SHA256.new(img_sig)
+
+        # Build header fields
         version = self.version
         header_size = self.header_size
         image_size = len(self.image)
-        ofs_img_sig = 64 + len(sig)
+        ofs_img_sig = 64 + len(img_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())
+        # Pack first header (64 bytes, big-endian)
+        first_header = struct.pack(
+            '>4sIIIIIII32s',
+            PRE_LOAD_MAGIC,      # 4 bytes: magic number 'UBSH'
+            version,             # 4 bytes: header version
+            header_size,         # 4 bytes: total header size
+            image_size,          # 4 bytes: image size
+            ofs_img_sig,         # 4 bytes: offset to image signature
+            flags,               # 4 bytes: flags (reserved)
+            reserved0,           # 4 bytes: reserved
+            reserved1,           # 4 bytes: reserved
+            hash_sig.digest()    # 32 bytes: SHA256 hash of image signature
+        )
+
+        # Sign the header
+        hdr_sig = self._SignData(first_header)
 
-        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)
+        # Assemble complete header: first_header + header_sig + image_sig
+        data = first_header + hdr_sig + img_sig
 
-        data = first_header + sig_first_header + sig
-        pad  = bytearray(self.header_size - len(data))
+        # Add padding to reach header_size
+        pad = bytearray(self.header_size - len(data))
 
         return data + pad
 
Signature · 1 line
2.43.0
#6 lore raw

Hi Yan,

Quoted 5 lines · Yan WANG

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

Extend the pre-load entry type to support signing via hardware security modules (HSM) using PKCS#11. The implementation integrates with the pkcs11_tool btool to perform signing operations.

This patch does much more than the commit message says. It:

- moves the signing code into a new _SignData() helper
- changes / to // in RSAS
- rewrites the error messages
- converts strings to f-strings
- reformats the struct.pack() call
- drops the image2 wrapper from the docstring example

Please can you put the refactoring (extracting _SignData() with no functional change) in its own patch ahead of this one, so this patch only adds the HSM path? Please also list the new properties in the commit message and say why someone would want this, e.g. so that production keys never have to sit on the build machine.

Quoted 8 lines

tools/binman/etype/pre_load.py | 285 +++++++++++++++++++++++++++++++----------

 1 file changed, 214 insertions(+), 71 deletions(-)

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

Quoted 8 lines
tools/binman/etype/pre_load.py +8 -0
@@ -46,29 +47,57 @@ class Entry_pre_load(Entry_collection):
+    HSM Signing Properties (optional):
+        - hsm-support: Enable HSM signing (boolean)
+        - hsm-library: Path to PKCS#11 library (.so file)
+        - hsm-token-label: HSM token label
+        - hsm-token-serial: HSM token serial number (alternative to token-label)
+        - hsm-key-label: HSM private key label
+        - hsm-key-id: HSM private key ID (alternative to key-label)
+        - hsm-pin: HSM user PIN

The code also reads hsm-slot-index, but it isn't documented here. Please add it, and say which of label/serial/slot takes priority when more than one is given.

Is hsm-support needed at all? The HSM path could be selected whenever hsm-library is present. That would also remove the 'hsm-library is required' error case.

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

Quoted 3 lines
tools/binman/etype/pre_load.py +1 -0
@@ -79,6 +108,19 @@ class Entry_pre_load(Entry_collection):
+        self.hsm_slot_index = fdt_util.GetString(self._node, 'hsm-slot-index')

A slot index is naturally an integer. With 'hsm-slot-index = <0>;', GetString() returns something strange rather than giving a clear error. I suggest using GetInt() and converting with str() when building the pkcs11-tool arguments.

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

Quoted 3 lines
tools/binman/etype/pre_load.py +1 -0
@@ -79,6 +108,19 @@ class Entry_pre_load(Entry_collection):
+        self.hsm_pin = fdt_util.GetString(self._node, 'hsm-pin')

My main concern with the design is the PIN in the devicetree. The binman description normally lives in the U-Boot source tree (the -u-boot.dtsi files), so this pushes people towards committing a token PIN to git. The PIN also ends up in the binman output DTB and the fdtmap (if present). FIT signing with PKCS#11 already avoids this:
mkimage reads the PIN from the MKIMAGE_SIGN_PIN environment variable, as used by testFitSignPKCS11Simple and friends in ftest.py. Please can you take the PIN from an entry argument (e.g. -a pre-load-hsm-pin=...) or the environment, like pre-load-key-path? Ideally the PIN should not be accepted as a DT property at all.

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

Quoted 6 lines
tools/binman/etype/pre_load.py +4 -0
@@ -86,68 +128,169 @@ class Entry_pre_load(Entry_collection):
+        if self.hsm_support:
+            # HSM-based signing via pkcs11-tool btool
+            if not self.pkcs11_tool.is_present():
+                self.Raise("pkcs11-tool btool not available for HSM signing")

Other etypes (mkimage, x509_cert, fit, etc.) call self.record_missing_bintool() here. That way --allow-missing / --fake-ext-blobs keeps working and binman reports the missing tool in the usual way. Please follow that pattern: record the tool as missing and write a dummy header rather than raising.

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

Quoted 5 lines
tools/binman/etype/pre_load.py +3 -0
@@ -86,68 +128,169 @@ class Entry_pre_load(Entry_collection):
+            # Use slot index if provided (simpler than serial lookup)
+            try:
+                signature = self.pkcs11_tool.sign(

The comment doesn't match the code. The code passes all the identifiers through and leaves the choice to sign().

More importantly, the HSM path skips the hash_name/sign_name checks against SHAS and RSAS, and doesn't check the size of the returned signature. U-Boot's image_pre_load_sig_check_header_sig() and image_pre_load_sig_check_img_sig_sha256() read info->sig_size bytes, which come from the verifying key, not the length binman used. So if algo-name says rsa2048 but the HSM key is 4096 bits, binman happily produces a header that can never verify. Equally, 'sha256,ec256' gets through to _build_mechanism() and produces an ECDSA signature, which this entry doesn't otherwise support. Please do the SHAS/RSAS checks for both paths, before the if, and check that len(signature) == RSAS[sign_name] after signing.

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

Quoted 7 lines
tools/binman/etype/pre_load.py +5 -0
@@ -86,68 +128,169 @@ class Entry_pre_load(Entry_collection):
+        # Sign the image data
+        img_sig = self._SignData(self.image)
+
+        # Compute hash of image signature (always SHA256 for header)
+        hash_sig = SHA256.new(img_sig)

On the HSM path, each _SignData() call runs pkcs11-tool three times (--list-slots, --list-mechanisms, --sign), and we sign twice per header. Binman can also call _CreateHeader() several times as entries settle (ObtainContents() and ProcessContents()). That adds up to quite a few logins to a real HSM, which may be slow or rate-limited. Not a blocker, but it might be worth resolving the slot and checking the mechanism once, then caching the result. What do you think?

Quoted 5 lines
tools/binman/etype/pre_load.py +3 -0
@@ -86,68 +128,169 @@ class Entry_pre_load(Entry_collection):
+        # Pack first header (64 bytes, big-endian)
+        first_header = struct.pack(
+            '>4sIIIIIII32s',

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

Quoted 10 lines
tools/binman/etype/pre_load.py +10 -0
+            PRE_LOAD_MAGIC,      # 4 bytes: magic number 'UBSH'
+            version,             # 4 bytes: header version
+            header_size,         # 4 bytes: total header size
+            image_size,          # 4 bytes: image size
+            ofs_img_sig,         # 4 bytes: offset to image signature
+            flags,               # 4 bytes: flags (reserved)
+            reserved0,           # 4 bytes: reserved
+            reserved1,           # 4 bytes: reserved
+            hash_sig.digest()    # 32 bytes: SHA256 hash of image signature
+        )

This only reformats the existing code. Please drop it, or move it into the refactoring patch.

Regards,
Simon

author
#7 lore raw

PATCH 4/5 binman: test: Add SoftHSM functional test for pre-load HSM signing

In reply to Yan WANG

Add testPreLoadHsmSign, a functional test that exercises end-to-end pre-load header signing using SoftHSM as a PKCS#11 token.

---
 tools/binman/ftest.py                         | 64 +++++++++++++++++
 .../test/security/pre_load_hsm_sign.dts       | 68 +++++++++++++++++++
 2 files changed, 132 insertions(+)
 create mode 100644 tools/binman/test/security/pre_load_hsm_sign.dts
tools/binman/ftest.py +64 -0
index 2fb452b4e46..329b91dfd06 100644
@@ -5931,6 +5931,70 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
         self.assertEqual(PRE_LOAD_HDR_SIZE, data[8:8 + len(PRE_LOAD_HDR_SIZE)])
         self.assertEqual(is_signed, True)
 
+    def testPreLoadHsmSign(self):
+        """Test an image with a pre-load header signed using HSM (SoftHSM)"""
+        # Check for required bintools
+        softhsm2_util = bintool.Bintool.create('softhsm2_util')
+        self._CheckBintool(softhsm2_util)
+
+        pkcs11_tool = bintool.Bintool.create('pkcs11-tool')
+        self._CheckBintool(pkcs11_tool)
+
+        # Place holder of public key file
+        public_key = self._MakeInputFile("public.key", b"")
+        pubkey_der = self._MakeInputFile("pubkey.der", b"")
+
+        # Create AES key for FIT encryption (required by pre_load_hsm_sign.dts)
+        # Put it in a subdirectory to avoid polluting the main input directory
+        data = tools.read_file(self.TestFile("fit/aes256.bin"))
+        self._MakeInputFile("hsm_keys/aes256.bin", data)
+
+        prefix = "testPreLoadHsmSign."
+
+        # Configure SoftHSMv2
+        data = tools.read_file(self.TestFile('fit/softhsm2.conf'))
+        softhsm2_conf = self._MakeInputFile(f'{prefix}softhsm2.conf', 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')
+
+        # Set up HSM environment and build image
+        with unittest.mock.patch.dict('os.environ',
+                                      {'SOFTHSM2_CONF': softhsm2_conf}):
+            # Initialize token
+            softhsm2_util.run_cmd('--init-token', '--free', '--label',
+                                  'uboot-hsm', '--pin', '1234',
+                                  '--so-pin', '1234')
+
+            # Generate key pair directly in SoftHSM
+            pkcs11_tool.run_cmd('--module', '/usr/lib/softhsm/libsofthsm2.so',
+                                '--keypairgen', '--key-type', 'rsa:2048',
+                                '--label', 'uboot-key', '--login', '--pin', '1234')
+
+            # Extract public key from SoftHSM
+            pkcs11_tool.run_cmd('--module', '/usr/lib/softhsm/libsofthsm2.so',
+                                '--read-object', '--type', 'pubkey',
+                                '--label', 'uboot-key', '--login', '--pin', '1234',
+                                '--output-file', pubkey_der)
+            tools.run('openssl', 'rsa', '-pubin', '-inform', 'DER',
+                      '-in', pubkey_der, '-out', public_key)
+
+            # Build image with HSM signing
+            hsm_keys_subdir = os.path.join(self._indir, "hsm_keys")
+            data = self._DoReadFileDtb('security/pre_load_hsm_sign.dts',
+                                       use_expanded=True,
+                                       extra_indirs=[hsm_keys_subdir])[0]
+
+        image_fname = tools.get_output_filename('image.bin')
+        is_signed = self._CheckPreload(image_fname, public_key)
+        # Verify pre-load header structure
+        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.assertEqual(is_signed, True)
+
+
     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_sign.dts new file +68 -0

68 lines not on this page · raw message

Signature · 1 line
2.43.0
#8 lore raw

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

Hi Yan,

Quoted 1 line · Yan WANG

binman: test: Add SoftHSM functional test for pre-load HSM signing

This subject is almost the same as the one for patch 5, so the two are hard to tell apart. Binman expects full test coverage for each feature. Please can you fold this patch and patch 5 into patch 3, so the HSM support arrives with its tests? If you keep them separate, please add a short paragraph on what the test sets up: a SoftHSM token, a key generated on the token, and a signature check with preload_check_sign.

Quoted 12 lines

Add testPreLoadHsmSign, a functional test that exercises end-to-end pre-load header signing using SoftHSM as a PKCS#11 token.

tools/binman/ftest.py | 64 ++++++++++++++++++++++

 tools/binman/test/security/pre_load_hsm_sign.dts | 68 ++++++++++++++++++++++++
 2 files changed, 132 insertions(+)

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5934

Quoted 4 lines
tools/binman/ftest.py +4 -0
@@ -5931,6 +5931,70 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+            # Generate key pair directly in SoftHSM
+            pkcs11_tool.run_cmd('--module', '/usr/lib/softhsm/libsofthsm2.so',
+                                '--keypairgen', '--key-type', 'rsa:2048',
+                                '--label', 'uboot-key', '--login', '--pin', '1234')

The library path is hard-coded here and in pre_load_hsm_sign.dts. That path is Debian/Ubuntu-specific. Fedora uses /usr/lib64/pkcs11/libsofthsm2.so, and Arch uses /usr/lib/softhsm/libsofthsm2.so via a different package. On those hosts softhsm2-util and pkcs11-tool are present, so the test fails rather than skipping, because sign() raises 'PKCS#11 module not found'. testPkcs11SignedCapsuleGen already finds the library with 'p11-kit print-config'. Please can you do the same here and pass the path into the image rather than putting it in the dts? For example, hsm-library could come from an entry arg via GetEntryArgsOrProps(), as pre-load-key-path does. That would also help real users, since the library location is a host detail that doesn't belong in the board's devicetree.

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5933

Quoted 5 lines
tools/binman/ftest.py +3 -0
@@ -5931,6 +5931,70 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+        # Place holder of public key file
+        public_key = self._MakeInputFile("public.key", b"")
+        pubkey_der = self._MakeInputFile("pubkey.der", b"")

There is no need to create empty files just to get a path:
os.path.join(self._indir, ...) or tools.get_output_filename() is enough.

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5932

Quoted 4 lines
tools/binman/ftest.py +2 -0
@@ -5931,6 +5931,70 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+            tools.run('openssl', 'rsa', '-pubin', '-inform', 'DER',
+                      '-in', pubkey_der, '-out', public_key)

Please use the openssl bintool and call _CheckBintool() on it, as testPkcs11SignedCapsuleGen does, so the test skips cleanly if openssl is missing.

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5934

Quoted 6 lines
tools/binman/ftest.py +4 -0
@@ -5931,6 +5931,70 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+        # Create AES key for FIT encryption (required by pre_load_hsm_sign.dts)
+        # Put it in a subdirectory to avoid polluting the main input directory
+        data = tools.read_file(self.TestFile("fit/aes256.bin"))
+        self._MakeInputFile("hsm_keys/aes256.bin", data)

Just to check, why use an encrypted FIT here? It looks copied from testPreLoadEncryptedFit, but FIT encryption has nothing to do with HSM signing. With a plain blob or u-boot entry as the content, you could drop the AES key, the subdirectory and extra_indirs, and the test would be easier to follow.

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5932

Quoted 4 lines
tools/binman/ftest.py +2 -0
@@ -5931,6 +5931,70 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+        image_fname = tools.get_output_filename('image.bin')
+        is_signed = self._CheckPreload(image_fname, public_key)

This only covers pkcs-1.5. The HSM path has its own padding mapping, and with PSS, pkcs11-tool chooses the salt length rather than binman. Please can you also cover PSS, with padding-name = "pss" in the dts and padding='pss' passed to _CheckPreload()? A second dts would do, or a parameterised helper.

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5933

Quoted 5 lines
tools/binman/ftest.py +3 -0
@@ -5931,6 +5931,70 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+        self.assertEqual(is_signed, True)
+
+

This leaves two blank lines between methods. Please drop one.

Regards,
Simon

author
#9 lore raw

PATCH 5/5 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.

---
 tools/binman/ftest.py                         | 76 +++++++++++++++++++
 .../security/pre_load_default_padding.dts     | 23 ++++++
 .../security/pre_load_hsm_invalid_padding.dts | 27 +++++++
 .../security/pre_load_hsm_missing_library.dts | 27 +++++++
 .../security/pre_load_hsm_missing_tool.dts    | 27 +++++++
 .../security/pre_load_missing_key_name.dts    | 23 ++++++
 6 files changed, 203 insertions(+)
 create mode 100644 tools/binman/test/security/pre_load_default_padding.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_invalid_padding.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_missing_library.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_missing_tool.dts
 create mode 100644 tools/binman/test/security/pre_load_missing_key_name.dts
tools/binman/ftest.py +76 -0
index 329b91dfd06..e76a8042f4c 100644
@@ -5994,6 +5994,82 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
         self.assertEqual(PRE_LOAD_HDR_SIZE, data[8:8 + len(PRE_LOAD_HDR_SIZE)])
         self.assertEqual(is_signed, True)
 
+    def testPreLoadHsmMissingLibrary(self):
+        """Test HSM signing with missing hsm-library property"""
+        with self.assertRaises(ValueError) as exc:
+            self._DoReadFile('security/pre_load_hsm_missing_library.dts')
+        self.assertIn('hsm-library is required for HSM signing',
+                      str(exc.exception))
+
+    def testPreLoadHsmInvalidPadding(self):
+        """Test HSM signing with invalid padding"""
+        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 HSM signing when pkcs11_tool is not available"""
+        try:
+            with self.assertRaises(ValueError) as exc:
+                self._DoTestFile('security/pre_load_hsm_missing_tool.dts',
+                             force_missing_bintools='pkcs11-tool')
+            self.assertIn('pkcs11-tool btool not available', str(exc.exception))
+        finally:
+            bintool.Bintool.set_missing_list(None)
+
+    def testPreLoadHsmSignError(self):
+        """Test HSM signing with pkcs11-tool ValueError"""
+        from binman.btool import pkcs11_tool
+
+        def mock_sign_value_error(*args, **kwargs):
+            raise ValueError("Mock HSM error")
+
+        with unittest.mock.patch.object(pkcs11_tool.Bintoolpkcs11_tool, 'is_present',
+                                       return_value=True):
+            with unittest.mock.patch.object(pkcs11_tool.Bintoolpkcs11_tool, 'sign',
+                                           side_effect=mock_sign_value_error):
+                with self.assertRaises(ValueError) as exc:
+                    self._DoReadFile('security/pre_load_hsm_missing_tool.dts')
+                self.assertIn('HSM signing failed', str(exc.exception))
+
+    def testPreLoadHsmSignRuntimeError(self):
+        """Test HSM signing with pkcs11-tool RuntimeError"""
+        from binman.btool import pkcs11_tool
+
+        def mock_sign_runtime_error(*args, **kwargs):
+            raise RuntimeError("Mock HSM runtime error")
+
+        with unittest.mock.patch.object(pkcs11_tool.Bintoolpkcs11_tool, 'is_present',
+                                       return_value=True):
+            with unittest.mock.patch.object(pkcs11_tool.Bintoolpkcs11_tool, 'sign',
+                                           side_effect=mock_sign_runtime_error):
+                with self.assertRaises(ValueError) as exc:
+                    self._DoReadFile('security/pre_load_hsm_missing_tool.dts')
+                self.assertIn('HSM signing failed', 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 testPreLoadDefaultPadding(self):
+        """Test pre-load with no padding-name (should default to pkcs-1.5)"""
+        entry_args = {
+            'pre-load-key-path': os.path.join(self._binman_dir, 'test'),
+        }
+        data = self._DoReadFileDtb('security/pre_load_default_padding.dts',
+                                   entry_args=entry_args,
+                                   extra_indirs=[os.path.join(self._binman_dir, 'test')])[0]
+        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)])
+
 
     def _CheckSafeUniqueNames(self, *images):
         """Check all entries of given images for unsafe unique names"""
tools/binman/test/security/pre_load_default_padding.dts new file +23 -0
new file mode 100644
index 00000000000..2263df72a25
@@ -0,0 +1,23 @@
+// 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 intentionally omitted to test default */
+			key-name = "dev.key";
+			header-size = <4096>;
+			version = <0x11223344>;
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_hsm_invalid_padding.dts new file +27 -0
new file mode 100644
index 00000000000..3e735e545a9
@@ -0,0 +1,27 @@
+// 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-padding";
+			header-size = <4096>;
+			version = <1>;
+			hsm-support;
+			hsm-library = "/usr/lib/softhsm/libsofthsm2.so";
+			hsm-token-label = "uboot-hsm";
+			hsm-key-label = "uboot-key";
+			hsm-pin = "1234";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_hsm_missing_library.dts new file +27 -0
new file mode 100644
index 00000000000..34dfd16c163
@@ -0,0 +1,27 @@
+// 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-support;
+			/* hsm-library intentionally missing to test error */
+			hsm-token-label = "uboot-hsm";
+			hsm-key-label = "uboot-key";
+			hsm-pin = "1234";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_hsm_missing_tool.dts new file +27 -0
new file mode 100644
index 00000000000..451429688fe
@@ -0,0 +1,27 @@
+// 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-support;
+			hsm-library = "/usr/lib/softhsm/libsofthsm2.so";
+			hsm-token-label = "uboot-hsm";
+			hsm-key-label = "uboot-key";
+			hsm-pin = "1234";
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
tools/binman/test/security/pre_load_missing_key_name.dts new file +23 -0
new file mode 100644
index 00000000000..b83fa817b0b
@@ -0,0 +1,23 @@
+// 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 = "pkcs-1.5";
+			/* key-name intentionally missing for file-based signing */
+			header-size = <4096>;
+			version = <1>;
+		};
+
+		image: blob-ext {
+			filename = "refcode.bin";
+		};
+	};
+};
Signature · 1 line
2.43.0
#10 lore raw

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

Hi Yan,

Quoted 6 lines · Yan WANG

binman: Add functional test for pre-load HSM signing

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.

This describes patch 4. This patch adds error-path tests and a couple of file-based tests, and none of them signs anything with an HSM. Please can you rewrite the subject and message to say what this patch adds, e.g. 'binman: test: Add error-path tests for pre-load signing'? The missing key-name test is about the file-based path, so it belongs in the refactoring patch suggested on patch 3.

Quoted 15 lines

tools/binman/ftest.py | 76 ++++++++++++++++++++++

 .../test/security/pre_load_default_padding.dts     | 23 +++++++
 .../test/security/pre_load_hsm_invalid_padding.dts | 27 ++++++++
 .../test/security/pre_load_hsm_missing_library.dts | 27 ++++++++
 .../test/security/pre_load_hsm_missing_tool.dts    | 27 ++++++++
 .../test/security/pre_load_missing_key_name.dts    | 23 +++++++
 6 files changed, 203 insertions(+)
tools/binman/ftest.py +2 -0
@@ -5994,6 +5994,82 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+    def testPreLoadHsmMissingLibrary(self):
+        """Test HSM signing with missing hsm-library property"""

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 6005

Quoted 10 lines
tools/binman/ftest.py +10 -0
+        with self.assertRaises(ValueError) as exc:
+            self._DoReadFile('security/pre_load_hsm_missing_library.dts')
+        self.assertIn('hsm-library is required for HSM signing',
+                      str(exc.exception))
+
+    def testPreLoadHsmInvalidPadding(self):
+        """Test HSM signing with invalid padding"""
+        with self.assertRaises(ValueError) as exc:
+            self._DoReadFile('security/pre_load_hsm_invalid_padding.dts')
+        self.assertIn('Unsupported padding scheme', str(exc.exception))

In _SignData(), the pkcs11_tool.is_present() check runs before the hsm-library and padding checks. So on a machine without pkcs11-tool, both tests get 'pkcs11-tool btool not available' and fail, but the binman tests have to pass on a plain build host. I suggest moving the config checks in patch 3 ahead of the tool check. Better still, do them in ReadNode() so a bad DT fails early. Otherwise these tests need to mock is_present(), as the later ones do.

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 6002

Quoted 11 lines
tools/binman/ftest.py +9 -0
@@ -5994,6 +5994,82 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+    def testPreLoadHsmMissingTool(self):
+        """Test HSM signing when pkcs11_tool is not available"""
+        try:
+            with self.assertRaises(ValueError) as exc:
+                self._DoTestFile('security/pre_load_hsm_missing_tool.dts',
+                             force_missing_bintools='pkcs11-tool')
+            self.assertIn('pkcs11-tool btool not available', str(exc.exception))
+        finally:
+            bintool.Bintool.set_missing_list(None)

This bakes in patch 3's behaviour of raising an error when the tool is missing. Other etypes (fit, mkimage, gbb, efi_capsule) produce fake data instead, so -M lets the build complete and binman reports the missing tool at the end. Once pre_load does the same, please change this test to match the existing missing-tool tests, e.g. the futility one in testGbbMissing.

The try/finally isn't needed, since control.Binman() calls set_missing_list() on every run and the other force_missing_bintools tests don't reset it. Also, the continuation line isn't aligned with the open parenthesis.

Quoted 6 lines
tools/binman/ftest.py +4 -0
@@ -5994,6 +5994,82 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+    def testPreLoadHsmSignError(self):
+        """Test HSM signing with pkcs11-tool ValueError"""
+        from binman.btool import pkcs11_tool
+

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 6007

Quoted 10 lines
tools/binman/ftest.py +10 -0
+        def mock_sign_value_error(*args, **kwargs):
+            raise ValueError("Mock HSM error")
+
+        with unittest.mock.patch.object(pkcs11_tool.Bintoolpkcs11_tool, 'is_present',
+                                       return_value=True):
+            with unittest.mock.patch.object(pkcs11_tool.Bintoolpkcs11_tool, 'sign',
+                                           side_effect=mock_sign_value_error):
+                with self.assertRaises(ValueError) as exc:
+                    self._DoReadFile('security/pre_load_hsm_missing_tool.dts')
+                self.assertIn('HSM signing failed', str(exc.exception))

This test and testPreLoadHsmSignRuntimeError differ only in the exception type. Please can you merge them into one test that loops over (ValueError, RuntimeError)? You can pass side_effect=ValueError('Mock HSM error') directly, without the nested function, and a single 'with' statement can apply both patches.

Please move the import to the top of the file with the others. Please also rename pre_load_hsm_missing_tool.dts to something generic like pre_load_hsm.dts, since several tests use it and only one is about a missing tool. The patch.object() lines also go over 80 columns.

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 6001

Quoted 10 lines
tools/binman/ftest.py +8 -0
@@ -5994,6 +5994,82 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+    def testPreLoadDefaultPadding(self):
+        """Test pre-load with no padding-name (should default to pkcs-1.5)"""
+        entry_args = {
+            'pre-load-key-path': os.path.join(self._binman_dir, 'test'),
+        }
+        data = self._DoReadFileDtb('security/pre_load_default_padding.dts',
+                                   entry_args=entry_args,
+                                   extra_indirs=[os.path.join(self._binman_dir, 'test')])[0]

This duplicates testPreLoad. pre_load.dts already omits padding-name, and testPreLoad checks the result with _CheckPreload(), whose default padding is pkcs-1.5. This version only checks the header fields, so it wouldn't notice the wrong padding. Please can you drop this test and pre_load_default_padding.dts?

Regards,
Simon

#11 lore raw
In reply to Yan WANG

Hi Yan,

Quoted 3 lines · Yan WANG

The implementation builds on the existing pkcs11_tool btool: a sign() method is added that drives pkcs11-tool to perform the actual cryptographic operation.

Binman can already describe a PKCS#11 key for FIT signing: fit,engine set to pkcs11, with fit,engine-keydir and key-name-hint, which become a pkcs11: URI. This series adds a second scheme of eight properties that works quite differently. It would be better for users if pre-load followed the FIT conventions, e.g. a single PKCS#11 URI property for the token and key plus the module path. Then both entry types would be configured the same way. What do you think?

Regards,
Simon

author
#12 lore raw

v2 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 functional tests use SoftHSM.

Changes in v2:
- Merge the unit tests into the pkcs11_tool patch and the functional tests into a single patch (5 patches become 4)
- Replace the eight hsm-* devicetree properties with one hsm-key PKCS#11 URI
- Keep the PIN and library path out of the devicetree
- Pass the PIN to pkcs11-tool through the environment, not argv
- Read the signature from an output file instead of stdout
- Add ECDSA support, with a host-hash fallback for tokens such as SoftHSM
- Split the integer division and key-name fixes into their own patch
- Check the length of the returned signature
- Extend the tests: PSS, ECDSA and many error paths

yan wang (4):
binman: bintool: Add PKCS#11 HSM signing support
binman: pre_load: Validate file signing key
binman: pre_load: Add HSM signing support to pre-load entry type
binman: Add functional test for pre-load HSM signing

 tools/binman/bintool.py                       |   8 +-
 tools/binman/bintool_test.py                  | 497 ++++++++++++++++++
 tools/binman/btool/pkcs11_tool.py             | 339 +++++++++++-
 tools/binman/etype/pre_load.py                | 238 ++++++++-
 tools/binman/ftest.py                         | 241 +++++++++
 tools/binman/test/security/pre_load_hsm.dts   |  21 +
 .../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.dts       |  21 +
 .../test/security/pre_load_hsm_sign_pss.dts   |  22 +
 .../security/pre_load_missing_key_name.dts    |  20 +
 15 files changed, 1520 insertions(+), 14 deletions(-)
 create mode 100644 tools/binman/test/security/pre_load_hsm.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.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
#13 lore raw

PATCH v2 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.

The implementation:
- adds the public method find_slot_by_serial() to resolve an HSM token serial number to its slot index;
- selects tokens by label or slot index;
- selects signing keys by label or object ID;
- verifies that the requested mechanism is supported;
- writes signatures through pkcs11-tool's output-file interface;
- passes the HSM PIN through BINMAN_PKCS11_PIN and references it as env:BINMAN_PKCS11_PIN;
- requires a PIN and enables PKCS#11 login for signing.

Add comprehensive unit tests covering token and key selection, mechanism validation, signing failures, and successful signatures.

---
Changes in v2:
- Merge v1 patches 1 and 2, so the unit tests come with the code
- Make sign() take an input file path instead of a bytes buffer
- Read the signature from pkcs11-tool --output-file instead of stdout, which only holds diagnostic text
- Pass the PIN through the BINMAN_PKCS11_PIN environment variable (--pin env:...) instead of the command line; add an env argument to Bintool.run_cmd_result()
- Require a PIN and always enable PKCS#11 login
- Accept slot index 0 (compare with None instead of testing truthiness)
- Make find_slot_by_serial() robust: use run_cmd_result(), return None on failure and match the "serial num" line more strictly
- Reject unknown hash algorithms in _build_mechanism()
- Log a message when mechanism verification is skipped
- Add ECDSA support, falling back to host-side hashing plus raw ECDSA when the token has no combined hash+ECDSA mechanism (e.g. SoftHSM)
- Add tests for the ECDSA paths, missing mechanisms, missing PIN and unlink errors; drop test_pkcs11_tool_cleanup_error as the temporary input file is gone

 tools/binman/bintool.py           |   8 +-
 tools/binman/bintool_test.py      | 497 ++++++++++++++++++++++++++++++
 tools/binman/btool/pkcs11_tool.py | 339 +++++++++++++++++++-
 3 files changed, 837 insertions(+), 7 deletions(-)
tools/binman/bintool.py +5 -3
index 4cf8d5b165b..7396bbcf6b5 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:
@@ -291,10 +291,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()
+        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 +497 -0

515 lines not on this page · raw message

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

358 lines not on this page · raw message

Signature · 1 line
2.43.0
#14 lore raw

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

Hi Yan,

Quoted 28 lines · yan wang

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.

The implementation:
- adds the public method find_slot_by_serial() to resolve an HSM token serial number to its slot index;
- selects tokens by label or slot index;
- selects signing keys by label or object ID;
- verifies that the requested mechanism is supported;
- writes signatures through pkcs11-tool's output-file interface;
- passes the HSM PIN through BINMAN_PKCS11_PIN and references it as env:BINMAN_PKCS11_PIN;
- requires a PIN and enables PKCS#11 login for signing.

Add comprehensive unit tests covering token and key selection, mechanism validation, signing failures, and successful signatures.

 tools/binman/bintool.py           |   8 +-
 tools/binman/bintool_test.py      | 497 ++++++++++++++++++++++++++++++++++++++
 tools/binman/btool/pkcs11_tool.py | 339 +++++++++++++++++++++++++-
 3 files changed, 837 insertions(+), 7 deletions(-)

tools/binman/bintool.py class Bintool: · line 273

Quoted 2 lines
tools/binman/bintool.py +1 -1
@@ -273,7 +273,7 @@ class Bintool:
-    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):

Please can you add 'env' to the Args: section of the docstring, e.g. a dict of extra environment variables to set when running the tool.

tools/binman/btool/pkcs11_tool.py class Bintoolpkcs11_tool(bintool.Bintool): · line 34

Quoted 4 lines
tools/binman/btool/pkcs11_tool.py +2 -0
@@ -22,6 +33,326 @@ class Bintoolpkcs11_tool(bintool.Bintool):
+        Use pkcs11-tool's '--pin env:VAR' option (available in newer OpenSC
+        versions) or a protected authentication path where possible.

This reads as advice to the caller, but sign() now always uses env: so it is out of date. My question from v1 is still open: which OpenSC version added 'env:' support? I believe an older pkcs11-tool uses the literal string 'env:BINMAN_PKCS11_PIN' as the PIN, so each build counts as a failed login and could lock the token after a few attempts. Please can you find the minimum version and mention it here and in the pre-load documentation?

tools/binman/btool/pkcs11_tool.py class Bintoolpkcs11_tool(bintool.Bintool): · line 35

Quoted 5 lines
tools/binman/btool/pkcs11_tool.py +3 -0
@@ -22,6 +33,326 @@ class Bintoolpkcs11_tool(bintool.Bintool):
+            fd, digest_file = tempfile.mkstemp(prefix='binman_digest_')
+            with os.fdopen(fd, 'wb') as dfd:
+                dfd.write(digest)

The pre-load entry never passes output_file, so the mkstemp()/unlink() handling is used every time, and the ECDSA digest adds another temporary file. Please can you make output_file a required argument and have the etype pass a name from tools.get_output_filename()? The digest could also go in the output directory, e.g. alongside the input file. Then the files are kept for debugging and the cleanup code (and the unlink-error test) can go.

tools/binman/btool/pkcs11_tool.py class Bintoolpkcs11_tool(bintool.Bintool): · line 34

Quoted 4 lines
tools/binman/btool/pkcs11_tool.py +2 -0
@@ -22,6 +33,326 @@ class Bintoolpkcs11_tool(bintool.Bintool):
+        run_env = None
+        args += ['--pin', 'env:BINMAN_PKCS11_PIN', '--login']

The 'run_env = None' line can be dropped, since run_env is set two lines later.

Regards,
Simon

author
#15 lore raw

PATCH 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
author
#16 lore raw

PATCH v2 2/4 binman: pre_load: Validate file signing key

In reply to yan wang

Use integer division when calculating RSA and ECDSA signature sizes and reject file-based signing without a key-name property.

---
Changes in v2:
- New patch, split out of v1 patch 3
- Use integer division for the RSA and ECDSA signature sizes
- Reject file-based signing when key-name is missing
- Add testPreLoadMissingKeyName and its devicetree (moved from v1 patch 5)

 tools/binman/etype/pre_load.py                | 16 +++++++++------
 tools/binman/ftest.py                         | 11 ++++++++++
 .../security/pre_load_missing_key_name.dts    | 20 +++++++++++++++++++
 3 files changed, 41 insertions(+), 6 deletions(-)
 create mode 100644 tools/binman/test/security/pre_load_missing_key_name.dts
tools/binman/etype/pre_load.py +10 -6
index 7890c1c62a8..49a63ecaafa 100644
@@ -24,15 +24,15 @@ from Cryptodome.Signature import DSS
 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 = {
@@ -199,6 +199,10 @@ class Entry_pre_load(Entry_collection):
 
     def _CreateHeader(self):
         """Create a pre load header"""
+
+        # File-based path: dispatch on signing algorithm
+        if not self.key_name:
+            self.Raise('key-name is required for file-based signing')
         hash_name, sign_name = self.algo_name.split(',')
         padding_name = self.padding_name
         key_name = os.path.join(self.key_path, self.key_name)
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
#17 lore raw

Re: [PATCH v2 2/4] binman: pre_load: Validate file signing key

Hi Yan,

Quoted 4 lines · yan wang

binman: pre_load: Validate file signing key

Use integer division when calculating RSA and ECDSA signature sizes and reject file-based signing without a key-name property.

Please can you start with the motivation? Without key-name, os.path.join() is called with None and binman fails with a TypeError traceback rather than a useful message. For the division, as far as I can tell the float values still compare equal to the integer key sizes, so say that this is a tidy-up ahead of the signature-length check in the next patch. The subject also only covers half of the change.

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

Quoted 6 lines
tools/binman/etype/pre_load.py +4 -0
@@ -199,6 +199,10 @@ class Entry_pre_load(Entry_collection):
+
+        # File-based path: dispatch on signing algorithm
+        if not self.key_name:
+            self.Raise('key-name is required for file-based signing')

The 'File-based path' comment only makes sense once patch 3 adds the HSM branch, so please move it there, and drop the blank line after the docstring. Also, patch 3 checks the HSM settings in ReadNode() so that a bad devicetree fails early. Doing the key-name check there too (when hsm-key is not set) would be more consistent. What do you think?

Quoted 7 lines
 tools/binman/etype/pre_load.py                       | 16 ++++++++++------
 tools/binman/ftest.py                                | 11 +++++++++++
 .../test/security/pre_load_missing_key_name.dts      | 20 ++++++++++++++++++++
 3 files changed, 41 insertions(+), 6 deletions(-)

Regards,
Simon

author
#18 lore raw

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

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
author
#19 lore raw

PATCH v2 3/4 binman: pre_load: Add HSM signing support to pre-load entry type

In reply to yan wang

Extend the pre-load entry type to support signing via hardware security modules (HSM) using PKCS#11. The implementation integrates with the pkcs11_tool btool to perform signing operations.

---
Changes in v2:
- Replace the hsm-support, hsm-library, hsm-token-label, hsm-token-serial, hsm-slot-index, hsm-key-label, hsm-key-id and hsm-pin properties with a single hsm-key PKCS#11 URI (RFC 7512), in line with FIT signing
- Do not store the PIN in the devicetree: use -a pre-load-hsm-pin or the PKCS11_SIGN_PIN environment variable
- Take the library path from -a pre-load-hsm-library, the hsm-library property or the module-path attribute of the URI
- Drop the _SignData() refactoring of v1; keep the file-based code unchanged and add a separate _SignHsmData() helper to reduce the diff
- Write the data to a file in the output directory, as sign() now takes a file
- Add ECDSA support
- Validate the HSM configuration early in ReadNode(), before the tool is looked up
- Check the length of the returned signature
- If pkcs11-tool is missing, record it as a missing bintool and emit a dummy header instead of raising an error

 tools/binman/etype/pre_load.py | 222 ++++++++++++++++++++++++++++++++-
 1 file changed, 221 insertions(+), 1 deletion(-)
tools/binman/etype/pre_load.py +221 -1
index 49a63ecaafa..14bfb23afb5 100644
@@ -7,6 +7,7 @@
 
 import os
 import struct
+from urllib.parse import unquote
 from dtoc import fdt_util
 from u_boot_pylib import tools
 
@@ -21,6 +22,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,6 +82,37 @@ 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
+        - 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 set via the hsm-library
+          DT property when the build host is always the same, or 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.
+
+    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 RSA
+    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.
+
 
     This entry creates a pre-load header that contains a global
     image signature.
@@ -77,6 +137,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=1234
     """
 
     def __init__(self, section, etype, node):
@@ -87,6 +169,18 @@ 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 = fdt_util.GetString(self._node, 'hsm-library')
+        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.pkcs11_tool = None
+
     def ReadNode(self):
         super().ReadNode()
         self.key_path, = self.GetEntryArgsOrProps(
@@ -94,6 +188,50 @@ class Entry_pre_load(Entry_collection):
         if self.key_path is None:
             self.key_path = ''
 
+        # hsm-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.
+        pin_arg, = self.GetEntryArgsOrProps([EntryArg('pre-load-hsm-pin', str)])
+        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']
+
+            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 not in RSAS and sign_name not in ECDSAS:
+                self.Raise(f'{sign_name} is not supported')
+            padding_name = self.padding_name or 'pkcs-1.5'
+            if padding_name not in ('pss', 'pkcs-1.5'):
+                self.Raise(f'Unsupported padding scheme: {padding_name}')
+
+    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 _CreateHeaderRsa(self, hash_name, sign_name, padding_name, key_name):
         # Check hash and signature name/type
         if hash_name not in SHAS:
@@ -197,8 +335,90 @@ class Entry_pre_load(Entry_collection):
 
         return data + pad
 
+    def _SignHsmData(self, data):
+        """Sign data with the configured HSM via PKCS#11."""
+        hash_name, sign_name = self.algo_name.split(',')
+        padding_name = self.padding_name or 'pkcs-1.5'
+
+        if hash_name not in SHAS:
+            self.Raise(f'{hash_name} is not supported')
+        if sign_name not in RSAS and sign_name not in ECDSAS:
+            self.Raise(f'{sign_name} is not supported')
+
+        padding = {'pss': 'pss', 'pkcs-1.5': 'pkcs1v15'}.get(padding_name)
+        if padding is None:
+            self.Raise(f'Unsupported padding scheme: {padding_name}')
+
+        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)
+
+        try:
+            signature = self.pkcs11_tool.sign(
+                input_file=input_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=hash_name,
+                sign_algo=sign_name,
+                padding=padding)
+        except (ValueError, RuntimeError) as e:
+            self.Raise(f'HSM signing failed: {e}')
+
+        expected = (RSAS[sign_name] if sign_name in RSAS
+                    else ECDSAS[sign_name])
+        if len(signature) != expected:
+            self.Raise(
+                f'HSM returned {len(signature)}-byte signature but '
+                f'{sign_name} requires {expected} bytes')
+        return signature
+
     def _CreateHeader(self):
-        """Create a pre load header"""
+        """Create a pre-load header.
+
+        When HSM signing is active the pkcs11-tool btool is called twice per
+        _CreateHeader() invocation (once for the image signature and once for
+        the header signature). Binman may call ProcessContents() several times
+        as entries settle, so consider caching the slot and mechanism results
+        in a real deployment against a rate-limited HSM.
+        """
+        if self.hsm_key_uri:
+            # HSM path: use the HSM signing helper
+            img_sig = self._SignHsmData(self.image)
+            if img_sig is None:
+                # pkcs11-tool is missing; return a dummy header
+                return tools.get_bytes(0, self.header_size)
+
+            hash_sig = SHA256.new(img_sig)
+
+            version = self.version
+            header_size = self.header_size
+            image_size = len(self.image)
+            ofs_img_sig = 64 + len(img_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())
+
+            hdr_sig = self._SignHsmData(first_header)
+            if hdr_sig is None:
+                return tools.get_bytes(0, self.header_size)
+
+            data = first_header + hdr_sig + img_sig
+            pad = bytearray(self.header_size - len(data))
+            return data + pad
 
         # File-based path: dispatch on signing algorithm
         if not self.key_name:
Signature · 1 line
2.43.0
#20 lore raw

Re: [PATCH v2 3/4] binman: pre_load: Add HSM signing support to pre-load entry type

Hi Yan,

Quoted 5 lines · yan wang

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

Extend the pre-load entry type to support signing via hardware security modules (HSM) using PKCS#11. The implementation integrates with the pkcs11_tool btool to perform signing operations.

The commit message is the same as in v1. Please can you describe the hsm-key property, the pre-load-hsm-library / pre-load-hsm-pin entry arguments and PKCS11_SIGN_PIN, and give the reason for the change, i.e. so the private key never has to leave the token? Your cover letter already says this well.

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

Quoted 11 lines
tools/binman/etype/pre_load.py +6 -0
@@ -53,6 +82,37 @@ class Entry_pre_load(Entry_collection):
+    This entry creates a pre-load header that contains a global image
+    signature. The signature can be created using either a traditional RSA
+    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.
+
 
     This entry creates a pre-load header that contains a global
     image signature.

The old paragraph is still there, so the docs now say this twice, with two blank lines in between. Please merge them. Also, a key file can be ECDSA as well, so 'RSA' is not right here.

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

Quoted 3 lines
tools/binman/etype/pre_load.py +1 -0
@@ -87,6 +169,18 @@ class Entry_pre_load(Entry_collection):
+        self.hsm_library = fdt_util.GetString(self._node, 'hsm-library')

The cover letter says the library is not stored in the devicetree, but the DT can provide it in three ways: this hsm-library property, a 'pre-load-hsm-library' property (see below) and module-path= in the URI. Please can you drop the hsm-library property? The entry argument and module-path= cover it.

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

Quoted 5 lines
tools/binman/etype/pre_load.py +3 -0
@@ -94,6 +188,50 @@ class Entry_pre_load(Entry_collection):
+        # PIN from entry arg or environment variable, NOT from the DT.
+        pin_arg, = self.GetEntryArgsOrProps([EntryArg('pre-load-hsm-pin', str)])
+        self.hsm_pin = pin_arg or os.environ.get('PKCS11_SIGN_PIN')

One thing I'd like to check here: GetEntryArgsOrProps() calls GetArg(), which falls back to fdt_util.GetDatatype() on the node when no -a argument is given. So 'pre-load-hsm-pin = '1234';' in the DT is still used, despite the comment. Please can you use state.GetEntryArg('pre-load-hsm-pin') directly so the DT is never read for the PIN? A test that puts the PIN in the DT and checks it is ignored would be good.

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

Quoted 10 lines
tools/binman/etype/pre_load.py +8 -0
@@ -94,6 +188,50 @@ class Entry_pre_load(Entry_collection):
+            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 not in RSAS and sign_name not in ECDSAS:
+                self.Raise(f'{sign_name} is not supported')
+            padding_name = self.padding_name or 'pkcs-1.5'
+            if padding_name not in ('pss', 'pkcs-1.5'):
+                self.Raise(f'Unsupported padding scheme: {padding_name}')

_SignHsmData() repeats these checks. Since ReadNode() always runs first, please keep them here and work out the values once, e.g. in instance variables.

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

Quoted 7 lines
tools/binman/etype/pre_load.py +5 -0
@@ -197,8 +335,90 @@ class Entry_pre_load(Entry_collection):
+        When HSM signing is active the pkcs11-tool btool is called twice per
+        _CreateHeader() invocation (once for the image signature and once for
+        the header signature). Binman may call ProcessContents() several times
+        as entries settle, so consider caching the slot and mechanism results
+        in a real deployment against a rate-limited HSM.

Someone running binman can't act on this. Please either do the caching or drop the paragraph (perhaps leave a short TODO instead).

Quoted 6 lines
tools/binman/etype/pre_load.py +4 -0
@@ -197,8 +335,90 @@ class Entry_pre_load(Entry_collection):
+            hash_sig = SHA256.new(img_sig)
+
+            version = self.version
+            header_size = self.header_size

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

Quoted 10 lines
tools/binman/etype/pre_load.py +10 -0
+            image_size = len(self.image)
+            ofs_img_sig = 64 + len(img_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())

This is the third copy of the header-building code, after _CreateHeaderRsa() and _CreateHeaderEcdsa(). It would be worth a preparatory patch with a helper that takes a signing function and builds the header, so the HSM path only has to provide _SignHsmData(). What do you think?

Quoted 5 lines
 tools/binman/etype/pre_load.py | 222 ++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 221 insertions(+), 1 deletion(-)

Regards,
Simon

author
#21 lore raw

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

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
author
#22 lore raw

PATCH v2 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.

---
Changes in v2:
- Merge v1 patches 4 and 5
- Extend testPreLoadHsmSign (SoftHSM) to cover both pkcs-1.5 and PSS
- Add testPreLoadHsmEcdsaSign (SoftHSM) which verifies the signatures with the public key read from the token
- Add tests for an invalid URI, hash and algorithm, module-path in the URI, the data checks in _SignHsmData(), a bad signature length and a missing tool before the header signature
- Merge testPreLoadHsmSignRuntimeError into testPreLoadHsmSignError
- Drop testPreLoadDefaultPadding and testPreLoadHsmMissingLibrary; move testPreLoadMissingKeyName to patch 2
- Rework the devicetrees for the hsm-key URI and make them smaller

 tools/binman/ftest.py                         | 230 ++++++++++++++++++
 tools/binman/test/security/pre_load_hsm.dts   |  21 ++
 .../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.dts       |  21 ++
 .../test/security/pre_load_hsm_sign_pss.dts   |  22 ++
 10 files changed, 421 insertions(+)
 create mode 100644 tools/binman/test/security/pre_load_hsm.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.dts
 create mode 100644 tools/binman/test/security/pre_load_hsm_sign_pss.dts
tools/binman/ftest.py +230 -0
index d4522e905e0..08523141b48 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,231 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
         self.assertIn('key-name is required for file-based signing',
                       str(exc.exception))
 
+    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.
+        """
+        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)
+
+        openssl = bintool.Bintool.create('openssl')
+        self._CheckBintool(openssl)
+
+        prefix = 'testPreLoadHsmSign.'
+
+        # 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, 'pubkey.der')
+        pubkey_pem = os.path.join(self._indir, 'pubkey.pem')
+
+        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', 'rsa:2048',
+                                '--label', 'uboot-key', '--login',
+                                '--pin', '1234')
+            pkcs11_tool.run_cmd('--module', softhsm2_lib,
+                                '--read-object', '--type', 'pubkey',
+                                '--label', 'uboot-key', '--login',
+                                '--pin', '1234', '--output-file', pubkey_der)
+            openssl.run_cmd_result('rsa', '-pubin', '-inform', 'DER',
+                                   '-in', pubkey_der, '-out', pubkey_pem)
+
+            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_sign.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_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)
+
+        prefix = 'testPreLoadHsmEcdsaSign.'
+        conf = self._MakeInputFile(
+            f'{prefix}softhsm2.conf',
+            tools.read_file(self.TestFile('fit/softhsm2.conf')))
+        token_dir = self._MakeInputDir(f'{prefix}tokens')
+        with open(conf, 'a') as fd:
+            fd.write(f'directories.tokendir = {token_dir}\n')
+
+        cfg = configparser.ConfigParser()
+        cfg.read_string(p11_kit.run_cmd('print-config'))
+        lib = cfg.get('softhsm2', 'module', fallback=None)
+        self.assertIsNotNone(lib)
+
+        with unittest.mock.patch.dict('os.environ', {'SOFTHSM2_CONF': conf}):
+            softhsm2_util.run_cmd('--init-token', '--free', '--label',
+                                  'uboot-hsm', '--pin', '1234',
+                                  '--so-pin', '1234')
+            pkcs11_tool.run_cmd('--module', lib, '--keypairgen',
+                                '--key-type', 'EC:prime256v1',
+                                '--label', 'uboot-ecdsa', '--login',
+                                '--pin', '1234')
+            pubkey_der = os.path.join(self._indir, 'ecpubkey.der')
+            pkcs11_tool.run_cmd('--module', lib, '--read-object',
+                                '--type', 'pubkey', '--label', 'uboot-ecdsa',
+                                '--login', '--pin', '1234',
+                                '--output-file', pubkey_der)
+            args = {'pre-load-hsm-library': 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 testPreLoadHsmSignDataChecks(self):
+        """Test _SignHsmData() re-validates algorithm and padding"""
+        self._DoTestFile('security/pre_load_hsm.dts',
+                         force_missing_bintools='pkcs11-tool')
+        entry = control.images['image'].GetEntries()['pre-load']
+        for algo, padding, msg in (
+                ('sha1,rsa2048', None, 'sha1 is not supported'),
+                ('sha256,rsa1234', None, 'rsa1234 is not supported'),
+                ('sha256,rsa2048', 'bad', 'Unsupported padding scheme')):
+            entry.algo_name = algo
+            entry.padding_name = padding
+            with self.assertRaises(ValueError) as exc:
+                entry._SignHsmData(b'data')
+            self.assertIn(msg, str(exc.exception))
+
+    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 testPreLoadHsmHeaderSignMissing(self):
+        """Test dummy header when the tool vanishes before the header sign"""
+        from binman.etype import pre_load as pre_load_etype
+        calls = []
+
+        def fake_sign(data):
+            calls.append(1)
+            return bytes(256) if len(calls) % 2 else None
+
+        with unittest.mock.patch.object(pre_load_etype.Entry_pre_load,
+                                        '_SignHsmData',
+                                        side_effect=fake_sign):
+            data = self._DoReadFile('security/pre_load_hsm.dts')
+        self.assertEqual(tools.get_bytes(0, 4096), data[:4096])
+
     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_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.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_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
#23 lore raw

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

Hi Yan,

Quoted 6 lines · yan wang

binman: Add functional test for pre-load HSM signing

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.

Please can you add the short paragraph I asked for last time, saying what the test sets up: a SoftHSM token, RSA and ECDSA keys generated on the token, and a check with preload_check_sign (or Cryptodome, for ECDSA)? Please mention the new error-path tests too.

Quoted 17 lines
 tools/binman/ftest.py                              | 230 +++++++++++++++++++++
 tools/binman/test/security/pre_load_hsm.dts        |  21 ++
 tools/binman/test/security/pre_load_hsm_ecdsa.dts  |  21 ++
 .../test/security/pre_load_hsm_invalid_algo.dts    |  21 ++
 .../test/security/pre_load_hsm_invalid_padding.dts |  22 ++
 .../test/security/pre_load_hsm_invalid_sha.dts     |  21 ++
 .../test/security/pre_load_hsm_invalid_uri.dts     |  21 ++
 .../test/security/pre_load_hsm_module_path.dts     |  21 ++
 tools/binman/test/security/pre_load_hsm_sign.dts   |  21 ++
 .../binman/test/security/pre_load_hsm_sign_pss.dts |  22 ++
 10 files changed, 421 insertions(+)

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 6003

Quoted 7 lines
tools/binman/ftest.py +7 -0
@@ -5992,6 +5997,231 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+        prefix = 'testPreLoadHsmEcdsaSign.'
+        conf = self._MakeInputFile(
+            f'{prefix}softhsm2.conf',
+            tools.read_file(self.TestFile('fit/softhsm2.conf')))
+        token_dir = self._MakeInputDir(f'{prefix}tokens')
+        with open(conf, 'a') as fd:
+            fd.write(f'directories.tokendir = {token_dir}\n')

This repeats the SoftHSM setup from testPreLoadHsmSign() (bintool checks, conf file, p11-kit lookup, token init and key generation). Only the key type and label differ, so this should be in a helper.

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5998

Quoted 4 lines
tools/binman/ftest.py +2 -0
@@ -5992,6 +5997,231 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+    def testPreLoadHsmSignDataChecks(self):
+        """Test _SignHsmData() re-validates algorithm and padding"""

This test only covers the duplicate checks in _SignHsmData(). Once those are dropped in patch 3, please drop this test too, rather than reaching into the entry to change algo_name after the fact.

tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5999

Quoted 5 lines
tools/binman/ftest.py +3 -0
@@ -5992,6 +5997,231 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
+    def testPreLoadHsmHeaderSignMissing(self):
+        """Test dummy header when the tool vanishes before the header sign"""
+        from binman.etype import pre_load as pre_load_etype

Same here. The tool cannot go missing between the two _SignHsmData() calls, so the second None check in _CreateHeader() is dead code. Please can you remove that check in patch 3, along with this test? If you do keep the test, the import should go at the top of the file.

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

Quoted 3 lines
tools/binman/test/security/pre_load_hsm_sign.dts +1 -0
@@ -0,0 +1,21 @@
+			hsm-key = "pkcs11:token=uboot-hsm;object=uboot-key";

This file is identical to pre_load_hsm.dts, so please drop one and use the other in both places.

Regards,
Simon

author
#24 lore raw

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

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
author
#25 lore raw

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

In reply to yan wang

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
#26 lore raw
In reply to Simon Glass
Quoted 8 lines · Simon Glass

Hi Yan,

Quoted 3 lines · Yan WANG

The implementation builds on the existing pkcs11_tool btool: a sign() method is added that drives pkcs11-tool to perform the actual cryptographic operation.

Quoted 7 lines

Binman can already describe a PKCS#11 key for FIT signing: fit,engine set to pkcs11, with fit,engine-keydir and key-name-hint, which become a pkcs11: URI. This series adds a second scheme of eight properties that works quite differently. It would be better for users if pre-load followed the FIT conventions, e.g. a single PKCS#11 URI property for the token and key plus the module path. Then both entry types would be configured the same way. What do you think?

I have another idea, not directly related to this patch (this could also be used in mkimage) - would a two-step asynchronous process be acceptable?

First step, binman calculates byte ranges to be signed and provides a value (possibly a hash) that can be fed to a signing process.

External process talks to the HSM via the interface of choice and provides a ready-to-embed signature for the actual binman run. Yes, this breaks the notion "only run binman once", unfortunately.

That would decouple us from the openssl engine/pkcs11/whatever interfaces and also could enable enterprise-grade workflows where signing a production image involves approvals, n-of-m or whatever additional protections might be needed.

Marcin