binman: pre-load: Allow signing with an OpenSSL engine
cover binman: pre-load: Allow signing with an OpenSSL engine
The pre-load entry type signs with Cryptodome, which has no PKCS#11 support, so the private key must be a file. Keys held in an HSM or on a smart card cannot be used.
Add an optional 'engine' property. When set, binman signs by running openssl with that engine and takes 'key-name' as the engine-specific key identifier.
Tested with SoftHSM via the new tests (both paddings) and with an RSA-2048 key on a YubiKey PIV slot. The tests are skipped when softhsm2-util or the pkcs11 engine is unavailable.
Lorenz Kofler (3):
binman: pre-load: Move signing into its own function
binman: pre-load: Allow signing with an OpenSSL engine
binman: pre-load: Test signing with an OpenSSL engine
tools/binman/btool/openssl.py | 28 ++++ tools/binman/etype/pre_load.py | 130 ++++++++++++++---- tools/binman/ftest.py | 91 +++++++++++- .../test/security/pre_load_engine_pkcs11.dts | 24 ++++ .../security/pre_load_engine_pkcs11_pss.dts | 24 ++++ 5 files changed, 266 insertions(+), 31 deletions(-) create mode 100644 tools/binman/test/security/pre_load_engine_pkcs11.dts create mode 100644 tools/binman/test/security/pre_load_engine_pkcs11_pss.dts
base-commit: 444aca6d1439e4c4b9955171a7f45c053b540f69
Signature · 1 line
2.55.0
PATCH 1/3 binman: pre-load: Move signing into its own function
_CreateHeader() signs twice, once for the image and once for the first header, with the same key and the same padding. Move the signing into a _sign() helper rather than repeating it.
This is a preparation for signing with an OpenSSL engine, which needs a second implementation of _sign(). No functional change.
--- tools/binman/etype/pre_load.py | 49 +++++++++++++++++++++------------- 1 file changed, 30 insertions(+), 19 deletions(-)
tools/binman/etype/pre_load.py +30 -19
@@ -86,6 +86,31 @@ class Entry_pre_load(Entry_collection): if self.key_path is None: self.key_path = '' + def _sign(self, data, key, hash_name, padding_name): + """Sign data with a key + + Args: + data (bytes): Data to sign + key (RsaKey): Key to sign with + hash_name (str): Hash algorithm to use + padding_name (str): Padding to use + + Returns: + bytes: Signature + """ + hash_data = SHAS[hash_name].new() + hash_data.update(data) + + if padding_name == "pss": + salt_len = key.size_in_bytes() - hash_data.digest_size - 2 + padding = pss + padding_args = {'salt_bytes': salt_len} + else: + padding = pkcs1_15 + padding_args = {} + + return padding.new(key, **padding_args).sign(hash_data) + def _CreateHeader(self): """Create a pre load header""" hash_name, sign_name = self.algo_name.split(',')
@@ -105,26 +130,13 @@ class Entry_pre_load(Entry_collection): 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 = {} - else: + if padding_name not in ("pss", "pkcs-1.5"): self.Raise(padding_name + " is not supported") - sig = padding.new(key, **padding_args).sign(hash_image) + # Compute the signature + sig = self._sign(self.image, key, hash_name, padding_name) hash_sig = SHA256.new() hash_sig.update(sig)
@@ -142,9 +154,8 @@ class Entry_pre_load(Entry_collection): 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) + sig_first_header = self._sign(first_header, key, hash_name, + padding_name) data = first_header + sig_first_header + sig pad = bytearray(self.header_size - len(data))
Signature · 1 line
2.55.0
Re: [PATCH 1/3] binman: pre-load: Move signing into its own function
Quoted 6 lines · Lorenz Kofler
binman: pre-load: Move signing into its own function
_CreateHeader()signs twice, once for the image and once for the first header, with the same key and the same padding. Move the signing into a_sign()helper rather than repeating it.
Quoted 8 lines
This is a preparation for signing with an OpenSSL engine, which needs a second implementation of
_sign(). No functional change.Assisted-by Claude:claude-opus-5Signed-off-by Lorenz Kofler <[email protected]>
tools/binman/etype/pre_load.py| 49 ++++++++++++++++++++++++++----------------1 file changed, 30 insertions(+), 19 deletions(-)
PATCH 2/3 binman: pre-load: Allow signing with an OpenSSL engine
In reply to Lorenz KoflerThe pre-load entry type imports a private key from a file and signs with Cryptodome, so the key must be readable as a file. Keys held in an HSM or on a smart card cannot be used. The FIT entry type is not affected as it delegates signing to mkimage, which signs through the OpenSSL engine API.
Add an optional 'engine' property. When set, sign with openssl using that engine and interpret 'key-name' as the engine-specific key identifier, instead of reading a key from 'pre-load-key-path'.
For the pkcs11 engine, expand a 'key-name' that is not already a PKCS#11 URI to:
pkcs11:object=<key-name>;type=private
With an engine, binman never loads the key itself and so cannot check its size before signing. Check the length of the resulting RSA signature instead, which is the modulus size either way.
Behavior is otherwise unchanged when 'engine' is absent.
--- tools/binman/btool/openssl.py | 28 +++++++++++ tools/binman/etype/pre_load.py | 87 +++++++++++++++++++++++++++++----- tools/binman/ftest.py | 12 +++-- 3 files changed, 112 insertions(+), 15 deletions(-)
tools/binman/btool/openssl.py +28 -0
@@ -36,6 +36,34 @@ class Bintoolopenssl(bintool.Bintool): name, 'openssl cryptography toolkit', version_regex=r'OpenSSL (.*) \(', version_args='version') + def sign(self, input_fname, output_fname, key, hash_name, padding_name, + engine=None): + """Sign a file + + The key is a filename, or, when an engine is used, anything the engine + accepts as a key identifier, e.g. a PKCS#11 URI. + + Args: + input_fname (str): Filename holding the data to sign + output_fname (str): Filename to write the signature to + key (str): Key filename, or key identifier for the engine + hash_name (str): Hash algorithm to use, e.g. 'sha256' + padding_name (str): Padding to use, 'pkcs-1.5' or 'pss' + engine (str): OpenSSL engine to use for signing, or None to sign + with a local key file + + Returns: + str: Tool output + """ + args = ['dgst', f'-{hash_name}', '-sign', key, '-out', output_fname] + if engine: + args += ['-engine', engine, '-keyform', 'engine'] + if padding_name == 'pss': + args += ['-sigopt', 'rsa_padding_mode:pss', + '-sigopt', 'rsa_pss_saltlen:max'] + args.append(input_fname) + return self.run_cmd(*args) + def x509_cert(self, cert_fname, input_fname, key_fname, cn, revision, config_fname): """Create a certificate
tools/binman/etype/pre_load.py +75 -12
149 lines not on this page · raw message
tools/binman/ftest.py +9 -3
@@ -5888,12 +5888,18 @@ fdt fdtmap Extract the devicetree blob from the fdtmap def testPreLoadInvalidKey(self): """Test an image with a pre-load header with an invalid key""" + from binman.etype import pre_load + entry_args = { 'pre-load-key-path': os.path.join(self._binman_dir, 'test'), } - with self.assertRaises(ValueError) as e: - data = self._DoReadFileDtb('security/pre_load_invalid_key.dts', - entry_args=entry_args) + with unittest.mock.patch.object( + pre_load.Entry_pre_load, '_sign', + side_effect=AssertionError('signing should not be attempted')): + with self.assertRaisesRegex(ValueError, + "don't have the expected size"): + self._DoReadFileDtb('security/pre_load_invalid_key.dts', + entry_args=entry_args) def testPreLoadEncryptedFit(self): """Test an encrypted FIT image with a pre-load header"""
Signature · 1 line
2.55.0
Hi Lorenz,
Quoted 31 lines · Lorenz Kofler
binman: pre-load: Allow signing with an OpenSSL engine
The pre-load entry type imports a private key from a file and signs with Cryptodome, so the key must be readable as a file. Keys held in an HSM or on a smart card cannot be used. The FIT entry type is not affected as it delegates signing to mkimage, which signs through the OpenSSL engine API.
Add an optional 'engine' property. When set, sign with openssl using that engine and interpret 'key-name' as the engine-specific key identifier, instead of reading a key from 'pre-load-key-path'.
For the pkcs11 engine, expand a 'key-name' that is not already a PKCS#11 URI to:
pkcs11:object=<key-name>;type=private
With an engine, binman never loads the key itself and so cannot check its size before signing. Check the length of the resulting RSA signature instead, which is the modulus size either way.
[...]
tools/binman/btool/openssl.py| 28 ++++++++++++++tools/binman/etype/pre_load.py | 85 ++++++++++++++++++++++++++++++++++++------ tools/binman/ftest.py | 12 ++++-- 3 files changed, 111 insertions(+), 14 deletions(-)tools/binman/etype/pre_load.py +4
-0+ def _sign_engine(self, data, hash_name, padding_name): + """Sign data with an OpenSSL engine + + Args:
tools/binman/etype/pre_load.py class Entry_pre_load(Entry_collection): · line 123
Quoted 10 lines
tools/binman/etype/pre_load.py +10
-0+ data (bytes): Data to sign + hash_name (str): Hash algorithm to use + padding_name (str): Padding to use + + Returns: + bytes: Signature, or zeroes if openssl is missing + """ + key_id = self.key_name + if self.engine == 'pkcs11' and not key_id.startswith('pkcs11:'): + key_id = f'pkcs11:object={key_id};type=private'
If key-name is absent, self.key_name is None and this crashes with an unhelpful AttributeError from startswith(). Please can you validate that key_name is set when engine is used and raise via self.Raise().
tools/binman/etype/pre_load.py class Entry_pre_load(Entry_collection): · line 98
Quoted 3 lines
tools/binman/etype/pre_load.py +1
-0@@ -78,6 +98,7 @@ class Entry_pre_load(Entry_collection): + self.engine = fdt_util.GetString(self._node, 'engine')
Embedding the pkcs11 URI expansion in the etype ties this generic engine knob to one specific engine. If another engine with different URI conventions is added later, the etype grows another special case. I'd prefer the etype pass key-name through unchanged and require the user to supply a full PKCS#11 URI - or move the munging into openssl.sign() where the engine-specific knowledge lives. What do you think?
tools/binman/etype/pre_load.py line 169
Quoted 5 lines
tools/binman/etype/pre_load.py +3
-0@@ -115,7 +167,7 @@ + # An engine does not expose its key, so infer its size from the signature + if self.engine and len(sig) != RSAS[sign_name]: + self.Raise("The key " + self.key_name + " don't have the expected size")
Worth a short comment noting that _sign_engine() returns a zero-filled placeholder of exactly RSAS[sign_name] bytes when openssl is missing, so this check silently passes and the missing-bintool path is preserved. The placeholder-length coupling is not obvious.
tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5909
Quoted 9 lines
tools/binman/ftest.py +7
-0@@ -5903,12 +5903,18 @@ fdt fdtmap Extract the devicetree blob from the fdtmap + with unittest.mock.patch.object( + pre_load.Entry_pre_load, '_sign', + side_effect=AssertionError('signing should not be attempted')): + with self.assertRaisesRegex(ValueError, + "don't have the expected size"): + self._DoReadFileDtb('security/pre_load_invalid_key.dts', + entry_args=entry_args)
This belongs in patch 1, where _sign() is introduced and _CreateHeader() is reshuffled - the test would have caught a regression in that refactor. Please can you move it there and keep patch 2 focused on the engine change?
Regards,
Simon
PATCH 3/3 binman: pre-load: Test signing with an OpenSSL engine
In reply to Lorenz KoflerAdd a test that signs a pre-load header through the pkcs11 engine, with a key imported into SoftHSM, like the existing FIT signature tests. It is skipped when softhsm2-util is not installed.
--- tools/binman/ftest.py | 79 +++++++++++++++++++ .../test/security/pre_load_engine_pkcs11.dts | 24 ++++++ .../security/pre_load_engine_pkcs11_pss.dts | 24 ++++++ 3 files changed, 127 insertions(+) create mode 100644 tools/binman/test/security/pre_load_engine_pkcs11.dts create mode 100644 tools/binman/test/security/pre_load_engine_pkcs11_pss.dts
tools/binman/ftest.py +79 -0
@@ -5922,6 +5922,85 @@ 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 _SetupPreLoadEngine(self, prefix): + """Set up a SoftHSM token holding the key used by the engine tests + + Args: + prefix (str): Prefix for the files created in the input directory + + Returns: + str: Filename of the SoftHSM configuration file + """ + softhsm2_util = bintool.Bintool.create('softhsm2_util') + self._CheckBintool(softhsm2_util) + + try: + tools.run('openssl', 'engine', 'dynamic', '-c', 'pkcs11') + except ValueError: + self.skipTest('PKCS11 engine setup not functional, ' + 'did you install libengine-pkcs11-openssl?') + + 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') + + with unittest.mock.patch.dict('os.environ', + {'SOFTHSM2_CONF': softhsm2_conf}): + softhsm2_util.run_cmd('--init-token', '--free', '--label', + 'U-Boot token', '--pin', '1111', + '--so-pin', '222222') + softhsm2_util.run_cmd('--import', self.TestFile('dev.key'), + '--token', 'U-Boot token', '--label', + 'test_key', '--id', '999999', '--pin', '1111') + + return softhsm2_conf + + def _CheckPreLoadEngine(self, dts, softhsm2_conf, padding): + """Sign an image through the pkcs11 engine and check the signature + + Args: + dts (str): Filename of the device tree to build + softhsm2_conf (str): Filename of the SoftHSM configuration file + padding (str): Padding used by the device tree + """ + ossl_conf = self.TestFile('fit/openssl.conf') + with unittest.mock.patch.dict('os.environ', + {'OPENSSL_CONF': ossl_conf, + 'SOFTHSM2_CONF': softhsm2_conf}): + data = self._DoReadFile(dts) + + image_fname = tools.get_output_filename('image.bin') + is_signed = self._CheckPreload(image_fname, self.TestFile('dev.key'), + padding=padding) + + 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 testPreLoadEnginePkcs11(self): + """Test a pre-load header signed through the pkcs11 OpenSSL engine""" + softhsm2_conf = self._SetupPreLoadEngine('testPreLoadEnginePkcs11.') + self._CheckPreLoadEngine('security/pre_load_engine_pkcs11.dts', + softhsm2_conf, 'pkcs-1.5') + + def testPreLoadEnginePkcs11Pss(self): + """Test a pre-load header signed through the engine with pss padding""" + softhsm2_conf = self._SetupPreLoadEngine('testPreLoadEnginePkcs11Pss.') + self._CheckPreLoadEngine('security/pre_load_engine_pkcs11_pss.dts', + softhsm2_conf, 'pss') + + def testPreLoadEngineMissingOpenssl(self): + """Test that a missing openssl is reported when using an engine""" + with terminal.capture() as (_, stderr): + self._DoTestFile('security/pre_load_engine_pkcs11.dts', + force_missing_bintools='openssl') + err = stderr.getvalue() + self.assertRegex(err, "Image 'image'.*missing bintools.*: openssl") + def _CheckSafeUniqueNames(self, *images): """Check all entries of given images for unsafe unique names""" for image in images:
tools/binman/test/security/pre_load_engine_pkcs11.dts new file +24 -0
@@ -0,0 +1,24 @@ +// 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 = "test_key"; + engine = "pkcs11"; + header-size = <4096>; + version = <0x11223344>; + }; + + image: blob-ext { + filename = "refcode.bin"; + }; + }; +};
tools/binman/test/security/pre_load_engine_pkcs11_pss.dts new file +24 -0
@@ -0,0 +1,24 @@ +// 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"; + key-name = "test_key"; + engine = "pkcs11"; + header-size = <4096>; + version = <0x11223344>; + }; + + image: blob-ext { + filename = "refcode.bin"; + }; + }; +};
Signature · 1 line
2.55.0
Re: [PATCH 3/3] binman: pre-load: Test signing with an OpenSSL engine
Hi Lorenz,
Quoted 18 lines · Lorenz Kofler
binman: pre-load: Test signing with an OpenSSL engine
Add a test that signs a pre-load header through the pkcs11 engine, with a key imported into SoftHSM, like the existing FIT signature tests. It is skipped when softhsm2-util is not installed.
Assisted-by Claude:claude-opus-5Signed-off-by Lorenz Kofler <[email protected]>
tools/binman/ftest.py| 79 ++++++++++++++++++++++.../test/security/pre_load_engine_pkcs11.dts | 24 +++++++ .../test/security/pre_load_engine_pkcs11_pss.dts | 24 +++++++ 3 files changed, 127 insertions(+)tools/binman/ftest.py +2
-0@@ -5937,6 +5937,85 @@ fdt fdtmap Extract the devicetree blob from the fdtmap + def _SetupPreLoadEngine(self, prefix): + """Set up a SoftHSM token holding the key used by the engine tests
...
Quoted 5 lines
tools/binman/ftest.py +5
-0+ softhsm2_util = bintool.Bintool.create('softhsm2_util') + self._CheckBintool(softhsm2_util) + + try: + tools.run('openssl', 'engine', 'dynamic', '-c', 'pkcs11')
tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5948
Quoted 10 lines
tools/binman/ftest.py +10
-0+ except ValueError: + self.skipTest('PKCS11 engine setup not functional, ' + 'did you install libengine-pkcs11-openssl?') + + 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')
You could use tools.write_file() here if you like
tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5957
Quoted 9 lines
tools/binman/ftest.py +9
-0+ + with unittest.mock.patch.dict('os.environ', + {'SOFTHSM2_CONF': softhsm2_conf}): + softhsm2_util.run_cmd('--init-token', '--free', '--label', + 'U-Boot token', '--pin', '1111', + '--so-pin', '222222') + softhsm2_util.run_cmd('--import', self.TestFile('dev.key'), + '--token', 'U-Boot token', '--label', + 'test_key', '--id', '999999', '--pin', '1111')
Nearly identical to the SoftHSM setup open-coded in testFitSignPKCS11Simple() and testFitSignPKCS11Object() (and the CI capsule tests). Please can you factor this out to a shared _SetupSoftHsm() helper on the base class and have both the FIT and pre-load tests call it? Otherwise the third copy will drift from the first two.
tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5947
Quoted 13 lines
tools/binman/ftest.py +11
-0@@ -5937,6 +5937,85 @@ fdt fdtmap Extract the devicetree blob from the fdtmap + def testPreLoadEnginePkcs11(self): + """Test a pre-load header signed through the pkcs11 OpenSSL engine""" + softhsm2_conf = self._SetupPreLoadEngine('testPreLoadEnginePkcs11.') + self._CheckPreLoadEngine('security/pre_load_engine_pkcs11.dts', + softhsm2_conf, 'pkcs-1.5') + + def testPreLoadEnginePkcs11Pss(self): + """Test a pre-load header signed through the engine with pss padding""" + softhsm2_conf = self._SetupPreLoadEngine('testPreLoadEnginePkcs11Pss.') + self._CheckPreLoadEngine('security/pre_load_engine_pkcs11_pss.dts', + softhsm2_conf, 'pss')
Both DTS files use the bare key-name = "test_key" form, so only the URI-expansion branch of _sign_engine() is exercised. The docstring in 2/3 documents key-name = "pkcs11:object=preload;type=private" as supported - please add a case using a full PKCS#11 URI so the startswith('pkcs11:') branch is covered.
tools/binman/ftest.py fdt fdtmap Extract the devicetree blob from the fdtmap · line 5943
Quoted 9 lines
tools/binman/ftest.py +7
-0@@ -5937,6 +5937,85 @@ fdt fdtmap Extract the devicetree blob from the fdtmap + def testPreLoadEngineMissingOpenssl(self): + """Test that a missing openssl is reported when using an engine""" + with terminal.capture() as (_, stderr): + self._DoTestFile('security/pre_load_engine_pkcs11.dts', + force_missing_bintools='openssl') + err = stderr.getvalue() + self.assertRegex(err, "Image 'image'.*missing bintools.*: openssl")
Nothing covers the new 'if self.engine and len(sig) != RSAS[sign_name]' check from patch 2 - with openssl forced missing the stub signature is exactly RSAS[sign_name] bytes so the check never fires. Please add a case where the engine returns a signature of the wrong size (e.g. by mocking Bintoolopenssl.sign() to return a shorter buffer) and assert that "don't have the expected size" is raised.
tools/binman/test/security/pre_load_engine_pkcs11.dts line 9
Quoted 11 lines
tools/binman/test/security/pre_load_engine_pkcs11.dts +9
-0@@ -0,0 +1,24 @@ + pre-load { + content = <&image>; + algo-name = "sha256,rsa2048"; + padding-name = "pkcs-1.5"; + key-name = "test_key"; + engine = "pkcs11"; + header-size = <4096>; + version = <0x11223344>; + };
The two DTS files differ only in padding-name. Since _CheckPreLoadEngine() already parametrises padding, please keep a single DTS and inject the padding via an entry arg or a small template rather than carrying two near-identical files.
Regards,
Simon
Hi,
gentle ping. Please let me know if there are any issues with the patches.
Thanks!
Lorenz
Quoted 28 lines · Lorenz Kofler
The pre-load entry type signs with Cryptodome, which has no PKCS#11 support, so the private key must be a file. Keys held in an HSM or on a smart card cannot be used.
Add an optional 'engine' property. When set, binman signs by running openssl with that engine and takes 'key-name' as the engine-specific key identifier.
Tested with SoftHSM via the new tests (both paddings) and with an RSA-2048 key on a YubiKey PIV slot. The tests are skipped when softhsm2-util or the pkcs11 engine is unavailable.
Lorenz Kofler (3):
binman: pre-load: Move signing into its own function
binman: pre-load: Allow signing with an OpenSSL engine
binman: pre-load: Test signing with an OpenSSL enginetools/binman/btool/openssl.py | 28 ++++ tools/binman/etype/pre_load.py | 130 ++++++++++++++---- tools/binman/ftest.py | 91 +++++++++++- .../test/security/pre_load_engine_pkcs11.dts | 24 ++++ .../security/pre_load_engine_pkcs11_pss.dts | 24 ++++ 5 files changed, 266 insertions(+), 31 deletions(-)create mode 100644
tools/binman/test/security/pre_load_engine_pkcs11.dtscreate mode 100644tools/binman/test/security/pre_load_engine_pkcs11_pss.dtsbase-commit:
444aca6d1439e4c4b9955171a7f45c053b540f69
Signature · 2 lines
sigma star gmbh | Eduard-Bodem-Gasse 6, 6020 Innsbruck, Austria UID/VAT Nr: ATU 66964118 | FN: 374287y
v2 cover binman: pre-load: Allow signing with an OpenSSL engine
In reply to Lorenz KoflerThe pre-load entry type signs with Cryptodome, which has no PKCS#11 support, so the private key must be a file. Keys held in an HSM or on a smart card cannot be used.
Add an optional 'engine' property. When set, binman signs by running openssl with that engine and takes 'key-name' as the engine-specific key identifier.
Tested with SoftHSM via the new tests (both paddings) and with an RSA-2048 key on a YubiKey PIV slot.
Simon, thank you for reviewing v1. I hope this version addresses your feedback.
Changes in v2:
- Reject a missing engine key-name before attempting to sign.
- Remove automatic PKCS#11 URI construction. Pass the engine key identifiers unchanged.
- Explain that, when OpenSSL is missing, _sign_engine() returns exactly RSAS[sign_name] zero-filled bytes so binman can report the missing tool without failing the signature-size check.
- Move the change to the testPreLoadInvalidKey() test to patch 1.
- Add a separate SoftHSM setup refactor (patch 3).
- Use one device-tree for both paddings.
- Add tests for a missing engine key name and an incorrect signature size.
Lorenz Kofler (4):
binman: pre-load: Move signing into its own function
binman: pre-load: Allow signing with an OpenSSL engine
binman: tests: Share SoftHSM token setup
binman: pre-load: Test signing with an OpenSSL engine
tools/binman/btool/openssl.py | 28 +++ tools/binman/etype/pre_load.py | 131 +++++++++--- tools/binman/ftest.py | 189 +++++++++++++----- .../test/security/pre_load_engine_pkcs11.dts | 24 +++ 4 files changed, 291 insertions(+), 81 deletions(-) create mode 100644 tools/binman/test/security/pre_load_engine_pkcs11.dts
Signature · 1 line
2.55.0
PATCH v2 1/4 binman: pre-load: Move signing into its own function
_CreateHeader() signs twice, once for the image and once for the first header, with the same key and padding. Move the signing into a _sign() helper rather than repeating it.
This is a preparation for signing with an OpenSSL engine, which needs a second implementation of _sign().
Adjust testPreLoadInvalidKey() test to verify that signing is never attempted for a key with the wrong size.
---
Changes in v2:
- Move the invalid-key test change into this patch to verify that signing is not attempted for a key with the wrong size.
tools/binman/etype/pre_load.py | 49 +++++++++++++++++++++------------- tools/binman/ftest.py | 12 ++++++--- 2 files changed, 39 insertions(+), 22 deletions(-)
tools/binman/etype/pre_load.py +30 -19
@@ -86,6 +86,31 @@ def ReadNode(self): if self.key_path is None: self.key_path = '' + def _sign(self, data, key, hash_name, padding_name): + """Sign data with a key + + Args: + data (bytes): Data to sign + key (RsaKey): Key to sign with + hash_name (str): Hash algorithm to use + padding_name (str): Padding to use + + Returns: + bytes: Signature + """ + hash_data = SHAS[hash_name].new() + hash_data.update(data) + + if padding_name == "pss": + salt_len = key.size_in_bytes() - hash_data.digest_size - 2 + padding = pss + padding_args = {'salt_bytes': salt_len} + else: + padding = pkcs1_15 + padding_args = {} + + return padding.new(key, **padding_args).sign(hash_data) + def _CreateHeader(self): """Create a pre load header""" hash_name, sign_name = self.algo_name.split(',')
@@ -105,26 +130,13 @@ def _CreateHeader(self): 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 = {} - else: + if padding_name not in ("pss", "pkcs-1.5"): self.Raise(padding_name + " is not supported") - sig = padding.new(key, **padding_args).sign(hash_image) + # Compute the signature + sig = self._sign(self.image, key, hash_name, padding_name) hash_sig = SHA256.new() hash_sig.update(sig)
@@ -142,9 +154,8 @@ def _CreateHeader(self): 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) + sig_first_header = self._sign(first_header, key, hash_name, + padding_name) data = first_header + sig_first_header + sig pad = bytearray(self.header_size - len(data))
tools/binman/ftest.py +9 -3
@@ -5903,12 +5903,18 @@ def testPreLoadInvalidAlgo(self): def testPreLoadInvalidKey(self): """Test an image with a pre-load header with an invalid key""" + from binman.etype import pre_load + entry_args = { 'pre-load-key-path': os.path.join(self._binman_dir, 'test'), } - with self.assertRaises(ValueError) as e: - data = self._DoReadFileDtb('security/pre_load_invalid_key.dts', - entry_args=entry_args) + with unittest.mock.patch.object( + pre_load.Entry_pre_load, '_sign', + side_effect=AssertionError('signing should not be attempted')): + with self.assertRaisesRegex(ValueError, + "don't have the expected size"): + self._DoReadFileDtb('security/pre_load_invalid_key.dts', + entry_args=entry_args) def testPreLoadEncryptedFit(self): """Test an encrypted FIT image with a pre-load header"""
Signature · 1 line
2.55.0
Re: [PATCH v2 1/4] binman: pre-load: Move signing into its own function
Quoted 9 lines · Lorenz Kofler
binman: pre-load: Move signing into its own function
_CreateHeader()signs twice, once for the image and once for the first header, with the same key and padding. Move the signing into a_sign()helper rather than repeating it.This is a preparation for signing with an OpenSSL engine, which needs a second implementation of
_sign().
Quoted 8 lines
Adjust
testPreLoadInvalidKey()test to verify that signing is never attempted for a key with the wrong size.Signed-off-by Lorenz Kofler <[email protected]>tools/binman/etype/pre_load.py | 49 ++++++++++++++++++++++++++---------------- tools/binman/ftest.py | 12 ++++++++--- 2 files changed, 39 insertions(+), 22 deletions(-)
PATCH v2 2/4 binman: pre-load: Allow signing with an OpenSSL engine
In reply to Lorenz KoflerThe pre-load entry type imports a private key from a file and signs with Cryptodome, so the key must be readable as a file. Keys held in an HSM or on a smart card cannot be used.
Add an optional 'engine' property. When set, sign with openssl using that engine and interpret 'key-name' as the engine-specific key identifier, instead of reading a key from 'pre-load-key-path'.
With an engine, binman never loads the key itself and so cannot check its size before signing. Check the length of the resulting RSA signature instead, which is the modulus size either way.
Behavior is otherwise unchanged when 'engine' is absent.
---
Changes in v2:
- Reject a missing engine key-name before attempting to sign.
- Remove automatic PKCS#11 URI construction. Pass the engine key identifiers unchanged.
- Explain that, when OpenSSL is missing, _sign_engine() returns exactly RSAS[sign_name] zero-filled bytes so binman can report the missing tool without failing the signature-size check.
- Move the change to the testPreLoadInvalidKey() test to patch 1.
tools/binman/btool/openssl.py | 28 +++++++++++ tools/binman/etype/pre_load.py | 88 +++++++++++++++++++++++++++++----- 2 files changed, 104 insertions(+), 12 deletions(-)
tools/binman/btool/openssl.py +28 -0
@@ -36,6 +36,34 @@ def __init__(self, name): name, 'openssl cryptography toolkit', version_regex=r'OpenSSL (.*) \(', version_args='version') + def sign(self, input_fname, output_fname, key, hash_name, padding_name, + engine=None): + """Sign a file + + The key is a filename, or, when an engine is used, anything the engine + accepts as a key identifier, e.g. a PKCS#11 URI. + + Args: + input_fname (str): Filename holding the data to sign + output_fname (str): Filename to write the signature to + key (str): Key filename, or key identifier for the engine + hash_name (str): Hash algorithm to use, e.g. 'sha256' + padding_name (str): Padding to use, 'pkcs-1.5' or 'pss' + engine (str): OpenSSL engine to use for signing, or None to sign + with a local key file + + Returns: + str: Tool output + """ + args = ['dgst', f'-{hash_name}', '-sign', key, '-out', output_fname] + if engine: + args += ['-engine', engine, '-keyform', 'engine'] + if padding_name == 'pss': + args += ['-sigopt', 'rsa_padding_mode:pss', + '-sigopt', 'rsa_pss_saltlen:max'] + args.append(input_fname) + return self.run_cmd(*args) + def x509_cert(self, cert_fname, input_fname, key_fname, cn, revision, config_fname): """Create a certificate
tools/binman/etype/pre_load.py +76 -12
150 lines not on this page · raw message
Signature · 1 line
2.55.0
Quoted 14 lines · Lorenz Kofler
binman: pre-load: Allow signing with an OpenSSL engine
The pre-load entry type imports a private key from a file and signs with Cryptodome, so the key must be readable as a file. Keys held in an HSM or on a smart card cannot be used.
Add an optional 'engine' property. When set, sign with openssl using that engine and interpret 'key-name' as the engine-specific key identifier, instead of reading a key from 'pre-load-key-path'.
With an engine, binman never loads the key itself and so cannot check its size before signing. Check the length of the resulting RSA signature instead, which is the modulus size either way.
Quoted 7 lines
Behavior is otherwise unchanged when 'engine' is absent.
Signed-off-by Lorenz Kofler <[email protected]>tools/binman/btool/openssl.py | 28 +++++++++++++ tools/binman/etype/pre_load.py | 89 ++++++++++++++++++++++++++++++++++++------ 2 files changed, 106 insertions(+), 11 deletions(-)
Quoted 42 lines
The pre-load entry type imports a private key from a file and signs with Cryptodome, so the key must be readable as a file. Keys held in an HSM or on a smart card cannot be used.
Add an optional 'engine' property. When set, sign with openssl using that engine and interpret 'key-name' as the engine-specific key identifier, instead of reading a key from 'pre-load-key-path'.
With an engine, binman never loads the key itself and so cannot check its size before signing. Check the length of the resulting RSA signature instead, which is the modulus size either way.
Behavior is otherwise unchanged when 'engine' is absent.
Signed-off-by Lorenz Kofler <[email protected]>---
Changes in v2:
- Reject a missing engine key-name before attempting to sign.
- Remove automatic PKCS#11 URI construction. Pass the engine key identifiers unchanged.
- Explain that, when OpenSSL is missing,_sign_engine()returns exactly RSAS[sign_name] zero-filled bytes so binman can report the missing tool without failing the signature-size check.
- Move the change to thetestPreLoadInvalidKey()test to patch 1.tools/binman/btool/openssl.py | 28 +++++++++++ tools/binman/etype/pre_load.py | 88 +++++++++++++++++++++++++++++----- 2 files changed, 104 insertions(+), 12 deletions(-)tools/binman/btool/openssl.py +5
-0@@ -36,6 +36,34 @@ class Bintoolopenssl(bintool.Bintool): name, 'openssl cryptography toolkit', version_regex=r'OpenSSL (.*) \(', version_args='version') + def sign(self, input_fname, output_fname, key, hash_name, padding_name, + engine=None): + """Sign a file + + The key is a filename, or, when an engine is used, anything the engine
tools/binman/btool/openssl.py class Bintoolopenssl(bintool.Bintool): · line 53
Quoted 10 lines
tools/binman/btool/openssl.py +10
-0+ accepts as a key identifier, e.g. a PKCS#11 URI. + + Args: + input_fname (str): Filename holding the data to sign + output_fname (str): Filename to write the signature to + key (str): Key filename, or key identifier for the engine + hash_name (str): Hash algorithm to use, e.g. 'sha256' + padding_name (str): Padding to use, 'pkcs-1.5' or 'pss' + engine (str): OpenSSL engine to use for signing, or None to sign + with a local key file
I didn't see a case where we call this with engine=None since we go through a different code path when the engine property is omitted. So I would just make the argument required for now. Or if I missed something, please add a test to show how it is meant to be used.
tools/binman/btool/openssl.py def __init__(self, name): · line 60
Quoted 7 lines
tools/binman/btool/openssl.py +7
-0+ + Returns: + str: Tool output + """ + args = ['dgst', f'-{hash_name}', '-sign', key, '-out', output_fname] + if engine: + args += ['-engine', engine, '-keyform', 'engine']
I expect folks will want to be able to pass a PIN via an environment variable similar to how we already have MKIMAGE_SIGN_PIN. Can we add support for that here?
if 'BINMAN_SIGN_PIN' in os.environ:
args += ['-passin', 'env:BINMAN_SIGN_PIN']
Otherwise, people will have to manually provide the PIN through the OpenSSL prompt or put the PIN somewhere less secure than an environment variable.
Signature · 1 line
David Lechner <[email protected]>
Hi David, Lorenz,
Do we really want to add support for signing with engines? OpenSSL 4.x has already removed support for them. There are providers available, so I'm assuming if we want to add support for signing with HSM, hopefully a provider is available for it and we should support that now? I'm trying to prevent the same situation we have with mkimage FIT signing with HSM where we need to support engines for backward compatibility (OpenSSL 1.x and 3.x) but providers (not there yet but I have patches) for OpenSSL 3.x+ (and necessary on OpenSSL 4.x).
As far as I remember, on OpenSSL with provider support, passing the appropriate URI scheme in the filepath should be enough for OpenSSL to use it. e.g. pkcs11: prefix is enough for OpenSSL to know it needs to use a pkcs11 provider. Which one and how to use it is better stored in openssl.conf outside of the build system. So maybe the answer is to support that in the key_name argument?
Cheers,
Quentin
Quoted 76 lines · David Lechner
Quoted 42 lines
The pre-load entry type imports a private key from a file and signs with Cryptodome, so the key must be readable as a file. Keys held in an HSM or on a smart card cannot be used.
Add an optional 'engine' property. When set, sign with openssl using that engine and interpret 'key-name' as the engine-specific key identifier, instead of reading a key from 'pre-load-key-path'.
With an engine, binman never loads the key itself and so cannot check its size before signing. Check the length of the resulting RSA signature instead, which is the modulus size either way.
Behavior is otherwise unchanged when 'engine' is absent.
Signed-off-by Lorenz Kofler <[email protected]>---
Changes in v2:
- Reject a missing engine key-name before attempting to sign.
- Remove automatic PKCS#11 URI construction. Pass the engine key identifiers unchanged.
- Explain that, when OpenSSL is missing,_sign_engine()returns exactly RSAS[sign_name] zero-filled bytes so binman can report the missing tool without failing the signature-size check.
- Move the change to thetestPreLoadInvalidKey()test to patch 1.tools/binman/btool/openssl.py | 28 +++++++++++ tools/binman/etype/pre_load.py | 88 +++++++++++++++++++++++++++++----- 2 files changed, 104 insertions(+), 12 deletions(-)tools/binman/btool/openssl.py +5
-0@@ -36,6 +36,34 @@ class Bintoolopenssl(bintool.Bintool): name, 'openssl cryptography toolkit', version_regex=r'OpenSSL (.*) \(', version_args='version') + def sign(self, input_fname, output_fname, key, hash_name, padding_name, + engine=None): + """Sign a file + + The key is a filename, or, when an engine is used, anything the enginetools/binman/btool/openssl.py class Bintoolopenssl(bintool.Bintool): · line 53
Quoted 10 lines
tools/binman/btool/openssl.py +10
-0+ accepts as a key identifier, e.g. a PKCS#11 URI. + + Args: + input_fname (str): Filename holding the data to sign + output_fname (str): Filename to write the signature to + key (str): Key filename, or key identifier for the engine + hash_name (str): Hash algorithm to use, e.g. 'sha256' + padding_name (str): Padding to use, 'pkcs-1.5' or 'pss' + engine (str): OpenSSL engine to use for signing, or None to sign + with a local key fileI didn't see a case where we call this with engine=None since we go through a different code path when the engine property is omitted. So I would just make the argument required for now. Or if I missed something, please add a test to show how it is meant to be used.
tools/binman/btool/openssl.py def __init__(self, name): · line 60
Quoted 7 lines
tools/binman/btool/openssl.py +7
-0+ + Returns: + str: Tool output + """ + args = ['dgst', f'-{hash_name}', '-sign', key, '-out', output_fname] + if engine: + args += ['-engine', engine, '-keyform', 'engine']I expect folks will want to be able to pass a PIN via an environment variable similar to how we already have
MKIMAGE_SIGN_PIN. Can we add support for that here?if '
BINMAN_SIGN_PIN' in os.environ:
args += ['-passin', 'env:BINMAN_SIGN_PIN']Otherwise, people will have to manually provide the PIN through the OpenSSL prompt or put the PIN somewhere less secure than an environment variable.
Quoted 10 lines · Quentin Schulz
Hi David, Lorenz,
Do we really want to add support for signing with engines? OpenSSL 4.x has already removed support for them. There are providers available, so I'm assuming if we want to add support for signing with HSM, hopefully a provider is available for it and we should support that now? I'm trying to prevent the same situation we have with mkimage FIT signing with HSM where we need to support engines for backward compatibility (OpenSSL 1.x and 3.x) but providers (not there yet but I have patches) for OpenSSL 3.x+ (and necessary on OpenSSL 4.x).
I know sometimes people are "stuck" with older OpenSSL versions, so if that is the case, it could justify adding engine support. If not, we could just jump straight to using providers instead so we don't have to support both.
Quoted 7 lines
As far as I remember, on OpenSSL with provider support, passing the appropriate URI scheme in the filepath should be enough for OpenSSL to use it. e.g. pkcs11: prefix is enough for OpenSSL to know it needs to use a pkcs11 provider. Which one and how to use it is better stored in openssl.conf outside of the build system. So maybe the answer is to support that in the
key_nameargument?
Sounds reasonable. I don't have any strong intuition here on which way to go about it would be best.
Signature · 1 line
David Lechner <[email protected]>
Quoted 12 lines · David Lechner
Quoted 10 lines · Quentin Schulz
Hi David, Lorenz,
Do we really want to add support for signing with engines? OpenSSL 4.x has already removed support for them. There are providers available, so I'm assuming if we want to add support for signing with HSM, hopefully a provider is available for it and we should support that now? I'm trying to prevent the same situation we have with mkimage FIT signing with HSM where we need to support engines for backward compatibility (OpenSSL 1.x and 3.x) but providers (not there yet but I have patches) for OpenSSL 3.x+ (and necessary on OpenSSL 4.x).
Quoted 4 lines
I know sometimes people are "stuck" with older OpenSSL versions, so if that is the case, it could justify adding engine support. If not, we could just jump straight to using providers instead so we don't have to support both.
It depends how old they need to go. If they only need to support OpenSSL 3.x+ but cannot go with an actual provider (yet), then they can still use an engine via the provider path and we avoid having to support the old syntax forever. The prefix is org.openssl.engine:. Sergio has done this for x509 certificates for example, c.f. https://lore.kernel.org/u-boot/[email protected]/
Cheers,
Quentin
Quoted 11 lines
Quoted 7 lines
As far as I remember, on OpenSSL with provider support, passing the appropriate URI scheme in the filepath should be enough for OpenSSL to use it. e.g. pkcs11: prefix is enough for OpenSSL to know it needs to use a pkcs11 provider. Which one and how to use it is better stored in openssl.conf outside of the build system. So maybe the answer is to support that in the
key_nameargument?Sounds reasonable. I don't have any strong intuition here on which way to go about it would be best.
PATCH v2 3/4 binman: tests: Share SoftHSM token setup
In reply to Lorenz KoflerFactor SoftHSM configuration setup into _SetupSoftHsm(). Use it for tests testPkcs11SignedCapsuleGen(), testFitSignPKCS11Simple() and testFitSignPKCS11Object().
---
Changes in v2:
- New patch: share SoftHSM setup between tests.
tools/binman/ftest.py | 89 +++++++++++++++++++------------------------ 1 file changed, 39 insertions(+), 50 deletions(-)
tools/binman/ftest.py +39 -50
@@ -5937,6 +5937,38 @@ def testPreLoadEncryptedFit(self): self.assertEqual(PRE_LOAD_HDR_SIZE, data[8:8 + len(PRE_LOAD_HDR_SIZE)]) self.assertEqual(is_signed, True) + def _SetupSoftHsm(self, softhsm2_util, prefix, private_key, + token='U-Boot token', label='test_key', pin='1111'): + """Set up a SoftHSM token containing a private key + + Args: + softhsm2_util (Bintool): SoftHSM bintool to use for token setup + prefix (str): Prefix for the files created in the input directory + private_key (str): Filename of the private key to import + token (str): Token label + label (str): Private-key object label + pin (str): User PIN for the token + + Returns: + str: Filename of the SoftHSM configuration file + """ + data = tools.read_file(self.TestFile('fit/softhsm2.conf')) + softhsm2_tokens_dir = self._MakeInputDir(f'{prefix}softhsm2.tokens') + softhsm2_conf = self._MakeInputFile( + f'{prefix}softhsm2.conf', + data + f'directories.tokendir = {softhsm2_tokens_dir}\n'.encode()) + + with unittest.mock.patch.dict('os.environ', + {'SOFTHSM2_CONF': softhsm2_conf}): + softhsm2_util.run_cmd('--init-token', '--free', '--label', + token, '--pin', pin, + '--so-pin', '222222') + softhsm2_util.run_cmd('--import', private_key, + '--token', token, '--label', + label, '--id', '999999', '--pin', pin) + + return softhsm2_conf + def _CheckSafeUniqueNames(self, *images): """Check all entries of given images for unsafe unique names""" for image in images:
@@ -7593,14 +7625,8 @@ def testPkcs11SignedCapsuleGen(self): pkcs11_tool = bintool.Bintool.create('pkcs11-tool') self._CheckBintool(pkcs11_tool) - prefix = "testPkcs11SignedCapsuleGen." - # 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') + softhsm2_conf = self._SetupSoftHsm( + softhsm2_util, 'testPkcs11SignedCapsuleGen.', private_key) # Find the path to softhsm2 library p11_kit = bintool.Bintool.create('p11-kit')
@@ -7616,16 +7642,10 @@ def testPkcs11SignedCapsuleGen(self): with unittest.mock.patch.dict('os.environ', {'SOFTHSM2_CONF': softhsm2_conf, 'PKCS11_MODULE_PATH': softhsm2_lib}): - softhsm2_util.run_cmd('--init-token', '--free', '--label', - 'U-Boot token', '--pin', '1111', - '--so-pin', '222222') pkcs11_tool.run_cmd('--module', softhsm2_lib, '--write-object', cert_file, '--pin', '1111', '--type', 'cert', '--id', '999999', '--label', 'test_cert', '--login') - softhsm2_util.run_cmd('--import', private_key, '--token', - 'U-Boot token', '--label', 'test_key', - '--id', '999999', '--pin', '1111') data = self._DoReadFile('capsule/signed_pkcs11.dts') self._CheckCapsule(data, signed_capsule=True)
@@ -8359,26 +8379,10 @@ def testFitSignPKCS11Simple(self): self.skipTest('PKCS11 engine setup not functional, ' 'did you install libengine-pkcs11-openssl?') - prefix = "testFitSignPKCS11Simple." - # 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') - # Generate pubkey DTB with random RSA4096 key _, _, private_key, pubkey_dtb = self._PrepareSignEnv() - - with unittest.mock.patch.dict('os.environ', - {'SOFTHSM2_CONF': softhsm2_conf}): - softhsm2_util.run_cmd('--init-token', '--free', '--label', - 'U-Boot token', '--pin', '1111', - '--so-pin', '222222') - softhsm2_util.run_cmd('--import', private_key, '--token', - 'U-Boot token', '--label', 'test_key', - '--id', '999999', '--pin', '1111') + softhsm2_conf = self._SetupSoftHsm( + softhsm2_util, 'testFitSignPKCS11Simple.', private_key) # Make sure the private key can only be accessed through the engine os.remove(private_key)
@@ -8434,26 +8438,11 @@ def testFitSignPKCS11Object(self): self.skipTest('PKCS11 engine setup not functional, ' 'did you install libengine-pkcs11-openssl?') - prefix = "testFitSignPKCS11Object." - # 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}') - # Generate pubkey DTB with random RSA4096 key _, _, private_key, pubkey_dtb = self._PrepareSignEnv() - - with unittest.mock.patch.dict('os.environ', - {'SOFTHSM2_CONF': softhsm2_conf}): - softhsm2_util.run_cmd('--init-token', '--free', '--label', - 'U-Boot prod token', '--pin', '1234', - '--so-pin', '222222') - softhsm2_util.run_cmd('--import', private_key, '--token', - 'U-Boot prod token', '--label', 'prod', - '--id', '999999', '--pin', '1234') + softhsm2_conf = self._SetupSoftHsm( + softhsm2_util, 'testFitSignPKCS11Object.', private_key, + token='U-Boot prod token', label='prod', pin='1234') # Make sure the private key can only be accessed through the engine os.remove(private_key)
Signature · 1 line
2.55.0
Re: [PATCH v2 3/4] binman: tests: Share SoftHSM token setup
Quoted 10 lines · Lorenz Kofler
binman: tests: Share SoftHSM token setup
Factor SoftHSM configuration setup into
_SetupSoftHsm(). Use it for teststestPkcs11SignedCapsuleGen(),testFitSignPKCS11Simple()andtestFitSignPKCS11Object().Signed-off-by Lorenz Kofler <[email protected]>tools/binman/ftest.py | 89 ++++++++++++++++++++++----------------------------- 1 file changed, 39 insertions(+), 50 deletions(-)
PATCH v2 4/4 binman: pre-load: Test signing with an OpenSSL engine
In reply to Lorenz KoflerTest pre-load signing through the pkcs11 engine with a key imported into SoftHSM.
Add tests for:
- PKCS#11 signing with PKCS1.5 padding.
- PKCS#11 signing with PSS padding.
- Reporting a missing OpenSSL bintool.
- Rejecting a missing engine key name before signing.
- Rejecting an engine signature with an incorrect size.
---
Changes in v2:
- Use the separate SoftHSM setup refactor introduced in patch 3.
- Use one device-tree for both paddings.
- Add tests for a missing engine key name and an incorrect signature size.
tools/binman/ftest.py | 88 +++++++++++++++++++ .../test/security/pre_load_engine_pkcs11.dts | 24 +++++ 2 files changed, 112 insertions(+) create mode 100644 tools/binman/test/security/pre_load_engine_pkcs11.dts
tools/binman/ftest.py +88 -0
@@ -5969,6 +5969,94 @@ def _SetupSoftHsm(self, softhsm2_util, prefix, private_key, return softhsm2_conf + def _CheckPreLoadEngine(self, padding): + """Sign an image through the pkcs11 engine and check the signature + + Args: + padding (str): Padding used by the device tree + """ + softhsm2_util = bintool.Bintool.create('softhsm2_util') + self._CheckBintool(softhsm2_util) + + try: + tools.run('openssl', 'engine', 'dynamic', '-c', 'pkcs11') + except ValueError: + self.skipTest('PKCS11 engine setup not functional, ' + 'did you install libengine-pkcs11-openssl?') + + softhsm2_conf = self._SetupSoftHsm( + softhsm2_util, f'pre_load_engine_{padding}.', + self.TestFile('dev.key')) + + data = tools.read_file( + self.TestFile('security/pre_load_engine_pkcs11.dts')) + data = data.replace(b'padding-name = "pkcs-1.5";', + f'padding-name = "{padding}";'.encode()) + dts = self._MakeInputFile(f'pre_load_engine_{padding}.dts', data) + + ossl_conf = self.TestFile('fit/openssl.conf') + with unittest.mock.patch.dict('os.environ', + {'OPENSSL_CONF': ossl_conf, + 'SOFTHSM2_CONF': softhsm2_conf}): + data = self._DoReadFile(dts) + + image_fname = tools.get_output_filename('image.bin') + is_signed = self._CheckPreload(image_fname, self.TestFile('dev.key'), + padding=padding) + + 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 testPreLoadEnginePkcs11(self): + """Test a pre-load header signed through the pkcs11 OpenSSL engine""" + self._CheckPreLoadEngine('pkcs-1.5') + + def testPreLoadEnginePkcs11Pss(self): + """Test a pre-load header signed through the engine with pss padding""" + self._CheckPreLoadEngine('pss') + + def testPreLoadEngineMissingOpenssl(self): + """Test that a missing openssl is reported when using an engine""" + with terminal.capture() as (_, stderr): + self._DoTestFile('security/pre_load_engine_pkcs11.dts', + force_missing_bintools='openssl') + err = stderr.getvalue() + self.assertRegex(err, "Image 'image'.*missing bintools.*: openssl") + + def testPreLoadEngineMissingKey(self): + """Test that an engine requires a key name before signing""" + from binman.etype import pre_load + + data = tools.read_file( + self.TestFile('security/pre_load_engine_pkcs11.dts')) + data = data.replace( + b'key-name = "pkcs11:object=test_key;type=private";', b'') + dts = self._MakeInputFile('pre_load_engine_missing_key.dts', data) + + with unittest.mock.patch.object( + pre_load.Entry_pre_load, '_sign', + side_effect=AssertionError('signing should not be attempted')): + with self.assertRaisesRegex( + ValueError, 'key-name must be provided when using an engine'): + self._DoReadFile(dts) + + def testPreLoadEngineInvalidKeySize(self): + """Test that an engine signature with the wrong size is rejected""" + from binman.btool import openssl + + def sign(input_fname, output_fname, key, hash_name, padding_name, + engine=None): + tools.write_file(output_fname, tools.get_bytes(0, 128)) + return '' + + with unittest.mock.patch.object(openssl.Bintoolopenssl, 'sign', + side_effect=sign): + with self.assertRaisesRegex(ValueError, + "don't have the expected size"): + self._DoReadFile('security/pre_load_engine_pkcs11.dts') + def _CheckSafeUniqueNames(self, *images): """Check all entries of given images for unsafe unique names""" for image in images:
tools/binman/test/security/pre_load_engine_pkcs11.dts new file +24 -0
@@ -0,0 +1,24 @@ +// 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 = "pkcs11:object=test_key;type=private"; + engine = "pkcs11"; + header-size = <4096>; + version = <0x11223344>; + }; + + image: blob-ext { + filename = "refcode.bin"; + }; + }; +};
Signature · 1 line
2.55.0
Re: [PATCH v2 4/4] binman: pre-load: Test signing with an OpenSSL engine
Quoted 13 lines · Lorenz Kofler
binman: pre-load: Test signing with an OpenSSL engine
Test pre-load signing through the pkcs11 engine with a key imported into SoftHSM.
Add tests for:
- PKCS#11 signing with PKCS1.5 padding.
- PKCS#11 signing with PSS padding.
- Reporting a missing OpenSSL bintool.
- Rejecting a missing engine key name before signing.
- Rejecting an engine signature with an incorrect size.
Quoted 5 lines
Signed-off-by Lorenz Kofler <[email protected]>tools/binman/ftest.py | 88 ++++++++++++++++++++++ .../test/security/pre_load_engine_pkcs11.dts | 24 ++++++ 2 files changed, 112 insertions(+)
Re: [PATCH v2 4/4] binman: pre-load: Test signing with an OpenSSL engine
In reply to Lorenz KoflerQuoted 28 lines
Test pre-load signing through the pkcs11 engine with a key imported into SoftHSM.
Add tests for:
- PKCS#11 signing with PKCS1.5 padding.
- PKCS#11 signing with PSS padding.
- Reporting a missing OpenSSL bintool.
- Rejecting a missing engine key name before signing.
- Rejecting an engine signature with an incorrect size.Signed-off-by Lorenz Kofler <[email protected]>---
Changes in v2:
- Use the separate SoftHSM setup refactor introduced in patch 3.
- Use one device-tree for both paddings.
- Add tests for a missing engine key name and an incorrect signature size.tools/binman/ftest.py | 88 +++++++++++++++++++ .../test/security/pre_load_engine_pkcs11.dts | 24 +++++ 2 files changed, 112 insertions(+) create mode 100644 tools/binman/test/security/pre_load_engine_pkcs11.dtstools/binman/ftest.py +0
-0
...
tools/binman/ftest.py def _SetupSoftHsm(self, softhsm2_util, prefix, private_key, · line 6040
Quoted 13 lines
tools/binman/ftest.py +13
-0+ def testPreLoadEngineMissingKey(self): + """Test that an engine requires a key name before signing""" + from binman.etype import pre_load + + data = tools.read_file( + self.TestFile('security/pre_load_engine_pkcs11.dts')) + data = data.replace( + b'key-name = "pkcs11:object=test_key;type=private";', b'') + dts = self._MakeInputFile('pre_load_engine_missing_key.dts', data) + + with unittest.mock.patch.object( + pre_load.Entry_pre_load, '_sign', + side_effect=AssertionError('signing should not be attempted')):
Do we really need to patch '_sign' here? The test will still fail anyway if the exception is not raised.
Quoted 5 lines
tools/binman/ftest.py +5
-0+ with self.assertRaisesRegex( + ValueError, 'key-name must be provided when using an engine'): + self._DoReadFile(dts) + + def testPreLoadEngineInvalidKeySize(self):
tools/binman/ftest.py def _SetupSoftHsm(self, softhsm2_util, prefix, private_key, · line 6055
Quoted 10 lines
tools/binman/ftest.py +10
-0+ """Test that an engine signature with the wrong size is rejected""" + from binman.btool import openssl + + def sign(input_fname, output_fname, key, hash_name, padding_name, + engine=None): + tools.write_file(output_fname, tools.get_bytes(0, 128)) + return '' + + with unittest.mock.patch.object(openssl.Bintoolopenssl, 'sign', + side_effect=sign):
Why are we mocking sign here? We have SoftHSM, so could do a proper test.
Quoted 13 lines
tools/binman/ftest.py +4
-0+ with self.assertRaisesRegex(ValueError, + "don't have the expected size"): + self._DoReadFile('security/pre_load_engine_pkcs11.dts') + def _CheckSafeUniqueNames(self, *images): """Check all entries of given images for unsafe unique names""" for image in images:tools/binman/test/security/pre_load_engine_pkcs11.dts new file +0
-0
tools/binman/test/security/pre_load_engine_pkcs11.dts line 1
Quoted 1 line
tools/binman/test/security/pre_load_engine_pkcs11.dts new file +1
-0@@ -0,0 +1,24 @@ +// SPDX-License-Identifier: GPL-2.0+
nit: GPL-2.0+ is deprecated, prefer GPL-2.0-or-later
Signature · 1 line
David Lechner <[email protected]>
Quoted 33 lines · Lorenz Kofler
The pre-load entry type signs with Cryptodome, which has no PKCS#11 support, so the private key must be a file. Keys held in an HSM or on a smart card cannot be used.
Add an optional 'engine' property. When set, binman signs by running openssl with that engine and takes 'key-name' as the engine-specific key identifier.
Tested with SoftHSM via the new tests (both paddings) and with an RSA-2048 key on a YubiKey PIV slot.
Simon, thank you for reviewing v1. I hope this version addresses your feedback.
Changes in v2:
- Reject a missing engine key-name before attempting to sign.
- Remove automatic PKCS#11 URI construction. Pass the engine key identifiers unchanged.
- Explain that, when OpenSSL is missing,_sign_engine()returns exactly RSAS[sign_name] zero-filled bytes so binman can report the missing tool without failing the signature-size check.
- Move the change to thetestPreLoadInvalidKey()test to patch 1.
- Add a separate SoftHSM setup refactor (patch 3).
- Use one device-tree for both paddings.
- Add tests for a missing engine key name and an incorrect signature size.Lorenz Kofler (4):
binman: pre-load: Move signing into its own function
binman: pre-load: Allow signing with an OpenSSL engine
binman: tests: Share SoftHSM token setup
binman: pre-load: Test signing with an OpenSSL engine
Quoted 11 lines
tools/binman/btool/openssl.py | 28 +++ tools/binman/etype/pre_load.py | 131 +++++++++--- tools/binman/ftest.py | 189 +++++++++++++----- .../test/security/pre_load_engine_pkcs11.dts | 24 +++ 4 files changed, 291 insertions(+), 81 deletions(-) create mode 100644 tools/binman/test/security/pre_load_engine_pkcs11.dtsSignature · 1 line
2.55.0
This needs to be rebased on the next branch as it conflicts with the pre-load ECDSA support that was picked up in the meantime.
https://git.u-boot-project.org/u-boot/u-boot/-/commit/7f651808b40c8ab0ed568b9d2abca369130180fe
Signature · 1 line
David Lechner <[email protected]>