Skip to contentSkip to conversation

Add support for ECDSA image signing (with test)

PATCH Superseded Alexandru Gagniuc 2 participants 14 messages Jan 7, 2021 – Jan 14, 2021

Subsystems (2)

v3 of 6 Superseded Latest is v6 →

lore
Share & tools
lore
#0 lore raw

v3 cover Add support for ECDSA image signing (with test)

## Purpose and intent

The ROM code on the STM32MP requires an ECDSA-signed FSBL. Maintaining verified boot through FIT images would require switching to an RSA key after SPL. This would be stupid, so this series is focused on enabling ECDSA signing. The use case that I am focused on is signing an existing FIT image:

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

I don't care about signing while assembling the FIT. The reason is that I want the machine that builds things to be separate from the machine that has access to the super-secret-key.pem. The purpose of this series is to lay the foundations for ECDSA FIT signature verification on STM32MP.

# Implementation

## Signing

I initially tried to model this after the RSA implementation (rsa-sign.c), but that didn't go well for a few reasons:
(a) The openssl/libcrypto API is a pain in the ass
(b) The RSA path doesn't have a way to pass a specific key file.

On point (a), I don't want to spend too much time battling a C API for crypto. I find pyCryptodomex to be vastly superior, but that is not available for mkimage. I am thus focusing on the simple case of key in, signature out.

On point (b), the RSA path takes the FDT property 'key-name-hint' to decide which key file to read from disk. In the context of "which fdt node describes my signing key", this makes sense. On the other hand, 'key-name-hint' is also used as the basename of where the key is on the filesystem. This leads to some funny search paths, such as

	"some/dir/(null).key"

So I am using the -K option to mkimage as the _full_ path to the key file. It doesn't have to be named .key, it doesn't have to be named .crt, and it doesn't have to exist in a particular directory (as is the case for the RSA path). Take that as is for here -- we can discuss the merits of this in a separate thread.

## Verification

This will be implemented in a future patch series. The proof of concept is on github:
https://github.com/mrnuke/u-boot/commits/patch-stm32-ecdsa

# Testing

test/py/tests/test_fit_ecdsa.py is implementing a test for mkimage. It lets mkimage run wild, tehn verifies the signature against pyCryptodomex -- see earlier point on for I didn't use openssl.

# Things not yet resolved:
- is mkimage '-k' supposed to be a directory or file path
I'm hoping I can postpone answering this question pending further discussion.

# 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 (6):
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

 common/image-fit-sig.c                        |   2 +-
 common/image-sig.c                            |  13 +-
 doc/uImage.FIT/signature.txt                  |   7 +-
 include/image.h                               |   5 +-
 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                   | 306 ++++++++++++++++++
 lib/fdt-libcrypto.c                           |  72 +++++
 lib/{rsa/rsa-checksum.c => hash-checksum.c}   |   3 +-
 lib/rsa/Makefile                              |   2 +-
 lib/rsa/rsa-sign.c                            |  65 +---
 test/py/requirements.txt                      |   1 +
 test/py/tests/test_fit_ecdsa.py               | 111 +++++++
 tools/Makefile                                |   7 +-
 18 files changed, 645 insertions(+), 75 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 v3 1/6 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/crypto, 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 5401d9411b..7fcbb47235 100644
@@ -15,7 +15,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 f3c209ae8b..21dafe6b91 100644
@@ -16,7 +16,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 41473dbb9c..a55b11b3ae 100644
@@ -1258,7 +1258,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 851a80ef3b..cf64188ba5 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 320ba49f79..3c411f651f 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 253a6b9706..b1595ad814 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/, \
@@ -105,6 +105,7 @@ dumpimage-mkimage-objs := aisimage.o \
 			$(ROCKCHIP_OBS) \
 			socfpgaimage.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 v3 1/6 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/crypto, and rename it to hash-checksum.c, to give it a more "generic" feel.

Quoted 15 lines
---
 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%)
