Skip to contentSkip to conversation

binman: add nxp_imx93cst etype for i.MX93 flash.bin signing

PATCH Superseded Jérémie Dautheribes (Schneider Electric) 3 participants 12 messages Oct 1 – Oct 2

Subsystems (2)

v5 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

v5 cover binman: add nxp_imx93cst etype for i.MX93 flash.bin signing

Hello,

This series adds support for signing i.MX93 images by leveraging binman and CST, the NXP tool used for secure boot. This introduces a new binman entry type (etype) for this purpose.

As the implementation is largely similar to the existing i.MX8M support, this series also introduce a new common nxp_imxcst etype to share the common functionnalities.

This procedure has been tested on the imx93-evk board, using both ECDSA and RSA-PSS keys.

Patches 1-2: introduce the new common etype and convert the imx8cst one Patch 3: introduces the new nxp_imx93cst etype
Patch 4: updates the imx93-u-boot.dtsi description to include the new signing nodes
Patches 5-6: documentation
Patches 7-9: add test coverage

---
Changes in v5:
- test: add short-input test instead of SetImagePos and delete nxp_imx93_csf_imagename.dts, which became useless after this change (as recommended by Simon Glass)
- test: factor the SPL container setup

- Link to v4: https://patch.msgid.link/[email protected]

Changes in v4:
- new patches: move the fake cst run_cmd() mock into a _MockCstRunCmd()
helper and use it from the imx8m test
- binman: test: nxp_imx93cst coverage: check the CST configuration offsets generated in the missing-bintool case, reuse the new mock helper, and
drop the unneeded force_missing_bintools='mkimage'
- doc: imx: ahab: fix the i.MX 9x diagram box characters, and reword the
mx93 guide signing description (two signing nodes), key location and
CST_DIR example
- Link to v3: https://patch.msgid.link/[email protected]

Changes in v3:
- doc: removed *.txt files wrongly introduced in the previous series
- doc: fixed some inconsistencies between what the doc states and CST v4.0.1
- doc: fixed broken bootflow diagrams

- Link to v2: https://patch.msgid.link/[email protected]

Changes in v2:
- Following Simong Glass' feedback:
- Created a new common class shared between the nxp_imx8mcst and the nxp_imx93cst etypes
- rewrote the doc in reStructuredText and mention binman instead of imx-mkimage
- took into account the other minor suggestions
- Link to v1: https://patch.msgid.link/[email protected]

To: "NXP i.MX U-Boot Team" <[email protected]>
To: [email protected]
Cc: Miquèl Raynal <[email protected]>
Cc: Thomas Petazzoni <[email protected]>
Cc: Tom Rini <[email protected]>
Cc: Simon Glass <[email protected]>
Cc: Alper Nebi Yasak <[email protected]>
Cc: Stefano Babic <[email protected]>
Cc: Fabio Estevam <[email protected]>
Cc: "Jérémie Dautheribes (Schneider Electric)" <[email protected]>
Cc: Marek Vasut <[email protected]>
Cc: Denis Mukhin <[email protected]>
Cc: Rasmus Villemoes <[email protected]>
Cc: Ilias Apalodimas <[email protected]>
Cc: Krzysztof Drobiński <[email protected]>
Cc: Peng Fan <[email protected]>
Cc: Alice Guo <[email protected]>
Cc: Simona Toaca <[email protected]>
Cc: Ye Li <[email protected]>
Cc: Quentin Schulz <[email protected]>
Cc: Christophe Guerreiro <[email protected]>
Cc: Thomas Bonnefille <[email protected]>
Cc: Marek Vasut <[email protected]>
Cc: Mathieu Dubois-Briand <[email protected]>
Cc: Lei Xu <[email protected]>
Cc: Joseph Guo <[email protected]>
Cc: Vincent Jardin <[email protected]>

---
Jérémie Dautheribes (Schneider Electric) (9):
binman: add nxp_imxcst base etype for i.MX CST signing
binman: nxp_imx8mcst: use the nxp_imxcst base etype
binman: add nxp_imx93cst etype for i.MX93 flash.bin signing
imx93-u-boot: wrap SPL and U-Boot nodes in a CST node if AHAB_BOOT enabled
doc: imx: ahab: add AHAB introduction
doc: imx: ahab: add i.MX93 secure boot guide
binman: test: add a helper to mock the cst bintool run_cmd()
binman: test: use the cst mock helper in testNxpImx8mCSTSigned
binman: test: add code coverage for nxp_imx93cst etype

 .gitignore                                 |   2 +
 arch/arm/dts/imx93-u-boot.dtsi             |  54 ++--
 doc/board/nxp/index.rst                    |   1 +
 doc/imx/ahab/guides/mx93_secure_boot.rst   | 297 +++++++++++++++++++
 doc/imx/ahab/introduction_ahab.rst         | 460 +++++++++++++++++++++++++++++
 doc/imx/index.rst                          |  14 +
 tools/binman/etype/nxp_imx8mcst.py         |  60 +---
 tools/binman/etype/nxp_imx93cst.py         | 112 +++++++
 tools/binman/etype/nxp_imxcst.py           | 120 ++++++++
 tools/binman/ftest.py                      | 125 +++++++-
 tools/binman/test/vendor/nxp_imx93_csf.dts |  18 ++
 11 files changed, 1183 insertions(+), 80 deletions(-)

---
base-commit: 2b8902913c19eb581fb0d567201c09b8fa46ac74
change-id: 20260814-imx93-secureboot-b914e7b6cbbf

Best regards,

Signature · 1 line
Jérémie Dautheribes (Schneider Electric) <[email protected]>
#1 lore raw

PATCH v5 1/9 binman: add nxp_imxcst base etype for i.MX CST signing

