Skip to contentSkip to conversation

u-boot: Support for SPL verified boot

PATCH In review Klaus Heinrich Kiwi 2 participants 8 messages Mar 26, 2021 – Apr 6, 2021

lore
Share & tools
lore
#0 lore raw

v2 cover u-boot: Support for SPL verified boot

This patch series aims at extending U-Boot's verified boot support to also include SPL.

Presently, setting UBOOT_SIGN_ENABLE instructs the classes uboot-sign and kernel-fitimage to create and sign a Linux Kernel fitImage. This proposal introduces the variables UBOOT_FITIMAGE_ENABLE and SPL_SIGN_ENABLE that will, respectively, create and sign a U-Boot (proper) fitImage that the SPL can load (and verify if enabled)

In order to accomplish this, the first patch moves some of necessary infrastructure (variables, functions) used to sign the Kernel fitImage to more common locations, and then essentially duplicates the method currently used to sign the Kernel fitImage to also sign the U-Boot fitImage.

If the variable UBOOT_FITIMAGE_ENABLE = "1", the uboot-sign class will copy the SPL files (nodtb image and dtb file) from the u-boot recipe to the staging area, so that the Kernel recipe can then create the U-Boot fitImage.

In case SPL_SIGN_ENABLE = "1", the U-Boot fitImage will be signed using the key provided by SPL_SIGN_KEYNAME / SPL_SIGN_KEYDIR, or will auto-generate keys based on UBOOT_FIT_HASH_ALG, UBOOT_FIT_SIGN_ALG and UBOOT_FIT_SIGN_NUMBITS if UBOOT_FIT_GENERATE_KEYS is "1".

After the operations above, the Kernel recipe will deploy the (signed) U-Boot fitImage, the ITS script used to create it, as well as the SPL concatenated with the DTB containing the pubkey to the images directory.

The reason why the U-Boot fitImage is created by the Kernel is in order to make sure that, when UBOOT_SIGN_ENABLE is set (and the Kernel fitImage is signed), the U-Boot fitImage being created/signed contains the pubkey used by the Kernel recipe to sign the Kernel fitImage.

I added oe-selftest testcases and also tested this on upstream OpenBMC with AST2600 BMC devices.

---
Changes since V1:

* Separated SPL_SIGN_ENABLE from UBOOT_FITIMAGE_ENABLE so that an U-Boot fitImage can be created without a signature

* Completely moved the task of creating/signing the U-Boot fitImage to the Kernel recipe, so that we don't get collisions when reusing the build tree while changing the configuration. This is apparently also necessary for testcases to be sane.

* Testcases changes and additions, covering the above scenarios

 meta/classes/kernel-fitimage.bbclass     |  82 ++---
 meta/classes/uboot-config.bbclass        |  58 ++++
 meta/classes/uboot-sign.bbclass          | 407 +++++++++++++++++++++++--
 meta/lib/oeqa/selftest/cases/fitimage.py | 468 +++++++++++++++++++++++++++++
 meta/recipes-bsp/u-boot/u-boot.inc       |  46 ---
 5 files changed, 928 insertions(+), 133 deletions(-)
#1 lore raw

PATCH v2 1/4 u-boot: Move definitions to common locations

Move some definitions from u-boot.inc into uboot-config.bbclass and similarly from kernel-fitimage.bbclass into uboot-sign.bbclass, so that they can be useful when signing the U-boot proper fitimage, for a verified-boot SPL.

---
 meta/classes/kernel-fitimage.bbclass | 58 ----------------------------
 meta/classes/uboot-config.bbclass    | 56 +++++++++++++++++++++++++++
 meta/classes/uboot-sign.bbclass      | 35 +++++++++++++++++
 meta/recipes-bsp/u-boot/u-boot.inc   | 46 ----------------------
 4 files changed, 91 insertions(+), 104 deletions(-)
meta/classes/kernel-fitimage.bbclass +0 -58
index b9d8270027..6b7c1c3a7d 100644
@@ -53,30 +53,6 @@ python __anonymous () {
                 d.appendVarFlag('do_assemble_fitimage_initramfs', 'depends', ' %s:do_populate_sysroot' % uboot_pn)
 }
 
-# Options for the device tree compiler passed to mkimage '-D' feature:
-UBOOT_MKIMAGE_DTCOPTS ??= ""
-
-# fitImage Hash Algo
-FIT_HASH_ALG ?= "sha256"
-
-# fitImage Signature Algo
-FIT_SIGN_ALG ?= "rsa2048"
-
-# Generate keys for signing fitImage
-FIT_GENERATE_KEYS ?= "0"
-
-# Size of private key in number of bits
-FIT_SIGN_NUMBITS ?= "2048"
-
-# args to openssl genrsa (Default is just the public exponent)
-FIT_KEY_GENRSA_ARGS ?= "-F4"
-
-# args to openssl req (Default is -batch for non interactive mode and
-# -new for new certificate)
-FIT_KEY_REQ_ARGS ?= "-batch -new"
-
-# Standard format for public key certificate
-FIT_KEY_SIGN_PKCS ?= "-x509"
 
 # Description string
 FIT_DESC ?= "U-Boot fitImage for ${DISTRO_NAME}/${PV}/${MACHINE}"
@@ -84,13 +60,6 @@ FIT_DESC ?= "U-Boot fitImage for ${DISTRO_NAME}/${PV}/${MACHINE}"
 # Sign individual images as well
 FIT_SIGN_INDIVIDUAL ?= "0"
 