#3 lore raw

PATCH v3 2/6 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                 |  1 +
 4 files changed, 101 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 +1 -0
index b1595ad814..af7698fd01 100644
@@ -106,6 +106,7 @@ dumpimage-mkimage-objs := aisimage.o \
 			socfpgaimage.o \
 			lib/crc16.o \
 			lib/hash-checksum.o \
+			lib/fdt-libcrypto.o \
 			lib/sha1.o \
 			lib/sha256.o \
 			lib/sha512.o \
Signature · 1 line
2.26.2
#4 lore raw

PATCH v3 2/6 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.

Quoted 8 lines
---
 include/u-boot/fdt-libcrypto.h | 27 +++++++++++++
 lib/fdt-libcrypto.c            | 72 ++++++++++++++++++++++++++++++++++
 lib/rsa/rsa-sign.c             | 65 +-----------------------------
 tools/Makefile                 |  1 +
 4 files changed, 101 insertions(+), 64 deletions(-)
 create mode 100644 include/u-boot/fdt-libcrypto.h
 create mode 100644 lib/fdt-libcrypto.c
#5 lore raw

PATCH v3 3/6 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 21dafe6b91..4b7d01f6c2 100644
@@ -15,6 +15,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>
 
@@ -82,8 +83,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 a55b11b3ae..6628173dca 100644
@@ -1199,16 +1199,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 af7698fd01..a4f7b7e80c 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)
 
@@ -119,6 +121,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 v3 3/6 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.

Quoted 9 lines
---
 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

But you should check the return value of do_sign(). Why do you call ecdsa_check_signature() afterwards? Can you not trust the library?

Regards,
Simon

author
#7 lore raw

PATCH v3 3/6 lib: Add support for ECDSA image signing

Quoted 21 lines · Simon Glass
Quoted 17 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.

---
  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(-)
Quoted 2 lines

create mode 100644 include/u-boot/ecdsa.h
create mode 100644 lib/ecdsa/ecdsa-libcrypto.c

Quoted 4 lines

But you should check the return value of do_sign(). Why do you call ecdsa_check_signature() afterwards? Can you not trust the library?

You are right that it's a redundant step. It's an automatic test for the ecdsa_sig_encode_raw()/ecdsa_sig_from_raw() pair.

Alex

Quoted 3 lines

Regards,
Simon

#8 lore raw

PATCH v3 4/6 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
#9 lore raw

PATCH v3 4/6 doc: signature.txt: Document devicetree format for ECDSA keys

Quoted 6 lines · Alexandru Gagniuc
---
 doc/uImage.FIT/signature.txt | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

I think you left off my review tag so I am adding it again here. You can try 'patman status' to collect review tags from patchwork.

#10 lore raw

PATCH v3 5/6 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 cf251186f4..5a25a9d5d5 100644
@@ -10,6 +10,7 @@ packaging==19.2
 pbr==5.4.3
 pluggy==0.13.0
 py==1.8.0
+pycryptodomex==3.9.8
 pyparsing==2.4.2
 pytest==5.2.1
 python-mimeparse==1.6.0
Signature · 1 line
2.26.2
#11 lore raw

PATCH v3 5/6 test/py: Add pycryptodomex to list of required pakages

Quoted 9 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

---
 test/py/requirements.txt | 1 +
 1 file changed, 1 insertion(+)
#12 lore raw

PATCH v3 6/6 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..6cadb0cbb5
@@ -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))
+
+    # invokations 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
#13 lore raw

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

Hi Alexandru,

Quoted 6 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.

Quoted 6 lines
---
 test/py/tests/test_fit_ecdsa.py | 111 ++++++++++++++++++++++++++++++++
 1 file changed, 111 insertions(+)
 create mode 100644 test/py/tests/test_fit_ecdsa.py

This is fine for now, but I think it will need to be integrated with the existing test somehow once you have the runtime side working.

Regards,
Simon