aes: Allow to store randomly generated IV in the FIT
PATCH v3 1/3 aes: Allow to store randomly generated IV in the FIT
When the initialisation vector is randomly generated, its value shall be stored in the FIT together with the encrypted data. The changes allow to store the IV in the FIT also in the case where the key is not stored in the DTB but retrieved somewhere else at runtime.
--- lib/aes/aes-encrypt.c | 7 +++++++ tools/image-host.c | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-)
lib/aes/aes-encrypt.c +7 -0
@@ -84,6 +84,13 @@ int image_aes_add_cipher_data(struct image_cipher_info *info, void *keydest,char name[128 ];int ret =0 ; +if (!keydest && !info->ivname) { +/* At least, store the IV in the FIT image */ + ret =fdt_setprop (fit, node_noffset,"iv" , + info->iv, info->cipher->iv_len); + goto done; + } +/* Either create or overwrite the named cipher node */ parent =fdt_subnode_offset (keydest,0 ,FIT_CIPHER_NODENAME );if (parent == -FDT_ERR_NOTFOUND ) {
tools/image-host.c +1 -1
@@ -535,7 +535,7 @@ fit_image_process_cipher(const char *keydir, void *keydest, void *fit,* size values * And, if needed, write the iv in the FIT file */ -if (keydest) { +if (keydest || (!keydest && !info.ivname)) { ret = info.cipher->add_cipher_data (&info, keydest, fit, node_noffset);if (ret) { fprintf(stderr,
Signature · 1 line
2.43.0
PATCH v3 2/3 tools: binman: Replace 'fit, sign' by 'fit, keys-directory'
mkimage can be used for both signing the FIT or encrypt its content and the option '-k' can be used to pass a directory where both signing and encryption keys can be retrieved._get_priv_keys_dir() is also renamed as _get_keys_dir() and adapted to support both signing and encryption nodes in the FIT.
---
Changes for v3:
- Adapt the code after changes made in commit 133c000ca334
- Rename property 'fit,sign' as 'fit,keys-directory' since this is not only about signing but passing a key directory to mkimage for both signing and encrypting
- Update the tests and documentation accordingly
My initial changes proposed in v1 and v2 has been outdated by the changes proposed in commit 133c000ca334.
tools/binman/btool/mkimage.py | 8 +++---- tools/binman/entries.rst | 13 ++++++----- tools/binman/etype/fit.py | 31 ++++++++++++++----------- tools/binman/ftest.py | 2 +- tools/binman/test/340_fit_signature.dts | 2 +- tools/binman/test/341_fit_signature.dts | 2 +- tools/binman/test/342_fit_signature.dts | 2 +- 7 files changed, 32 insertions(+), 28 deletions(-)
tools/binman/btool/mkimage.py +4 -4
@@ -22,7 +22,7 @@ class Bintoolmkimage(bintool.Bintool): # pylint: disable=R0913 def run(self, reset_timestamp=False, output_fname=None, external=False, - pad=None, align=None, priv_keys_dir=None): + pad=None, align=None, keys_dir=None): """Run mkimage Args:
@@ -34,7 +34,7 @@ class Bintoolmkimage(bintool.Bintool): other things to be easily added later, if required, such as signatures align: Bytes to use for alignment of the FIT and its external data - priv_keys_dir: Path to directory containing private keys + keys_dir: Path to directory containing private and encryption keys version: True to get the mkimage version """ args = []
@@ -46,8 +46,8 @@ class Bintoolmkimage(bintool.Bintool): args += ['-B', f'{align:x}'] if reset_timestamp: args.append('-t') - if priv_keys_dir: - args += ['-k', f'{priv_keys_dir}'] + if keys_dir: + args += ['-k', f'{keys_dir}'] if output_fname: args += ['-F', output_fname] return self.run_cmd(*args)
tools/binman/entries.rst +7 -6
@@ -864,12 +864,13 @@ The top-level 'fit' node supports the following special properties: fit,fdt-list-dir = "arch/arm/dts - fit,sign - Enable signing FIT images via mkimage as described in - verified-boot.rst. If the property is found, the private keys path is - detected among binman include directories and passed to mkimage via - -k flag. All the keys required for signing FIT must be available at - time of signing and must be located in single include directory. + fit,keys-directory + Look for a directory where signing and encryption keys are stored. + If the property is found, the keys path is detected among binman + include directories and passed to mkimage via -k flag. All the keys + required for signing and encrypting the FIT must be available at the + time of signing and encrypting and must be located in a single + include directory. Substitutions ~~~~~~~~~~~~~
tools/binman/etype/fit.py +17 -14
@@ -102,13 +102,13 @@ class Entry_fit(Entry_section): In this case the input directories are ignored and all devicetree files must be in that directory. - fit,sign - Enable signing FIT images via mkimage as described in - verified-boot.rst. If the property is found, the private keys path - is detected among binman include directories and passed to mkimage - via -k flag. All the keys required for signing FIT must be - available at time of signing and must be located in single include - directory. + fit,keys-directory + Look for a directory where signing and encryption keys are stored. + If the property is found, the keys path is detected among binman + include directories and passed to mkimage via -k flag. All the keys + required for signing and encrypting the FIT must be available at the + time of signing and encrypting and must be located in a single + include directory. Substitutions ~~~~~~~~~~~~~
@@ -518,14 +518,14 @@ class Entry_fit(Entry_section): # are removed from self._entries later. self._priv_entries = dict(self._entries) - def _get_priv_keys_dir(self, data): - """Detect private keys path among binman include directories + def _get_keys_dir(self, data): + """Detect private and encryption keys path among binman include directories Args: data: FIT image in binary format Returns: - str: Single path containing all private keys found or None + str: Single path containing all keys found or None Raises: ValueError: Filename 'rsa2048.key' not found in input path
@@ -533,11 +533,14 @@ class Entry_fit(Entry_section): """ def _find_keys_dir(node): for subnode in node.subnodes: - if subnode.name.startswith('signature'): + if (subnode.name.startswith('signature') or + subnode.name.startswith('cipher')): if subnode.props.get('key-name-hint') is None: continue hint = subnode.props['key-name-hint'].value - name = tools.get_input_filename(f"{hint}.key") + name = tools.get_input_filename( + f"{hint}.key" if subnode.name.startswith('signature') + else f"{hint}.bin") path = os.path.dirname(name) if path not in paths: paths.append(path)
@@ -587,8 +590,8 @@ class Entry_fit(Entry_section): align = self._fit_props.get('fit,align') if align is not None: args.update({'align': fdt_util.fdt32_to_cpu(align.value)}) - if self._fit_props.get('fit,sign') is not None: - args.update({'priv_keys_dir': self._get_priv_keys_dir(data)}) + if self._fit_props.get('fit,keys-directory') is not None: + args.update({'keys_dir': self._get_keys_dir(data)}) if self.mkimage.run(reset_timestamp=True, output_fname=output_fname, **args) is None: if not self.GetAllowMissing():
tools/binman/ftest.py +1 -1
@@ -7885,7 +7885,7 @@ fdt fdtmap Extract the devicetree blob from the fdtmap str(e.exception)) def testFitSignNoSingatureNodes(self): - """Test that fit,sign doens't raise error if no signature nodes found""" + """Test that fit,keys-directory doesn't raise error if no signature nodes found""" if not elf.ELF_TOOLS: self.skipTest('Python elftools not available') entry_args = {
tools/binman/test/340_fit_signature.dts +1 -1
@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot {
tools/binman/test/341_fit_signature.dts +1 -1
@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot {
tools/binman/test/342_fit_signature.dts +1 -1
@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot {
Signature · 1 line
2.43.0
Re: [PATCH v3 2/3] tools: binman: Replace 'fit, sign' by 'fit, keys-directory'
Hi Paul,
Quoted 19 lines · Paul HENRYS
mkimage can be used for both signing the FIT or encrypt its content and the option '-k' can be used to pass a directory where both signing and encryption keys can be retrieved.
_get_priv_keys_dir()is also renamed as_get_keys_dir()and adapted to support both signing and encryption nodes in the FIT.Signed-off-by Paul HENRYS <[email protected]>---
Changes for v3:
- Adapt the code after changes made in commit133c000ca334
- Rename property 'fit,sign' as 'fit,keys-directory' since this is not only about signing but passing a key directory to mkimage for both signing and encrypting
- Update the tests and documentation accordinglyMy initial changes proposed in v1 and v2 has been outdated by the changes proposed in commit
133c000ca334.
Quoted 8 lines
tools/binman/btool/mkimage.py | 8 +++---- tools/binman/entries.rst | 13 ++++++----- tools/binman/etype/fit.py | 31 ++++++++++++++----------- tools/binman/ftest.py | 2 +- tools/binman/test/340_fit_signature.dts | 2 +- tools/binman/test/341_fit_signature.dts | 2 +- tools/binman/test/342_fit_signature.dts | 2 +- 7 files changed, 32 insertions(+), 28 deletions(-)
I think it is good to be able to specify the keys directory and not just rely on Binman's input path. But do we need to remove the fit,sign property? It is the signal that signing should be done., although I understand that there is a key directory too.
If we need to remove it, please do that in a separate patch.
Perhaps we also need a signal that encryption should be done?
Quoted 182 lines
tools/binman/btool/mkimage.py +4
-4@@ -22,7 +22,7 @@ class Bintoolmkimage(bintool.Bintool): # pylint: disable=R0913 def run(self, reset_timestamp=False, output_fname=None, external=False, - pad=None, align=None, priv_keys_dir=None): + pad=None, align=None, keys_dir=None): """Run mkimage Args:@@ -34,7 +34,7 @@ class Bintoolmkimage(bintool.Bintool): other things to be easily added later, if required, such as signatures align: Bytes to use for alignment of the FIT and its external data - priv_keys_dir: Path to directory containing private keys + keys_dir: Path to directory containing private and encryption keys version: True to get the mkimage version """ args = []@@ -46,8 +46,8 @@ class Bintoolmkimage(bintool.Bintool): args += ['-B', f'{align:x}'] if reset_timestamp: args.append('-t') - if priv_keys_dir: - args += ['-k', f'{priv_keys_dir}'] + if keys_dir: + args += ['-k', f'{keys_dir}'] if output_fname: args += ['-F', output_fname] return self.run_cmd(*args)tools/binman/entries.rst +7
-6@@ -864,12 +864,13 @@ The top-level 'fit' node supports the following special properties: fit,fdt-list-dir = "arch/arm/dts - fit,sign - Enable signing FIT images via mkimage as described in - verified-boot.rst. If the property is found, the private keys path is - detected among binman include directories and passed to mkimage via - -k flag. All the keys required for signing FIT must be available at - time of signing and must be located in single include directory. + fit,keys-directory + Look for a directory where signing and encryption keys are stored. + If the property is found, the keys path is detected among binman + include directories and passed to mkimage via -k flag. All the keys + required for signing and encrypting the FIT must be available at the + time of signing and encrypting and must be located in a single + include directory. Substitutions ~~~~~~~~~~~~~tools/binman/etype/fit.py +17
-14@@ -102,13 +102,13 @@ class Entry_fit(Entry_section): In this case the input directories are ignored and all devicetree files must be in that directory. - fit,sign - Enable signing FIT images via mkimage as described in - verified-boot.rst. If the property is found, the private keys path - is detected among binman include directories and passed to mkimage - via -k flag. All the keys required for signing FIT must be - available at time of signing and must be located in single include - directory. + fit,keys-directory + Look for a directory where signing and encryption keys are stored. + If the property is found, the keys path is detected among binman + include directories and passed to mkimage via -k flag. All the keys + required for signing and encrypting the FIT must be available at the + time of signing and encrypting and must be located in a single + include directory. Substitutions ~~~~~~~~~~~~~@@ -518,14 +518,14 @@ class Entry_fit(Entry_section): # are removed from self._entries later. self._priv_entries = dict(self._entries) - def _get_priv_keys_dir(self, data): - """Detect private keys path among binman include directories + def _get_keys_dir(self, data): + """Detect private and encryption keys path among binman include directories Args: data: FIT image in binary format Returns: - str: Single path containing all private keys found or None + str: Single path containing all keys found or None Raises: ValueError: Filename 'rsa2048.key' not found in input path@@ -533,11 +533,14 @@ class Entry_fit(Entry_section): """ def _find_keys_dir(node): for subnode in node.subnodes: - if subnode.name.startswith('signature'): + if (subnode.name.startswith('signature') or + subnode.name.startswith('cipher')): if subnode.props.get('key-name-hint') is None: continue hint = subnode.props['key-name-hint'].value - name = tools.get_input_filename(f"{hint}.key") + name = tools.get_input_filename( + f"{hint}.key" if subnode.name.startswith('signature') + else f"{hint}.bin") path = os.path.dirname(name) if path not in paths: paths.append(path)@@ -587,8 +590,8 @@ class Entry_fit(Entry_section): align = self._fit_props.get('fit,align') if align is not None: args.update({'align': fdt_util.fdt32_to_cpu(align.value)}) - if self._fit_props.get('fit,sign') is not None: - args.update({'priv_keys_dir': self._get_priv_keys_dir(data)}) + if self._fit_props.get('fit,keys-directory') is not None: + args.update({'keys_dir': self._get_keys_dir(data)}) if self.mkimage.run(reset_timestamp=True, output_fname=output_fname, **args) is None: if not self.GetAllowMissing():tools/binman/ftest.py +1
-1@@ -7885,7 +7885,7 @@ fdt fdtmap Extract the devicetree blob from the fdtmap str(e.exception)) def testFitSignNoSingatureNodes(self): - """Test that fit,sign doens't raise error if no signature nodes found""" + """Test that fit,keys-directory doesn't raise error if no signature nodes found""" if not elf.ELF_TOOLS: self.skipTest('Python elftools not available') entry_args = {tools/binman/test/340_fit_signature.dts +1
-1@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot {tools/binman/test/341_fit_signature.dts +1
-1@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot {tools/binman/test/342_fit_signature.dts +1
-2@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot { --
Quoted 1 line
2.43.0
[..]
Regards,
Simon
Re: [PATCH v3 2/3] tools: binman: Replace 'fit,sign' by 'fit,keys-directory'
Hi Simon,
Quoted 32 lines · Simon Glass
This Mail comes from Outside of SoftAtHome: Do not answer, click links or open attachments unless you recognize the sender and know the content is safe.
Hi Paul,
Quoted 18 lines · Paul HENRYS
mkimage can be used for both signing the FIT or encrypt its content and the option '-k' can be used to pass a directory where both signing and encryption keys can be retrieved.
_get_priv_keys_dir()is also renamed as_get_keys_dir()and adapted to support both signing and encryption nodes in the FIT.Signed-off-by Paul HENRYS <[email protected]>---
Changes for v3:
- Adapt the code after changes made in commit133c000ca334
- Rename property 'fit,sign' as 'fit,keys-directory' since this is not only about signing but passing a key directory to mkimage for both signing and encrypting
- Update the tests and documentation accordinglyMy initial changes proposed in v1 and v2 has been outdated by the changes proposed in commit
133c000ca334.Quoted 8 lines
tools/binman/btool/mkimage.py | 8 +++---- tools/binman/entries.rst | 13 ++++++----- tools/binman/etype/fit.py | 31 ++++++++++++++----------- tools/binman/ftest.py | 2 +- tools/binman/test/340_fit_signature.dts | 2 +- tools/binman/test/341_fit_signature.dts | 2 +- tools/binman/test/342_fit_signature.dts | 2 +- 7 files changed, 32 insertions(+), 28 deletions(-)
Quoted 8 lines
I think it is good to be able to specify the keys directory and not just rely on Binman's input path. But do we need to remove the fit,sign property? It is the signal that signing should be done., although I understand that there is a key directory too.
If we need to remove it, please do that in a separate patch.
Perhaps we also need a signal that encryption should be done?
Based on my understanding, we don't enable the signing by adding 'fit,sign' property but by having a signature node in the DTS passed to binman and thus also in the ITS passed to mkimage by binman (at least with the current implementation). In the current implementation, adding 'fit,sign property' in the DTS passed to binman only leads to add the argument '-k' with a directory where the private keys are stored and nothing more. The '-k' argument of mkimage is used to specify the keys directory for both signing and ciphering FIT data. That is why I thought the property could be shared for providing the keys directory for both signing and ciphering when generating the FIT. Then maybe your idea would be to use such a property, i.e. 'fit,sign' property, to be able to add more options related to the signature (key-name-hint, algo...) instead of having those information in the ITS in a signature node. In this case, I guess it would indeed make sense to have separate properties that could both set the '-k' argument passed to mkimage.
The current signal for the encryption is to have a 'cipher' node in the ITS provided to mkimage.
Quoted 187 lines
Quoted 182 lines
tools/binman/btool/mkimage.py +4
-4@@ -22,7 +22,7 @@ class Bintoolmkimage(bintool.Bintool): # pylint: disable=R0913 def run(self, reset_timestamp=False, output_fname=None, external=False, - pad=None, align=None, priv_keys_dir=None): + pad=None, align=None, keys_dir=None): """Run mkimage Args:@@ -34,7 +34,7 @@ class Bintoolmkimage(bintool.Bintool): other things to be easily added later, if required, such as signatures align: Bytes to use for alignment of the FIT and its external data - priv_keys_dir: Path to directory containing private keys + keys_dir: Path to directory containing private and encryption keys version: True to get the mkimage version """ args = []@@ -46,8 +46,8 @@ class Bintoolmkimage(bintool.Bintool): args += ['-B', f'{align:x}'] if reset_timestamp: args.append('-t') - if priv_keys_dir: - args += ['-k', f'{priv_keys_dir}'] + if keys_dir: + args += ['-k', f'{keys_dir}'] if output_fname: args += ['-F', output_fname] return self.run_cmd(*args)tools/binman/entries.rst +7
-6@@ -864,12 +864,13 @@ The top-level 'fit' node supports the following special properties: fit,fdt-list-dir = "arch/arm/dts - fit,sign - Enable signing FIT images via mkimage as described in - verified-boot.rst. If the property is found, the private keys path is - detected among binman include directories and passed to mkimage via - -k flag. All the keys required for signing FIT must be available at - time of signing and must be located in single include directory. + fit,keys-directory + Look for a directory where signing and encryption keys are stored. + If the property is found, the keys path is detected among binman + include directories and passed to mkimage via -k flag. All the keys + required for signing and encrypting the FIT must be available at the + time of signing and encrypting and must be located in a single + include directory. Substitutions ~~~~~~~~~~~~~tools/binman/etype/fit.py +17
-14@@ -102,13 +102,13 @@ class Entry_fit(Entry_section): In this case the input directories are ignored and all devicetree files must be in that directory. - fit,sign - Enable signing FIT images via mkimage as described in - verified-boot.rst. If the property is found, the private keys path - is detected among binman include directories and passed to mkimage - via -k flag. All the keys required for signing FIT must be - available at time of signing and must be located in single include - directory. + fit,keys-directory + Look for a directory where signing and encryption keys are stored. + If the property is found, the keys path is detected among binman + include directories and passed to mkimage via -k flag. All the keys + required for signing and encrypting the FIT must be available at the + time of signing and encrypting and must be located in a single + include directory. Substitutions ~~~~~~~~~~~~~@@ -518,14 +518,14 @@ class Entry_fit(Entry_section): # are removed from self._entries later. self._priv_entries = dict(self._entries) - def _get_priv_keys_dir(self, data): - """Detect private keys path among binman include directories + def _get_keys_dir(self, data): + """Detect private and encryption keys path among binman include directories Args: data: FIT image in binary format Returns: - str: Single path containing all private keys found or None + str: Single path containing all keys found or None Raises: ValueError: Filename 'rsa2048.key' not found in input path@@ -533,11 +533,14 @@ class Entry_fit(Entry_section): """ def _find_keys_dir(node): for subnode in node.subnodes: - if subnode.name.startswith('signature'): + if (subnode.name.startswith('signature') or + subnode.name.startswith('cipher')): if subnode.props.get('key-name-hint') is None: continue hint = subnode.props['key-name-hint'].value - name = tools.get_input_filename(f"{hint}.key") + name = tools.get_input_filename( + f"{hint}.key" if subnode.name.startswith('signature') + else f"{hint}.bin") path = os.path.dirname(name) if path not in paths: paths.append(path)@@ -587,8 +590,8 @@ class Entry_fit(Entry_section): align = self._fit_props.get('fit,align') if align is not None: args.update({'align': fdt_util.fdt32_to_cpu(align.value)}) - if self._fit_props.get('fit,sign') is not None: - args.update({'priv_keys_dir': self._get_priv_keys_dir(data)}) + if self._fit_props.get('fit,keys-directory') is not None: + args.update({'keys_dir': self._get_keys_dir(data)}) if self.mkimage.run(reset_timestamp=True, output_fname=output_fname, **args) is None: if not self.GetAllowMissing():tools/binman/ftest.py +1
-1@@ -7885,7 +7885,7 @@ fdt fdtmap Extract the devicetree blob from the fdtmap str(e.exception)) def testFitSignNoSingatureNodes(self): - """Test that fit,sign doens't raise error if no signature nodes found""" + """Test that fit,keys-directory doesn't raise error if no signature nodes found""" if not elf.ELF_TOOLS: self.skipTest('Python elftools not available') entry_args = {tools/binman/test/340_fit_signature.dts +1
-1@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot {tools/binman/test/341_fit_signature.dts +1
-1@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot {tools/binman/test/342_fit_signature.dts +1
-2@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot { --Quoted 1 line
2.43.0
[..]
Regards,
Simon
Re: [PATCH v3 2/3] tools: binman: Replace 'fit,sign' by 'fit,keys-directory'
Here how I understand Simon’s answer.
He suggested to introduce new property like ‘fit,encrypt’. And if you see that property, then you enable keys detection (and so you enable encryption).
Regarding you current (v3) implementation. I would call the new property as ‘fit,detect-keys-directory’ as it makes more clear that binman have to do during fit processing.
For me, then I see ‘fit,keys-directory’ I expect, that directory path must be provided with the property. You did that in v2. But Simon told, that its better to implement that behavior using entyarg (https://lists.denx.de/pipermail/u-boot/2024-August/561346.html).
I have no idea how to do that. May be any usage example could clarify.
Regarding implementation of signing in the binman. First, I thought to implement singing in the binman. There are another entryargs that implements signing e.g. preload_enty.py. I could extract signing code into separate file and implement signing in the fit entry arg: I see fit,sign, I see fit entries related to the signature (key-name-hint, algo…) and do signing. Later I found that mkimage get called during FIT creation and decided not to duplicate functionality.
Alexander.
Quoted 235 lines
21 нояб. 2024 г., в 13:17, Paul HENRYS <[email protected]> написал(а):
Hi Simon,
Quoted 32 lines · Simon Glass
This Mail comes from Outside of SoftAtHome: Do not answer, click links or open attachments unless you recognize the sender and know the content is safe.
Hi Paul,
Quoted 18 lines · Paul HENRYS
mkimage can be used for both signing the FIT or encrypt its content and the option '-k' can be used to pass a directory where both signing and encryption keys can be retrieved.
_get_priv_keys_dir()is also renamed as_get_keys_dir()and adapted to support both signing and encryption nodes in the FIT.Signed-off-by Paul HENRYS <[email protected]>---
Changes for v3:
- Adapt the code after changes made in commit133c000ca334
- Rename property 'fit,sign' as 'fit,keys-directory' since this is not only about signing but passing a key directory to mkimage for both signing and encrypting
- Update the tests and documentation accordinglyMy initial changes proposed in v1 and v2 has been outdated by the changes proposed in commit
133c000ca334.Quoted 8 lines
tools/binman/btool/mkimage.py | 8 +++---- tools/binman/entries.rst | 13 ++++++----- tools/binman/etype/fit.py | 31 ++++++++++++++----------- tools/binman/ftest.py | 2 +- tools/binman/test/340_fit_signature.dts | 2 +- tools/binman/test/341_fit_signature.dts | 2 +- tools/binman/test/342_fit_signature.dts | 2 +- 7 files changed, 32 insertions(+), 28 deletions(-)Quoted 8 lines
I think it is good to be able to specify the keys directory and not just rely on Binman's input path. But do we need to remove the fit,sign property? It is the signal that signing should be done., although I understand that there is a key directory too.
If we need to remove it, please do that in a separate patch.
Perhaps we also need a signal that encryption should be done?
Based on my understanding, we don't enable the signing by adding 'fit,sign' property but by having a signature node in the DTS passed to binman and thus also in the ITS passed to mkimage by binman (at least with the current implementation). In the current implementation, adding 'fit,sign property' in the DTS passed to binman only leads to add the argument '-k' with a directory where the private keys are stored and nothing more. The '-k' argument of mkimage is used to specify the keys directory for both signing and ciphering FIT data. That is why I thought the property could be shared for providing the keys directory for both signing and ciphering when generating the FIT. Then maybe your idea would be to use such a property, i.e. 'fit,sign' property, to be able to add more options related to the signature (key-name-hint, algo...) instead of having those information in the ITS in a signature node. In this case, I guess it would indeed make sense to have separate properties that could both set the '-k' argument passed to mkimage.
The current signal for the encryption is to have a 'cipher' node in the ITS provided to mkimage.Quoted 187 lines
Quoted 182 lines
tools/binman/btool/mkimage.py +4
-4@@ -22,7 +22,7 @@ class Bintoolmkimage(bintool.Bintool): # pylint: disable=R0913 def run(self, reset_timestamp=False, output_fname=None, external=False, - pad=None, align=None, priv_keys_dir=None): + pad=None, align=None, keys_dir=None): """Run mkimage Args:@@ -34,7 +34,7 @@ class Bintoolmkimage(bintool.Bintool): other things to be easily added later, if required, such as signatures align: Bytes to use for alignment of the FIT and its external data - priv_keys_dir: Path to directory containing private keys + keys_dir: Path to directory containing private and encryption keys version: True to get the mkimage version """ args = []@@ -46,8 +46,8 @@ class Bintoolmkimage(bintool.Bintool): args += ['-B', f'{align:x}'] if reset_timestamp: args.append('-t') - if priv_keys_dir: - args += ['-k', f'{priv_keys_dir}'] + if keys_dir: + args += ['-k', f'{keys_dir}'] if output_fname: args += ['-F', output_fname] return self.run_cmd(*args)tools/binman/entries.rst +7
-6@@ -864,12 +864,13 @@ The top-level 'fit' node supports the following special properties: fit,fdt-list-dir = "arch/arm/dts - fit,sign - Enable signing FIT images via mkimage as described in - verified-boot.rst. If the property is found, the private keys path is - detected among binman include directories and passed to mkimage via - -k flag. All the keys required for signing FIT must be available at - time of signing and must be located in single include directory. + fit,keys-directory + Look for a directory where signing and encryption keys are stored. + If the property is found, the keys path is detected among binman + include directories and passed to mkimage via -k flag. All the keys + required for signing and encrypting the FIT must be available at the + time of signing and encrypting and must be located in a single + include directory. Substitutions ~~~~~~~~~~~~~tools/binman/etype/fit.py +17
-14@@ -102,13 +102,13 @@ class Entry_fit(Entry_section): In this case the input directories are ignored and all devicetree files must be in that directory. - fit,sign - Enable signing FIT images via mkimage as described in - verified-boot.rst. If the property is found, the private keys path - is detected among binman include directories and passed to mkimage - via -k flag. All the keys required for signing FIT must be - available at time of signing and must be located in single include - directory. + fit,keys-directory + Look for a directory where signing and encryption keys are stored. + If the property is found, the keys path is detected among binman + include directories and passed to mkimage via -k flag. All the keys + required for signing and encrypting the FIT must be available at the + time of signing and encrypting and must be located in a single + include directory. Substitutions ~~~~~~~~~~~~~@@ -518,14 +518,14 @@ class Entry_fit(Entry_section): # are removed from self._entries later. self._priv_entries = dict(self._entries) - def _get_priv_keys_dir(self, data): - """Detect private keys path among binman include directories + def _get_keys_dir(self, data): + """Detect private and encryption keys path among binman include directories Args: data: FIT image in binary format Returns: - str: Single path containing all private keys found or None + str: Single path containing all keys found or None Raises: ValueError: Filename 'rsa2048.key' not found in input path@@ -533,11 +533,14 @@ class Entry_fit(Entry_section): """ def _find_keys_dir(node): for subnode in node.subnodes: - if subnode.name.startswith('signature'): + if (subnode.name.startswith('signature') or + subnode.name.startswith('cipher')): if subnode.props.get('key-name-hint') is None: continue hint = subnode.props['key-name-hint'].value - name = tools.get_input_filename(f"{hint}.key") + name = tools.get_input_filename( + f"{hint}.key" if subnode.name.startswith('signature') + else f"{hint}.bin") path = os.path.dirname(name) if path not in paths: paths.append(path)@@ -587,8 +590,8 @@ class Entry_fit(Entry_section): align = self._fit_props.get('fit,align') if align is not None: args.update({'align': fdt_util.fdt32_to_cpu(align.value)}) - if self._fit_props.get('fit,sign') is not None: - args.update({'priv_keys_dir': self._get_priv_keys_dir(data)}) + if self._fit_props.get('fit,keys-directory') is not None: + args.update({'keys_dir': self._get_keys_dir(data)}) if self.mkimage.run(reset_timestamp=True, output_fname=output_fname, **args) is None: if not self.GetAllowMissing():tools/binman/ftest.py +1
-1@@ -7885,7 +7885,7 @@ fdt fdtmap Extract the devicetree blob from the fdtmap str(e.exception)) def testFitSignNoSingatureNodes(self): - """Test that fit,sign doens't raise error if no signature nodes found""" + """Test that fit,keys-directory doesn't raise error if no signature nodes found""" if not elf.ELF_TOOLS: self.skipTest('Python elftools not available') entry_args = {tools/binman/test/340_fit_signature.dts +1
-1@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot {tools/binman/test/341_fit_signature.dts +1
-1@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot {tools/binman/test/342_fit_signature.dts +1
-2@@ -11,7 +11,7 @@ description = "test desc"; #address-cells = <1>; fit,fdt-list = "of-list"; - fit,sign; + fit,keys-directory; images { u-boot { --Quoted 1 line
2.43.0
[..]
Regards,
Simon
PATCH v3 3/3 tools: binman: Add tests for FIT with data encrypted by mkimage
In reply to Paul HENRYSTest the property 'fit,keys-directory' which, when a cipher node is present, encrypts the data stored in the FIT.
---
Changes for v3:
- Write out IV in full for clarity as requested
- Do not replace the null byte but use fdt_util.GetString() instead
- Adapt the tests for the FIT data encryption to create a file with the content of the AES key in the working directory and pass the path to binman
tools/binman/ftest.py | 45 +++++++++++++++ tools/binman/test/343_fit_encrypt_data.dts | 53 ++++++++++++++++++ .../test/344_fit_encrypt_data_no_key.dts | 53 ++++++++++++++++++ tools/binman/test/aes256.bin | Bin 0 -> 32 bytes 4 files changed, 151 insertions(+) create mode 100644 tools/binman/test/343_fit_encrypt_data.dts create mode 100644 tools/binman/test/344_fit_encrypt_data_no_key.dts create mode 100644 tools/binman/test/aes256.bin
tools/binman/ftest.py +45 -0
@@ -7900,5 +7900,50 @@ fdt fdtmap Extract the devicetree blob from the fdtmap extra_indirs=[test_subdir])[0] + def testSimpleFitEncryptedData(self): + """Test an image with a FIT containing data to be encrypted""" + data = tools.read_file(self.TestFile("aes256.bin")) + self._MakeInputFile("keys/aes256.bin", data) + + keys_subdir = os.path.join(self._indir, "keys") + data = self._DoReadFileDtb( + '343_fit_encrypt_data.dts', + extra_indirs=[keys_subdir])[0] + + fit = fdt.Fdt.FromData(data) + fit.Scan() + + # Extract the encrypted data and the Initialization Vector from the FIT + node = fit.GetNode('/images/u-boot') + subnode = fit.GetNode('/images/u-boot/cipher') + data_size_unciphered = int.from_bytes(fit.GetProps(node)['data-size-unciphered'].bytes, + byteorder='big') + self.assertEqual(data_size_unciphered, len(U_BOOT_NODTB_DATA)) + + # Retrieve the key name from the FIT removing any null byte + key_name = fit.GetProps(subnode)['key-name-hint'].bytes.replace(b'\x00', b'') + with open(self.TestFile(key_name.decode('ascii') + '.bin'), 'rb') as file: + key = file.read() + iv = fit.GetProps(subnode)['iv'].bytes.hex() + enc_data = fit.GetProps(node)['data'].bytes + outdir = tools.get_output_dir() + enc_data_file = os.path.join(outdir, 'encrypted_data.bin') + tools.write_file(enc_data_file, enc_data) + data_file = os.path.join(outdir, 'data.bin') + + # Decrypt the encrypted data from the FIT and compare the data + tools.run('openssl', 'enc', '-aes-256-cbc', '-nosalt', '-d', '-in', + enc_data_file, '-out', data_file, '-K', key.hex(), '-iv', iv) + with open(data_file, 'r') as file: + dec_data = file.read() + self.assertEqual(U_BOOT_NODTB_DATA, dec_data.encode('ascii')) + + def testSimpleFitEncryptedDataMissingKey(self): + """Test an image with a FIT containing data to be encrypted but with a missing key""" + with self.assertRaises(ValueError) as e: + self._DoReadFile('344_fit_encrypt_data_no_key.dts') + + self.assertIn("Filename 'aes256.bin' not found in input path", str(e.exception)) + if __name__ == "__main__": unittest.main()
tools/binman/test/343_fit_encrypt_data.dts new file +53 -0
53 lines not on this page · raw message
tools/binman/test/344_fit_encrypt_data_no_key.dts new file +53 -0
53 lines not on this page · raw message
tools/binman/test/aes256.bin new file binary +0 -0
Signature · 1 line
2.43.0
Re: [PATCH v3 3/3] tools: binman: Add tests for FIT with data encrypted by mkimage
Quoted 12 lines · Paul HENRYS
Test the property 'fit,keys-directory' which, when a cipher node is present, encrypts the data stored in the FIT.
Signed-off-by Paul HENRYS <[email protected]>---
Changes for v3:
- Write out IV in full for clarity as requested
- Do not replace the null byte but usefdt_util.GetString()instead
- Adapt the tests for the FIT data encryption to create a file with the content of the AES key in the working directory and pass the path to binman
Quoted 8 lines
tools/binman/ftest.py | 45 +++++++++++++++ tools/binman/test/343_fit_encrypt_data.dts | 53 ++++++++++++++++++ .../test/344_fit_encrypt_data_no_key.dts | 53 ++++++++++++++++++ tools/binman/test/aes256.bin | Bin 0 -> 32 bytes 4 files changed, 151 insertions(+) create mode 100644 tools/binman/test/343_fit_encrypt_data.dts create mode 100644 tools/binman/test/344_fit_encrypt_data_no_key.dts create mode 100644 tools/binman/test/aes256.bin
Quoted 186 lines
tools/binman/ftest.py +45
-0@@ -7900,5 +7900,50 @@ fdt fdtmap Extract the devicetree blob from the fdtmap extra_indirs=[test_subdir])[0] + def testSimpleFitEncryptedData(self): + """Test an image with a FIT containing data to be encrypted""" + data = tools.read_file(self.TestFile("aes256.bin")) + self._MakeInputFile("keys/aes256.bin", data) + + keys_subdir = os.path.join(self._indir, "keys") + data = self._DoReadFileDtb( + '343_fit_encrypt_data.dts', + extra_indirs=[keys_subdir])[0] + + fit = fdt.Fdt.FromData(data) + fit.Scan() + + # Extract the encrypted data and the Initialization Vector from the FIT + node = fit.GetNode('/images/u-boot') + subnode = fit.GetNode('/images/u-boot/cipher') + data_size_unciphered = int.from_bytes(fit.GetProps(node)['data-size-unciphered'].bytes, + byteorder='big') + self.assertEqual(data_size_unciphered, len(U_BOOT_NODTB_DATA)) + + # Retrieve the key name from the FIT removing any null byte + key_name = fit.GetProps(subnode)['key-name-hint'].bytes.replace(b'\x00', b'') + with open(self.TestFile(key_name.decode('ascii') + '.bin'), 'rb') as file: + key = file.read() + iv = fit.GetProps(subnode)['iv'].bytes.hex() + enc_data = fit.GetProps(node)['data'].bytes + outdir = tools.get_output_dir() + enc_data_file = os.path.join(outdir, 'encrypted_data.bin') + tools.write_file(enc_data_file, enc_data) + data_file = os.path.join(outdir, 'data.bin') + + # Decrypt the encrypted data from the FIT and compare the data + tools.run('openssl', 'enc', '-aes-256-cbc', '-nosalt', '-d', '-in', + enc_data_file, '-out', data_file, '-K', key.hex(), '-iv', iv) + with open(data_file, 'r') as file: + dec_data = file.read() + self.assertEqual(U_BOOT_NODTB_DATA, dec_data.encode('ascii')) + + def testSimpleFitEncryptedDataMissingKey(self): + """Test an image with a FIT containing data to be encrypted but with a missing key""" + with self.assertRaises(ValueError) as e: + self._DoReadFile('344_fit_encrypt_data_no_key.dts') + + self.assertIn("Filename 'aes256.bin' not found in input path", str(e.exception)) + if __name__ == "__main__": unittest.main()tools/binman/test/343_fit_encrypt_data.dts new file +53
-0@@ -0,0 +1,53 @@ +// SPDX-License-Identifier: GPL-2.0+ + +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + fit { + fit,keys-directory; + description = "Test a FIT with encrypted data"; + #address-cells = <1>; + + images { + u-boot { + description = "U-Boot"; + type = "firmware"; + arch = "arm64"; + os = "U-Boot"; + compression = "none"; + load = <00000000>; + entry = <00000000>; + cipher { + algo = "aes256"; + key-name-hint = "aes256"; + }; + u-boot-nodtb { + }; + }; + fdt-1 { + description = "Flattened Device Tree blob"; + type = "flat_dt"; + arch = "arm64"; + compression = "none"; + cipher { + algo = "aes256"; + key-name-hint = "aes256"; + }; + }; + }; + + configurations { + default = "conf-1"; + conf-1 { + description = "Boot U-Boot with FDT blob"; + firmware = "u-boot"; + fdt = "fdt-1"; + }; + }; + }; + }; +};tools/binman/test/344_fit_encrypt_data_no_key.dts new file +53
-0@@ -0,0 +1,53 @@ +// SPDX-License-Identifier: GPL-2.0+ + +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + fit { + fit,keys-directory; + description = "Test a FIT with encrypted data"; + #address-cells = <1>; + + images { + u-boot { + description = "U-Boot"; + type = "firmware"; + arch = "arm64"; + os = "U-Boot"; + compression = "none"; + load = <00000000>; + entry = <00000000>; + cipher { + algo = "aes256"; + key-name-hint = "aes256"; + }; + u-boot-nodtb { + }; + }; + fdt-1 { + description = "Flattened Device Tree blob"; + type = "flat_dt"; + arch = "arm64"; + compression = "none"; + cipher { + algo = "aes256"; + key-name-hint = "aes256"; + }; + }; + }; + + configurations { + default = "conf-1"; + conf-1 { + description = "Boot U-Boot with FDT blob"; + firmware = "u-boot"; + fdt = "fdt-1"; + }; + }; + }; + }; +};tools/binman/test/aes256.bin new file binary +0
-1--2.43.0
[..]
Hi Paul,
Quoted 6 lines · Paul HENRYS
When the initialisation vector is randomly generated, its value shall be stored in the FIT together with the encrypted data. The changes allow to store the IV in the FIT also in the case where the key is not stored in the DTB but retrieved somewhere else at runtime.
Quoted 6 lines
Signed-off-by Paul HENRYS <[email protected]>--- lib/aes/aes-encrypt.c | 7 +++++++ tools/image-host.c | 2 +- 2 files changed, 8 insertions(+), 1 deletion(-)
I see that struct cipher_algo does not have a function comment for add_cipher_data(), so it is not clear that keydest can be NULL, etc. Can you please add one?
Otherwise this seems good to me.
Quoted 32 lines
lib/aes/aes-encrypt.c +7
-0@@ -84,6 +84,13 @@ int image_aes_add_cipher_data(struct image_cipher_info *info, void *keydest,char name[128 ];int ret =0 ; +if (!keydest && !info->ivname) { +/* At least, store the IV in the FIT image */ + ret =fdt_setprop (fit, node_noffset,"iv" , + info->iv, info->cipher->iv_len); + goto done; + } +/* Either create or overwrite the named cipher node */ parent =fdt_subnode_offset (keydest,0 ,FIT_CIPHER_NODENAME );if (parent == -FDT_ERR_NOTFOUND ) {tools/image-host.c +1
-2@@ -535,7 +535,7 @@ fit_image_process_cipher(const char *keydir, void *keydest, void *fit,* size values * And, if needed, write the iv in the FIT file */ -if (keydest) { +if (keydest || (!keydest && !info.ivname)) { ret = info.cipher->add_cipher_data (&info, keydest, fit, node_noffset);if (ret) { fprintf(stderr, --
Quoted 2 lines
2.43.0
[..]
Regards,
SImon