Add a common etype which provides the shared functionality for signing i.MX images with the NXP Code Signing Tool (CST). This includes the SRK table property handling, the CST bintool registration, and helpers for writing the input data and configuration files and for running cst.

The nxp_imx8mcst etype and the upcoming nxp_imx93cst etype will be converted to use this common base in the following commits.

No functional changes.

---
 tools/binman/etype/nxp_imxcst.py | 120 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 120 insertions(+)
tools/binman/etype/nxp_imxcst.py new file +120 -0
new file mode 100644
index 00000000000..718537fda40
@@ -0,0 +1,120 @@
+# SPDX-License-Identifier: GPL-2.0+
+# Copyright 2026 (C) Bootlin
+# Author: Jérémie Dautheribes <[email protected]>
+#
+# Derived from nxp_imx8mcst.py
+# Copyright 2023-2024 Marek Vasut <[email protected]>
+
+# Entry-type module for NXP i.MX Code Signing Tool (CST) base class
+#
+
+import configparser
+import os
+
+from binman.etype.mkimage import Entry_mkimage
+from binman.etype.section import Entry_section
+from dtoc import fdt_util
+from u_boot_pylib import tools
+
+
+class Entry_nxp_imxcst(Entry_mkimage):
+    """NXP i.MX CST .cfg file generator and cst invoker base class
+
+    Properties / Entry arguments:
+        - nxp,srk-table - full path to SRK_1_2_3_4_table.bin
+    """
+
+    def __init__(self, section, etype, node):
+        super().__init__(section, etype, node)
+        self.cst = None
+        self.srk_table = None
+
+    def ReadNode(self):
+        super().ReadNode()
+        self.srk_table = os.getenv(
+            'SRK_TABLE', fdt_util.GetString(self._node, 'nxp,srk-table',
+                                            'SRK_1_2_3_4_table.bin'))
+
+    def SetImagePos(self, image_pos):
+        # Customized SoC specific SetImagePos which skips the mkimage etype
+        # implementation and removes the 0x48 offset introduced there. That
+        # offset is only used for uImage/fitImage, which is not the case in
+        # here.
+        upto = 0x00
+        for entry in super().GetEntries().values():
+            entry.SetOffsetSize(upto, None)
+
+            # Give up if any entries lack a size
+            if entry.size is None:
+                return
+            upto += entry.size
+
+        Entry_section.SetImagePos(self, image_pos)
+
+    def AddBintools(self, btools):
+        super().AddBintools(btools)
+        self.cst = self.AddBintool(btools, 'cst')
+
+    def write_input_data(self, data, uniq):
+        """Write input data to a temporary file for CST
+
+        Args:
+            data: Data to write
+            uniq: Unique string for naming output files
+
+        Returns:
+            str: Path to the written file
+        """
+        output_dname = tools.get_output_filename(f'nxp.cst-input-data.{uniq}')
+        tools.write_file(output_dname, data)
+        return output_dname
+
+    def get_config(self, template):
+        """Get a ConfigParser loaded with the given template
+
+        Args:
+            template: Configuration template string
+
+        Returns:
+            ConfigParser instance
+        """
+        config = configparser.ConfigParser()
+        # Do not make key names lowercase
+        config.optionxform = str
+        config.read_string(template)
+        return config
+
+    def write_config(self, config, uniq):
+        """Write ConfigParser object to a temporary file for CST
+
+        Args:
+            config: ConfigParser instance
+            uniq: Unique string for naming output files
+
+        Returns:
+            str: Path to the written configuration file
+        """
+        cfg_fname = tools.get_output_filename(f'nxp.csf-config-txt.{uniq}')
+        with open(cfg_fname, 'w') as cfgf:
+            config.write(cfgf)
+        return cfg_fname
+
+    def run_cst(self, cfg_fname, uniq, backend=None):
+        """Run CST tool with given configuration file
+
+        Args:
+            cfg_fname: Filename of the CST configuration file
+            uniq: Unique string for naming output files
+            backend: Optional backend (e.g. 'ssl' or 'pkcs11')
+
+        Returns:
+            bytes: Output data from CST, or None if bintool is missing
+        """
+        output_fname = tools.get_output_filename(f'nxp.csf-output-blob.{uniq}')
+        args = ['-i', cfg_fname, '-o', output_fname]
+        if backend:
+            args.extend(['-b', backend])
+        if self.cst.run_cmd(*args) is not None:
+            return tools.read_file(output_fname)
+        self.record_missing_bintool(self.cst)
+        return None
Signature · 1 line
2.55.0
#2 lore raw

PATCH v5 2/9 binman: nxp_imx8mcst: use the nxp_imxcst base etype

In reply to Jérémie Dautheribes (Schneider Electric)

Use the new nxp_imxcst base etype and remove duplicated code. This should not have any functional impact.

---
 tools/binman/etype/nxp_imx8mcst.py | 60 +++++++-------------------------------
 1 file changed, 10 insertions(+), 50 deletions(-)
tools/binman/etype/nxp_imx8mcst.py +10 -50
index 29a7451678d..3f81b9f83c6 100644
@@ -7,16 +7,10 @@
 # input configuration file and input data to be signed.
 #
 
-import configparser
 import os
 import struct
 
-from collections import OrderedDict
-
-from binman.entry import Entry
-from binman.etype.mkimage import Entry_mkimage
-from binman.etype.section import Entry_section
-from binman import elf
+from binman.etype.nxp_imxcst import Entry_nxp_imxcst
 from dtoc import fdt_util
 from u_boot_pylib import tools
 
@@ -61,7 +55,8 @@ CSF_CONFIG_TEMPLATE = f'''
   Blocks = 0x1234 0x78 0xabcd "data.bin"
 '''
 
