Skip to contentSkip to conversation

Add support for ECDSA image signing

PATCH New Alexandru Gagniuc 3 participants 24 messages Feb 19, 2021 – Apr 16, 2021

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

v6 cover Add support for ECDSA image signing

## Purpose and intent

The purpose of this series is to enable ECDSA as an alternative to RSA for FIT signing. As new chips have built-in support for ECDSA verified boot, it makes sense to stick to one signing algorithm, instead of resorting to RSA for u-boot images.

The focus of this series is signing an existing FIT image:

mkimage -F some-existing.fit -G some/key.pem

Signing while assembling a FIT is not a tested use case. This concatenates two series:

* Add support for ECDSA image signing (with test)
* mkimage: Add a 'keyfile' argument for image signing

# Testing

test/py/tests/test_fit_ecdsa.py is implemented withe the goal to check that the signing is done correctly, and that the signature is encoded in the proper raw format. Verification is done with pyCryptodomex, so this test will catch both coding errors and openssl bugs. This is the only scope of testing proposed here.

Changes since v5:
- Include "mkimage: Add a 'keyfile' argument for image signing" series
- Update python test to use 'keyfile' (-G) mkinage argument
- document which strings can be null in image.h
- Fix typo in python test (invokations -> invocations)

Changes since v4:
- Fixed tools/ build issue with # FIT_SIGNATURE is not selected

Changes since v3:
- Don't use 'log_msg_ret()', as it's not available host-side

Changes since v1 and v2:
- Added lots of function comments
- Replaced hardcoded error numbers with more meaningful errno numbers
- Changed some error paths to use 'return log_msg_ret'

Alexandru Gagniuc (11):
lib: Rename rsa-checksum.c to hash-checksum.c lib/rsa: Make fdt_add_bignum() available outside of RSA code
lib: Add support for ECDSA image signing
doc: signature.txt: Document devicetree format for ECDSA keys test/py: Add pycryptodomex to list of required pakages test/py: ecdsa: Add test for mkimage ECDSA signing
doc: signature.txt: Document the keydir and keyfile arguments
mkimage: Add a 'keyfile' argument for image signing lib/rsa: Use the 'keyfile' argument from mkimage lib/ecdsa: Use the 'keydir' argument from mkimage if appropriate test/py: ecdsa: Use mkimage keyfile instead of keydir argument

 common/image-fit-sig.c                        |   2 +-
 common/image-sig.c                            |  13 +-
 doc/uImage.FIT/signature.txt                  |  20 +-
 include/image.h                               |  21 +-
 include/u-boot/ecdsa.h                        |  94 ++++++
 include/u-boot/fdt-libcrypto.h                |  27 ++
 .../{rsa-checksum.h => hash-checksum.h}       |   0
 lib/Makefile                                  |   1 +
 lib/crypto/pkcs7_verify.c                     |   2 +-
 lib/crypto/x509_public_key.c                  |   2 +-
 lib/ecdsa/ecdsa-libcrypto.c                   | 318 ++++++++++++++++++
 lib/fdt-libcrypto.c                           |  72 ++++
 lib/{rsa/rsa-checksum.c => hash-checksum.c}   |   3 +-
 lib/rsa/Makefile                              |   2 +-
 lib/rsa/rsa-sign.c                            |  99 ++----
 test/py/requirements.txt                      |   1 +
 test/py/tests/test_fit_ecdsa.py               | 111 ++++++
 tools/Makefile                                |  11 +-
 tools/fit_image.c                             |   3 +-
 tools/image-host.c                            |  58 ++--
 tools/imagetool.h                             |   1 +
 tools/mkimage.c                               |   6 +-
 22 files changed, 752 insertions(+), 115 deletions(-)
 create mode 100644 include/u-boot/ecdsa.h
 create mode 100644 include/u-boot/fdt-libcrypto.h
 rename include/u-boot/{rsa-checksum.h => hash-checksum.h} (100%)
 create mode 100644 lib/ecdsa/ecdsa-libcrypto.c
 create mode 100644 lib/fdt-libcrypto.c
 rename lib/{rsa/rsa-checksum.c => hash-checksum.c} (96%)
 create mode 100644 test/py/tests/test_fit_ecdsa.py
Signature · 1 line
2.26.2
#1 lore raw

PATCH v6 1/11 lib: Rename rsa-checksum.c to hash-checksum.c

rsa-checksum.c sontains the hash_calculate() implementations. Despite the "rsa-" file prefix, this function is useful for other algorithms.

To prevent confusion, move this file to lib/, and rename it to hash-checksum.c, to give it a more "generic" feel.

---
 common/image-fit-sig.c                             | 2 +-
 common/image-sig.c                                 | 2 +-
 include/image.h                                    | 2 +-
 include/u-boot/{rsa-checksum.h => hash-checksum.h} | 0
 lib/Makefile                                       | 1 +
 lib/crypto/pkcs7_verify.c                          | 2 +-
 lib/crypto/x509_public_key.c                       | 2 +-
 lib/{rsa/rsa-checksum.c => hash-checksum.c}        | 3 ++-
 lib/rsa/Makefile                                   | 2 +-
 tools/Makefile                                     | 3 ++-
 10 files changed, 11 insertions(+), 8 deletions(-)
 rename include/u-boot/{rsa-checksum.h => hash-checksum.h} (100%)
 rename lib/{rsa/rsa-checksum.c => hash-checksum.c} (96%)