-# mkimage command
-UBOOT_MKIMAGE ?= "uboot-mkimage"
-UBOOT_MKIMAGE_SIGN ?= "${UBOOT_MKIMAGE}"
-
-# Arguments passed to mkimage for signing
-UBOOT_MKIMAGE_SIGN_ARGS ?= ""
-
 #
 # Emit the fitImage ITS header
 #
@@ -698,33 +667,6 @@ do_assemble_fitimage_initramfs() {
 
 addtask assemble_fitimage_initramfs before do_deploy after do_bundle_initramfs
 
-do_generate_rsa_keys() {
-	if [ "${UBOOT_SIGN_ENABLE}" = "0" ] && [ "${FIT_GENERATE_KEYS}" = "1" ]; then
-		bbwarn "FIT_GENERATE_KEYS is set to 1 eventhough UBOOT_SIGN_ENABLE is set to 0. The keys will not be generated as they won't be used."
-	fi
-
-	if [ "${UBOOT_SIGN_ENABLE}" = "1" ] && [ "${FIT_GENERATE_KEYS}" = "1" ]; then
-
-		# Generate keys only if they don't already exist
-		if [ ! -f "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_KEYNAME}".key ] || \
-			[ ! -f "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_KEYNAME}".crt]; then
-
-			# make directory if it does not already exist
-			mkdir -p "${UBOOT_SIGN_KEYDIR}"
-
-			echo "Generating RSA private key for signing fitImage"
-			openssl genrsa ${FIT_KEY_GENRSA_ARGS} -out \
-				"${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_KEYNAME}".key \
-				"${FIT_SIGN_NUMBITS}"
-
-			echo "Generating certificate for signing fitImage"
-			openssl req ${FIT_KEY_REQ_ARGS} "${FIT_KEY_SIGN_PKCS}" \
-				-key "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_KEYNAME}".key \
-				-out "${UBOOT_SIGN_KEYDIR}/${UBOOT_SIGN_KEYNAME}".crt
-		fi
-	fi
-}
-
 addtask generate_rsa_keys before do_assemble_fitimage after do_compile
 
 kernel_do_deploy[vardepsexclude] = "DATETIME"
meta/classes/uboot-config.bbclass +56 -0

63 lines not on this page · raw message

meta/classes/uboot-sign.bbclass +35 -0
index 713196df41..d57bef6669 100644
@@ -31,6 +31,9 @@
 #
 # For more details on signature process, please refer to U-Boot documentation.
 
+# We need some variables from u-boot-config
+inherit uboot-config
+
 # Signature activation.
 UBOOT_SIGN_ENABLE ?= "0"
 
@@ -41,6 +44,38 @@ UBOOT_DTB_SYMLINK ?= "u-boot-${MACHINE}.dtb"
 UBOOT_NODTB_IMAGE ?= "u-boot-nodtb-${MACHINE}-${PV}-${PR}.${UBOOT_SUFFIX}"
 UBOOT_NODTB_BINARY ?= "u-boot-nodtb.${UBOOT_SUFFIX}"
 UBOOT_NODTB_SYMLINK ?= "u-boot-nodtb-${MACHINE}.${UBOOT_SUFFIX}"
+UBOOT_ITS_IMAGE ?= "u-boot-${MACHINE}-${PV}-${PR}.its"
+UBOOT_ITS ?= "u-boot.its"
+UBOOT_ITS_SYMLINK ?= "u-boot-${MACHINE}.its"
+SPL_DIR ?= "${@os.path.dirname(d.getVar("SPL_BINARY")) or '.'}"
+SPL_DTB_IMAGE ?= "u-boot-spl-${MACHINE}-${PV}-${PR}.dtb"
+SPL_DTB_BINARY ?= "u-boot-spl.dtb"
+SPL_DTB_SYMLINK ?= "u-boot-spl-${MACHINE}.dtb"
+SPL_NODTB_IMAGE ?= "${@os.path.splitext(d.getVar("SPL_BINARYNAME"))[0]}-nodtb-${MACHINE}-${PV}-${PR}${@os.path.splitext(d.getVar("SPL_BINARYNAME"))[1]}"
+SPL_NODTB_BINARY ?= "${@os.path.splitext(d.getVar("SPL_BINARYNAME"))[0]}-nodtb${@os.path.splitext(d.getVar("SPL_BINARYNAME"))[1]}"
+SPL_NODTB_SYMLINK ?= "${@os.path.splitext(d.getVar("SPL_BINARYNAME"))[0]}-nodtb-${MACHINE}${@os.path.splitext(d.getVar("SPL_BINARYNAME"))[1]}"
+
+# fitImage Hash Algo
+FIT_HASH_ALG ?= "sha256"
+
+# fitImage Signature Algo
+FIT_SIGN_ALG ?= "rsa2048"
+
+# Generate keys for signing fitImage
+FIT_GENERATE_KEYS ?= "0"
+
+# Size of private key in number of bits
+FIT_SIGN_NUMBITS ?= "2048"
+
+# args to openssl genrsa (Default is just the public exponent)
+FIT_KEY_GENRSA_ARGS ?= "-F4"
+
+# args to openssl req (Default is -batch for non interactive mode and
+# -new for new certificate)
+FIT_KEY_REQ_ARGS ?= "-batch -new"
+
+# Standard format for public key certificate
+FIT_KEY_SIGN_PKCS ?= "-x509"
 
 # Functions in this bbclass is for u-boot only
 UBOOT_PN = "${@d.getVar('PREFERRED_PROVIDER_u-boot') or 'u-boot'}"
meta/recipes-bsp/u-boot/u-boot.inc +0 -46

52 lines not on this page · raw message

Signature · 1 line
2.25.1
#2 lore raw

PATCH v2 2/4 u-boot: Add infrastructure to SPL verified boot

In reply to Klaus Heinrich Kiwi

Add the necessary infrastructure to create a U-boot proper fitimage, sign it (using the same keys as the kernel-fitimage), and put the public key in the SPL binary so that verified SPL boot can be accomplished.

---
 meta/classes/kernel-fitimage.bbclass |  24 +-
 meta/classes/uboot-sign.bbclass      | 351 ++++++++++++++++++++++++---
 2 files changed, 340 insertions(+), 35 deletions(-)
meta/classes/kernel-fitimage.bbclass +17 -7
index 6b7c1c3a7d..5cfd8af99d 100644
@@ -55,7 +55,7 @@ python __anonymous () {
 
 
 # Description string
-FIT_DESC ?= "U-Boot fitImage for ${DISTRO_NAME}/${PV}/${MACHINE}"
+FIT_DESC ?= "Kernel fitImage for ${DISTRO_NAME}/${PV}/${MACHINE}"
 
 # Sign individual images as well
 FIT_SIGN_INDIVIDUAL ?= "0"
@@ -695,12 +695,22 @@ kernel_do_deploy_append() {
 				ln -snf fitImage-${INITRAMFS_IMAGE_NAME}-${KERNEL_FIT_NAME}.bin "$deployDir/fitImage-${INITRAMFS_IMAGE_NAME}-${KERNEL_FIT_LINK_NAME}"
 			fi
 		fi
-		if [ "${UBOOT_SIGN_ENABLE}" = "1" -a -n "${UBOOT_DTB_BINARY}" ] ; then
-			# UBOOT_DTB_IMAGE is a realfile, but we can't use
-			# ${UBOOT_DTB_IMAGE} since it contains ${PV} which is aimed
-			# for u-boot, but we are in kernel env now.
-			install -m 0644 ${B}/u-boot-${MACHINE}*.dtb "$deployDir/"
-		fi
+	fi
+	if [ "${UBOOT_SIGN_ENABLE}" = "1" -o "${UBOOT_FITIMAGE_ENABLE}" = "1" ] && \
+	   [ -n "${UBOOT_DTB_BINARY}" ] ; then
+		# UBOOT_DTB_IMAGE is a realfile, but we can't use
+		# ${UBOOT_DTB_IMAGE} since it contains ${PV} which is aimed
+		# for u-boot, but we are in kernel env now.
+		install -m 0644 ${B}/u-boot-${MACHINE}*.dtb "$deployDir/"
+	fi
+	if [ "${UBOOT_FITIMAGE_ENABLE}" = "1" -a -n "${UBOOT_BINARY}" -a -n "${SPL_DTB_BINARY}" ] ; then
+		# If we're also creating and/or signing the uboot fit, now we need to
+		# deploy it, it's its file, as well as u-boot-spl.dtb
+		install -m 0644 ${B}/u-boot-spl-${MACHINE}*.dtb "$deployDir/"
+		echo "Copying u-boot-fitImage file..."
+		install -m 0644 ${B}/u-boot-fitImage-* "$deployDir/"
+		echo "Copying u-boot-its file..."
+		install -m 0644 ${B}/u-boot-its-* "$deployDir/"
 	fi
 }
 
meta/classes/uboot-sign.bbclass +323 -28

414 lines not on this page · raw message

Signature · 1 line
2.25.1
#3 lore raw

PATCH v2 3/4 u-boot: Use a different Key for SPL signing

In reply to Klaus Heinrich Kiwi

Duplicate the variables governing u-boot signing so that we can have a different set of keys/parameters signing the SPL.

---
 meta/classes/uboot-config.bbclass |  2 ++
 meta/classes/uboot-sign.bbclass   | 53 +++++++++++++++++++++++++------
 2 files changed, 45 insertions(+), 10 deletions(-)
meta/classes/uboot-config.bbclass +2 -0
index 31487c1418..3bba02828b 100644
@@ -61,6 +61,7 @@ UBOOT_EXTLINUX_SYMLINK ?= "${UBOOT_EXTLINUX_CONF_NAME}-${MACHINE}-${PR}"
 
 # Options for the device tree compiler passed to mkimage '-D' feature:
 UBOOT_MKIMAGE_DTCOPTS ??= ""
+SPL_MKIMAGE_DTCOPTS ??= ""
 
 # mkimage command
 UBOOT_MKIMAGE ?= "uboot-mkimage"
@@ -68,6 +69,7 @@ UBOOT_MKIMAGE_SIGN ?= "${UBOOT_MKIMAGE}"
 
 # Arguments passed to mkimage for signing
 UBOOT_MKIMAGE_SIGN_ARGS ?= ""
+SPL_MKIMAGE_SIGN_ARGS ?= ""
 
 python () {
     ubootmachine = d.getVar("UBOOT_MACHINE")
meta/classes/uboot-sign.bbclass +43 -10

103 lines not on this page · raw message

Signature · 1 line
2.25.1
#4 lore raw

PATCH v2 4/4 oe-selftest: Add U-Boot fitImage signing testcases

In reply to Klaus Heinrich Kiwi

Derived from the similar kernel fitImage sign testcase, the U-Boot fitImage testcases exercises the following fitimage.FitImageTest scenarios:

* test_uboot_fit_image - create unsigned U-Boot fitImage
* test_uboot_sign_fit_image - create unsigned U-Boot fitImage in addition to signed Kernel fitImage
* test_sign_standalone_uboot_fit_image - Create signed U-Boot fitImage without a Kernel fitImage
* test_sign_cascaded_uboot_fit_image - Create and sign U-Boot and Kernel fitImages

---
 meta/lib/oeqa/selftest/cases/fitimage.py | 468 +++++++++++++++++++++++
 1 file changed, 468 insertions(+)
meta/lib/oeqa/selftest/cases/fitimage.py +468 -0
index 02692de822..b911fded74 100644
@@ -231,6 +231,474 @@ UBOOT_MKIMAGE_SIGN_ARGS = "-c 'a smart comment'"
         result = runCmd('grep "### uboot-mkimage signing wrapper message" %s/log.do_assemble_fitimage' % tempdir, ignore_status=True)
         self.assertEqual(result.status, 0, 'UBOOT_MKIMAGE_SIGN did not work')
 
+    def test_uboot_fit_image(self):
+        """
+        Summary:     Check if Uboot FIT image and Image Tree Source
+                     (its) are built and the Image Tree Source has the
+                     correct fields.
+        Expected:    1. u-boot-fitImage and u-boot-its can be built
+                     2. The type, load address, entrypoint address and
+                     default values of U-boot image are correct in the
+                     Image Tree Source. Not all the fields are tested,
+                     only the key fields that wont vary between
+                     different architectures.
+        Product:     oe-core
+        Author:      Klaus Heinrich Kiwi <[email protected]>
+                     based on work by Usama Arif <[email protected]>
+        """
+        config = """
+# We need at least CONFIG_SPL_LOAD_FIT and CONFIG_SPL_OF_CONTROL set
+MACHINE = "qemuarm"
+UBOOT_MACHINE = "am57xx_evm_defconfig"
+SPL_BINARY = "MLO"
+
+# Enable creation of the U-Boot fitImage
+UBOOT_FITIMAGE_ENABLE = "1"
+
+# (U-boot) fitImage properties
+UBOOT_LOADADDRESS = "0x80080000"
+UBOOT_ENTRYPOINT = "0x80080000"
+UBOOT_FIT_DESC = "A model description"
+
+# Enable creation of Kernel fitImage
+KERNEL_IMAGETYPES += " fitImage "
+KERNEL_CLASSES = " kernel-fitimage"
+UBOOT_SIGN_ENABLE = "1"
+FIT_GENERATE_KEYS = "1"
+UBOOT_SIGN_KEYDIR = "${TOPDIR}/signing-keys"
+UBOOT_SIGN_KEYNAME = "oe-selftest"
+FIT_SIGN_INDIVIDUAL = "1"
+"""
+        self.write_config(config)
+
+        # The U-Boot fitImage is created as part of linux recipe
+        bitbake("virtual/kernel")
+
+        deploy_dir_image = get_bb_var('DEPLOY_DIR_IMAGE')
+        machine = get_bb_var('MACHINE')
+        fitimage_its_path = os.path.join(deploy_dir_image,
+            "u-boot-its-%s" % (machine,))
+        fitimage_path = os.path.join(deploy_dir_image,
+            "u-boot-fitImage-%s" % (machine,))
+
+        self.assertTrue(os.path.exists(fitimage_its_path),
+            "%s image tree source doesn't exist" % (fitimage_its_path))
+        self.assertTrue(os.path.exists(fitimage_path),
+            "%s FIT image doesn't exist" % (fitimage_path))
+
+        # Check that the type, load address, entrypoint address and default
+        # values for kernel and ramdisk in Image Tree Source are as expected.
+        # The order of fields in the below array is important. Not all the
+        # fields are tested, only the key fields that wont vary between
+        # different architectures.
+        its_field_check = [
+            'description = "A model description";',
+            'type = "uboot";',
+            'load = <0x80080000>;',
+            'entry = <0x80080000>;',
+            'default = "conf";',
+            'loadables = "uboot";',
+            'fdt = "fdt";'
+            ]
+
+        with open(fitimage_its_path) as its_file:
+            field_index = 0
+            for line in its_file:
+                if field_index == len(its_field_check):
+                    break
+                if its_field_check[field_index] in line:
+                    field_index +=1
+
+        if field_index != len(its_field_check): # if its equal, the test passed
+            self.assertTrue(field_index == len(its_field_check),
+                "Fields in Image Tree Source File %s did not match, error in finding %s"
+                % (fitimage_its_path, its_field_check[field_index]))
+
+    def test_uboot_sign_fit_image(self):
+        """
+        Summary:     Check if Uboot FIT image and Image Tree Source
+                     (its) are built and the Image Tree Source has the
+                     correct fields, in the scenario where the Kernel
+                     is also creating/signing it's fitImage.
+        Expected:    1. u-boot-fitImage and u-boot-its can be built
+                     2. The type, load address, entrypoint address and
+                     default values of U-boot image are correct in the
+                     Image Tree Source. Not all the fields are tested,
+                     only the key fields that wont vary between
+                     different architectures.
+        Product:     oe-core
+        Author:      Klaus Heinrich Kiwi <[email protected]>
+                     based on work by Usama Arif <[email protected]>
+        """
+        config = """
+# We need at least CONFIG_SPL_LOAD_FIT and CONFIG_SPL_OF_CONTROL set
+MACHINE = "qemuarm"
+UBOOT_MACHINE = "am57xx_evm_defconfig"
+SPL_BINARY = "MLO"
+
+# Enable creation of the U-Boot fitImage
+UBOOT_FITIMAGE_ENABLE = "1"
+
+# (U-boot) fitImage properties
+UBOOT_LOADADDRESS = "0x80080000"
+UBOOT_ENTRYPOINT = "0x80080000"
+UBOOT_FIT_DESC = "A model description"
+KERNEL_IMAGETYPES += " fitImage "
+KERNEL_CLASSES = " kernel-fitimage test-mkimage-wrapper "
+UBOOT_SIGN_ENABLE = "1"
+FIT_GENERATE_KEYS = "1"
+UBOOT_SIGN_KEYDIR = "${TOPDIR}/signing-keys"
+UBOOT_SIGN_KEYNAME = "oe-selftest"
+FIT_SIGN_INDIVIDUAL = "1"
+UBOOT_MKIMAGE_SIGN_ARGS = "-c 'a smart U-Boot comment'"
+"""
+        self.write_config(config)
+
+        # The U-Boot fitImage is created as part of linux recipe
+        bitbake("virtual/kernel")
+
+        deploy_dir_image = get_bb_var('DEPLOY_DIR_IMAGE')
+        machine = get_bb_var('MACHINE')
+        fitimage_its_path = os.path.join(deploy_dir_image,
+            "u-boot-its-%s" % (machine,))
+        fitimage_path = os.path.join(deploy_dir_image,
+            "u-boot-fitImage-%s" % (machine,))
+
+        self.assertTrue(os.path.exists(fitimage_its_path),
+            "%s image tree source doesn't exist" % (fitimage_its_path))
+        self.assertTrue(os.path.exists(fitimage_path),
+            "%s FIT image doesn't exist" % (fitimage_path))
+
+        # Check that the type, load address, entrypoint address and default
+        # values for kernel and ramdisk in Image Tree Source are as expected.
+        # The order of fields in the below array is important. Not all the
+        # fields are tested, only the key fields that wont vary between
+        # different architectures.
+        its_field_check = [
+            'description = "A model description";',
+            'type = "uboot";',
+            'load = <0x80080000>;',
+            'entry = <0x80080000>;',
+            'default = "conf";',
+            'loadables = "uboot";',
+            'fdt = "fdt";'
+            ]
+
+        with open(fitimage_its_path) as its_file:
+            field_index = 0
+            for line in its_file:
+                if field_index == len(its_field_check):
+                    break
+                if its_field_check[field_index] in line:
+                    field_index +=1
+
+        if field_index != len(its_field_check): # if its equal, the test passed
+            self.assertTrue(field_index == len(its_field_check),
+                "Fields in Image Tree Source File %s did not match, error in finding %s"
+                % (fitimage_its_path, its_field_check[field_index]))
+
+
+    def test_sign_standalone_uboot_fit_image(self):
+        """
+        Summary:     Check if U-Boot FIT image and Image Tree Source (its) are
+                     created and signed correctly for the scenario where only
+                     the U-Boot proper fitImage is being created and signed.
+        Expected:    1) U-Boot its and FIT image are built successfully
+                     2) Scanning the its file indicates signing is enabled
+                        as requested by SPL_SIGN_ENABLE (using keys generated
+                        via UBOOT_FIT_GENERATE_KEYS)
+                     3) Dumping the FIT image indicates signature values
+                        are present
+                     4) Examination of the do_uboot_assemble_fitimage
+                     runfile/logfile indicate that UBOOT_MKIMAGE, UBOOT_MKIMAGE_SIGN
+                     and SPL_MKIMAGE_SIGN_ARGS are working as expected.
+        Product:     oe-core
+        Author:      Klaus Heinrich Kiwi <[email protected]> based upon
+                     work by Paul Eggleton <[email protected]> and
+                     Usama Arif <[email protected]>
+        """
+        config = """
+# There's no U-boot deconfig with CONFIG_FIT_SIGNATURE yet, so we need at
+# least CONFIG_SPL_LOAD_FIT and CONFIG_SPL_OF_CONTROL set
+MACHINE = "qemuarm"
+UBOOT_MACHINE = "am57xx_evm_defconfig"
+SPL_BINARY = "MLO"
+# The kernel-fitimage class is a dependency even if we're only
+# creating/signing the U-Boot fitImage
+KERNEL_CLASSES = " kernel-fitimage test-mkimage-wrapper "
+# Enable creation and signing of the U-Boot fitImage
+UBOOT_FITIMAGE_ENABLE = "1"
+SPL_SIGN_ENABLE = "1"
+SPL_SIGN_KEYNAME = "spl-oe-selftest"
+SPL_SIGN_KEYDIR = "${TOPDIR}/signing-keys"
+UBOOT_DTB_BINARY = "u-boot.dtb"
+UBOOT_ENTRYPOINT  = "0x80000000"
+UBOOT_LOADADDRESS = "0x80000000"
+UBOOT_DTB_LOADADDRESS = "0x82000000"
+UBOOT_ARCH = "arm"
+SPL_MKIMAGE_DTCOPTS = "-I dts -O dtb -p 2000"
+SPL_MKIMAGE_SIGN_ARGS = "-c 'a smart U-Boot comment'"
+UBOOT_EXTLINUX = "0"
+UBOOT_FIT_GENERATE_KEYS = "1"
+UBOOT_FIT_HASH_ALG = "sha256"
+"""
+        self.write_config(config)
+
+        # The U-Boot fitImage is created as part of linux recipe
+        bitbake("virtual/kernel")
+
+        image_type = "core-image-minimal"
+        deploy_dir_image = get_bb_var('DEPLOY_DIR_IMAGE')
+        machine = get_bb_var('MACHINE')
+        fitimage_its_path = os.path.join(deploy_dir_image,
+            "u-boot-its-%s" % (machine,))
+        fitimage_path = os.path.join(deploy_dir_image,
+            "u-boot-fitImage-%s" % (machine,))
+
+        self.assertTrue(os.path.exists(fitimage_its_path),
+            "%s image tree source doesn't exist" % (fitimage_its_path))
+        self.assertTrue(os.path.exists(fitimage_path),
+            "%s FIT image doesn't exist" % (fitimage_path))
+
+        req_itspaths = [
+            ['/', 'images', 'uboot'],
+            ['/', 'images', 'uboot', 'signature'],
+            ['/', 'images', 'fdt'],
+            ['/', 'images', 'fdt', 'signature'],
+        ]
+
+        itspath = []
+        itspaths = []
+        linect = 0
+        sigs = {}
+        with open(fitimage_its_path) as its_file:
+            linect += 1
+            for line in its_file:
+                line = line.strip()
+                if line.endswith('};'):
+                    itspath.pop()
+                elif line.endswith('{'):
+                    itspath.append(line[:-1].strip())
+                    itspaths.append(itspath[:])
+                elif itspath and itspath[-1] == 'signature':
+                    itsdotpath = '.'.join(itspath)
+                    if not itsdotpath in sigs:
+                        sigs[itsdotpath] = {}
+                    if not '=' in line or not line.endswith(';'):
+                        self.fail('Unexpected formatting in %s sigs section line %d:%s' % (fitimage_its_path, linect, line))
+                    key, value = line.split('=', 1)
+                    sigs[itsdotpath][key.rstrip()] = value.lstrip().rstrip(';')
+
+        for reqpath in req_itspaths:
+            if not reqpath in itspaths:
+                self.fail('Missing section in its file: %s' % reqpath)
+
+        reqsigvalues_image = {
+            'algo': '"sha256,rsa2048"',
+            'key-name-hint': '"spl-oe-selftest"',
+        }
+
+        for itspath, values in sigs.items():
+            reqsigvalues = reqsigvalues_image
+            for reqkey, reqvalue in reqsigvalues.items():
+                value = values.get(reqkey, None)
+                if value is None:
+                    self.fail('Missing key "%s" in its file signature section %s' % (reqkey, itspath))
+                self.assertEqual(value, reqvalue)
+
+        # Dump the image to see if it really got signed
+        bitbake("u-boot-tools-native -c addto_recipe_sysroot")
+        result = runCmd('bitbake -e u-boot-tools-native | grep ^RECIPE_SYSROOT_NATIVE=')
+        recipe_sysroot_native = result.output.split('=')[1].strip('"')
+        dumpimage_path = os.path.join(recipe_sysroot_native, 'usr', 'bin', 'dumpimage')
+        result = runCmd('%s -l %s' % (dumpimage_path, fitimage_path))
+        in_signed = None
+        signed_sections = {}
+        for line in result.output.splitlines():
+            if line.startswith((' Image')):
+                in_signed = re.search('\((.*)\)', line).groups()[0]
+            elif re.match(' \w', line):
+                in_signed = None
+            elif in_signed:
+                if not in_signed in signed_sections:
+                    signed_sections[in_signed] = {}
+                key, value = line.split(':', 1)
+                signed_sections[in_signed][key.strip()] = value.strip()
+        self.assertIn('uboot', signed_sections)
+        self.assertIn('fdt', signed_sections)
+        for signed_section, values in signed_sections.items():
+            value = values.get('Sign algo', None)
+            self.assertEqual(value, 'sha256,rsa2048:spl-oe-selftest', 'Signature algorithm for %s not expected value' % signed_section)
+            value = values.get('Sign value', None)
+            self.assertEqual(len(value), 512, 'Signature value for section %s not expected length' % signed_section)
+
+        # Check for SPL_MKIMAGE_SIGN_ARGS
+        result = runCmd('bitbake -e virtual/kernel | grep ^T=')
+        tempdir = result.output.split('=', 1)[1].strip().strip('')
+        result = runCmd('grep "a smart U-Boot comment" %s/run.do_uboot_assemble_fitimage' % tempdir, ignore_status=True)
+        self.assertEqual(result.status, 0, 'SPL_MKIMAGE_SIGN_ARGS value did not get used')
+
+        # Check for evidence of test-mkimage-wrapper class
+        result = runCmd('grep "### uboot-mkimage wrapper message" %s/log.do_uboot_assemble_fitimage' % tempdir, ignore_status=True)
+        self.assertEqual(result.status, 0, 'UBOOT_MKIMAGE did not work')
+        result = runCmd('grep "### uboot-mkimage signing wrapper message" %s/log.do_uboot_assemble_fitimage' % tempdir, ignore_status=True)
+        self.assertEqual(result.status, 0, 'UBOOT_MKIMAGE_SIGN did not work')
+
+    def test_sign_cascaded_uboot_fit_image(self):
+        """
+        Summary:     Check if U-Boot FIT image and Image Tree Source (its) are
+                     created and signed correctly for the scenario where both
+                     U-Boot proper and Kernel fitImages are being created and
+                     signed.
+        Expected:    1) U-Boot its and FIT image are built successfully
+                     2) Scanning the its file indicates signing is enabled
+                        as requested by SPL_SIGN_ENABLE (using keys generated
+                        via UBOOT_FIT_GENERATE_KEYS)
+                     3) Dumping the FIT image indicates signature values
+                        are present
+                     4) Examination of the do_uboot_assemble_fitimage
+                     runfile/logfile indicate that UBOOT_MKIMAGE, UBOOT_MKIMAGE_SIGN
+                     and SPL_MKIMAGE_SIGN_ARGS are working as expected.
+        Product:     oe-core
+        Author:      Klaus Heinrich Kiwi <[email protected]> based upon
+                     work by Paul Eggleton <[email protected]> and
+                     Usama Arif <[email protected]>
+        """
+        config = """
+# There's no U-boot deconfig with CONFIG_FIT_SIGNATURE yet, so we need at
+# least CONFIG_SPL_LOAD_FIT and CONFIG_SPL_OF_CONTROL set
+MACHINE = "qemuarm"
+UBOOT_MACHINE = "am57xx_evm_defconfig"
+SPL_BINARY = "MLO"
+# Enable creation and signing of the U-Boot fitImage
+UBOOT_FITIMAGE_ENABLE = "1"
+SPL_SIGN_ENABLE = "1"
+SPL_SIGN_KEYNAME = "spl-cascaded-oe-selftest"
+SPL_SIGN_KEYDIR = "${TOPDIR}/signing-keys"
+UBOOT_DTB_BINARY = "u-boot.dtb"
+UBOOT_ENTRYPOINT  = "0x80000000"
+UBOOT_LOADADDRESS = "0x80000000"
+UBOOT_MKIMAGE_DTCOPTS = "-I dts -O dtb -p 2000"
+UBOOT_MKIMAGE_SIGN_ARGS = "-c 'a smart cascaded Kernel comment'"
+UBOOT_DTB_LOADADDRESS = "0x82000000"
+UBOOT_ARCH = "arm"
+SPL_MKIMAGE_DTCOPTS = "-I dts -O dtb -p 2000"
+SPL_MKIMAGE_SIGN_ARGS = "-c 'a smart cascaded U-Boot comment'"
+UBOOT_EXTLINUX = "0"
+UBOOT_FIT_GENERATE_KEYS = "1"
+UBOOT_FIT_HASH_ALG = "sha256"
+KERNEL_IMAGETYPES += " fitImage "
+KERNEL_CLASSES = " kernel-fitimage test-mkimage-wrapper "
+UBOOT_SIGN_ENABLE = "1"
+FIT_GENERATE_KEYS = "1"
+UBOOT_SIGN_KEYDIR = "${TOPDIR}/signing-keys"
+UBOOT_SIGN_KEYNAME = "kernel-oe-selftest"
+FIT_SIGN_INDIVIDUAL = "1"
+"""
+        self.write_config(config)
+
+        # The U-Boot fitImage is created as part of linux recipe
+        bitbake("virtual/kernel")
+
+        image_type = "core-image-minimal"
+        deploy_dir_image = get_bb_var('DEPLOY_DIR_IMAGE')
+        machine = get_bb_var('MACHINE')
+        fitimage_its_path = os.path.join(deploy_dir_image,
+            "u-boot-its-%s" % (machine,))
+        fitimage_path = os.path.join(deploy_dir_image,
+            "u-boot-fitImage-%s" % (machine,))
+
+        self.assertTrue(os.path.exists(fitimage_its_path),
+            "%s image tree source doesn't exist" % (fitimage_its_path))
+        self.assertTrue(os.path.exists(fitimage_path),
+            "%s FIT image doesn't exist" % (fitimage_path))
+
+        req_itspaths = [
+            ['/', 'images', 'uboot'],
+            ['/', 'images', 'uboot', 'signature'],
+            ['/', 'images', 'fdt'],
+            ['/', 'images', 'fdt', 'signature'],
+        ]
+
+        itspath = []
+        itspaths = []
+        linect = 0
+        sigs = {}
+        with open(fitimage_its_path) as its_file:
+            linect += 1
+            for line in its_file:
+                line = line.strip()
+                if line.endswith('};'):
+                    itspath.pop()
+                elif line.endswith('{'):
+                    itspath.append(line[:-1].strip())
+                    itspaths.append(itspath[:])
+                elif itspath and itspath[-1] == 'signature':
+                    itsdotpath = '.'.join(itspath)
+                    if not itsdotpath in sigs:
+                        sigs[itsdotpath] = {}
+                    if not '=' in line or not line.endswith(';'):
+                        self.fail('Unexpected formatting in %s sigs section line %d:%s' % (fitimage_its_path, linect, line))
+                    key, value = line.split('=', 1)
+                    sigs[itsdotpath][key.rstrip()] = value.lstrip().rstrip(';')
+
+        for reqpath in req_itspaths:
+            if not reqpath in itspaths:
+                self.fail('Missing section in its file: %s' % reqpath)
+
+        reqsigvalues_image = {
+            'algo': '"sha256,rsa2048"',
+            'key-name-hint': '"spl-cascaded-oe-selftest"',
+        }
+
+        for itspath, values in sigs.items():
+            reqsigvalues = reqsigvalues_image
+            for reqkey, reqvalue in reqsigvalues.items():
+                value = values.get(reqkey, None)
+                if value is None:
+                    self.fail('Missing key "%s" in its file signature section %s' % (reqkey, itspath))
+                self.assertEqual(value, reqvalue)
+
+        # Dump the image to see if it really got signed
+        bitbake("u-boot-tools-native -c addto_recipe_sysroot")
+        result = runCmd('bitbake -e u-boot-tools-native | grep ^RECIPE_SYSROOT_NATIVE=')
+        recipe_sysroot_native = result.output.split('=')[1].strip('"')
+        dumpimage_path = os.path.join(recipe_sysroot_native, 'usr', 'bin', 'dumpimage')
+        result = runCmd('%s -l %s' % (dumpimage_path, fitimage_path))
+        in_signed = None
+        signed_sections = {}
+        for line in result.output.splitlines():
+            if line.startswith((' Image')):
+                in_signed = re.search('\((.*)\)', line).groups()[0]
+            elif re.match(' \w', line):
+                in_signed = None
+            elif in_signed:
+                if not in_signed in signed_sections:
+                    signed_sections[in_signed] = {}
+                key, value = line.split(':', 1)
+                signed_sections[in_signed][key.strip()] = value.strip()
+        self.assertIn('uboot', signed_sections)
+        self.assertIn('fdt', signed_sections)
+        for signed_section, values in signed_sections.items():
+            value = values.get('Sign algo', None)
+            self.assertEqual(value, 'sha256,rsa2048:spl-cascaded-oe-selftest', 'Signature algorithm for %s not expected value' % signed_section)
+            value = values.get('Sign value', None)
+            self.assertEqual(len(value), 512, 'Signature value for section %s not expected length' % signed_section)
+
+        # Check for SPL_MKIMAGE_SIGN_ARGS
+        result = runCmd('bitbake -e virtual/kernel | grep ^T=')
+        tempdir = result.output.split('=', 1)[1].strip().strip('')
+        result = runCmd('grep "a smart cascaded U-Boot comment" %s/run.do_uboot_assemble_fitimage' % tempdir, ignore_status=True)
+        self.assertEqual(result.status, 0, 'SPL_MKIMAGE_SIGN_ARGS value did not get used')
+
+        # Check for evidence of test-mkimage-wrapper class
+        result = runCmd('grep "### uboot-mkimage wrapper message" %s/log.do_uboot_assemble_fitimage' % tempdir, ignore_status=True)
+        self.assertEqual(result.status, 0, 'UBOOT_MKIMAGE did not work')
+        result = runCmd('grep "### uboot-mkimage signing wrapper message" %s/log.do_uboot_assemble_fitimage' % tempdir, ignore_status=True)
+        self.assertEqual(result.status, 0, 'UBOOT_MKIMAGE_SIGN did not work')
+
+
+
     def test_initramfs_bundle(self):
         """
         Summary:     Verifies the content of the initramfs bundle node in the FIT Image Tree Source (its)
Signature · 1 line
2.25.1
#5 lore raw
In reply to Klaus Heinrich Kiwi
Quoted 34 lines · Klaus Heinrich Kiwi

This patch series aims at extending U-Boot's verified boot support to also include SPL.

Presently, setting UBOOT_SIGN_ENABLE instructs the classes uboot-sign and kernel-fitimage to create and sign a Linux Kernel fitImage. This proposal introduces the variables UBOOT_FITIMAGE_ENABLE and SPL_SIGN_ENABLE that will, respectively, create and sign a U-Boot (proper) fitImage that the SPL can load (and verify if enabled)

In order to accomplish this, the first patch moves some of necessary infrastructure (variables, functions) used to sign the Kernel fitImage to more common locations, and then essentially duplicates the method currently used to sign the Kernel fitImage to also sign the U-Boot fitImage.

If the variable UBOOT_FITIMAGE_ENABLE = "1", the uboot-sign class will copy the SPL files (nodtb image and dtb file) from the u-boot recipe to the staging area, so that the Kernel recipe can then create the U-Boot fitImage.

In case SPL_SIGN_ENABLE = "1", the U-Boot fitImage will be signed using the key provided by SPL_SIGN_KEYNAME / SPL_SIGN_KEYDIR, or will auto-generate keys based on UBOOT_FIT_HASH_ALG, UBOOT_FIT_SIGN_ALG and UBOOT_FIT_SIGN_NUMBITS if UBOOT_FIT_GENERATE_KEYS is "1".

After the operations above, the Kernel recipe will deploy the (signed) U-Boot fitImage, the ITS script used to create it, as well as the SPL concatenated with the DTB containing the pubkey to the images directory.

The reason why the U-Boot fitImage is created by the Kernel is in order to make sure that, when UBOOT_SIGN_ENABLE is set (and the Kernel fitImage is signed), the U-Boot fitImage being created/signed contains the pubkey used by the Kernel recipe to sign the Kernel fitImage.

Quoted 4 lines

I added oe-selftest testcases and also tested this on upstream OpenBMC with AST2600 BMC devices.

I've merged this, I wanted to say a big thanks for writing some test cases for these code paths. It should start to help a lot in this area in the future. I'm going to be asking that future fixes in this area add/improve test cases to cover issues too.

Cheers,

Richard

#6 lore raw
Quoted 11 lines · Richard Purdie
Quoted 4 lines · Klaus Heinrich Kiwi

This patch series aims at extending U-Boot's verified boot support to also include SPL.

I've merged this, I wanted to say a big thanks for writing some test cases for these code paths. It should start to help a lot in this area in the future. I'm going to be asking that future fixes in this area add/improve test cases to cover issues too.

Thanks Richard.

FYI, there's a patch I sent recently with relatively important fixes (for some corner cases) that should apply on top of the patches above:

Subject: [PATCH] uboot: Fixes SPL verified boot on corner cases
Date: Mar 31, 2021

I'd recommend applying that patch as well, before yocto / other projects start pulling from oe-core.

Thanks,

-Klaus

Signature · 1 line
Klaus Heinrich Kiwi <[email protected]>
#7 lore raw
Quoted 17 lines · Klaus Heinrich Kiwi
Quoted 11 lines · Richard Purdie
Quoted 4 lines · Klaus Heinrich Kiwi

This patch series aims at extending U-Boot's verified boot support to also include SPL.

I've merged this, I wanted to say a big thanks for writing some test cases for these code paths. It should start to help a lot in this area in the future. I'm going to be asking that future fixes in this area add/improve test cases to cover issues too.

Thanks Richard.

Quoted 8 lines

FYI, there's a patch I sent recently with relatively important fixes (for some corner cases) that should apply on top of the patches above:

Subject: [PATCH] uboot: Fixes SPL verified boot on corner cases
Date: Mar 31, 2021

I'd recommend applying that patch as well, before yocto / other projects start pulling from oe-core.

Thanks, it didn't apply 100% cleanly which is why I'd deferred it but I've got to apply and am testing...

Cheers,

Richard