-class Entry_nxp_imx8mcst(Entry_mkimage):
+
+class Entry_nxp_imx8mcst(Entry_nxp_imxcst):
     """NXP i.MX8M CST .cfg file generator and cst invoker
 
     Properties / Entry arguments:
@@ -82,9 +77,6 @@ class Entry_nxp_imx8mcst(Entry_mkimage):
     def ReadNode(self):
         super().ReadNode()
         self.loader_address = fdt_util.GetInt(self._node, 'nxp,loader-address')
-        self.srk_table = os.getenv(
-            'SRK_TABLE', fdt_util.GetString(self._node, 'nxp,srk-table',
-                                            'SRK_1_2_3_4_table.bin'))
         self.fast_auth = fdt_util.GetBool(self._node, 'nxp,fast-auth')
         if not self.fast_auth:
             self.csf_crt = os.getenv(
@@ -158,17 +150,11 @@ class Entry_nxp_imx8mcst(Entry_mkimage):
             return data
 
         # Write out customized data to be signed
-        output_dname = tools.get_output_filename(f'nxp.cst-input-data.{uniq}')
-        tools.write_file(output_dname, data)
+        output_dname = self.write_input_data(data, uniq)
 
         # Generate CST configuration file used to sign payload
-        cfg_fname = tools.get_output_filename(f'nxp.csf-config-txt.{uniq}')
-        config = configparser.ConfigParser()
-        # Do not make key names lowercase
-        config.optionxform = str
-        # Load configuration template and modify keys of interest
-        config.read_string(CSF_CONFIG_TEMPLATE)
-        config['Install SRK']['File']  = f'"{self.srk_table}"'
+        config = self.get_config(CSF_CONFIG_TEMPLATE)
+        config['Install SRK']['File'] = f'"{self.srk_table}"'
         if not self.fast_auth:
             config.remove_section('Install NOCAK')
             config['Install CSFK']['File'] = f'"{self.csf_crt}"'
@@ -184,8 +170,7 @@ class Entry_nxp_imx8mcst(Entry_mkimage):
 
         if not self.unlock:
             config.remove_section('Unlock')
-        with open(cfg_fname, 'w') as cfgf:
-            config.write(cfgf)
+        cfg_fname = self.write_config(config, uniq)
 
         # SSL is the default backend, PKCS11 backend is optional
         if self.backend == "pkcs11":
@@ -193,34 +178,9 @@ class Entry_nxp_imx8mcst(Entry_mkimage):
         else:
             cst_backend = "ssl"
 
-        output_fname = tools.get_output_filename(f'nxp.csf-output-blob.{uniq}')
-        args = ['-i', cfg_fname, '-o', output_fname, '-b', cst_backend]
-        if self.cst.run_cmd(*args) is not None:
-            outdata = tools.read_file(output_fname)
+        outdata = self.run_cst(cfg_fname, uniq, cst_backend)
+        if outdata is not None:
             # fixme: 0x2000 should be CONFIG_CSF_SIZE
             outdata += tools.get_bytes(0, 0x2000 - 0x20 - len(outdata))
             return data + outdata
-        else:
-            # Bintool is missing; just use the input data as the output
-            self.record_missing_bintool(self.cst)
-            return data
-
-    def SetImagePos(self, image_pos):
-        # Customized SoC specific SetImagePos which skips the mkimage etype
-        # implementation and removes the 0x48 offset introduced there. That
-        # offset is only used for uImage/fitImage, which is not the case in
-        # here.
-        upto = 0x00
-        for entry in super().GetEntries().values():
-            entry.SetOffsetSize(upto, None)
-
-            # Give up if any entries lack a size
-            if entry.size is None:
-                return
-            upto += entry.size
-
-        Entry_section.SetImagePos(self, image_pos)
-
-    def AddBintools(self, btools):
-        super().AddBintools(btools)
-        self.cst = self.AddBintool(btools, 'cst')
+        return data
Signature · 1 line
2.55.0
#3 lore raw

PATCH v5 3/9 binman: add nxp_imx93cst etype for i.MX93 flash.bin signing

In reply to Jérémie Dautheribes (Schneider Electric)

Add a binman etype which allows signing the SPL and U-Boot proper sections of the i.MX93 flash.bin using CST and AHAB. The implementation reuses the shared functionality from the nxp_imxcst base etype.

---
 .gitignore                         |   2 +
 tools/binman/etype/nxp_imx93cst.py | 112 +++++++++++++++++++++++++++++++++++++
 2 files changed, 114 insertions(+)
.gitignore +2 -0
index 0e09715cc60..5cb135fc58c 100644
@@ -82,6 +82,8 @@ fit-dtb.blob*
 /keep-syms-lto.*
 /*imx8mimage*
 /*imx8mcst*
+/*imx9image*
+/*imx93cst*
 /*rcar4-sa0*
 /drivers/video/u_boot_logo.bmp.S
 /test/fdt_overlay/test-fdt-overlay-stacked.dtbo.S
tools/binman/etype/nxp_imx93cst.py new file +112 -0

112 lines not on this page · raw message

Signature · 1 line
2.55.0
#4 lore raw

PATCH v5 4/9 imx93-u-boot: wrap SPL and U-Boot nodes in a CST node if AHAB_BOOT enabled

In reply to Jérémie Dautheribes (Schneider Electric)

When CONFIG_AHAB_BOOT is enabled, wrap the SPL and U-Boot binman nodes in a CST node so that binman signs them automatically.

---
 arch/arm/dts/imx93-u-boot.dtsi | 54 +++++++++++++++++++++++++++---------------
 1 file changed, 35 insertions(+), 19 deletions(-)
arch/arm/dts/imx93-u-boot.dtsi +35 -19
index bd970c955cf..569b3ef5d9c 100644
@@ -47,32 +47,48 @@
 			filename = "flash.bin";
 			pad-byte = <0x00>;
 
-			spl {
-				type = "nxp-imx9image";
-				cfg-path = "spl/u-boot-spl.cfgout";
+#ifdef CONFIG_AHAB_BOOT
+			nxp-imx93cst@0 {
+				filename = "spl.signed.bin";
 				args;
-
-				boot-from = "sd";
-				soc-type = "IMX9";
-				append = "mx93a1-ahab-container.img";
-				container;
-				image = "a55", "u-boot-spl-ddr.bin", "0x2049A000";
+#endif
+				spl {
+					type = "nxp-imx9image";
+					cfg-path = "spl/u-boot-spl.cfgout";
+					args;
+
+					boot-from = "sd";
+					soc-type = "IMX9";
+					append = "mx93a1-ahab-container.img";
+					container;
+					image = "a55", "u-boot-spl-ddr.bin", "0x2049A000";
+				};
+#ifdef CONFIG_AHAB_BOOT
 			};
+#endif
 
-			u-boot {
-				type = "nxp-imx9image";
-				cfg-path = "u-boot-container.cfgout";
+#ifdef CONFIG_AHAB_BOOT
+			nxp-imx93cst@1 {
+				filename = "u-boot-container.signed.bin";
 				args;
-
-				boot-from = "sd";
-				soc-type = "IMX9";
-				container;
-				image0 = "a55", "bl31.bin", "0x204E0000";
-				image1 = "a55", "u-boot.bin", "0x80200000";
+#endif
+				u-boot {
+					type = "nxp-imx9image";
+					cfg-path = "u-boot-container.cfgout";
+					args;
+
+					boot-from = "sd";
+					soc-type = "IMX9";
+					container;
+					image0 = "a55", "bl31.bin", "0x204E0000";
+					image1 = "a55", "u-boot.bin", "0x80200000";
 #if defined(CONFIG_OPTEE)
-				image2 = "a55", "tee.bin", "0x96000000";
+					image2 = "a55", "tee.bin", "0x96000000";
 #endif
+				};
+#ifdef CONFIG_AHAB_BOOT
 			};
+#endif
 		};
 	};
 };
Signature · 1 line
2.55.0
#5 lore raw

PATCH v5 5/9 doc: imx: ahab: add AHAB introduction

In reply to Jérémie Dautheribes (Schneider Electric)

Add an introductory document describing the AHAB (Advanced High Assurance Boot) secure and encrypted boot flow, covering the following topics:
- AHAB architecture overview (SCU, SECO, PKI tree)
- AHAB secure boot and encrypted boot flow
- PKI tree generation (ahab_pki_tree)
- SRK Table and SRK Hash generation (srktool)
- SRK Hash fuse programming and sanity check notes
- i.MX 8ULP/93 secure boot support

This is based on doc/imx/ahab/introduction_ahab.txt from uboot-imx (lf_v2026.04). Originally written by Breno Lima, with contributions from Ye Li, Vanessa Maegima, and Utkarsh Gupta upstream in uboot-imx.

---
 doc/board/nxp/index.rst            |   1 +
 doc/imx/ahab/introduction_ahab.rst | 459 +++++++++++++++++++++++++++++++++++++
 doc/imx/index.rst                  |  13 ++
 3 files changed, 473 insertions(+)
doc/board/nxp/index.rst +1 -0
index b11730e1eac..07cf9b220d9 100644
@@ -31,6 +31,7 @@ NXP Semiconductors
    mx6ul_14x14_evk
    mx6ullevk
    nbxv3
+   i.MX AHAB secure boot <../../imx/index>
    rproc
    psb
    quickboot
doc/imx/ahab/introduction_ahab.rst new file +459 -0

459 lines not on this page · raw message

doc/imx/index.rst new file +13 -0
new file mode 100644
index 00000000000..cc5f427de92
@@ -0,0 +1,13 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+i.MX AHAB secure boot
+======================
+
+This section provides documentation for the NXP i.MX AHAB (Advanced
+High Assurance Boot) secure boot mechanisms, covering the AHAB
+architecture introduction and the i.MX93 secure boot guide.
+
+.. toctree::
+   :maxdepth: 2
+
+   ahab/introduction_ahab
Signature · 1 line
2.55.0
#6 lore raw

PATCH v5 6/9 doc: imx: ahab: add i.MX93 secure boot guide

In reply to Jérémie Dautheribes (Schneider Electric)

Add a step-by-step guide describing how to securely boot an i.MX93 image using AHAB.

This guide is largely based on the following documents:
- doc/imx/ahab/guides/mx8ulp_9x_secure_boot.txt, from uboot-imx (lf_v2026.04), originally written by Utkarsh Gupta
- doc/imx/habv4/guides/mx8m_spl_secure_boot.txt, from this tree, originally written by Marek Vasut

---
 doc/imx/ahab/guides/mx93_secure_boot.rst | 297 +++++++++++++++++++++++++++++++
 doc/imx/ahab/introduction_ahab.rst       |   3 +-
 doc/imx/index.rst                        |   1 +
 3 files changed, 300 insertions(+), 1 deletion(-)
doc/imx/ahab/guides/mx93_secure_boot.rst new file +297 -0
new file mode 100644
index 00000000000..bfc17b7ad79
@@ -0,0 +1,297 @@
+.. SPDX-License-Identifier: GPL-2.0+
+
+i.MX93 Secure boot guide using AHAB
+===================================
+
+This document provides a step-by-step guide on how to securely boot an
+i.MX93 boot image. It is assumed that the reader is familiar with basic
+AHAB concepts and with the PKI tree generation. Details about AHAB can be
+found in the :doc:`AHAB introduction <../introduction_ahab>` document and
+in the processor Security Reference Manual (SRM). The i.MX93 signing
+procedure is integrated in the U-Boot build thanks to binman.
+
+1. Preparing the environment to build a secure boot image
+---------------------------------------------------------
+
+Secure boot image preparation requires the U-Boot build system to build
+the image and the Code Signing Tool (CST) to sign it.
+
+The following files are needed to prepare the boot image:
+
+  - EdgeLock secure enclave Firmware (ELE) (Optional).
+  - DDR PHY initialization firmware.
+  - U-Boot proper and SPL.
+  - ARM Trusted Firmware (ATF).
+  - OPTEE (Optional)
+
+The ELE FW is distributed by NXP and is already signed using NXP keys.
+In the following sections, <work> designates the repository where all
+parts have been downloaded and built.
+
+2. Preparing U-Boot to support AHAB secure boot features
+--------------------------------------------------------
+
+The U-Boot/SPL provides extra AHAB supported functionalities that include
+extension of Root of Trust, checking any events(issues) after image
+authentication, chip lifecycle status, securing the target etc.
+
+The support is enabled by adding CONFIG_AHAB_BOOT to the defconfig file
+used by your target:
+
+  - Defconfig:
+    CONFIG_AHAB_BOOT=y
+  - Kconfig:
+    ARM architecture -> Support i.MX9 AHAB features
+
+Enabling this feature allows the SPL and U-Boot images to extend the Root
+of Trust by using the AHAB API call via ELE FW. It also enables binman to
+automatically sign the SPL and U-Boot containers while building
+flash.bin, as described in the next sections.
+
+3. i.MX93 AHAB image layout
+---------------------------
+
+The i.MX93 flash.bin image is built by binman and is composed of up to
+three containers. The ELE FW container is optional and is provided by NXP,
+it is appended at the beginning of the image when the file
+mx93a1-ahab-container.img is present in the build directory. The SPL and
+U-Boot containers are built by the nxp-imx9image etype and signed by the
+nxp-imx93cst etype.
+
+.. code-block:: text
+
+              *start ----> +---------------------------+ ---------
+                           |   1st Container header    |   ^
+                           |       and signature       |   |  Authenticated at
+                           +---------------------------+   |  ELE ROM/FW Level
+                           |          Padding          |   |
+                           +---------------------------+   |
+                           |           ELE FW          |   v
+       *start + 0x400 ---> +---------------------------+ ---------
+                           |   2nd Container header    |   ^
+                           |       and signature       |   |  Authenticated at
+                           +---------------------------+   |  ELE ROM/FW Level
+                           |          Padding          |   |
+                           +---------------------------+   |
+                           |            SPL            |   v
+                           +---------------------------+ ---------
+                           |   3rd Container header    |   ^
+                           |       and signature       |   |  Authenticated at
+                           +---------------------------+   |  SPL Level
+                           |          Padding          |   |
+                           +---------------------------+   |
+                           |    ARM Trusted FW (ATF)   |   |
+                           +---------------------------+   |
+                           |       U-Boot proper       |   |
+                           +---------------------------+   |
+                           |      OPTEE (optional)     |   v
+                           +---------------------------+ ---------
+
+The first container includes the ELE FW which is signed using NXP keys,
+this container is authenticated by ELE ROM.
+
+The second container includes the SPL which is signed using OEM keys,
+this container is authenticated at ELE FW level.
+
+The third container includes the U-Boot proper and the ATF. The SPL is in
+charge to load this container and also to interface with ELE FW to
+authenticate the additional container.
+
+The signing procedure is slightly different when compared with HABv4
+series. On AHAB the signature is directly included in the container, the
+CST is responsible to sign and handle the "Signature Block":
+
+.. code-block:: text
+
+               +----------------------------+ ---------
+               |                            |  ^
+               |                            |  |
+               |      Container header      |  |
+               |                            |  |
+               |                            |  |
+               +---+------------------------+  |
+               | S | Signature block header |  | Signed
+               | i +------------------------+  |
+               | g |                        |  |
+               | n |                        |  |
+               | a |        SRK table       |  |
+               | t |                        |  |
+               | u |                        |  v
+               | r +------------------------+ ---------
+               | e |       Signature        |
+               |   +------------------------+
+               | B |                        |
+               | l |        SGK Key         |
+               | o | Certificate (optional) |
+               | c |                        |
+               | k |                        |
+               +---+------------------------+
+
+The certificate block is divided into:
+
+.. code-block:: text
+
+                      +---------------+ ^
+                      |  Public key   | | Signed
+                      |  Permission   | |
+                      +---------------+ v
+                      |   Signature   |
+                      +---------------+
+
+The first block (public key permission) verifies the Signature block
+preceding (between SRK table and Certificate blocks), while the second
+block (signature) is verified by the SRK table block.
+
+In case not using the subordinate key, the container signature is
+verified against the SRK keys directly.
+
+4. Signing the images
+---------------------
+
+Internally, Command Sequence Files (CSF) are used. The CSF files contain
+all the commands that the AHAB executes during the secure boot. These
+commands instruct the AHAB code on which memory areas of the image to
+authenticate, which keys to install and use, and so on. The CSF is generated
+using the CST Code Signing Tool based on input configuration file. This
+tool input configuration file is generated using binman, and the tool
+is invoked from binman as well.
+
+The SPL and U-Boot containers built by the nxp-imx9image etype are each
+wrapped in their own nxp-imx93cst node and signed individually by the CST
+tool. For each container, the container header address and the signature
+block offset are read from the i.MX container header itself, so the offsets
+in the CST configuration file are always correct, whether the ELE FW is
+bundled in the SPL container or not.
+
+Per default the AHAB keys and certificates need to be located in the
+build directory, this means creating a symbolic link or copying the
+following files from the AHAB PKI tree directory into the u-boot build
+directory for the CST Code Signing Tool to locate them:
+
+- ``crts/SRK_1_2_3_4_table.bin``
+- ``crts/SRK1_sha384_secp384r1_v3_usr_crt.pem``
+- ``keys/SRK1_sha384_secp384r1_v3_usr_key.pem``
+- ``keys/key_pass.txt``
+
+See the :doc:`AHAB introduction <../introduction_ahab>` document for the
+PKI tree generation procedure (ahab_pki_tree tool) and for the SRK Table
+generation (srktool).
+
+The nxp-imx93cst etype is configurable using either DT properties or
+environment variables. The following DT properties and environment
+variables are supported. Note that environment variables override DT
+properties.
+
+.. list-table::
+   :header-rows: 1
+
+   * - DT property
+     - Variable
+     - Description
+   * - ``nxp,srk-table``
+     - ``SRK_TABLE``
+     - full path to ``SRK_1_2_3_4_table.bin``
+   * - ``nxp,srk-crt``
+     - ``SRK_KEY``
+     - full path to the SRK certificate ``SRK1_sha384_secp384r1_v3_usr_crt.pem``
+
+
+The SRK private key (``SRK1_sha384_secp384r1_v3_usr_key.pem``) and the
+``key_pass.txt`` file, which contains the passphrase protecting the private
+keys, are required by the CST tool as well, and will be searched for in
+relation to the SRK table and certificate paths.
+
+When the key material is not located in the build directory, environment
+variables can be set to point the build process to it. In the example
+below, CST_DIR designates the CST installation directory, that is the
+directory holding the crts/ and keys/ directories generated when creating
+the PKI tree:
+
+.. code-block:: console
+
+   $ export CST_DIR=<path_to_cst_dir>
+   $ export SRK_TABLE=$CST_DIR/crts/SRK_1_2_3_4_table.bin
+   $ export SRK_KEY=$CST_DIR/crts/SRK1_sha384_secp384r1_v3_usr_crt.pem
+   $ make flash.bin
+
+5. Programming SRK Hash
+-----------------------
+
+As explained in the :doc:`AHAB introduction <../introduction_ahab>`
+document, the SRK Hash fuse values are generated by the srktool and
+should be programmed in the SoC SRK_HASH[255:0] fuses.
+
+Be careful when programming these values, as this data is the basis for
+the root of trust. An error in SRK Hash results in a part that does not
+boot.
+
+The U-Boot fuse tool can be used for programming eFuses on i.MX SoCs.
+
+- Dump SRK Hash fuses values in host machine:
+
+  On i.MX93 family, the SRK Hash uses sha256 and dump 8 words fuses:
+
+  .. code-block:: console
+
+     $ od -t x4 SRK_1_2_3_4_fuse.bin
+     0000000 db2959f2 90dfc39c 53394566 e0b75829
+     0000020 85e6f3b1 af00983d e5e804fe 7a451024
+
+- Program SRK_HASH[255:0] fuses:
+
+On i.MX93:
+
+.. code-block:: console
+
+   => fuse prog 16 0 0xdb2959f2
+   => fuse prog 16 1 0x90dfc39c
+   => fuse prog 16 2 0x53394566
+   => fuse prog 16 3 0xe0b75829
+   => fuse prog 16 4 0x85e6f3b1
+   => fuse prog 16 5 0xaf00983d
+   => fuse prog 16 6 0xe5e804fe
+   => fuse prog 16 7 0x7a451024
+
+6. Verify AHAB events
+---------------------
+
+If the fuses have been burned properly, there should be no AHAB events
+after boot. To validate this, power on the board, and run ahab_status
+command on U-Boot terminal.
+
+No events should be returned after this command:
+
+.. code-block:: console
+
+   => ahab_status
+   Lifecycle: 0x00000008, OEM Open
+
+           No Events Found!
+
+7. Close the device
+-------------------
+.. warning::
+
+   Before closing the device, please ensure your sample is in OEM Open state,
+   OEM SRK hash has been fused, and you are able to boot a signed image
+   successfully without any AHAB events reported . If not, your sample will be
+   unrecoverable.
+
+After the device successfully boots a signed image without generating any
+AHAB security events, it is safe to close the device. The chip lifecycle
+should be changed from OEM open to OEM closed. Be aware this step can
+damage your board if a previous step failed. It is also irreversible. Run
+on the U-Boot terminal:
+
+.. code-block:: console
+
+   => ahab_close
+
+Now reboot the target, and run:
+
+.. code-block:: console
+
+   => ahab_status
+   Lifecycle: 0x00000020, OEM Closed
+
+           No Events Found!
doc/imx/ahab/introduction_ahab.rst +2 -1
index e6376229383..621724711fb 100644
@@ -292,7 +292,8 @@ scenario in i.MX 9x:
               │          │          │          │         │
 
 More details on the boot flow can be found in respective Security Reference
-Manual (SRM).
+Manual (SRM) and in the :doc:`i.MX93 Secure boot guide
+<guides/mx93_secure_boot>`.
 
 2. Generating a PKI tree
 ------------------------
doc/imx/index.rst +1 -0
index cc5f427de92..daf846947cc 100644
@@ -11,3 +11,4 @@ architecture introduction and the i.MX93 secure boot guide.
    :maxdepth: 2
 
    ahab/introduction_ahab
+   ahab/guides/mx93_secure_boot
Signature · 1 line
2.55.0
#7 lore raw

PATCH v5 7/9 binman: test: add a helper to mock the cst bintool run_cmd()

In reply to Jérémie Dautheribes (Schneider Electric)

Add a _MockCstRunCmd() helper which fakes the cst invocation so that the signing path can be tested without the real tool.

This will be used by the nxp_imx8mcst and nxp_imx93cst tests in the following commits.

---
 tools/binman/ftest.py | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
tools/binman/ftest.py +20 -0
index 5f0de4c74a7..239787345f8 100644
@@ -8105,6 +8105,26 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
             self._DoTestFile('vendor/nxp_imx8_imagename.dts',
                              force_missing_bintools='mkimage')
 
+    def _MockCstRunCmd(self):
+        """Mock Bintool.run_cmd() so that cst writes a fake output blob
+
+        Returns:
+            unittest.mock.patch: Patcher for Bintool.run_cmd
+        """
+        original = bintool.Bintool.run_cmd
+
+        def fake_cst_run_cmd(self_tool, *args, binary=False):
+            if self_tool.name == 'cst':
+                arg_list = list(args)
+                if '-o' in arg_list:
+                    idx = arg_list.index('-o')
+                    tools.write_file(arg_list[idx + 1], b'\x00' * 32)
+                return 'fake cst output'
+            return original(self_tool, *args, binary=binary)
+
+        return unittest.mock.patch.object(bintool.Bintool, 'run_cmd',
+                                          new=fake_cst_run_cmd)
+
     def testNxpImx8mCSTSigned(self):
         """Test CST-signing-success path with mocked cst invocation"""
         ivt_data = struct.pack('<I', 0x412000d1)
Signature · 1 line
2.55.0
#8 lore raw

PATCH v5 8/9 binman: test: use the cst mock helper in testNxpImx8mCSTSigned

In reply to Jérémie Dautheribes (Schneider Electric)

Use the _MockCstRunCmd() helper instead of the inline fake cst run_cmd() mock in testNxpImx8mCSTSigned(). No functional change.

---
 tools/binman/ftest.py | 16 +---------------
 1 file changed, 1 insertion(+), 15 deletions(-)
tools/binman/ftest.py +1 -15
index 239787345f8..783836045cb 100644
@@ -8133,21 +8133,7 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
         ivt_data += b'\x00' * 36
         self._MakeInputFile('imx8m-ivt.bin', ivt_data)
 
-        # Mock run_cmd() so that when cst is invoked, it creates a fake output
-        # blob and returns success, thus covering the signing path
-        original = bintool.Bintool.run_cmd
-
-        def fake_cst_run_cmd(self_tool, *args, binary=False):
-            if self_tool.name == 'cst':
-                arg_list = list(args)
-                if '-o' in arg_list:
-                    idx = arg_list.index('-o')
-                    tools.write_file(arg_list[idx + 1], b'\x00' * 32)
-                return 'fake cst output'
-            return original(self_tool, *args, binary=binary)
-
-        with unittest.mock.patch.object(bintool.Bintool, 'run_cmd',
-                                        new=fake_cst_run_cmd):
+        with self._MockCstRunCmd():
             self._DoTestFile('vendor/nxp_imx8_csf.dts')
 
     def testNxpImx8mCSTBintool(self):
Signature · 1 line
2.55.0
#9 lore raw

PATCH v5 9/9 binman: test: add code coverage for nxp_imx93cst etype

In reply to Jérémie Dautheribes (Schneider Electric)

Add test methods to cover all code paths of the nxp_imx93cst etype, reusing the pattern of the nxp_imx8mcst as done in commit 0cab35362d77 ("binman: test: Fix code coverage for iMX8 and cst bintool") by Simon Glass.

This brings nxp_imx93cst to 100% coverage.

---
 tools/binman/ftest.py                      | 97 ++++++++++++++++++++++++++++++
 tools/binman/test/vendor/nxp_imx93_csf.dts | 18 ++++++
 2 files changed, 115 insertions(+)
tools/binman/ftest.py +97 -0
index 783836045cb..822ad5c6f07 100644
@@ -35,6 +35,7 @@ from dtoc import fdt
 from dtoc import fdt_util
 from binman.etype import fdtmap
 from binman.etype import image_header
+from binman.etype import nxp_imx93cst
 from binman.image import Image
 from u_boot_pylib import command
 from u_boot_pylib import terminal
@@ -8158,6 +8159,102 @@ fdt         fdtmap                Extract the devicetree blob from the fdtmap
             result = cst.fetch(bintool.FETCH_BUILD)
             self.assertEqual(('cst', None), result)
 
+    def _MakeImx93SplContainer(self, offset=0):
+        """Create a fake AHAB image containing an SPL container
+
+        The SPL container header tag is placed at the given offset, and the
+        returned buffer is large enough to also cover the signature block
+        referenced by that header. The image-entry flags hold the A55
+        core/type (0x23) as their low byte.
+
+        Args:
+            offset: Offset of the SPL container header. Use
+                nxp_imx93cst.SPL_CONTAINER_OFFSET to build an image which
+                starts with the ELE FW instead.
+
+        Returns:
+            bytes: Fake AHAB image data
+        """
+        data = bytearray(offset + 0x100)
+        data[offset + 3] = nxp_imx93cst.CONTAINER_HDR_TAG
+        data[offset + 12:offset + 14] = struct.pack('<H', 0x90)
+        data[offset + 40:offset + 44] = struct.pack('<I', 0x123)
+        return bytes(data)
+
+    def testNxpImx93cstNormal(self):
+        """Test CST signing with an i.MX93 SPL container (no ELE FW)"""
+        self._MakeInputFile('imx93-container.bin',
+                            self._MakeImx93SplContainer())
+
+        with terminal.capture() as (_, stderr):
+            self._DoTestFile('vendor/nxp_imx93_csf.dts',
+                             force_missing_bintools='cst')
+        err = stderr.getvalue()
+        self.assertRegex(err, "Image 'image'.*missing bintools.*: cst")
+
+        cfg = tools.read_file(tools.get_output_filename(
+            'nxp.csf-config-txt.nxp-imx93cst'), binary=False)
+        self.assertIn('Offsets = 0x0 0x90', cfg)
+
+    def testNxpImx93cstELE(self):
+        """Test CST signing where the SPL container starts with the ELE FW"""
+        # Create a fake AHAB image starting with the NXP-signed ELE
+        # container. The low byte of the first image entry flags (0x66) is
+        # the ELE core/type, so the SPL container header starts at
+        # SPL_CONTAINER_OFFSET and the signature block is covered too.
+        ele_data = bytearray(self._MakeImx93SplContainer(
+            nxp_imx93cst.SPL_CONTAINER_OFFSET))
+        ele_data[3] = nxp_imx93cst.CONTAINER_HDR_TAG
+        ele_data[40:44] = struct.pack('<I', 0x866)
+        self._MakeInputFile('imx93-container.bin', bytes(ele_data))
+
+        with terminal.capture() as (_, stderr):
+            self._DoTestFile('vendor/nxp_imx93_csf.dts',
+                             force_missing_bintools='cst')
+        err = stderr.getvalue()
+        self.assertRegex(err, "Image 'image'.*missing bintools.*: cst")
+
+        cfg = tools.read_file(tools.get_output_filename(
+            'nxp.csf-config-txt.nxp-imx93cst'), binary=False)
+        self.assertIn('Offsets = 0x400 0x490', cfg)
+
+    def testNxpImx93cstUnknownTag(self):
+        """Test CST with unknown input tag passes data through"""
+        # Trigger the pass-through path using an input without the AHAB
+        # container tag
+        data = b'\x00' * 64
+        self._MakeInputFile('imx93-container.bin', data)
+        self._DoTestFile('vendor/nxp_imx93_csf.dts',
+                         force_missing_bintools='cst')
+
+        # The pass-through branch returns the input data unchanged, so the
+        # produced image must be exactly the 64 zero bytes
+        out = tools.read_file(tools.get_output_filename('image.bin'))
+        self.assertEqual(out, b'\x00' * 64)
+
+    def testNxpImx93cstSigned(self):
+        """Test CST-signing-success path with mocked cst invocation"""
+        self._MakeInputFile('imx93-container.bin',
+                            self._MakeImx93SplContainer())
+
+        with self._MockCstRunCmd():
+            data = self._DoReadFile('vendor/nxp_imx93_csf.dts')
+
+        # The output must be the fake 32-byte CST blob produced by cst
+        self.assertEqual(data, b'\x00' * 32)
+
+    def testNxpImx93cstShortInput(self):
+        """Test BuildSectionData() passes a too-short input through"""
+        # The input is too short to hold the container header fields read by
+        # BuildSectionData(), so it must be passed through unchanged
+        data = b'\x00' * 32
+        self._MakeInputFile('imx93-container.bin', data)
+        self._DoTestFile('vendor/nxp_imx93_csf.dts',
+                         force_missing_bintools='cst')
+
+        out = tools.read_file(tools.get_output_filename('image.bin'))
+        self.assertEqual(out, data)
+
     def testNxpImx8MFSPI(self):
         """Test that binman can produce an iMX8m FSPI image"""
         self._DoTestFile('vendor/nxp_imx8m_fspi.dts')
tools/binman/test/vendor/nxp_imx93_csf.dts new file +18 -0
new file mode 100644
index 00000000000..bbe8eda4b70
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: GPL-2.0+
+
+/dts-v1/;
+
+/ {
+	#address-cells = <1>;
+	#size-cells = <1>;
+
+	binman {
+		nxp-imx93cst {
+			args;
+
+			blob {
+				filename = "imx93-container.bin";
+			};
+		};
+	};
+};
Signature · 1 line
2.55.0
Reviewed-by on v5 9/9
#10 lore raw

Re: [PATCH v5 9/9] binman: test: add code coverage for nxp_imx93cst etype

Quoted 7 lines · Jérémie Dautheribes (Schneider Electric)

binman: test: add code coverage for nxp_imx93cst etype

Add test methods to cover all code paths of the nxp_imx93cst etype, reusing the pattern of the nxp_imx8mcst as done in commit 0cab35362d77 ("binman: test: Fix code coverage for iMX8 and cst bintool") by Simon Glass.

Quoted 7 lines

This brings nxp_imx93cst to 100% coverage.

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

 tools/binman/test/vendor/nxp_imx93_csf.dts | 18 ++++++
 2 files changed, 115 insertions(+)
reviewer
#11 lore raw
In reply to Jérémie Dautheribes (Schneider Electric)

Hi Jérémie,

Quoted 7 lines · Jérémie Dautheribes (Schneider Electric)

Hello,

This series adds support for signing i.MX93 images by leveraging binman and CST, the NXP tool used for secure boot. This introduces a new binman entry type (etype) for this purpose.

Quoted 6 lines

As the implementation is largely similar to the existing i.MX8M support, this series also introduce a new common nxp_imxcst etype to share the common functionnalities.

This procedure has been tested on the imx93-evk board, using both ECDSA and RSA-PSS keys.

This series causes CI to fail:

+binman: Error 1 running 'mkimage -d ./[email protected] -n ./u-boot-container.cfgout -T imx8image ./[email protected]': ././bl31.bin: Can't
open: No such file or directory
+make[1]: *** [Makefile:1410: .binman_stamp] Error 1 +make: *** [Makefile:189: __sub-make] Error 2

https://git.u-boot-project.org/u-boot/custodians/u-boot-imx/-/jobs/105126

Please fix and resend.

Thanks