common/image-fit-sig.c +1 -1
index 34ebb8edfe..55ddf1879e 100644
@@ -16,7 +16,7 @@ DECLARE_GLOBAL_DATA_PTR;
 #include <fdt_region.h>
 #include <image.h>
 #include <u-boot/rsa.h>
-#include <u-boot/rsa-checksum.h>
+#include <u-boot/hash-checksum.h>
 
 #define IMAGE_MAX_HASHED_NODES		100
 
common/image-sig.c +1 -1
index 4abd3c080f..54f0eb2019 100644
@@ -17,7 +17,7 @@ DECLARE_GLOBAL_DATA_PTR;
 #endif /* !USE_HOSTCC*/
 #include <image.h>
 #include <u-boot/rsa.h>
-#include <u-boot/rsa-checksum.h>
+#include <u-boot/hash-checksum.h>
 
 #define IMAGE_MAX_HASHED_NODES		100
 
include/image.h +1 -1
index d5a940313a..fbe9537c00 100644
@@ -1278,7 +1278,7 @@ struct image_region {
 };
 
 #if IMAGE_ENABLE_VERIFY
-# include <u-boot/rsa-checksum.h>
+# include <u-boot/hash-checksum.h>
 #endif
 struct checksum_algo {
 	const char *name;
include/u-boot/hash-checksum.h renamed from include/u-boot/rsa-checksum.h +0 -0
similarity index 100%
rename from include/u-boot/rsa-checksum.h
rename to include/u-boot/hash-checksum.h
lib/Makefile +1 -0
index edc1c3dd4f..1d4b7d3aad 100644
@@ -60,6 +60,7 @@ endif
 obj-$(CONFIG_$(SPL_)ACPIGEN) += acpi/
 obj-$(CONFIG_$(SPL_)MD5) += md5.o
 obj-$(CONFIG_$(SPL_)RSA) += rsa/
+obj-$(CONFIG_FIT_SIGNATURE) += hash-checksum.o
 obj-$(CONFIG_SHA1) += sha1.o
 obj-$(CONFIG_SHA256) += sha256.o
 obj-$(CONFIG_SHA512_ALGO) += sha512.o
lib/crypto/pkcs7_verify.c +1 -1
index 58683ef614..82c5c745d4 100644
@@ -15,7 +15,7 @@
 #include <linux/bitops.h>
 #include <linux/compat.h>
 #include <linux/asn1.h>
-#include <u-boot/rsa-checksum.h>
+#include <u-boot/hash-checksum.h>
 #include <crypto/public_key.h>
 #include <crypto/pkcs7_parser.h>
 #else
lib/crypto/x509_public_key.c +1 -1
index 91810a8640..d557ab27ae 100644
@@ -19,7 +19,7 @@
 #include <linux/kernel.h>
 #ifdef __UBOOT__
 #include <crypto/x509_parser.h>
-#include <u-boot/rsa-checksum.h>
+#include <u-boot/hash-checksum.h>
 #else
 #include <linux/slab.h>
 #include <keys/asymmetric-subtype.h>
lib/hash-checksum.c renamed from lib/rsa/rsa-checksum.c +2 -1
similarity index 96%
rename from lib/rsa/rsa-checksum.c
rename to lib/hash-checksum.c
index e60debb7df..d732ecc38f 100644
@@ -13,7 +13,8 @@
 #else
 #include "fdt_host.h"
 #endif
-#include <u-boot/rsa.h>
+#include <hash.h>
+#include <image.h>
 
 int hash_calculate(const char *name,
 		    const struct image_region region[],
lib/rsa/Makefile +1 -1
index 8b75d41f04..c9ac72c1e2 100644
@@ -5,6 +5,6 @@
 # (C) Copyright 2000-2007
 # Wolfgang Denk, DENX Software Engineering, wd at denx.de.
 
-obj-$(CONFIG_$(SPL_TPL_)RSA_VERIFY) += rsa-verify.o rsa-checksum.o
+obj-$(CONFIG_$(SPL_TPL_)RSA_VERIFY) += rsa-verify.o
 obj-$(CONFIG_$(SPL_TPL_)RSA_VERIFY_WITH_PKEY) += rsa-keyprop.o
 obj-$(CONFIG_RSA_SOFTWARE_EXP) += rsa-mod-exp.o
tools/Makefile +2 -1
index 2d550432ba..96316ed729 100644
@@ -67,7 +67,7 @@ LIBFDT_OBJS := $(addprefix libfdt/, fdt.o fdt_ro.o fdt_wip.o fdt_sw.o fdt_rw.o \
 		fdt_strerror.o fdt_empty_tree.o fdt_addresses.o fdt_overlay.o)
 
 RSA_OBJS-$(CONFIG_FIT_SIGNATURE) := $(addprefix lib/rsa/, \
-					rsa-sign.o rsa-verify.o rsa-checksum.o \
+					rsa-sign.o rsa-verify.o \
 					rsa-mod-exp.o)
 
 AES_OBJS-$(CONFIG_FIT_CIPHER) := $(addprefix lib/aes/, \
@@ -106,6 +106,7 @@ dumpimage-mkimage-objs := aisimage.o \
 			socfpgaimage.o \
 			sunxi_egon.o \
 			lib/crc16.o \
+			lib/hash-checksum.o \
 			lib/sha1.o \
 			lib/sha256.o \
 			lib/sha512.o \
Signature · 1 line
2.26.2
#2 lore raw

PATCH v6 1/11 lib: Rename rsa-checksum.c to hash-checksum.c

Quoted 8 lines · Alexandru Gagniuc

rsa-checksum.c sontains the hash_calculate() implementations. Despite the "rsa-" file prefix, this function is useful for other algorithms.

To prevent confusion, move this file to lib/, and rename it to hash-checksum.c, to give it a more "generic" feel.

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210416/b46480cf/attachment.sig>
#3 lore raw

PATCH v6 2/11 lib/rsa: Make fdt_add_bignum() available outside of RSA code

In reply to Alexandru Gagniuc

fdt_add_bignum() is useful for algorithms other than just RSA. To allow its use for ECDSA, move it to a common file under lib/.

The new file is suffixed with '-libcrypto' because it has a direct dependency on openssl. This is due to the use of the "BIGNUM *" type.

---
 include/u-boot/fdt-libcrypto.h | 27 +++++++++++++
 lib/fdt-libcrypto.c            | 72 ++++++++++++++++++++++++++++++++++
 lib/rsa/rsa-sign.c             | 65 +-----------------------------
 tools/Makefile                 |  5 +++
 4 files changed, 105 insertions(+), 64 deletions(-)
 create mode 100644 include/u-boot/fdt-libcrypto.h
 create mode 100644 lib/fdt-libcrypto.c
include/u-boot/fdt-libcrypto.h new file +27 -0
new file mode 100644
index 0000000000..5142f37039
@@ -0,0 +1,27 @@
+/* SPDX-License-Identifier: GPL-2.0+ */
+/*
+ * Copyright (c) 2020, Alexandru Gagniuc <[email protected]>
+ * Copyright (c) 2013, Google Inc.
+ */
+
+#ifndef _FDT_LIBCRYPTO_H
+#define _FDT_LIBCRYPTO_H
+
+#include <openssl/bn.h>
+
+/**
+ * fdt_add_bignum() - Write a libcrypto BIGNUM as an FDT property
+ *
+ * Convert a libcrypto BIGNUM * into a big endian array of integers.
+ *
+ * @blob:	FDT blob to modify
+ * @noffset:	Offset of the FDT node
+ * @prop_name:	What to call the property in the FDT
+ * @num:	pointer to a libcrypto big number
+ * @num_bits:	How big is 'num' in bits?
+ * @return 0 if all good all working, -ve on horror
+ */
+int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
+		   BIGNUM *num, int num_bits);
+
+#endif /* _FDT_LIBCRYPTO_H */
lib/fdt-libcrypto.c new file +72 -0

72 lines not on this page · raw message

lib/rsa/rsa-sign.c +1 -64

77 lines not on this page · raw message

tools/Makefile +5 -0
index 96316ed729..58b13eaf12 100644
@@ -73,6 +73,10 @@ RSA_OBJS-$(CONFIG_FIT_SIGNATURE) := $(addprefix lib/rsa/, \
 AES_OBJS-$(CONFIG_FIT_CIPHER) := $(addprefix lib/aes/, \
 					aes-encrypt.o aes-decrypt.o)
 
+# Cryptographic helpers that depend on openssl/libcrypto
+LIBCRYPTO_OBJS-$(CONFIG_FIT_SIGNATURE) := $(addprefix lib/, \
+					fdt-libcrypto.o)
+
 ROCKCHIP_OBS = lib/rc4.o rkcommon.o rkimage.o rksd.o rkspi.o
 
 # common objs for dumpimage and mkimage
@@ -115,6 +119,7 @@ dumpimage-mkimage-objs := aisimage.o \
 			zynqimage.o \
 			zynqmpimage.o \
 			zynqmpbif.o \
+			$(LIBCRYPTO_OBJS-y) \
 			$(LIBFDT_OBJS) \
 			gpimage.o \
 			gpimage-common.o \
Signature · 1 line
2.26.2
#4 lore raw

PATCH v6 2/11 lib/rsa: Make fdt_add_bignum() available outside of RSA code

Quoted 8 lines · Alexandru Gagniuc

fdt_add_bignum() is useful for algorithms other than just RSA. To allow its use for ECDSA, move it to a common file under lib/.

The new file is suffixed with '-libcrypto' because it has a direct dependency on openssl. This is due to the use of the "BIGNUM *" type.

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210416/e54496e2/attachment.sig>
#5 lore raw

PATCH v6 3/11 lib: Add support for ECDSA image signing

In reply to Alexandru Gagniuc

mkimage supports rsa2048, and rsa4096 signatures. With newer silicon now supporting hardware-accelerated ECDSA, it makes sense to expand signing support to elliptic curves.

Implement host-side ECDSA signing and verification with libcrypto. Device-side implementation of signature verification is beyond the scope of this patch.

---
 common/image-sig.c          |  11 +-
 include/image.h             |   3 +
 include/u-boot/ecdsa.h      |  94 +++++++++++
 lib/ecdsa/ecdsa-libcrypto.c | 306 ++++++++++++++++++++++++++++++++++++
 tools/Makefile              |   3 +
 5 files changed, 415 insertions(+), 2 deletions(-)
 create mode 100644 include/u-boot/ecdsa.h
 create mode 100644 lib/ecdsa/ecdsa-libcrypto.c
common/image-sig.c +9 -2
index 54f0eb2019..0f8e592aba 100644
@@ -16,6 +16,7 @@
 DECLARE_GLOBAL_DATA_PTR;
 #endif /* !USE_HOSTCC*/
 #include <image.h>
+#include <u-boot/ecdsa.h>
 #include <u-boot/rsa.h>
 #include <u-boot/hash-checksum.h>
 
@@ -83,8 +84,14 @@ struct crypto_algo crypto_algos[] = {
 		.sign = rsa_sign,
 		.add_verify_data = rsa_add_verify_data,
 		.verify = rsa_verify,
-	}
-
+	},
+	{
+		.name = "ecdsa256",
+		.key_len = ECDSA256_BYTES,
+		.sign = ecdsa_sign,
+		.add_verify_data = ecdsa_add_verify_data,
+		.verify = ecdsa_verify,
+	},
 };
 
 struct padding_algo padding_algos[] = {
include/image.h +3 -0
index fbe9537c00..37feb5d56f 100644
@@ -1219,16 +1219,19 @@ int calculate_hash(const void *data, int data_len, const char *algo,
 # if defined(CONFIG_FIT_SIGNATURE)
 #  define IMAGE_ENABLE_SIGN	1
 #  define IMAGE_ENABLE_VERIFY	1
+#  define IMAGE_ENABLE_VERIFY_ECDSA	1
 #  define FIT_IMAGE_ENABLE_VERIFY	1
 #  include <openssl/evp.h>
 # else
 #  define IMAGE_ENABLE_SIGN	0
 #  define IMAGE_ENABLE_VERIFY	0
+# define IMAGE_ENABLE_VERIFY_ECDSA	0
 #  define FIT_IMAGE_ENABLE_VERIFY	0
 # endif
 #else
 # define IMAGE_ENABLE_SIGN	0
 # define IMAGE_ENABLE_VERIFY		CONFIG_IS_ENABLED(RSA_VERIFY)
+# define IMAGE_ENABLE_VERIFY_ECDSA	0
 # define FIT_IMAGE_ENABLE_VERIFY	CONFIG_IS_ENABLED(FIT_SIGNATURE)
 #endif
 
include/u-boot/ecdsa.h new file +94 -0

94 lines not on this page · raw message

lib/ecdsa/ecdsa-libcrypto.c new file +306 -0

306 lines not on this page · raw message

tools/Makefile +3 -0
index 58b13eaf12..90f4c90576 100644
@@ -70,6 +70,8 @@ RSA_OBJS-$(CONFIG_FIT_SIGNATURE) := $(addprefix lib/rsa/, \
 					rsa-sign.o rsa-verify.o \
 					rsa-mod-exp.o)
 
+ECDSA_OBJS-$(CONFIG_FIT_SIGNATURE) := $(addprefix lib/ecdsa/, ecdsa-libcrypto.o)
+
 AES_OBJS-$(CONFIG_FIT_CIPHER) := $(addprefix lib/aes/, \
 					aes-encrypt.o aes-decrypt.o)
 
@@ -124,6 +126,7 @@ dumpimage-mkimage-objs := aisimage.o \
 			gpimage.o \
 			gpimage-common.o \
 			mtk_image.o \
+			$(ECDSA_OBJS-y) \
 			$(RSA_OBJS-y) \
 			$(AES_OBJS-y)
 
Signature · 1 line
2.26.2
#6 lore raw

PATCH v6 3/11 lib: Add support for ECDSA image signing

Quoted 10 lines · Alexandru Gagniuc

mkimage supports rsa2048, and rsa4096 signatures. With newer silicon now supporting hardware-accelerated ECDSA, it makes sense to expand signing support to elliptic curves.

Implement host-side ECDSA signing and verification with libcrypto. Device-side implementation of signature verification is beyond the scope of this patch.

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210416/0e08c375/attachment.sig>
#7 lore raw

PATCH v6 4/11 doc: signature.txt: Document devicetree format for ECDSA keys

In reply to Alexandru Gagniuc
---
 doc/uImage.FIT/signature.txt | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
doc/uImage.FIT/signature.txt +6 -1
index a3455889ed..0139295d33 100644
@@ -142,7 +142,7 @@ public key in U-Boot's control FDT (using CONFIG_OF_CONTROL).
 Public keys should be stored as sub-nodes in a /signature node. Required
 properties are:
 
-- algo: Algorithm name (e.g. "sha1,rsa2048")
+- algo: Algorithm name (e.g. "sha1,rsa2048" or "sha256,ecdsa256")
 
 Optional properties are:
 
@@ -167,6 +167,11 @@ For RSA the following are mandatory:
 - rsa,r-squared: (2^num-bits)^2 as a big-endian multi-word integer
 - rsa,n0-inverse: -1 / modulus[0] mod 2^32
 
+For ECDSA the following are mandatory:
+- ecdsa,curve: Name of ECDSA curve (e.g. "prime256v1")
+- ecdsa,x-point: Public key X coordinate as a big-endian multi-word integer
+- ecdsa,y-point: Public key Y coordinate as a big-endian multi-word integer
+
 These parameters can be added to a binary device tree using parameter -K of the
 mkimage command::
 
Signature · 1 line
2.26.2
#8 lore raw

PATCH v6 4/11 doc: signature.txt: Document devicetree format for ECDSA keys

Quoted 2 lines · Alexandru Gagniuc

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210416/9903cac7/attachment.sig>
#9 lore raw

PATCH v6 5/11 test/py: Add pycryptodomex to list of required pakages

In reply to Alexandru Gagniuc

We wish to use pycryptodomex to verify code paths involving ECDSA signatures. Add it to requirements.txt so that they get picked up automatically .gitlab and .azure tasks

---
 test/py/requirements.txt | 1 +
 1 file changed, 1 insertion(+)
test/py/requirements.txt +1 -0
index 926bccad69..9dea9415a7 100644
@@ -10,6 +10,7 @@ packaging==19.2
 pbr==5.4.3
 pluggy==0.13.0
 py==1.8.0
+pycryptodomex==3.9.8
 pyelftools==0.27
 pygit2==1.4.0
 pyparsing==2.4.2
Signature · 1 line
2.26.2
#10 lore raw

PATCH v6 5/11 test/py: Add pycryptodomex to list of required pakages

Quoted 6 lines · Alexandru Gagniuc

We wish to use pycryptodomex to verify code paths involving ECDSA signatures. Add it to requirements.txt so that they get picked up automatically .gitlab and .azure tasks

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210416/69ad42e2/attachment.sig>
#11 lore raw

PATCH v6 6/11 test/py: ecdsa: Add test for mkimage ECDSA signing

In reply to Alexandru Gagniuc

Add a test to make sure that the ECDSA signatures generated by mkimage can be verified successfully. pyCryptodomex was chosen as the crypto library because it integrates much better with python code. Using openssl would have been unnecessarily painful.

---
 test/py/tests/test_fit_ecdsa.py | 111 ++++++++++++++++++++++++++++++++
 1 file changed, 111 insertions(+)
 create mode 100644 test/py/tests/test_fit_ecdsa.py
test/py/tests/test_fit_ecdsa.py new file +111 -0
new file mode 100644
index 0000000000..f597570281
@@ -0,0 +1,111 @@
+# SPDX-License-Identifier:	GPL-2.0+
+#
+# Copyright (c) 2020,2021 Alexandru Gagniuc <[email protected]>
+
+"""
+Test ECDSA signing of FIT images
+
+This test uses mkimage to sign an existing FIT image with an ECDSA key. The
+signature is then extracted, and verified against pyCryptodome.
+This test doesn't run the sandbox. It only checks the host tool 'mkimage'
+"""
+
+import pytest
+import u_boot_utils as util
+from Cryptodome.Hash import SHA256
+from Cryptodome.PublicKey import ECC
+from Cryptodome.Signature import DSS
+
+class SignableFitImage(object):
+    """ Helper to manipulate a FIT image on disk """
+    def __init__(self, cons, file_name):
+        self.fit = file_name
+        self.cons = cons
+        self.signable_nodes = set()
+
+    def __fdt_list(self, path):
+        return util.run_and_log(self.cons, f'fdtget -l {self.fit} {path}')
+
+    def __fdt_set(self, node, **prop_value):
+        for prop, value in prop_value.items():
+            util.run_and_log(self.cons, f'fdtput -ts {self.fit} {node} {prop} {value}')
+
+    def __fdt_get_binary(self, node, prop):
+        numbers = util.run_and_log(self.cons, f'fdtget -tbi {self.fit} {node} {prop}')
+
+        bignum = bytearray()
+        for little_num in numbers.split():
+            bignum.append(int(little_num))
+
+        return bignum
+
+    def find_signable_image_nodes(self):
+        for node in self.__fdt_list('/images').split():
+            image = f'/images/{node}'
+            if 'signature' in self.__fdt_list(image):
+                self.signable_nodes.add(image)
+
+        return self.signable_nodes
+
+    def change_signature_algo_to_ecdsa(self):
+        for image in self.signable_nodes:
+            self.__fdt_set(f'{image}/signature', algo='sha256,ecdsa256')
+
+    def sign(self, mkimage, key_file):
+        util.run_and_log(self.cons, [mkimage, '-F', self.fit, f'-k{key_file}'])
+
+    def check_signatures(self, key):
+        for image in self.signable_nodes:
+            raw_sig = self.__fdt_get_binary(f'{image}/signature', 'value')
+            raw_bin = self.__fdt_get_binary(image, 'data')
+
+            sha = SHA256.new(raw_bin)
+            verifier = DSS.new(key, 'fips-186-3')
+            verifier.verify(sha, bytes(raw_sig))
+
+
+ at pytest.mark.buildconfigspec('fit_signature')
+ at pytest.mark.requiredtool('dtc')
+ at pytest.mark.requiredtool('fdtget')
+ at pytest.mark.requiredtool('fdtput')
+def test_fit_ecdsa(u_boot_console):
+    """ Test that signatures generated by mkimage are legible. """
+    def generate_ecdsa_key():
+        return ECC.generate(curve='prime256v1')
+
+    def assemble_fit_image(dest_fit, its, destdir):
+        dtc_args = f'-I dts -O dtb -i {destdir}'
+        util.run_and_log(cons, [mkimage, '-D', dtc_args, '-f', its, dest_fit])
+
+    def dtc(dts):
+        dtb = dts.replace('.dts', '.dtb')
+        util.run_and_log(cons, f'dtc {datadir}/{dts} -O dtb -o {tempdir}/{dtb}')
+
+    cons = u_boot_console
+    mkimage = cons.config.build_dir + '/tools/mkimage'
+    datadir = cons.config.source_dir + '/test/py/tests/vboot/'
+    tempdir = cons.config.result_dir
+    key_file = f'{tempdir}/ecdsa-test-key.pem'
+    fit_file = f'{tempdir}/test.fit'
+    dtc('sandbox-kernel.dts')
+
+    key = generate_ecdsa_key()
+
+    # Create a fake kernel image -- zeroes will do just fine
+    with open(f'{tempdir}/test-kernel.bin', 'w') as fd:
+        fd.write(500 * chr(0))
+
+    # invocations of mkimage expect to read the key from disk
+    with open(key_file, 'w') as f:
+        f.write(key.export_key(format='PEM'))
+
+    assemble_fit_image(fit_file, f'{datadir}/sign-images-sha256.its', tempdir)
+
+    fit = SignableFitImage(cons, fit_file)
+    nodes = fit.find_signable_image_nodes()
+    if len(nodes) == 0:
+        raise ValueError('FIT image has no "/image" nodes with "signature"')
+
+    fit.change_signature_algo_to_ecdsa()
+    fit.sign(mkimage, key_file)
+    fit.check_signatures(key)
Signature · 1 line
2.26.2
#12 lore raw

PATCH v6 6/11 test/py: ecdsa: Add test for mkimage ECDSA signing

Quoted 7 lines · Alexandru Gagniuc

Add a test to make sure that the ECDSA signatures generated by mkimage can be verified successfully. pyCryptodomex was chosen as the crypto library because it integrates much better with python code. Using openssl would have been unnecessarily painful.

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210416/a4f965ac/attachment.sig>
#13 lore raw

PATCH v6 7/11 doc: signature.txt: Document the keydir and keyfile arguments

In reply to Alexandru Gagniuc

After lots of debating, this documents how we'd like mkimage to treat 'keydir' and 'keyfile' arguments. The rest is in the docs.

---
 doc/uImage.FIT/signature.txt | 13 +++++++++++++
 1 file changed, 13 insertions(+)
doc/uImage.FIT/signature.txt +13 -0
index 0139295d33..d9a9121190 100644
@@ -472,6 +472,19 @@ Test Verified Boot Run: signed config with bad hash: OK
 Test passed
 
 
+Software signing: keydir vs keyfile
+-----------------------------------
+
+In the simplest case, signing is done by giving mkimage the 'keyfile'. This is
+the path to a file containing the signing key.
+
+The alternative is to pass the 'keydir' argument. In this case the filename of
+the key is derived from the 'keydir' and the "key-name-hint" property in the
+FIT. In this case the "key-name-hint" property is mandatory, and the key must
+exist in "<keydir>/<key-name-hint>.<ext>" Here the extension "ext" is
+specific to the signing algorithm.
+
+
 Hardware Signing with PKCS#11 or with HSM
 -----------------------------------------
 
Signature · 1 line
2.26.2
#14 lore raw

PATCH v6 7/11 doc: signature.txt: Document the keydir and keyfile arguments

Quoted 5 lines · Alexandru Gagniuc

After lots of debating, this documents how we'd like mkimage to treat 'keydir' and 'keyfile' arguments. The rest is in the docs.

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210416/1cf2db16/attachment.sig>
#15 lore raw

PATCH v6 8/11 mkimage: Add a 'keyfile' argument for image signing

In reply to Alexandru Gagniuc

It's not always desirable to use 'keydir' and some ad-hoc heuristics to get the filename of the signing key. More often, just passing the filename is the simpler, easier, and logical thing to do.

Since mkimage doesn't use long options, we're slowly running out of letters. I've chosen '-G' because it was available.

---
 include/image.h    | 16 +++++++++----
 tools/fit_image.c  |  3 ++-
 tools/image-host.c | 58 +++++++++++++++++++++++++---------------------
 tools/imagetool.h  |  1 +
 tools/mkimage.c    |  6 ++++-
 5 files changed, 52 insertions(+), 32 deletions(-)
include/image.h +12 -4
index 37feb5d56f..5bb7922a66 100644
@@ -1131,9 +1131,10 @@ int fit_cipher_data(const char *keydir, void *keydest, void *fit,
  *     0, on success
  *     libfdt error code, on failure
  */
-int fit_add_verification_data(const char *keydir, void *keydest, void *fit,
-			      const char *comment, int require_keys,
-			      const char *engine_id, const char *cmdname);
+int fit_add_verification_data(const char *keydir, const char *keyfile,
+			      void *keydest, void *fit, const char *comment,
+			      int require_keys, const char *engine_id,
+			      const char *cmdname);
 
 int fit_image_verify_with_data(const void *fit, int image_noffset,
 			       const void *data, size_t size);
@@ -1251,10 +1252,17 @@ void image_set_host_blob(void *host_blob);
 #endif
 #endif /* IMAGE_ENABLE_FIT */
 
-/* Information passed to the signing routines */
+/*
+ * Information passed to the signing routines
+ *
+ * Either 'keydir',  'keyname', or 'keyfile' can be NULL. However, either
+ * 'keyfile', or both 'keydir' and 'keyname' should have valid values. If
+ * neither are valid, some operations might fail with EINVAL.
+ */
 struct image_sign_info {
 	const char *keydir;		/* Directory conaining keys */
 	const char *keyname;		/* Name of key to use */
+	const char *keyfile;		/* Filename of private or public key */
 	void *fit;			/* Pointer to FIT blob */
 	int node_offset;		/* Offset of signature node */
 	const char *name;		/* Algorithm name */
tools/fit_image.c +2 -1
index d440d143c6..ae30f80783 100644
@@ -68,7 +68,8 @@ static int fit_add_file_data(struct image_tool_params *params, size_t size_inc,
 	}
 
 	if (!ret) {
-		ret = fit_add_verification_data(params->keydir, dest_blob, ptr,
+		ret = fit_add_verification_data(params->keydir,
+						params->keyfile, dest_blob, ptr,
 						params->comment,
 						params->require_keys,
 						params->engine_id,
tools/image-host.c +32 -26

144 lines not on this page · raw message

tools/imagetool.h +1 -0
index 8726792c8c..8400e87e62 100644
@@ -67,6 +67,7 @@ struct image_tool_params {
 	const char *outfile;	/* Output filename */
 	const char *keydir;	/* Directory holding private keys */
 	const char *keydest;	/* Destination .dtb for public key */
+	const char *keyfile;	/* Filename of private or public key */
 	const char *comment;	/* Comment to add to signature node */
 	int require_keys;	/* 1 to mark signing keys as 'required' */
 	int file_size;		/* Total size of output file */
tools/mkimage.c +5 -1
index 68d5206cb4..cc7b242faf 100644
@@ -108,6 +108,7 @@ static void usage(const char *msg)
 		"Signing / verified boot options: [-k keydir] [-K dtb] [ -c <comment>] [-p addr] [-r] [-N engine]\n"
 		"          -k => set directory containing private keys\n"
 		"          -K => write public keys to this .dtb file\n"
+		"          -G => use this signing key (in lieu of -k)\n"
 		"          -c => add comment in signature node\n"
 		"          -F => re-sign existing FIT image\n"
 		"          -p => place external data at a static position\n"
@@ -151,7 +152,7 @@ static void process_args(int argc, char **argv)
 	int opt;
 
 	while ((opt = getopt(argc, argv,
-		   "a:A:b:B:c:C:d:D:e:Ef:Fk:i:K:ln:N:p:O:rR:qstT:vVx")) != -1) {
+		   "a:A:b:B:c:C:d:D:e:Ef:FG:k:i:K:ln:N:p:O:rR:qstT:vVx")) != -1) {
 		switch (opt) {
 		case 'a':
 			params.addr = strtoull(optarg, &ptr, 16);
@@ -226,6 +227,9 @@ static void process_args(int argc, char **argv)
 			params.type = IH_TYPE_FLATDT;
 			params.fflag = 1;
 			break;
+		case 'G':
+			params.keyfile = optarg;
+			break;
 		case 'i':
 			params.fit_ramdisk = optarg;
 			break;
Signature · 1 line
2.26.2
#16 lore raw

PATCH v6 8/11 mkimage: Add a 'keyfile' argument for image signing

Quoted 9 lines · Alexandru Gagniuc

It's not always desirable to use 'keydir' and some ad-hoc heuristics to get the filename of the signing key. More often, just passing the filename is the simpler, easier, and logical thing to do.

Since mkimage doesn't use long options, we're slowly running out of letters. I've chosen '-G' because it was available.

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210416/3ffc6fc3/attachment.sig>
#17 lore raw

PATCH v6 9/11 lib/rsa: Use the 'keyfile' argument from mkimage

In reply to Alexandru Gagniuc

Keys can be derived from keydir, and the "key-name-hint" property of the FIT. They can also be specified ad-literam via 'keyfile'. Update the RSA signing path to use the appropriate one.

---
 lib/rsa/rsa-sign.c | 34 ++++++++++++++++++++++++++--------
 1 file changed, 26 insertions(+), 8 deletions(-)
lib/rsa/rsa-sign.c +26 -8
index 557c690a6d..65c6d4490c 100644
@@ -210,14 +210,20 @@ static int rsa_get_pub_key(const char *keydir, const char *name,
  * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
  */
 static int rsa_pem_get_priv_key(const char *keydir, const char *name,
-				RSA **rsap)
+				const char *keyfile, RSA **rsap)
 {
 	char path[1024];
 	RSA *rsa;
 	FILE *f;
 
 	*rsap = NULL;
-	snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
+	if (keydir && name)
+		snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
+	else if (keyfile)
+		snprintf(path, sizeof(path), "%s", keyfile);
+	else
+		return -EINVAL;
+
 	f = fopen(path, "r");
 	if (!f) {
 		fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
@@ -247,6 +253,7 @@ static int rsa_pem_get_priv_key(const char *keydir, const char *name,
  * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
  */
 static int rsa_engine_get_priv_key(const char *keydir, const char *name,
+				   const char *keyfile,
 				   ENGINE *engine, RSA **rsap)
 {
 	const char *engine_id;
@@ -260,6 +267,10 @@ static int rsa_engine_get_priv_key(const char *keydir, const char *name,
 	engine_id = ENGINE_get_id(engine);
 
 	if (engine_id && !strcmp(engine_id, "pkcs11")) {
+		if (!keydir && !name) {
+			fprintf(stderr, "Please use 'keydir' with PKCS11\n");
+			return -EINVAL;
+		}
 		if (keydir)
 			if (strstr(keydir, "object="))
 				snprintf(key_id, sizeof(key_id),
@@ -274,14 +285,19 @@ static int rsa_engine_get_priv_key(const char *keydir, const char *name,
 				 "pkcs11:object=%s;type=private",
 				 name);
 	} else if (engine_id) {
-		if (keydir)
+		if (keydir && name)
 			snprintf(key_id, sizeof(key_id),
 				 "%s%s",
 				 keydir, name);
-		else
+		else if (keydir)
 			snprintf(key_id, sizeof(key_id),
 				 "%s",
 				 name);
+		else if (keyfile)
+			snprintf(key_id, sizeof(key_id), "%s", keyfile);
+		else
+			return -EINVAL;
+
 	} else {
 		fprintf(stderr, "Engine not supported\n");
 		return -ENOTSUP;
@@ -319,11 +335,12 @@ err_rsa:
  * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL)
  */
 static int rsa_get_priv_key(const char *keydir, const char *name,
-			    ENGINE *engine, RSA **rsap)
+			    const char *keyfile, ENGINE *engine, RSA **rsap)
 {
 	if (engine)
-		return rsa_engine_get_priv_key(keydir, name, engine, rsap);
-	return rsa_pem_get_priv_key(keydir, name, rsap);
+		return rsa_engine_get_priv_key(keydir, name, keyfile, engine,
+					       rsap);
+	return rsa_pem_get_priv_key(keydir, name, keyfile, rsap);
 }
 
 static int rsa_init(void)
@@ -534,7 +551,8 @@ int rsa_sign(struct image_sign_info *info,
 			goto err_engine;
 	}
 
-	ret = rsa_get_priv_key(info->keydir, info->keyname, e, &rsa);
+	ret = rsa_get_priv_key(info->keydir, info->keyname, info->keyfile,
+			       e, &rsa);
 	if (ret)
 		goto err_priv;
 	ret = rsa_sign_with_key(rsa, info->padding, info->checksum, region,
Signature · 1 line
2.26.2
#18 lore raw

PATCH v6 9/11 lib/rsa: Use the 'keyfile' argument from mkimage

Quoted 6 lines · Alexandru Gagniuc

Keys can be derived from keydir, and the "key-name-hint" property of the FIT. They can also be specified ad-literam via 'keyfile'. Update the RSA signing path to use the appropriate one.

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210416/82c4cb1f/attachment.sig>
#19 lore raw

PATCH v6 10/11 lib/ecdsa: Use the 'keydir' argument from mkimage if appropriate

In reply to Alexandru Gagniuc

Keys can be derived from keydir, and the "key-name-hint" property of the FIT. They can also be specified ad-literam via 'keyfile'. Update the ECDSA signing path to use the appropriate one.

---
 lib/ecdsa/ecdsa-libcrypto.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
lib/ecdsa/ecdsa-libcrypto.c +13 -1
index 322880963f..1757a14562 100644
@@ -140,8 +140,20 @@ static int read_key(struct signer *ctx, const char *key_name)
 /* Prepare a 'signer' context that's ready to sign and verify. */
 static int prepare_ctx(struct signer *ctx, const struct image_sign_info *info)
 {
-	const char *kname = info->keydir;
 	int key_len_bytes, ret;
+	char kname[1024];
+
+	memset(ctx, 0, sizeof(*ctx));
+
+	if (info->keyfile) {
+		snprintf(kname,  sizeof(kname), "%s", info->keyfile);
+	} else if (info->keydir && info->keyname) {
+		snprintf(kname, sizeof(kname), "%s/%s.pem", info->keydir,
+			 info->keyname);
+	} else {
+		fprintf(stderr, "keyfile, keyname, or key-name-hint missing\n");
+		return -EINVAL;
+	}
 
 	ret = alloc_ctx(ctx, info);
 	if (ret)
Signature · 1 line
2.26.2
#20 lore raw

PATCH v6 10/11 lib/ecdsa: Use the 'keydir' argument from mkimage if appropriate

Quoted 6 lines · Alexandru Gagniuc

Keys can be derived from keydir, and the "key-name-hint" property of the FIT. They can also be specified ad-literam via 'keyfile'. Update the ECDSA signing path to use the appropriate one.

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210416/92f05818/attachment.sig>
#21 lore raw

PATCH v6 11/11 test/py: ecdsa: Use mkimage keyfile instead of keydir argument

In reply to Alexandru Gagniuc

Originally, the ECDSA code path used 'keydir' as the key filename. mkimage has since been updated to include a new 'keyfile' argument. Use the new argument for passing in the key.

---
 test/py/tests/test_fit_ecdsa.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
test/py/tests/test_fit_ecdsa.py +1 -1
index f597570281..87b6081222 100644
@@ -52,7 +52,7 @@ class SignableFitImage(object):
             self.__fdt_set(f'{image}/signature', algo='sha256,ecdsa256')
 
     def sign(self, mkimage, key_file):
-        util.run_and_log(self.cons, [mkimage, '-F', self.fit, f'-k{key_file}'])
+        util.run_and_log(self.cons, [mkimage, '-F', self.fit, f'-G{key_file}'])
 
     def check_signatures(self, key):
         for image in self.signable_nodes:
Signature · 1 line
2.26.2
#22 lore raw

PATCH v6 11/11 test/py: ecdsa: Use mkimage keyfile instead of keydir argument

Quoted 9 lines · Alexandru Gagniuc

Originally, the ECDSA code path used 'keydir' as the key filename. mkimage has since been updated to include a new 'keyfile' argument. Use the new argument for passing in the key.

---
 test/py/tests/test_fit_ecdsa.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
#23 lore raw

PATCH v6 11/11 test/py: ecdsa: Use mkimage keyfile instead of keydir argument

In reply to Alexandru Gagniuc
Quoted 6 lines · Alexandru Gagniuc

Originally, the ECDSA code path used 'keydir' as the key filename. mkimage has since been updated to include a new 'keyfile' argument. Use the new argument for passing in the key.

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210416/2bfce8d9/attachment.sig>