Skip to contentSkip to conversation

efi_loader: add secure boot support

PATCH Superseded AKASHI Takahiro 4 participants 36 messages Apr 14, 2020 – Apr 20, 2020

lore
Share & tools
lore
#0 lore raw

v7 cover efi_loader: add secure boot support

One of major missing features in current UEFI implementation is "secure boot." The ultimate goal of my attempt is to implement image authentication based on signature and provide UEFI secure boot support which would be fully compliant with UEFI specification, section 32[1].
(The code was originally developed by Patrick Wildt.)

This patch set requires one prerequisite[2]. For complete workable cod, see my repository[3].

My "non-volatile" support[4], which is under discussion, is not mandatory and so not included here, but this inevitably implies that, for example, signature database variables, like db and dbx, won't be persistent unless you explicitly run "env save" command.
Anyhow, Linaro is also working on implementing real "secure storage" solution based on TF-A and OP-TEE.

Supported features:
* image authentication based on db and dbx
* supported signature types are EFI_CERT_SHA256_GUID (SHA256 digest for unsigned images) EFI_CERT_X509_GUID (x509 certificate for signed images)
* SecureBoot/SignatureSupport variables
* SetupMode and user mode
* variable authentication based on PK and KEK EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
* basic pytest test cases

Unsupported features: (marked as TODO in most cases in the source code,
and won't be included in this series)
* hash algorithms other than SHA256
* dbt: timestamp(RFC6131)-based certificate revocation
* dbr: OS recovery
* xxxDefault: default values for signature stores
* transition to AuditMode and DeployedMode
* recording rejected images in EFI_IMAGE_EXECUTION_INFO_TABLE
* verification "policy", in particular, check against signature's owner
* private authenticated variables
* variable authentication with EFI_VARIABLE_ENHANCED_AUTHENTICATED_ACCESS
* real secure storage support, including hardware-specific PK (Platform Key) installation

TODO's other than "Unsupported features": (won't be included in this series)
* fail recovery, in particular, in modifying authenticated variables
* support read-only attributes of well-defined global variables in particular, "SignatureSupport"
* Extensive test suite (or more test cases) to confirm compatibility with EDK2
=> I requested EDK SCT community to add tests[5].

Test:
* My pytest, included in this patch set, passed.
* efi_selftest passed. (At least no regression.)
* Travis CI tests have passed.

Known issues:
* efitools is used in pytest, and its version must be v1.5.2 or later. (Solution: You can define EFITOOLS_PATH in defs.py for your own efitools.)

Hints about how to use:
(Please see other documents, or my pytest scripts, for details.)
* You can create your own certificates with openssl.
* You can sign your application with sbsign (on Ubuntu).
* You can create raw data for signature database with efitools, and install/manage authenticated variables with "env -set -e" command or efitools' "UpdateVars.efi" application.

[1] https://uefi.org/sites/default/files/resources/UEFI_Spec_2_8_final.pdf
[2] https://lists.denx.de/pipermail/u-boot/2020-January/398057.html
(extend rsa_verify() for UEFI secure boot)
[3] http://git.linaro.org/people/takahiro.akashi/u-boot.git/ efi/secboot
[4] https://lists.denx.de/pipermail/u-boot/2019-September/382835.html
(non-volatile variables support)
[5] https://bugzilla.tianocore.org/show_bug.cgi?id=2230
[6] https://lists.denx.de/pipermail/u-boot/2020-February/399446.html

Changes in v7 (Apr 14, 2020)
* fix a usage of qsort() in efi_image_parse() (patch#7)
* merge my document patch[6] (patch#17)

Changes in v6 (Feb 26, 2020)
* fix 'make htmldocs' warnings (patch#4,#7)
* refactor efi_load_pe() to avoid test_efi_fit.py error (patch#7)
* fix pytest warnings (patch#14)

Changes in v5 (Jan 28, 2020)
* rebased to pre-v2020.04-rc1 (fixed some merge conflicts)
* remove already-merged commits (v4's patch#1)
* fix a compile error caused by gcc 9.x (patch#4)
* return SECURITY_VIOLATION instead of ACCESS_DENIED if authentication fails (patch#7)
* use qsort() for section sorting (patch#7)
* add "efidebug test" sub-command (patch#11)
* add efi_start_image(SECURITY_VIOLATION) test (patch#14)

Changes in v4 (Dec 18, 2019)
* adjust EFI_SECURE_BOOT dependencies due to a change of RSA extension patch v5 (patch#2)
* change "imply" to "select" against kconfig dependencies (patch#2)
* otherwise, no functional changes

Changes in v3 (Dec 9, 2019)
* allow for arbitrary number of regions in efi_image_region_add() (patch#3, #5 and #8)
* remove a redundant check in a while loop at efi_sigstore_free() (patch#4)

Changes in v2 (Nov 26, 2019)
* rebased to v2020.01-rc3
* rename IMAGE_DIRECTORY_ENTRY_CERTTABLE to IMAGE_DIRECTORY_ENTRY_SECURITY (patch#1,#9)
* add comments (patch#1)
* drop v1's patch#2 as it is no longer necessary
* drop v1's patch#3 as other "SECURE_BOOT" architectures have renamed this option and no longer use it
* add structure descriptions (patch#3)
* rework hash calculation code in efi_signature_verify() and remove an odd constant, WinIndrectSha256 (patch#3)
* move travis.yml changes to a separate patch (patch#12, #16)
* yield_fixture() -> fixture() (patch#12)
* call console.restart_uboot() at every test case (13,#14)
* add patch#15; enable UEFI-related configurations by default on sandbox
* add patch#16; modify Travis CI environment to run UEFI secure boot test

Changes in v1 (Nov 13, 2019)
* rebased to v2020.01-rc
* remove already-merged patches
* re-work the patch set for easier reviews, including
- move a config definition patch forward (patch#4)
- refactor/rename verification functions (patch#5/#10)
- split signature database parser as a separate patch (patch#6)
- split secure state transition code as a separate patch (patch#8)
- move most part of init_secure_boot() into init_variables() (patch#8)
- split test environment setup from test patches (patch#14)
* add function descriptions (patch#5-#11)
* make sure the section list is sorted in ascending order in hash calculation of PE image (patch#10)
* add a new "-at" (authenticated access) option to "env -e" (patch#13)
* list required host packages, in particular udisks2, in pytest (patch#14)
* modify conftest.py to run under python3 (patch#14)
* use a partition on a disk instead of a whole disk without partition table (patch#14)
* reduce dependency on efitools, yet relying on its host tools (patch#14)
* modify pytests to catch up wth latest changes of "env -e" syntax (patch#15,#16)

RFC (Sept 18, 2019)

AKASHI Takahiro (17):
efi_loader: add CONFIG_EFI_SECURE_BOOT config option
efi_loader: add signature verification functions
efi_loader: add signature database parser
efi_loader: variable: support variable authentication
efi_loader: variable: add secure boot state transition
efi_loader: variable: add VendorKeys variable
efi_loader: image_loader: support image authentication
efi_loader: set up secure boot
cmd: env: use appropriate guid for authenticated UEFI variable
cmd: env: add "-at" option to "env set -e" command
cmd: efidebug: add "test bootmgr" sub-command efi_loader, pytest: set up secure boot environment efi_loader, pytest: add UEFI secure boot tests (authenticated
variables)
efi_loader, pytest: add UEFI secure boot tests (image)
sandbox: add extra configurations for UEFI and related tests
travis: add packages for UEFI secure boot test
efi_loader: add some description about UEFI secure boot

 .travis.yml                                   |  11 +-
 cmd/efidebug.c                                |  78 +-
 cmd/nvedit.c                                  |   5 +-
 cmd/nvedit_efi.c                              |  23 +-
 configs/sandbox64_defconfig                   |   3 +
 configs/sandbox_defconfig                     |   3 +
 doc/uefi/uefi.rst                             |  77 ++
 include/efi_api.h                             |  87 ++
 include/efi_loader.h                          |  91 +-
 lib/efi_loader/Kconfig                        |  18 +
 lib/efi_loader/Makefile                       |   1 +
 lib/efi_loader/efi_boottime.c                 |  10 +-
 lib/efi_loader/efi_image_loader.c             | 462 ++++++++-
 lib/efi_loader/efi_setup.c                    |  38 +
 lib/efi_loader/efi_signature.c                | 809 +++++++++++++++
 lib/efi_loader/efi_variable.c                 | 952 ++++++++++++++++--
 test/py/README.md                             |   8 +
 test/py/tests/test_efi_secboot/conftest.py    | 151 +++
 test/py/tests/test_efi_secboot/defs.py        |  21 +
 .../py/tests/test_efi_secboot/test_authvar.py | 282 ++++++
 test/py/tests/test_efi_secboot/test_signed.py | 117 +++
 .../tests/test_efi_secboot/test_unsigned.py   | 121 +++
 22 files changed, 3237 insertions(+), 131 deletions(-)
 create mode 100644 lib/efi_loader/efi_signature.c
 create mode 100644 test/py/tests/test_efi_secboot/conftest.py
 create mode 100644 test/py/tests/test_efi_secboot/defs.py
 create mode 100644 test/py/tests/test_efi_secboot/test_authvar.py
 create mode 100644 test/py/tests/test_efi_secboot/test_signed.py
 create mode 100644 test/py/tests/test_efi_secboot/test_unsigned.py
Signature · 1 line
2.25.2
#1 lore raw

PATCH v7 1/17 efi_loader: add CONFIG_EFI_SECURE_BOOT config option

Under this configuration, UEFI secure boot support will be added in later patches.

---
 lib/efi_loader/Kconfig | 18 ++++++++++++++++++
 1 file changed, 18 insertions(+)
lib/efi_loader/Kconfig +18 -0
index 9890144d4161..71a0d003c914 100644
@@ -145,4 +145,22 @@ config EFI_INITRD_FILESPEC
 	help
 	  Full path of the initramfs file, e.g. mmc 0:2 initramfs.cpio.gz.
 
+config EFI_SECURE_BOOT
+	bool "Enable EFI secure boot support"
+	depends on EFI_LOADER
+	select SHA256
+	select RSA
+	select RSA_VERIFY_WITH_PKEY
+	select IMAGE_SIGN_INFO
+	select ASYMMETRIC_KEY_TYPE
+	select ASYMMETRIC_PUBLIC_KEY_SUBTYPE
+	select X509_CERTIFICATE_PARSER
+	select PKCS7_MESSAGE_PARSER
+	default n
+	help
+	  Select this option to enable EFI secure boot support.
+	  Once SecureBoot mode is enforced, any EFI binary can run only if
+	  it is signed with a trusted key. To do that, you need to install,
+	  at least, PK, KEK and db.
+
 endif
Signature · 1 line
2.25.2
#2 lore raw

PATCH v7 2/17 efi_loader: add signature verification functions

In reply to AKASHI Takahiro

In this commit, implemented are a couple of helper functions which will be used to materialize variable authentication as well as image authentication in later patches.

---
 include/efi_api.h              |  87 +++++
 include/efi_loader.h           |  72 ++++
 lib/efi_loader/Makefile        |   1 +
 lib/efi_loader/efi_signature.c | 583 +++++++++++++++++++++++++++++++++
 4 files changed, 743 insertions(+)
 create mode 100644 lib/efi_loader/efi_signature.c
include/efi_api.h +87 -0
index 1c40ffc4f56c..77d6bf2660b9 100644
@@ -18,6 +18,7 @@
 
 #include <efi.h>
 #include <charset.h>
+#include <pe.h>
 
 #ifdef CONFIG_EFI_LOADER
 #include <asm/setjmp.h>
@@ -329,6 +330,10 @@ struct efi_runtime_services {
 	EFI_GUID(0x8be4df61, 0x93ca, 0x11d2, 0xaa, 0x0d, \
 		 0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c)
 
+#define EFI_IMAGE_SECURITY_DATABASE_GUID \
+	EFI_GUID(0xd719b2cb, 0x3d3a, 0x4596, 0xa3, 0xbc, \
+		 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f)
+
 #define EFI_FDT_GUID \
 	EFI_GUID(0xb1b621d5, 0xf19c, 0x41a5, \
 		 0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0)
@@ -1682,4 +1687,86 @@ struct efi_load_file_protocol {
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MIN 0x00001000
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MAX 0x00004000
 
+/* Certificate types in signature database */
+#define EFI_CERT_SHA256_GUID \
+	EFI_GUID(0xc1c41626, 0x504c, 0x4092, 0xac, 0xa9, \
+		 0x41, 0xf9, 0x36, 0x93, 0x43, 0x28)
+#define EFI_CERT_RSA2048_GUID \
+	EFI_GUID(0x3c5766e8, 0x269c, 0x4e34, 0xaa, 0x14, \
+		 0xed, 0x77, 0x6e, 0x85, 0xb3, 0xb6)
+#define EFI_CERT_X509_GUID \
+	EFI_GUID(0xa5c059a1, 0x94e4, 0x4aa7, 0x87, 0xb5, \
+		 0xab, 0x15, 0x5c, 0x2b, 0xf0, 0x72)
+#define EFI_CERT_X509_SHA256_GUID \
+	EFI_GUID(0x3bd2a492, 0x96c0, 0x4079, 0xb4, 0x20, \
+		 0xfc, 0xf9, 0x8e, 0xf1, 0x03, 0xed)
+#define EFI_CERT_TYPE_PKCS7_GUID \
+	EFI_GUID(0x4aafd29d, 0x68df, 0x49ee, 0x8a, 0xa9, \
+		 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7)
+
+/**
+ * win_certificate_uefi_guid - A certificate that encapsulates
+ * a GUID-specific signature
+ *
+ * @hdr:	Windows certificate header
+ * @cert_type:	Certificate type
+ * @cert_data:	Certificate data
+ */
+struct win_certificate_uefi_guid {
+	WIN_CERTIFICATE	hdr;
+	efi_guid_t	cert_type;
+	u8		cert_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_variable_authentication_2 - A time-based authentication method
+ * descriptor
+ *
+ * This structure describes an authentication information for
+ * a variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
+ * and should be included as part of a variable's value.
+ * Only EFI_CERT_TYPE_PKCS7_GUID is accepted.
+ *
+ * @time_stamp:	Descriptor's time stamp
+ * @auth_info:	Authentication info
+ */
+struct efi_variable_authentication_2 {
+	struct efi_time			 time_stamp;
+	struct win_certificate_uefi_guid auth_info;
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_data - A format of signature
+ *
+ * This structure describes a single signature in signature database.
+ *
+ * @signature_owner:	Signature owner
+ * @signature_data:	Signature data
+ */
+struct efi_signature_data {
+	efi_guid_t	signature_owner;
+	u8		signature_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_list - A format of signature database
+ *
+ * This structure describes a list of signatures with the same type.
+ * An authenticated variable's value is a concatenation of one or more
+ * efi_signature_list's.
+ *
+ * @signature_type:		Signature type
+ * @signature_list_size:	Size of signature list
+ * @signature_header_size:	Size of signature header
+ * @signature_size:		Size of signature
+ */
+struct efi_signature_list {
+	efi_guid_t	signature_type;
+	u32		signature_list_size;
+	u32		signature_header_size;
+	u32		signature_size;
+/*	u8		signature_header[signature_header_size]; */
+/*	struct efi_signature_data signatures[...][signature_size]; */
+} __attribute__((__packed__));
+
 #endif
include/efi_loader.h +72 -0

90 lines not on this page · raw message

lib/efi_loader/Makefile +1 -0
index 9b3b70447336..eff3c25ec301 100644
@@ -44,3 +44,4 @@ obj-$(CONFIG_GENERATE_ACPI_TABLE) += efi_acpi.o
 obj-$(CONFIG_GENERATE_SMBIOS_TABLE) += efi_smbios.o
 obj-$(CONFIG_EFI_RNG_PROTOCOL) += efi_rng.o
 obj-$(CONFIG_EFI_LOAD_FILE2_INITRD) += efi_load_initrd.o
+obj-y += efi_signature.o
lib/efi_loader/efi_signature.c new file +583 -0

583 lines not on this page · raw message

Signature · 1 line
2.25.2
#3 lore raw

PATCH v7 2/17 efi_loader: add signature verification functions

Quoted 89 lines · AKASHI Takahiro

In this commit, implemented are a couple of helper functions which will be used to materialize variable authentication as well as image authentication in later patches.

---
 include/efi_api.h              |  87 +++++
 include/efi_loader.h           |  72 ++++
 lib/efi_loader/Makefile        |   1 +
 lib/efi_loader/efi_signature.c | 583 +++++++++++++++++++++++++++++++++
 4 files changed, 743 insertions(+)
 create mode 100644 lib/efi_loader/efi_signature.c
include/efi_api.h +54 -0
index 1c40ffc4f56c..77d6bf2660b9 100644
@@ -18,6 +18,7 @@
 
 #include <efi.h>
 #include <charset.h>
+#include <pe.h>
 
 #ifdef CONFIG_EFI_LOADER
 #include <asm/setjmp.h>
@@ -329,6 +330,10 @@ struct efi_runtime_services {
 	EFI_GUID(0x8be4df61, 0x93ca, 0x11d2, 0xaa, 0x0d, \
 		 0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c)
 
+#define EFI_IMAGE_SECURITY_DATABASE_GUID \
+	EFI_GUID(0xd719b2cb, 0x3d3a, 0x4596, 0xa3, 0xbc, \
+		 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f)
+
 #define EFI_FDT_GUID \
 	EFI_GUID(0xb1b621d5, 0xf19c, 0x41a5, \
 		 0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0)
@@ -1682,4 +1687,86 @@ struct efi_load_file_protocol {
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MIN 0x00001000
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MAX 0x00004000
 
+/* Certificate types in signature database */
+#define EFI_CERT_SHA256_GUID \
+	EFI_GUID(0xc1c41626, 0x504c, 0x4092, 0xac, 0xa9, \
+		 0x41, 0xf9, 0x36, 0x93, 0x43, 0x28)
+#define EFI_CERT_RSA2048_GUID \
+	EFI_GUID(0x3c5766e8, 0x269c, 0x4e34, 0xaa, 0x14, \
+		 0xed, 0x77, 0x6e, 0x85, 0xb3, 0xb6)
+#define EFI_CERT_X509_GUID \
+	EFI_GUID(0xa5c059a1, 0x94e4, 0x4aa7, 0x87, 0xb5, \
+		 0xab, 0x15, 0x5c, 0x2b, 0xf0, 0x72)
+#define EFI_CERT_X509_SHA256_GUID \
+	EFI_GUID(0x3bd2a492, 0x96c0, 0x4079, 0xb4, 0x20, \
+		 0xfc, 0xf9, 0x8e, 0xf1, 0x03, 0xed)
+#define EFI_CERT_TYPE_PKCS7_GUID \
+	EFI_GUID(0x4aafd29d, 0x68df, 0x49ee, 0x8a, 0xa9, \
+		 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7)
+
+/**
+ * win_certificate_uefi_guid - A certificate that encapsulates
+ * a GUID-specific signature
+ *
+ * @hdr:	Windows certificate header
+ * @cert_type:	Certificate type
+ * @cert_data:	Certificate data
+ */
+struct win_certificate_uefi_guid {
+	WIN_CERTIFICATE	hdr;
+	efi_guid_t	cert_type;
+	u8		cert_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_variable_authentication_2 - A time-based authentication method
+ * descriptor
+ *
+ * This structure describes an authentication information for
+ * a variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
+ * and should be included as part of a variable's value.
+ * Only EFI_CERT_TYPE_PKCS7_GUID is accepted.
+ *
+ * @time_stamp:	Descriptor's time stamp
+ * @auth_info:	Authentication info
+ */
+struct efi_variable_authentication_2 {
+	struct efi_time			 time_stamp;
+	struct win_certificate_uefi_guid auth_info;
+} __attribute__((__packed__));
+
+/**

include/efi_api.h struct efi_load_file_protocol { · line 1748

Quoted 10 lines
include/efi_api.h +10 -0
+ * efi_signature_data - A format of signature
+ *
+ * This structure describes a single signature in signature database.
+ *
+ * @signature_owner:	Signature owner
+ * @signature_data:	Signature data
+ */
+struct efi_signature_data {
+	efi_guid_t	signature_owner;
+	u8		signature_data[];

Please, use [0].

Quoted 139 lines
include/efi_api.h +23 -0
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_list - A format of signature database
+ *
+ * This structure describes a list of signatures with the same type.
+ * An authenticated variable's value is a concatenation of one or more
+ * efi_signature_list's.
+ *
+ * @signature_type:		Signature type
+ * @signature_list_size:	Size of signature list
+ * @signature_header_size:	Size of signature header
+ * @signature_size:		Size of signature
+ */
+struct efi_signature_list {
+	efi_guid_t	signature_type;
+	u32		signature_list_size;
+	u32		signature_header_size;
+	u32		signature_size;
+/*	u8		signature_header[signature_header_size]; */
+/*	struct efi_signature_data signatures[...][signature_size]; */
+} __attribute__((__packed__));
+
 #endif
include/efi_loader.h +72 -0
index 3f2792892f34..8cf85d2fb7e2 100644
@@ -26,6 +26,7 @@ static inline void *guidcpy(void *dst, const void *src)
 #if CONFIG_IS_ENABLED(EFI_LOADER)
 
 #include <linux/list.h>
+#include <linux/oid_registry.h>
 
 /* Maximum number of configuration tables */
 #define EFI_MAX_CONFIGURATION_TABLES 16
@@ -178,6 +179,11 @@ extern const efi_guid_t efi_guid_hii_config_routing_protocol;
 extern const efi_guid_t efi_guid_hii_config_access_protocol;
 extern const efi_guid_t efi_guid_hii_database_protocol;
 extern const efi_guid_t efi_guid_hii_string_protocol;
+/* GUIDs for authentication */
+extern const efi_guid_t efi_guid_image_security_database;
+extern const efi_guid_t efi_guid_sha256;
+extern const efi_guid_t efi_guid_cert_x509;
+extern const efi_guid_t efi_guid_cert_x509_sha256;
 
 /* GUID of RNG protocol */
 extern const efi_guid_t efi_guid_rng_protocol;
@@ -680,6 +686,72 @@ void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data);
 unsigned long efi_serialize_load_option(struct efi_load_option *lo, u8 **data);
 efi_status_t efi_bootmgr_load(efi_handle_t *handle);
 
+#ifdef CONFIG_EFI_SECURE_BOOT
+#include <image.h>
+
+/**
+ * efi_image_regions - A list of memory regions
+ *
+ * @max:	Maximum number of regions
+ * @num:	Number of regions
+ * @reg:	array of regions
+ */
+struct efi_image_regions {
+	int			max;
+	int			num;
+	struct image_region	reg[];
+};
+
+/**
+ * efi_sig_data - A decoded data of struct efi_signature_data
+ *
+ * This structure represents an internal form of signature in
+ * signature database. A listed list may represent a signature list.
+ *
+ * @next:	Pointer to next entry
+ * @onwer:	Signature owner
+ * @data:	Pointer to signature data
+ * @size:	Size of signature data
+ */
+struct efi_sig_data {
+	struct efi_sig_data *next;
+	efi_guid_t owner;
+	void *data;
+	size_t size;
+};
+
+/**
+ * efi_signature_store - A decoded data of signature database
+ *
+ * This structure represents an internal form of signature database.
+ *
+ * @next:		Pointer to next entry
+ * @sig_type:		Signature type
+ * @sig_data_list:	Pointer to signature list
+ */
+struct efi_signature_store {
+	struct efi_signature_store *next;
+	efi_guid_t sig_type;
+	struct efi_sig_data *sig_data_list;
+};
+
+struct x509_certificate;
+struct pkcs7_message;
+
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx);
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx);
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				  struct efi_signature_store *db,
+				  struct x509_certificate **cert);
+
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck);
+#endif /* CONFIG_EFI_SECURE_BOOT */
+
 #else /* CONFIG_IS_ENABLED(EFI_LOADER) */
 
 /* Without CONFIG_EFI_LOADER we don't have a runtime section, stub it out */
lib/efi_loader/Makefile +1 -0
index 9b3b70447336..eff3c25ec301 100644
@@ -44,3 +44,4 @@ obj-$(CONFIG_GENERATE_ACPI_TABLE) += efi_acpi.o
 obj-$(CONFIG_GENERATE_SMBIOS_TABLE) += efi_smbios.o
 obj-$(CONFIG_EFI_RNG_PROTOCOL) += efi_rng.o
 obj-$(CONFIG_EFI_LOAD_FILE2_INITRD) += efi_load_initrd.o
+obj-y += efi_signature.o
lib/efi_loader/efi_signature.c new file +3 -0
new file mode 100644
index 000000000000..23dac94c0593
@@ -0,0 +1,583 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2018 Patrick Wildt <[email protected]>

lib/efi_loader/efi_signature.c line 13

Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10 -0
+ * Copyright (c) 2019 Linaro Limited, Author: AKASHI Takahiro
+ */
+
+#include <common.h>
+#include <charset.h>
+#include <efi_loader.h>
+#include <image.h>
+#include <hexdump.h>
+#include <malloc.h>
+#include <pe.h>

You just added pe.h to efi_api.h which is included in efi_loader.h. Please, avoid adding the includes twice.

lib/efi_loader/efi_signature.c line 19

Quoted 6 lines
lib/efi_loader/efi_signature.c new file +6 -0
+#include <linux/compat.h>
+#include <linux/oid_registry.h>
+#include <u-boot/rsa.h>
+#include <u-boot/sha256.h>
+/*
+ * avoid duplicated inclusion:

Why don't you fix the lib/crypto/x509_parser.h that you created? Just add the missing

#ifdef _X509_PARSER_H
#define _X509_PARSER_H
#endif /* _X509_PARSER_H */

Same problem in pkcs7_parser.h.

lib/efi_loader/efi_signature.c line 21

Quoted 2 lines
lib/efi_loader/efi_signature.c new file +2 -0
+ * #include "../lib/crypto/x509_parser.h"
+ */

If you patch is working I see no reason to add the comment here.

lib/efi_loader/efi_signature.c line 22

Quoted 1 line
lib/efi_loader/efi_signature.c new file +1 -0
+#include "../lib/crypto/pkcs7_parser.h"

Why is pkcs7_parser.h in lib/ and not in include/?

I would prefer to avoid relative paths.

I will remove the superfluous comment and include when merging. The rest can be fixed later.

Best regards

Heinrich

Quoted 562 lines
lib/efi_loader/efi_signature.c new file +561 -0
+
+const efi_guid_t efi_guid_image_security_database =
+		EFI_IMAGE_SECURITY_DATABASE_GUID;
+const efi_guid_t efi_guid_sha256 = EFI_CERT_SHA256_GUID;
+const efi_guid_t efi_guid_cert_rsa2048 = EFI_CERT_RSA2048_GUID;
+const efi_guid_t efi_guid_cert_x509 = EFI_CERT_X509_GUID;
+const efi_guid_t efi_guid_cert_x509_sha256 = EFI_CERT_X509_SHA256_GUID;
+
+#ifdef CONFIG_EFI_SECURE_BOOT
+
+/**
+ * efi_hash_regions - calculate a hash value
+ * @regs:	List of regions
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of @regs and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_regions(struct efi_image_regions *regs, void **hash,
+			     size_t *size)
+{
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	hash_calculate("sha256", regs->reg, regs->num, *hash);
+#ifdef DEBUG
+	debug("hash calculated:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_hash_msg_content - calculate a hash value of contentInfo
+ * @msg:	Signature
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of contentInfo in @msg and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_msg_content(struct pkcs7_message *msg, void **hash,
+				 size_t *size)
+{
+	struct image_region regtmp;
+
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		free(msg);
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	regtmp.data = msg->data;
+	regtmp.size = msg->data_len;
+
+	hash_calculate("sha256", &regtmp, 1, *hash);
+#ifdef DEBUG
+	debug("hash calculated based on contentInfo:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_signature_verify - verify a signature with a certificate
+ * @regs:		List of regions to be authenticated
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @cert:		x509 certificate
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by a certificate pointed to by @cert.
+ * @signed_info holds a signature, including a message digest which is to be
+ * compared with a hash value calculated from @regs.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static bool efi_signature_verify(struct efi_image_regions *regs,
+				 struct pkcs7_message *msg,
+				 struct pkcs7_signed_info *ps_info,
+				 struct x509_certificate *cert)
+{
+	struct image_sign_info info;
+	struct image_region regtmp[2];
+	void *hash;
+	size_t size;
+	char c;
+	bool verified;
+
+	debug("%s: Enter, %p, %p, %p(issuer: %s, subject: %s)\n", __func__,
+	      regs, ps_info, cert, cert->issuer, cert->subject);
+
+	verified = false;
+
+	memset(&info, '\0', sizeof(info));
+	info.padding = image_get_padding_algo("pkcs-1.5");
+	/*
+	 * Note: image_get_[checksum|crypto]_algo takes an string
+	 * argument like "<checksum>,<crypto>"
+	 * TODO: support other hash algorithms
+	 */
+	if (!strcmp(ps_info->sig->hash_algo, "sha1")) {
+		info.checksum = image_get_checksum_algo("sha1,rsa2048");
+		info.name = "sha1,rsa2048";
+	} else if (!strcmp(ps_info->sig->hash_algo, "sha256")) {
+		info.checksum = image_get_checksum_algo("sha256,rsa2048");
+		info.name = "sha256,rsa2048";
+	} else {
+		debug("unknown msg digest algo: %s\n", ps_info->sig->hash_algo);
+		goto out;
+	}
+	info.crypto = image_get_crypto_algo(info.name);
+
+	info.key = cert->pub->key;
+	info.keylen = cert->pub->keylen;
+
+	/* verify signature */
+	debug("%s: crypto: %s, signature len:%x\n", __func__,
+	      info.name, ps_info->sig->s_size);
+	if (ps_info->aa_set & (1UL << sinfo_has_message_digest)) {
+		debug("%s: RSA verify authentication attribute\n", __func__);
+		/*
+		 * NOTE: This path will be executed only for
+		 * PE image authentication
+		 */
+
+		/* check if hash matches digest first */
+		debug("checking msg digest first, len:0x%x\n",
+		      ps_info->msgdigest_len);
+
+#ifdef DEBUG
+		debug("hash in database:\n");
+		print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+			       ps_info->msgdigest, ps_info->msgdigest_len,
+			       false);
+#endif
+		/* against contentInfo first */
+		if ((msg->data && efi_hash_msg_content(msg, &hash, &size)) ||
+				/* for signed image */
+		    efi_hash_regions(regs, &hash, &size)) {
+				/* for authenticated variable */
+			if (ps_info->msgdigest_len != size ||
+			    memcmp(hash, ps_info->msgdigest, size)) {
+				debug("Digest doesn't match\n");
+				free(hash);
+				goto out;
+			}
+
+			free(hash);
+		} else {
+			debug("Digesting image failed\n");
+			goto out;
+		}
+
+		/* against digest */
+		c = 0x31;
+		regtmp[0].data = &c;
+		regtmp[0].size = 1;
+		regtmp[1].data = ps_info->authattrs;
+		regtmp[1].size = ps_info->authattrs_len;
+
+		if (!rsa_verify(&info, regtmp, 2,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	} else {
+		debug("%s: RSA verify content data\n", __func__);
+		/* against all data */
+		if (!rsa_verify(&info, regs->reg, regs->num,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_list - verify a signature with signature list
+ * @regs:		List of regions to be authenticated
+ * @msg:		Signature
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @siglist:		Signature list for certificates
+ * @valid_cert:		x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by signature list pointed to by @siglist.
+ * Signature database is a simple concatenation of one or more
+ * signature list(s).
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static
+bool efi_signature_verify_with_list(struct efi_image_regions *regs,
+				    struct pkcs7_message *msg,
+				    struct pkcs7_signed_info *signed_info,
+				    struct efi_signature_store *siglist,
+				    struct x509_certificate **valid_cert)
+{
+	struct x509_certificate *cert;
+	struct efi_sig_data *sig_data;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__,
+	      regs, signed_info, siglist, valid_cert);
+
+	if (!signed_info) {
+		void *hash;
+		size_t size;
+
+		debug("%s: unsigned image\n", __func__);
+		/*
+		 * verify based on calculated hash value
+		 * TODO: support other hash algorithms
+		 */
+		if (guidcmp(&siglist->sig_type, &efi_guid_sha256)) {
+			debug("Digest algorithm is not supported: %pUl\n",
+			      &siglist->sig_type);
+			goto out;
+		}
+
+		if (!efi_hash_regions(regs, &hash, &size)) {
+			debug("Digesting unsigned image failed\n");
+			goto out;
+		}
+
+		/* go through the list */
+		for (sig_data = siglist->sig_data_list; sig_data;
+		     sig_data = sig_data->next) {
+#ifdef DEBUG
+			debug("Msg digest in database:\n");
+			print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+				       sig_data->data, sig_data->size, false);
+#endif
+			if ((sig_data->size == size) &&
+			    !memcmp(sig_data->data, hash, size)) {
+				verified = true;
+				free(hash);
+				goto out;
+			}
+		}
+		free(hash);
+		goto out;
+	}
+
+	debug("%s: signed image\n", __func__);
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509)) {
+		debug("Signature type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* go through the list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/* TODO: support owner check based on policy */
+
+		cert = x509_cert_parse(sig_data->data, sig_data->size);
+		if (IS_ERR(cert)) {
+			debug("Parsing x509 certificate failed\n");
+			goto out;
+		}
+
+		verified = efi_signature_verify(regs, msg, signed_info, cert);
+
+		if (verified) {
+			if (valid_cert)
+				*valid_cert = cert;
+			else
+				x509_free_certificate(cert);
+			break;
+		}
+		x509_free_certificate(cert);
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_sigdb - verify a signature with db
+ * @regs:	List of regions to be authenticated
+ * @msg:	Signature
+ * @db:		Signature database for trusted certificates
+ * @cert:	x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @msg against image pointed to by @regs
+ * is verified by signature database pointed to by @db.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				     struct efi_signature_store *db,
+				     struct x509_certificate **cert)
+{
+	struct pkcs7_signed_info *info;
+	struct efi_signature_store *siglist;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__, regs, msg, db, cert);
+
+	if (!db)
+		goto out;
+
+	if (!db->sig_data_list)
+		goto out;
+
+	/* for unsigned image */
+	if (!msg) {
+		debug("%s: Verify unsigned image with db\n", __func__);
+		for (siglist = db; siglist; siglist = siglist->next)
+			if (efi_signature_verify_with_list(regs, NULL, NULL,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+
+		goto out;
+	}
+
+	/* for signed image or variable */
+	debug("%s: Verify signed image with db\n", __func__);
+	for (info = msg->signed_infos; info; info = info->next) {
+		debug("Signed Info: digest algo: %s, pkey algo: %s\n",
+		      info->sig->hash_algo, info->sig->pkey_algo);
+
+		for (siglist = db; siglist; siglist = siglist->next) {
+			if (efi_signature_verify_with_list(regs, msg, info,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+		}
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_search_siglist - search signature list for a certificate
+ * @cert:	x509 certificate
+ * @siglist:	Signature list
+ * @revoc_time:	Pointer to buffer for revocation time
+ *
+ * Search signature list pointed to by @siglist and find a certificate
+ * pointed to by @cert.
+ * If found, revocation time that is specified in signature database is
+ * returned in @revoc_time.
+ *
+ * Return:	true if certificate is found, false if not
+ */
+static bool efi_search_siglist(struct x509_certificate *cert,
+			       struct efi_signature_store *siglist,
+			       time64_t *revoc_time)
+{
+	struct image_region reg[1];
+	void *hash = NULL, *msg = NULL;
+	struct efi_sig_data *sig_data;
+	bool found = false;
+
+	/* can be null */
+	if (!siglist->sig_data_list)
+		return false;
+
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509_sha256)) {
+		/* TODO: other hash algos */
+		debug("Certificate's digest type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* calculate hash of TBSCertificate */
+	msg = calloc(1, SHA256_SUM_LEN);
+	if (!msg) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	hash = calloc(1, SHA256_SUM_LEN);
+	if (!hash) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	reg[0].data = cert->tbs;
+	reg[0].size = cert->tbs_size;
+	hash_calculate("sha256", reg, 1, msg);
+
+	/* go through signature list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/*
+		 * struct efi_cert_x509_sha256 {
+		 *	u8 tbs_hash[256/8];
+		 *	time64_t revocation_time;
+		 * };
+		 */
+		if ((sig_data->size == SHA256_SUM_LEN) &&
+		    !memcmp(sig_data->data, hash, SHA256_SUM_LEN)) {
+			memcpy(revoc_time, sig_data->data + SHA256_SUM_LEN,
+			       sizeof(*revoc_time));
+			found = true;
+			goto out;
+		}
+	}
+
+out:
+	free(hash);
+	free(msg);
+
+	return found;
+}
+
+/**
+ * efi_signature_verify_cert - verify a certificate with dbx
+ * @cert:	x509 certificate
+ * @dbx:	Signature database
+ *
+ * Search signature database pointed to by @dbx and find a certificate
+ * pointed to by @cert.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if a certificate is not rejected, false otherwise.
+ */
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx)
+{
+	struct efi_signature_store *siglist;
+	time64_t revoc_time;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, dbx, cert);
+
+	if (!cert)
+		return false;
+
+	for (siglist = dbx; siglist; siglist = siglist->next) {
+		if (efi_search_siglist(cert, siglist, &revoc_time)) {
+			/* TODO */
+			/* compare signing time with revocation time */
+
+			found = true;
+			break;
+		}
+	}
+
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_signature_verify_signers - verify signers' certificates with dbx
+ * @msg:	Signature
+ * @dbx:	Signature database
+ *
+ * Determine if any of signers' certificates in @msg may be verified
+ * by any of certificates in signature database pointed to by @dbx.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if none of certificates is rejected, false otherwise.
+ */
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx)
+{
+	struct pkcs7_signed_info *info;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, msg, dbx);
+
+	if (!msg)
+		goto out;
+
+	for (info = msg->signed_infos; info; info = info->next) {
+		if (info->signer &&
+		    !efi_signature_verify_cert(info->signer, dbx)) {
+			found = true;
+			goto out;
+		}
+	}
+out:
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_image_region_add - add an entry of region
+ * @regs:	Pointer to array of regions
+ * @start:	Start address of region
+ * @end:	End address of region
+ * @nocheck:	flag against overlapped regions
+ *
+ * Take one entry of region [@start, @end] and append it to the list
+ * pointed to by @regs. If @nocheck is false, overlapping among entries
+ * will be checked first.
+ *
+ * Return:	0 on success, status code (negative) on error
+ */
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck)
+{
+	struct image_region *reg;
+	int i, j;
+
+	if (regs->num >= regs->max) {
+		debug("%s: no more room for regions\n", __func__);
+		return EFI_OUT_OF_RESOURCES;
+	}
+
+	if (end < start)
+		return EFI_INVALID_PARAMETER;
+
+	for (i = 0; i < regs->num; i++) {
+		reg = &regs->reg[i];
+		if (nocheck)
+			continue;
+
+		if (start > reg->data + reg->size)
+			continue;
+
+		if ((start >= reg->data && start < reg->data + reg->size) ||
+		    (end > reg->data && end < reg->data + reg->size)) {
+			debug("%s: new region already part of another\n",
+			      __func__);
+			return EFI_INVALID_PARAMETER;
+		}
+
+		if (start < reg->data && end < reg->data + reg->size) {
+			for (j = regs->num - 1; j >= i; j--)
+				memcpy(&regs->reg[j], &regs->reg[j + 1],
+				       sizeof(*reg));
+			break;
+		}
+	}
+
+	reg = &regs->reg[i];
+	reg->data = start;
+	reg->size = end - start;
+	regs->num++;
+
+	return EFI_SUCCESS;
+}
+#endif /* CONFIG_EFI_SECURE_BOOT */
#4 lore raw

PATCH v7 2/17 efi_loader: add signature verification functions

Heinrich,

Quoted 94 lines · Heinrich Schuchardt
Quoted 93 lines · AKASHI Takahiro

In this commit, implemented are a couple of helper functions which will be used to materialize variable authentication as well as image authentication in later patches.

---
 include/efi_api.h              |  87 +++++
 include/efi_loader.h           |  72 ++++
 lib/efi_loader/Makefile        |   1 +
 lib/efi_loader/efi_signature.c | 583 +++++++++++++++++++++++++++++++++
 4 files changed, 743 insertions(+)
 create mode 100644 lib/efi_loader/efi_signature.c
include/efi_api.h +58 -0
index 1c40ffc4f56c..77d6bf2660b9 100644
@@ -18,6 +18,7 @@
 
 #include <efi.h>
 #include <charset.h>
+#include <pe.h>
 
 #ifdef CONFIG_EFI_LOADER
 #include <asm/setjmp.h>
@@ -329,6 +330,10 @@ struct efi_runtime_services {
 	EFI_GUID(0x8be4df61, 0x93ca, 0x11d2, 0xaa, 0x0d, \
 		 0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c)
 
+#define EFI_IMAGE_SECURITY_DATABASE_GUID \
+	EFI_GUID(0xd719b2cb, 0x3d3a, 0x4596, 0xa3, 0xbc, \
+		 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f)
+
 #define EFI_FDT_GUID \
 	EFI_GUID(0xb1b621d5, 0xf19c, 0x41a5, \
 		 0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0)
@@ -1682,4 +1687,86 @@ struct efi_load_file_protocol {
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MIN 0x00001000
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MAX 0x00004000
 
+/* Certificate types in signature database */
+#define EFI_CERT_SHA256_GUID \
+	EFI_GUID(0xc1c41626, 0x504c, 0x4092, 0xac, 0xa9, \
+		 0x41, 0xf9, 0x36, 0x93, 0x43, 0x28)
+#define EFI_CERT_RSA2048_GUID \
+	EFI_GUID(0x3c5766e8, 0x269c, 0x4e34, 0xaa, 0x14, \
+		 0xed, 0x77, 0x6e, 0x85, 0xb3, 0xb6)
+#define EFI_CERT_X509_GUID \
+	EFI_GUID(0xa5c059a1, 0x94e4, 0x4aa7, 0x87, 0xb5, \
+		 0xab, 0x15, 0x5c, 0x2b, 0xf0, 0x72)
+#define EFI_CERT_X509_SHA256_GUID \
+	EFI_GUID(0x3bd2a492, 0x96c0, 0x4079, 0xb4, 0x20, \
+		 0xfc, 0xf9, 0x8e, 0xf1, 0x03, 0xed)
+#define EFI_CERT_TYPE_PKCS7_GUID \
+	EFI_GUID(0x4aafd29d, 0x68df, 0x49ee, 0x8a, 0xa9, \
+		 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7)
+
+/**
+ * win_certificate_uefi_guid - A certificate that encapsulates
+ * a GUID-specific signature
+ *
+ * @hdr:	Windows certificate header
+ * @cert_type:	Certificate type
+ * @cert_data:	Certificate data
+ */
+struct win_certificate_uefi_guid {
+	WIN_CERTIFICATE	hdr;
+	efi_guid_t	cert_type;
+	u8		cert_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_variable_authentication_2 - A time-based authentication method
+ * descriptor
+ *
+ * This structure describes an authentication information for
+ * a variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
+ * and should be included as part of a variable's value.
+ * Only EFI_CERT_TYPE_PKCS7_GUID is accepted.
+ *
+ * @time_stamp:	Descriptor's time stamp
+ * @auth_info:	Authentication info
+ */
+struct efi_variable_authentication_2 {
+	struct efi_time			 time_stamp;
+	struct win_certificate_uefi_guid auth_info;
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_data - A format of signature
+ *
+ * This structure describes a single signature in signature database.
+ *
Quoted 8 lines

include/efi_api.h struct efi_load_file_protocol { · line 1748

Quoted 6 lines
include/efi_api.h +6 -0
+ * @signature_owner:	Signature owner
+ * @signature_data:	Signature data
+ */
+struct efi_signature_data {
+	efi_guid_t	signature_owner;
+	u8		signature_data[];

Please, use [0].

Actually, there are a bunch of uses of [] notation in efi.h, efi_api.h and efi_loader.h.

Do you really want to modify all?

Quoted 144 lines
Quoted 144 lines
include/efi_api.h +23 -0
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_list - A format of signature database
+ *
+ * This structure describes a list of signatures with the same type.
+ * An authenticated variable's value is a concatenation of one or more
+ * efi_signature_list's.
+ *
+ * @signature_type:		Signature type
+ * @signature_list_size:	Size of signature list
+ * @signature_header_size:	Size of signature header
+ * @signature_size:		Size of signature
+ */
+struct efi_signature_list {
+	efi_guid_t	signature_type;
+	u32		signature_list_size;
+	u32		signature_header_size;
+	u32		signature_size;
+/*	u8		signature_header[signature_header_size]; */
+/*	struct efi_signature_data signatures[...][signature_size]; */
+} __attribute__((__packed__));
+
 #endif
include/efi_loader.h +72 -0
index 3f2792892f34..8cf85d2fb7e2 100644
@@ -26,6 +26,7 @@ static inline void *guidcpy(void *dst, const void *src)
 #if CONFIG_IS_ENABLED(EFI_LOADER)
 
 #include <linux/list.h>
+#include <linux/oid_registry.h>
 
 /* Maximum number of configuration tables */
 #define EFI_MAX_CONFIGURATION_TABLES 16
@@ -178,6 +179,11 @@ extern const efi_guid_t efi_guid_hii_config_routing_protocol;
 extern const efi_guid_t efi_guid_hii_config_access_protocol;
 extern const efi_guid_t efi_guid_hii_database_protocol;
 extern const efi_guid_t efi_guid_hii_string_protocol;
+/* GUIDs for authentication */
+extern const efi_guid_t efi_guid_image_security_database;
+extern const efi_guid_t efi_guid_sha256;
+extern const efi_guid_t efi_guid_cert_x509;
+extern const efi_guid_t efi_guid_cert_x509_sha256;
 
 /* GUID of RNG protocol */
 extern const efi_guid_t efi_guid_rng_protocol;
@@ -680,6 +686,72 @@ void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data);
 unsigned long efi_serialize_load_option(struct efi_load_option *lo, u8 **data);
 efi_status_t efi_bootmgr_load(efi_handle_t *handle);
 
+#ifdef CONFIG_EFI_SECURE_BOOT
+#include <image.h>
+
+/**
+ * efi_image_regions - A list of memory regions
+ *
+ * @max:	Maximum number of regions
+ * @num:	Number of regions
+ * @reg:	array of regions
+ */
+struct efi_image_regions {
+	int			max;
+	int			num;
+	struct image_region	reg[];
+};
+
+/**
+ * efi_sig_data - A decoded data of struct efi_signature_data
+ *
+ * This structure represents an internal form of signature in
+ * signature database. A listed list may represent a signature list.
+ *
+ * @next:	Pointer to next entry
+ * @onwer:	Signature owner
+ * @data:	Pointer to signature data
+ * @size:	Size of signature data
+ */
+struct efi_sig_data {
+	struct efi_sig_data *next;
+	efi_guid_t owner;
+	void *data;
+	size_t size;
+};
+
+/**
+ * efi_signature_store - A decoded data of signature database
+ *
+ * This structure represents an internal form of signature database.
+ *
+ * @next:		Pointer to next entry
+ * @sig_type:		Signature type
+ * @sig_data_list:	Pointer to signature list
+ */
+struct efi_signature_store {
+	struct efi_signature_store *next;
+	efi_guid_t sig_type;
+	struct efi_sig_data *sig_data_list;
+};
+
+struct x509_certificate;
+struct pkcs7_message;
+
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx);
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx);
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				  struct efi_signature_store *db,
+				  struct x509_certificate **cert);
+
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck);
+#endif /* CONFIG_EFI_SECURE_BOOT */
+
 #else /* CONFIG_IS_ENABLED(EFI_LOADER) */
 
 /* Without CONFIG_EFI_LOADER we don't have a runtime section, stub it out */
lib/efi_loader/Makefile +1 -0
index 9b3b70447336..eff3c25ec301 100644
@@ -44,3 +44,4 @@ obj-$(CONFIG_GENERATE_ACPI_TABLE) += efi_acpi.o
 obj-$(CONFIG_GENERATE_SMBIOS_TABLE) += efi_smbios.o
 obj-$(CONFIG_EFI_RNG_PROTOCOL) += efi_rng.o
 obj-$(CONFIG_EFI_LOAD_FILE2_INITRD) += efi_load_initrd.o
+obj-y += efi_signature.o
lib/efi_loader/efi_signature.c new file +8 -0
new file mode 100644
index 000000000000..23dac94c0593
@@ -0,0 +1,583 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2018 Patrick Wildt <[email protected]>
+ * Copyright (c) 2019 Linaro Limited, Author: AKASHI Takahiro
+ */
+
+#include <common.h>
+#include <charset.h>
Quoted 8 lines

lib/efi_loader/efi_signature.c line 13

Quoted 5 lines
lib/efi_loader/efi_signature.c new file +5 -0
+#include <efi_loader.h>
+#include <image.h>
+#include <hexdump.h>
+#include <malloc.h>
+#include <pe.h>

You just added pe.h to efi_api.h which is included in efi_loader.h. Please, avoid adding the includes twice.

I agree as there is no use of any symbols from pe.h here.

Quoted 10 lines

lib/efi_loader/efi_signature.c line 19

Quoted 6 lines
lib/efi_loader/efi_signature.c new file +6 -0
+#include <linux/compat.h>
+#include <linux/oid_registry.h>
+#include <u-boot/rsa.h>
+#include <u-boot/sha256.h>
+/*
+ * avoid duplicated inclusion:

Why don't you fix the lib/crypto/x509_parser.h that you created? Just add the missing

Quoted 3 lines

#ifdef _X509_PARSER_H
#define _X509_PARSER_H
#endif /* _X509_PARSER_H */

Okay.

Quoted 5 lines

Same problem in pkcs7_parser.h.

lib/efi_loader/efi_signature.c line 21

Quoted 2 lines
lib/efi_loader/efi_signature.c new file +2 -0
+ * #include "../lib/crypto/x509_parser.h"
+ */
Quoted 7 lines

If you patch is working I see no reason to add the comment here.

lib/efi_loader/efi_signature.c line 22

Quoted 1 line
lib/efi_loader/efi_signature.c new file +1 -0
+#include "../lib/crypto/pkcs7_parser.h"

Why is pkcs7_parser.h in lib/ and not in include/?

I would prefer to avoid relative paths.

My basic approach was to minimize the modification to the original (i.e. linux code) as much as possible.
Anyhow, I will try to fix it.

Thanks,
-Takahiro Akashi

Quoted 570 lines

I will remove the superfluous comment and include when merging. The rest can be fixed later.

Best regards

Heinrich

Quoted 562 lines
lib/efi_loader/efi_signature.c new file +561 -0
+
+const efi_guid_t efi_guid_image_security_database =
+		EFI_IMAGE_SECURITY_DATABASE_GUID;
+const efi_guid_t efi_guid_sha256 = EFI_CERT_SHA256_GUID;
+const efi_guid_t efi_guid_cert_rsa2048 = EFI_CERT_RSA2048_GUID;
+const efi_guid_t efi_guid_cert_x509 = EFI_CERT_X509_GUID;
+const efi_guid_t efi_guid_cert_x509_sha256 = EFI_CERT_X509_SHA256_GUID;
+
+#ifdef CONFIG_EFI_SECURE_BOOT
+
+/**
+ * efi_hash_regions - calculate a hash value
+ * @regs:	List of regions
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of @regs and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_regions(struct efi_image_regions *regs, void **hash,
+			     size_t *size)
+{
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	hash_calculate("sha256", regs->reg, regs->num, *hash);
+#ifdef DEBUG
+	debug("hash calculated:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_hash_msg_content - calculate a hash value of contentInfo
+ * @msg:	Signature
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of contentInfo in @msg and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_msg_content(struct pkcs7_message *msg, void **hash,
+				 size_t *size)
+{
+	struct image_region regtmp;
+
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		free(msg);
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	regtmp.data = msg->data;
+	regtmp.size = msg->data_len;
+
+	hash_calculate("sha256", &regtmp, 1, *hash);
+#ifdef DEBUG
+	debug("hash calculated based on contentInfo:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_signature_verify - verify a signature with a certificate
+ * @regs:		List of regions to be authenticated
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @cert:		x509 certificate
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by a certificate pointed to by @cert.
+ * @signed_info holds a signature, including a message digest which is to be
+ * compared with a hash value calculated from @regs.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static bool efi_signature_verify(struct efi_image_regions *regs,
+				 struct pkcs7_message *msg,
+				 struct pkcs7_signed_info *ps_info,
+				 struct x509_certificate *cert)
+{
+	struct image_sign_info info;
+	struct image_region regtmp[2];
+	void *hash;
+	size_t size;
+	char c;
+	bool verified;
+
+	debug("%s: Enter, %p, %p, %p(issuer: %s, subject: %s)\n", __func__,
+	      regs, ps_info, cert, cert->issuer, cert->subject);
+
+	verified = false;
+
+	memset(&info, '\0', sizeof(info));
+	info.padding = image_get_padding_algo("pkcs-1.5");
+	/*
+	 * Note: image_get_[checksum|crypto]_algo takes an string
+	 * argument like "<checksum>,<crypto>"
+	 * TODO: support other hash algorithms
+	 */
+	if (!strcmp(ps_info->sig->hash_algo, "sha1")) {
+		info.checksum = image_get_checksum_algo("sha1,rsa2048");
+		info.name = "sha1,rsa2048";
+	} else if (!strcmp(ps_info->sig->hash_algo, "sha256")) {
+		info.checksum = image_get_checksum_algo("sha256,rsa2048");
+		info.name = "sha256,rsa2048";
+	} else {
+		debug("unknown msg digest algo: %s\n", ps_info->sig->hash_algo);
+		goto out;
+	}
+	info.crypto = image_get_crypto_algo(info.name);
+
+	info.key = cert->pub->key;
+	info.keylen = cert->pub->keylen;
+
+	/* verify signature */
+	debug("%s: crypto: %s, signature len:%x\n", __func__,
+	      info.name, ps_info->sig->s_size);
+	if (ps_info->aa_set & (1UL << sinfo_has_message_digest)) {
+		debug("%s: RSA verify authentication attribute\n", __func__);
+		/*
+		 * NOTE: This path will be executed only for
+		 * PE image authentication
+		 */
+
+		/* check if hash matches digest first */
+		debug("checking msg digest first, len:0x%x\n",
+		      ps_info->msgdigest_len);
+
+#ifdef DEBUG
+		debug("hash in database:\n");
+		print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+			       ps_info->msgdigest, ps_info->msgdigest_len,
+			       false);
+#endif
+		/* against contentInfo first */
+		if ((msg->data && efi_hash_msg_content(msg, &hash, &size)) ||
+				/* for signed image */
+		    efi_hash_regions(regs, &hash, &size)) {
+				/* for authenticated variable */
+			if (ps_info->msgdigest_len != size ||
+			    memcmp(hash, ps_info->msgdigest, size)) {
+				debug("Digest doesn't match\n");
+				free(hash);
+				goto out;
+			}
+
+			free(hash);
+		} else {
+			debug("Digesting image failed\n");
+			goto out;
+		}
+
+		/* against digest */
+		c = 0x31;
+		regtmp[0].data = &c;
+		regtmp[0].size = 1;
+		regtmp[1].data = ps_info->authattrs;
+		regtmp[1].size = ps_info->authattrs_len;
+
+		if (!rsa_verify(&info, regtmp, 2,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	} else {
+		debug("%s: RSA verify content data\n", __func__);
+		/* against all data */
+		if (!rsa_verify(&info, regs->reg, regs->num,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_list - verify a signature with signature list
+ * @regs:		List of regions to be authenticated
+ * @msg:		Signature
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @siglist:		Signature list for certificates
+ * @valid_cert:		x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by signature list pointed to by @siglist.
+ * Signature database is a simple concatenation of one or more
+ * signature list(s).
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static
+bool efi_signature_verify_with_list(struct efi_image_regions *regs,
+				    struct pkcs7_message *msg,
+				    struct pkcs7_signed_info *signed_info,
+				    struct efi_signature_store *siglist,
+				    struct x509_certificate **valid_cert)
+{
+	struct x509_certificate *cert;
+	struct efi_sig_data *sig_data;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__,
+	      regs, signed_info, siglist, valid_cert);
+
+	if (!signed_info) {
+		void *hash;
+		size_t size;
+
+		debug("%s: unsigned image\n", __func__);
+		/*
+		 * verify based on calculated hash value
+		 * TODO: support other hash algorithms
+		 */
+		if (guidcmp(&siglist->sig_type, &efi_guid_sha256)) {
+			debug("Digest algorithm is not supported: %pUl\n",
+			      &siglist->sig_type);
+			goto out;
+		}
+
+		if (!efi_hash_regions(regs, &hash, &size)) {
+			debug("Digesting unsigned image failed\n");
+			goto out;
+		}
+
+		/* go through the list */
+		for (sig_data = siglist->sig_data_list; sig_data;
+		     sig_data = sig_data->next) {
+#ifdef DEBUG
+			debug("Msg digest in database:\n");
+			print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+				       sig_data->data, sig_data->size, false);
+#endif
+			if ((sig_data->size == size) &&
+			    !memcmp(sig_data->data, hash, size)) {
+				verified = true;
+				free(hash);
+				goto out;
+			}
+		}
+		free(hash);
+		goto out;
+	}
+
+	debug("%s: signed image\n", __func__);
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509)) {
+		debug("Signature type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* go through the list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/* TODO: support owner check based on policy */
+
+		cert = x509_cert_parse(sig_data->data, sig_data->size);
+		if (IS_ERR(cert)) {
+			debug("Parsing x509 certificate failed\n");
+			goto out;
+		}
+
+		verified = efi_signature_verify(regs, msg, signed_info, cert);
+
+		if (verified) {
+			if (valid_cert)
+				*valid_cert = cert;
+			else
+				x509_free_certificate(cert);
+			break;
+		}
+		x509_free_certificate(cert);
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_sigdb - verify a signature with db
+ * @regs:	List of regions to be authenticated
+ * @msg:	Signature
+ * @db:		Signature database for trusted certificates
+ * @cert:	x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @msg against image pointed to by @regs
+ * is verified by signature database pointed to by @db.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				     struct efi_signature_store *db,
+				     struct x509_certificate **cert)
+{
+	struct pkcs7_signed_info *info;
+	struct efi_signature_store *siglist;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__, regs, msg, db, cert);
+
+	if (!db)
+		goto out;
+
+	if (!db->sig_data_list)
+		goto out;
+
+	/* for unsigned image */
+	if (!msg) {
+		debug("%s: Verify unsigned image with db\n", __func__);
+		for (siglist = db; siglist; siglist = siglist->next)
+			if (efi_signature_verify_with_list(regs, NULL, NULL,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+
+		goto out;
+	}
+
+	/* for signed image or variable */
+	debug("%s: Verify signed image with db\n", __func__);
+	for (info = msg->signed_infos; info; info = info->next) {
+		debug("Signed Info: digest algo: %s, pkey algo: %s\n",
+		      info->sig->hash_algo, info->sig->pkey_algo);
+
+		for (siglist = db; siglist; siglist = siglist->next) {
+			if (efi_signature_verify_with_list(regs, msg, info,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+		}
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_search_siglist - search signature list for a certificate
+ * @cert:	x509 certificate
+ * @siglist:	Signature list
+ * @revoc_time:	Pointer to buffer for revocation time
+ *
+ * Search signature list pointed to by @siglist and find a certificate
+ * pointed to by @cert.
+ * If found, revocation time that is specified in signature database is
+ * returned in @revoc_time.
+ *
+ * Return:	true if certificate is found, false if not
+ */
+static bool efi_search_siglist(struct x509_certificate *cert,
+			       struct efi_signature_store *siglist,
+			       time64_t *revoc_time)
+{
+	struct image_region reg[1];
+	void *hash = NULL, *msg = NULL;
+	struct efi_sig_data *sig_data;
+	bool found = false;
+
+	/* can be null */
+	if (!siglist->sig_data_list)
+		return false;
+
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509_sha256)) {
+		/* TODO: other hash algos */
+		debug("Certificate's digest type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* calculate hash of TBSCertificate */
+	msg = calloc(1, SHA256_SUM_LEN);
+	if (!msg) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	hash = calloc(1, SHA256_SUM_LEN);
+	if (!hash) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	reg[0].data = cert->tbs;
+	reg[0].size = cert->tbs_size;
+	hash_calculate("sha256", reg, 1, msg);
+
+	/* go through signature list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/*
+		 * struct efi_cert_x509_sha256 {
+		 *	u8 tbs_hash[256/8];
+		 *	time64_t revocation_time;
+		 * };
+		 */
+		if ((sig_data->size == SHA256_SUM_LEN) &&
+		    !memcmp(sig_data->data, hash, SHA256_SUM_LEN)) {
+			memcpy(revoc_time, sig_data->data + SHA256_SUM_LEN,
+			       sizeof(*revoc_time));
+			found = true;
+			goto out;
+		}
+	}
+
+out:
+	free(hash);
+	free(msg);
+
+	return found;
+}
+
+/**
+ * efi_signature_verify_cert - verify a certificate with dbx
+ * @cert:	x509 certificate
+ * @dbx:	Signature database
+ *
+ * Search signature database pointed to by @dbx and find a certificate
+ * pointed to by @cert.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if a certificate is not rejected, false otherwise.
+ */
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx)
+{
+	struct efi_signature_store *siglist;
+	time64_t revoc_time;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, dbx, cert);
+
+	if (!cert)
+		return false;
+
+	for (siglist = dbx; siglist; siglist = siglist->next) {
+		if (efi_search_siglist(cert, siglist, &revoc_time)) {
+			/* TODO */
+			/* compare signing time with revocation time */
+
+			found = true;
+			break;
+		}
+	}
+
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_signature_verify_signers - verify signers' certificates with dbx
+ * @msg:	Signature
+ * @dbx:	Signature database
+ *
+ * Determine if any of signers' certificates in @msg may be verified
+ * by any of certificates in signature database pointed to by @dbx.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if none of certificates is rejected, false otherwise.
+ */
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx)
+{
+	struct pkcs7_signed_info *info;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, msg, dbx);
+
+	if (!msg)
+		goto out;
+
+	for (info = msg->signed_infos; info; info = info->next) {
+		if (info->signer &&
+		    !efi_signature_verify_cert(info->signer, dbx)) {
+			found = true;
+			goto out;
+		}
+	}
+out:
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_image_region_add - add an entry of region
+ * @regs:	Pointer to array of regions
+ * @start:	Start address of region
+ * @end:	End address of region
+ * @nocheck:	flag against overlapped regions
+ *
+ * Take one entry of region [@start, @end] and append it to the list
+ * pointed to by @regs. If @nocheck is false, overlapping among entries
+ * will be checked first.
+ *
+ * Return:	0 on success, status code (negative) on error
+ */
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck)
+{
+	struct image_region *reg;
+	int i, j;
+
+	if (regs->num >= regs->max) {
+		debug("%s: no more room for regions\n", __func__);
+		return EFI_OUT_OF_RESOURCES;
+	}
+
+	if (end < start)
+		return EFI_INVALID_PARAMETER;
+
+	for (i = 0; i < regs->num; i++) {
+		reg = &regs->reg[i];
+		if (nocheck)
+			continue;
+
+		if (start > reg->data + reg->size)
+			continue;
+
+		if ((start >= reg->data && start < reg->data + reg->size) ||
+		    (end > reg->data && end < reg->data + reg->size)) {
+			debug("%s: new region already part of another\n",
+			      __func__);
+			return EFI_INVALID_PARAMETER;
+		}
+
+		if (start < reg->data && end < reg->data + reg->size) {
+			for (j = regs->num - 1; j >= i; j--)
+				memcpy(&regs->reg[j], &regs->reg[j + 1],
+				       sizeof(*reg));
+			break;
+		}
+	}
+
+	reg = &regs->reg[i];
+	reg->data = start;
+	reg->size = end - start;
+	regs->num++;
+
+	return EFI_SUCCESS;
+}
+#endif /* CONFIG_EFI_SECURE_BOOT */
#5 lore raw

PATCH v7 2/17 efi_loader: add signature verification functions

In reply to AKASHI Takahiro
Quoted 148 lines · AKASHI Takahiro

In this commit, implemented are a couple of helper functions which will be used to materialize variable authentication as well as image authentication in later patches.

---
 include/efi_api.h              |  87 +++++
 include/efi_loader.h           |  72 ++++
 lib/efi_loader/Makefile        |   1 +
 lib/efi_loader/efi_signature.c | 583 +++++++++++++++++++++++++++++++++
 4 files changed, 743 insertions(+)
 create mode 100644 lib/efi_loader/efi_signature.c
include/efi_api.h +87 -0
index 1c40ffc4f56c..77d6bf2660b9 100644
@@ -18,6 +18,7 @@
 
 #include <efi.h>
 #include <charset.h>
+#include <pe.h>
 
 #ifdef CONFIG_EFI_LOADER
 #include <asm/setjmp.h>
@@ -329,6 +330,10 @@ struct efi_runtime_services {
 	EFI_GUID(0x8be4df61, 0x93ca, 0x11d2, 0xaa, 0x0d, \
 		 0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c)
 
+#define EFI_IMAGE_SECURITY_DATABASE_GUID \
+	EFI_GUID(0xd719b2cb, 0x3d3a, 0x4596, 0xa3, 0xbc, \
+		 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f)
+
 #define EFI_FDT_GUID \
 	EFI_GUID(0xb1b621d5, 0xf19c, 0x41a5, \
 		 0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0)
@@ -1682,4 +1687,86 @@ struct efi_load_file_protocol {
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MIN 0x00001000
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MAX 0x00004000
 
+/* Certificate types in signature database */
+#define EFI_CERT_SHA256_GUID \
+	EFI_GUID(0xc1c41626, 0x504c, 0x4092, 0xac, 0xa9, \
+		 0x41, 0xf9, 0x36, 0x93, 0x43, 0x28)
+#define EFI_CERT_RSA2048_GUID \
+	EFI_GUID(0x3c5766e8, 0x269c, 0x4e34, 0xaa, 0x14, \
+		 0xed, 0x77, 0x6e, 0x85, 0xb3, 0xb6)
+#define EFI_CERT_X509_GUID \
+	EFI_GUID(0xa5c059a1, 0x94e4, 0x4aa7, 0x87, 0xb5, \
+		 0xab, 0x15, 0x5c, 0x2b, 0xf0, 0x72)
+#define EFI_CERT_X509_SHA256_GUID \
+	EFI_GUID(0x3bd2a492, 0x96c0, 0x4079, 0xb4, 0x20, \
+		 0xfc, 0xf9, 0x8e, 0xf1, 0x03, 0xed)
+#define EFI_CERT_TYPE_PKCS7_GUID \
+	EFI_GUID(0x4aafd29d, 0x68df, 0x49ee, 0x8a, 0xa9, \
+		 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7)
+
+/**
+ * win_certificate_uefi_guid - A certificate that encapsulates
+ * a GUID-specific signature
+ *
+ * @hdr:	Windows certificate header
+ * @cert_type:	Certificate type
+ * @cert_data:	Certificate data
+ */
+struct win_certificate_uefi_guid {
+	WIN_CERTIFICATE	hdr;
+	efi_guid_t	cert_type;
+	u8		cert_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_variable_authentication_2 - A time-based authentication method
+ * descriptor
+ *
+ * This structure describes an authentication information for
+ * a variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
+ * and should be included as part of a variable's value.
+ * Only EFI_CERT_TYPE_PKCS7_GUID is accepted.
+ *
+ * @time_stamp:	Descriptor's time stamp
+ * @auth_info:	Authentication info
+ */
+struct efi_variable_authentication_2 {
+	struct efi_time			 time_stamp;
+	struct win_certificate_uefi_guid auth_info;
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_data - A format of signature
+ *
+ * This structure describes a single signature in signature database.
+ *
+ * @signature_owner:	Signature owner
+ * @signature_data:	Signature data
+ */
+struct efi_signature_data {
+	efi_guid_t	signature_owner;
+	u8		signature_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_list - A format of signature database
+ *
+ * This structure describes a list of signatures with the same type.
+ * An authenticated variable's value is a concatenation of one or more
+ * efi_signature_list's.
+ *
+ * @signature_type:		Signature type
+ * @signature_list_size:	Size of signature list
+ * @signature_header_size:	Size of signature header
+ * @signature_size:		Size of signature
+ */
+struct efi_signature_list {
+	efi_guid_t	signature_type;
+	u32		signature_list_size;
+	u32		signature_header_size;
+	u32		signature_size;
+/*	u8		signature_header[signature_header_size]; */
+/*	struct efi_signature_data signatures[...][signature_size]; */
+} __attribute__((__packed__));
+
 #endif
include/efi_loader.h +6 -0
index 3f2792892f34..8cf85d2fb7e2 100644
@@ -26,6 +26,7 @@ static inline void *guidcpy(void *dst, const void *src)
 #if CONFIG_IS_ENABLED(EFI_LOADER)
 
 #include <linux/list.h>
+#include <linux/oid_registry.h>
 
 /* Maximum number of configuration tables */
 #define EFI_MAX_CONFIGURATION_TABLES 16
@@ -178,6 +179,11 @@ extern const efi_guid_t efi_guid_hii_config_routing_protocol;
 extern const efi_guid_t efi_guid_hii_config_access_protocol;
 extern const efi_guid_t efi_guid_hii_database_protocol;
 extern const efi_guid_t efi_guid_hii_string_protocol;
+/* GUIDs for authentication */
+extern const efi_guid_t efi_guid_image_security_database;
+extern const efi_guid_t efi_guid_sha256;
+extern const efi_guid_t efi_guid_cert_x509;
+extern const efi_guid_t efi_guid_cert_x509_sha256;
 
 /* GUID of RNG protocol */
 extern const efi_guid_t efi_guid_rng_protocol;

include/efi_loader.h void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data); · line 689

Quoted 4 lines
include/efi_loader.h +1 -0
@@ -680,6 +686,72 @@ void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data);
 unsigned long efi_serialize_load_option(struct efi_load_option *lo, u8 **data);
 efi_status_t efi_bootmgr_load(efi_handle_t *handle);
 
+#ifdef CONFIG_EFI_SECURE_BOOT

Why do we need an #ifdef here?

Quoted 657 lines
include/efi_loader.h +65 -0
+#include <image.h>
+
+/**
+ * efi_image_regions - A list of memory regions
+ *
+ * @max:	Maximum number of regions
+ * @num:	Number of regions
+ * @reg:	array of regions
+ */
+struct efi_image_regions {
+	int			max;
+	int			num;
+	struct image_region	reg[];
+};
+
+/**
+ * efi_sig_data - A decoded data of struct efi_signature_data
+ *
+ * This structure represents an internal form of signature in
+ * signature database. A listed list may represent a signature list.
+ *
+ * @next:	Pointer to next entry
+ * @onwer:	Signature owner
+ * @data:	Pointer to signature data
+ * @size:	Size of signature data
+ */
+struct efi_sig_data {
+	struct efi_sig_data *next;
+	efi_guid_t owner;
+	void *data;
+	size_t size;
+};
+
+/**
+ * efi_signature_store - A decoded data of signature database
+ *
+ * This structure represents an internal form of signature database.
+ *
+ * @next:		Pointer to next entry
+ * @sig_type:		Signature type
+ * @sig_data_list:	Pointer to signature list
+ */
+struct efi_signature_store {
+	struct efi_signature_store *next;
+	efi_guid_t sig_type;
+	struct efi_sig_data *sig_data_list;
+};
+
+struct x509_certificate;
+struct pkcs7_message;
+
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx);
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx);
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				  struct efi_signature_store *db,
+				  struct x509_certificate **cert);
+
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck);
+#endif /* CONFIG_EFI_SECURE_BOOT */
+
 #else /* CONFIG_IS_ENABLED(EFI_LOADER) */
 
 /* Without CONFIG_EFI_LOADER we don't have a runtime section, stub it out */
lib/efi_loader/Makefile +1 -0
index 9b3b70447336..eff3c25ec301 100644
@@ -44,3 +44,4 @@ obj-$(CONFIG_GENERATE_ACPI_TABLE) += efi_acpi.o
 obj-$(CONFIG_GENERATE_SMBIOS_TABLE) += efi_smbios.o
 obj-$(CONFIG_EFI_RNG_PROTOCOL) += efi_rng.o
 obj-$(CONFIG_EFI_LOAD_FILE2_INITRD) += efi_load_initrd.o
+obj-y += efi_signature.o
lib/efi_loader/efi_signature.c new file +573 -0
new file mode 100644
index 000000000000..23dac94c0593
@@ -0,0 +1,583 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2018 Patrick Wildt <[email protected]>
+ * Copyright (c) 2019 Linaro Limited, Author: AKASHI Takahiro
+ */
+
+#include <common.h>
+#include <charset.h>
+#include <efi_loader.h>
+#include <image.h>
+#include <hexdump.h>
+#include <malloc.h>
+#include <pe.h>
+#include <linux/compat.h>
+#include <linux/oid_registry.h>
+#include <u-boot/rsa.h>
+#include <u-boot/sha256.h>
+/*
+ * avoid duplicated inclusion:
+ * #include "../lib/crypto/x509_parser.h"
+ */
+#include "../lib/crypto/pkcs7_parser.h"
+
+const efi_guid_t efi_guid_image_security_database =
+		EFI_IMAGE_SECURITY_DATABASE_GUID;
+const efi_guid_t efi_guid_sha256 = EFI_CERT_SHA256_GUID;
+const efi_guid_t efi_guid_cert_rsa2048 = EFI_CERT_RSA2048_GUID;
+const efi_guid_t efi_guid_cert_x509 = EFI_CERT_X509_GUID;
+const efi_guid_t efi_guid_cert_x509_sha256 = EFI_CERT_X509_SHA256_GUID;
+
+#ifdef CONFIG_EFI_SECURE_BOOT
+
+/**
+ * efi_hash_regions - calculate a hash value
+ * @regs:	List of regions
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of @regs and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_regions(struct efi_image_regions *regs, void **hash,
+			     size_t *size)
+{
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	hash_calculate("sha256", regs->reg, regs->num, *hash);
+#ifdef DEBUG
+	debug("hash calculated:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_hash_msg_content - calculate a hash value of contentInfo
+ * @msg:	Signature
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of contentInfo in @msg and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_msg_content(struct pkcs7_message *msg, void **hash,
+				 size_t *size)
+{
+	struct image_region regtmp;
+
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		free(msg);
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	regtmp.data = msg->data;
+	regtmp.size = msg->data_len;
+
+	hash_calculate("sha256", &regtmp, 1, *hash);
+#ifdef DEBUG
+	debug("hash calculated based on contentInfo:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_signature_verify - verify a signature with a certificate
+ * @regs:		List of regions to be authenticated
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @cert:		x509 certificate
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by a certificate pointed to by @cert.
+ * @signed_info holds a signature, including a message digest which is to be
+ * compared with a hash value calculated from @regs.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static bool efi_signature_verify(struct efi_image_regions *regs,
+				 struct pkcs7_message *msg,
+				 struct pkcs7_signed_info *ps_info,
+				 struct x509_certificate *cert)
+{
+	struct image_sign_info info;
+	struct image_region regtmp[2];
+	void *hash;
+	size_t size;
+	char c;
+	bool verified;
+
+	debug("%s: Enter, %p, %p, %p(issuer: %s, subject: %s)\n", __func__,
+	      regs, ps_info, cert, cert->issuer, cert->subject);
+
+	verified = false;
+
+	memset(&info, '\0', sizeof(info));
+	info.padding = image_get_padding_algo("pkcs-1.5");
+	/*
+	 * Note: image_get_[checksum|crypto]_algo takes an string
+	 * argument like "<checksum>,<crypto>"
+	 * TODO: support other hash algorithms
+	 */
+	if (!strcmp(ps_info->sig->hash_algo, "sha1")) {
+		info.checksum = image_get_checksum_algo("sha1,rsa2048");
+		info.name = "sha1,rsa2048";
+	} else if (!strcmp(ps_info->sig->hash_algo, "sha256")) {
+		info.checksum = image_get_checksum_algo("sha256,rsa2048");
+		info.name = "sha256,rsa2048";
+	} else {
+		debug("unknown msg digest algo: %s\n", ps_info->sig->hash_algo);
+		goto out;
+	}
+	info.crypto = image_get_crypto_algo(info.name);
+
+	info.key = cert->pub->key;
+	info.keylen = cert->pub->keylen;
+
+	/* verify signature */
+	debug("%s: crypto: %s, signature len:%x\n", __func__,
+	      info.name, ps_info->sig->s_size);
+	if (ps_info->aa_set & (1UL << sinfo_has_message_digest)) {
+		debug("%s: RSA verify authentication attribute\n", __func__);
+		/*
+		 * NOTE: This path will be executed only for
+		 * PE image authentication
+		 */
+
+		/* check if hash matches digest first */
+		debug("checking msg digest first, len:0x%x\n",
+		      ps_info->msgdigest_len);
+
+#ifdef DEBUG
+		debug("hash in database:\n");
+		print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+			       ps_info->msgdigest, ps_info->msgdigest_len,
+			       false);
+#endif
+		/* against contentInfo first */
+		if ((msg->data && efi_hash_msg_content(msg, &hash, &size)) ||
+				/* for signed image */
+		    efi_hash_regions(regs, &hash, &size)) {
+				/* for authenticated variable */
+			if (ps_info->msgdigest_len != size ||
+			    memcmp(hash, ps_info->msgdigest, size)) {
+				debug("Digest doesn't match\n");
+				free(hash);
+				goto out;
+			}
+
+			free(hash);
+		} else {
+			debug("Digesting image failed\n");
+			goto out;
+		}
+
+		/* against digest */
+		c = 0x31;
+		regtmp[0].data = &c;
+		regtmp[0].size = 1;
+		regtmp[1].data = ps_info->authattrs;
+		regtmp[1].size = ps_info->authattrs_len;
+
+		if (!rsa_verify(&info, regtmp, 2,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	} else {
+		debug("%s: RSA verify content data\n", __func__);
+		/* against all data */
+		if (!rsa_verify(&info, regs->reg, regs->num,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_list - verify a signature with signature list
+ * @regs:		List of regions to be authenticated
+ * @msg:		Signature
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @siglist:		Signature list for certificates
+ * @valid_cert:		x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by signature list pointed to by @siglist.
+ * Signature database is a simple concatenation of one or more
+ * signature list(s).
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static
+bool efi_signature_verify_with_list(struct efi_image_regions *regs,
+				    struct pkcs7_message *msg,
+				    struct pkcs7_signed_info *signed_info,
+				    struct efi_signature_store *siglist,
+				    struct x509_certificate **valid_cert)
+{
+	struct x509_certificate *cert;
+	struct efi_sig_data *sig_data;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__,
+	      regs, signed_info, siglist, valid_cert);
+
+	if (!signed_info) {
+		void *hash;
+		size_t size;
+
+		debug("%s: unsigned image\n", __func__);
+		/*
+		 * verify based on calculated hash value
+		 * TODO: support other hash algorithms
+		 */
+		if (guidcmp(&siglist->sig_type, &efi_guid_sha256)) {
+			debug("Digest algorithm is not supported: %pUl\n",
+			      &siglist->sig_type);
+			goto out;
+		}
+
+		if (!efi_hash_regions(regs, &hash, &size)) {
+			debug("Digesting unsigned image failed\n");
+			goto out;
+		}
+
+		/* go through the list */
+		for (sig_data = siglist->sig_data_list; sig_data;
+		     sig_data = sig_data->next) {
+#ifdef DEBUG
+			debug("Msg digest in database:\n");
+			print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+				       sig_data->data, sig_data->size, false);
+#endif
+			if ((sig_data->size == size) &&
+			    !memcmp(sig_data->data, hash, size)) {
+				verified = true;
+				free(hash);
+				goto out;
+			}
+		}
+		free(hash);
+		goto out;
+	}
+
+	debug("%s: signed image\n", __func__);
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509)) {
+		debug("Signature type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* go through the list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/* TODO: support owner check based on policy */
+
+		cert = x509_cert_parse(sig_data->data, sig_data->size);
+		if (IS_ERR(cert)) {
+			debug("Parsing x509 certificate failed\n");
+			goto out;
+		}
+
+		verified = efi_signature_verify(regs, msg, signed_info, cert);
+
+		if (verified) {
+			if (valid_cert)
+				*valid_cert = cert;
+			else
+				x509_free_certificate(cert);
+			break;
+		}
+		x509_free_certificate(cert);
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_sigdb - verify a signature with db
+ * @regs:	List of regions to be authenticated
+ * @msg:	Signature
+ * @db:		Signature database for trusted certificates
+ * @cert:	x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @msg against image pointed to by @regs
+ * is verified by signature database pointed to by @db.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				     struct efi_signature_store *db,
+				     struct x509_certificate **cert)
+{
+	struct pkcs7_signed_info *info;
+	struct efi_signature_store *siglist;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__, regs, msg, db, cert);
+
+	if (!db)
+		goto out;
+
+	if (!db->sig_data_list)
+		goto out;
+
+	/* for unsigned image */
+	if (!msg) {
+		debug("%s: Verify unsigned image with db\n", __func__);
+		for (siglist = db; siglist; siglist = siglist->next)
+			if (efi_signature_verify_with_list(regs, NULL, NULL,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+
+		goto out;
+	}
+
+	/* for signed image or variable */
+	debug("%s: Verify signed image with db\n", __func__);
+	for (info = msg->signed_infos; info; info = info->next) {
+		debug("Signed Info: digest algo: %s, pkey algo: %s\n",
+		      info->sig->hash_algo, info->sig->pkey_algo);
+
+		for (siglist = db; siglist; siglist = siglist->next) {
+			if (efi_signature_verify_with_list(regs, msg, info,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+		}
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_search_siglist - search signature list for a certificate
+ * @cert:	x509 certificate
+ * @siglist:	Signature list
+ * @revoc_time:	Pointer to buffer for revocation time
+ *
+ * Search signature list pointed to by @siglist and find a certificate
+ * pointed to by @cert.
+ * If found, revocation time that is specified in signature database is
+ * returned in @revoc_time.
+ *
+ * Return:	true if certificate is found, false if not
+ */
+static bool efi_search_siglist(struct x509_certificate *cert,
+			       struct efi_signature_store *siglist,
+			       time64_t *revoc_time)
+{
+	struct image_region reg[1];
+	void *hash = NULL, *msg = NULL;
+	struct efi_sig_data *sig_data;
+	bool found = false;
+
+	/* can be null */
+	if (!siglist->sig_data_list)
+		return false;
+
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509_sha256)) {
+		/* TODO: other hash algos */
+		debug("Certificate's digest type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* calculate hash of TBSCertificate */
+	msg = calloc(1, SHA256_SUM_LEN);
+	if (!msg) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	hash = calloc(1, SHA256_SUM_LEN);
+	if (!hash) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	reg[0].data = cert->tbs;
+	reg[0].size = cert->tbs_size;
+	hash_calculate("sha256", reg, 1, msg);
+
+	/* go through signature list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/*
+		 * struct efi_cert_x509_sha256 {
+		 *	u8 tbs_hash[256/8];
+		 *	time64_t revocation_time;
+		 * };
+		 */
+		if ((sig_data->size == SHA256_SUM_LEN) &&
+		    !memcmp(sig_data->data, hash, SHA256_SUM_LEN)) {
+			memcpy(revoc_time, sig_data->data + SHA256_SUM_LEN,
+			       sizeof(*revoc_time));
+			found = true;
+			goto out;
+		}
+	}
+
+out:
+	free(hash);
+	free(msg);
+
+	return found;
+}
+
+/**
+ * efi_signature_verify_cert - verify a certificate with dbx
+ * @cert:	x509 certificate
+ * @dbx:	Signature database
+ *
+ * Search signature database pointed to by @dbx and find a certificate
+ * pointed to by @cert.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if a certificate is not rejected, false otherwise.
+ */
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx)
+{
+	struct efi_signature_store *siglist;
+	time64_t revoc_time;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, dbx, cert);
+
+	if (!cert)
+		return false;
+
+	for (siglist = dbx; siglist; siglist = siglist->next) {
+		if (efi_search_siglist(cert, siglist, &revoc_time)) {
+			/* TODO */
+			/* compare signing time with revocation time */
+
+			found = true;
+			break;
+		}
+	}
+
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_signature_verify_signers - verify signers' certificates with dbx
+ * @msg:	Signature
+ * @dbx:	Signature database
+ *
+ * Determine if any of signers' certificates in @msg may be verified
+ * by any of certificates in signature database pointed to by @dbx.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if none of certificates is rejected, false otherwise.
+ */
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx)
+{
+	struct pkcs7_signed_info *info;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, msg, dbx);
+
+	if (!msg)
+		goto out;
+
+	for (info = msg->signed_infos; info; info = info->next) {
+		if (info->signer &&
+		    !efi_signature_verify_cert(info->signer, dbx)) {
+			found = true;
+			goto out;
+		}
+	}
+out:
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_image_region_add - add an entry of region
+ * @regs:	Pointer to array of regions
+ * @start:	Start address of region
+ * @end:	End address of region
+ * @nocheck:	flag against overlapped regions
+ *
+ * Take one entry of region [@start, @end] and append it to the list
+ * pointed to by @regs. If @nocheck is false, overlapping among entries
+ * will be checked first.
+ *
+ * Return:	0 on success, status code (negative) on error
+ */
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck)
+{
+	struct image_region *reg;
+	int i, j;
+
+	if (regs->num >= regs->max) {
+		debug("%s: no more room for regions\n", __func__);
+		return EFI_OUT_OF_RESOURCES;
+	}
+
+	if (end < start)
+		return EFI_INVALID_PARAMETER;
+
+	for (i = 0; i < regs->num; i++) {
+		reg = &regs->reg[i];
+		if (nocheck)
+			continue;
+
+		if (start > reg->data + reg->size)
+			continue;
+
+		if ((start >= reg->data && start < reg->data + reg->size) ||
+		    (end > reg->data && end < reg->data + reg->size)) {
+			debug("%s: new region already part of another\n",
+			      __func__);
+			return EFI_INVALID_PARAMETER;
+		}
+
+		if (start < reg->data && end < reg->data + reg->size) {
+			for (j = regs->num - 1; j >= i; j--)
+				memcpy(&regs->reg[j], &regs->reg[j + 1],
+				       sizeof(*reg));
+			break;
+		}

lib/efi_loader/efi_signature.c line 583

Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10 -0
+	}
+
+	reg = &regs->reg[i];
+	reg->data = start;
+	reg->size = end - start;
+	regs->num++;
+
+	return EFI_SUCCESS;
+}
+#endif /* CONFIG_EFI_SECURE_BOOT */

If I define CONFIG_EFI_SECURE_BOOT I get a warning:

lib/efi_loader/efi_signature.c: In function ?efi_hash_regions?:
lib/efi_loader/efi_signature.c:52:2: warning: implicit declaration of function ?hash_calculate? [-Wimplicit-function-declaration]

   52 |  hash_calculate("sha256", regs->reg, regs->num, *hash);
      |  ^~~~~~~~~~~~~~

#include u-boot/rsa-checksum.h
seems to be missing in the code.

Best regards

Heinrich

#6 lore raw

PATCH v7 2/17 efi_loader: add signature verification functions

Quoted 829 lines · Heinrich Schuchardt
Quoted 148 lines · AKASHI Takahiro

In this commit, implemented are a couple of helper functions which will be used to materialize variable authentication as well as image authentication in later patches.

---
 include/efi_api.h              |  87 +++++
 include/efi_loader.h           |  72 ++++
 lib/efi_loader/Makefile        |   1 +
 lib/efi_loader/efi_signature.c | 583 +++++++++++++++++++++++++++++++++
 4 files changed, 743 insertions(+)
 create mode 100644 lib/efi_loader/efi_signature.c
include/efi_api.h +87 -0
index 1c40ffc4f56c..77d6bf2660b9 100644
@@ -18,6 +18,7 @@
 
 #include <efi.h>
 #include <charset.h>
+#include <pe.h>
 
 #ifdef CONFIG_EFI_LOADER
 #include <asm/setjmp.h>
@@ -329,6 +330,10 @@ struct efi_runtime_services {
 	EFI_GUID(0x8be4df61, 0x93ca, 0x11d2, 0xaa, 0x0d, \
 		 0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c)
 
+#define EFI_IMAGE_SECURITY_DATABASE_GUID \
+	EFI_GUID(0xd719b2cb, 0x3d3a, 0x4596, 0xa3, 0xbc, \
+		 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f)
+
 #define EFI_FDT_GUID \
 	EFI_GUID(0xb1b621d5, 0xf19c, 0x41a5, \
 		 0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0)
@@ -1682,4 +1687,86 @@ struct efi_load_file_protocol {
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MIN 0x00001000
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MAX 0x00004000
 
+/* Certificate types in signature database */
+#define EFI_CERT_SHA256_GUID \
+	EFI_GUID(0xc1c41626, 0x504c, 0x4092, 0xac, 0xa9, \
+		 0x41, 0xf9, 0x36, 0x93, 0x43, 0x28)
+#define EFI_CERT_RSA2048_GUID \
+	EFI_GUID(0x3c5766e8, 0x269c, 0x4e34, 0xaa, 0x14, \
+		 0xed, 0x77, 0x6e, 0x85, 0xb3, 0xb6)
+#define EFI_CERT_X509_GUID \
+	EFI_GUID(0xa5c059a1, 0x94e4, 0x4aa7, 0x87, 0xb5, \
+		 0xab, 0x15, 0x5c, 0x2b, 0xf0, 0x72)
+#define EFI_CERT_X509_SHA256_GUID \
+	EFI_GUID(0x3bd2a492, 0x96c0, 0x4079, 0xb4, 0x20, \
+		 0xfc, 0xf9, 0x8e, 0xf1, 0x03, 0xed)
+#define EFI_CERT_TYPE_PKCS7_GUID \
+	EFI_GUID(0x4aafd29d, 0x68df, 0x49ee, 0x8a, 0xa9, \
+		 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7)
+
+/**
+ * win_certificate_uefi_guid - A certificate that encapsulates
+ * a GUID-specific signature
+ *
+ * @hdr:	Windows certificate header
+ * @cert_type:	Certificate type
+ * @cert_data:	Certificate data
+ */
+struct win_certificate_uefi_guid {
+	WIN_CERTIFICATE	hdr;
+	efi_guid_t	cert_type;
+	u8		cert_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_variable_authentication_2 - A time-based authentication method
+ * descriptor
+ *
+ * This structure describes an authentication information for
+ * a variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
+ * and should be included as part of a variable's value.
+ * Only EFI_CERT_TYPE_PKCS7_GUID is accepted.
+ *
+ * @time_stamp:	Descriptor's time stamp
+ * @auth_info:	Authentication info
+ */
+struct efi_variable_authentication_2 {
+	struct efi_time			 time_stamp;
+	struct win_certificate_uefi_guid auth_info;
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_data - A format of signature
+ *
+ * This structure describes a single signature in signature database.
+ *
+ * @signature_owner:	Signature owner
+ * @signature_data:	Signature data
+ */
+struct efi_signature_data {
+	efi_guid_t	signature_owner;
+	u8		signature_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_list - A format of signature database
+ *
+ * This structure describes a list of signatures with the same type.
+ * An authenticated variable's value is a concatenation of one or more
+ * efi_signature_list's.
+ *
+ * @signature_type:		Signature type
+ * @signature_list_size:	Size of signature list
+ * @signature_header_size:	Size of signature header
+ * @signature_size:		Size of signature
+ */
+struct efi_signature_list {
+	efi_guid_t	signature_type;
+	u32		signature_list_size;
+	u32		signature_header_size;
+	u32		signature_size;
+/*	u8		signature_header[signature_header_size]; */
+/*	struct efi_signature_data signatures[...][signature_size]; */
+} __attribute__((__packed__));
+
 #endif
include/efi_loader.h +6 -0
index 3f2792892f34..8cf85d2fb7e2 100644
@@ -26,6 +26,7 @@ static inline void *guidcpy(void *dst, const void *src)
 #if CONFIG_IS_ENABLED(EFI_LOADER)
 
 #include <linux/list.h>
+#include <linux/oid_registry.h>
 
 /* Maximum number of configuration tables */
 #define EFI_MAX_CONFIGURATION_TABLES 16
@@ -178,6 +179,11 @@ extern const efi_guid_t efi_guid_hii_config_routing_protocol;
 extern const efi_guid_t efi_guid_hii_config_access_protocol;
 extern const efi_guid_t efi_guid_hii_database_protocol;
 extern const efi_guid_t efi_guid_hii_string_protocol;
+/* GUIDs for authentication */
+extern const efi_guid_t efi_guid_image_security_database;
+extern const efi_guid_t efi_guid_sha256;
+extern const efi_guid_t efi_guid_cert_x509;
+extern const efi_guid_t efi_guid_cert_x509_sha256;
 
 /* GUID of RNG protocol */
 extern const efi_guid_t efi_guid_rng_protocol;

include/efi_loader.h void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data); · line 689

Quoted 4 lines
include/efi_loader.h +1 -0
@@ -680,6 +686,72 @@ void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data);
 unsigned long efi_serialize_load_option(struct efi_load_option *lo, u8 **data);
 efi_status_t efi_bootmgr_load(efi_handle_t *handle);
 
+#ifdef CONFIG_EFI_SECURE_BOOT

Why do we need an #ifdef here?

Quoted 657 lines
include/efi_loader.h +65 -0
+#include <image.h>
+
+/**
+ * efi_image_regions - A list of memory regions
+ *
+ * @max:	Maximum number of regions
+ * @num:	Number of regions
+ * @reg:	array of regions
+ */
+struct efi_image_regions {
+	int			max;
+	int			num;
+	struct image_region	reg[];
+};
+
+/**
+ * efi_sig_data - A decoded data of struct efi_signature_data
+ *
+ * This structure represents an internal form of signature in
+ * signature database. A listed list may represent a signature list.
+ *
+ * @next:	Pointer to next entry
+ * @onwer:	Signature owner
+ * @data:	Pointer to signature data
+ * @size:	Size of signature data
+ */
+struct efi_sig_data {
+	struct efi_sig_data *next;
+	efi_guid_t owner;
+	void *data;
+	size_t size;
+};
+
+/**
+ * efi_signature_store - A decoded data of signature database
+ *
+ * This structure represents an internal form of signature database.
+ *
+ * @next:		Pointer to next entry
+ * @sig_type:		Signature type
+ * @sig_data_list:	Pointer to signature list
+ */
+struct efi_signature_store {
+	struct efi_signature_store *next;
+	efi_guid_t sig_type;
+	struct efi_sig_data *sig_data_list;
+};
+
+struct x509_certificate;
+struct pkcs7_message;
+
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx);
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx);
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				  struct efi_signature_store *db,
+				  struct x509_certificate **cert);
+
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck);
+#endif /* CONFIG_EFI_SECURE_BOOT */
+
 #else /* CONFIG_IS_ENABLED(EFI_LOADER) */
 
 /* Without CONFIG_EFI_LOADER we don't have a runtime section, stub it out */
lib/efi_loader/Makefile +1 -0
index 9b3b70447336..eff3c25ec301 100644
@@ -44,3 +44,4 @@ obj-$(CONFIG_GENERATE_ACPI_TABLE) += efi_acpi.o
 obj-$(CONFIG_GENERATE_SMBIOS_TABLE) += efi_smbios.o
 obj-$(CONFIG_EFI_RNG_PROTOCOL) += efi_rng.o
 obj-$(CONFIG_EFI_LOAD_FILE2_INITRD) += efi_load_initrd.o
+obj-y += efi_signature.o
lib/efi_loader/efi_signature.c new file +573 -0
new file mode 100644
index 000000000000..23dac94c0593
@@ -0,0 +1,583 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2018 Patrick Wildt <[email protected]>
+ * Copyright (c) 2019 Linaro Limited, Author: AKASHI Takahiro
+ */
+
+#include <common.h>
+#include <charset.h>
+#include <efi_loader.h>
+#include <image.h>
+#include <hexdump.h>
+#include <malloc.h>
+#include <pe.h>
+#include <linux/compat.h>
+#include <linux/oid_registry.h>
+#include <u-boot/rsa.h>
+#include <u-boot/sha256.h>
+/*
+ * avoid duplicated inclusion:
+ * #include "../lib/crypto/x509_parser.h"
+ */
+#include "../lib/crypto/pkcs7_parser.h"
+
+const efi_guid_t efi_guid_image_security_database =
+		EFI_IMAGE_SECURITY_DATABASE_GUID;
+const efi_guid_t efi_guid_sha256 = EFI_CERT_SHA256_GUID;
+const efi_guid_t efi_guid_cert_rsa2048 = EFI_CERT_RSA2048_GUID;
+const efi_guid_t efi_guid_cert_x509 = EFI_CERT_X509_GUID;
+const efi_guid_t efi_guid_cert_x509_sha256 = EFI_CERT_X509_SHA256_GUID;
+
+#ifdef CONFIG_EFI_SECURE_BOOT
+
+/**
+ * efi_hash_regions - calculate a hash value
+ * @regs:	List of regions
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of @regs and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_regions(struct efi_image_regions *regs, void **hash,
+			     size_t *size)
+{
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	hash_calculate("sha256", regs->reg, regs->num, *hash);
+#ifdef DEBUG
+	debug("hash calculated:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_hash_msg_content - calculate a hash value of contentInfo
+ * @msg:	Signature
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of contentInfo in @msg and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_msg_content(struct pkcs7_message *msg, void **hash,
+				 size_t *size)
+{
+	struct image_region regtmp;
+
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		free(msg);
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	regtmp.data = msg->data;
+	regtmp.size = msg->data_len;
+
+	hash_calculate("sha256", &regtmp, 1, *hash);
+#ifdef DEBUG
+	debug("hash calculated based on contentInfo:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_signature_verify - verify a signature with a certificate
+ * @regs:		List of regions to be authenticated
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @cert:		x509 certificate
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by a certificate pointed to by @cert.
+ * @signed_info holds a signature, including a message digest which is to be
+ * compared with a hash value calculated from @regs.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static bool efi_signature_verify(struct efi_image_regions *regs,
+				 struct pkcs7_message *msg,
+				 struct pkcs7_signed_info *ps_info,
+				 struct x509_certificate *cert)
+{
+	struct image_sign_info info;
+	struct image_region regtmp[2];
+	void *hash;
+	size_t size;
+	char c;
+	bool verified;
+
+	debug("%s: Enter, %p, %p, %p(issuer: %s, subject: %s)\n", __func__,
+	      regs, ps_info, cert, cert->issuer, cert->subject);
+
+	verified = false;
+
+	memset(&info, '\0', sizeof(info));
+	info.padding = image_get_padding_algo("pkcs-1.5");
+	/*
+	 * Note: image_get_[checksum|crypto]_algo takes an string
+	 * argument like "<checksum>,<crypto>"
+	 * TODO: support other hash algorithms
+	 */
+	if (!strcmp(ps_info->sig->hash_algo, "sha1")) {
+		info.checksum = image_get_checksum_algo("sha1,rsa2048");
+		info.name = "sha1,rsa2048";
+	} else if (!strcmp(ps_info->sig->hash_algo, "sha256")) {
+		info.checksum = image_get_checksum_algo("sha256,rsa2048");
+		info.name = "sha256,rsa2048";
+	} else {
+		debug("unknown msg digest algo: %s\n", ps_info->sig->hash_algo);
+		goto out;
+	}
+	info.crypto = image_get_crypto_algo(info.name);
+
+	info.key = cert->pub->key;
+	info.keylen = cert->pub->keylen;
+
+	/* verify signature */
+	debug("%s: crypto: %s, signature len:%x\n", __func__,
+	      info.name, ps_info->sig->s_size);
+	if (ps_info->aa_set & (1UL << sinfo_has_message_digest)) {
+		debug("%s: RSA verify authentication attribute\n", __func__);
+		/*
+		 * NOTE: This path will be executed only for
+		 * PE image authentication
+		 */
+
+		/* check if hash matches digest first */
+		debug("checking msg digest first, len:0x%x\n",
+		      ps_info->msgdigest_len);
+
+#ifdef DEBUG
+		debug("hash in database:\n");
+		print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+			       ps_info->msgdigest, ps_info->msgdigest_len,
+			       false);
+#endif
+		/* against contentInfo first */
+		if ((msg->data && efi_hash_msg_content(msg, &hash, &size)) ||
+				/* for signed image */
+		    efi_hash_regions(regs, &hash, &size)) {
+				/* for authenticated variable */
+			if (ps_info->msgdigest_len != size ||
+			    memcmp(hash, ps_info->msgdigest, size)) {
+				debug("Digest doesn't match\n");
+				free(hash);
+				goto out;
+			}
+
+			free(hash);
+		} else {
+			debug("Digesting image failed\n");
+			goto out;
+		}
+
+		/* against digest */
+		c = 0x31;
+		regtmp[0].data = &c;
+		regtmp[0].size = 1;
+		regtmp[1].data = ps_info->authattrs;
+		regtmp[1].size = ps_info->authattrs_len;
+
+		if (!rsa_verify(&info, regtmp, 2,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	} else {
+		debug("%s: RSA verify content data\n", __func__);
+		/* against all data */
+		if (!rsa_verify(&info, regs->reg, regs->num,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_list - verify a signature with signature list
+ * @regs:		List of regions to be authenticated
+ * @msg:		Signature
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @siglist:		Signature list for certificates
+ * @valid_cert:		x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by signature list pointed to by @siglist.
+ * Signature database is a simple concatenation of one or more
+ * signature list(s).
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static
+bool efi_signature_verify_with_list(struct efi_image_regions *regs,
+				    struct pkcs7_message *msg,
+				    struct pkcs7_signed_info *signed_info,
+				    struct efi_signature_store *siglist,
+				    struct x509_certificate **valid_cert)
+{
+	struct x509_certificate *cert;
+	struct efi_sig_data *sig_data;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__,
+	      regs, signed_info, siglist, valid_cert);
+
+	if (!signed_info) {
+		void *hash;
+		size_t size;
+
+		debug("%s: unsigned image\n", __func__);
+		/*
+		 * verify based on calculated hash value
+		 * TODO: support other hash algorithms
+		 */
+		if (guidcmp(&siglist->sig_type, &efi_guid_sha256)) {
+			debug("Digest algorithm is not supported: %pUl\n",
+			      &siglist->sig_type);
+			goto out;
+		}
+
+		if (!efi_hash_regions(regs, &hash, &size)) {
+			debug("Digesting unsigned image failed\n");
+			goto out;
+		}
+
+		/* go through the list */
+		for (sig_data = siglist->sig_data_list; sig_data;
+		     sig_data = sig_data->next) {
+#ifdef DEBUG
+			debug("Msg digest in database:\n");
+			print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+				       sig_data->data, sig_data->size, false);
+#endif
+			if ((sig_data->size == size) &&
+			    !memcmp(sig_data->data, hash, size)) {
+				verified = true;
+				free(hash);
+				goto out;
+			}
+		}
+		free(hash);
+		goto out;
+	}
+
+	debug("%s: signed image\n", __func__);
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509)) {
+		debug("Signature type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* go through the list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/* TODO: support owner check based on policy */
+
+		cert = x509_cert_parse(sig_data->data, sig_data->size);
+		if (IS_ERR(cert)) {
+			debug("Parsing x509 certificate failed\n");
+			goto out;
+		}
+
+		verified = efi_signature_verify(regs, msg, signed_info, cert);
+
+		if (verified) {
+			if (valid_cert)
+				*valid_cert = cert;
+			else
+				x509_free_certificate(cert);
+			break;
+		}
+		x509_free_certificate(cert);
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_sigdb - verify a signature with db
+ * @regs:	List of regions to be authenticated
+ * @msg:	Signature
+ * @db:		Signature database for trusted certificates
+ * @cert:	x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @msg against image pointed to by @regs
+ * is verified by signature database pointed to by @db.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				     struct efi_signature_store *db,
+				     struct x509_certificate **cert)
+{
+	struct pkcs7_signed_info *info;
+	struct efi_signature_store *siglist;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__, regs, msg, db, cert);
+
+	if (!db)
+		goto out;
+
+	if (!db->sig_data_list)
+		goto out;
+
+	/* for unsigned image */
+	if (!msg) {
+		debug("%s: Verify unsigned image with db\n", __func__);
+		for (siglist = db; siglist; siglist = siglist->next)
+			if (efi_signature_verify_with_list(regs, NULL, NULL,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+
+		goto out;
+	}
+
+	/* for signed image or variable */
+	debug("%s: Verify signed image with db\n", __func__);
+	for (info = msg->signed_infos; info; info = info->next) {
+		debug("Signed Info: digest algo: %s, pkey algo: %s\n",
+		      info->sig->hash_algo, info->sig->pkey_algo);
+
+		for (siglist = db; siglist; siglist = siglist->next) {
+			if (efi_signature_verify_with_list(regs, msg, info,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+		}
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_search_siglist - search signature list for a certificate
+ * @cert:	x509 certificate
+ * @siglist:	Signature list
+ * @revoc_time:	Pointer to buffer for revocation time
+ *
+ * Search signature list pointed to by @siglist and find a certificate
+ * pointed to by @cert.
+ * If found, revocation time that is specified in signature database is
+ * returned in @revoc_time.
+ *
+ * Return:	true if certificate is found, false if not
+ */
+static bool efi_search_siglist(struct x509_certificate *cert,
+			       struct efi_signature_store *siglist,
+			       time64_t *revoc_time)
+{
+	struct image_region reg[1];
+	void *hash = NULL, *msg = NULL;
+	struct efi_sig_data *sig_data;
+	bool found = false;
+
+	/* can be null */
+	if (!siglist->sig_data_list)
+		return false;
+
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509_sha256)) {
+		/* TODO: other hash algos */
+		debug("Certificate's digest type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* calculate hash of TBSCertificate */
+	msg = calloc(1, SHA256_SUM_LEN);
+	if (!msg) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	hash = calloc(1, SHA256_SUM_LEN);
+	if (!hash) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	reg[0].data = cert->tbs;
+	reg[0].size = cert->tbs_size;
+	hash_calculate("sha256", reg, 1, msg);
+
+	/* go through signature list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/*
+		 * struct efi_cert_x509_sha256 {
+		 *	u8 tbs_hash[256/8];
+		 *	time64_t revocation_time;
+		 * };
+		 */
+		if ((sig_data->size == SHA256_SUM_LEN) &&
+		    !memcmp(sig_data->data, hash, SHA256_SUM_LEN)) {
+			memcpy(revoc_time, sig_data->data + SHA256_SUM_LEN,
+			       sizeof(*revoc_time));
+			found = true;
+			goto out;
+		}
+	}
+
+out:
+	free(hash);
+	free(msg);
+
+	return found;
+}
+
+/**
+ * efi_signature_verify_cert - verify a certificate with dbx
+ * @cert:	x509 certificate
+ * @dbx:	Signature database
+ *
+ * Search signature database pointed to by @dbx and find a certificate
+ * pointed to by @cert.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if a certificate is not rejected, false otherwise.
+ */
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx)
+{
+	struct efi_signature_store *siglist;
+	time64_t revoc_time;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, dbx, cert);
+
+	if (!cert)
+		return false;
+
+	for (siglist = dbx; siglist; siglist = siglist->next) {
+		if (efi_search_siglist(cert, siglist, &revoc_time)) {
+			/* TODO */
+			/* compare signing time with revocation time */
+
+			found = true;
+			break;
+		}
+	}
+
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_signature_verify_signers - verify signers' certificates with dbx
+ * @msg:	Signature
+ * @dbx:	Signature database
+ *
+ * Determine if any of signers' certificates in @msg may be verified
+ * by any of certificates in signature database pointed to by @dbx.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if none of certificates is rejected, false otherwise.
+ */
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx)
+{
+	struct pkcs7_signed_info *info;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, msg, dbx);
+
+	if (!msg)
+		goto out;
+
+	for (info = msg->signed_infos; info; info = info->next) {
+		if (info->signer &&
+		    !efi_signature_verify_cert(info->signer, dbx)) {
+			found = true;
+			goto out;
+		}
+	}
+out:
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_image_region_add - add an entry of region
+ * @regs:	Pointer to array of regions
+ * @start:	Start address of region
+ * @end:	End address of region
+ * @nocheck:	flag against overlapped regions
+ *
+ * Take one entry of region [@start, @end] and append it to the list
+ * pointed to by @regs. If @nocheck is false, overlapping among entries
+ * will be checked first.
+ *
+ * Return:	0 on success, status code (negative) on error
+ */
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck)
+{
+	struct image_region *reg;
+	int i, j;
+
+	if (regs->num >= regs->max) {
+		debug("%s: no more room for regions\n", __func__);
+		return EFI_OUT_OF_RESOURCES;
+	}
+
+	if (end < start)
+		return EFI_INVALID_PARAMETER;
+
+	for (i = 0; i < regs->num; i++) {
+		reg = &regs->reg[i];
+		if (nocheck)
+			continue;
+
+		if (start > reg->data + reg->size)
+			continue;
+
+		if ((start >= reg->data && start < reg->data + reg->size) ||
+		    (end > reg->data && end < reg->data + reg->size)) {
+			debug("%s: new region already part of another\n",
+			      __func__);
+			return EFI_INVALID_PARAMETER;
+		}
+
+		if (start < reg->data && end < reg->data + reg->size) {
+			for (j = regs->num - 1; j >= i; j--)
+				memcpy(&regs->reg[j], &regs->reg[j + 1],
+				       sizeof(*reg));
+			break;
+		}

lib/efi_loader/efi_signature.c line 583

Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10 -0
+	}
+
+	reg = &regs->reg[i];
+	reg->data = start;
+	reg->size = end - start;
+	regs->num++;
+
+	return EFI_SUCCESS;
+}
+#endif /* CONFIG_EFI_SECURE_BOOT */

If I define CONFIG_EFI_SECURE_BOOT I get a warning:

lib/efi_loader/efi_signature.c: In function ?efi_hash_regions?:
lib/efi_loader/efi_signature.c:52:2: warning: implicit declaration of function ?hash_calculate? [-Wimplicit-function-declaration]

Quoted 6 lines
   52 |  hash_calculate("sha256", regs->reg, regs->num, *hash);
      |  ^~~~~~~~~~~~~~

#include u-boot/rsa-checksum.h
seems to be missing in the code.

The problem only occurs with an old version of your patch. Sorry.

Quoted 5 lines

Best regards

Heinrich

#7 lore raw

PATCH v7 2/17 efi_loader: add signature verification functions

In reply to AKASHI Takahiro
Quoted 363 lines · AKASHI Takahiro

In this commit, implemented are a couple of helper functions which will be used to materialize variable authentication as well as image authentication in later patches.

---
 include/efi_api.h              |  87 +++++
 include/efi_loader.h           |  72 ++++
 lib/efi_loader/Makefile        |   1 +
 lib/efi_loader/efi_signature.c | 583 +++++++++++++++++++++++++++++++++
 4 files changed, 743 insertions(+)
 create mode 100644 lib/efi_loader/efi_signature.c
include/efi_api.h +87 -0
index 1c40ffc4f56c..77d6bf2660b9 100644
@@ -18,6 +18,7 @@
 
 #include <efi.h>
 #include <charset.h>
+#include <pe.h>
 
 #ifdef CONFIG_EFI_LOADER
 #include <asm/setjmp.h>
@@ -329,6 +330,10 @@ struct efi_runtime_services {
 	EFI_GUID(0x8be4df61, 0x93ca, 0x11d2, 0xaa, 0x0d, \
 		 0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c)
 
+#define EFI_IMAGE_SECURITY_DATABASE_GUID \
+	EFI_GUID(0xd719b2cb, 0x3d3a, 0x4596, 0xa3, 0xbc, \
+		 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f)
+
 #define EFI_FDT_GUID \
 	EFI_GUID(0xb1b621d5, 0xf19c, 0x41a5, \
 		 0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0)
@@ -1682,4 +1687,86 @@ struct efi_load_file_protocol {
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MIN 0x00001000
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MAX 0x00004000
 
+/* Certificate types in signature database */
+#define EFI_CERT_SHA256_GUID \
+	EFI_GUID(0xc1c41626, 0x504c, 0x4092, 0xac, 0xa9, \
+		 0x41, 0xf9, 0x36, 0x93, 0x43, 0x28)
+#define EFI_CERT_RSA2048_GUID \
+	EFI_GUID(0x3c5766e8, 0x269c, 0x4e34, 0xaa, 0x14, \
+		 0xed, 0x77, 0x6e, 0x85, 0xb3, 0xb6)
+#define EFI_CERT_X509_GUID \
+	EFI_GUID(0xa5c059a1, 0x94e4, 0x4aa7, 0x87, 0xb5, \
+		 0xab, 0x15, 0x5c, 0x2b, 0xf0, 0x72)
+#define EFI_CERT_X509_SHA256_GUID \
+	EFI_GUID(0x3bd2a492, 0x96c0, 0x4079, 0xb4, 0x20, \
+		 0xfc, 0xf9, 0x8e, 0xf1, 0x03, 0xed)
+#define EFI_CERT_TYPE_PKCS7_GUID \
+	EFI_GUID(0x4aafd29d, 0x68df, 0x49ee, 0x8a, 0xa9, \
+		 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7)
+
+/**
+ * win_certificate_uefi_guid - A certificate that encapsulates
+ * a GUID-specific signature
+ *
+ * @hdr:	Windows certificate header
+ * @cert_type:	Certificate type
+ * @cert_data:	Certificate data
+ */
+struct win_certificate_uefi_guid {
+	WIN_CERTIFICATE	hdr;
+	efi_guid_t	cert_type;
+	u8		cert_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_variable_authentication_2 - A time-based authentication method
+ * descriptor
+ *
+ * This structure describes an authentication information for
+ * a variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
+ * and should be included as part of a variable's value.
+ * Only EFI_CERT_TYPE_PKCS7_GUID is accepted.
+ *
+ * @time_stamp:	Descriptor's time stamp
+ * @auth_info:	Authentication info
+ */
+struct efi_variable_authentication_2 {
+	struct efi_time			 time_stamp;
+	struct win_certificate_uefi_guid auth_info;
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_data - A format of signature
+ *
+ * This structure describes a single signature in signature database.
+ *
+ * @signature_owner:	Signature owner
+ * @signature_data:	Signature data
+ */
+struct efi_signature_data {
+	efi_guid_t	signature_owner;
+	u8		signature_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_list - A format of signature database
+ *
+ * This structure describes a list of signatures with the same type.
+ * An authenticated variable's value is a concatenation of one or more
+ * efi_signature_list's.
+ *
+ * @signature_type:		Signature type
+ * @signature_list_size:	Size of signature list
+ * @signature_header_size:	Size of signature header
+ * @signature_size:		Size of signature
+ */
+struct efi_signature_list {
+	efi_guid_t	signature_type;
+	u32		signature_list_size;
+	u32		signature_header_size;
+	u32		signature_size;
+/*	u8		signature_header[signature_header_size]; */
+/*	struct efi_signature_data signatures[...][signature_size]; */
+} __attribute__((__packed__));
+
 #endif
include/efi_loader.h +72 -0
index 3f2792892f34..8cf85d2fb7e2 100644
@@ -26,6 +26,7 @@ static inline void *guidcpy(void *dst, const void *src)
 #if CONFIG_IS_ENABLED(EFI_LOADER)
 
 #include <linux/list.h>
+#include <linux/oid_registry.h>
 
 /* Maximum number of configuration tables */
 #define EFI_MAX_CONFIGURATION_TABLES 16
@@ -178,6 +179,11 @@ extern const efi_guid_t efi_guid_hii_config_routing_protocol;
 extern const efi_guid_t efi_guid_hii_config_access_protocol;
 extern const efi_guid_t efi_guid_hii_database_protocol;
 extern const efi_guid_t efi_guid_hii_string_protocol;
+/* GUIDs for authentication */
+extern const efi_guid_t efi_guid_image_security_database;
+extern const efi_guid_t efi_guid_sha256;
+extern const efi_guid_t efi_guid_cert_x509;
+extern const efi_guid_t efi_guid_cert_x509_sha256;
 
 /* GUID of RNG protocol */
 extern const efi_guid_t efi_guid_rng_protocol;
@@ -680,6 +686,72 @@ void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data);
 unsigned long efi_serialize_load_option(struct efi_load_option *lo, u8 **data);
 efi_status_t efi_bootmgr_load(efi_handle_t *handle);
 
+#ifdef CONFIG_EFI_SECURE_BOOT
+#include <image.h>
+
+/**
+ * efi_image_regions - A list of memory regions
+ *
+ * @max:	Maximum number of regions
+ * @num:	Number of regions
+ * @reg:	array of regions
+ */
+struct efi_image_regions {
+	int			max;
+	int			num;
+	struct image_region	reg[];
+};
+
+/**
+ * efi_sig_data - A decoded data of struct efi_signature_data
+ *
+ * This structure represents an internal form of signature in
+ * signature database. A listed list may represent a signature list.
+ *
+ * @next:	Pointer to next entry
+ * @onwer:	Signature owner
+ * @data:	Pointer to signature data
+ * @size:	Size of signature data
+ */
+struct efi_sig_data {
+	struct efi_sig_data *next;
+	efi_guid_t owner;
+	void *data;
+	size_t size;
+};
+
+/**
+ * efi_signature_store - A decoded data of signature database
+ *
+ * This structure represents an internal form of signature database.
+ *
+ * @next:		Pointer to next entry
+ * @sig_type:		Signature type
+ * @sig_data_list:	Pointer to signature list
+ */
+struct efi_signature_store {
+	struct efi_signature_store *next;
+	efi_guid_t sig_type;
+	struct efi_sig_data *sig_data_list;
+};
+
+struct x509_certificate;
+struct pkcs7_message;
+
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx);
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx);
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				  struct efi_signature_store *db,
+				  struct x509_certificate **cert);
+
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck);
+#endif /* CONFIG_EFI_SECURE_BOOT */
+
 #else /* CONFIG_IS_ENABLED(EFI_LOADER) */
 
 /* Without CONFIG_EFI_LOADER we don't have a runtime section, stub it out */
lib/efi_loader/Makefile +1 -0
index 9b3b70447336..eff3c25ec301 100644
@@ -44,3 +44,4 @@ obj-$(CONFIG_GENERATE_ACPI_TABLE) += efi_acpi.o
 obj-$(CONFIG_GENERATE_SMBIOS_TABLE) += efi_smbios.o
 obj-$(CONFIG_EFI_RNG_PROTOCOL) += efi_rng.o
 obj-$(CONFIG_EFI_LOAD_FILE2_INITRD) += efi_load_initrd.o
+obj-y += efi_signature.o
lib/efi_loader/efi_signature.c new file +128 -0
new file mode 100644
index 000000000000..23dac94c0593
@@ -0,0 +1,583 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2018 Patrick Wildt <[email protected]>
+ * Copyright (c) 2019 Linaro Limited, Author: AKASHI Takahiro
+ */
+
+#include <common.h>
+#include <charset.h>
+#include <efi_loader.h>
+#include <image.h>
+#include <hexdump.h>
+#include <malloc.h>
+#include <pe.h>
+#include <linux/compat.h>
+#include <linux/oid_registry.h>
+#include <u-boot/rsa.h>
+#include <u-boot/sha256.h>
+/*
+ * avoid duplicated inclusion:
+ * #include "../lib/crypto/x509_parser.h"
+ */
+#include "../lib/crypto/pkcs7_parser.h"
+
+const efi_guid_t efi_guid_image_security_database =
+		EFI_IMAGE_SECURITY_DATABASE_GUID;
+const efi_guid_t efi_guid_sha256 = EFI_CERT_SHA256_GUID;
+const efi_guid_t efi_guid_cert_rsa2048 = EFI_CERT_RSA2048_GUID;
+const efi_guid_t efi_guid_cert_x509 = EFI_CERT_X509_GUID;
+const efi_guid_t efi_guid_cert_x509_sha256 = EFI_CERT_X509_SHA256_GUID;
+
+#ifdef CONFIG_EFI_SECURE_BOOT
+
+/**
+ * efi_hash_regions - calculate a hash value
+ * @regs:	List of regions
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of @regs and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_regions(struct efi_image_regions *regs, void **hash,
+			     size_t *size)
+{
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	hash_calculate("sha256", regs->reg, regs->num, *hash);
+#ifdef DEBUG
+	debug("hash calculated:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_hash_msg_content - calculate a hash value of contentInfo
+ * @msg:	Signature
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of contentInfo in @msg and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_msg_content(struct pkcs7_message *msg, void **hash,
+				 size_t *size)
+{
+	struct image_region regtmp;
+
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		free(msg);
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	regtmp.data = msg->data;
+	regtmp.size = msg->data_len;
+
+	hash_calculate("sha256", &regtmp, 1, *hash);
+#ifdef DEBUG
+	debug("hash calculated based on contentInfo:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_signature_verify - verify a signature with a certificate
+ * @regs:		List of regions to be authenticated
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @cert:		x509 certificate
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by a certificate pointed to by @cert.
+ * @signed_info holds a signature, including a message digest which is to be
+ * compared with a hash value calculated from @regs.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static bool efi_signature_verify(struct efi_image_regions *regs,
+				 struct pkcs7_message *msg,
+				 struct pkcs7_signed_info *ps_info,
+				 struct x509_certificate *cert)
+{
+	struct image_sign_info info;
+	struct image_region regtmp[2];
+	void *hash;
+	size_t size;
+	char c;
+	bool verified;
+
+	debug("%s: Enter, %p, %p, %p(issuer: %s, subject: %s)\n", __func__,
+	      regs, ps_info, cert, cert->issuer, cert->subject);
+

lib/efi_loader/efi_signature.c line 138

Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10 -0
+	verified = false;
+
+	memset(&info, '\0', sizeof(info));
+	info.padding = image_get_padding_algo("pkcs-1.5");
+	/*
+	 * Note: image_get_[checksum|crypto]_algo takes an string
+	 * argument like "<checksum>,<crypto>"
+	 * TODO: support other hash algorithms
+	 */
+	if (!strcmp(ps_info->sig->hash_algo, "sha1")) {

There is a call
efi_signature_verify_with_list(regs, NULL, NULL, siglist, cert) So ps_info may be NULL

Quoted 8 lines
lib/efi_loader/efi_signature.c new file +8 -0
+		info.checksum = image_get_checksum_algo("sha1,rsa2048");
+		info.name = "sha1,rsa2048";
+	} else if (!strcmp(ps_info->sig->hash_algo, "sha256")) {
+		info.checksum = image_get_checksum_algo("sha256,rsa2048");
+		info.name = "sha256,rsa2048";
+	} else {
+		debug("unknown msg digest algo: %s\n", ps_info->sig->hash_algo);
+		goto out;

lib/efi_loader/efi_signature.c line 156

Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10 -0
+	}
+	info.crypto = image_get_crypto_algo(info.name);
+
+	info.key = cert->pub->key;
+	info.keylen = cert->pub->keylen;
+
+	/* verify signature */
+	debug("%s: crypto: %s, signature len:%x\n", __func__,
+	      info.name, ps_info->sig->s_size);
+	if (ps_info->aa_set & (1UL << sinfo_has_message_digest)) {

There is a call
efi_signature_verify_with_list(regs, NULL, NULL, siglist, cert) So ps_info may be NULL

Quoted 9 lines
lib/efi_loader/efi_signature.c new file +9 -0
+		debug("%s: RSA verify authentication attribute\n", __func__);
+		/*
+		 * NOTE: This path will be executed only for
+		 * PE image authentication
+		 */
+
+		/* check if hash matches digest first */
+		debug("checking msg digest first, len:0x%x\n",
+		      ps_info->msgdigest_len);

lib/efi_loader/efi_signature.c line 175

Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10 -0
+
+#ifdef DEBUG
+		debug("hash in database:\n");
+		print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+			       ps_info->msgdigest, ps_info->msgdigest_len,
+			       false);
+#endif
+		/* against contentInfo first */
+		if ((msg->data && efi_hash_msg_content(msg, &hash, &size)) ||
+				/* for signed image */

There is a call
efi_signature_verify_with_list(regs, NULL, NULL, siglist, cert) So msg may be NULL.

Either avoid the call will NULL or check the parameters before dereferencing.

Please, provide a follow up patch.

I used cppcheck to identify this problem.

Best regards

Heinrich

Quoted 409 lines
lib/efi_loader/efi_signature.c new file +408 -0
+		    efi_hash_regions(regs, &hash, &size)) {
+				/* for authenticated variable */
+			if (ps_info->msgdigest_len != size ||
+			    memcmp(hash, ps_info->msgdigest, size)) {
+				debug("Digest doesn't match\n");
+				free(hash);
+				goto out;
+			}
+
+			free(hash);
+		} else {
+			debug("Digesting image failed\n");
+			goto out;
+		}
+
+		/* against digest */
+		c = 0x31;
+		regtmp[0].data = &c;
+		regtmp[0].size = 1;
+		regtmp[1].data = ps_info->authattrs;
+		regtmp[1].size = ps_info->authattrs_len;
+
+		if (!rsa_verify(&info, regtmp, 2,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	} else {
+		debug("%s: RSA verify content data\n", __func__);
+		/* against all data */
+		if (!rsa_verify(&info, regs->reg, regs->num,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_list - verify a signature with signature list
+ * @regs:		List of regions to be authenticated
+ * @msg:		Signature
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @siglist:		Signature list for certificates
+ * @valid_cert:		x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by signature list pointed to by @siglist.
+ * Signature database is a simple concatenation of one or more
+ * signature list(s).
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static
+bool efi_signature_verify_with_list(struct efi_image_regions *regs,
+				    struct pkcs7_message *msg,
+				    struct pkcs7_signed_info *signed_info,
+				    struct efi_signature_store *siglist,
+				    struct x509_certificate **valid_cert)
+{
+	struct x509_certificate *cert;
+	struct efi_sig_data *sig_data;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__,
+	      regs, signed_info, siglist, valid_cert);
+
+	if (!signed_info) {
+		void *hash;
+		size_t size;
+
+		debug("%s: unsigned image\n", __func__);
+		/*
+		 * verify based on calculated hash value
+		 * TODO: support other hash algorithms
+		 */
+		if (guidcmp(&siglist->sig_type, &efi_guid_sha256)) {
+			debug("Digest algorithm is not supported: %pUl\n",
+			      &siglist->sig_type);
+			goto out;
+		}
+
+		if (!efi_hash_regions(regs, &hash, &size)) {
+			debug("Digesting unsigned image failed\n");
+			goto out;
+		}
+
+		/* go through the list */
+		for (sig_data = siglist->sig_data_list; sig_data;
+		     sig_data = sig_data->next) {
+#ifdef DEBUG
+			debug("Msg digest in database:\n");
+			print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+				       sig_data->data, sig_data->size, false);
+#endif
+			if ((sig_data->size == size) &&
+			    !memcmp(sig_data->data, hash, size)) {
+				verified = true;
+				free(hash);
+				goto out;
+			}
+		}
+		free(hash);
+		goto out;
+	}
+
+	debug("%s: signed image\n", __func__);
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509)) {
+		debug("Signature type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* go through the list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/* TODO: support owner check based on policy */
+
+		cert = x509_cert_parse(sig_data->data, sig_data->size);
+		if (IS_ERR(cert)) {
+			debug("Parsing x509 certificate failed\n");
+			goto out;
+		}
+
+		verified = efi_signature_verify(regs, msg, signed_info, cert);
+
+		if (verified) {
+			if (valid_cert)
+				*valid_cert = cert;
+			else
+				x509_free_certificate(cert);
+			break;
+		}
+		x509_free_certificate(cert);
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_sigdb - verify a signature with db
+ * @regs:	List of regions to be authenticated
+ * @msg:	Signature
+ * @db:		Signature database for trusted certificates
+ * @cert:	x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @msg against image pointed to by @regs
+ * is verified by signature database pointed to by @db.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				     struct efi_signature_store *db,
+				     struct x509_certificate **cert)
+{
+	struct pkcs7_signed_info *info;
+	struct efi_signature_store *siglist;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__, regs, msg, db, cert);
+
+	if (!db)
+		goto out;
+
+	if (!db->sig_data_list)
+		goto out;
+
+	/* for unsigned image */
+	if (!msg) {
+		debug("%s: Verify unsigned image with db\n", __func__);
+		for (siglist = db; siglist; siglist = siglist->next)
+			if (efi_signature_verify_with_list(regs, NULL, NULL,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+
+		goto out;
+	}
+
+	/* for signed image or variable */
+	debug("%s: Verify signed image with db\n", __func__);
+	for (info = msg->signed_infos; info; info = info->next) {
+		debug("Signed Info: digest algo: %s, pkey algo: %s\n",
+		      info->sig->hash_algo, info->sig->pkey_algo);
+
+		for (siglist = db; siglist; siglist = siglist->next) {
+			if (efi_signature_verify_with_list(regs, msg, info,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+		}
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_search_siglist - search signature list for a certificate
+ * @cert:	x509 certificate
+ * @siglist:	Signature list
+ * @revoc_time:	Pointer to buffer for revocation time
+ *
+ * Search signature list pointed to by @siglist and find a certificate
+ * pointed to by @cert.
+ * If found, revocation time that is specified in signature database is
+ * returned in @revoc_time.
+ *
+ * Return:	true if certificate is found, false if not
+ */
+static bool efi_search_siglist(struct x509_certificate *cert,
+			       struct efi_signature_store *siglist,
+			       time64_t *revoc_time)
+{
+	struct image_region reg[1];
+	void *hash = NULL, *msg = NULL;
+	struct efi_sig_data *sig_data;
+	bool found = false;
+
+	/* can be null */
+	if (!siglist->sig_data_list)
+		return false;
+
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509_sha256)) {
+		/* TODO: other hash algos */
+		debug("Certificate's digest type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* calculate hash of TBSCertificate */
+	msg = calloc(1, SHA256_SUM_LEN);
+	if (!msg) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	hash = calloc(1, SHA256_SUM_LEN);
+	if (!hash) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	reg[0].data = cert->tbs;
+	reg[0].size = cert->tbs_size;
+	hash_calculate("sha256", reg, 1, msg);
+
+	/* go through signature list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/*
+		 * struct efi_cert_x509_sha256 {
+		 *	u8 tbs_hash[256/8];
+		 *	time64_t revocation_time;
+		 * };
+		 */
+		if ((sig_data->size == SHA256_SUM_LEN) &&
+		    !memcmp(sig_data->data, hash, SHA256_SUM_LEN)) {
+			memcpy(revoc_time, sig_data->data + SHA256_SUM_LEN,
+			       sizeof(*revoc_time));
+			found = true;
+			goto out;
+		}
+	}
+
+out:
+	free(hash);
+	free(msg);
+
+	return found;
+}
+
+/**
+ * efi_signature_verify_cert - verify a certificate with dbx
+ * @cert:	x509 certificate
+ * @dbx:	Signature database
+ *
+ * Search signature database pointed to by @dbx and find a certificate
+ * pointed to by @cert.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if a certificate is not rejected, false otherwise.
+ */
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx)
+{
+	struct efi_signature_store *siglist;
+	time64_t revoc_time;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, dbx, cert);
+
+	if (!cert)
+		return false;
+
+	for (siglist = dbx; siglist; siglist = siglist->next) {
+		if (efi_search_siglist(cert, siglist, &revoc_time)) {
+			/* TODO */
+			/* compare signing time with revocation time */
+
+			found = true;
+			break;
+		}
+	}
+
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_signature_verify_signers - verify signers' certificates with dbx
+ * @msg:	Signature
+ * @dbx:	Signature database
+ *
+ * Determine if any of signers' certificates in @msg may be verified
+ * by any of certificates in signature database pointed to by @dbx.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if none of certificates is rejected, false otherwise.
+ */
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx)
+{
+	struct pkcs7_signed_info *info;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, msg, dbx);
+
+	if (!msg)
+		goto out;
+
+	for (info = msg->signed_infos; info; info = info->next) {
+		if (info->signer &&
+		    !efi_signature_verify_cert(info->signer, dbx)) {
+			found = true;
+			goto out;
+		}
+	}
+out:
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_image_region_add - add an entry of region
+ * @regs:	Pointer to array of regions
+ * @start:	Start address of region
+ * @end:	End address of region
+ * @nocheck:	flag against overlapped regions
+ *
+ * Take one entry of region [@start, @end] and append it to the list
+ * pointed to by @regs. If @nocheck is false, overlapping among entries
+ * will be checked first.
+ *
+ * Return:	0 on success, status code (negative) on error
+ */
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck)
+{
+	struct image_region *reg;
+	int i, j;
+
+	if (regs->num >= regs->max) {
+		debug("%s: no more room for regions\n", __func__);
+		return EFI_OUT_OF_RESOURCES;
+	}
+
+	if (end < start)
+		return EFI_INVALID_PARAMETER;
+
+	for (i = 0; i < regs->num; i++) {
+		reg = &regs->reg[i];
+		if (nocheck)
+			continue;
+
+		if (start > reg->data + reg->size)
+			continue;
+
+		if ((start >= reg->data && start < reg->data + reg->size) ||
+		    (end > reg->data && end < reg->data + reg->size)) {
+			debug("%s: new region already part of another\n",
+			      __func__);
+			return EFI_INVALID_PARAMETER;
+		}
+
+		if (start < reg->data && end < reg->data + reg->size) {
+			for (j = regs->num - 1; j >= i; j--)
+				memcpy(&regs->reg[j], &regs->reg[j + 1],
+				       sizeof(*reg));
+			break;
+		}
+	}
+
+	reg = &regs->reg[i];
+	reg->data = start;
+	reg->size = end - start;
+	regs->num++;
+
+	return EFI_SUCCESS;
+}
+#endif /* CONFIG_EFI_SECURE_BOOT */
#8 lore raw

PATCH v7 2/17 efi_loader: add signature verification functions

Heinrich,

Quoted 370 lines · Heinrich Schuchardt
Quoted 369 lines · AKASHI Takahiro

In this commit, implemented are a couple of helper functions which will be used to materialize variable authentication as well as image authentication in later patches.

---
 include/efi_api.h              |  87 +++++
 include/efi_loader.h           |  72 ++++
 lib/efi_loader/Makefile        |   1 +
 lib/efi_loader/efi_signature.c | 583 +++++++++++++++++++++++++++++++++
 4 files changed, 743 insertions(+)
 create mode 100644 lib/efi_loader/efi_signature.c
include/efi_api.h +87 -0
index 1c40ffc4f56c..77d6bf2660b9 100644
@@ -18,6 +18,7 @@
 
 #include <efi.h>
 #include <charset.h>
+#include <pe.h>
 
 #ifdef CONFIG_EFI_LOADER
 #include <asm/setjmp.h>
@@ -329,6 +330,10 @@ struct efi_runtime_services {
 	EFI_GUID(0x8be4df61, 0x93ca, 0x11d2, 0xaa, 0x0d, \
 		 0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c)
 
+#define EFI_IMAGE_SECURITY_DATABASE_GUID \
+	EFI_GUID(0xd719b2cb, 0x3d3a, 0x4596, 0xa3, 0xbc, \
+		 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f)
+
 #define EFI_FDT_GUID \
 	EFI_GUID(0xb1b621d5, 0xf19c, 0x41a5, \
 		 0x83, 0x0b, 0xd9, 0x15, 0x2c, 0x69, 0xaa, 0xe0)
@@ -1682,4 +1687,86 @@ struct efi_load_file_protocol {
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MIN 0x00001000
 #define LAST_ATTEMPT_STATUS_ERROR_UNSUCCESSFUL_VENDOR_RANGE_MAX 0x00004000
 
+/* Certificate types in signature database */
+#define EFI_CERT_SHA256_GUID \
+	EFI_GUID(0xc1c41626, 0x504c, 0x4092, 0xac, 0xa9, \
+		 0x41, 0xf9, 0x36, 0x93, 0x43, 0x28)
+#define EFI_CERT_RSA2048_GUID \
+	EFI_GUID(0x3c5766e8, 0x269c, 0x4e34, 0xaa, 0x14, \
+		 0xed, 0x77, 0x6e, 0x85, 0xb3, 0xb6)
+#define EFI_CERT_X509_GUID \
+	EFI_GUID(0xa5c059a1, 0x94e4, 0x4aa7, 0x87, 0xb5, \
+		 0xab, 0x15, 0x5c, 0x2b, 0xf0, 0x72)
+#define EFI_CERT_X509_SHA256_GUID \
+	EFI_GUID(0x3bd2a492, 0x96c0, 0x4079, 0xb4, 0x20, \
+		 0xfc, 0xf9, 0x8e, 0xf1, 0x03, 0xed)
+#define EFI_CERT_TYPE_PKCS7_GUID \
+	EFI_GUID(0x4aafd29d, 0x68df, 0x49ee, 0x8a, 0xa9, \
+		 0x34, 0x7d, 0x37, 0x56, 0x65, 0xa7)
+
+/**
+ * win_certificate_uefi_guid - A certificate that encapsulates
+ * a GUID-specific signature
+ *
+ * @hdr:	Windows certificate header
+ * @cert_type:	Certificate type
+ * @cert_data:	Certificate data
+ */
+struct win_certificate_uefi_guid {
+	WIN_CERTIFICATE	hdr;
+	efi_guid_t	cert_type;
+	u8		cert_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_variable_authentication_2 - A time-based authentication method
+ * descriptor
+ *
+ * This structure describes an authentication information for
+ * a variable with EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
+ * and should be included as part of a variable's value.
+ * Only EFI_CERT_TYPE_PKCS7_GUID is accepted.
+ *
+ * @time_stamp:	Descriptor's time stamp
+ * @auth_info:	Authentication info
+ */
+struct efi_variable_authentication_2 {
+	struct efi_time			 time_stamp;
+	struct win_certificate_uefi_guid auth_info;
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_data - A format of signature
+ *
+ * This structure describes a single signature in signature database.
+ *
+ * @signature_owner:	Signature owner
+ * @signature_data:	Signature data
+ */
+struct efi_signature_data {
+	efi_guid_t	signature_owner;
+	u8		signature_data[];
+} __attribute__((__packed__));
+
+/**
+ * efi_signature_list - A format of signature database
+ *
+ * This structure describes a list of signatures with the same type.
+ * An authenticated variable's value is a concatenation of one or more
+ * efi_signature_list's.
+ *
+ * @signature_type:		Signature type
+ * @signature_list_size:	Size of signature list
+ * @signature_header_size:	Size of signature header
+ * @signature_size:		Size of signature
+ */
+struct efi_signature_list {
+	efi_guid_t	signature_type;
+	u32		signature_list_size;
+	u32		signature_header_size;
+	u32		signature_size;
+/*	u8		signature_header[signature_header_size]; */
+/*	struct efi_signature_data signatures[...][signature_size]; */
+} __attribute__((__packed__));
+
 #endif
include/efi_loader.h +72 -0
index 3f2792892f34..8cf85d2fb7e2 100644
@@ -26,6 +26,7 @@ static inline void *guidcpy(void *dst, const void *src)
 #if CONFIG_IS_ENABLED(EFI_LOADER)
 
 #include <linux/list.h>
+#include <linux/oid_registry.h>
 
 /* Maximum number of configuration tables */
 #define EFI_MAX_CONFIGURATION_TABLES 16
@@ -178,6 +179,11 @@ extern const efi_guid_t efi_guid_hii_config_routing_protocol;
 extern const efi_guid_t efi_guid_hii_config_access_protocol;
 extern const efi_guid_t efi_guid_hii_database_protocol;
 extern const efi_guid_t efi_guid_hii_string_protocol;
+/* GUIDs for authentication */
+extern const efi_guid_t efi_guid_image_security_database;
+extern const efi_guid_t efi_guid_sha256;
+extern const efi_guid_t efi_guid_cert_x509;
+extern const efi_guid_t efi_guid_cert_x509_sha256;
 
 /* GUID of RNG protocol */
 extern const efi_guid_t efi_guid_rng_protocol;
@@ -680,6 +686,72 @@ void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data);
 unsigned long efi_serialize_load_option(struct efi_load_option *lo, u8 **data);
 efi_status_t efi_bootmgr_load(efi_handle_t *handle);
 
+#ifdef CONFIG_EFI_SECURE_BOOT
+#include <image.h>
+
+/**
+ * efi_image_regions - A list of memory regions
+ *
+ * @max:	Maximum number of regions
+ * @num:	Number of regions
+ * @reg:	array of regions
+ */
+struct efi_image_regions {
+	int			max;
+	int			num;
+	struct image_region	reg[];
+};
+
+/**
+ * efi_sig_data - A decoded data of struct efi_signature_data
+ *
+ * This structure represents an internal form of signature in
+ * signature database. A listed list may represent a signature list.
+ *
+ * @next:	Pointer to next entry
+ * @onwer:	Signature owner
+ * @data:	Pointer to signature data
+ * @size:	Size of signature data
+ */
+struct efi_sig_data {
+	struct efi_sig_data *next;
+	efi_guid_t owner;
+	void *data;
+	size_t size;
+};
+
+/**
+ * efi_signature_store - A decoded data of signature database
+ *
+ * This structure represents an internal form of signature database.
+ *
+ * @next:		Pointer to next entry
+ * @sig_type:		Signature type
+ * @sig_data_list:	Pointer to signature list
+ */
+struct efi_signature_store {
+	struct efi_signature_store *next;
+	efi_guid_t sig_type;
+	struct efi_sig_data *sig_data_list;
+};
+
+struct x509_certificate;
+struct pkcs7_message;
+
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx);
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx);
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				  struct efi_signature_store *db,
+				  struct x509_certificate **cert);
+
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck);
+#endif /* CONFIG_EFI_SECURE_BOOT */
+
 #else /* CONFIG_IS_ENABLED(EFI_LOADER) */
 
 /* Without CONFIG_EFI_LOADER we don't have a runtime section, stub it out */
lib/efi_loader/Makefile +1 -0
index 9b3b70447336..eff3c25ec301 100644
@@ -44,3 +44,4 @@ obj-$(CONFIG_GENERATE_ACPI_TABLE) += efi_acpi.o
 obj-$(CONFIG_GENERATE_SMBIOS_TABLE) += efi_smbios.o
 obj-$(CONFIG_EFI_RNG_PROTOCOL) += efi_rng.o
 obj-$(CONFIG_EFI_LOAD_FILE2_INITRD) += efi_load_initrd.o
+obj-y += efi_signature.o
lib/efi_loader/efi_signature.c new file +134 -0
new file mode 100644
index 000000000000..23dac94c0593
@@ -0,0 +1,583 @@
+// SPDX-License-Identifier: GPL-2.0+
+/*
+ * Copyright (c) 2018 Patrick Wildt <[email protected]>
+ * Copyright (c) 2019 Linaro Limited, Author: AKASHI Takahiro
+ */
+
+#include <common.h>
+#include <charset.h>
+#include <efi_loader.h>
+#include <image.h>
+#include <hexdump.h>
+#include <malloc.h>
+#include <pe.h>
+#include <linux/compat.h>
+#include <linux/oid_registry.h>
+#include <u-boot/rsa.h>
+#include <u-boot/sha256.h>
+/*
+ * avoid duplicated inclusion:
+ * #include "../lib/crypto/x509_parser.h"
+ */
+#include "../lib/crypto/pkcs7_parser.h"
+
+const efi_guid_t efi_guid_image_security_database =
+		EFI_IMAGE_SECURITY_DATABASE_GUID;
+const efi_guid_t efi_guid_sha256 = EFI_CERT_SHA256_GUID;
+const efi_guid_t efi_guid_cert_rsa2048 = EFI_CERT_RSA2048_GUID;
+const efi_guid_t efi_guid_cert_x509 = EFI_CERT_X509_GUID;
+const efi_guid_t efi_guid_cert_x509_sha256 = EFI_CERT_X509_SHA256_GUID;
+
+#ifdef CONFIG_EFI_SECURE_BOOT
+
+/**
+ * efi_hash_regions - calculate a hash value
+ * @regs:	List of regions
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of @regs and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_regions(struct efi_image_regions *regs, void **hash,
+			     size_t *size)
+{
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	hash_calculate("sha256", regs->reg, regs->num, *hash);
+#ifdef DEBUG
+	debug("hash calculated:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_hash_msg_content - calculate a hash value of contentInfo
+ * @msg:	Signature
+ * @hash:	Pointer to a pointer to buffer holding a hash value
+ * @size:	Size of buffer to be returned
+ *
+ * Calculate a sha256 value of contentInfo in @msg and return a value in @hash.
+ *
+ * Return:	true on success, false on error
+ */
+static bool efi_hash_msg_content(struct pkcs7_message *msg, void **hash,
+				 size_t *size)
+{
+	struct image_region regtmp;
+
+	*size = 0;
+	*hash = calloc(1, SHA256_SUM_LEN);
+	if (!*hash) {
+		debug("Out of memory\n");
+		free(msg);
+		return false;
+	}
+	*size = SHA256_SUM_LEN;
+
+	regtmp.data = msg->data;
+	regtmp.size = msg->data_len;
+
+	hash_calculate("sha256", &regtmp, 1, *hash);
+#ifdef DEBUG
+	debug("hash calculated based on contentInfo:\n");
+	print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+		       *hash, SHA256_SUM_LEN, false);
+#endif
+
+	return true;
+}
+
+/**
+ * efi_signature_verify - verify a signature with a certificate
+ * @regs:		List of regions to be authenticated
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @cert:		x509 certificate
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by a certificate pointed to by @cert.
+ * @signed_info holds a signature, including a message digest which is to be
+ * compared with a hash value calculated from @regs.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static bool efi_signature_verify(struct efi_image_regions *regs,
+				 struct pkcs7_message *msg,
+				 struct pkcs7_signed_info *ps_info,
+				 struct x509_certificate *cert)
+{
+	struct image_sign_info info;
+	struct image_region regtmp[2];
+	void *hash;
+	size_t size;
+	char c;
+	bool verified;
+
+	debug("%s: Enter, %p, %p, %p(issuer: %s, subject: %s)\n", __func__,
+	      regs, ps_info, cert, cert->issuer, cert->subject);
+
+	verified = false;
+
+	memset(&info, '\0', sizeof(info));
+	info.padding = image_get_padding_algo("pkcs-1.5");
+	/*
+	 * Note: image_get_[checksum|crypto]_algo takes an string
Quoted 8 lines

lib/efi_loader/efi_signature.c line 138

Quoted 4 lines
lib/efi_loader/efi_signature.c new file +4 -0
+	 * argument like "<checksum>,<crypto>"
+	 * TODO: support other hash algorithms
+	 */
+	if (!strcmp(ps_info->sig->hash_algo, "sha1")) {

There is a call
efi_signature_verify_with_list(regs, NULL, NULL, siglist, cert) So ps_info may be NULL

efi_signature_verify() is called only if signed_info is not NULL.

Quoted 14 lines
Quoted 14 lines
lib/efi_loader/efi_signature.c new file +14 -0
+		info.checksum = image_get_checksum_algo("sha1,rsa2048");
+		info.name = "sha1,rsa2048";
+	} else if (!strcmp(ps_info->sig->hash_algo, "sha256")) {
+		info.checksum = image_get_checksum_algo("sha256,rsa2048");
+		info.name = "sha256,rsa2048";
+	} else {
+		debug("unknown msg digest algo: %s\n", ps_info->sig->hash_algo);
+		goto out;
+	}
+	info.crypto = image_get_crypto_algo(info.name);
+
+	info.key = cert->pub->key;
+	info.keylen = cert->pub->keylen;
+
Quoted 8 lines

lib/efi_loader/efi_signature.c line 156

Quoted 4 lines
lib/efi_loader/efi_signature.c new file +4 -0
+	/* verify signature */
+	debug("%s: crypto: %s, signature len:%x\n", __func__,
+	      info.name, ps_info->sig->s_size);
+	if (ps_info->aa_set & (1UL << sinfo_has_message_digest)) {

There is a call
efi_signature_verify_with_list(regs, NULL, NULL, siglist, cert) So ps_info may be NULL

ditto

Quoted 15 lines
Quoted 15 lines
lib/efi_loader/efi_signature.c new file +15 -0
+		debug("%s: RSA verify authentication attribute\n", __func__);
+		/*
+		 * NOTE: This path will be executed only for
+		 * PE image authentication
+		 */
+
+		/* check if hash matches digest first */
+		debug("checking msg digest first, len:0x%x\n",
+		      ps_info->msgdigest_len);
+
+#ifdef DEBUG
+		debug("hash in database:\n");
+		print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+			       ps_info->msgdigest, ps_info->msgdigest_len,
+			       false);
Quoted 8 lines

lib/efi_loader/efi_signature.c line 175

Quoted 4 lines
lib/efi_loader/efi_signature.c new file +4 -0
+#endif
+		/* against contentInfo first */
+		if ((msg->data && efi_hash_msg_content(msg, &hash, &size)) ||
+				/* for signed image */

There is a call
efi_signature_verify_with_list(regs, NULL, NULL, siglist, cert) So msg may be NULL.

msg is used only if signed_info is also provided.
Please note that <msg,psinfo> == <NULL,NULL> case means that the image is not signed. That is why the code causes no runtime memory fault.

Quoted 4 lines

Either avoid the call will NULL or check the parameters before dereferencing.

Please, provide a follow up patch.

Therefore I don't think that any fix will be necessary.

Thanks,
-Takahiro Akashi

Quoted 416 lines

I used cppcheck to identify this problem.

Best regards

Heinrich

Quoted 409 lines
lib/efi_loader/efi_signature.c new file +408 -0
+		    efi_hash_regions(regs, &hash, &size)) {
+				/* for authenticated variable */
+			if (ps_info->msgdigest_len != size ||
+			    memcmp(hash, ps_info->msgdigest, size)) {
+				debug("Digest doesn't match\n");
+				free(hash);
+				goto out;
+			}
+
+			free(hash);
+		} else {
+			debug("Digesting image failed\n");
+			goto out;
+		}
+
+		/* against digest */
+		c = 0x31;
+		regtmp[0].data = &c;
+		regtmp[0].size = 1;
+		regtmp[1].data = ps_info->authattrs;
+		regtmp[1].size = ps_info->authattrs_len;
+
+		if (!rsa_verify(&info, regtmp, 2,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	} else {
+		debug("%s: RSA verify content data\n", __func__);
+		/* against all data */
+		if (!rsa_verify(&info, regs->reg, regs->num,
+				ps_info->sig->s, ps_info->sig->s_size))
+			verified = true;
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_list - verify a signature with signature list
+ * @regs:		List of regions to be authenticated
+ * @msg:		Signature
+ * @signed_info:	Pointer to PKCS7's signed_info
+ * @siglist:		Signature list for certificates
+ * @valid_cert:		x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @signed_info against image pointed to by @regs
+ * is verified by signature list pointed to by @siglist.
+ * Signature database is a simple concatenation of one or more
+ * signature list(s).
+ *
+ * Return:	true if signature is verified, false if not
+ */
+static
+bool efi_signature_verify_with_list(struct efi_image_regions *regs,
+				    struct pkcs7_message *msg,
+				    struct pkcs7_signed_info *signed_info,
+				    struct efi_signature_store *siglist,
+				    struct x509_certificate **valid_cert)
+{
+	struct x509_certificate *cert;
+	struct efi_sig_data *sig_data;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__,
+	      regs, signed_info, siglist, valid_cert);
+
+	if (!signed_info) {
+		void *hash;
+		size_t size;
+
+		debug("%s: unsigned image\n", __func__);
+		/*
+		 * verify based on calculated hash value
+		 * TODO: support other hash algorithms
+		 */
+		if (guidcmp(&siglist->sig_type, &efi_guid_sha256)) {
+			debug("Digest algorithm is not supported: %pUl\n",
+			      &siglist->sig_type);
+			goto out;
+		}
+
+		if (!efi_hash_regions(regs, &hash, &size)) {
+			debug("Digesting unsigned image failed\n");
+			goto out;
+		}
+
+		/* go through the list */
+		for (sig_data = siglist->sig_data_list; sig_data;
+		     sig_data = sig_data->next) {
+#ifdef DEBUG
+			debug("Msg digest in database:\n");
+			print_hex_dump("    ", DUMP_PREFIX_OFFSET, 16, 1,
+				       sig_data->data, sig_data->size, false);
+#endif
+			if ((sig_data->size == size) &&
+			    !memcmp(sig_data->data, hash, size)) {
+				verified = true;
+				free(hash);
+				goto out;
+			}
+		}
+		free(hash);
+		goto out;
+	}
+
+	debug("%s: signed image\n", __func__);
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509)) {
+		debug("Signature type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* go through the list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/* TODO: support owner check based on policy */
+
+		cert = x509_cert_parse(sig_data->data, sig_data->size);
+		if (IS_ERR(cert)) {
+			debug("Parsing x509 certificate failed\n");
+			goto out;
+		}
+
+		verified = efi_signature_verify(regs, msg, signed_info, cert);
+
+		if (verified) {
+			if (valid_cert)
+				*valid_cert = cert;
+			else
+				x509_free_certificate(cert);
+			break;
+		}
+		x509_free_certificate(cert);
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_signature_verify_with_sigdb - verify a signature with db
+ * @regs:	List of regions to be authenticated
+ * @msg:	Signature
+ * @db:		Signature database for trusted certificates
+ * @cert:	x509 certificate that verifies this signature
+ *
+ * Signature pointed to by @msg against image pointed to by @regs
+ * is verified by signature database pointed to by @db.
+ *
+ * Return:	true if signature is verified, false if not
+ */
+bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
+				     struct pkcs7_message *msg,
+				     struct efi_signature_store *db,
+				     struct x509_certificate **cert)
+{
+	struct pkcs7_signed_info *info;
+	struct efi_signature_store *siglist;
+	bool verified = false;
+
+	debug("%s: Enter, %p, %p, %p, %p\n", __func__, regs, msg, db, cert);
+
+	if (!db)
+		goto out;
+
+	if (!db->sig_data_list)
+		goto out;
+
+	/* for unsigned image */
+	if (!msg) {
+		debug("%s: Verify unsigned image with db\n", __func__);
+		for (siglist = db; siglist; siglist = siglist->next)
+			if (efi_signature_verify_with_list(regs, NULL, NULL,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+
+		goto out;
+	}
+
+	/* for signed image or variable */
+	debug("%s: Verify signed image with db\n", __func__);
+	for (info = msg->signed_infos; info; info = info->next) {
+		debug("Signed Info: digest algo: %s, pkey algo: %s\n",
+		      info->sig->hash_algo, info->sig->pkey_algo);
+
+		for (siglist = db; siglist; siglist = siglist->next) {
+			if (efi_signature_verify_with_list(regs, msg, info,
+							   siglist, cert)) {
+				verified = true;
+				goto out;
+			}
+		}
+	}
+
+out:
+	debug("%s: Exit, verified: %d\n", __func__, verified);
+	return verified;
+}
+
+/**
+ * efi_search_siglist - search signature list for a certificate
+ * @cert:	x509 certificate
+ * @siglist:	Signature list
+ * @revoc_time:	Pointer to buffer for revocation time
+ *
+ * Search signature list pointed to by @siglist and find a certificate
+ * pointed to by @cert.
+ * If found, revocation time that is specified in signature database is
+ * returned in @revoc_time.
+ *
+ * Return:	true if certificate is found, false if not
+ */
+static bool efi_search_siglist(struct x509_certificate *cert,
+			       struct efi_signature_store *siglist,
+			       time64_t *revoc_time)
+{
+	struct image_region reg[1];
+	void *hash = NULL, *msg = NULL;
+	struct efi_sig_data *sig_data;
+	bool found = false;
+
+	/* can be null */
+	if (!siglist->sig_data_list)
+		return false;
+
+	if (guidcmp(&siglist->sig_type, &efi_guid_cert_x509_sha256)) {
+		/* TODO: other hash algos */
+		debug("Certificate's digest type is not supported: %pUl\n",
+		      &siglist->sig_type);
+		goto out;
+	}
+
+	/* calculate hash of TBSCertificate */
+	msg = calloc(1, SHA256_SUM_LEN);
+	if (!msg) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	hash = calloc(1, SHA256_SUM_LEN);
+	if (!hash) {
+		debug("Out of memory\n");
+		goto out;
+	}
+
+	reg[0].data = cert->tbs;
+	reg[0].size = cert->tbs_size;
+	hash_calculate("sha256", reg, 1, msg);
+
+	/* go through signature list */
+	for (sig_data = siglist->sig_data_list; sig_data;
+	     sig_data = sig_data->next) {
+		/*
+		 * struct efi_cert_x509_sha256 {
+		 *	u8 tbs_hash[256/8];
+		 *	time64_t revocation_time;
+		 * };
+		 */
+		if ((sig_data->size == SHA256_SUM_LEN) &&
+		    !memcmp(sig_data->data, hash, SHA256_SUM_LEN)) {
+			memcpy(revoc_time, sig_data->data + SHA256_SUM_LEN,
+			       sizeof(*revoc_time));
+			found = true;
+			goto out;
+		}
+	}
+
+out:
+	free(hash);
+	free(msg);
+
+	return found;
+}
+
+/**
+ * efi_signature_verify_cert - verify a certificate with dbx
+ * @cert:	x509 certificate
+ * @dbx:	Signature database
+ *
+ * Search signature database pointed to by @dbx and find a certificate
+ * pointed to by @cert.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if a certificate is not rejected, false otherwise.
+ */
+bool efi_signature_verify_cert(struct x509_certificate *cert,
+			       struct efi_signature_store *dbx)
+{
+	struct efi_signature_store *siglist;
+	time64_t revoc_time;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, dbx, cert);
+
+	if (!cert)
+		return false;
+
+	for (siglist = dbx; siglist; siglist = siglist->next) {
+		if (efi_search_siglist(cert, siglist, &revoc_time)) {
+			/* TODO */
+			/* compare signing time with revocation time */
+
+			found = true;
+			break;
+		}
+	}
+
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_signature_verify_signers - verify signers' certificates with dbx
+ * @msg:	Signature
+ * @dbx:	Signature database
+ *
+ * Determine if any of signers' certificates in @msg may be verified
+ * by any of certificates in signature database pointed to by @dbx.
+ * This function is expected to be used against "dbx".
+ *
+ * Return:	true if none of certificates is rejected, false otherwise.
+ */
+bool efi_signature_verify_signers(struct pkcs7_message *msg,
+				  struct efi_signature_store *dbx)
+{
+	struct pkcs7_signed_info *info;
+	bool found = false;
+
+	debug("%s: Enter, %p, %p\n", __func__, msg, dbx);
+
+	if (!msg)
+		goto out;
+
+	for (info = msg->signed_infos; info; info = info->next) {
+		if (info->signer &&
+		    !efi_signature_verify_cert(info->signer, dbx)) {
+			found = true;
+			goto out;
+		}
+	}
+out:
+	debug("%s: Exit, verified: %d\n", __func__, !found);
+	return !found;
+}
+
+/**
+ * efi_image_region_add - add an entry of region
+ * @regs:	Pointer to array of regions
+ * @start:	Start address of region
+ * @end:	End address of region
+ * @nocheck:	flag against overlapped regions
+ *
+ * Take one entry of region [@start, @end] and append it to the list
+ * pointed to by @regs. If @nocheck is false, overlapping among entries
+ * will be checked first.
+ *
+ * Return:	0 on success, status code (negative) on error
+ */
+efi_status_t efi_image_region_add(struct efi_image_regions *regs,
+				  const void *start, const void *end,
+				  int nocheck)
+{
+	struct image_region *reg;
+	int i, j;
+
+	if (regs->num >= regs->max) {
+		debug("%s: no more room for regions\n", __func__);
+		return EFI_OUT_OF_RESOURCES;
+	}
+
+	if (end < start)
+		return EFI_INVALID_PARAMETER;
+
+	for (i = 0; i < regs->num; i++) {
+		reg = &regs->reg[i];
+		if (nocheck)
+			continue;
+
+		if (start > reg->data + reg->size)
+			continue;
+
+		if ((start >= reg->data && start < reg->data + reg->size) ||
+		    (end > reg->data && end < reg->data + reg->size)) {
+			debug("%s: new region already part of another\n",
+			      __func__);
+			return EFI_INVALID_PARAMETER;
+		}
+
+		if (start < reg->data && end < reg->data + reg->size) {
+			for (j = regs->num - 1; j >= i; j--)
+				memcpy(&regs->reg[j], &regs->reg[j + 1],
+				       sizeof(*reg));
+			break;
+		}
+	}
+
+	reg = &regs->reg[i];
+	reg->data = start;
+	reg->size = end - start;
+	regs->num++;
+
+	return EFI_SUCCESS;
+}
+#endif /* CONFIG_EFI_SECURE_BOOT */
#9 lore raw

PATCH v7 3/17 efi_loader: add signature database parser

In reply to AKASHI Takahiro

efi_signature_parse_sigdb() is a helper function will be used to parse signature database variable and instantiate a signature store structure in later patches.

---
 include/efi_loader.h           |   3 +
 lib/efi_loader/efi_signature.c | 226 +++++++++++++++++++++++++++++++++
 2 files changed, 229 insertions(+)
include/efi_loader.h +3 -0
index 8cf85d2fb7e2..fea2ead02e93 100644
@@ -750,6 +750,9 @@ bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
 efi_status_t efi_image_region_add(struct efi_image_regions *regs,
 				  const void *start, const void *end,
 				  int nocheck);
+
+void efi_sigstore_free(struct efi_signature_store *sigstore);
+struct efi_signature_store *efi_sigstore_parse_sigdb(u16 *name);
 #endif /* CONFIG_EFI_SECURE_BOOT */
 
 #else /* CONFIG_IS_ENABLED(EFI_LOADER) */
lib/efi_loader/efi_signature.c +226 -0

230 lines not on this page · raw message

Signature · 1 line
2.25.2
#10 lore raw

PATCH v7 3/17 efi_loader: add signature database parser

Quoted 117 lines · AKASHI Takahiro

efi_signature_parse_sigdb() is a helper function will be used to parse signature database variable and instantiate a signature store structure in later patches.

---
 include/efi_loader.h           |   3 +
 lib/efi_loader/efi_signature.c | 226 +++++++++++++++++++++++++++++++++
 2 files changed, 229 insertions(+)
include/efi_loader.h +3 -0
index 8cf85d2fb7e2..fea2ead02e93 100644
@@ -750,6 +750,9 @@ bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
 efi_status_t efi_image_region_add(struct efi_image_regions *regs,
 				  const void *start, const void *end,
 				  int nocheck);
+
+void efi_sigstore_free(struct efi_signature_store *sigstore);
+struct efi_signature_store *efi_sigstore_parse_sigdb(u16 *name);
 #endif /* CONFIG_EFI_SECURE_BOOT */
 
 #else /* CONFIG_IS_ENABLED(EFI_LOADER) */
lib/efi_loader/efi_signature.c +85 -0
index 23dac94c0593..2d1f38980e5f 100644
@@ -580,4 +580,230 @@ efi_status_t efi_image_region_add(struct efi_image_regions *regs,
 
 	return EFI_SUCCESS;
 }
+
+/**
+ * efi_sigstore_free - free signature store
+ * @sigstore:	Pointer to signature store structure
+ *
+ * Feee all the memories held in signature store and itself,
+ * which were allocated by efi_sigstore_parse_sigdb().
+ */
+void efi_sigstore_free(struct efi_signature_store *sigstore)
+{
+	struct efi_signature_store *sigstore_next;
+	struct efi_sig_data *sig_data, *sig_data_next;
+
+	while (sigstore) {
+		sigstore_next = sigstore->next;
+
+		sig_data = sigstore->sig_data_list;
+		while (sig_data) {
+			sig_data_next = sig_data->next;
+			free(sig_data->data);
+			free(sig_data);
+			sig_data = sig_data_next;
+		}
+
+		free(sigstore);
+		sigstore = sigstore_next;
+	}
+}
+
+/**
+ * efi_sigstore_parse_siglist - parse a signature list
+ * @name:	Pointer to signature list
+ *
+ * Parse signature list and instantiate a signature store structure.
+ * Signature database is a simple concatenation of one or more
+ * signature list(s).
+ *
+ * Return:	Pointer to signature store on success, NULL on error
+ */
+static struct efi_signature_store *
+efi_sigstore_parse_siglist(struct efi_signature_list *esl)
+{
+	struct efi_signature_store *siglist = NULL;
+	struct efi_sig_data *sig_data, *sig_data_next;
+	struct efi_signature_data *esd;
+	size_t left;
+
+	/*
+	 * UEFI specification defines certificate types:
+	 *   for non-signed images,
+	 *	EFI_CERT_SHA256_GUID
+	 *	EFI_CERT_RSA2048_GUID
+	 *	EFI_CERT_RSA2048_SHA256_GUID
+	 *	EFI_CERT_SHA1_GUID
+	 *	EFI_CERT_RSA2048_SHA_GUID
+	 *	EFI_CERT_SHA224_GUID
+	 *	EFI_CERT_SHA384_GUID
+	 *	EFI_CERT_SHA512_GUID
+	 *
+	 *   for signed images,
+	 *	EFI_CERT_X509_GUID
+	 *	NOTE: Each certificate will normally be in a separate
+	 *	EFI_SIGNATURE_LIST as the size may vary depending on
+	 *	its algo's.
+	 *
+	 *   for timestamp revocation of certificate,
+	 *	EFI_CERT_X509_SHA512_GUID
+	 *	EFI_CERT_X509_SHA256_GUID
+	 *	EFI_CERT_X509_SHA384_GUID
+	 */
+
+	if (esl->signature_list_size
+			<= (sizeof(*esl) + esl->signature_header_size)) {
+		debug("Siglist in wrong format\n");
+		return NULL;
+	}
+
+	/* Create a head */
+	siglist = calloc(sizeof(*siglist), 1);
+	if (!siglist) {
+		debug("Out of memory\n");
+		goto err;
+	}
+	memcpy(&siglist->sig_type, &esl->signature_type, sizeof(efi_guid_t));
+

lib/efi_loader/efi_signature.c efi_status_t efi_image_region_add(struct efi_image_regions *regs, · line 677

Quoted 10 lines
lib/efi_loader/efi_signature.c +10 -0
+	/* Go through the list */
+	sig_data_next = NULL;
+	left = esl->signature_list_size
+			- (sizeof(*esl) + esl->signature_header_size);
+	esd = (struct efi_signature_data *)
+			((u8 *)esl + sizeof(*esl) + esl->signature_header_size);
+
+	while ((left > 0) && left >= esl->signature_size) {
+		/* Signature must exist if there is remaining data. */
+		if (left < esl->signature_size) {

This code is unreachable (as indicated by cppcheck).

Please, send a follow-up patch.

Best regards

Heinrich

Quoted 133 lines
lib/efi_loader/efi_signature.c +131 -0
+			debug("Certificate is too small\n");
+			goto err;
+		}
+
+		sig_data = calloc(esl->signature_size
+					- sizeof(esd->signature_owner), 1);
+		if (!sig_data) {
+			debug("Out of memory\n");
+			goto err;
+		}
+
+		/* Append signature data */
+		memcpy(&sig_data->owner, &esd->signature_owner,
+		       sizeof(efi_guid_t));
+		sig_data->size = esl->signature_size
+					- sizeof(esd->signature_owner);
+		sig_data->data = malloc(sig_data->size);
+		if (!sig_data->data) {
+			debug("Out of memory\n");
+			goto err;
+		}
+		memcpy(sig_data->data, esd->signature_data, sig_data->size);
+
+		sig_data->next = sig_data_next;
+		sig_data_next = sig_data;
+
+		/* Next */
+		esd = (struct efi_signature_data *)
+				((u8 *)esd + esl->signature_size);
+		left -= esl->signature_size;
+	}
+	siglist->sig_data_list = sig_data_next;
+
+	return siglist;
+
+err:
+	efi_sigstore_free(siglist);
+
+	return NULL;
+}
+
+/**
+ * efi_sigstore_parse_sigdb - parse a signature database variable
+ * @name:	Variable's name
+ *
+ * Read in a value of signature database variable pointed to by
+ * @name, parse it and instantiate a signature store structure.
+ *
+ * Return:	Pointer to signature store on success, NULL on error
+ */
+struct efi_signature_store *efi_sigstore_parse_sigdb(u16 *name)
+{
+	struct efi_signature_store *sigstore = NULL, *siglist;
+	struct efi_signature_list *esl;
+	const efi_guid_t *vendor;
+	void *db;
+	efi_uintn_t db_size;
+	efi_status_t ret;
+
+	if (!u16_strcmp(name, L"PK") || !u16_strcmp(name, L"KEK")) {
+		vendor = &efi_global_variable_guid;
+	} else if (!u16_strcmp(name, L"db") || !u16_strcmp(name, L"dbx")) {
+		vendor = &efi_guid_image_security_database;
+	} else {
+		debug("unknown signature database, %ls\n", name);
+		return NULL;
+	}
+
+	/* retrieve variable data */
+	db_size = 0;
+	ret = EFI_CALL(efi_get_variable(name, vendor, NULL, &db_size, NULL));
+	if (ret == EFI_NOT_FOUND) {
+		debug("variable, %ls, not found\n", name);
+		sigstore = calloc(sizeof(*sigstore), 1);
+		return sigstore;
+	} else if (ret != EFI_BUFFER_TOO_SMALL) {
+		debug("Getting variable, %ls, failed\n", name);
+		return NULL;
+	}
+
+	db = malloc(db_size);
+	if (!db) {
+		debug("Out of memory\n");
+		return NULL;
+	}
+
+	ret = EFI_CALL(efi_get_variable(name, vendor, NULL, &db_size, db));
+	if (ret != EFI_SUCCESS) {
+		debug("Getting variable, %ls, failed\n", name);
+		goto err;
+	}
+
+	/* Parse siglist list */
+	esl = db;
+	while (db_size > 0) {
+		/* List must exist if there is remaining data. */
+		if (db_size < sizeof(*esl)) {
+			debug("variable, %ls, in wrong format\n", name);
+			goto err;
+		}
+
+		if (db_size < esl->signature_list_size) {
+			debug("variable, %ls, in wrong format\n", name);
+			goto err;
+		}
+
+		/* Parse a single siglist. */
+		siglist = efi_sigstore_parse_siglist(esl);
+		if (!siglist) {
+			debug("Parsing signature list of %ls failed\n", name);
+			goto err;
+		}
+
+		/* Append siglist */
+		siglist->next = sigstore;
+		sigstore = siglist;
+
+		/* Next */
+		db_size -= esl->signature_list_size;
+		esl = (void *)esl + esl->signature_list_size;
+	}
+	free(db);
+
+	return sigstore;
+
+err:
+	efi_sigstore_free(sigstore);
+	free(db);
+
+	return NULL;
+}
 #endif /* CONFIG_EFI_SECURE_BOOT */
#11 lore raw

PATCH v7 3/17 efi_loader: add signature database parser

Heinrich,

Quoted 122 lines · Heinrich Schuchardt
Quoted 121 lines · AKASHI Takahiro

efi_signature_parse_sigdb() is a helper function will be used to parse signature database variable and instantiate a signature store structure in later patches.

---
 include/efi_loader.h           |   3 +
 lib/efi_loader/efi_signature.c | 226 +++++++++++++++++++++++++++++++++
 2 files changed, 229 insertions(+)
include/efi_loader.h +3 -0
index 8cf85d2fb7e2..fea2ead02e93 100644
@@ -750,6 +750,9 @@ bool efi_signature_verify_with_sigdb(struct efi_image_regions *regs,
 efi_status_t efi_image_region_add(struct efi_image_regions *regs,
 				  const void *start, const void *end,
 				  int nocheck);
+
+void efi_sigstore_free(struct efi_signature_store *sigstore);
+struct efi_signature_store *efi_sigstore_parse_sigdb(u16 *name);
 #endif /* CONFIG_EFI_SECURE_BOOT */
 
 #else /* CONFIG_IS_ENABLED(EFI_LOADER) */
lib/efi_loader/efi_signature.c +89 -0
index 23dac94c0593..2d1f38980e5f 100644
@@ -580,4 +580,230 @@ efi_status_t efi_image_region_add(struct efi_image_regions *regs,
 
 	return EFI_SUCCESS;
 }
+
+/**
+ * efi_sigstore_free - free signature store
+ * @sigstore:	Pointer to signature store structure
+ *
+ * Feee all the memories held in signature store and itself,
+ * which were allocated by efi_sigstore_parse_sigdb().
+ */
+void efi_sigstore_free(struct efi_signature_store *sigstore)
+{
+	struct efi_signature_store *sigstore_next;
+	struct efi_sig_data *sig_data, *sig_data_next;
+
+	while (sigstore) {
+		sigstore_next = sigstore->next;
+
+		sig_data = sigstore->sig_data_list;
+		while (sig_data) {
+			sig_data_next = sig_data->next;
+			free(sig_data->data);
+			free(sig_data);
+			sig_data = sig_data_next;
+		}
+
+		free(sigstore);
+		sigstore = sigstore_next;
+	}
+}
+
+/**
+ * efi_sigstore_parse_siglist - parse a signature list
+ * @name:	Pointer to signature list
+ *
+ * Parse signature list and instantiate a signature store structure.
+ * Signature database is a simple concatenation of one or more
+ * signature list(s).
+ *
+ * Return:	Pointer to signature store on success, NULL on error
+ */
+static struct efi_signature_store *
+efi_sigstore_parse_siglist(struct efi_signature_list *esl)
+{
+	struct efi_signature_store *siglist = NULL;
+	struct efi_sig_data *sig_data, *sig_data_next;
+	struct efi_signature_data *esd;
+	size_t left;
+
+	/*
+	 * UEFI specification defines certificate types:
+	 *   for non-signed images,
+	 *	EFI_CERT_SHA256_GUID
+	 *	EFI_CERT_RSA2048_GUID
+	 *	EFI_CERT_RSA2048_SHA256_GUID
+	 *	EFI_CERT_SHA1_GUID
+	 *	EFI_CERT_RSA2048_SHA_GUID
+	 *	EFI_CERT_SHA224_GUID
+	 *	EFI_CERT_SHA384_GUID
+	 *	EFI_CERT_SHA512_GUID
+	 *
+	 *   for signed images,
+	 *	EFI_CERT_X509_GUID
+	 *	NOTE: Each certificate will normally be in a separate
+	 *	EFI_SIGNATURE_LIST as the size may vary depending on
+	 *	its algo's.
+	 *
+	 *   for timestamp revocation of certificate,
+	 *	EFI_CERT_X509_SHA512_GUID
+	 *	EFI_CERT_X509_SHA256_GUID
+	 *	EFI_CERT_X509_SHA384_GUID
+	 */
+
+	if (esl->signature_list_size
+			<= (sizeof(*esl) + esl->signature_header_size)) {
+		debug("Siglist in wrong format\n");
+		return NULL;
+	}
+
+	/* Create a head */
+	siglist = calloc(sizeof(*siglist), 1);
+	if (!siglist) {
+		debug("Out of memory\n");
+		goto err;
+	}
+	memcpy(&siglist->sig_type, &esl->signature_type, sizeof(efi_guid_t));
+
+	/* Go through the list */
+	sig_data_next = NULL;
+	left = esl->signature_list_size
+			- (sizeof(*esl) + esl->signature_header_size);
Quoted 8 lines

lib/efi_loader/efi_signature.c efi_status_t efi_image_region_add(struct efi_image_regions *regs, · line 677

Quoted 6 lines
lib/efi_loader/efi_signature.c +6 -0
+	esd = (struct efi_signature_data *)
+			((u8 *)esl + sizeof(*esl) + esl->signature_header_size);
+
+	while ((left > 0) && left >= esl->signature_size) {
+		/* Signature must exist if there is remaining data. */
+		if (left < esl->signature_size) {

This code is unreachable (as indicated by cppcheck).

Right, but I think the check (and an error message) is valuable just in case that a given signature database might be somehow corrupted.
So I will fix 'while' statement.

Thanks,
-Takahiro Akashi

Quoted 140 lines

Please, send a follow-up patch.

Best regards

Heinrich

Quoted 133 lines
lib/efi_loader/efi_signature.c +131 -0
+			debug("Certificate is too small\n");
+			goto err;
+		}
+
+		sig_data = calloc(esl->signature_size
+					- sizeof(esd->signature_owner), 1);
+		if (!sig_data) {
+			debug("Out of memory\n");
+			goto err;
+		}
+
+		/* Append signature data */
+		memcpy(&sig_data->owner, &esd->signature_owner,
+		       sizeof(efi_guid_t));
+		sig_data->size = esl->signature_size
+					- sizeof(esd->signature_owner);
+		sig_data->data = malloc(sig_data->size);
+		if (!sig_data->data) {
+			debug("Out of memory\n");
+			goto err;
+		}
+		memcpy(sig_data->data, esd->signature_data, sig_data->size);
+
+		sig_data->next = sig_data_next;
+		sig_data_next = sig_data;
+
+		/* Next */
+		esd = (struct efi_signature_data *)
+				((u8 *)esd + esl->signature_size);
+		left -= esl->signature_size;
+	}
+	siglist->sig_data_list = sig_data_next;
+
+	return siglist;
+
+err:
+	efi_sigstore_free(siglist);
+
+	return NULL;
+}
+
+/**
+ * efi_sigstore_parse_sigdb - parse a signature database variable
+ * @name:	Variable's name
+ *
+ * Read in a value of signature database variable pointed to by
+ * @name, parse it and instantiate a signature store structure.
+ *
+ * Return:	Pointer to signature store on success, NULL on error
+ */
+struct efi_signature_store *efi_sigstore_parse_sigdb(u16 *name)
+{
+	struct efi_signature_store *sigstore = NULL, *siglist;
+	struct efi_signature_list *esl;
+	const efi_guid_t *vendor;
+	void *db;
+	efi_uintn_t db_size;
+	efi_status_t ret;
+
+	if (!u16_strcmp(name, L"PK") || !u16_strcmp(name, L"KEK")) {
+		vendor = &efi_global_variable_guid;
+	} else if (!u16_strcmp(name, L"db") || !u16_strcmp(name, L"dbx")) {
+		vendor = &efi_guid_image_security_database;
+	} else {
+		debug("unknown signature database, %ls\n", name);
+		return NULL;
+	}
+
+	/* retrieve variable data */
+	db_size = 0;
+	ret = EFI_CALL(efi_get_variable(name, vendor, NULL, &db_size, NULL));
+	if (ret == EFI_NOT_FOUND) {
+		debug("variable, %ls, not found\n", name);
+		sigstore = calloc(sizeof(*sigstore), 1);
+		return sigstore;
+	} else if (ret != EFI_BUFFER_TOO_SMALL) {
+		debug("Getting variable, %ls, failed\n", name);
+		return NULL;
+	}
+
+	db = malloc(db_size);
+	if (!db) {
+		debug("Out of memory\n");
+		return NULL;
+	}
+
+	ret = EFI_CALL(efi_get_variable(name, vendor, NULL, &db_size, db));
+	if (ret != EFI_SUCCESS) {
+		debug("Getting variable, %ls, failed\n", name);
+		goto err;
+	}
+
+	/* Parse siglist list */
+	esl = db;
+	while (db_size > 0) {
+		/* List must exist if there is remaining data. */
+		if (db_size < sizeof(*esl)) {
+			debug("variable, %ls, in wrong format\n", name);
+			goto err;
+		}
+
+		if (db_size < esl->signature_list_size) {
+			debug("variable, %ls, in wrong format\n", name);
+			goto err;
+		}
+
+		/* Parse a single siglist. */
+		siglist = efi_sigstore_parse_siglist(esl);
+		if (!siglist) {
+			debug("Parsing signature list of %ls failed\n", name);
+			goto err;
+		}
+
+		/* Append siglist */
+		siglist->next = sigstore;
+		sigstore = siglist;
+
+		/* Next */
+		db_size -= esl->signature_list_size;
+		esl = (void *)esl + esl->signature_list_size;
+	}
+	free(db);
+
+	return sigstore;
+
+err:
+	efi_sigstore_free(sigstore);
+	free(db);
+
+	return NULL;
+}
 #endif /* CONFIG_EFI_SECURE_BOOT */
#12 lore raw

PATCH v7 4/17 efi_loader: variable: support variable authentication

In reply to AKASHI Takahiro

With this commit, EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS is supported for authenticated variables and the system secure state will transfer between setup mode and user mode as UEFI specification section 32.3 describes.

Internally, authentication data is stored as part of authenticated variable's value. It is nothing but a pkcs7 message (but we need some wrapper, see efi_variable_parse_signature()) and will be validated by efi_variable_authenticate(), hence efi_signature_verify_with_db().

Associated time value will be encoded in "{...,time=...}" along with other UEFI variable's attributes.

---
 include/efi_loader.h          |   3 +
 lib/efi_loader/efi_variable.c | 666 ++++++++++++++++++++++++++++------
 2 files changed, 565 insertions(+), 104 deletions(-)
include/efi_loader.h +3 -0
index fea2ead02e93..ef8d184a6ee7 100644
@@ -184,6 +184,7 @@ extern const efi_guid_t efi_guid_image_security_database;
 extern const efi_guid_t efi_guid_sha256;
 extern const efi_guid_t efi_guid_cert_x509;
 extern const efi_guid_t efi_guid_cert_x509_sha256;
+extern const efi_guid_t efi_guid_cert_type_pkcs7;
 
 /* GUID of RNG protocol */
 extern const efi_guid_t efi_guid_rng_protocol;
@@ -753,6 +754,8 @@ efi_status_t efi_image_region_add(struct efi_image_regions *regs,
 
 void efi_sigstore_free(struct efi_signature_store *sigstore);
 struct efi_signature_store *efi_sigstore_parse_sigdb(u16 *name);
+
+bool efi_secure_boot_enabled(void);
 #endif /* CONFIG_EFI_SECURE_BOOT */
 
 #else /* CONFIG_IS_ENABLED(EFI_LOADER) */
lib/efi_loader/efi_variable.c +562 -104

835 lines not on this page · raw message

Signature · 1 line
2.25.2
#13 lore raw

PATCH v7 4/17 efi_loader: variable: support variable authentication

Quoted 19 lines · AKASHI Takahiro

With this commit, EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS is supported for authenticated variables and the system secure state will transfer between setup mode and user mode as UEFI specification section 32.3 describes.

Internally, authentication data is stored as part of authenticated variable's value. It is nothing but a pkcs7 message (but we need some wrapper, see efi_variable_parse_signature()) and will be validated by efi_variable_authenticate(), hence efi_signature_verify_with_db().

Associated time value will be encoded in "{...,time=...}" along with other UEFI variable's attributes.

---
 include/efi_loader.h          |   3 +
 lib/efi_loader/efi_variable.c | 666 ++++++++++++++++++++++++++++------
 2 files changed, 565 insertions(+), 104 deletions(-)

<snip>

Quoted 99 lines
lib/efi_loader/efi_variable.c +8 -1
index fe2f26459136..adb78470f2d6 100644
@@ -10,8 +10,14 @@
 #include <env_internal.h>
 #include <hexdump.h>
 #include <malloc.h>
+#include <rtc.h>
 #include <search.h>
+#include <linux/compat.h>
 #include <u-boot/crc.h>
+#include "../lib/crypto/pkcs7_parser.h"
+
+const efi_guid_t efi_guid_cert_type_pkcs7 = EFI_CERT_TYPE_PKCS7_GUID;
+static bool efi_secure_boot;
 
 #define READ_ONLY BIT(31)
 
@@ -106,9 +112,10 @@ static const char *prefix(const char *str, const char
 *prefix)
  *
  * @str:       value of U-Boot variable
  * @attrp:     pointer to UEFI attributes
+ * @timep:     pointer to time attribute
  * Return:     pointer to remainder of U-Boot variable value
  */
-static const char *parse_attr(const char *str, u32 *attrp)
+static const char *parse_attr(const char *str, u32 *attrp, u64 *timep)
 {
        u32 attr = 0;
        char sep = '{';
lib/efi_loader/efi_variable.c +6 -0
@@ -131,6 +138,12 @@ static const char *parse_attr(const char *str, u32
 *attrp)
                        attr |= EFI_VARIABLE_BOOTSERVICE_ACCESS;
                } else if ((s = prefix(str, "run"))) {
                        attr |= EFI_VARIABLE_RUNTIME_ACCESS;
+               } else if ((s = prefix(str, "time="))) {
+                       attr |=
 EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
+                       hex2bin((u8 *)timep, s, sizeof(*timep));
+                       s += sizeof(*timep) * 2;
+               } else if (*str == '}') {
+                       break;
                } else {
                        printf("invalid attribute: %s\n", str);
                        break;
lib/efi_loader/efi_variable.c +26 -8
@@ -148,48 +161,291 @@ static const char *parse_attr(const char *str, u32
 *attrp)
 }
 
 /**
- * efi_get_variable() - retrieve value of a UEFI variable
+ * efi_secure_boot_enabled - return if secure boot is enabled or not
  *
- * This function implements the GetVariable runtime service.
+ * Return:     true if enabled, false if disabled
+ */
+bool efi_secure_boot_enabled(void)
+{
+       return efi_secure_boot;
+}
+
+#ifdef CONFIG_EFI_SECURE_BOOT
+static u8 pkcs7_hdr[] = {
+       /* SEQUENCE */
+       0x30, 0x82, 0x05, 0xc7,
+       /* OID: pkcs7-signedData */
+       0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02,
+       /* Context Structured? */
+       0xa0, 0x82, 0x05, 0xb8,
+};
+
+/**
+ * efi_variable_parse_signature - parse a signature in variable
+ * @buf:       Pointer to variable's value
+ * @buflen:    Length of @buf
  *
- * See the Unified Extensible Firmware Interface (UEFI) specification for
- * details.
+ * Parse a signature embedded in variable's value and instantiate
+ * a pkcs7_message structure. Since pkcs7_parse_message() accepts only
+ * pkcs7's signedData, some header needed be prepended for correctly
+ * parsing authentication data, particularly for variable's.
  *
- * @variable_name:     name of the variable
- * @vendor:            vendor GUID
- * @attributes:                attributes of the variable
- * @data_size:         size of the buffer to which the variable value is

copied
- * @data: buffer to which the variable value is copied
- * Return: status code
+ * Return: Pointer to pkcs7_message structure on success, NULL on
error
*/

lib/efi_loader/efi_variable.c +0 -2
-efi_status_t EFIAPI efi_get_variable(u16 *variable_name,
-                                    const efi_guid_t *vendor, u32

*attributes,

lib/efi_loader/efi_variable.c static const char *parse_attr(const char *str, u32 *attrp) · line 196

Quoted 3 lines
lib/efi_loader/efi_variable.c +2 -1
-                                    efi_uintn_t *data_size, void *data)
+static struct pkcs7_message *efi_variable_parse_signature(const void *buf,
+                                                         size_t buflen)

This is a generic function used for parsing the pkcs7 header. This will also be used for capsule authentication. Can you move this under efi_signature.c as an api, and change the name to something like efi_parse_pkcs7_header.

-sughosh

#14 lore raw

PATCH v7 4/17 efi_loader: variable: support variable authentication

Quoted 135 lines · Sughosh Ganu

On Tue, 14 Apr 2020 at 08:23, AKASHI Takahiro
<takahiro.akashi at linaro.org <mailto:[email protected]>> wrote:

With this commit, EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS is supported for authenticated variables and the system secure state will transfer between setup mode and user mode as UEFI specification section 32.3 describes.

Internally, authentication data is stored as part of authenticated variable's value. It is nothing but a pkcs7 message (but we need some wrapper, see efi_variable_parse_signature()) and will be validated by efi_variable_authenticate(), hence efi_signature_verify_with_db().

Associated time value will be encoded in "{...,time=...}" along with other UEFI variable's attributes.

<mailto:[email protected]>>
---
?include/efi_loader.h? ? ? ? ? |? ?3 + ?lib/efi_loader/efi_variable.c | 666 ++++++++++++++++++++++++++++------ ?2 files changed, 565 insertions(+), 104 deletions(-)?

<snip>
?

    diff --git a/lib/efi_loader/efi_variable.c
    b/lib/efi_loader/efi_variable.c
    index fe2f26459136..adb78470f2d6 100644
    --- a/lib/efi_loader/efi_variable.c
    +++ b/lib/efi_loader/efi_variable.c
    @@ -10,8 +10,14 @@
    ?#include <env_internal.h>
    ?#include <hexdump.h>
    ?#include <malloc.h>
    +#include <rtc.h>
    ?#include <search.h>
    +#include <linux/compat.h>
    ?#include <u-boot/crc.h>
    +#include "../lib/crypto/pkcs7_parser.h"
    +
    +const efi_guid_t efi_guid_cert_type_pkcs7 = EFI_CERT_TYPE_PKCS7_GUID;
    +static bool efi_secure_boot;

    ?#define READ_ONLY BIT(31)

    @@ -106,9 +112,10 @@ static const char *prefix(const char *str,
    const char *prefix)
    ? *
    ? * @str:? ? ? ?value of U-Boot variable
    ? * @attrp:? ? ?pointer to UEFI attributes
    + * @timep:? ? ?pointer to time attribute
    ? * Return:? ? ?pointer to remainder of U-Boot variable value
    ? */
    -static const char *parse_attr(const char *str, u32 *attrp)
    +static const char *parse_attr(const char *str, u32 *attrp, u64 *timep)
    ?{
    ? ? ? ? u32 attr = 0;
    ? ? ? ? char sep = '{';
    @@ -131,6 +138,12 @@ static const char *parse_attr(const char *str,
    u32 *attrp)
    ? ? ? ? ? ? ? ? ? ? ? ? attr |= EFI_VARIABLE_BOOTSERVICE_ACCESS;
    ? ? ? ? ? ? ? ? } else if ((s = prefix(str, "run"))) {
    ? ? ? ? ? ? ? ? ? ? ? ? attr |= EFI_VARIABLE_RUNTIME_ACCESS;
    +? ? ? ? ? ? ? ?} else if ((s = prefix(str, "time="))) {
    +? ? ? ? ? ? ? ? ? ? ? ?attr |=
    EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
    +? ? ? ? ? ? ? ? ? ? ? ?hex2bin((u8 *)timep, s, sizeof(*timep));
    +? ? ? ? ? ? ? ? ? ? ? ?s += sizeof(*timep) * 2;
    +? ? ? ? ? ? ? ?} else if (*str == '}') {
    +? ? ? ? ? ? ? ? ? ? ? ?break;
    ? ? ? ? ? ? ? ? } else {
    ? ? ? ? ? ? ? ? ? ? ? ? printf("invalid attribute: %s\n", str);
    ? ? ? ? ? ? ? ? ? ? ? ? break;
    @@ -148,48 +161,291 @@ static const char *parse_attr(const char
    *str, u32 *attrp)
    ?}

    ?/**
    - * efi_get_variable() - retrieve value of a UEFI variable
    + * efi_secure_boot_enabled - return if secure boot is enabled or not
    ? *
    - * This function implements the GetVariable runtime service.
    + * Return:? ? ?true if enabled, false if disabled
    + */
    +bool efi_secure_boot_enabled(void)
    +{
    +? ? ? ?return efi_secure_boot;
    +}
    +
    +#ifdef CONFIG_EFI_SECURE_BOOT
    +static u8 pkcs7_hdr[] = {
    +? ? ? ?/* SEQUENCE */
    +? ? ? ?0x30, 0x82, 0x05, 0xc7,
    +? ? ? ?/* OID: pkcs7-signedData */
    +? ? ? ?0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07,
    0x02,
    +? ? ? ?/* Context Structured? */
    +? ? ? ?0xa0, 0x82, 0x05, 0xb8,
    +};
    +
    +/**
    + * efi_variable_parse_signature - parse a signature in variable
    + * @buf:? ? ? ?Pointer to variable's value
    + * @buflen:? ? Length of @buf
    ? *
    - * See the Unified Extensible Firmware Interface (UEFI)
    specification for
    - * details.
    + * Parse a signature embedded in variable's value and instantiate
    + * a pkcs7_message structure. Since pkcs7_parse_message() accepts only
    + * pkcs7's signedData, some header needed be prepended for correctly
    + * parsing authentication data, particularly for variable's.
    ? *
    - * @variable_name:? ? ?name of the variable
    - * @vendor:? ? ? ? ? ? vendor GUID
    - * @attributes:? ? ? ? ? ? ? ? attributes of the variable
    - * @data_size:? ? ? ? ?size of the buffer to which the variable
    value is copied
    - * @data:? ? ? ? ? ? ? buffer to which the variable value is copied
    - * Return:? ? ? ? ? ? ?status code
    + * Return:? ? ?Pointer to pkcs7_message structure on success, NULL
    on error
    ? */
    -efi_status_t EFIAPI efi_get_variable(u16 *variable_name,
    -? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? const efi_guid_t *vendor, u32
    *attributes,
    -? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? efi_uintn_t *data_size, void *data)
    +static struct pkcs7_message *efi_variable_parse_signature(const
    void *buf,
    +? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?size_t buflen)
Quoted 6 lines

This is a generic function used for parsing the pkcs7 header. This will also be used for capsule authentication. Can you move this under efi_signature.c as an api, and change the name to something like efi_parse_pkcs7_header.

-sughosh

Hello Sughosh,

the patch is already merged. Could you, please, provide a follow-up patch with the suggested change.

Best regards

Heinrich

#15 lore raw

PATCH v7 4/17 efi_loader: variable: support variable authentication

hello Heinrich,

Quoted 147 lines · Heinrich Schuchardt
Quoted 14 lines · Sughosh Ganu

On Tue, 14 Apr 2020 at 08:23, AKASHI Takahiro
<takahiro.akashi at linaro.org <mailto:[email protected]>> wrote:

With this commit, EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS is supported for authenticated variables and the system secure state will transfer between setup mode and user mode as UEFI specification section 32.3 describes.

Internally, authentication data is stored as part of authenticated variable's value. It is nothing but a pkcs7 message (but we need some wrapper, see efi_variable_parse_signature()) and will be validated by efi_variable_authenticate(), hence efi_signature_verify_with_db().

Quoted 8 lines

Associated time value will be encoded in "{...,time=...}" along with other UEFI variable's attributes.

<mailto:[email protected]>>
---
include/efi_loader.h | 3 +
lib/efi_loader/efi_variable.c | 666

++++++++++++++++++++++++++++------

Quoted 6 lines
     2 files changed, 565 insertions(+), 104 deletions(-)

<snip>

Quoted 16 lines
    diff --git a/lib/efi_loader/efi_variable.c
    b/lib/efi_loader/efi_variable.c
    index fe2f26459136..adb78470f2d6 100644
    --- a/lib/efi_loader/efi_variable.c
    +++ b/lib/efi_loader/efi_variable.c
    @@ -10,8 +10,14 @@
     #include <env_internal.h>
     #include <hexdump.h>
     #include <malloc.h>
    +#include <rtc.h>
     #include <search.h>
    +#include <linux/compat.h>
     #include <u-boot/crc.h>
    +#include "../lib/crypto/pkcs7_parser.h"
    +
    +const efi_guid_t efi_guid_cert_type_pkcs7 =

EFI_CERT_TYPE_PKCS7_GUID;

Quoted 4 lines

+static bool efi_secure_boot;

#define READ_ONLY BIT(31)

Quoted 10 lines

@@ -106,9 +112,10 @@ static const char *prefix(const char *str, const char *prefix)
*
* @str: value of U-Boot variable
* @attrp: pointer to UEFI attributes
+ * @timep: pointer to time attribute
* Return: pointer to remainder of U-Boot variable value
*/
-static const char *parse_attr(const char *str, u32 *attrp) +static const char *parse_attr(const char *str, u32 *attrp, u64

*timep)

Quoted 47 lines
     {
            u32 attr = 0;
            char sep = '{';
    @@ -131,6 +138,12 @@ static const char *parse_attr(const char *str,
    u32 *attrp)
                            attr |= EFI_VARIABLE_BOOTSERVICE_ACCESS;
                    } else if ((s = prefix(str, "run"))) {
                            attr |= EFI_VARIABLE_RUNTIME_ACCESS;
    +               } else if ((s = prefix(str, "time="))) {
    +                       attr |=
    EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
    +                       hex2bin((u8 *)timep, s, sizeof(*timep));
    +                       s += sizeof(*timep) * 2;
    +               } else if (*str == '}') {
    +                       break;
                    } else {
                            printf("invalid attribute: %s\n", str);
                            break;
    @@ -148,48 +161,291 @@ static const char *parse_attr(const char
    *str, u32 *attrp)
     }

     /**
    - * efi_get_variable() - retrieve value of a UEFI variable
    + * efi_secure_boot_enabled - return if secure boot is enabled or not
      *
    - * This function implements the GetVariable runtime service.
    + * Return:     true if enabled, false if disabled
    + */
    +bool efi_secure_boot_enabled(void)
    +{
    +       return efi_secure_boot;
    +}
    +
    +#ifdef CONFIG_EFI_SECURE_BOOT
    +static u8 pkcs7_hdr[] = {
    +       /* SEQUENCE */
    +       0x30, 0x82, 0x05, 0xc7,
    +       /* OID: pkcs7-signedData */
    +       0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07,
    0x02,
    +       /* Context Structured? */
    +       0xa0, 0x82, 0x05, 0xb8,
    +};
    +
    +/**
    + * efi_variable_parse_signature - parse a signature in variable
Quoted 8 lines
    + * @buf:       Pointer to variable's value
    + * @buflen:    Length of @buf
      *
    - * See the Unified Extensible Firmware Interface (UEFI)
    specification for
    - * details.
    + * Parse a signature embedded in variable's value and instantiate
    + * a pkcs7_message structure. Since pkcs7_parse_message() accepts

only

Quoted 9 lines

+ * pkcs7's signedData, some header needed be prepended for correctly
+ * parsing authentication data, particularly for variable's. *
- * @variable_name: name of the variable
- * @vendor: vendor GUID
- * @attributes: attributes of the variable
- * @data_size: size of the buffer to which the variable
value is copied
- * @data: buffer to which the variable value is copied

Quoted 8 lines

- * Return: status code
+ * Return: Pointer to pkcs7_message structure on success, NULL
on error
*/
-efi_status_t EFIAPI efi_get_variable(u16 *variable_name,
- const efi_guid_t *vendor, u32
*attributes,
- efi_uintn_t *data_size, void

*data)

Quoted 3 lines

+static struct pkcs7_message *efi_variable_parse_signature(const void *buf,
+ size_t

buflen)

Quoted 7 lines

This is a generic function used for parsing the pkcs7 header. This will also be used for capsule authentication. Can you move this under efi_signature.c as an api, and change the name to something like efi_parse_pkcs7_header.

Quoted 7 lines
Quoted 1 line

-sughosh

Hello Sughosh,

the patch is already merged. Could you, please, provide a follow-up patch with the suggested change.

Will do, as part of my capsule authentication changes. Thanks.

-sughosh

#16 lore raw

PATCH v7 5/17 efi_loader: variable: add secure boot state transition

In reply to AKASHI Takahiro

UEFI specification defines several global variables which are related to the current secure boot state. In this commit, those values will be maintained according to operations. Currently, AuditMode and DeployedMode are defined but not implemented.

---
 lib/efi_loader/efi_variable.c | 231 +++++++++++++++++++++++++++++++++-
 1 file changed, 228 insertions(+), 3 deletions(-)
lib/efi_loader/efi_variable.c +228 -3
index adb78470f2d6..fd5c41f830b1 100644
@@ -16,8 +16,16 @@
 #include <u-boot/crc.h>
 #include "../lib/crypto/pkcs7_parser.h"
 
+enum efi_secure_mode {
+	EFI_MODE_SETUP,
+	EFI_MODE_USER,
+	EFI_MODE_AUDIT,
+	EFI_MODE_DEPLOYED,
+};
+
 const efi_guid_t efi_guid_cert_type_pkcs7 = EFI_CERT_TYPE_PKCS7_GUID;
 static bool efi_secure_boot;
+static int efi_secure_mode;
 
 #define READ_ONLY BIT(31)
 
@@ -160,6 +168,210 @@ static const char *parse_attr(const char *str, u32 *attrp, u64 *timep)
 	return str;
 }
 
+static efi_status_t efi_set_variable_internal(u16 *variable_name,
+					      const efi_guid_t *vendor,
+					      u32 attributes,
+					      efi_uintn_t data_size,
+					      const void *data,
+					      bool ro_check);
+
+/**
+ * efi_transfer_secure_state - handle a secure boot state transition
+ * @mode:	new state
+ *
+ * Depending on @mode, secure boot related variables are updated.
+ * Those variables are *read-only* for users, efi_set_variable_internal()
+ * is called here.
+ *
+ * Return:	EFI_SUCCESS on success, status code (negative) on error
+ */
+static efi_status_t efi_transfer_secure_state(enum efi_secure_mode mode)
+{
+	u32 attributes;
+	u8 val;
+	efi_status_t ret;
+
+	debug("Secure state from %d to %d\n", efi_secure_mode, mode);
+
+	attributes = EFI_VARIABLE_BOOTSERVICE_ACCESS |
+		     EFI_VARIABLE_RUNTIME_ACCESS;
+	if (mode == EFI_MODE_DEPLOYED) {
+		val = 1;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+
+		efi_secure_boot = true;
+	} else if (mode == EFI_MODE_AUDIT) {
+		ret = efi_set_variable_internal(L"PK",
+						&efi_global_variable_guid,
+						attributes,
+						0, NULL,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+
+		efi_secure_boot = true;
+	} else if (mode == EFI_MODE_USER) {
+		val = 1;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+
+		efi_secure_boot = true;
+	} else if (mode == EFI_MODE_SETUP) {
+		val = 0;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+	} else {
+		return EFI_INVALID_PARAMETER;
+	}
+
+	return EFI_SUCCESS;
+
+err:
+	/* TODO: What action should be taken here? */
+	printf("ERROR: Secure state transition failed\n");
+	return ret;
+}
+
+/**
+ * efi_init_secure_state - initialize secure boot state
+ *
+ * Return:	EFI_SUCCESS on success, status code (negative) on error
+ */
+static efi_status_t efi_init_secure_state(void)
+{
+	efi_uintn_t size = 0;
+	efi_status_t ret;
+
+	ret = EFI_CALL(efi_get_variable(L"PK", &efi_global_variable_guid,
+					NULL, &size, NULL));
+	if (ret == EFI_BUFFER_TOO_SMALL && IS_ENABLED(CONFIG_EFI_SECURE_BOOT))
+		ret = efi_transfer_secure_state(EFI_MODE_USER);
+	else
+		ret = efi_transfer_secure_state(EFI_MODE_SETUP);
+
+	return ret;
+}
+
 /**
  * efi_secure_boot_enabled - return if secure boot is enabled or not
  *
@@ -910,10 +1122,19 @@ efi_status_t EFIAPI efi_set_variable_common(u16 *variable_name,
 	EFI_PRINT("setting: %s=%s\n", native_name, val);
 
 out:
-	if (env_set(native_name, val))
+	if (env_set(native_name, val)) {
 		ret = EFI_DEVICE_ERROR;
-	else
+	} else {
+		if ((u16_strcmp(variable_name, L"PK") == 0 &&
+		     guidcmp(vendor, &efi_global_variable_guid) == 0)) {
+			ret = efi_transfer_secure_state(
+					(delete ? EFI_MODE_SETUP :
+						  EFI_MODE_USER));
+			if (ret != EFI_SUCCESS)
+				goto err;
+		}
 		ret = EFI_SUCCESS;
+	}
 
 err:
 	free(native_name);
@@ -1098,5 +1319,9 @@ void efi_variables_boot_exit_notify(void)
  */
 efi_status_t efi_init_variables(void)
 {
-	return EFI_SUCCESS;
+	efi_status_t ret;
+
+	ret = efi_init_secure_state();
+
+	return ret;
 }
Signature · 1 line
2.25.2
#17 lore raw

PATCH v7 5/17 efi_loader: variable: add secure boot state transition

Quoted 49 lines · AKASHI Takahiro

UEFI specification defines several global variables which are related to the current secure boot state. In this commit, those values will be maintained according to operations. Currently, AuditMode and DeployedMode are defined but not implemented.

---
 lib/efi_loader/efi_variable.c | 231 +++++++++++++++++++++++++++++++++-
 1 file changed, 228 insertions(+), 3 deletions(-)
lib/efi_loader/efi_variable.c +22 -0
index adb78470f2d6..fd5c41f830b1 100644
@@ -16,8 +16,16 @@
 #include <u-boot/crc.h>
 #include "../lib/crypto/pkcs7_parser.h"
 
+enum efi_secure_mode {
+	EFI_MODE_SETUP,
+	EFI_MODE_USER,
+	EFI_MODE_AUDIT,
+	EFI_MODE_DEPLOYED,
+};
+
 const efi_guid_t efi_guid_cert_type_pkcs7 = EFI_CERT_TYPE_PKCS7_GUID;
 static bool efi_secure_boot;
+static int efi_secure_mode;
 
 #define READ_ONLY BIT(31)
 
@@ -160,6 +168,210 @@ static const char *parse_attr(const char *str, u32 *attrp, u64 *timep)
 	return str;
 }
 
+static efi_status_t efi_set_variable_internal(u16 *variable_name,
+					      const efi_guid_t *vendor,
+					      u32 attributes,
+					      efi_uintn_t data_size,
+					      const void *data,
+					      bool ro_check);
+
+/**
+ * efi_transfer_secure_state - handle a secure boot state transition
+ * @mode:	new state
+ *
+ * Depending on @mode, secure boot related variables are updated.
+ * Those variables are *read-only* for users, efi_set_variable_internal()
+ * is called here.

lib/efi_loader/efi_variable.c static const char *parse_attr(const char *str, u32 *attrp, u64 *timep) · line 194

Quoted 10 lines
lib/efi_loader/efi_variable.c +10 -0
+ *
+ * Return:	EFI_SUCCESS on success, status code (negative) on error
+ */
+static efi_status_t efi_transfer_secure_state(enum efi_secure_mode mode)
+{
+	u32 attributes;
+	u8 val;
+	efi_status_t ret;
+
+	debug("Secure state from %d to %d\n", efi_secure_mode, mode);

Do you mean "Switching secure state from %d to %d\n"?

lib/efi_loader/efi_variable.c static const char *parse_attr(const char *str, u32 *attrp, u64 *timep) · line 198

Quoted 4 lines
lib/efi_loader/efi_variable.c +4 -0
+
+	attributes = EFI_VARIABLE_BOOTSERVICE_ACCESS |
+		     EFI_VARIABLE_RUNTIME_ACCESS;
+	if (mode == EFI_MODE_DEPLOYED) {

Please, use switch.

Quoted 23 lines
lib/efi_loader/efi_variable.c +23 -0
+		val = 1;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)

lib/efi_loader/efi_variable.c static const char *parse_attr(const char *str, u32 *attrp, u64 *timep) · line 231

Quoted 10 lines
lib/efi_loader/efi_variable.c +10 -0
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+

You are repeating this code block four times. Please extract a function, eg. efi_set_secure_state(). Than this reduces to

switch (mode) {
case EFI_MODE_DEPLOYED:

	ret = efi_set_secure_stat(1, 0, 0, 1);
	break;
case EFI_MODE_AUDIT:
	ret = efi_set_variable_internal(L"PK",
					&efi_global_variable_guid,
					attributes,
					0, NULL, false);
	if (ret == EFI_SUCCESS)
		ret = efi_set_secure_stat(0, 1, 1, 0);
	break;
case EFI_MODE_USER:
	ret = efi_set_secure_stat(1, 0, 0, 0);
	break;

...

Best regards

Heinrich

Quoted 180 lines
lib/efi_loader/efi_variable.c +159 -3
+		efi_secure_boot = true;
+	} else if (mode == EFI_MODE_AUDIT) {
+		ret = efi_set_variable_internal(L"PK",
+						&efi_global_variable_guid,
+						attributes,
+						0, NULL,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+
+		efi_secure_boot = true;
+	} else if (mode == EFI_MODE_USER) {
+		val = 1;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+
+		efi_secure_boot = true;
+	} else if (mode == EFI_MODE_SETUP) {
+		val = 0;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+	} else {
+		return EFI_INVALID_PARAMETER;
+	}
+
+	return EFI_SUCCESS;
+
+err:
+	/* TODO: What action should be taken here? */
+	printf("ERROR: Secure state transition failed\n");
+	return ret;
+}
+
+/**
+ * efi_init_secure_state - initialize secure boot state
+ *
+ * Return:	EFI_SUCCESS on success, status code (negative) on error
+ */
+static efi_status_t efi_init_secure_state(void)
+{
+	efi_uintn_t size = 0;
+	efi_status_t ret;
+
+	ret = EFI_CALL(efi_get_variable(L"PK", &efi_global_variable_guid,
+					NULL, &size, NULL));
+	if (ret == EFI_BUFFER_TOO_SMALL && IS_ENABLED(CONFIG_EFI_SECURE_BOOT))
+		ret = efi_transfer_secure_state(EFI_MODE_USER);
+	else
+		ret = efi_transfer_secure_state(EFI_MODE_SETUP);
+
+	return ret;
+}
+
 /**
  * efi_secure_boot_enabled - return if secure boot is enabled or not
  *
@@ -910,10 +1122,19 @@ efi_status_t EFIAPI efi_set_variable_common(u16 *variable_name,
 	EFI_PRINT("setting: %s=%s\n", native_name, val);
 
 out:
-	if (env_set(native_name, val))
+	if (env_set(native_name, val)) {
 		ret = EFI_DEVICE_ERROR;
-	else
+	} else {
+		if ((u16_strcmp(variable_name, L"PK") == 0 &&
+		     guidcmp(vendor, &efi_global_variable_guid) == 0)) {
+			ret = efi_transfer_secure_state(
+					(delete ? EFI_MODE_SETUP :
+						  EFI_MODE_USER));
+			if (ret != EFI_SUCCESS)
+				goto err;
+		}
 		ret = EFI_SUCCESS;
+	}
 
 err:
 	free(native_name);
@@ -1098,5 +1319,9 @@ void efi_variables_boot_exit_notify(void)
  */
 efi_status_t efi_init_variables(void)
 {
-	return EFI_SUCCESS;
+	efi_status_t ret;
+
+	ret = efi_init_secure_state();
+
+	return ret;
 }
#18 lore raw

PATCH v7 5/17 efi_loader: variable: add secure boot state transition

Heinrich,

Quoted 122 lines · Heinrich Schuchardt
Quoted 49 lines · AKASHI Takahiro

UEFI specification defines several global variables which are related to the current secure boot state. In this commit, those values will be maintained according to operations. Currently, AuditMode and DeployedMode are defined but not implemented.

---
 lib/efi_loader/efi_variable.c | 231 +++++++++++++++++++++++++++++++++-
 1 file changed, 228 insertions(+), 3 deletions(-)
lib/efi_loader/efi_variable.c +22 -0
index adb78470f2d6..fd5c41f830b1 100644
@@ -16,8 +16,16 @@
 #include <u-boot/crc.h>
 #include "../lib/crypto/pkcs7_parser.h"
 
+enum efi_secure_mode {
+	EFI_MODE_SETUP,
+	EFI_MODE_USER,
+	EFI_MODE_AUDIT,
+	EFI_MODE_DEPLOYED,
+};
+
 const efi_guid_t efi_guid_cert_type_pkcs7 = EFI_CERT_TYPE_PKCS7_GUID;
 static bool efi_secure_boot;
+static int efi_secure_mode;
 
 #define READ_ONLY BIT(31)
 
@@ -160,6 +168,210 @@ static const char *parse_attr(const char *str, u32 *attrp, u64 *timep)
 	return str;
 }
 
+static efi_status_t efi_set_variable_internal(u16 *variable_name,
+					      const efi_guid_t *vendor,
+					      u32 attributes,
+					      efi_uintn_t data_size,
+					      const void *data,
+					      bool ro_check);
+
+/**
+ * efi_transfer_secure_state - handle a secure boot state transition
+ * @mode:	new state
+ *
+ * Depending on @mode, secure boot related variables are updated.
+ * Those variables are *read-only* for users, efi_set_variable_internal()
+ * is called here.

lib/efi_loader/efi_variable.c static const char *parse_attr(const char *str, u32 *attrp, u64 *timep) · line 194

Quoted 10 lines
lib/efi_loader/efi_variable.c +10 -0
+ *
+ * Return:	EFI_SUCCESS on success, status code (negative) on error
+ */
+static efi_status_t efi_transfer_secure_state(enum efi_secure_mode mode)
+{
+	u32 attributes;
+	u8 val;
+	efi_status_t ret;
+
+	debug("Secure state from %d to %d\n", efi_secure_mode, mode);

Do you mean "Switching secure state from %d to %d\n"?

lib/efi_loader/efi_variable.c static const char *parse_attr(const char *str, u32 *attrp, u64 *timep) · line 198

Quoted 4 lines
lib/efi_loader/efi_variable.c +4 -0
+
+	attributes = EFI_VARIABLE_BOOTSERVICE_ACCESS |
+		     EFI_VARIABLE_RUNTIME_ACCESS;
+	if (mode == EFI_MODE_DEPLOYED) {

Please, use switch.

Quoted 23 lines
lib/efi_loader/efi_variable.c +23 -0
+		val = 1;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)

lib/efi_loader/efi_variable.c static const char *parse_attr(const char *str, u32 *attrp, u64 *timep) · line 231

Quoted 10 lines
lib/efi_loader/efi_variable.c +10 -0
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+

You are repeating this code block four times. Please extract a function, eg. efi_set_secure_state(). Than this reduces to

switch (mode) {
case EFI_MODE_DEPLOYED:

	ret = efi_set_secure_stat(1, 0, 0, 1);
	break;
case EFI_MODE_AUDIT:
	ret = efi_set_variable_internal(L"PK",
					&efi_global_variable_guid,
					attributes,
					0, NULL, false);
	if (ret == EFI_SUCCESS)
		ret = efi_set_secure_stat(0, 1, 1, 0);
	break;
case EFI_MODE_USER:
	ret = efi_set_secure_stat(1, 0, 0, 0);
	break;
Quoted 1 line

...

Okay, but please let me know when you finish to review *all* the patches.
I have not changed the code in this commit for a long time (probably since v1) and don't want to repeatedly submit the whole set which is only partially reviewed.

Thanks,
-Takahiro Akashi

Quoted 185 lines

Best regards

Heinrich

Quoted 180 lines
lib/efi_loader/efi_variable.c +159 -3
+		efi_secure_boot = true;
+	} else if (mode == EFI_MODE_AUDIT) {
+		ret = efi_set_variable_internal(L"PK",
+						&efi_global_variable_guid,
+						attributes,
+						0, NULL,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+
+		efi_secure_boot = true;
+	} else if (mode == EFI_MODE_USER) {
+		val = 1;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+
+		efi_secure_boot = true;
+	} else if (mode == EFI_MODE_SETUP) {
+		val = 0;
+		ret = efi_set_variable_internal(L"SecureBoot",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 1;
+		ret = efi_set_variable_internal(L"SetupMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"AuditMode",
+						&efi_global_variable_guid,
+						attributes,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+		val = 0;
+		ret = efi_set_variable_internal(L"DeployedMode",
+						&efi_global_variable_guid,
+						attributes | READ_ONLY,
+						sizeof(val), &val,
+						false);
+		if (ret != EFI_SUCCESS)
+			goto err;
+	} else {
+		return EFI_INVALID_PARAMETER;
+	}
+
+	return EFI_SUCCESS;
+
+err:
+	/* TODO: What action should be taken here? */
+	printf("ERROR: Secure state transition failed\n");
+	return ret;
+}
+
+/**
+ * efi_init_secure_state - initialize secure boot state
+ *
+ * Return:	EFI_SUCCESS on success, status code (negative) on error
+ */
+static efi_status_t efi_init_secure_state(void)
+{
+	efi_uintn_t size = 0;
+	efi_status_t ret;
+
+	ret = EFI_CALL(efi_get_variable(L"PK", &efi_global_variable_guid,
+					NULL, &size, NULL));
+	if (ret == EFI_BUFFER_TOO_SMALL && IS_ENABLED(CONFIG_EFI_SECURE_BOOT))
+		ret = efi_transfer_secure_state(EFI_MODE_USER);
+	else
+		ret = efi_transfer_secure_state(EFI_MODE_SETUP);
+
+	return ret;
+}
+
 /**
  * efi_secure_boot_enabled - return if secure boot is enabled or not
  *
@@ -910,10 +1122,19 @@ efi_status_t EFIAPI efi_set_variable_common(u16 *variable_name,
 	EFI_PRINT("setting: %s=%s\n", native_name, val);
 
 out:
-	if (env_set(native_name, val))
+	if (env_set(native_name, val)) {
 		ret = EFI_DEVICE_ERROR;
-	else
+	} else {
+		if ((u16_strcmp(variable_name, L"PK") == 0 &&
+		     guidcmp(vendor, &efi_global_variable_guid) == 0)) {
+			ret = efi_transfer_secure_state(
+					(delete ? EFI_MODE_SETUP :
+						  EFI_MODE_USER));
+			if (ret != EFI_SUCCESS)
+				goto err;
+		}
 		ret = EFI_SUCCESS;
+	}
 
 err:
 	free(native_name);
@@ -1098,5 +1319,9 @@ void efi_variables_boot_exit_notify(void)
  */
 efi_status_t efi_init_variables(void)
 {
-	return EFI_SUCCESS;
+	efi_status_t ret;
+
+	ret = efi_init_secure_state();
+
+	return ret;
 }
#19 lore raw

PATCH v7 6/17 efi_loader: variable: add VendorKeys variable

In reply to AKASHI Takahiro

The following variable is exported as UEFI specification defines:
VendorKeys: whether the system is configured to use only vendor-provided
keys or not
The value will have to be modified if a platform has its own way of initializing signature database, in particular, PK.

---
 lib/efi_loader/efi_variable.c | 69 ++++++++++++++++++++++++++++++++---
 1 file changed, 63 insertions(+), 6 deletions(-)
lib/efi_loader/efi_variable.c +63 -6
index fd5c41f830b1..7df881a74b44 100644
@@ -26,6 +26,7 @@ enum efi_secure_mode {
 const efi_guid_t efi_guid_cert_type_pkcs7 = EFI_CERT_TYPE_PKCS7_GUID;
 static bool efi_secure_boot;
 static int efi_secure_mode;
+static u8 efi_vendor_keys;
 
 #define READ_ONLY BIT(31)
 
@@ -344,6 +345,8 @@ static efi_status_t efi_transfer_secure_state(enum efi_secure_mode mode)
 		return EFI_INVALID_PARAMETER;
 	}
 
+	efi_secure_mode = mode;
+
 	return EFI_SUCCESS;
 
 err:
@@ -359,16 +362,46 @@ err:
  */
 static efi_status_t efi_init_secure_state(void)
 {
-	efi_uintn_t size = 0;
+	enum efi_secure_mode mode;
+	efi_uintn_t size;
 	efi_status_t ret;
 
+	/*
+	 * TODO:
+	 * Since there is currently no "platform-specific" installation
+	 * method of Platform Key, we can't say if VendorKeys is 0 or 1
+	 * precisely.
+	 */
+
+	size = 0;
 	ret = EFI_CALL(efi_get_variable(L"PK", &efi_global_variable_guid,
 					NULL, &size, NULL));
-	if (ret == EFI_BUFFER_TOO_SMALL && IS_ENABLED(CONFIG_EFI_SECURE_BOOT))
-		ret = efi_transfer_secure_state(EFI_MODE_USER);
-	else
-		ret = efi_transfer_secure_state(EFI_MODE_SETUP);
+	if (ret == EFI_BUFFER_TOO_SMALL) {
+		if (IS_ENABLED(CONFIG_EFI_SECURE_BOOT))
+			mode = EFI_MODE_USER;
+		else
+			mode = EFI_MODE_SETUP;
+
+		efi_vendor_keys = 0;
+	} else if (ret == EFI_NOT_FOUND) {
+		mode = EFI_MODE_SETUP;
+		efi_vendor_keys = 1;
+	} else {
+		goto err;
+	}
 
+	ret = efi_transfer_secure_state(mode);
+	if (ret == EFI_SUCCESS)
+		ret = efi_set_variable_internal(L"VendorKeys",
+						&efi_global_variable_guid,
+						EFI_VARIABLE_BOOTSERVICE_ACCESS
+						 | EFI_VARIABLE_RUNTIME_ACCESS
+						 | READ_ONLY,
+						sizeof(efi_vendor_keys),
+						&efi_vendor_keys,
+						false);
+
+err:
 	return ret;
 }
 
@@ -1125,6 +1158,8 @@ out:
 	if (env_set(native_name, val)) {
 		ret = EFI_DEVICE_ERROR;
 	} else {
+		bool vendor_keys_modified = false;
+
 		if ((u16_strcmp(variable_name, L"PK") == 0 &&
 		     guidcmp(vendor, &efi_global_variable_guid) == 0)) {
 			ret = efi_transfer_secure_state(
@@ -1132,8 +1167,30 @@ out:
 						  EFI_MODE_USER));
 			if (ret != EFI_SUCCESS)
 				goto err;
+
+			if (efi_secure_mode != EFI_MODE_SETUP)
+				vendor_keys_modified = true;
+		} else if ((u16_strcmp(variable_name, L"KEK") == 0 &&
+		     guidcmp(vendor, &efi_global_variable_guid) == 0)) {
+			if (efi_secure_mode != EFI_MODE_SETUP)
+				vendor_keys_modified = true;
+		}
+
+		/* update VendorKeys */
+		if (vendor_keys_modified & efi_vendor_keys) {
+			efi_vendor_keys = 0;
+			ret = efi_set_variable_internal(
+						L"VendorKeys",
+						&efi_global_variable_guid,
+						EFI_VARIABLE_BOOTSERVICE_ACCESS
+						 | EFI_VARIABLE_RUNTIME_ACCESS
+						 | READ_ONLY,
+						sizeof(efi_vendor_keys),
+						&efi_vendor_keys,
+						false);
+		} else {
+			ret = EFI_SUCCESS;
 		}
-		ret = EFI_SUCCESS;
 	}
 
 err:
Signature · 1 line
2.25.2
#20 lore raw

PATCH v7 7/17 efi_loader: image_loader: support image authentication

In reply to AKASHI Takahiro

With this commit, image validation can be enforced, as UEFI specification section 32.5 describes, if CONFIG_EFI_SECURE_BOOT is enabled.

Currently we support
* authentication based on db and dbx,
so dbx-validated image will always be rejected.
* following signature types:
EFI_CERT_SHA256_GUID (SHA256 digest for unsigned images) EFI_CERT_X509_GUID (x509 certificate for signed images)
Timestamp-based certificate revocation is not supported here.

Internally, authentication data is stored in one of certificates tables of PE image (See efi_image_parse()) and will be verified by efi_image_authenticate() before loading a given image.

It seems that UEFI specification defines the verification process in a bit ambiguous way. I tried to implement it as closely to as EDK2 does.

---
 include/efi_loader.h              |  13 +-
 lib/efi_loader/efi_boottime.c     |  10 +-
 lib/efi_loader/efi_image_loader.c | 462 +++++++++++++++++++++++++++++-
 3 files changed, 469 insertions(+), 16 deletions(-)
include/efi_loader.h +12 -1
index ef8d184a6ee7..0ba9a1f702a6 100644
@@ -11,6 +11,7 @@
 #include <common.h>
 #include <part_efi.h>
 #include <efi_api.h>
+#include <pe.h>
 
 static inline int guidcmp(const void *g1, const void *g2)
 {
@@ -263,6 +264,11 @@ struct efi_object {
 	enum efi_object_type type;
 };
 
+enum efi_image_auth_status {
+	EFI_IMAGE_AUTH_FAILED = 0,
+	EFI_IMAGE_AUTH_PASSED,
+};
+
 /**
  * struct efi_loaded_image_obj - handle of a loaded image
  *
@@ -282,6 +288,7 @@ struct efi_loaded_image_obj {
 	EFIAPI efi_status_t (*entry)(efi_handle_t image_handle,
 				     struct efi_system_table *st);
 	u16 image_type;
+	enum efi_image_auth_status auth_status;
 };
 
 /**
@@ -415,7 +422,8 @@ efi_status_t efi_set_watchdog(unsigned long timeout);
 /* Called from places to check whether a timer expired */
 void efi_timer_check(void);
 /* PE loader implementation */
-efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle, void *efi,
+efi_status_t efi_load_pe(struct efi_loaded_image_obj *handle,
+			 void *efi, size_t efi_size,
 			 struct efi_loaded_image *loaded_image_info);
 /* Called once to store the pristine gd pointer */
 void efi_save_gd(void);
@@ -756,6 +764,9 @@ void efi_sigstore_free(struct efi_signature_store *sigstore);
 struct efi_signature_store *efi_sigstore_parse_sigdb(u16 *name);
 
 bool efi_secure_boot_enabled(void);
+
+bool efi_image_parse(void *efi, size_t len, struct efi_image_regions **regp,
+		     WIN_CERTIFICATE **auth, size_t *auth_len);
 #endif /* CONFIG_EFI_SECURE_BOOT */
 
 #else /* CONFIG_IS_ENABLED(EFI_LOADER) */
lib/efi_loader/efi_boottime.c +8 -2
index 3b79a88a480f..a3f11eaf6228 100644
@@ -1882,12 +1882,12 @@ efi_status_t EFIAPI efi_load_image(bool boot_policy,
 	efi_dp_split_file_path(file_path, &dp, &fp);
 	ret = efi_setup_loaded_image(dp, fp, image_obj, &info);
 	if (ret == EFI_SUCCESS)
-		ret = efi_load_pe(*image_obj, dest_buffer, info);
+		ret = efi_load_pe(*image_obj, dest_buffer, source_size, info);
 	if (!source_buffer)
 		/* Release buffer to which file was loaded */
 		efi_free_pages((uintptr_t)dest_buffer,
 			       efi_size_in_pages(source_size));
-	if (ret == EFI_SUCCESS) {
+	if (ret == EFI_SUCCESS || ret == EFI_SECURITY_VIOLATION) {
 		info->system_table = &systab;
 		info->parent_handle = parent_image;
 	} else {
@@ -2885,10 +2885,16 @@ efi_status_t EFIAPI efi_start_image(efi_handle_t image_handle,
 
 	EFI_ENTRY("%p, %p, %p", image_handle, exit_data_size, exit_data);
 
+	if (!efi_search_obj(image_handle))
+		return EFI_EXIT(EFI_INVALID_PARAMETER);
+
 	/* Check parameters */
 	if (image_obj->header.type != EFI_OBJECT_TYPE_LOADED_IMAGE)
 		return EFI_EXIT(EFI_INVALID_PARAMETER);
 
+	if (image_obj->auth_status != EFI_IMAGE_AUTH_PASSED)
+		return EFI_EXIT(EFI_SECURITY_VIOLATION);
+
 	ret = EFI_CALL(efi_open_protocol(image_handle, &efi_guid_loaded_image,
 					 &info, NULL, NULL,
 					 EFI_OPEN_PROTOCOL_GET_PROTOCOL));
lib/efi_loader/efi_image_loader.c +449 -13

542 lines not on this page · raw message

Signature · 1 line
2.25.2
#21 lore raw

PATCH v7 8/17 efi_loader: set up secure boot

In reply to AKASHI Takahiro

The following variable is exported as UEFI specification defines:
SignatureSupport: array of GUIDs representing the type of signatures
supported by the platform firmware

---
 lib/efi_loader/efi_setup.c | 38 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 38 insertions(+)
lib/efi_loader/efi_setup.c +38 -0
index b458093dfbd5..1b648c84673a 100644
@@ -82,6 +82,39 @@ out:
 	return ret;
 }
 
+#ifdef CONFIG_EFI_SECURE_BOOT
+/**
+ * efi_init_secure_boot - initialize secure boot state
+ *
+ * Return:	EFI_SUCCESS on success, status code (negative) on error
+ */
+static efi_status_t efi_init_secure_boot(void)
+{
+	efi_guid_t signature_types[] = {
+		EFI_CERT_SHA256_GUID,
+		EFI_CERT_X509_GUID,
+	};
+	efi_status_t ret;
+
+	/* TODO: read-only */
+	ret = EFI_CALL(efi_set_variable(L"SignatureSupport",
+					&efi_global_variable_guid,
+					EFI_VARIABLE_BOOTSERVICE_ACCESS
+					 | EFI_VARIABLE_RUNTIME_ACCESS,
+					sizeof(signature_types),
+					&signature_types));
+	if (ret != EFI_SUCCESS)
+		printf("EFI: cannot initialize SignatureSupport variable\n");
+
+	return ret;
+}
+#else
+static efi_status_t efi_init_secure_boot(void)
+{
+	return EFI_SUCCESS;
+}
+#endif /* CONFIG_EFI_SECURE_BOOT */
+
 /**
  * efi_init_obj_list() - Initialize and populate EFI object list
  *
@@ -127,6 +160,11 @@ efi_status_t efi_init_obj_list(void)
 	if (ret != EFI_SUCCESS)
 		goto out;
 
+	/* Secure boot */
+	ret = efi_init_secure_boot();
+	if (ret != EFI_SUCCESS)
+		goto out;
+
 	/* Indicate supported runtime services */
 	ret = efi_init_runtime_supported();
 	if (ret != EFI_SUCCESS)
Signature · 1 line
2.25.2
#22 lore raw

PATCH v7 9/17 cmd: env: use appropriate guid for authenticated UEFI variable

In reply to AKASHI Takahiro

A signature database variable is associated with a specific guid. For convenience, if user doesn't supply any guid info, "env set|print -e" should complement it.

---
 cmd/nvedit_efi.c | 18 ++++++++++++++----
 1 file changed, 14 insertions(+), 4 deletions(-)
cmd/nvedit_efi.c +14 -4
index 8ea0da01283f..579cf430593c 100644
@@ -41,6 +41,11 @@ static const struct {
 } efi_guid_text[] = {
 	/* signature database */
 	{EFI_GLOBAL_VARIABLE_GUID, "EFI_GLOBAL_VARIABLE_GUID"},
+	{EFI_IMAGE_SECURITY_DATABASE_GUID, "EFI_IMAGE_SECURITY_DATABASE_GUID"},
+	/* certificate type */
+	{EFI_CERT_SHA256_GUID, "EFI_CERT_SHA256_GUID"},
+	{EFI_CERT_X509_GUID, "EFI_CERT_X509_GUID"},
+	{EFI_CERT_TYPE_PKCS7_GUID, "EFI_CERT_TYPE_PKCS7_GUID"},
 };
 
 /* "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" */
@@ -525,9 +530,9 @@ int do_env_set_efi(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
 			if (*ep != ',')
 				return CMD_RET_USAGE;
 
+			/* 0 should be allowed for delete */
 			size = simple_strtoul(++ep, NULL, 16);
-			if (!size)
-				return CMD_RET_FAILURE;
+
 			value_on_memory = true;
 		} else if (!strcmp(argv[0], "-v")) {
 			verbose = true;
@@ -539,8 +544,13 @@ int do_env_set_efi(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
 		return CMD_RET_USAGE;
 
 	var_name = argv[0];
-	if (default_guid)
-		guid = efi_global_variable_guid;
+	if (default_guid) {
+		if (!strcmp(var_name, "db") || !strcmp(var_name, "dbx") ||
+		    !strcmp(var_name, "dbt"))
+			guid = efi_guid_image_security_database;
+		else
+			guid = efi_global_variable_guid;
+	}
 
 	if (verbose) {
 		printf("GUID: %s\n", efi_guid_to_str((const efi_guid_t *)
Signature · 1 line
2.25.2
#23 lore raw

PATCH v7 10/17 cmd: env: add "-at" option to "env set -e" command

In reply to AKASHI Takahiro

With "-at" option, EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS will be passed to SetVariable() to authenticate the variable.

---
 cmd/nvedit.c     | 5 +++--
 cmd/nvedit_efi.c | 5 ++++-
 2 files changed, 7 insertions(+), 3 deletions(-)
cmd/nvedit.c +3 -2
index 81d94cd193c6..966c13405956 100644
@@ -1417,7 +1417,7 @@ static char env_help_text[] =
 #endif
 #endif
 #if defined(CONFIG_CMD_NVEDIT_EFI)
-	"env set -e [-nv][-bs][-rt][-a][-i addr,size][-v] name [arg ...]\n"
+	"env set -e [-nv][-bs][-rt][-at][-a][-i addr,size][-v] name [arg ...]\n"
 	"    - set UEFI variable; unset if '-i' or 'arg' not specified\n"
 #endif
 	"env set [-f] name [arg ...]\n";
@@ -1479,13 +1479,14 @@ U_BOOT_CMD_COMPLETE(
 	setenv, CONFIG_SYS_MAXARGS, 0,	do_env_set,
 	"set environment variables",
 #if defined(CONFIG_CMD_NVEDIT_EFI)
-	"-e [-guid guid][-nv][-bs][-rt][-a][-v]\n"
+	"-e [-guid guid][-nv][-bs][-rt][-at][-a][-v]\n"
 	"        [-i addr,size name], or [name [value ...]]\n"
 	"    - set UEFI variable 'name' to 'value' ...'\n"
 	"      \"-guid\": set vendor guid\n"
 	"      \"-nv\": set non-volatile attribute\n"
 	"      \"-bs\": set boot-service attribute\n"
 	"      \"-rt\": set runtime attribute\n"
+	"      \"-at\": set time-based authentication attribute\n"
 	"      \"-a\": append-write\n"
 	"      \"-i addr,size\": use <addr,size> as variable's value\n"
 	"      \"-v\": verbose message\n"
cmd/nvedit_efi.c +4 -1
index 579cf430593c..837e39e02179 100644
@@ -458,7 +458,7 @@ out:
  * Return:	CMD_RET_SUCCESS on success, or CMD_RET_RET_FAILURE
  *
  * This function is for "env set -e" or "setenv -e" command:
- *   => env set -e [-guid guid][-nv][-bs][-rt][-a][-v]
+ *   => env set -e [-guid guid][-nv][-bs][-rt][-at][-a][-v]
  *		   [-i address,size] var, or
  *                 var [value ...]
  * Encode values specified and set given UEFI variable.
@@ -517,6 +517,9 @@ int do_env_set_efi(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
 			attributes |= EFI_VARIABLE_RUNTIME_ACCESS;
 		} else if (!strcmp(argv[0], "-nv")) {
 			attributes |= EFI_VARIABLE_NON_VOLATILE;
+		} else if (!strcmp(argv[0], "-at")) {
+			attributes |=
+			  EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
 		} else if (!strcmp(argv[0], "-a")) {
 			attributes |= EFI_VARIABLE_APPEND_WRITE;
 		} else if (!strcmp(argv[0], "-i")) {
Signature · 1 line
2.25.2
#24 lore raw

PATCH v7 11/17 cmd: efidebug: add "test bootmgr" sub-command

In reply to AKASHI Takahiro

This sub-command will be used to test image authentication, in particular, a case where efi_load_image() failed with EFI_SECURITY_VIOLATION but we still want to try efi_start_image(). We won't run such a case under normal bootmgr because it simply refuses to call efi_start_image() if anything but EFI_SUCCESS is returned when loading an image.

---
 cmd/efidebug.c | 78 +++++++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 77 insertions(+), 1 deletion(-)
cmd/efidebug.c +77 -1
index bb7c13d6a1ce..9769aeeac58b 100644
@@ -1087,6 +1087,78 @@ static int do_efi_boot_opt(cmd_tbl_t *cmdtp, int flag,
 	return cp->cmd(cmdtp, flag, argc, argv);
 }
 
+/**
+ * do_efi_test_bootmgr() - run simple bootmgr for test
+ *
+ * @cmdtp:	Command table
+ * @flag:	Command flag
+ * @argc:	Number of arguments
+ * @argv:	Argument array
+ * Return:	CMD_RET_SUCCESS on success,
+ *		CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
+ *
+ * Implement efidebug "test bootmgr" sub-command.
+ * Run simple bootmgr for test.
+ *
+ *     efidebug test bootmgr
+ */
+static int do_efi_test_bootmgr(cmd_tbl_t *cmdtp, int flag,
+			       int argc, char * const argv[])
+{
+	efi_handle_t image;
+	efi_uintn_t exit_data_size = 0;
+	u16 *exit_data = NULL;
+	efi_status_t ret;
+
+	ret = efi_bootmgr_load(&image);
+	printf("efi_bootmgr_load() returned: %ld\n", ret & ~EFI_ERROR_MASK);
+
+	/* We call efi_start_image() even if error for test purpose. */
+	ret = EFI_CALL(efi_start_image(image, &exit_data_size, &exit_data));
+	printf("efi_start_image() returned: %ld\n", ret & ~EFI_ERROR_MASK);
+	if (ret && exit_data)
+		efi_free_pool(exit_data);
+
+	efi_restore_gd();
+
+	return CMD_RET_SUCCESS;
+}
+
+static cmd_tbl_t cmd_efidebug_test_sub[] = {
+	U_BOOT_CMD_MKENT(bootmgr, CONFIG_SYS_MAXARGS, 1, do_efi_test_bootmgr,
+			 "", ""),
+};
+
+/**
+ * do_efi_test() - manage UEFI load options
+ *
+ * @cmdtp:	Command table
+ * @flag:	Command flag
+ * @argc:	Number of arguments
+ * @argv:	Argument array
+ * Return:	CMD_RET_SUCCESS on success,
+ *		CMD_RET_USAGE or CMD_RET_RET_FAILURE on failure
+ *
+ * Implement efidebug "test" sub-command.
+ */
+static int do_efi_test(cmd_tbl_t *cmdtp, int flag,
+		       int argc, char * const argv[])
+{
+	cmd_tbl_t *cp;
+
+	if (argc < 2)
+		return CMD_RET_USAGE;
+
+	argc--; argv++;
+
+	cp = find_cmd_tbl(argv[0], cmd_efidebug_test_sub,
+			  ARRAY_SIZE(cmd_efidebug_test_sub));
+	if (!cp)
+		return CMD_RET_USAGE;
+
+	return cp->cmd(cmdtp, flag, argc, argv);
+}
+
 static cmd_tbl_t cmd_efidebug_sub[] = {
 	U_BOOT_CMD_MKENT(boot, CONFIG_SYS_MAXARGS, 1, do_efi_boot_opt, "", ""),
 	U_BOOT_CMD_MKENT(devices, CONFIG_SYS_MAXARGS, 1, do_efi_show_devices,
@@ -1101,6 +1173,8 @@ static cmd_tbl_t cmd_efidebug_sub[] = {
 			 "", ""),
 	U_BOOT_CMD_MKENT(tables, CONFIG_SYS_MAXARGS, 1, do_efi_show_tables,
 			 "", ""),
+	U_BOOT_CMD_MKENT(test, CONFIG_SYS_MAXARGS, 1, do_efi_test,
+			 "", ""),
 };
 
 /**
@@ -1170,7 +1244,9 @@ static char efidebug_help_text[] =
 	"efidebug memmap\n"
 	"  - show UEFI memory map\n"
 	"efidebug tables\n"
-	"  - show UEFI configuration tables\n";
+	"  - show UEFI configuration tables\n"
+	"efidebug test bootmgr\n"
+	"  - run simple bootmgr for test\n";
 #endif
 
 U_BOOT_CMD(
Signature · 1 line
2.25.2
#25 lore raw

PATCH v7 12/17 efi_loader, pytest: set up secure boot environment

In reply to AKASHI Takahiro

A fixture for UEFI secure boot tests (image authentication and variable authentication) is defined. A small file system with test data in a single partition formatted in fat is created.

This test requires efitools v1.5.2 or later. If the system's efitools is older, you have to build it on your own and define EFITOOLS_PATH.

---
 test/py/README.md                          |   8 ++
 test/py/tests/test_efi_secboot/conftest.py | 151 +++++++++++++++++++++
 test/py/tests/test_efi_secboot/defs.py     |  21 +++
 3 files changed, 180 insertions(+)
 create mode 100644 test/py/tests/test_efi_secboot/conftest.py
 create mode 100644 test/py/tests/test_efi_secboot/defs.py
test/py/README.md +8 -0
index 3cbe01b73e28..aa8a5607b064 100644
@@ -37,7 +37,15 @@ will be required.  The following is an incomplete list:
 | openssl        |
 | sudo OR guestmount |
 | e2fsprogs      |
+| util-linux     |
+| coreutils      |
 | dosfstools     |
+| efitools       |
+| mount          |
+| mtools         |
+| sbsigntool     |
+| udisks2        |
+
 
 Please use the apporirate commands for your distribution to match these tools
 up with the package that provides them.
test/py/tests/test_efi_secboot/conftest.py new file +151 -0

151 lines not on this page · raw message

test/py/tests/test_efi_secboot/defs.py new file +21 -0
new file mode 100644
index 000000000000..d6222809c547
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier:      GPL-2.0+
+
+# Disk image name
+EFI_SECBOOT_IMAGE_NAME='test_efi_secboot.img'
+
+# Size in MiB
+EFI_SECBOOT_IMAGE_SIZE=16
+EFI_SECBOOT_PART_SIZE=8
+
+# Partition file system type
+EFI_SECBOOT_FS_TYPE='vfat'
+
+# Owner guid
+GUID='11111111-2222-3333-4444-123456789abc'
+
+# v1.5.1 or earlier of efitools has a bug in sha256 calculation, and
+# you need build a newer version on your own.
+EFITOOLS_PATH=''
+
+# Hello World application for sandbox
+HELLO_PATH=''
Signature · 1 line
2.25.2
#26 lore raw

PATCH v7 12/17 efi_loader, pytest: set up secure boot environment

Quoted 105 lines · AKASHI Takahiro

A fixture for UEFI secure boot tests (image authentication and variable authentication) is defined. A small file system with test data in a single partition formatted in fat is created.

This test requires efitools v1.5.2 or later. If the system's efitools is older, you have to build it on your own and define EFITOOLS_PATH.

---
 test/py/README.md                          |   8 ++
 test/py/tests/test_efi_secboot/conftest.py | 151 +++++++++++++++++++++
 test/py/tests/test_efi_secboot/defs.py     |  21 +++
 3 files changed, 180 insertions(+)
 create mode 100644 test/py/tests/test_efi_secboot/conftest.py
 create mode 100644 test/py/tests/test_efi_secboot/defs.py
test/py/README.md +8 -0
index 3cbe01b73e28..aa8a5607b064 100644
@@ -37,7 +37,15 @@ will be required.  The following is an incomplete list:
 | openssl        |
 | sudo OR guestmount |
 | e2fsprogs      |
+| util-linux     |
+| coreutils      |
 | dosfstools     |
+| efitools       |
+| mount          |
+| mtools         |
+| sbsigntool     |
+| udisks2        |
+
 
 Please use the apporirate commands for your distribution to match these tools
 up with the package that provides them.
test/py/tests/test_efi_secboot/conftest.py new file +63 -0
new file mode 100644
index 000000000000..e542fef6e819
@@ -0,0 +1,151 @@
+# SPDX-License-Identifier:      GPL-2.0+
+# Copyright (c) 2019, Linaro Limited
+# Author: AKASHI Takahiro <[email protected]>
+
+import os
+import os.path
+import pytest
+import re
+from subprocess import call, check_call, check_output, CalledProcessError
+from defs import *
+
+# from test/py/conftest.py
+def tool_is_in_path(tool):
+    for path in os.environ["PATH"].split(os.pathsep):
+        fn = os.path.join(path, tool)
+        if os.path.isfile(fn) and os.access(fn, os.X_OK):
+            return True
+    return False
+
+#
+# Fixture for UEFI secure boot test
+#
+ at pytest.fixture(scope='session')
+def efi_boot_env(request, u_boot_config):
+    """Set up a file system to be used in UEFI secure boot test.
+
+    Args:
+        request: Pytest request object.
+	u_boot_config: U-boot configuration.
+
+    Return:
+        A path to disk image to be used for testing
+    """
+    global HELLO_PATH
+
+    image_path = u_boot_config.persistent_data_dir
+    image_path = image_path + '/' + EFI_SECBOOT_IMAGE_NAME
+    image_size = EFI_SECBOOT_IMAGE_SIZE
+    part_size = EFI_SECBOOT_PART_SIZE
+    fs_type = EFI_SECBOOT_FS_TYPE
+
+    if HELLO_PATH == '':
+        HELLO_PATH = u_boot_config.build_dir + '/lib/efi_loader/helloworld.efi'
+
+    try:
+        non_root = tool_is_in_path('udisksctl')
+
+        # create a disk/partition
+        check_call('dd if=/dev/zero of=%s bs=1MiB count=%d'
+                            % (image_path, image_size), shell=True)
+        check_call('sgdisk %s -n 1:0:+%dMiB'
+                            % (image_path, part_size), shell=True)
+        # create a file system
+        check_call('dd if=/dev/zero of=%s.tmp bs=1MiB count=%d'
+                            % (image_path, part_size), shell=True)
+        check_call('mkfs -t %s %s.tmp' % (fs_type, image_path), shell=True)
+        check_call('dd if=%s.tmp of=%s bs=1MiB seek=1 count=%d conv=notrunc'
+                            % (image_path, image_path, 1), shell=True)
+        check_call('rm %s.tmp' % image_path, shell=True)
+        if non_root:
+            out_data = check_output('udisksctl loop-setup -f %s -o %d'
+                                % (image_path, 1048576), shell=True).decode()
+            m = re.search('(?<= as )(.*)\.', out_data)

test/py/tests/test_efi_secboot/conftest.py line 73

Quoted 10 lines
test/py/tests/test_efi_secboot/conftest.py new file +10 -0
+            loop_dev = m.group(1)
+            # print 'loop device is: %s' % loop_dev
+            out_data = check_output('udisksctl info -b %s'
+                                % loop_dev, shell=True).decode()
+            m = re.search('MountPoints:[ \t]+(.*)', out_data)
+            mnt_point = m.group(1)
+        else:
+            loop_dev = check_output('sudo losetup -o 1MiB --sizelimit %dMiB --show -f %s | tr -d "\n"'
+                                % (part_size, image_path), shell=True).decode()
+            mnt_point = '/mnt'

This is not a good idea. On my systems I have a mount /mnt/iscsi and this is where I checked out the u-boot repository where I run 'make tests'. Other people may also have mounted something of importance in /mnt.

Please, supply a followi up patch creating a directory in the build path for mounting.

Best regards

Heinrich

Quoted 106 lines
test/py/tests/test_efi_secboot/conftest.py new file +78 -0
+            check_output('sudo mount -t %s -o umask=000 %s %s'
+                                % (fs_type, loop_dev, mnt_point), shell=True)
+
+        # print 'mount point is: %s' % mnt_point
+
+        # suffix
+        # *.key: RSA private key in PEM
+        # *.crt: X509 certificate (self-signed) in PEM
+        # *.esl: signature list
+        # *.hash: message digest of image as signature list
+        # *.auth: signed signature list in signature database format
+        # *.efi: UEFI image
+        # *.efi.signed: signed UEFI image
+
+        # Create signature database
+        ## PK
+        check_call('cd %s; openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_PK/ -keyout PK.key -out PK.crt -nodes -days 365'
+                            % mnt_point, shell=True)
+        check_call('cd %s; %scert-to-efi-sig-list -g %s PK.crt PK.esl; %ssign-efi-sig-list -c PK.crt -k PK.key PK PK.esl PK.auth'
+                            % (mnt_point, EFITOOLS_PATH, GUID, EFITOOLS_PATH),
+                            shell=True)
+        ## PK_null for deletion
+        check_call('cd %s; sleep 2; touch PK_null.esl; %ssign-efi-sig-list -c PK.crt -k PK.key PK PK_null.esl PK_null.auth'
+                            % (mnt_point, EFITOOLS_PATH), shell=True)
+        ## KEK
+        check_call('cd %s; openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_KEK/ -keyout KEK.key -out KEK.crt -nodes -days 365'
+                            % mnt_point, shell=True)
+        check_call('cd %s; %scert-to-efi-sig-list -g %s KEK.crt KEK.esl; %ssign-efi-sig-list -c PK.crt -k PK.key KEK KEK.esl KEK.auth'
+                            % (mnt_point, EFITOOLS_PATH, GUID, EFITOOLS_PATH),
+                            shell=True)
+        ## db
+        check_call('cd %s; openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_db/ -keyout db.key -out db.crt -nodes -days 365'
+                            % mnt_point, shell=True)
+        check_call('cd %s; %scert-to-efi-sig-list -g %s db.crt db.esl; %ssign-efi-sig-list -c KEK.crt -k KEK.key db db.esl db.auth'
+                            % (mnt_point, EFITOOLS_PATH, GUID, EFITOOLS_PATH),
+                            shell=True)
+        ## db1
+        check_call('cd %s; openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_db1/ -keyout db1.key -out db1.crt -nodes -days 365'
+                            % mnt_point, shell=True)
+        check_call('cd %s; %scert-to-efi-sig-list -g %s db1.crt db1.esl; %ssign-efi-sig-list -c KEK.crt -k KEK.key db db1.esl db1.auth'
+                            % (mnt_point, EFITOOLS_PATH, GUID, EFITOOLS_PATH),
+                            shell=True)
+        ## db1-update
+        check_call('cd %s; %ssign-efi-sig-list -a -c KEK.crt -k KEK.key db db1.esl db1-update.auth'
+                            % (mnt_point, EFITOOLS_PATH), shell=True)
+        ## dbx
+        check_call('cd %s; openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_dbx/ -keyout dbx.key -out dbx.crt -nodes -days 365'
+                            % mnt_point, shell=True)
+        check_call('cd %s; %scert-to-efi-sig-list -g %s dbx.crt dbx.esl; %ssign-efi-sig-list -c KEK.crt -k KEK.key dbx dbx.esl dbx.auth'
+                            % (mnt_point, EFITOOLS_PATH, GUID, EFITOOLS_PATH),
+                            shell=True)
+
+        # Copy image
+        check_call('cp %s %s' % (HELLO_PATH, mnt_point), shell=True)
+
+        ## Sign image
+        check_call('cd %s; sbsign --key db.key --cert db.crt helloworld.efi'
+                            % mnt_point, shell=True)
+        ## Digest image
+        check_call('cd %s; %shash-to-efi-sig-list helloworld.efi db_hello.hash; %ssign-efi-sig-list -c KEK.crt -k KEK.key db db_hello.hash db_hello.auth'
+                            % (mnt_point, EFITOOLS_PATH, EFITOOLS_PATH),
+                            shell=True)
+
+        if non_root:
+            check_call('udisksctl unmount -b %s' % loop_dev, shell=True)
+            # not needed
+            # check_call('udisksctl loop-delete -b %s' % loop_dev, shell=True)
+        else:
+            check_call('sudo umount %s' % loop_dev, shell=True)
+            check_call('sudo losetup -d %s' % loop_dev, shell=True)
+
+    except CalledProcessError as e:
+        pytest.skip('Setup failed: %s' % e.cmd)
+        return
+    else:
+        yield image_path
+    finally:
+        call('rm -f %s' % image_path, shell=True)
test/py/tests/test_efi_secboot/defs.py new file +21 -0
new file mode 100644
index 000000000000..d6222809c547
@@ -0,0 +1,21 @@
+# SPDX-License-Identifier:      GPL-2.0+
+
+# Disk image name
+EFI_SECBOOT_IMAGE_NAME='test_efi_secboot.img'
+
+# Size in MiB
+EFI_SECBOOT_IMAGE_SIZE=16
+EFI_SECBOOT_PART_SIZE=8
+
+# Partition file system type
+EFI_SECBOOT_FS_TYPE='vfat'
+
+# Owner guid
+GUID='11111111-2222-3333-4444-123456789abc'
+
+# v1.5.1 or earlier of efitools has a bug in sha256 calculation, and
+# you need build a newer version on your own.
+EFITOOLS_PATH=''
+
+# Hello World application for sandbox
+HELLO_PATH=''
#27 lore raw

PATCH v7 13/17 efi_loader, pytest: add UEFI secure boot tests (authenticated variables)

In reply to AKASHI Takahiro

Provide a couple of test cases for variable authentication.

---
 .../py/tests/test_efi_secboot/test_authvar.py | 282 ++++++++++++++++++
 1 file changed, 282 insertions(+)
 create mode 100644 test/py/tests/test_efi_secboot/test_authvar.py
test/py/tests/test_efi_secboot/test_authvar.py new file +282 -0
new file mode 100644
index 000000000000..55dcaa95f1ea
@@ -0,0 +1,282 @@
+# SPDX-License-Identifier:      GPL-2.0+
+# Copyright (c) 2019, Linaro Limited
+# Author: AKASHI Takahiro <[email protected]>
+#
+# U-Boot UEFI: Variable Authentication Test
+
+"""
+This test verifies variable authentication
+"""
+
+import pytest
+import re
+from defs import *
+
+ at pytest.mark.boardspec('sandbox')
+ at pytest.mark.buildconfigspec('efi_secure_boot')
+ at pytest.mark.buildconfigspec('cmd_fat')
+ at pytest.mark.buildconfigspec('cmd_nvedit_efi')
+ at pytest.mark.slow
+class TestEfiAuthVar(object):
+    def test_efi_var_auth1(self, u_boot_console, efi_boot_env):
+        """
+        Test Case 1 - Install signature database
+        """
+        u_boot_console.restart_uboot()
+        disk_img = efi_boot_env
+        with u_boot_console.log.section('Test Case 1a'):
+            # Test Case 1a, Initial secure state
+            output = u_boot_console.run_command_list([
+                'host bind 0 %s' % disk_img,
+                'printenv -e SecureBoot'])
+            assert('00000000: 00' in ''.join(output))
+
+            output = u_boot_console.run_command(
+                'printenv -e SetupMode')
+            assert('00000000: 01' in output)
+
+        with u_boot_console.log.section('Test Case 1b'):
+            # Test Case 1b, PK without AUTHENTICATED_WRITE_ACCESS
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 PK.auth',
+                'setenv -e -nv -bs -rt -i 4000000,$filesize PK'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 1c'):
+            # Test Case 1c, install PK
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 PK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK',
+                'printenv -e -n PK'])
+            assert(re.search('PK:', ''.join(output)))
+
+            output = u_boot_console.run_command(
+                'printenv -e SecureBoot')
+            assert('00000000: 01' in output)
+            output = u_boot_console.run_command(
+                'printenv -e SetupMode')
+            assert('00000000: 00' in output)
+
+        with u_boot_console.log.section('Test Case 1d'):
+            # Test Case 1d, db/dbx without KEK
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize db'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize dbx'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 1e'):
+            # Test Case 1e, install KEK
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 KEK.auth',
+                'setenv -e -nv -bs -rt -i 4000000,$filesize KEK'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 KEK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK',
+                'printenv -e -n KEK'])
+            assert(re.search('KEK:', ''.join(output)))
+
+            output = u_boot_console.run_command(
+                'printenv -e SecureBoot')
+            assert('00000000: 01' in output)
+
+        with u_boot_console.log.section('Test Case 1f'):
+            # Test Case 1f, install db
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -i 4000000,$filesize db'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize db',
+                'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('db:', ''.join(output)))
+
+            output = u_boot_console.run_command(
+                'printenv -e SecureBoot')
+            assert('00000000: 01' in output)
+
+        with u_boot_console.log.section('Test Case 1g'):
+            # Test Case 1g, install dbx
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -i 4000000,$filesize db'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize db',
+                'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('db:', ''.join(output)))
+
+            output = u_boot_console.run_command(
+                'printenv -e SecureBoot')
+            assert('00000000: 01' in output)
+
+    def test_efi_var_auth2(self, u_boot_console, efi_boot_env):
+        """
+        Test Case 2 - Update database by overwriting
+        """
+        u_boot_console.restart_uboot()
+        disk_img = efi_boot_env
+        with u_boot_console.log.section('Test Case 2a'):
+            # Test Case 2a, update without AUTHENTICATED_WRITE_ACCESS
+            output = u_boot_console.run_command_list([
+                'host bind 0 %s' % disk_img,
+                'fatload host 0:1 4000000 PK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK',
+                'fatload host 0:1 4000000 KEK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK',
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize db',
+                'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('db:', ''.join(output)))
+
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db1.auth',
+                'setenv -e -nv -bs -rt -i 4000000,$filesize db'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 2b'):
+            # Test Case 2b, update without correct signature
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db.esl',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize db'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 2c'):
+            # Test Case 2c, update with correct signature
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db1.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize db',
+                'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('db:', ''.join(output)))
+
+    def test_efi_var_auth3(self, u_boot_console, efi_boot_env):
+        """
+        Test Case 3 - Append database
+        """
+        u_boot_console.restart_uboot()
+        disk_img = efi_boot_env
+        with u_boot_console.log.section('Test Case 3a'):
+            # Test Case 3a, update without AUTHENTICATED_WRITE_ACCESS
+            output = u_boot_console.run_command_list([
+                'host bind 0 %s' % disk_img,
+                'fatload host 0:1 4000000 PK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK',
+                'fatload host 0:1 4000000 KEK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK',
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize db',
+                'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('db:', ''.join(output)))
+
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db1.auth',
+                'setenv -e -nv -bs -rt -a -i 4000000,$filesize db'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 3b'):
+            # Test Case 3b, update without correct signature
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db.esl',
+                'setenv -e -nv -bs -rt -at -a -i 4000000,$filesize db'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 3c'):
+            # Test Case 3c, update with correct signature
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db1.auth',
+                'setenv -e -nv -bs -rt -at -a -i 4000000,$filesize db',
+                'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('db:', ''.join(output)))
+
+    def test_efi_var_auth4(self, u_boot_console, efi_boot_env):
+        """
+        Test Case 4 - Delete database without authentication
+        """
+        u_boot_console.restart_uboot()
+        disk_img = efi_boot_env
+        with u_boot_console.log.section('Test Case 4a'):
+            # Test Case 4a, update without AUTHENTICATED_WRITE_ACCESS
+            output = u_boot_console.run_command_list([
+                'host bind 0 %s' % disk_img,
+                'fatload host 0:1 4000000 PK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK',
+                'fatload host 0:1 4000000 KEK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK',
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize db',
+                'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('db:', ''.join(output)))
+
+            output = u_boot_console.run_command_list([
+                'setenv -e -nv -bs -rt db',
+                'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('db:', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 4b'):
+            # Test Case 4b, update without correct signature/data
+            output = u_boot_console.run_command_list([
+                'setenv -e -nv -bs -rt -at db',
+                'printenv -e -n -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('db:', ''.join(output)))
+
+    def test_efi_var_auth5(self, u_boot_console, efi_boot_env):
+        """
+        Test Case 5 - Uninstall(delete) PK
+        """
+        u_boot_console.restart_uboot()
+        disk_img = efi_boot_env
+        with u_boot_console.log.section('Test Case 5a'):
+            # Test Case 5a, Uninstall PK without correct signature
+            output = u_boot_console.run_command_list([
+                'host bind 0 %s' % disk_img,
+                'fatload host 0:1 4000000 PK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK',
+                'fatload host 0:1 4000000 KEK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK',
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize db',
+                'printenv -e -n PK'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('PK:', ''.join(output)))
+
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 PK_null.esl',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK',
+                'printenv -e -n PK'])
+            assert(re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('PK:', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 5b'):
+            # Test Case 5b, Uninstall PK with correct signature
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 PK_null.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK',
+                'printenv -e -n PK'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            assert(re.search('\"PK\" not defined', ''.join(output)))
+
+            output = u_boot_console.run_command(
+                'printenv -e SecureBoot')
+            assert('00000000: 00' in output)
+            output = u_boot_console.run_command(
+                'printenv -e SetupMode')
+            assert('00000000: 01' in output)
Signature · 1 line
2.25.2
#28 lore raw

PATCH v7 14/17 efi_loader, pytest: add UEFI secure boot tests (image)

In reply to AKASHI Takahiro

Provide test cases for
* image authentication for signed images
(test_efi_secboot/test_signed.py)
* image authentication for unsigned images
(test_efi_secboot/test_unsigned.py)

---
 test/py/tests/test_efi_secboot/test_signed.py | 117 +++++++++++++++++
 .../tests/test_efi_secboot/test_unsigned.py   | 121 ++++++++++++++++++
 2 files changed, 238 insertions(+)
 create mode 100644 test/py/tests/test_efi_secboot/test_signed.py
 create mode 100644 test/py/tests/test_efi_secboot/test_unsigned.py
test/py/tests/test_efi_secboot/test_signed.py new file +117 -0
new file mode 100644
index 000000000000..584282b338bc
@@ -0,0 +1,117 @@
+# SPDX-License-Identifier:      GPL-2.0+
+# Copyright (c) 2019, Linaro Limited
+# Author: AKASHI Takahiro <[email protected]>
+#
+# U-Boot UEFI: Signed Image Authentication Test
+
+"""
+This test verifies image authentication for signed images.
+"""
+
+import pytest
+import re
+from defs import *
+
+ at pytest.mark.boardspec('sandbox')
+ at pytest.mark.buildconfigspec('efi_secure_boot')
+ at pytest.mark.buildconfigspec('cmd_efidebug')
+ at pytest.mark.buildconfigspec('cmd_fat')
+ at pytest.mark.buildconfigspec('cmd_nvedit_efi')
+ at pytest.mark.slow
+class TestEfiSignedImage(object):
+    def test_efi_signed_image_auth1(self, u_boot_console, efi_boot_env):
+        """
+        Test Case 1 - authenticated by db
+        """
+        u_boot_console.restart_uboot()
+        disk_img = efi_boot_env
+        with u_boot_console.log.section('Test Case 1a'):
+            # Test Case 1a, run signed image if no db/dbx
+            output = u_boot_console.run_command_list([
+                'host bind 0 %s' % disk_img,
+                'efidebug boot add 1 HELLO1 host 0:1 /helloworld.efi.signed ""',
+                'efidebug boot next 1',
+                'bootefi bootmgr'])
+            assert(re.search('Hello, world!', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 1b'):
+            # Test Case 1b, run unsigned image if no db/dbx
+            output = u_boot_console.run_command_list([
+                'efidebug boot add 2 HELLO2 host 0:1 /helloworld.efi ""',
+                'efidebug boot next 2',
+                'bootefi bootmgr'])
+            assert(re.search('Hello, world!', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 1c'):
+            # Test Case 1c, not authenticated by db
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize db',
+                'fatload host 0:1 4000000 KEK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK',
+                'fatload host 0:1 4000000 PK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            output = u_boot_console.run_command_list([
+                'efidebug boot next 2',
+                'bootefi bootmgr'])
+            assert(re.search('\'HELLO2\' failed', ''.join(output)))
+            output = u_boot_console.run_command_list([
+                'efidebug boot next 2',
+                'efidebug test bootmgr'])
+            assert(re.search('efi_start_image[(][)] returned: 26',
+                ''.join(output)))
+            assert(not re.search('Hello, world!', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 1d'):
+            # Test Case 1d, authenticated by db
+            output = u_boot_console.run_command_list([
+                'efidebug boot next 1',
+                'bootefi bootmgr'])
+            assert(re.search('Hello, world!', ''.join(output)))
+
+    def test_efi_signed_image_auth2(self, u_boot_console, efi_boot_env):
+        """
+        Test Case 2 - rejected by dbx
+        """
+        u_boot_console.restart_uboot()
+        disk_img = efi_boot_env
+        with u_boot_console.log.section('Test Case 2a'):
+            # Test Case 2a, rejected by dbx
+            output = u_boot_console.run_command_list([
+                'host bind 0 %s' % disk_img,
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize dbx',
+                'fatload host 0:1 4000000 KEK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize KEK',
+                'fatload host 0:1 4000000 PK.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize PK'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            output = u_boot_console.run_command_list([
+                'efidebug boot add 1 HELLO host 0:1 /helloworld.efi.signed ""',
+                'efidebug boot next 1',
+                'bootefi bootmgr'])
+            assert(re.search('\'HELLO\' failed', ''.join(output)))
+            output = u_boot_console.run_command_list([
+                'efidebug boot next 1',
+                'efidebug test bootmgr'])
+            assert(re.search('efi_start_image[(][)] returned: 26',
+                ''.join(output)))
+            assert(not re.search('Hello, world!', ''.join(output)))
+
+        with u_boot_console.log.section('Test Case 2b'):
+            # Test Case 2b, rejected by dbx even if db allows
+            output = u_boot_console.run_command_list([
+                'fatload host 0:1 4000000 db.auth',
+                'setenv -e -nv -bs -rt -at -i 4000000,$filesize db'])
+            assert(not re.search('Failed to set EFI variable', ''.join(output)))
+            output = u_boot_console.run_command_list([
+                'efidebug boot next 1',
+                'bootefi bootmgr'])
+            assert(re.search('\'HELLO\' failed', ''.join(output)))
+            output = u_boot_console.run_command_list([
+                'efidebug boot next 1',
+                'efidebug test bootmgr'])
+            assert(re.search('efi_start_image[(][)] returned: 26',
+                ''.join(output)))
+            assert(not re.search('Hello, world!', ''.join(output)))
test/py/tests/test_efi_secboot/test_unsigned.py new file +121 -0

121 lines not on this page · raw message

Signature · 1 line
2.25.2
#29 lore raw

PATCH v7 15/17 sandbox: add extra configurations for UEFI and related tests

In reply to AKASHI Takahiro

Adding those extra configurations allows us to successfully run UEFI secure boot pytest on Travis CI.

---
 configs/sandbox64_defconfig | 3 +++
 configs/sandbox_defconfig   | 3 +++
 2 files changed, 6 insertions(+)
configs/sandbox64_defconfig +3 -0
index 8ca17d621bbf..60fbc9a89cc7 100644
@@ -27,6 +27,7 @@ CONFIG_CMD_ASKENV=y
 CONFIG_CMD_GREPENV=y
 CONFIG_CMD_ENV_CALLBACK=y
 CONFIG_CMD_ENV_FLAGS=y
+CONFIG_CMD_NVEDIT_EFI=y
 CONFIG_LOOPW=y
 CONFIG_CMD_MD5SUM=y
 CONFIG_CMD_MEMINFO=y
@@ -53,6 +54,7 @@ CONFIG_CMD_DNS=y
 CONFIG_CMD_LINK_LOCAL=y
 CONFIG_CMD_ETHSW=y
 CONFIG_CMD_BMP=y
+CONFIG_CMD_EFIDEBUG=y
 CONFIG_CMD_TIME=y
 CONFIG_CMD_TIMER=y
 CONFIG_CMD_SOUND=y
@@ -203,6 +205,7 @@ CONFIG_RSA_VERIFY_WITH_PKEY=y
 CONFIG_TPM=y
 CONFIG_LZ4=y
 CONFIG_ERRNO_STR=y
+CONFIG_EFI_SECURE_BOOT=y
 CONFIG_TEST_FDTDEC=y
 CONFIG_UNIT_TEST=y
 CONFIG_UT_TIME=y
configs/sandbox_defconfig +3 -0
index cc90f0006e24..72e1de3086ee 100644
@@ -31,6 +31,7 @@ CONFIG_CMD_ASKENV=y
 CONFIG_CMD_GREPENV=y
 CONFIG_CMD_ENV_CALLBACK=y
 CONFIG_CMD_ENV_FLAGS=y
+CONFIG_CMD_NVEDIT_EFI=y
 CONFIG_LOOPW=y
 CONFIG_CMD_MD5SUM=y
 CONFIG_CMD_MEMINFO=y
@@ -62,6 +63,7 @@ CONFIG_CMD_LINK_LOCAL=y
 CONFIG_CMD_ETHSW=y
 CONFIG_CMD_BMP=y
 CONFIG_CMD_BOOTCOUNT=y
+CONFIG_CMD_EFIDEBUG=y
 CONFIG_CMD_TIME=y
 CONFIG_CMD_TIMER=y
 CONFIG_CMD_SOUND=y
@@ -229,6 +231,7 @@ CONFIG_RSA_VERIFY_WITH_PKEY=y
 CONFIG_TPM=y
 CONFIG_LZ4=y
 CONFIG_ERRNO_STR=y
+CONFIG_EFI_SECURE_BOOT=y
 CONFIG_TEST_FDTDEC=y
 CONFIG_UNIT_TEST=y
 CONFIG_UT_TIME=y
Signature · 1 line
2.25.2
#30 lore raw

PATCH v7 16/17 travis: add packages for UEFI secure boot test

In reply to AKASHI Takahiro

Pytest for UEFI secure boot will use several host commands.
In particular, Test setup relies on efitools, whose version must be v1.5.2 or later. So fetch a new version of deb package directly. Please note it has a dependency on mtools, which must also be installed along wih efitools.

In addition, the path, '/sbin', is added to PATH for use of sgdisk and mkfs.

---
 .travis.yml | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
.travis.yml +10 -1
index c59bd7790b66..b08dd030ef02 100644
@@ -40,6 +40,14 @@ addons:
     - clang-7
     - srecord
     - graphviz
+    - coreutils
+    - util-linux
+    - dosfstools
+    - gdisk
+    - mount
+    - mtools
+    - openssl
+    - sbsigntool
 
 install:
  # Clone uboot-test-hooks
@@ -60,10 +68,11 @@ install:
  - mkdir ~/grub2-arm64
  - ( cd ~/grub2-arm64; wget -O - http://download.opensuse.org/ports/aarch64/distribution/leap/42.2/repo/oss/suse/aarch64/grub2-arm64-efi-2.02~beta2-87.1.aarch64.rpm | rpm2cpio | cpio -di )
  - wget http://mirrors.kernel.org/ubuntu/pool/main/m/mpfr4/libmpfr4_3.1.4-1_amd64.deb && sudo dpkg -i libmpfr4_3.1.4-1_amd64.deb && rm libmpfr4_3.1.4-1_amd64.deb
+ - wget http://mirrors.kernel.org/ubuntu/pool/universe/e/efitools/efitools_1.8.1-0ubuntu2_amd64.deb && sudo dpkg -i efitools_1.8.1-0ubuntu2_amd64.deb && rm efitools_1.8.1-0ubuntu2_amd64.deb
 
 env:
   global:
-    - PATH=/tmp/qemu-install/bin:/tmp/uboot-test-hooks/bin:/usr/bin:/bin:/usr/local/bin
+    - PATH=/tmp/qemu-install/bin:/tmp/uboot-test-hooks/bin:/sbin:/usr/bin:/bin:/usr/local/bin
     - PYTHONPATH=/tmp/uboot-test-hooks/py/travis-ci
     - BUILD_DIR=build
     - HOSTCC="cc"
Signature · 1 line
2.25.2
#31 lore raw

PATCH v7 16/17 travis: add packages for UEFI secure boot test

Quoted 35 lines · AKASHI Takahiro

Pytest for UEFI secure boot will use several host commands.
In particular, Test setup relies on efitools, whose version must be v1.5.2 or later. So fetch a new version of deb package directly. Please note it has a dependency on mtools, which must also be installed along wih efitools.

In addition, the path, '/sbin', is added to PATH for use of sgdisk and mkfs.

---
 .travis.yml | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
.travis.yml +8 -0
index c59bd7790b66..b08dd030ef02 100644
@@ -40,6 +40,14 @@ addons:
     - clang-7
     - srecord
     - graphviz
+    - coreutils
+    - util-linux
+    - dosfstools
+    - gdisk
+    - mount
+    - mtools
+    - openssl
+    - sbsigntool
 
 install:
  # Clone uboot-test-hooks

.travis.yml install: · line 71

Quoted 4 lines
.travis.yml +1 -0
@@ -60,10 +68,11 @@ install:
  - mkdir ~/grub2-arm64
  - ( cd ~/grub2-arm64; wget -O - http://download.opensuse.org/ports/aarch64/distribution/leap/42.2/repo/oss/suse/aarch64/grub2-arm64-efi-2.02~beta2-87.1.aarch64.rpm | rpm2cpio | cpio -di )
  - wget http://mirrors.kernel.org/ubuntu/pool/main/m/mpfr4/libmpfr4_3.1.4-1_amd64.deb && sudo dpkg -i libmpfr4_3.1.4-1_amd64.deb && rm libmpfr4_3.1.4-1_amd64.deb
+ - wget http://mirrors.kernel.org/ubuntu/pool/universe/e/efitools/efitools_1.8.1-0ubuntu2_amd64.deb && sudo dpkg -i efitools_1.8.1-0ubuntu2_amd64.deb && rm efitools_1.8.1-0ubuntu2_amd64.deb

Don't we need changes in the Gitlab CI and Azure CI configurations as well?

Best regards

Heinrich

Quoted 9 lines
.travis.yml +1 -1
 env:
   global:
-    - PATH=/tmp/qemu-install/bin:/tmp/uboot-test-hooks/bin:/usr/bin:/bin:/usr/local/bin
+    - PATH=/tmp/qemu-install/bin:/tmp/uboot-test-hooks/bin:/sbin:/usr/bin:/bin:/usr/local/bin
     - PYTHONPATH=/tmp/uboot-test-hooks/py/travis-ci
     - BUILD_DIR=build
     - HOSTCC="cc"
 
#32 lore raw

PATCH v7 16/17 travis: add packages for UEFI secure boot test

Heinrich,

Quoted 33 lines · Heinrich Schuchardt
Quoted 32 lines · AKASHI Takahiro

Pytest for UEFI secure boot will use several host commands.
In particular, Test setup relies on efitools, whose version must be v1.5.2 or later. So fetch a new version of deb package directly. Please note it has a dependency on mtools, which must also be installed along wih efitools.

In addition, the path, '/sbin', is added to PATH for use of sgdisk and mkfs.

---
 .travis.yml | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
.travis.yml +8 -0
index c59bd7790b66..b08dd030ef02 100644
@@ -40,6 +40,14 @@ addons:
     - clang-7
     - srecord
     - graphviz
+    - coreutils
+    - util-linux
+    - dosfstools
+    - gdisk
+    - mount
+    - mtools
+    - openssl
+    - sbsigntool
 
Quoted 9 lines

.travis.yml install: · line 71

Quoted 7 lines
.travis.yml +1 -0
 install:
  # Clone uboot-test-hooks
@@ -60,10 +68,11 @@ install:
  - mkdir ~/grub2-arm64
  - ( cd ~/grub2-arm64; wget -O - http://download.opensuse.org/ports/aarch64/distribution/leap/42.2/repo/oss/suse/aarch64/grub2-arm64-efi-2.02~beta2-87.1.aarch64.rpm | rpm2cpio | cpio -di )
  - wget http://mirrors.kernel.org/ubuntu/pool/main/m/mpfr4/libmpfr4_3.1.4-1_amd64.deb && sudo dpkg -i libmpfr4_3.1.4-1_amd64.deb && rm libmpfr4_3.1.4-1_amd64.deb
+ - wget http://mirrors.kernel.org/ubuntu/pool/universe/e/efitools/efitools_1.8.1-0ubuntu2_amd64.deb && sudo dpkg -i efitools_1.8.1-0ubuntu2_amd64.deb && rm efitools_1.8.1-0ubuntu2_amd64.deb

Don't we need changes in the Gitlab CI and Azure CI configurations as well?

I think that this is a repeated question.
Please see Tom's reply in [1].

[1] https://lists.denx.de/pipermail/u-boot/2020-February/401424.html

Thanks,
-Takahiro Akashi

Quoted 15 lines

Best regards

Heinrich

Quoted 9 lines
.travis.yml +1 -1
 env:
   global:
-    - PATH=/tmp/qemu-install/bin:/tmp/uboot-test-hooks/bin:/usr/bin:/bin:/usr/local/bin
+    - PATH=/tmp/qemu-install/bin:/tmp/uboot-test-hooks/bin:/sbin:/usr/bin:/bin:/usr/local/bin
     - PYTHONPATH=/tmp/uboot-test-hooks/py/travis-ci
     - BUILD_DIR=build
     - HOSTCC="cc"
 
#33 lore raw

PATCH v7 17/17 efi_loader: add some description about UEFI secure boot

In reply to AKASHI Takahiro

A small text in docs/uefi/uefi.rst was added to explain how we can configure and utilise UEFI secure boot feature on U-Boot.

---
 doc/uefi/uefi.rst | 77 +++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 77 insertions(+)
doc/uefi/uefi.rst +77 -0
index cfe2d84a4c64..a35fbd331c1f 100644
@@ -97,6 +97,83 @@ Below you find the output of an example session starting GRUB::
 
 See doc/uImage.FIT/howto.txt for an introduction to FIT images.
 
+Configuring UEFI secure boot
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+UEFI specification[1] defines a secure way of executing UEFI images
+by verifying a signature (or message digest) of image with certificates.
+This feature on U-Boot is enabled with::
+
+    CONFIG_UEFI_SECURE_BOOT=y
+
+To make the boot sequence safe, you need to establish a chain of trust;
+In UEFI secure boot, you can make it with the UEFI variables, "PK"
+(Platform Key), "KEK" (Key Exchange Keys), "db" (white list database)
+and "dbx" (black list database).
+
+There are many online documents that describe what UEFI secure boot is
+and how it works. Please consult some of them for details.
+
+Here is a simple example that you can follow for your initial attempt
+(Please note that the actual steps would absolutely depend on your system
+and environment.):
+
+1. Install utility commands on your host
+    * openssl
+    * efitools
+    * sbsigntool
+
+2. Create signing keys and key database files on your host
+    for PK::
+
+        $ openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_PK/ \
+                -keyout PK.key -out PK.crt -nodes -days 365
+        $ cert-to-efi-sig-list -g 11111111-2222-3333-4444-123456789abc \
+                PK.crt PK.esl;
+        $ sign-efi-sig-list -c PK.crt -k PK.key PK PK.esl PK.auth
+
+    for KEK::
+
+        $ openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_KEK/ \
+                -keyout KEK.key -out KEK.crt -nodes -days 365
+        $ cert-to-efi-sig-list -g 11111111-2222-3333-4444-123456789abc \
+                KEK.crt KEK.esl
+        $ sign-efi-sig-list -c PK.crt -k PK.key KEK KEK.esl KEK.auth
+
+    for db::
+
+        $ openssl req -x509 -sha256 -newkey rsa:2048 -subj /CN=TEST_db/ \
+                -keyout db.key -out db.crt -nodes -days 365
+        $ cert-to-efi-sig-list -g 11111111-2222-3333-4444-123456789abc \
+                db.crt db.esl
+        $ sign-efi-sig-list -c KEK.crt -k KEK.key db db.esl db.auth
+
+    Copy \*.auth to media, say mmc, that is accessible from U-Boot.
+
+3. Sign an image with one key in "db" on your host::
+
+    $ sbsign --key db.key --cert db.crt helloworld.efi
+
+4. Install keys on your board::
+
+    ==> fatload mmc 0:1 <tmpaddr> PK.auth
+    ==> setenv -e -nv -bs -rt -at -i <tmpaddr>,$filesize PK
+    ==> fatload mmc 0:1 <tmpaddr> KEK.auth
+    ==> setenv -e -nv -bs -rt -at -i <tmpaddr>,$filesize KEK
+    ==> fatload mmc 0:1 <tmpaddr> db.auth
+    ==> setenv -e -nv -bs -rt -at -i <tmpaddr>,$filesize db
+
+5. Set up boot parameters on your board::
+
+    ==> efidebug boot add 1 HELLO mmc 0:1 /helloworld.efi.signed ""
+
+Then your board runs that image from Boot manager (See below).
+You can also try this sequence by running Pytest, test_efi_secboot,
+on sandbox::
+
+    $ cd <U-Boot source directory>
+    $ pytest.py test/py/tests/test_efi_secboot/test_signed.py --bd sandbox
+
 Executing the boot manager
 ~~~~~~~~~~~~~~~~~~~~~~~~~~
 
Signature · 1 line
2.25.2
#34 lore raw

v7 cover efi_loader: add secure boot support

In reply to AKASHI Takahiro

Heinrich,

I was notified of some wrong implementation in this patch set. I think that the change will be contained in efi_signature_verify() function, but it is so essential in terms of "verification" logic.

While I'm still investigating the issue to determine what impact it will have, I would have to, in the worst case, ask you to revert all the commits.

Some details:
In my current implementation, a signature in UEFI image will be verified with one of certificates in UEFI signature database (PK/KEK/db).
The true logic would be that a signature be verified with a corresponding certificate also in the image (known as signers), and then that certificate be verified with UEFI signature database.

It is particularly crucial if we want to support "intermediate" certificates (or chain-of-trust) in UEFI image.

I will keep you updated when I have some progress.

Thanks,
-Takahiro Akashi

Quoted 204 lines · AKASHI Takahiro

One of major missing features in current UEFI implementation is "secure boot." The ultimate goal of my attempt is to implement image authentication based on signature and provide UEFI secure boot support which would be fully compliant with UEFI specification, section 32[1].
(The code was originally developed by Patrick Wildt.)

This patch set requires one prerequisite[2]. For complete workable cod, see my repository[3].

My "non-volatile" support[4], which is under discussion, is not mandatory and so not included here, but this inevitably implies that, for example, signature database variables, like db and dbx, won't be persistent unless you explicitly run "env save" command.
Anyhow, Linaro is also working on implementing real "secure storage" solution based on TF-A and OP-TEE.

Supported features:
* image authentication based on db and dbx
* supported signature types are EFI_CERT_SHA256_GUID (SHA256 digest for unsigned images) EFI_CERT_X509_GUID (x509 certificate for signed images)
* SecureBoot/SignatureSupport variables
* SetupMode and user mode
* variable authentication based on PK and KEK EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
* basic pytest test cases

Unsupported features: (marked as TODO in most cases in the source code,
and won't be included in this series)
* hash algorithms other than SHA256
* dbt: timestamp(RFC6131)-based certificate revocation
* dbr: OS recovery
* xxxDefault: default values for signature stores
* transition to AuditMode and DeployedMode
* recording rejected images in EFI_IMAGE_EXECUTION_INFO_TABLE
* verification "policy", in particular, check against signature's owner
* private authenticated variables
* variable authentication with EFI_VARIABLE_ENHANCED_AUTHENTICATED_ACCESS
* real secure storage support, including hardware-specific PK (Platform Key) installation

TODO's other than "Unsupported features": (won't be included in this series)
* fail recovery, in particular, in modifying authenticated variables
* support read-only attributes of well-defined global variables in particular, "SignatureSupport"
* Extensive test suite (or more test cases) to confirm compatibility with EDK2
=> I requested EDK SCT community to add tests[5].

Test:
* My pytest, included in this patch set, passed.
* efi_selftest passed. (At least no regression.)
* Travis CI tests have passed.

Known issues:
* efitools is used in pytest, and its version must be v1.5.2 or later. (Solution: You can define EFITOOLS_PATH in defs.py for your own efitools.)

Hints about how to use:
(Please see other documents, or my pytest scripts, for details.)
* You can create your own certificates with openssl.
* You can sign your application with sbsign (on Ubuntu).
* You can create raw data for signature database with efitools, and install/manage authenticated variables with "env -set -e" command or efitools' "UpdateVars.efi" application.

[1] https://uefi.org/sites/default/files/resources/UEFI_Spec_2_8_final.pdf
[2] https://lists.denx.de/pipermail/u-boot/2020-January/398057.html
(extend rsa_verify() for UEFI secure boot)
[3] http://git.linaro.org/people/takahiro.akashi/u-boot.git/ efi/secboot
[4] https://lists.denx.de/pipermail/u-boot/2019-September/382835.html
(non-volatile variables support)
[5] https://bugzilla.tianocore.org/show_bug.cgi?id=2230
[6] https://lists.denx.de/pipermail/u-boot/2020-February/399446.html

Changes in v7 (Apr 14, 2020)
* fix a usage of qsort() in efi_image_parse() (patch#7)
* merge my document patch[6] (patch#17)

Changes in v6 (Feb 26, 2020)
* fix 'make htmldocs' warnings (patch#4,#7)
* refactor efi_load_pe() to avoid test_efi_fit.py error (patch#7)
* fix pytest warnings (patch#14)

Changes in v5 (Jan 28, 2020)
* rebased to pre-v2020.04-rc1 (fixed some merge conflicts)
* remove already-merged commits (v4's patch#1)
* fix a compile error caused by gcc 9.x (patch#4)
* return SECURITY_VIOLATION instead of ACCESS_DENIED if authentication fails (patch#7)
* use qsort() for section sorting (patch#7)
* add "efidebug test" sub-command (patch#11)
* add efi_start_image(SECURITY_VIOLATION) test (patch#14)

Changes in v4 (Dec 18, 2019)
* adjust EFI_SECURE_BOOT dependencies due to a change of RSA extension patch v5 (patch#2)
* change "imply" to "select" against kconfig dependencies (patch#2)
* otherwise, no functional changes

Changes in v3 (Dec 9, 2019)
* allow for arbitrary number of regions in efi_image_region_add() (patch#3, #5 and #8)
* remove a redundant check in a while loop at efi_sigstore_free() (patch#4)

Changes in v2 (Nov 26, 2019)
* rebased to v2020.01-rc3
* rename IMAGE_DIRECTORY_ENTRY_CERTTABLE to IMAGE_DIRECTORY_ENTRY_SECURITY (patch#1,#9)
* add comments (patch#1)
* drop v1's patch#2 as it is no longer necessary
* drop v1's patch#3 as other "SECURE_BOOT" architectures have renamed this option and no longer use it
* add structure descriptions (patch#3)
* rework hash calculation code in efi_signature_verify() and remove an odd constant, WinIndrectSha256 (patch#3)
* move travis.yml changes to a separate patch (patch#12, #16)
* yield_fixture() -> fixture() (patch#12)
* call console.restart_uboot() at every test case (13,#14)
* add patch#15; enable UEFI-related configurations by default on sandbox
* add patch#16; modify Travis CI environment to run UEFI secure boot test

Changes in v1 (Nov 13, 2019)
* rebased to v2020.01-rc
* remove already-merged patches
* re-work the patch set for easier reviews, including
- move a config definition patch forward (patch#4)
- refactor/rename verification functions (patch#5/#10)
- split signature database parser as a separate patch (patch#6)
- split secure state transition code as a separate patch (patch#8)
- move most part of init_secure_boot() into init_variables() (patch#8)
- split test environment setup from test patches (patch#14)
* add function descriptions (patch#5-#11)
* make sure the section list is sorted in ascending order in hash calculation of PE image (patch#10)
* add a new "-at" (authenticated access) option to "env -e" (patch#13)
* list required host packages, in particular udisks2, in pytest (patch#14)
* modify conftest.py to run under python3 (patch#14)
* use a partition on a disk instead of a whole disk without partition table (patch#14)
* reduce dependency on efitools, yet relying on its host tools (patch#14)
* modify pytests to catch up wth latest changes of "env -e" syntax (patch#15,#16)

RFC (Sept 18, 2019)

AKASHI Takahiro (17):
efi_loader: add CONFIG_EFI_SECURE_BOOT config option
efi_loader: add signature verification functions
efi_loader: add signature database parser
efi_loader: variable: support variable authentication
efi_loader: variable: add secure boot state transition
efi_loader: variable: add VendorKeys variable
efi_loader: image_loader: support image authentication
efi_loader: set up secure boot
cmd: env: use appropriate guid for authenticated UEFI variable
cmd: env: add "-at" option to "env set -e" command
cmd: efidebug: add "test bootmgr" sub-command efi_loader, pytest: set up secure boot environment efi_loader, pytest: add UEFI secure boot tests (authenticated
variables)
efi_loader, pytest: add UEFI secure boot tests (image)
sandbox: add extra configurations for UEFI and related tests
travis: add packages for UEFI secure boot test
efi_loader: add some description about UEFI secure boot

 .travis.yml                                   |  11 +-
 cmd/efidebug.c                                |  78 +-
 cmd/nvedit.c                                  |   5 +-
 cmd/nvedit_efi.c                              |  23 +-
 configs/sandbox64_defconfig                   |   3 +
 configs/sandbox_defconfig                     |   3 +
 doc/uefi/uefi.rst                             |  77 ++
 include/efi_api.h                             |  87 ++
 include/efi_loader.h                          |  91 +-
 lib/efi_loader/Kconfig                        |  18 +
 lib/efi_loader/Makefile                       |   1 +
 lib/efi_loader/efi_boottime.c                 |  10 +-
 lib/efi_loader/efi_image_loader.c             | 462 ++++++++-
 lib/efi_loader/efi_setup.c                    |  38 +
 lib/efi_loader/efi_signature.c                | 809 +++++++++++++++
 lib/efi_loader/efi_variable.c                 | 952 ++++++++++++++++--
 test/py/README.md                             |   8 +
 test/py/tests/test_efi_secboot/conftest.py    | 151 +++
 test/py/tests/test_efi_secboot/defs.py        |  21 +
 .../py/tests/test_efi_secboot/test_authvar.py | 282 ++++++
 test/py/tests/test_efi_secboot/test_signed.py | 117 +++
 .../tests/test_efi_secboot/test_unsigned.py   | 121 +++
 22 files changed, 3237 insertions(+), 131 deletions(-)
 create mode 100644 lib/efi_loader/efi_signature.c
 create mode 100644 test/py/tests/test_efi_secboot/conftest.py
 create mode 100644 test/py/tests/test_efi_secboot/defs.py
 create mode 100644 test/py/tests/test_efi_secboot/test_authvar.py
 create mode 100644 test/py/tests/test_efi_secboot/test_signed.py
 create mode 100644 test/py/tests/test_efi_secboot/test_unsigned.py
Signature · 1 line
2.25.2
#35 lore raw

v7 cover efi_loader: add secure boot support

Takahiro,

Quoted 18 lines · AKASHI Takahiro

Heinrich,

I was notified of some wrong implementation in this patch set. I think that the change will be contained in efi_signature_verify() function, but it is so essential in terms of "verification" logic.

While I'm still investigating the issue to determine what impact it will have, I would have to, in the worst case, ask you to revert all the commits.

Some details:
In my current implementation, a signature in UEFI image will be verified with one of certificates in UEFI signature database (PK/KEK/db).
The true logic would be that a signature be verified with a corresponding certificate also in the image (known as signers), and then that certificate be verified with UEFI signature database.

Quoted 5 lines

It is particularly crucial if we want to support "intermediate" certificates (or chain-of-trust) in UEFI image.

I will keep you updated when I have some progress.

I do not think this is a wrong implementation. It's just that we currently do not have support for multi-certificate chain building and verification. But it would still be possible to do signature verification of an image/variable/capsule against the public key which is contained in the signature database variables(Pk, KEK, db). I think the unimplemented part can well be added to the current implementation as a follow-up patch series, so i don't see a reason why this patch series should not be applied, unless the current series has any other issues.

-sughosh

Quoted 219 lines

Thanks,
-Takahiro Akashi

Quoted 1 line · AKASHI Takahiro

One of major missing features in current UEFI implementation is "secure

boot."

Quoted 1 line

The ultimate goal of my attempt is to implement image authentication

based

Quoted 26 lines

on signature and provide UEFI secure boot support which would be fully compliant with UEFI specification, section 32[1].
(The code was originally developed by Patrick Wildt.)

This patch set requires one prerequisite[2]. For complete workable cod, see my repository[3].

My "non-volatile" support[4], which is under discussion, is not mandatory and so not included here, but this inevitably implies that, for example, signature database variables, like db and dbx, won't be persistent unless you explicitly run "env save" command.
Anyhow, Linaro is also working on implementing real "secure storage" solution based on TF-A and OP-TEE.

Supported features:
* image authentication based on db and dbx
* supported signature types are EFI_CERT_SHA256_GUID (SHA256 digest for unsigned images) EFI_CERT_X509_GUID (x509 certificate for signed images)
* SecureBoot/SignatureSupport variables
* SetupMode and user mode
* variable authentication based on PK and KEK EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
* basic pytest test cases

Quoted 12 lines

Unsupported features: (marked as TODO in most cases in the source code,
and won't be included in this series)
* hash algorithms other than SHA256
* dbt: timestamp(RFC6131)-based certificate revocation
* dbr: OS recovery
* xxxDefault: default values for signature stores
* transition to AuditMode and DeployedMode
* recording rejected images in EFI_IMAGE_EXECUTION_INFO_TABLE
* verification "policy", in particular, check against signature's owner
* private authenticated variables
* variable authentication with EFI_VARIABLE_ENHANCED_AUTHENTICATED_ACCESS
* real secure storage support, including hardware-specific PK (Platform

Key)

Quoted 3 lines

installation

TODO's other than "Unsupported features": (won't be included in this

series)

Quoted 7 lines

* fail recovery, in particular, in modifying authenticated variables
* support read-only attributes of well-defined global variables in particular, "SignatureSupport"
* Extensive test suite (or more test cases) to confirm compatibility with EDK2
=> I requested EDK SCT community to add tests[5].

Quoted 8 lines

Test:
* My pytest, included in this patch set, passed.
* efi_selftest passed. (At least no regression.)
* Travis CI tests have passed.

Known issues:
* efitools is used in pytest, and its version must be v1.5.2 or later. (Solution: You can define EFITOOLS_PATH in defs.py for your own

efitools.)

Quoted 11 lines

Hints about how to use:
(Please see other documents, or my pytest scripts, for details.)
* You can create your own certificates with openssl.
* You can sign your application with sbsign (on Ubuntu).
* You can create raw data for signature database with efitools, and install/manage authenticated variables with "env -set -e" command or efitools' "UpdateVars.efi" application.

Quoted 1 line

[1]

https://uefi.org/sites/default/files/resources/UEFI_Spec_2_8_final.pdf

Quoted 18 lines

[2] https://lists.denx.de/pipermail/u-boot/2020-January/398057.html
(extend rsa_verify() for UEFI secure boot)
[3] http://git.linaro.org/people/takahiro.akashi/u-boot.git/ efi/secboot
[4] https://lists.denx.de/pipermail/u-boot/2019-September/382835.html
(non-volatile variables support)
[5] https://bugzilla.tianocore.org/show_bug.cgi?id=2230
[6] https://lists.denx.de/pipermail/u-boot/2020-February/399446.html

Changes in v7 (Apr 14, 2020)
* fix a usage of qsort() in efi_image_parse() (patch#7)
* merge my document patch[6] (patch#17)

Changes in v6 (Feb 26, 2020)
* fix 'make htmldocs' warnings (patch#4,#7)
* refactor efi_load_pe() to avoid test_efi_fit.py error (patch#7)
* fix pytest warnings (patch#14)

Quoted 5 lines

Changes in v5 (Jan 28, 2020)
* rebased to pre-v2020.04-rc1 (fixed some merge conflicts)
* remove already-merged commits (v4's patch#1)
* fix a compile error caused by gcc 9.x (patch#4)
* return SECURITY_VIOLATION instead of ACCESS_DENIED if authentication

fails

Quoted 7 lines

(patch#7)
* use qsort() for section sorting (patch#7)
* add "efidebug test" sub-command (patch#11)
* add efi_start_image(SECURITY_VIOLATION) test (patch#14)

Changes in v4 (Dec 18, 2019)
* adjust EFI_SECURE_BOOT dependencies due to a change of RSA extension

patch v5

Quoted 8 lines

(patch#2)
* change "imply" to "select" against kconfig dependencies (patch#2)
* otherwise, no functional changes

Changes in v3 (Dec 9, 2019)
* allow for arbitrary number of regions in efi_image_region_add() (patch#3, #5 and #8)
* remove a redundant check in a while loop at efi_sigstore_free()

(patch#4)

Quoted 4 lines

Changes in v2 (Nov 26, 2019)
* rebased to v2020.01-rc3
* rename IMAGE_DIRECTORY_ENTRY_CERTTABLE to

IMAGE_DIRECTORY_ENTRY_SECURITY

Quoted 92 lines

(patch#1,#9)
* add comments (patch#1)
* drop v1's patch#2 as it is no longer necessary
* drop v1's patch#3 as other "SECURE_BOOT" architectures have renamed this option and no longer use it
* add structure descriptions (patch#3)
* rework hash calculation code in efi_signature_verify() and remove an odd constant, WinIndrectSha256 (patch#3)
* move travis.yml changes to a separate patch (patch#12, #16)
* yield_fixture() -> fixture() (patch#12)
* call console.restart_uboot() at every test case (13,#14)
* add patch#15; enable UEFI-related configurations by default on sandbox
* add patch#16; modify Travis CI environment to run UEFI secure boot test

Changes in v1 (Nov 13, 2019)
* rebased to v2020.01-rc
* remove already-merged patches
* re-work the patch set for easier reviews, including
- move a config definition patch forward (patch#4)
- refactor/rename verification functions (patch#5/#10)
- split signature database parser as a separate patch (patch#6)
- split secure state transition code as a separate patch (patch#8)
- move most part of init_secure_boot() into init_variables() (patch#8)
- split test environment setup from test patches (patch#14)
* add function descriptions (patch#5-#11)
* make sure the section list is sorted in ascending order in hash calculation of PE image (patch#10)
* add a new "-at" (authenticated access) option to "env -e" (patch#13)
* list required host packages, in particular udisks2, in pytest (patch#14)
* modify conftest.py to run under python3 (patch#14)
* use a partition on a disk instead of a whole disk without partition table (patch#14)
* reduce dependency on efitools, yet relying on its host tools (patch#14)
* modify pytests to catch up wth latest changes of "env -e" syntax (patch#15,#16)

RFC (Sept 18, 2019)

AKASHI Takahiro (17):
efi_loader: add CONFIG_EFI_SECURE_BOOT config option
efi_loader: add signature verification functions
efi_loader: add signature database parser
efi_loader: variable: support variable authentication
efi_loader: variable: add secure boot state transition
efi_loader: variable: add VendorKeys variable
efi_loader: image_loader: support image authentication
efi_loader: set up secure boot
cmd: env: use appropriate guid for authenticated UEFI variable
cmd: env: add "-at" option to "env set -e" command
cmd: efidebug: add "test bootmgr" sub-command efi_loader, pytest: set up secure boot environment efi_loader, pytest: add UEFI secure boot tests (authenticated
variables)
efi_loader, pytest: add UEFI secure boot tests (image)
sandbox: add extra configurations for UEFI and related tests
travis: add packages for UEFI secure boot test
efi_loader: add some description about UEFI secure boot

 .travis.yml                                   |  11 +-
 cmd/efidebug.c                                |  78 +-
 cmd/nvedit.c                                  |   5 +-
 cmd/nvedit_efi.c                              |  23 +-
 configs/sandbox64_defconfig                   |   3 +
 configs/sandbox_defconfig                     |   3 +
 doc/uefi/uefi.rst                             |  77 ++
 include/efi_api.h                             |  87 ++
 include/efi_loader.h                          |  91 +-
 lib/efi_loader/Kconfig                        |  18 +
 lib/efi_loader/Makefile                       |   1 +
 lib/efi_loader/efi_boottime.c                 |  10 +-
 lib/efi_loader/efi_image_loader.c             | 462 ++++++++-
 lib/efi_loader/efi_setup.c                    |  38 +
 lib/efi_loader/efi_signature.c                | 809 +++++++++++++++
 lib/efi_loader/efi_variable.c                 | 952 ++++++++++++++++--
 test/py/README.md                             |   8 +
 test/py/tests/test_efi_secboot/conftest.py    | 151 +++
 test/py/tests/test_efi_secboot/defs.py        |  21 +
 .../py/tests/test_efi_secboot/test_authvar.py | 282 ++++++
 test/py/tests/test_efi_secboot/test_signed.py | 117 +++
 .../tests/test_efi_secboot/test_unsigned.py   | 121 +++
 22 files changed, 3237 insertions(+), 131 deletions(-)
 create mode 100644 lib/efi_loader/efi_signature.c
 create mode 100644 test/py/tests/test_efi_secboot/conftest.py
 create mode 100644 test/py/tests/test_efi_secboot/defs.py
 create mode 100644 test/py/tests/test_efi_secboot/test_authvar.py
 create mode 100644 test/py/tests/test_efi_secboot/test_signed.py
 create mode 100644 test/py/tests/test_efi_secboot/test_unsigned.py

--
2.25.2