efi_loader: add secure boot support
Subsystems (2)
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.)
While this patch/RFC is still rough-edged, the aim here is to get early feedbacks from the community as the patch is quite huge (in total) and also as it's a security enhancement.
Please note, however, this patch doesn't work on its own; there are a couple of functional dependencies[2] and [3], that I have submitted before. For complete workable patch set, see my repository[4], which also contains exeperimental timestamp-based revocation suuport.
My "non-volatile" support[5], 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 and that UEFI variables are not separated from U-Boot environment. 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)
* struct efi_image_regions cannot have arbitrary number of regions
* 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[6].
Known issues:
* remove generic CONFIG_SECURE_BOOT option (on NXP/Freescale platforms) (I'm looking forward to fixes from NXP guys.)
* 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.)
* Pytest depends on standalone "helloworld" app for sandbox (Solution: You can define HELLO_PATH in defs.py or Heinrich's [7].)
Test:
* my pytest, included in this patch set, passed.
* efi_selftest passed. (At least no reguression.)
* Travis CI passed. (But pytest itself was skipped.)
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/2019-November/390127.html
(import x509/pkcs7 parsers from linux)
[3] https://lists.denx.de/pipermail/u-boot/2019-November/390150.html
(extend rsa_verify() for UEFI secure boot)
[4] http://git.linaro.org/people/takahiro.akashi/u-boot.git/ efi/secboot
[5] https://lists.denx.de/pipermail/u-boot/2019-September/382835.html
(non-volatile variables support)
[6] https://bugzilla.tianocore.org/show_bug.cgi?id=2230
[7] https://lists.denx.de/pipermail/u-boot/2019-November/389593.html
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 depencendy 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 (16):
include: pe.h: add signature-related definitions
include: image.h: export hash algorithm helper functions secure boot: rename CONFIG_SECURE_BOOT config option
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 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)
.travis.yml | 4 + Kconfig | 7 + arch/arm/cpu/armv7/ls102xa/Kconfig | 3 +- arch/arm/cpu/armv8/fsl-layerscape/Kconfig | 3 +- arch/powerpc/cpu/mpc85xx/Kconfig | 3 +- cmd/nvedit.c | 5 +- cmd/nvedit_efi.c | 23 +- include/efi_api.h | 47 + include/efi_loader.h | 59 +- include/image.h | 10 +- include/pe.h | 16 + lib/efi_loader/Kconfig | 13 + lib/efi_loader/Makefile | 1 + lib/efi_loader/efi_boottime.c | 2 +- lib/efi_loader/efi_image_loader.c | 443 +++++++- lib/efi_loader/efi_setup.c | 38 + lib/efi_loader/efi_signature.c | 827 +++++++++++++++ lib/efi_loader/efi_variable.c | 950 ++++++++++++++++-- test/py/README.md | 4 + test/py/tests/test_efi_secboot/conftest.py | 128 +++ test/py/tests/test_efi_secboot/defs.py | 21 + .../py/tests/test_efi_secboot/test_authvar.py | 289 ++++++ test/py/tests/test_efi_secboot/test_signed.py | 97 ++ .../tests/test_efi_secboot/test_unsigned.py | 100 ++ 24 files changed, 2958 insertions(+), 135 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.21.0
PATCH 1/16 include: pe.h: add signature-related definitions
The index (IMAGE_DIRECTORY_ENTRY_CERTTABLE) in a table points to a region containing authentication information (image's signature) in PE format.
WIN_CERTIFICATE structure defines an embedded signature format.
Those definitions will be used in my UEFI secure boot patch.
--- include/pe.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)
include/pe.h +16 -0
@@ -155,6 +155,7 @@ typedef struct _IMAGE_SECTION_HEADER {uint32_t Characteristics; }IMAGE_SECTION_HEADER , *PIMAGE_SECTION_HEADER ; +#define IMAGE_DIRECTORY_ENTRY_CERTTABLE 4#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 typedef struct _IMAGE_BASE_RELOCATION
@@ -252,4 +253,19 @@ typedef struct _IMAGE_RELOCATION#define IMAGE_REL_AMD64_PAIR 0x000F#define IMAGE_REL_AMD64_SSPAN32 0x0010 +/* certificate appended to PE image */ +typedef struct _WIN_CERTIFICATE { +uint32_t dwLength; +uint16_t wRevision; +uint16_t wCertificateType; +uint8_t bCertificate[]; +}WIN_CERTIFICATE , *LPWIN_CERTIFICATE ; + +#define WIN_CERT_TYPE_PKCS_SIGNED_DATA 0x0002 +#define WIN_CERT_TYPE_EFI_OKCS115 0x0EF0 +#define WIN_CERT_TYPE_EFI_GUID 0x0EF1 + +#define WIN_CERT_REVISION_1_0 0x0100 +#define WIN_CERT_REVISION_2_0 0x0200 +#endif /* _PE_H */
Signature · 1 line
2.21.0
PATCH 1/16 include: pe.h: add signature-related definitions
Quoted 18 lines · AKASHI Takahiro
The index (
IMAGE_DIRECTORY_ENTRY_CERTTABLE) in a table points to a region containing authentication information (image's signature) in PE format.
WIN_CERTIFICATEstructure defines an embedded signature format.Those definitions will be used in my UEFI secure boot patch.
Signed-off-by AKASHI Takahiro <[email protected]>--- include/pe.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)include/pe.h +0
-0
include/pe.h typedef struct _IMAGE_SECTION_HEADER { · line 157
Quoted 3 lines
include/pe.h +0
-0@@ -155,6 +155,7 @@ typedef struct _IMAGE_SECTION_HEADER {uint32_t Characteristics; }IMAGE_SECTION_HEADER , *PIMAGE_SECTION_HEADER ;
Please, add a comment here:
/* Indices for Optional Header Data Directories */
include/pe.h typedef struct _IMAGE_SECTION_HEADER { · line 158
Quoted 1 line
include/pe.h +1
-0+#define IMAGE_DIRECTORY_ENTRY_CERTTABLE 4
Yes, 4 is the index of the certificate table. But EDK II calls this EFI_IMAGE_DIRECTORY_ENTRY_SECURITY. Should we use the same name to avoid confusion?
include/pe.h typedef struct _IMAGE_RELOCATION · line 257
Quoted 9 lines
include/pe.h +2
-0#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5 typedef struct _IMAGE_BASE_RELOCATION@@ -252,4 +253,19 @@ typedef struct _IMAGE_RELOCATION#define IMAGE_REL_AMD64_PAIR 0x000F#define IMAGE_REL_AMD64_SSPAN32 0x0010 +/* certificate appended to PE image */ +typedef struct _WIN_CERTIFICATE {
We do not capitalize structs. Please use 'win_certificate' (like Linux does).
include/pe.h typedef struct _IMAGE_RELOCATION · line 261
Quoted 4 lines
include/pe.h +4
-0+uint32_t dwLength; +uint16_t wRevision; +uint16_t wCertificateType; +uint8_t bCertificate[];
We do not use camelcase and type prefixes. Please, use the same component names as Linux (plus 'certificate' for your extra field).
include/pe.h typedef struct _IMAGE_RELOCATION · line 262
Quoted 1 line
include/pe.h +1
-0+}WIN_CERTIFICATE , *LPWIN_CERTIFICATE ;
Please, always make use of scripts/checkpatch.pl before submitting patches. It says 'WARNING: do not add new typedefs'.
Please, avoid the typedefs.
include/pe.h typedef struct _IMAGE_RELOCATION · line 263
Quoted 1 line
include/pe.h +1
-0+
The following defines are verbatim copies from Linux. Please, also copy the comment:
/* Definitions for the contents of the certs data block */
include/pe.h typedef struct _IMAGE_RELOCATION · line 271
Quoted 9 lines
include/pe.h +7
-0+#define WIN_CERT_TYPE_PKCS_SIGNED_DATA 0x0002 +#define WIN_CERT_TYPE_EFI_OKCS115 0x0EF0 +#define WIN_CERT_TYPE_EFI_GUID 0x0EF1 + +#define WIN_CERT_REVISION_1_0 0x0100 +#define WIN_CERT_REVISION_2_0 0x0200 +#endif /* _PE_H */
Except for the style issues this looks ok.
Best regards
Heinrich
AKASHI Takahiro
NAKPATCH 1/16 include: pe.h: add signature-related definitions
Heinrich,
Quoted 25 lines · Heinrich Schuchardt
Quoted 18 lines · AKASHI Takahiro
The index (
IMAGE_DIRECTORY_ENTRY_CERTTABLE) in a table points to a region containing authentication information (image's signature) in PE format.
WIN_CERTIFICATEstructure defines an embedded signature format.Those definitions will be used in my UEFI secure boot patch.
Signed-off-by AKASHI Takahiro <[email protected]>--- include/pe.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)include/pe.h +0
-0include/pe.h typedef struct _IMAGE_SECTION_HEADER { · line 157
Quoted 3 lines
include/pe.h +0
-0@@ -155,6 +155,7 @@ typedef struct _IMAGE_SECTION_HEADER {uint32_t Characteristics; }IMAGE_SECTION_HEADER , *PIMAGE_SECTION_HEADER ;Please, add a comment here:
Quoted 1 line
/* Indices for Optional Header Data Directories */
Okay.
Quoted 5 lines
include/pe.h typedef struct _IMAGE_SECTION_HEADER { · line 158
Quoted 1 line
include/pe.h +1
-0+#define IMAGE_DIRECTORY_ENTRY_CERTTABLE 4Yes, 4 is the index of the certificate table. But EDK II calls this
EFI_IMAGE_DIRECTORY_ENTRY_SECURITY. Should we use the same name to avoid confusion?
No. Because the naming is consistent with
Quoted 1 line
include/pe.h typedef struct _IMAGE_SECTION_HEADER { · line 159
Quoted 1 line
include/pe.h +0
-0#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5
this existing one.
Quoted 12 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 257
Quoted 8 lines
include/pe.h +2
-0typedef struct _IMAGE_BASE_RELOCATION@@ -252,4 +253,19 @@ typedef struct _IMAGE_RELOCATION#define IMAGE_REL_AMD64_PAIR 0x000F#define IMAGE_REL_AMD64_SSPAN32 0x0010 +/* certificate appended to PE image */ +typedef struct _WIN_CERTIFICATE {We do not capitalize structs. Please use '
win_certificate' (like Linux does).
Quoted 7 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 261
Quoted 4 lines
include/pe.h +4
-0+uint32_t dwLength; +uint16_t wRevision; +uint16_t wCertificateType; +uint8_t bCertificate[];We do not use camelcase and type prefixes. Please, use the same component names as Linux (plus 'certificate' for your extra field).
nak.
Have you looked at 'pe.h' at all?
There are already bunch of use of camelcase's and capital names since this file was first introduced by Alex.
Quoted 4 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 262
Quoted 1 line
include/pe.h +1
-0+}WIN_CERTIFICATE , *LPWIN_CERTIFICATE ;Please, always make use of
scripts/checkpatch.plbefore submitting patches. It says 'WARNING: do not add new typedefs'.
ditto.
I have run scripts/cehckpatch.pl and dare to leave them unchanged.
Quoted 1 line
Please, avoid the typedefs.
No. this is also consistent with other typedef's.
Quoted 6 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 263
Quoted 1 line
include/pe.h +1
-0+The following defines are verbatim copies from Linux. Please, also copy the comment:
/* Definitions for the contents of the certs data block */
Okay.
Quoted 11 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 271
Quoted 9 lines
include/pe.h +7
-0+#define WIN_CERT_TYPE_PKCS_SIGNED_DATA 0x0002 +#define WIN_CERT_TYPE_EFI_OKCS115 0x0EF0 +#define WIN_CERT_TYPE_EFI_GUID 0x0EF1 + +#define WIN_CERT_REVISION_1_0 0x0100 +#define WIN_CERT_REVISION_2_0 0x0200 +#endif /* _PE_H */ Except for the style issues this looks ok.
Thank you for your comments.
-Takahiro Akashi
Quoted 4 lines
Best regards
Heinrich
PATCH 1/16 include: pe.h: add signature-related definitions
Quoted 38 lines · AKASHI Takahiro
Heinrich,
Quoted 25 lines · Heinrich Schuchardt
Quoted 18 lines · AKASHI Takahiro
The index (
IMAGE_DIRECTORY_ENTRY_CERTTABLE) in a table points to a region containing authentication information (image's signature) in PE format.
WIN_CERTIFICATEstructure defines an embedded signature format.Those definitions will be used in my UEFI secure boot patch.
Signed-off-by AKASHI Takahiro <[email protected]>--- include/pe.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)include/pe.h +0
-0include/pe.h typedef struct _IMAGE_SECTION_HEADER { · line 157
Quoted 3 lines
include/pe.h +0
-0@@ -155,6 +155,7 @@ typedef struct _IMAGE_SECTION_HEADER {uint32_t Characteristics; }IMAGE_SECTION_HEADER , *PIMAGE_SECTION_HEADER ;Please, add a comment here:
Quoted 1 line
/* Indices for Optional Header Data Directories */
Okay.
Quoted 5 lines
include/pe.h typedef struct _IMAGE_SECTION_HEADER { · line 158
Quoted 1 line
include/pe.h +1
-0+#define IMAGE_DIRECTORY_ENTRY_CERTTABLE 4Yes, 4 is the index of the certificate table. But EDK II calls this
EFI_IMAGE_DIRECTORY_ENTRY_SECURITY. Should we use the same name to avoid confusion?
Quoted 5 lines
No. Because the naming is consistent with
Quoted 1 line
include/pe.h typedef struct _IMAGE_SECTION_HEADER { · line 159
Quoted 1 line
include/pe.h +0
-0#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5this existing one.
IMAGE_DIRECTORY_ENTRY_BASERELOC is a constant name used by EDK2 in MdePkg/Include/IndustryStandard/PeImage.h. Why do you want to deviate for EFI_IMAGE_DIRECTORY_ENTRY_SECURITY?
Quoted 21 lines
Quoted 13 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 257
Quoted 9 lines
include/pe.h +2
-0typedef struct _IMAGE_BASE_RELOCATION@@ -252,4 +253,19 @@ typedef struct _IMAGE_RELOCATION#define IMAGE_REL_AMD64_PAIR 0x000F#define IMAGE_REL_AMD64_SSPAN32 0x0010 +/* certificate appended to PE image */ +typedef struct _WIN_CERTIFICATE {We do not capitalize structs. Please use '
win_certificate' (like Linux does).Quoted 7 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 261
Quoted 4 lines
include/pe.h +4
-0+uint32_t dwLength; +uint16_t wRevision; +uint16_t wCertificateType; +uint8_t bCertificate[];We do not use camelcase and type prefixes. Please, use the same component names as Linux (plus 'certificate' for your extra field).
Quoted 4 lines
nak.
Have you looked at 'pe.h' at all?
There are already bunch of use of camelcase's and capital names since this file was first introduced by Alex.
This shouldn't have happened in the first place.
Best regards
Heinrich
Quoted 43 lines
Quoted 5 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 262
Quoted 2 lines
include/pe.h +1
-0+}WIN_CERTIFICATE , *LPWIN_CERTIFICATE ;Please, always make use of
scripts/checkpatch.plbefore submitting patches. It says 'WARNING: do not add new typedefs'.ditto.
I have runscripts/cehckpatch.pland dare to leave them unchanged.Quoted 1 line
Please, avoid the typedefs.
No. this is also consistent with other typedef's.
Quoted 6 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 263
Quoted 1 line
include/pe.h +1
-0+The following defines are verbatim copies from Linux. Please, also copy the comment:
/* Definitions for the contents of the certs data block */
Okay.
Quoted 11 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 271
Quoted 9 lines
include/pe.h +7
-0+#define WIN_CERT_TYPE_PKCS_SIGNED_DATA 0x0002 +#define WIN_CERT_TYPE_EFI_OKCS115 0x0EF0 +#define WIN_CERT_TYPE_EFI_GUID 0x0EF1 + +#define WIN_CERT_REVISION_1_0 0x0100 +#define WIN_CERT_REVISION_2_0 0x0200 +#endif /* _PE_H */ Except for the style issues this looks ok.
Thank you for your comments.
-Takahiro AkashiQuoted 4 lines
Best regards
Heinrich
PATCH 1/16 include: pe.h: add signature-related definitions
Quoted 41 lines · Heinrich Schuchardt
Quoted 40 lines · AKASHI Takahiro
Heinrich,
Quoted 25 lines · Heinrich Schuchardt
Quoted 18 lines · AKASHI Takahiro
The index (
IMAGE_DIRECTORY_ENTRY_CERTTABLE) in a table points to a region containing authentication information (image's signature) in PE format.
WIN_CERTIFICATEstructure defines an embedded signature format.Those definitions will be used in my UEFI secure boot patch.
Signed-off-by AKASHI Takahiro <[email protected]>--- include/pe.h | 16 ++++++++++++++++ 1 file changed, 16 insertions(+)include/pe.h +0
-0include/pe.h typedef struct _IMAGE_SECTION_HEADER { · line 157
Quoted 3 lines
include/pe.h +0
-0@@ -155,6 +155,7 @@ typedef struct _IMAGE_SECTION_HEADER {uint32_t Characteristics; }IMAGE_SECTION_HEADER , *PIMAGE_SECTION_HEADER ;Please, add a comment here:
Quoted 1 line
/* Indices for Optional Header Data Directories */
Okay.
Quoted 5 lines
include/pe.h typedef struct _IMAGE_SECTION_HEADER { · line 158
Quoted 1 line
include/pe.h +1
-0+#define IMAGE_DIRECTORY_ENTRY_CERTTABLE 4Yes, 4 is the index of the certificate table. But EDK II calls this
EFI_IMAGE_DIRECTORY_ENTRY_SECURITY. Should we use the same name to avoid confusion?No. Because the naming is consistent with
Quoted 7 lines
Quoted 3 lines
Quoted 1 line
include/pe.h typedef struct _IMAGE_SECTION_HEADER { · line 159
Quoted 1 line
include/pe.h +0
-0#define IMAGE_DIRECTORY_ENTRY_BASERELOC 5this existing one.
IMAGE_DIRECTORY_ENTRY_BASERELOCis a constant name used by EDK2 inMdePkg/Include/IndustryStandard/PeImage.h. Why do you want to deviate forEFI_IMAGE_DIRECTORY_ENTRY_SECURITY?
Okay, but not due to EDK2, but because Windows uses it:
https://docs.microsoft.com/en-us/windows/win32/api/dbghelp/nf-dbghelp-imagedirectoryentrytodata
Quoted 21 lines
Quoted 21 lines
Quoted 20 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 257
Quoted 9 lines
include/pe.h +2
-0typedef struct _IMAGE_BASE_RELOCATION@@ -252,4 +253,19 @@ typedef struct _IMAGE_RELOCATION#define IMAGE_REL_AMD64_PAIR 0x000F#define IMAGE_REL_AMD64_SSPAN32 0x0010 +/* certificate appended to PE image */ +typedef struct _WIN_CERTIFICATE {We do not capitalize structs. Please use '
win_certificate' (like Linux does).include/pe.h typedef struct _IMAGE_RELOCATION · line 261
Quoted 4 lines
include/pe.h +4
-0+uint32_t dwLength; +uint16_t wRevision; +uint16_t wCertificateType; +uint8_t bCertificate[];We do not use camelcase and type prefixes. Please, use the same component names as Linux (plus 'certificate' for your extra field).
Quoted 6 lines
Quoted 4 lines
nak.
Have you looked at 'pe.h' at all?
There are already bunch of use of camelcase's and capital names since this file was first introduced by Alex.This shouldn't have happened in the first place.
For consistency, we should keep the style in the *existing* files.
-Takahiro Akashi
Quoted 48 lines
Best regards
Heinrich
Quoted 43 lines
Quoted 5 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 262
Quoted 2 lines
include/pe.h +1
-0+}WIN_CERTIFICATE , *LPWIN_CERTIFICATE ;Please, always make use of
scripts/checkpatch.plbefore submitting patches. It says 'WARNING: do not add new typedefs'.ditto.
I have runscripts/cehckpatch.pland dare to leave them unchanged.Quoted 1 line
Please, avoid the typedefs.
No. this is also consistent with other typedef's.
Quoted 6 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 263
Quoted 1 line
include/pe.h +1
-0+The following defines are verbatim copies from Linux. Please, also copy the comment:
/* Definitions for the contents of the certs data block */
Okay.
Quoted 11 lines
include/pe.h typedef struct _IMAGE_RELOCATION · line 271
Quoted 9 lines
include/pe.h +7
-0+#define WIN_CERT_TYPE_PKCS_SIGNED_DATA 0x0002 +#define WIN_CERT_TYPE_EFI_OKCS115 0x0EF0 +#define WIN_CERT_TYPE_EFI_GUID 0x0EF1 + +#define WIN_CERT_REVISION_1_0 0x0100 +#define WIN_CERT_REVISION_2_0 0x0200 +#endif /* _PE_H */ Except for the style issues this looks ok.
Thank you for your comments.
-Takahiro AkashiQuoted 4 lines
Best regards
Heinrich
PATCH 2/16 include: image.h: export hash algorithm helper functions
In reply to AKASHI TakahiroThis commit allows us to use common/image-sig.c even if CONFIG_FIT is disabled but CONFIG_EFI_LOADER is enabled.
--- include/image.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-)
include/image.h +5 -5
@@ -53,7 +53,7 @@ struct fdt_region;#endif /* USE_HOSTCC */ -#if IMAGE_ENABLE_FIT +#if IMAGE_ENABLE_FIT || defined(CONFIG_EFI_SECURE_BOOT )#include <hash.h> #include <linux/libfdt.h> #include <fdt_support.h>
@@ -86,13 +86,14 @@ struct fdt_region;#endif #if defined(CONFIG_FIT_ENABLE_SHA256_SUPPORT ) || \ - defined(CONFIG_SPL_SHA256_SUPPORT ) + defined(CONFIG_SPL_SHA256_SUPPORT ) || \ + defined(CONFIG_EFI_SECURE_BOOT )#define IMAGE_ENABLE_SHA256 1#else #define IMAGE_ENABLE_SHA256 0#endif -#endif /* IMAGE_ENABLE_FIT */ +#endif /* IMAGE_ENABLE_FIT || defined(CONFIG_EFI_SECURE_BOOT) */ #ifdef CONFIG_SYS_BOOT_GET_CMDLINE # define IMAGE_BOOT_GET_CMDLINE 1
@@ -1261,7 +1262,6 @@ struct crypto_algo *image_get_crypto_algo(const char *full_name);struct padding_algo *image_get_padding_algo (const char *name);#if IMAGE_ENABLE_FIT -/** * fit_image_verify_required_sigs() - Verify signatures marked as 'required' *
@@ -1337,7 +1337,7 @@ static inline int fit_image_check_target_arch(const void *fdt, int node)#define fit_unsupported (msg)#define fit_unsupported_reset (msg)#endif /* CONFIG_FIT_VERBOSE */ -#endif /* CONFIG_FIT */ +#endif /* IMAGE_ENABLE_FIT */ #if defined(CONFIG_ANDROID_BOOT_IMAGE )struct andr_img_hdr ;
Signature · 1 line
2.21.0
PATCH 2/16 include: image.h: export hash algorithm helper functions
Quoted 13 lines · AKASHI Takahiro
This commit allows us to use
common/image-sig.ceven ifCONFIG_FITis disabled butCONFIG_EFI_LOADERis enabled.Signed-off-by AKASHI Takahiro <[email protected]>--- include/image.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-)include/image.h +0
-0
include/image.h struct fdt_region; · line 56
Quoted 5 lines
include/image.h +1
-1@@ -53,7 +53,7 @@ struct fdt_region;#endif /* USE_HOSTCC */ -#if IMAGE_ENABLE_FIT +#if IMAGE_ENABLE_FIT || defined(CONFIG_EFI_SECURE_BOOT )
Is this #if needed at all?
Did you run Travis to check that defining CONFIG_EFI_SECURE_BOOT does not lead to build failures if IMAGE_ENABLE_FIT is not defined?
include/image.h struct fdt_region; · line 90
Quoted 10 lines
include/image.h +2
-1#include <hash.h> #include <linux/libfdt.h> #include <fdt_support.h> @@ -86,13 +86,14 @@ struct fdt_region;#endif #if defined(CONFIG_FIT_ENABLE_SHA256_SUPPORT ) || \ - defined(CONFIG_SPL_SHA256_SUPPORT ) + defined(CONFIG_SPL_SHA256_SUPPORT ) || \ + defined(CONFIG_EFI_SECURE_BOOT )
IMAGE_ENABLE_SHA256 is only used in common/image-fit.c. So why would you change anything here?
Quoted 11 lines
include/image.h +1
-1#define IMAGE_ENABLE_SHA256 1#else #define IMAGE_ENABLE_SHA256 0#endif -#endif /* IMAGE_ENABLE_FIT */ +#endif /* IMAGE_ENABLE_FIT || defined(CONFIG_EFI_SECURE_BOOT) */ #ifdef CONFIG_SYS_BOOT_GET_CMDLINE # define IMAGE_BOOT_GET_CMDLINE 1
include/image.h struct crypto_algo *image_get_crypto_algo(const char *full_name); · line 1264
Quoted 4 lines
include/image.h +0
-1@@ -1261,7 +1262,6 @@ struct crypto_algo *image_get_crypto_algo(const char *full_name);struct padding_algo *image_get_padding_algo (const char *name);#if IMAGE_ENABLE_FIT -
This change is unrelated. It should be in a separate patch. Or at least mention in the commit message that you cleaned up other parts of the code.
include/image.h static inline int fit_image_check_target_arch(const void *fdt, int node) · line 1340
Quoted 9 lines
include/image.h +1
-1/** * fit_image_verify_required_sigs() - Verify signatures marked as 'required' * @@ -1337,7 +1337,7 @@ static inline int fit_image_check_target_arch(const void *fdt, int node)#define fit_unsupported (msg)#define fit_unsupported_reset (msg)#endif /* CONFIG_FIT_VERBOSE */ -#endif /* CONFIG_FIT */ +#endif /* IMAGE_ENABLE_FIT */
Same here.
Best regards
Heinrich
Quoted 4 lines
include/image.h +0
-0#if defined(CONFIG_ANDROID_BOOT_IMAGE )struct andr_img_hdr ;
PATCH 2/16 include: image.h: export hash algorithm helper functions
Heinrich,
Quoted 17 lines · Heinrich Schuchardt
Quoted 16 lines · AKASHI Takahiro
This commit allows us to use
common/image-sig.ceven ifCONFIG_FITis disabled butCONFIG_EFI_LOADERis enabled.Signed-off-by AKASHI Takahiro <[email protected]>--- include/image.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-)include/image.h +0
-0@@ -53,7 +53,7 @@ struct fdt_region;#endif /* USE_HOSTCC */
Quoted 7 lines
include/image.h struct fdt_region; · line 56
Quoted 2 lines
include/image.h +1
-1-#if IMAGE_ENABLE_FIT +#if IMAGE_ENABLE_FIT || defined(CONFIG_EFI_SECURE_BOOT )Is this #if needed at all?
Did you run Travis to check that defining
CONFIG_EFI_SECURE_BOOTdoes not lead to build failures ifIMAGE_ENABLE_FITis not defined?
Before posting, I have confirmed that the following combination of config options did not cause any build error, at least, on qemu_arm64:
1. CONFIG_EFI_SECURE_BOOT only
2. CONFIG_FIT (with/without CONFIG_FIT_SIGNATURE) only
3. CONFIG_EFI_SECURE_BOOT and CONFIG_FIT (with/without CONFIG_FIT_SIGNATURE)
I also successfully ran Travis although CONFI_EFI_SECURE_BOOT is not enabled by default.
Quoted 6 lines
Quoted 6 lines
include/image.h +0
-0#include <hash.h> #include <linux/libfdt.h> #include <fdt_support.h> @@ -86,13 +86,14 @@ struct fdt_region;#endif
Quoted 7 lines
include/image.h struct fdt_region; · line 90
Quoted 4 lines
include/image.h +2
-1#if defined(CONFIG_FIT_ENABLE_SHA256_SUPPORT ) || \ - defined(CONFIG_SPL_SHA256_SUPPORT ) + defined(CONFIG_SPL_SHA256_SUPPORT ) || \ + defined(CONFIG_EFI_SECURE_BOOT )
IMAGE_ENABLE_SHA256is only used incommon/image-fit.c. So why would you change anything here?
Okay, I have forgot to remove it.
At some point, I used to use both calculate_hash() and hash_calculate(), then dropped the former.
Quoted 13 lines
Quoted 13 lines
include/image.h +1
-1#define IMAGE_ENABLE_SHA256 1#else #define IMAGE_ENABLE_SHA256 0#endif -#endif /* IMAGE_ENABLE_FIT */ +#endif /* IMAGE_ENABLE_FIT || defined(CONFIG_EFI_SECURE_BOOT) */ #ifdef CONFIG_SYS_BOOT_GET_CMDLINE # define IMAGE_BOOT_GET_CMDLINE 1@@ -1261,7 +1262,6 @@ struct crypto_algo *image_get_crypto_algo(const char *full_name);struct padding_algo *image_get_padding_algo (const char *name);
Quoted 5 lines
include/image.h struct crypto_algo *image_get_crypto_algo(const char *full_name); · line 1264
Quoted 2 lines
include/image.h +0
-1#if IMAGE_ENABLE_FIT -This change is unrelated. It should be in a separate patch. Or at least mention in the commit message that you cleaned up other parts of the code.
I don't want to get bothered with minor clean-up patches, and will drop this hunk.
-Takahiro Akashi
Quoted 20 lines
include/image.h static inline int fit_image_check_target_arch(const void *fdt, int node) · line 1340
Quoted 9 lines
include/image.h +1
-1/** * fit_image_verify_required_sigs() - Verify signatures marked as 'required' * @@ -1337,7 +1337,7 @@ static inline int fit_image_check_target_arch(const void *fdt, int node)#define fit_unsupported (msg)#define fit_unsupported_reset (msg)#endif /* CONFIG_FIT_VERBOSE */ -#endif /* CONFIG_FIT */ +#endif /* IMAGE_ENABLE_FIT */ Same here.
Best regards
Heinrich
Quoted 4 lines
include/image.h +0
-0#if defined(CONFIG_ANDROID_BOOT_IMAGE )struct andr_img_hdr ;
PATCH 3/16 secure boot: rename CONFIG_SECURE_BOOT config option
In reply to AKASHI TakahiroThe configuration, CONFIG_SECURE_BOOT, is defined multiple times in different architecture directories for different implementation. If UEFI secure boot will be added later, it will make things more messy.
So let's rename them, giving each implementation to different configuration option. CONFIG_SECURE_BOOT still remains in order not to break existing implicit dependency.
--- Kconfig | 7 +++++++ arch/arm/cpu/armv7/ls102xa/Kconfig | 3 ++- arch/arm/cpu/armv8/fsl-layerscape/Kconfig | 3 ++- arch/powerpc/cpu/mpc85xx/Kconfig | 3 ++- 4 files changed, 13 insertions(+), 3 deletions(-)
Kconfig +7 -0
@@ -283,6 +283,13 @@ config SYS_LDSCRIPT endmenu # General setup +config SECURE_BOOT + bool "Secure Boot" + imply SHA256 + help + Enable Secure Boot feature. The actual behavior may vary + from architecture to architecture. + menu "Boot images" config ANDROID_BOOT_IMAGE
arch/arm/cpu/armv7/ls102xa/Kconfig +2 -1
@@ -50,8 +50,9 @@ config MAX_CPUS cores, count the reserved ports. This will allocate enough memory in spin table to properly handle all cores. -config SECURE_BOOT +config FSL_ARMV7_ENABLE_SECURE_BOOT bool "Secure Boot" + depends on SECURE_BOOT help Enable Freescale Secure Boot feature. Normally selected by defconfig. If unsure, do not change.
arch/arm/cpu/armv8/fsl-layerscape/Kconfig +2 -1
@@ -375,8 +375,9 @@ config EMC2305 Enable the EMC2305 fan controller for configuration of fan speed. -config SECURE_BOOT +config FSI_ARMV8_ENABLE_SECURE_BOOT bool "Secure Boot" + depends on SECURE_BOOT help Enable Freescale Secure Boot feature
arch/powerpc/cpu/mpc85xx/Kconfig +2 -1
@@ -1208,8 +1208,9 @@ config FSL_LAW help Use Freescale common code for Local Access Window -config SECURE_BOOT +config FSL_MPC_ENABLE_SECURE_BOOT bool "Secure Boot" + depends on SECURE_BOOT help Enable Freescale Secure Boot feature. Normally selected by defconfig. If unsure, do not change.
Signature · 1 line
2.21.0
PATCH 4/16 efi_loader: add CONFIG_EFI_SECURE_BOOT config option
In reply to AKASHI TakahiroUnder this configuration, UEFI secure boot support will be added in later patches.
--- lib/efi_loader/Kconfig | 13 +++++++++++++ 1 file changed, 13 insertions(+)
lib/efi_loader/Kconfig +13 -0
@@ -115,4 +115,17 @@ config EFI_GRUB_ARM32_WORKAROUND GRUB prior to version 2.04 requires U-Boot to disable caches. This workaround currently is also needed on systems with caches that cannot be managed via CP15. + +config EFI_SECURE_BOOT + bool "Enable EFI secure boot support" + depends on EFI_LOADER + depends on SECURE_BOOT + imply RSA_VERIFY_WITH_PKEY + 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.21.0
PATCH 5/16 efi_loader: add signature verification functions
In reply to AKASHI TakahiroIn 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 | 47 +++ include/efi_loader.h | 46 +++ lib/efi_loader/Makefile | 1 + lib/efi_loader/efi_signature.c | 600 +++++++++++++++++++++++++++++++++ 4 files changed, 694 insertions(+) create mode 100644 lib/efi_loader/efi_signature.c
include/efi_api.h +47 -0
@@ -18,6 +18,7 @@#include <efi.h> #include <charset.h> +#include <pe.h> #ifdef CONFIG_EFI_LOADER #include <asm/setjmp.h>
@@ -307,6 +308,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)
@@ -1616,4 +1621,46 @@ struct efi_unicode_collation_protocol {#define LOAD_OPTION_CATEGORY_BOOT 0x00000000#define LOAD_OPTION_CATEGORY_APP 0x00000100 +/* Secure boot */ +#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) + +struct win_certificate_uefi_guid { +WIN_CERTIFICATE hdr; +efi_guid_t cert_type; +u8 cert_data[]; +} __attribute__((__packed__ )); + +struct efi_variable_authentication_2 { +struct efi_time time_stamp; +struct win_certificate_uefi_guid auth_info; +} __attribute__((__packed__ )); + +struct efi_signature_data { +efi_guid_t signature_owner; +u8 signature_data[]; +} __attribute__((__packed__ )); + +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 +46 -0
64 lines not on this page · raw message
lib/efi_loader/Makefile +1 -0
@@ -39,3 +39,4 @@ obj-$(CONFIG_PARTITIONS) += efi_disk.o obj-$(CONFIG_NET) += efi_net.o obj-$(CONFIG_GENERATE_ACPI_TABLE) += efi_acpi.o obj-$(CONFIG_GENERATE_SMBIOS_TABLE) += efi_smbios.o +obj-y += efi_signature.o
lib/efi_loader/efi_signature.c new file +600 -0
600 lines not on this page · raw message
Signature · 1 line
2.21.0
PATCH 5/16 efi_loader: add signature verification functions
Quoted 3 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.
In which patch do you implement the unit tests for the new functions? I would expect them in /test/lib/ as tests invoked via the ut command.
Quoted 34 lines
Signed-off-by AKASHI Takahiro <[email protected]>--- include/efi_api.h | 47 +++ include/efi_loader.h | 46 +++ lib/efi_loader/Makefile | 1 + lib/efi_loader/efi_signature.c | 600 +++++++++++++++++++++++++++++++++ 4 files changed, 694 insertions(+)create mode 100644
lib/efi_loader/efi_signature.cinclude/efi_api.h +5
-0@@ -18,6 +18,7 @@#include <efi.h> #include <charset.h> +#include <pe.h> #ifdef CONFIG_EFI_LOADER #include <asm/setjmp.h> @@ -307,6 +308,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)
include/efi_api.h struct efi_unicode_collation_protocol { · line 1624
Quoted 4 lines
include/efi_api.h +1
-0@@ -1616,4 +1621,46 @@ struct efi_unicode_collation_protocol {#define LOAD_OPTION_CATEGORY_BOOT 0x00000000#define LOAD_OPTION_CATEGORY_APP 0x00000100 +/* Secure boot */
Please, add a comment for each GUID.
Quoted 6 lines
include/efi_api.h +6
-0+#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)
include/efi_api.h struct efi_unicode_collation_protocol { · line 1640
Quoted 10 lines
include/efi_api.h +10
-0+#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) +
Please add comments in Spinx style.
What is the structure used for?
What information do the fields hold?
Same for all structures.
include/efi_api.h struct efi_unicode_collation_protocol { · line 1642
Quoted 2 lines
include/efi_api.h +2
-0+struct win_certificate_uefi_guid { +WIN_CERTIFICATE hdr;
See comment to 01/16 (avoid typedefs).
Quoted 37 lines
include/efi_api.h +23
-0+efi_guid_t cert_type; +u8 cert_data[]; +} __attribute__((__packed__)); + +struct efi_variable_authentication_2 { +struct efi_time time_stamp; +struct win_certificate_uefi_guid auth_info; +} __attribute__((__packed__ )); + +struct efi_signature_data { +efi_guid_t signature_owner; +u8 signature_data[]; +} __attribute__((__packed__ )); + +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 +1
-0@@ -21,6 +21,7 @@ static inline int guidcmp(const void *g1, const void *g2)#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
include/efi_loader.h extern const efi_guid_t efi_guid_hii_config_routing_protocol; · line 173
Quoted 4 lines
include/efi_loader.h +1
-0@@ -169,6 +170,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; +/* GUID for authentication */
%s/GUID/GUIDs/g ?
include/efi_loader.h void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data); · line 659
Quoted 12 lines
include/efi_loader.h +5
-0+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 unsigned int __efi_runtime_start, __efi_runtime_stop;extern unsigned int __efi_runtime_rel_start, __efi_runtime_rel_stop;@@ -650,6 +656,46 @@ 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?
include/efi_loader.h void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data); · line 663
Quoted 4 lines
include/efi_loader.h +4
-0+#include <image.h> + +#define EFI_REGS_MAX 16/* currently good enough */ +
Do you mean: this could be exceeded in special cases?
Can't we use a linked list for regions? We should not embed any unnecessary restrictions.
Add comments explaining what the structures are used for.
Quoted 53 lines
include/efi_loader.h +35
-0+struct efi_image_regions { +int num; +struct image_region reg[EFI_REGS_MAX ]; +}; + +struct efi_sig_data { +struct efi_sig_data *next; +efi_guid_t owner; +void *data; +size_t size; +}; + +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@@ -39,3 +39,4 @@ obj-$(CONFIG_PARTITIONS) += efi_disk.o obj-$(CONFIG_NET) += efi_net.o obj-$(CONFIG_GENERATE_ACPI_TABLE) += efi_acpi.o obj-$(CONFIG_GENERATE_SMBIOS_TABLE) += efi_smbios.o +obj-y += efi_signature.olib/efi_loader/efi_signature.c new file +0
-0
lib/efi_loader/efi_signature.c line 3
Quoted 3 lines
lib/efi_loader/efi_signature.c new file +3
-0@@ -0,0 +1,600 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* +* Copyright (c) 2018 Patrick Wildt <[email protected]>
From which upstream did you take the code?
lib/efi_loader/efi_signature.c line 6
Quoted 3 lines
lib/efi_loader/efi_signature.c new file +3
-0+* Copyright (c) 2019 Linaro Limited, Author: AKASHI Takahiro +*/ +
debug() checks the value of _DEBUG.
Please, include common.h as first include.
Use the sequence of includes as defined in
https://www.denx.de/wiki/U-Boot/CodingStyle
lib/efi_loader/efi_signature.c line 15
Quoted 9 lines
lib/efi_loader/efi_signature.c new file +9
-0+#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>
Shouldn't we move all cryptography stuff into a directory crypto/?
Quoted 6 lines
lib/efi_loader/efi_signature.c new file +6
-0+#include <u-boot/sha256.h> +/* +* avoid duplicated inclusion: +* #include "../lib/crypto/x509_parser.h" +*/ +#include "../lib/crypto/pkcs7_parser.h"
lib/efi_loader/efi_signature.c line 31
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-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 +static const unsigned char WinIndirectSha256[] = {
We don't use camel case.
lib/efi_loader/efi_signature.c line 38
Quoted 7 lines
lib/efi_loader/efi_signature.c new file +7
-0+0x30 ,0x33 ,0x06 ,0x0a ,0x2b ,0x06 ,0x01 ,0x04 ,0x01 ,0x82 ,0x37 ,0x02 , +0x01 ,0x0f ,0x30 ,0x25 ,0x03 ,0x01 ,0x00 ,0xa0 ,0x20 ,0xa2 ,0x1e ,0x80 , +0x1c ,0x00 ,0x3c ,0x00 ,0x3c ,0x00 ,0x3c ,0x00 ,0x4f ,0x00 ,0x62 ,0x00 , +0x73 ,0x00 ,0x6f ,0x00 ,0x6c ,0x00 ,0x65 ,0x00 ,0x74 ,0x00 ,0x65 ,0x00 , +0x3e ,0x00 ,0x3e ,0x00 ,0x3e ,0x30 ,0x31 ,0x30 ,0x0d ,0x06 ,0x09 ,0x60 , +0x86 ,0x48 ,0x01 ,0x65 ,0x03 ,0x04 ,0x02 ,0x01 ,0x05 ,0x00 ,0x04 ,0x20 +};
What secret sauce is this? - Please, add comments where applicable. Add references where needed for verification of correctness.
Below you describe it as DER wrapper. So why call the variable Sha256?
lib/efi_loader/efi_signature.c line 46
Quoted 8 lines
lib/efi_loader/efi_signature.c new file +8
-0+ +/** +* 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.
Is this a hash of the concatenation of all regions - or is this a list of hashes one for each regions?
lib/efi_loader/efi_signature.c line 51
Quoted 5 lines
lib/efi_loader/efi_signature.c new file +5
-0+* +* Return: true on success, false on error +*/ +static bool efi_hash_regions (struct efi_image_regions *regs,void **hash, +size_t *size)
Why use void** for hash? There should be a structure for SHA256 hashes.
lib/efi_loader/efi_signature.c line 63
Quoted 12 lines
lib/efi_loader/efi_signature.c new file +12
-0+{ + *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" );
debug checks the value of _DEBUG not of DEBUG. So wouldn't you use #ifdef _DEBUG to be consistent?
lib/efi_loader/efi_signature.c line 65
Quoted 2 lines
lib/efi_loader/efi_signature.c new file +2
-0+print_hex_dump (" " ,DUMP_PREFIX_OFFSET ,16 ,1 , + *hash,SHA256_SUM_LEN , false);
This will fail to compile if CONFIG_HEXDUMP is not defined?
Quoted 182 lines
lib/efi_loader/efi_signature.c new file +182
-0+#endif + +return true; +} + +/** +* efi_hash_regions_in_der - 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. +* This function is a variant of efi_hash_regions(), and the data will +* be wrapped with some header in DER format before hash calculation. +* Message digest in signature of PE format will be calculated this way. +* +* Return: true on success, false on error +*/ +static bool efi_hash_regions_in_der (struct efi_image_regions *regs,void **hash, +size_t *size) +{ +void *msg; +size_t msg_size; +struct image_region regtmp[2 ]; + +if (!efi_hash_regions (regs, &msg, &msg_size)) { +debug ("Hash calculation failed\n" ); +return false; + ; + } + + *size =0 ; + *hash =calloc (1 ,SHA256_SUM_LEN ); +if (!*hash) { +debug ("Out of memory\n" ); +free (msg); +return false; + } + *size =SHA256_SUM_LEN ; + +/* File image hash is digested with some DER wrapper. */ + regtmp[0 ].data = WinIndirectSha256; + regtmp[0 ].size =sizeof (WinIndirectSha256); + regtmp[1 ].data = msg; + regtmp[1 ].size = msg_size; + +hash_calculate ("sha256" , regtmp,2 , *hash); +#ifdef DEBUG +debug ("hash calculated with extra header:\n" ); +print_hex_dump (" " ,DUMP_PREFIX_OFFSET ,16 ,1 , + *hash,SHA256_SUM_LEN , false); +#endif + +free (msg); + +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_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 +if (efi_hash_regions_in_der (regs, &hash, &size)) { +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 +* @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,
lib/efi_loader/efi_signature.c line 257
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-0+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);
Shouldn't we use EFI_PRINT() to get proper indentation?
lib/efi_loader/efi_signature.c line 263
Quoted 6 lines
lib/efi_loader/efi_signature.c new file +6
-0+ +if (!signed_info) { +void *hash; +size_t size; + +debug ("%s: unsigned image\n" , __func__);
We already have indicated the function above.
Quoted 12 lines
lib/efi_loader/efi_signature.c new file +12
-0+/* +* 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" );
lib/efi_loader/efi_signature.c line 285
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-0+ 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);
Does this compile if CONFIG_HEXDUMP is not defined?
Quoted 194 lines
lib/efi_loader/efi_signature.c new file +194
-0+#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, signed_info, cert); + +if (verified) { +if (valid_cert) + *valid_cert = cert; +else +x509_free_certificate (cert); +break ; + }else { +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 , + 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, 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". +*
lib/efi_loader/efi_signature.c line 489
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-0+* 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);
EFI_PRINT() ?
lib/efi_loader/efi_signature.c line 497
Quoted 8 lines
lib/efi_loader/efi_signature.c new file +8
-0+ +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 */
Is this a difficult thing to do? If not, please, fill the gap.
Best regards
Heinrich
Quoted 104 lines
lib/efi_loader/efi_signature.c new file +103
-0+ + 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 >=EFI_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 = ®s->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 (®s->reg[j], ®s->reg[j +1 ], +sizeof (*reg)); +break ; + } + } + + reg = ®s->reg[i]; + reg->data = start; + reg->size = end - start; + regs->num++; + +return EFI_SUCCESS ; +} +#endif /* CONFIG_EFI_SECURE_BOOT */
PATCH 5/16 efi_loader: add signature verification functions
Heinrich,
I will address other comments in a separate e-mail, but
it is worth mentioning that Patrick deserves credit for initial implementation of efi secure boot, which the main logic of my current patch set heavily relies on;
Quoted 13 lines · Heinrich Schuchardt
lib/efi_loader/efi_signature.c line 3
Quoted 9 lines · AKASHI Takahiro
lib/efi_loader/efi_signature.c new file +3
-0@@ -0,0 +1,600 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* +* Copyright (c) 2018 Patrick Wildt <[email protected]> From which upstream did you take the code?
The original code has never been upstreamed, and I took over his patch directly from him.
Thanks,
-Takahiro Akashi
Quoted 651 lines
lib/efi_loader/efi_signature.c line 6
Quoted 3 lines
lib/efi_loader/efi_signature.c new file +3
-0+* Copyright (c) 2019 Linaro Limited, Author: AKASHI Takahiro +*/ +
debug()checks the value of_DEBUG.
Please, includecommon.has first include.Use the sequence of includes as defined in
https://www.denx.de/wiki/U-Boot/CodingStylelib/efi_loader/efi_signature.c line 15
Quoted 9 lines
lib/efi_loader/efi_signature.c new file +9
-0+#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> Shouldn't we move all cryptography stuff into a directory
crypto/?Quoted 6 lines
lib/efi_loader/efi_signature.c new file +6
-0+#include <u-boot/sha256.h> +/* +* avoid duplicated inclusion: +* #include "../lib/crypto/x509_parser.h" +*/ +#include "../lib/crypto/pkcs7_parser.h" lib/efi_loader/efi_signature.c line 31
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-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 +static const unsigned char WinIndirectSha256[] = {We don't use camel case.
lib/efi_loader/efi_signature.c line 38
Quoted 7 lines
lib/efi_loader/efi_signature.c new file +7
-0+0x30 ,0x33 ,0x06 ,0x0a ,0x2b ,0x06 ,0x01 ,0x04 ,0x01 ,0x82 ,0x37 ,0x02 , +0x01 ,0x0f ,0x30 ,0x25 ,0x03 ,0x01 ,0x00 ,0xa0 ,0x20 ,0xa2 ,0x1e ,0x80 , +0x1c ,0x00 ,0x3c ,0x00 ,0x3c ,0x00 ,0x3c ,0x00 ,0x4f ,0x00 ,0x62 ,0x00 , +0x73 ,0x00 ,0x6f ,0x00 ,0x6c ,0x00 ,0x65 ,0x00 ,0x74 ,0x00 ,0x65 ,0x00 , +0x3e ,0x00 ,0x3e ,0x00 ,0x3e ,0x30 ,0x31 ,0x30 ,0x0d ,0x06 ,0x09 ,0x60 , +0x86 ,0x48 ,0x01 ,0x65 ,0x03 ,0x04 ,0x02 ,0x01 ,0x05 ,0x00 ,0x04 ,0x20 +};What secret sauce is this? - Please, add comments where applicable. Add references where needed for verification of correctness.
Below you describe it as DER wrapper. So why call the variable Sha256?
lib/efi_loader/efi_signature.c line 46
Quoted 8 lines
lib/efi_loader/efi_signature.c new file +8
-0+ +/** +* 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. Is this a hash of the concatenation of all regions - or is this a list of hashes one for each regions?
lib/efi_loader/efi_signature.c line 51
Quoted 5 lines
lib/efi_loader/efi_signature.c new file +5
-0+* +* Return: true on success, false on error +*/ +static bool efi_hash_regions (struct efi_image_regions *regs,void **hash, +size_t *size)Why use void** for hash? There should be a structure for SHA256 hashes.
lib/efi_loader/efi_signature.c line 63
Quoted 12 lines
lib/efi_loader/efi_signature.c new file +12
-0+{ + *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" );debug checks the value of
_DEBUGnot of DEBUG. So wouldn't you use #ifdef_DEBUGto be consistent?lib/efi_loader/efi_signature.c line 65
Quoted 2 lines
lib/efi_loader/efi_signature.c new file +2
-0+print_hex_dump (" " ,DUMP_PREFIX_OFFSET ,16 ,1 , + *hash,SHA256_SUM_LEN , false);This will fail to compile if
CONFIG_HEXDUMPis not defined?Quoted 182 lines
lib/efi_loader/efi_signature.c new file +182
-0+#endif + +return true; +} + +/** +* efi_hash_regions_in_der - 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. +* This function is a variant of efi_hash_regions(), and the data will +* be wrapped with some header in DER format before hash calculation. +* Message digest in signature of PE format will be calculated this way. +* +* Return: true on success, false on error +*/ +static bool efi_hash_regions_in_der (struct efi_image_regions *regs,void **hash, +size_t *size) +{ +void *msg; +size_t msg_size; +struct image_region regtmp[2 ]; + +if (!efi_hash_regions (regs, &msg, &msg_size)) { +debug ("Hash calculation failed\n" ); +return false; + ; + } + + *size =0 ; + *hash =calloc (1 ,SHA256_SUM_LEN ); +if (!*hash) { +debug ("Out of memory\n" ); +free (msg); +return false; + } + *size =SHA256_SUM_LEN ; + +/* File image hash is digested with some DER wrapper. */ + regtmp[0 ].data = WinIndirectSha256; + regtmp[0 ].size =sizeof (WinIndirectSha256); + regtmp[1 ].data = msg; + regtmp[1 ].size = msg_size; + +hash_calculate ("sha256" , regtmp,2 , *hash); +#ifdef DEBUG +debug ("hash calculated with extra header:\n" ); +print_hex_dump (" " ,DUMP_PREFIX_OFFSET ,16 ,1 , + *hash,SHA256_SUM_LEN , false); +#endif + +free (msg); + +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_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 +if (efi_hash_regions_in_der (regs, &hash, &size)) { +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 +* @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,lib/efi_loader/efi_signature.c line 257
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-0+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);Shouldn't we use
EFI_PRINT()to get proper indentation?lib/efi_loader/efi_signature.c line 263
Quoted 6 lines
lib/efi_loader/efi_signature.c new file +6
-0+ +if (!signed_info) { +void *hash; +size_t size; + +debug ("%s: unsigned image\n" , __func__);We already have indicated the function above.
Quoted 12 lines
lib/efi_loader/efi_signature.c new file +12
-0+/* +* 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" );lib/efi_loader/efi_signature.c line 285
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-0+ 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);Does this compile if
CONFIG_HEXDUMPis not defined?Quoted 194 lines
lib/efi_loader/efi_signature.c new file +194
-0+#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, signed_info, cert); + +if (verified) { +if (valid_cert) + *valid_cert = cert; +else +x509_free_certificate (cert); +break ; + }else { +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 , + 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, 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". +* lib/efi_loader/efi_signature.c line 489
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-0+* 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);
EFI_PRINT()?lib/efi_loader/efi_signature.c line 497
Quoted 8 lines
lib/efi_loader/efi_signature.c new file +8
-0+ +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 */ Is this a difficult thing to do? If not, please, fill the gap.
Best regards
Heinrich
Quoted 104 lines
lib/efi_loader/efi_signature.c new file +103
-0+ + 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 >=EFI_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 = ®s->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 (®s->reg[j], ®s->reg[j +1 ], +sizeof (*reg)); +break ; + } + } + + reg = ®s->reg[i]; + reg->data = start; + reg->size = end - start; + regs->num++; + +return EFI_SUCCESS ; +} +#endif /* CONFIG_EFI_SECURE_BOOT */
PATCH 5/16 efi_loader: add signature verification functions
In reply to Heinrich SchuchardtHeinrich,
Quoted 7 lines · Heinrich Schuchardt
Quoted 3 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.
In which patch do you implement the unit tests for the new functions? I would expect them in /test/lib/ as tests invoked via the ut command.
As I said elsewhere, signature verification will be best exercised and tested by image authentication or variable authentication (under pytest). As you may see, the interfaces take arguments of complicated structures and the code for setting up test environment and calling them properly would be almost equal to writing image authentication and variable authentication code.
Quoted 37 lines
Quoted 37 lines
Signed-off-by AKASHI Takahiro <[email protected]>--- include/efi_api.h | 47 +++ include/efi_loader.h | 46 +++ lib/efi_loader/Makefile | 1 + lib/efi_loader/efi_signature.c | 600 +++++++++++++++++++++++++++++++++ 4 files changed, 694 insertions(+) create mode 100644 lib/efi_loader/efi_signature.cinclude/efi_api.h +5
-0@@ -18,6 +18,7 @@#include <efi.h> #include <charset.h> +#include <pe.h> #ifdef CONFIG_EFI_LOADER #include <asm/setjmp.h> @@ -307,6 +308,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)@@ -1616,4 +1621,46 @@ struct efi_unicode_collation_protocol {#define LOAD_OPTION_CATEGORY_BOOT 0x00000000#define LOAD_OPTION_CATEGORY_APP 0x00000100
Quoted 3 lines
include/efi_api.h struct efi_unicode_collation_protocol { · line 1624
Quoted 1 line
include/efi_api.h +1
-0+/* Secure boot */ Please, add a comment for each GUID.
There are bunch of GUID definitions here that have no description. It is not very useful to do so since all those macro's are already defined by UEFI specification.
Quoted 19 lines
Quoted 6 lines
include/efi_api.h +6
-0+#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)include/efi_api.h struct efi_unicode_collation_protocol { · line 1640
Quoted 10 lines
include/efi_api.h +10
-0+#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) +Please add comments in Spinx style.
Quoted 4 lines
What is the structure used for?
What information do the fields hold?Same for all structures.
Okay.
Quoted 39 lines
include/efi_api.h struct efi_unicode_collation_protocol { · line 1642
Quoted 2 lines
include/efi_api.h +2
-0+struct win_certificate_uefi_guid { +WIN_CERTIFICATE hdr;See comment to 01/16 (avoid typedefs).
Quoted 34 lines
include/efi_api.h +23
-0+efi_guid_t cert_type; +u8 cert_data[]; +} __attribute__((__packed__)); + +struct efi_variable_authentication_2 { +struct efi_time time_stamp; +struct win_certificate_uefi_guid auth_info; +} __attribute__((__packed__ )); + +struct efi_signature_data { +efi_guid_t signature_owner; +u8 signature_data[]; +} __attribute__((__packed__ )); + +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 +1
-0@@ -21,6 +21,7 @@ static inline int guidcmp(const void *g1, const void *g2)#if CONFIG_IS_ENABLED (EFI_LOADER )#include <linux/list.h> +#include <linux/oid_registry.h>
Quoted 9 lines
include/efi_loader.h extern const efi_guid_t efi_guid_hii_config_routing_protocol; · line 173
Quoted 7 lines
include/efi_loader.h +1
-0/* Maximum number of configuration tables */ #define EFI_MAX_CONFIGURATION_TABLES 16@@ -169,6 +170,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; +/* GUID for authentication */ %s/GUID/GUIDs/g ?
Sure.
Quoted 11 lines
Quoted 11 lines
include/efi_loader.h +4
-0+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 unsigned int __efi_runtime_start, __efi_runtime_stop;extern unsigned int __efi_runtime_rel_start, __efi_runtime_rel_stop;@@ -650,6 +656,46 @@ 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);
Quoted 3 lines
include/efi_loader.h void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data); · line 659
Quoted 1 line
include/efi_loader.h +1
-0+#ifdef CONFIG_EFI_SECURE_BOOT Why do we need an #ifdef here?
Simply because those functions won't be defined if !CONFIG_EFI_SECURE_BOOT.
Quoted 10 lines
include/efi_loader.h void efi_deserialize_load_option(struct efi_load_option *lo, u8 *data); · line 663
Quoted 5 lines
include/efi_loader.h +4
-0+#include <image.h> + +#define EFI_REGS_MAX 16/* currently good enough */ +Do you mean: this could be exceeded in special cases?
Can't we use a linked list for regions? We should not embed any unnecessary restrictions.
I will address this issue in the next version.
Quoted 1 line
Add comments explaining what the structures are used for.
Okay.
Quoted 59 lines
Quoted 53 lines
include/efi_loader.h +35
-0+struct efi_image_regions { +int num; +struct image_region reg[EFI_REGS_MAX ]; +}; + +struct efi_sig_data { +struct efi_sig_data *next; +efi_guid_t owner; +void *data; +size_t size; +}; + +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@@ -39,3 +39,4 @@ obj-$(CONFIG_PARTITIONS) += efi_disk.o obj-$(CONFIG_NET) += efi_net.o obj-$(CONFIG_GENERATE_ACPI_TABLE) += efi_acpi.o obj-$(CONFIG_GENERATE_SMBIOS_TABLE) += efi_smbios.o +obj-y += efi_signature.olib/efi_loader/efi_signature.c new file +0
-0lib/efi_loader/efi_signature.c line 3
Quoted 3 lines
lib/efi_loader/efi_signature.c new file +3
-0@@ -0,0 +1,600 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* +* Copyright (c) 2018 Patrick Wildt <[email protected]> From which upstream did you take the code?
Quoted 6 lines
lib/efi_loader/efi_signature.c line 6
Quoted 3 lines
lib/efi_loader/efi_signature.c new file +3
-0+* Copyright (c) 2019 Linaro Limited, Author: AKASHI Takahiro +*/ +
debug()checks the value of_DEBUG.
Please, includecommon.has first include.
Sure.
Quoted 14 lines
Use the sequence of includes as defined in
https://www.denx.de/wiki/U-Boot/CodingStylelib/efi_loader/efi_signature.c line 15
Quoted 9 lines
lib/efi_loader/efi_signature.c new file +9
-0+#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> Shouldn't we move all cryptography stuff into a directory
crypto/?
On which part do you specifically have concerns?
The following code is UEFI specific, and I don't think that either crypto/ or lib/crypto, which I created for x509/pkcs7 parsers, is a right place.
Quoted 10 lines
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-0+#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 ;
Quoted 8 lines
lib/efi_loader/efi_signature.c line 31
Quoted 6 lines
lib/efi_loader/efi_signature.c new file +6
-0+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 +static const unsigned char WinIndirectSha256[] = {We don't use camel case.
Okay, this one is a local variable. Fix it.
Quoted 10 lines
lib/efi_loader/efi_signature.c line 38
Quoted 7 lines
lib/efi_loader/efi_signature.c new file +7
-0+0x30 ,0x33 ,0x06 ,0x0a ,0x2b ,0x06 ,0x01 ,0x04 ,0x01 ,0x82 ,0x37 ,0x02 , +0x01 ,0x0f ,0x30 ,0x25 ,0x03 ,0x01 ,0x00 ,0xa0 ,0x20 ,0xa2 ,0x1e ,0x80 , +0x1c ,0x00 ,0x3c ,0x00 ,0x3c ,0x00 ,0x3c ,0x00 ,0x4f ,0x00 ,0x62 ,0x00 , +0x73 ,0x00 ,0x6f ,0x00 ,0x6c ,0x00 ,0x65 ,0x00 ,0x74 ,0x00 ,0x65 ,0x00 , +0x3e ,0x00 ,0x3e ,0x00 ,0x3e ,0x30 ,0x31 ,0x30 ,0x0d ,0x06 ,0x09 ,0x60 , +0x86 ,0x48 ,0x01 ,0x65 ,0x03 ,0x04 ,0x02 ,0x01 ,0x05 ,0x00 ,0x04 ,0x20 +};What secret sauce is this? - Please, add comments where applicable. Add references where needed for verification of correctness.
A similar technique is also used in EDK2. I will add "decoded" version of data in a comment.
Quoted 1 line
Below you describe it as DER wrapper. So why call the variable Sha256?
Because it contains OID for sha256.
Quoted 20 lines
lib/efi_loader/efi_signature.c line 46
Quoted 8 lines
lib/efi_loader/efi_signature.c new file +8
-0+ +/** +* 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. Is this a hash of the concatenation of all regions - or is this a list of hashes one for each regions?
lib/efi_loader/efi_signature.c line 51
Quoted 5 lines
lib/efi_loader/efi_signature.c new file +5
-0+* +* Return: true on success, false on error +*/ +static bool efi_hash_regions (struct efi_image_regions *regs,void **hash, +size_t *size)Why use void** for hash? There should be a structure for SHA256 hashes.
Quoted 15 lines
lib/efi_loader/efi_signature.c line 63
Quoted 12 lines
lib/efi_loader/efi_signature.c new file +12
-0+{ + *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" );debug checks the value of
_DEBUGnot of DEBUG. So wouldn't you use #ifdef_DEBUGto be consistent?
It will be fixed once "common.h" (hence "log.h") is included.
Quoted 4 lines
lib/efi_loader/efi_signature.c line 65
Quoted 2 lines
lib/efi_loader/efi_signature.c new file +2
-0+print_hex_dump (" " ,DUMP_PREFIX_OFFSET ,16 ,1 , + *hash,SHA256_SUM_LEN , false);This will fail to compile if
CONFIG_HEXDUMPis not defined?
No. If CONFIG_HEXDUMP is not defined, print_hex_dump() will be nullified. See lib/hexdump.c.
Quoted 436 lines
Quoted 182 lines
lib/efi_loader/efi_signature.c new file +182
-0+#endif + +return true; +} + +/** +* efi_hash_regions_in_der - 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. +* This function is a variant of efi_hash_regions(), and the data will +* be wrapped with some header in DER format before hash calculation. +* Message digest in signature of PE format will be calculated this way. +* +* Return: true on success, false on error +*/ +static bool efi_hash_regions_in_der (struct efi_image_regions *regs,void **hash, +size_t *size) +{ +void *msg; +size_t msg_size; +struct image_region regtmp[2 ]; + +if (!efi_hash_regions (regs, &msg, &msg_size)) { +debug ("Hash calculation failed\n" ); +return false; + ; + } + + *size =0 ; + *hash =calloc (1 ,SHA256_SUM_LEN ); +if (!*hash) { +debug ("Out of memory\n" ); +free (msg); +return false; + } + *size =SHA256_SUM_LEN ; + +/* File image hash is digested with some DER wrapper. */ + regtmp[0 ].data = WinIndirectSha256; + regtmp[0 ].size =sizeof (WinIndirectSha256); + regtmp[1 ].data = msg; + regtmp[1 ].size = msg_size; + +hash_calculate ("sha256" , regtmp,2 , *hash); +#ifdef DEBUG +debug ("hash calculated with extra header:\n" ); +print_hex_dump (" " ,DUMP_PREFIX_OFFSET ,16 ,1 , + *hash,SHA256_SUM_LEN , false); +#endif + +free (msg); + +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_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 +if (efi_hash_regions_in_der (regs, &hash, &size)) { +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 +* @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,lib/efi_loader/efi_signature.c line 257
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-0+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);Shouldn't we use
EFI_PRINT()to get proper indentation?lib/efi_loader/efi_signature.c line 263
Quoted 6 lines
lib/efi_loader/efi_signature.c new file +6
-0+ +if (!signed_info) { +void *hash; +size_t size; + +debug ("%s: unsigned image\n" , __func__);We already have indicated the function above.
Quoted 12 lines
lib/efi_loader/efi_signature.c new file +12
-0+/* +* 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" );lib/efi_loader/efi_signature.c line 285
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-0+ 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);Does this compile if
CONFIG_HEXDUMPis not defined?Quoted 194 lines
lib/efi_loader/efi_signature.c new file +194
-0+#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, signed_info, cert); + +if (verified) { +if (valid_cert) + *valid_cert = cert; +else +x509_free_certificate (cert); +break ; + }else { +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 , + 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, 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". +* lib/efi_loader/efi_signature.c line 489
Quoted 10 lines
lib/efi_loader/efi_signature.c new file +10
-0+* 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);
EFI_PRINT()?
Quoted 10 lines
lib/efi_loader/efi_signature.c line 497
Quoted 8 lines
lib/efi_loader/efi_signature.c new file +8
-0+ +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 */ Is this a difficult thing to do? If not, please, fill the gap.
Actually, I have already implemented the prototype code
for revocation support. See my linaro repository described in the cover letter.
But I won't include relevant patches in this patch series because:
1. The basic authentication mechanism should be upstreamed first, yet it will provide enough function set.
2. Timestamp based revocation is quite complicated to understand. So excluding it makes your reviews easier.
3. I haven't seen no strong demands for revocation support at the moment.
Thanks,
-Takahiro Akashi
Quoted 109 lines
Best regards
Heinrich
Quoted 104 lines
lib/efi_loader/efi_signature.c new file +103
-0+ + 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 >=EFI_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 = ®s->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 (®s->reg[j], ®s->reg[j +1 ], +sizeof (*reg)); +break ; + } + } + + reg = ®s->reg[i]; + reg->data = start; + reg->size = end - start; + regs->num++; + +return EFI_SUCCESS ; +} +#endif /* CONFIG_EFI_SECURE_BOOT */
PATCH 5/16 efi_loader: add signature verification functions
Quoted 17 lines · AKASHI Takahiro
Quoted 3 lines
Quoted 1 line
+static const unsigned char WinIndirectSha256[] = {
We don't use camel case.
Okay, this one is a local variable. Fix it.
Quoted 10 lines
lib/efi_loader/efi_signature.c line 38
Quoted 7 lines
lib/efi_loader/efi_signature.c new file +7
-0+0x30 ,0x33 ,0x06 ,0x0a ,0x2b ,0x06 ,0x01 ,0x04 ,0x01 ,0x82 ,0x37 ,0x02 , +0x01 ,0x0f ,0x30 ,0x25 ,0x03 ,0x01 ,0x00 ,0xa0 ,0x20 ,0xa2 ,0x1e ,0x80 , +0x1c ,0x00 ,0x3c ,0x00 ,0x3c ,0x00 ,0x3c ,0x00 ,0x4f ,0x00 ,0x62 ,0x00 , +0x73 ,0x00 ,0x6f ,0x00 ,0x6c ,0x00 ,0x65 ,0x00 ,0x74 ,0x00 ,0x65 ,0x00 , +0x3e ,0x00 ,0x3e ,0x00 ,0x3e ,0x30 ,0x31 ,0x30 ,0x0d ,0x06 ,0x09 ,0x60 , +0x86 ,0x48 ,0x01 ,0x65 ,0x03 ,0x04 ,0x02 ,0x01 ,0x05 ,0x00 ,0x04 ,0x20 +};What secret sauce is this? - Please, add comments where applicable. Add references where needed for verification of correctness.
Quoted 2 lines
A similar technique is also used in EDK2. I will add "decoded" version of data in a comment.
I found that this header is already embedded in signature's contentInfo. So I will rework the code and remove this variable.
See some information about Windows authenticode's contentInfo:
http://download.microsoft.com/download/9/c/5/9c5b2167-8017-4bae-9fde-d599bac8184a/authenticode_pe.docx
and
https://github.com/rhboot/pesign/blob/master/src/content_info.c
Thanks,
-Takahiro Akashi
PATCH 6/16 efi_loader: add signature database parser
In reply to AKASHI Takahiroefi_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 | 227 +++++++++++++++++++++++++++++++++ 2 files changed, 230 insertions(+)
include/efi_loader.h +3 -0
@@ -694,6 +694,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 +227 -0
231 lines not on this page · raw message
Signature · 1 line
2.21.0
PATCH 7/16 efi_loader: variable: support variable authentication
In reply to AKASHI TakahiroWith 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 | 664 ++++++++++++++++++++++++++++------ 2 files changed, 563 insertions(+), 104 deletions(-)
include/efi_loader.h +3 -0
@@ -175,6 +175,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;extern unsigned int __efi_runtime_start, __efi_runtime_stop;extern unsigned int __efi_runtime_rel_start, __efi_runtime_rel_stop;
@@ -697,6 +698,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 +560 -104
830 lines not on this page · raw message
Signature · 1 line
2.21.0
PATCH 7/16 efi_loader: variable: support variable authentication
Quoted 5 lines · AKASHI Takahiro
With this commit,
EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESSis supported for authenticated variables and the system secure state will transfer between setup mode and user mode as UEFI specification section 32.3 describes.
Quoted 7 lines
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 byefi_variable_authenticate(), henceefi_signature_verify_with_db().Associated time value will be encoded in "{...,time=...}" along with other UEFI variable's attributes.
Please, provide a unit test testing this single feature.
Best regards
Heinrich
Quoted 875 lines
Signed-off-by AKASHI Takahiro <[email protected]>--- include/efi_loader.h | 3 + lib/efi_loader/efi_variable.c | 664 ++++++++++++++++++++++++++++------ 2 files changed, 563 insertions(+), 104 deletions(-)include/efi_loader.h +3
-0@@ -175,6 +175,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;extern unsigned int __efi_runtime_start, __efi_runtime_stop;extern unsigned int __efi_runtime_rel_start, __efi_runtime_rel_stop;@@ -697,6 +698,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 +560
-104@@ -10,7 +10,13 @@#include <env_internal.h> #include <hexdump.h> #include <malloc.h> +#include <rtc.h> #include <search.h> +#include <linux/compat.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)@@ -107,7 +113,7 @@ static const char *prefix(const char *str, const char *prefix)* @attrp: pointer to UEFI attributes * 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 ='{' ;@@ -130,6 +136,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 ;@@ -147,48 +159,290 @@ 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) +{ +u8 *ebuf; +size_t ebuflen, len; +struct pkcs7_message *msg; + +/* +* This is the best assumption to check if the binary is +* already in a form of pkcs7's signedData. +*/ +if (buflen >sizeof (pkcs7_hdr) && + !memcmp (&((u8 *)buf)[4 ], &pkcs7_hdr[4 ],11 )) { + msg =pkcs7_parse_message (buf, buflen); + goto out; + } + +/* +* Otherwise, we should add a dummy prefix sequence for pkcs7 +* message parser to be able to process. +* NOTE: EDK2 also uses similar hack in WrapPkcs7Data() +* in CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c +* TODO: +* The header should be composed in a more refined manner. +*/ +debug ("Makeshift prefix added to authentication data\n" ); + ebuflen =sizeof (pkcs7_hdr) + buflen; +if (ebuflen <=0x7f ) { +debug ("Data is too short\n" ); +return NULL ; + } + + ebuf =malloc (ebuflen); +if (!ebuf) { +debug ("Out of memory\n" ); +return NULL ; + } + +memcpy (ebuf, pkcs7_hdr,sizeof (pkcs7_hdr)); +memcpy (ebuf +sizeof (pkcs7_hdr), buf, buflen); + len = ebuflen -4 ; + ebuf[2 ] = (len >>8 ) &0xff ; + ebuf[3 ] = len &0xff ; + len = ebuflen -0x13 ; + ebuf[0x11 ] = (len >>8 ) &0xff ; + ebuf[0x12 ] = len &0xff ; + + msg =pkcs7_parse_message (ebuf, ebuflen); + +free (ebuf); + +out: +if (IS_ERR (msg)) +return NULL ; + +return msg; +} + +/** +* efi_variable_authenticate - authenticate a variable +* @variable: Variable name in u16 +* @vendor: Guid of variable +* @data_size: Size of @data +* @data: Pointer to variable's value +* @given_attr: Attributes to be given at SetVariable() +* @env_attr: Attributes that an existing variable holds +* @time: signed time that an existing variable holds +* +* Called by efi_set_variable() to verify that the input is correct. +* Will replace the given data pointer with another that points to +* the actual data to store in the internal memory. +* On success, @data and @data_size will be replaced with variable's +* actual data, excluding authentication data, and its size, and variable's +* attributes and signed time will also be returned in @env_attr and @time, +* respectively. +* +* Return: EFI_SUCCESS on success, status code (negative) on error +*/ +static efi_status_t efi_variable_authenticate (u16 *variable, +const efi_guid_t *vendor, +efi_uintn_t *data_size, +const void **data,u32 given_attr, +u32 *env_attr,u64 *time) +{ +const struct efi_variable_authentication_2 *auth; +struct efi_signature_store *truststore, *truststore2; +struct pkcs7_message *var_sig; +struct efi_image_regions *regs; +const struct efi_time *timestamp; +struct rtc_time tm; +u64 new_time; +efi_status_t ret; + + var_sig =NULL ; + truststore =NULL ; + truststore2 =NULL ; + regs =NULL ; + ret =EFI_SECURITY_VIOLATION ; + +if (*data_size <sizeof (struct efi_variable_authentication_2 )) + goto err; + +/* authentication data */ + auth = *data; +if (*data_size < (sizeof (auth->time_stamp) + + auth->auth_info.hdr.dwLength)) + goto err; + +if (guidcmp (&auth->auth_info.cert_type, &efi_guid_cert_type_pkcs7)) + goto err; + + *data +=sizeof (auth->time_stamp) + auth->auth_info.hdr.dwLength; + *data_size -= (sizeof (auth->time_stamp) + + auth->auth_info.hdr.dwLength); + + timestamp = &auth->time_stamp; +memset (&tm,0 ,sizeof (tm)); + tm.tm_year = timestamp->year; + tm.tm_mon = timestamp->month; + tm.tm_mday = timestamp->day; + tm.tm_hour = timestamp->hour; + tm.tm_min = timestamp->minute; + tm.tm_sec = timestamp->second; + new_time =rtc_mktime (&tm); + +if (!efi_secure_boot_enabled ()) { +/* finished checking */ + *time = new_time; +return EFI_SUCCESS ; + } + +if (new_time <= *time) + goto err; + +/* data to be digested */ + regs =calloc (1 ,sizeof (*regs)); +if (!regs) + goto err; +efi_image_region_add (regs, (uint8_t *)variable, + (uint8_t *)variable + +u16_strlen (variable) *sizeof (u16),1 ); +efi_image_region_add (regs, (uint8_t *)vendor, + (uint8_t *)vendor +sizeof (*vendor),1 ); +efi_image_region_add (regs, (uint8_t *)&given_attr, + (uint8_t *)&given_attr +sizeof (given_attr),1 ); +efi_image_region_add (regs, (uint8_t *)timestamp, + (uint8_t *)timestamp +sizeof (*timestamp),1 ); +efi_image_region_add (regs, (uint8_t *)*data, + (uint8_t *)*data + *data_size,1 ); + +/* variable's signature list */ +if (auth->auth_info.hdr.dwLength <sizeof (auth->auth_info)) + goto err; + var_sig =efi_variable_parse_signature (auth->auth_info.cert_data, + auth->auth_info.hdr.dwLength + -sizeof (auth->auth_info)); +if (IS_ERR (var_sig)) { +debug ("Parsing variable's signature failed\n" ); + var_sig =NULL ; + goto err; + } + +/* signature database used for authentication */ +if (u16_strcmp (variable,L"PK" ) ==0 || +u16_strcmp (variable,L"KEK" ) ==0 ) { +/* with PK */ + truststore =efi_sigstore_parse_sigdb (L"PK" ); +if (!truststore) + goto err; + }else if (u16_strcmp (variable,L"db" ) ==0 || +u16_strcmp (variable,L"dbx" ) ==0 ) { +/* with PK and KEK */ + truststore =efi_sigstore_parse_sigdb (L"KEK" ); + truststore2 =efi_sigstore_parse_sigdb (L"PK" ); + +if (!truststore) { +if (!truststore2) + goto err; + + truststore = truststore2; + truststore2 =NULL ; + } + }else { +/* TODO: support private authenticated variables */ + goto err; + } + +/* verify signature */ +if (efi_signature_verify_with_sigdb (regs, var_sig, truststore,NULL )) { +debug ("Verified\n" ); + }else { +if (truststore2 && +efi_signature_verify_with_sigdb (regs, var_sig, + truststore2,NULL )) { +debug ("Verified\n" ); + }else { +debug ("Verifying variable's signature failed\n" ); + goto err; + } + } + +/* finished checking */ + *time =rtc_mktime (&tm); + ret =EFI_SUCCESS ; + +err: +efi_sigstore_free (truststore); +efi_sigstore_free (truststore2); +pkcs7_free_message (var_sig); +free (regs); + +return ret; +} +#else +static efi_status_t efi_variable_authenticate (u16 *variable, +const efi_guid_t *vendor, +efi_uintn_t *data_size, +const void **data,u32 given_attr, +u32 *env_attr,u64 *time) +{ +return EFI_SUCCESS ; +} +#endif /* CONFIG_EFI_SECURE_BOOT */ + +static +efi_status_t EFIAPI efi_get_variable_common(u16 *variable_name, +const efi_guid_t *vendor, +u32 *attributes, +efi_uintn_t *data_size,void *data, +bool is_non_volatile) {char *native_name;efi_status_t ret;unsigned long in_size; -const char *val, *s; +const char *val =NULL , *s; +u64 time =0 ;u32 attr; -EFI_ENTRY ("\"%ls\" %pUl %p %p %p" , variable_name, vendor, attributes, - data_size, data); -if (!variable_name || !vendor || !data_size)return EFI_EXIT (EFI_INVALID_PARAMETER ); ret =efi_to_native (&native_name, variable_name, vendor);if (ret) -return EFI_EXIT (ret); +return ret;EFI_PRINT ("get '%s'\n" , native_name); val =env_get (native_name);free (native_name);if (!val) -return EFI_EXIT (EFI_NOT_FOUND ); +return EFI_NOT_FOUND ; - val =parse_attr (val, &attr); + val =parse_attr (val, &attr, &time); in_size = *data_size;@@ -197,7 +451,7 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name,/* number of hexadecimal digits must be even */ if (len &1 ) -return EFI_EXIT (EFI_DEVICE_ERROR ); +return EFI_DEVICE_ERROR ;/* two characters per byte: */ len /=2 ;@@ -208,11 +462,13 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name, goto out; } -if (!data) -return EFI_EXIT (EFI_INVALID_PARAMETER ); +if (!data) { +debug ("Variable with no data shouldn't exist.\n" ); +return EFI_INVALID_PARAMETER ; + }if (hex2bin (data, s, len)) -return EFI_EXIT (EFI_DEVICE_ERROR ); +return EFI_DEVICE_ERROR ;EFI_PRINT ("got value: \"%s\"\n" , s); }else if ((s =prefix (val,"(utf8)" ))) {@@ -225,8 +481,10 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name, goto out; } -if (!data) -return EFI_EXIT (EFI_INVALID_PARAMETER ); +if (!data) { +debug ("Variable with no data shouldn't exist.\n" ); +return EFI_INVALID_PARAMETER ; + }memcpy (data, s, len); ((char *)data)[len] ='\0' ;@@ -234,13 +492,67 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name,EFI_PRINT ("got value: \"%s\"\n" , (char *)data); }else {EFI_PRINT ("invalid value: '%s'\n" , val); -return EFI_EXIT (EFI_DEVICE_ERROR ); +return EFI_DEVICE_ERROR ; } out:if (attributes) *attributes = attr &EFI_VARIABLE_MASK ; +return ret; +} + +static +efi_status_t EFIAPI efi_get_volatile_variable(u16 *variable_name, +const efi_guid_t *vendor, +u32 *attributes, +efi_uintn_t *data_size, +void *data) +{ +return efi_get_variable_common (variable_name, vendor, attributes, + data_size, data, false); +} + +efi_status_t EFIAPI efi_get_nonvolatile_variable(u16 *variable_name, +const efi_guid_t *vendor, +u32 *attributes, +efi_uintn_t *data_size, +void *data) +{ +return efi_get_variable_common (variable_name, vendor, attributes, + data_size, data, true); +} + +/** +* efi_efi_get_variable() - retrieve value of a UEFI variable +* +* This function implements the GetVariable runtime service. +* +* See the Unified Extensible Firmware Interface (UEFI) specification for +* details. +* +* @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 +*/ +efi_status_t EFIAPI efi_get_variable(u16 *variable_name, +const efi_guid_t *vendor,u32 *attributes, +efi_uintn_t *data_size,void *data) +{ +efi_status_t ret; + +EFI_ENTRY ("\"%ls\" %pUl %p %p %p" , variable_name, vendor, attributes, + data_size, data); + + ret =efi_get_volatile_variable (variable_name, vendor, attributes, + data_size, data); +if (ret ==EFI_NOT_FOUND ) + ret =efi_get_nonvolatile_variable (variable_name, vendor, + attributes, data_size, data); +return EFI_EXIT (ret); }@@ -273,6 +585,7 @@ static efi_status_t parse_uboot_variable(char *variable, {char *guid, *name, *end, c;unsigned long name_len; +u64 time;u16 *p; guid =strchr (variable,'_' );@@ -307,7 +620,7 @@ static efi_status_t parse_uboot_variable(char *variable, *(name -1 ) = c;/* attributes */ -parse_attr (end, attributes); +parse_attr (end, attributes, &time);return EFI_SUCCESS ; }@@ -389,7 +702,7 @@ efi_status_t EFIAPI efi_get_next_variable_name(efi_uintn_t *variable_name_size, list_len =hexport_r (&env_htab,'\n' ,H_MATCH_REGEX |H_MATCH_KEY , &efi_variables_list,0 ,1 , regexlist); -/* 1 indicates that no match was found */ +if (list_len <=1 )return EFI_EXIT (EFI_NOT_FOUND );@@ -402,143 +715,286 @@ efi_status_t EFIAPI efi_get_next_variable_name(efi_uintn_t *variable_name_size,return EFI_EXIT (ret); } -/** -* efi_set_variable() - set value of a UEFI variable -* -* This function implements the SetVariable runtime service. -* -* See the Unified Extensible Firmware Interface (UEFI) specification for -* details. -* -* @variable_name: name of the variable -* @vendor: vendor GUID -* @attributes: attributes of the variable -* @data_size: size of the buffer with the variable value -* @data: buffer with the variable value -* Return: status code -*/ -efi_status_t EFIAPI efi_set_variable(u16 *variable_name, -const efi_guid_t *vendor,u32 attributes, -efi_uintn_t data_size,const void *data) +static +efi_status_t EFIAPI efi_set_variable_common(u16 *variable_name, +const efi_guid_t *vendor, +u32 attributes, +efi_uintn_t data_size, +const void *data, +bool ro_check, +bool is_non_volatile) { -char *native_name =NULL , *val =NULL , *s; -const char *old_val; -size_t old_size; -efi_status_t ret =EFI_SUCCESS ; +char *native_name =NULL , *old_data =NULL , *val =NULL , *s; +efi_uintn_t old_size; +bool append, delete; +u64 time =0 ;u32 attr; +efi_status_t ret =EFI_SUCCESS ; -EFI_ENTRY ("\"%ls\" %pUl %x %zu %p" , variable_name, vendor, attributes, - data_size, data); +debug ("%s: set '%s'\n" , __func__, native_name);if (!variable_name || !*variable_name || !vendor || ((attributes &EFI_VARIABLE_RUNTIME_ACCESS ) && !(attributes &EFI_VARIABLE_BOOTSERVICE_ACCESS ))) { ret =EFI_INVALID_PARAMETER ; - goto out; + goto err; } ret =efi_to_native (&native_name, variable_name, vendor);if (ret) - goto out; + goto err; + +/* check if a variable exists */ + old_size =0 ; + attr =0 ; + ret =EFI_CALL (efi_get_variable (variable_name, vendor, &attr, + &old_size,NULL )); +if (ret ==EFI_BUFFER_TOO_SMALL ) { +if ((is_non_volatile && !(attr &EFI_VARIABLE_NON_VOLATILE )) || + (!is_non_volatile && (attr &EFI_VARIABLE_NON_VOLATILE ))) { + ret =EFI_INVALID_PARAMETER ; + goto err; + } + } - old_val =env_get (native_name); -if (old_val) { - old_val =parse_attr (old_val, &attr); + append = !!(attributes &EFI_VARIABLE_APPEND_WRITE ); + attributes &= ~(u32 )EFI_VARIABLE_APPEND_WRITE ; + delete = !append && (!data_size || !attributes); -/* check read-only first */ -if (attr &READ_ONLY ) { +/* check attributes */ +if (old_size) { +if (ro_check && (attr &READ_ONLY )) { ret =EFI_WRITE_PROTECTED ; - goto out; - } - -if ((data_size ==0 && - !(attributes &EFI_VARIABLE_APPEND_WRITE )) || - !attributes) { -/* delete the variable: */ -env_set (native_name,NULL ); - ret =EFI_SUCCESS ; - goto out; + goto err; }/* attributes won't be changed */ -if (attr != (attributes & ~EFI_VARIABLE_APPEND_WRITE )) { +if (!delete && + ((ro_check && attr != attributes) || + (!ro_check && ((attr & ~(u32 )READ_ONLY ) + != (attributes & ~(u32 )READ_ONLY ))))) { ret =EFI_INVALID_PARAMETER ; - goto out; - } - -if (attributes &EFI_VARIABLE_APPEND_WRITE ) { -if (!prefix (old_val,"(blob)" )) { - ret =EFI_DEVICE_ERROR ; - goto out; - } - old_size =strlen (old_val); - }else { - old_size =0 ; + goto err; } }else { -if (data_size ==0 || !attributes || - (attributes &EFI_VARIABLE_APPEND_WRITE )) { +if (delete || append) {/* * Trying to delete or to update a non-existent * variable. */ ret =EFI_NOT_FOUND ; - goto out; + goto err; + } + } + +if (((!u16_strcmp (variable_name,L"PK" ) || + !u16_strcmp (variable_name,L"KEK" )) && + !guidcmp (vendor, &efi_global_variable_guid)) || + ((!u16_strcmp (variable_name,L"db" ) || + !u16_strcmp (variable_name,L"dbx" )) && + !guidcmp (vendor, &efi_guid_image_security_database))) { +/* authentication is mandatory */ +if (!(attributes & +EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS )) { +debug ("%ls: AUTHENTICATED_WRITE_ACCESS required\n" , + variable_name); + ret =EFI_INVALID_PARAMETER ; + goto err; } + } + +/* authenticate a variable */ +if (IS_ENABLED (CONFIG_EFI_SECURE_BOOT )) { +if (attributes &EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS ) { + ret =EFI_INVALID_PARAMETER ; + goto err; + } +if (attributes & +EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS ) { + ret =efi_variable_authenticate (variable_name, vendor, + &data_size, &data, + attributes, &attr, + &time); +if (ret !=EFI_SUCCESS ) + goto err; + +/* last chance to check for delete */ +if (!data_size) + delete = true; + } + }else { +if (attributes & + (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | +EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS )) { +debug ("Secure boot is not configured\n" ); + ret =EFI_INVALID_PARAMETER ; + goto err; + } + } + +/* delete a variable */ +if (delete) { +/* !old_size case has been handled before */ + val =NULL ; + ret =EFI_SUCCESS ; + goto out; + } +if (append) { + old_data =malloc (old_size); +if (!old_data) { +return EFI_OUT_OF_RESOURCES ; + goto err; + } + ret =EFI_CALL (efi_get_variable (variable_name, vendor, + &attr, &old_size, old_data)); +if (ret !=EFI_SUCCESS ) + goto err; + }else { old_size =0 ; } - val =malloc (old_size +2 * data_size - +strlen ("{ro,run,boot,nv}(blob)" ) +1 ); + val =malloc (2 * old_size +2 * data_size + +strlen ("{ro,run,boot,nv,time=0123456701234567}(blob)" ) + +1 );if (!val) { ret =EFI_OUT_OF_RESOURCES ; - goto out; + goto err; } s = val; -/* store attributes */ - attributes &= (EFI_VARIABLE_NON_VOLATILE | +/* +* store attributes +*/ + attributes &= (READ_ONLY | +EFI_VARIABLE_NON_VOLATILE |EFI_VARIABLE_BOOTSERVICE_ACCESS | -EFI_VARIABLE_RUNTIME_ACCESS ); +EFI_VARIABLE_RUNTIME_ACCESS | +EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS ); s +=sprintf (s,"{" );while (attributes) { -u32 attr =1 << (ffs (attributes) -1 ); + attr =1 << (ffs (attributes) -1 ); -if (attr ==EFI_VARIABLE_NON_VOLATILE ) +if (attr ==READ_ONLY ) { + s +=sprintf (s,"ro" ); + }else if (attr ==EFI_VARIABLE_NON_VOLATILE ) { s +=sprintf (s,"nv" ); -else if (attr ==EFI_VARIABLE_BOOTSERVICE_ACCESS ) + }else if (attr ==EFI_VARIABLE_BOOTSERVICE_ACCESS ) { s +=sprintf (s,"boot" ); -else if (attr ==EFI_VARIABLE_RUNTIME_ACCESS ) + }else if (attr ==EFI_VARIABLE_RUNTIME_ACCESS ) { s +=sprintf (s,"run" ); + }else if (attr == +EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS ) { + s +=sprintf (s,"time=" ); + s =bin2hex (s, (u8 *)&time,sizeof (time)); + } attributes &= ~attr;if (attributes) s +=sprintf (s,"," ); } s +=sprintf (s,"}" ); - -if (old_size) -/* APPEND_WRITE */ - s +=sprintf (s, old_val); -else - s +=sprintf (s,"(blob)" ); + s +=sprintf (s,"(blob)" );/* store payload: */ +if (append) + s =bin2hex (s, old_data, old_size); s =bin2hex (s, data, data_size); *s ='\0' ;EFI_PRINT ("setting: %s=%s\n" , native_name, val); +out:if (env_set (native_name, val)) ret =EFI_DEVICE_ERROR ; +else + ret =EFI_SUCCESS ; -out: +err:free (native_name); +free (old_data);free (val); -return EFI_EXIT (ret); +return ret; +} + +static +efi_status_t EFIAPI efi_set_volatile_variable(u16 *variable_name, +const efi_guid_t *vendor, +u32 attributes, +efi_uintn_t data_size, +const void *data, +bool ro_check) +{ +return efi_set_variable_common (variable_name, vendor, attributes, + data_size, data, ro_check, false); +} + +efi_status_t EFIAPI efi_set_nonvolatile_variable(u16 *variable_name, +const efi_guid_t *vendor, +u32 attributes, +efi_uintn_t data_size, +const void *data, +bool ro_check) +{ +efi_status_t ret; + + ret =efi_set_variable_common (variable_name, vendor, attributes, + data_size, data, ro_check, true); + +return ret; +} + +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_status_t ret; + +if (attributes &EFI_VARIABLE_NON_VOLATILE ) + ret =efi_set_nonvolatile_variable (variable_name, vendor, + attributes, + data_size, data, ro_check); +else + ret =efi_set_volatile_variable (variable_name, vendor, + attributes, data_size, data, + ro_check); + +return ret; +} + +/** +* efi_set_variable() - set value of a UEFI variable +* +* This function implements the SetVariable runtime service. +* +* See the Unified Extensible Firmware Interface (UEFI) specification for +* details. +* +* @variable_name: name of the variable +* @vendor: vendor GUID +* @attributes: attributes of the variable +* @data_size: size of the buffer with the variable value +* @data: buffer with the variable value +* Return: status code +*/ +efi_status_t EFIAPI efi_set_variable(u16 *variable_name, +const efi_guid_t *vendor,u32 attributes, +efi_uintn_t data_size,const void *data) +{ +EFI_ENTRY ("\"%ls\" %pUl %x %zu %p" , variable_name, vendor, attributes, + data_size, data); + +/* READ_ONLY bit is not part of API */ + attributes &= ~(u32 )READ_ONLY ; + +return EFI_EXIT (efi_set_variable_internal (variable_name, vendor, + attributes, data_size, data, + true)); }/**
PATCH 7/16 efi_loader: variable: support variable authentication
Quoted 11 lines · Heinrich Schuchardt
Quoted 10 lines · AKASHI Takahiro
With this commit,
EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESSis 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 byefi_variable_authenticate(), henceefi_signature_verify_with_db().
Quoted 4 lines
Quoted 2 lines
Associated time value will be encoded in "{...,time=...}" along with other UEFI variable's attributes.
Please, provide a unit test testing this single feature.
My test_efi_secboot/test_authvar.py provides various test cases. Pytest is much better solution than "ut" command in terms of flexible test scenario (and due to complexed setup).
-Takahiro Akashi
Quoted 880 lines
Best regards
Heinrich
Quoted 875 lines
Signed-off-by AKASHI Takahiro <[email protected]>--- include/efi_loader.h | 3 + lib/efi_loader/efi_variable.c | 664 ++++++++++++++++++++++++++++------ 2 files changed, 563 insertions(+), 104 deletions(-)include/efi_loader.h +3
-0@@ -175,6 +175,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;extern unsigned int __efi_runtime_start, __efi_runtime_stop;extern unsigned int __efi_runtime_rel_start, __efi_runtime_rel_stop;@@ -697,6 +698,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 +560
-104@@ -10,7 +10,13 @@#include <env_internal.h> #include <hexdump.h> #include <malloc.h> +#include <rtc.h> #include <search.h> +#include <linux/compat.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)@@ -107,7 +113,7 @@ static const char *prefix(const char *str, const char *prefix)* @attrp: pointer to UEFI attributes * 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 ='{' ;@@ -130,6 +136,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 ;@@ -147,48 +159,290 @@ 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) +{ +u8 *ebuf; +size_t ebuflen, len; +struct pkcs7_message *msg; + +/* +* This is the best assumption to check if the binary is +* already in a form of pkcs7's signedData. +*/ +if (buflen >sizeof (pkcs7_hdr) && + !memcmp (&((u8 *)buf)[4 ], &pkcs7_hdr[4 ],11 )) { + msg =pkcs7_parse_message (buf, buflen); + goto out; + } + +/* +* Otherwise, we should add a dummy prefix sequence for pkcs7 +* message parser to be able to process. +* NOTE: EDK2 also uses similar hack in WrapPkcs7Data() +* in CryptoPkg/Library/BaseCryptLib/Pk/CryptPkcs7VerifyCommon.c +* TODO: +* The header should be composed in a more refined manner. +*/ +debug ("Makeshift prefix added to authentication data\n" ); + ebuflen =sizeof (pkcs7_hdr) + buflen; +if (ebuflen <=0x7f ) { +debug ("Data is too short\n" ); +return NULL ; + } + + ebuf =malloc (ebuflen); +if (!ebuf) { +debug ("Out of memory\n" ); +return NULL ; + } + +memcpy (ebuf, pkcs7_hdr,sizeof (pkcs7_hdr)); +memcpy (ebuf +sizeof (pkcs7_hdr), buf, buflen); + len = ebuflen -4 ; + ebuf[2 ] = (len >>8 ) &0xff ; + ebuf[3 ] = len &0xff ; + len = ebuflen -0x13 ; + ebuf[0x11 ] = (len >>8 ) &0xff ; + ebuf[0x12 ] = len &0xff ; + + msg =pkcs7_parse_message (ebuf, ebuflen); + +free (ebuf); + +out: +if (IS_ERR (msg)) +return NULL ; + +return msg; +} + +/** +* efi_variable_authenticate - authenticate a variable +* @variable: Variable name in u16 +* @vendor: Guid of variable +* @data_size: Size of @data +* @data: Pointer to variable's value +* @given_attr: Attributes to be given at SetVariable() +* @env_attr: Attributes that an existing variable holds +* @time: signed time that an existing variable holds +* +* Called by efi_set_variable() to verify that the input is correct. +* Will replace the given data pointer with another that points to +* the actual data to store in the internal memory. +* On success, @data and @data_size will be replaced with variable's +* actual data, excluding authentication data, and its size, and variable's +* attributes and signed time will also be returned in @env_attr and @time, +* respectively. +* +* Return: EFI_SUCCESS on success, status code (negative) on error +*/ +static efi_status_t efi_variable_authenticate (u16 *variable, +const efi_guid_t *vendor, +efi_uintn_t *data_size, +const void **data,u32 given_attr, +u32 *env_attr,u64 *time) +{ +const struct efi_variable_authentication_2 *auth; +struct efi_signature_store *truststore, *truststore2; +struct pkcs7_message *var_sig; +struct efi_image_regions *regs; +const struct efi_time *timestamp; +struct rtc_time tm; +u64 new_time; +efi_status_t ret; + + var_sig =NULL ; + truststore =NULL ; + truststore2 =NULL ; + regs =NULL ; + ret =EFI_SECURITY_VIOLATION ; + +if (*data_size <sizeof (struct efi_variable_authentication_2 )) + goto err; + +/* authentication data */ + auth = *data; +if (*data_size < (sizeof (auth->time_stamp) + + auth->auth_info.hdr.dwLength)) + goto err; + +if (guidcmp (&auth->auth_info.cert_type, &efi_guid_cert_type_pkcs7)) + goto err; + + *data +=sizeof (auth->time_stamp) + auth->auth_info.hdr.dwLength; + *data_size -= (sizeof (auth->time_stamp) + + auth->auth_info.hdr.dwLength); + + timestamp = &auth->time_stamp; +memset (&tm,0 ,sizeof (tm)); + tm.tm_year = timestamp->year; + tm.tm_mon = timestamp->month; + tm.tm_mday = timestamp->day; + tm.tm_hour = timestamp->hour; + tm.tm_min = timestamp->minute; + tm.tm_sec = timestamp->second; + new_time =rtc_mktime (&tm); + +if (!efi_secure_boot_enabled ()) { +/* finished checking */ + *time = new_time; +return EFI_SUCCESS ; + } + +if (new_time <= *time) + goto err; + +/* data to be digested */ + regs =calloc (1 ,sizeof (*regs)); +if (!regs) + goto err; +efi_image_region_add (regs, (uint8_t *)variable, + (uint8_t *)variable + +u16_strlen (variable) *sizeof (u16),1 ); +efi_image_region_add (regs, (uint8_t *)vendor, + (uint8_t *)vendor +sizeof (*vendor),1 ); +efi_image_region_add (regs, (uint8_t *)&given_attr, + (uint8_t *)&given_attr +sizeof (given_attr),1 ); +efi_image_region_add (regs, (uint8_t *)timestamp, + (uint8_t *)timestamp +sizeof (*timestamp),1 ); +efi_image_region_add (regs, (uint8_t *)*data, + (uint8_t *)*data + *data_size,1 ); + +/* variable's signature list */ +if (auth->auth_info.hdr.dwLength <sizeof (auth->auth_info)) + goto err; + var_sig =efi_variable_parse_signature (auth->auth_info.cert_data, + auth->auth_info.hdr.dwLength + -sizeof (auth->auth_info)); +if (IS_ERR (var_sig)) { +debug ("Parsing variable's signature failed\n" ); + var_sig =NULL ; + goto err; + } + +/* signature database used for authentication */ +if (u16_strcmp (variable,L"PK" ) ==0 || +u16_strcmp (variable,L"KEK" ) ==0 ) { +/* with PK */ + truststore =efi_sigstore_parse_sigdb (L"PK" ); +if (!truststore) + goto err; + }else if (u16_strcmp (variable,L"db" ) ==0 || +u16_strcmp (variable,L"dbx" ) ==0 ) { +/* with PK and KEK */ + truststore =efi_sigstore_parse_sigdb (L"KEK" ); + truststore2 =efi_sigstore_parse_sigdb (L"PK" ); + +if (!truststore) { +if (!truststore2) + goto err; + + truststore = truststore2; + truststore2 =NULL ; + } + }else { +/* TODO: support private authenticated variables */ + goto err; + } + +/* verify signature */ +if (efi_signature_verify_with_sigdb (regs, var_sig, truststore,NULL )) { +debug ("Verified\n" ); + }else { +if (truststore2 && +efi_signature_verify_with_sigdb (regs, var_sig, + truststore2,NULL )) { +debug ("Verified\n" ); + }else { +debug ("Verifying variable's signature failed\n" ); + goto err; + } + } + +/* finished checking */ + *time =rtc_mktime (&tm); + ret =EFI_SUCCESS ; + +err: +efi_sigstore_free (truststore); +efi_sigstore_free (truststore2); +pkcs7_free_message (var_sig); +free (regs); + +return ret; +} +#else +static efi_status_t efi_variable_authenticate (u16 *variable, +const efi_guid_t *vendor, +efi_uintn_t *data_size, +const void **data,u32 given_attr, +u32 *env_attr,u64 *time) +{ +return EFI_SUCCESS ; +} +#endif /* CONFIG_EFI_SECURE_BOOT */ + +static +efi_status_t EFIAPI efi_get_variable_common(u16 *variable_name, +const efi_guid_t *vendor, +u32 *attributes, +efi_uintn_t *data_size,void *data, +bool is_non_volatile) {char *native_name;efi_status_t ret;unsigned long in_size; -const char *val, *s; +const char *val =NULL , *s; +u64 time =0 ;u32 attr; -EFI_ENTRY ("\"%ls\" %pUl %p %p %p" , variable_name, vendor, attributes, - data_size, data); -if (!variable_name || !vendor || !data_size)return EFI_EXIT (EFI_INVALID_PARAMETER ); ret =efi_to_native (&native_name, variable_name, vendor);if (ret) -return EFI_EXIT (ret); +return ret;EFI_PRINT ("get '%s'\n" , native_name); val =env_get (native_name);free (native_name);if (!val) -return EFI_EXIT (EFI_NOT_FOUND ); +return EFI_NOT_FOUND ; - val =parse_attr (val, &attr); + val =parse_attr (val, &attr, &time); in_size = *data_size;@@ -197,7 +451,7 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name,/* number of hexadecimal digits must be even */ if (len &1 ) -return EFI_EXIT (EFI_DEVICE_ERROR ); +return EFI_DEVICE_ERROR ;/* two characters per byte: */ len /=2 ;@@ -208,11 +462,13 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name, goto out; } -if (!data) -return EFI_EXIT (EFI_INVALID_PARAMETER ); +if (!data) { +debug ("Variable with no data shouldn't exist.\n" ); +return EFI_INVALID_PARAMETER ; + }if (hex2bin (data, s, len)) -return EFI_EXIT (EFI_DEVICE_ERROR ); +return EFI_DEVICE_ERROR ;EFI_PRINT ("got value: \"%s\"\n" , s); }else if ((s =prefix (val,"(utf8)" ))) {@@ -225,8 +481,10 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name, goto out; } -if (!data) -return EFI_EXIT (EFI_INVALID_PARAMETER ); +if (!data) { +debug ("Variable with no data shouldn't exist.\n" ); +return EFI_INVALID_PARAMETER ; + }memcpy (data, s, len); ((char *)data)[len] ='\0' ;@@ -234,13 +492,67 @@ efi_status_t EFIAPI efi_get_variable(u16 *variable_name,EFI_PRINT ("got value: \"%s\"\n" , (char *)data); }else {EFI_PRINT ("invalid value: '%s'\n" , val); -return EFI_EXIT (EFI_DEVICE_ERROR ); +return EFI_DEVICE_ERROR ; } out:if (attributes) *attributes = attr &EFI_VARIABLE_MASK ; +return ret; +} + +static +efi_status_t EFIAPI efi_get_volatile_variable(u16 *variable_name, +const efi_guid_t *vendor, +u32 *attributes, +efi_uintn_t *data_size, +void *data) +{ +return efi_get_variable_common (variable_name, vendor, attributes, + data_size, data, false); +} + +efi_status_t EFIAPI efi_get_nonvolatile_variable(u16 *variable_name, +const efi_guid_t *vendor, +u32 *attributes, +efi_uintn_t *data_size, +void *data) +{ +return efi_get_variable_common (variable_name, vendor, attributes, + data_size, data, true); +} + +/** +* efi_efi_get_variable() - retrieve value of a UEFI variable +* +* This function implements the GetVariable runtime service. +* +* See the Unified Extensible Firmware Interface (UEFI) specification for +* details. +* +* @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 +*/ +efi_status_t EFIAPI efi_get_variable(u16 *variable_name, +const efi_guid_t *vendor,u32 *attributes, +efi_uintn_t *data_size,void *data) +{ +efi_status_t ret; + +EFI_ENTRY ("\"%ls\" %pUl %p %p %p" , variable_name, vendor, attributes, + data_size, data); + + ret =efi_get_volatile_variable (variable_name, vendor, attributes, + data_size, data); +if (ret ==EFI_NOT_FOUND ) + ret =efi_get_nonvolatile_variable (variable_name, vendor, + attributes, data_size, data); +return EFI_EXIT (ret); }@@ -273,6 +585,7 @@ static efi_status_t parse_uboot_variable(char *variable, {char *guid, *name, *end, c;unsigned long name_len; +u64 time;u16 *p; guid =strchr (variable,'_' );@@ -307,7 +620,7 @@ static efi_status_t parse_uboot_variable(char *variable, *(name -1 ) = c;/* attributes */ -parse_attr (end, attributes); +parse_attr (end, attributes, &time);return EFI_SUCCESS ; }@@ -389,7 +702,7 @@ efi_status_t EFIAPI efi_get_next_variable_name(efi_uintn_t *variable_name_size, list_len =hexport_r (&env_htab,'\n' ,H_MATCH_REGEX |H_MATCH_KEY , &efi_variables_list,0 ,1 , regexlist); -/* 1 indicates that no match was found */ +if (list_len <=1 )return EFI_EXIT (EFI_NOT_FOUND );@@ -402,143 +715,286 @@ efi_status_t EFIAPI efi_get_next_variable_name(efi_uintn_t *variable_name_size,return EFI_EXIT (ret); } -/** -* efi_set_variable() - set value of a UEFI variable -* -* This function implements the SetVariable runtime service. -* -* See the Unified Extensible Firmware Interface (UEFI) specification for -* details. -* -* @variable_name: name of the variable -* @vendor: vendor GUID -* @attributes: attributes of the variable -* @data_size: size of the buffer with the variable value -* @data: buffer with the variable value -* Return: status code -*/ -efi_status_t EFIAPI efi_set_variable(u16 *variable_name, -const efi_guid_t *vendor,u32 attributes, -efi_uintn_t data_size,const void *data) +static +efi_status_t EFIAPI efi_set_variable_common(u16 *variable_name, +const efi_guid_t *vendor, +u32 attributes, +efi_uintn_t data_size, +const void *data, +bool ro_check, +bool is_non_volatile) { -char *native_name =NULL , *val =NULL , *s; -const char *old_val; -size_t old_size; -efi_status_t ret =EFI_SUCCESS ; +char *native_name =NULL , *old_data =NULL , *val =NULL , *s; +efi_uintn_t old_size; +bool append, delete; +u64 time =0 ;u32 attr; +efi_status_t ret =EFI_SUCCESS ; -EFI_ENTRY ("\"%ls\" %pUl %x %zu %p" , variable_name, vendor, attributes, - data_size, data); +debug ("%s: set '%s'\n" , __func__, native_name);if (!variable_name || !*variable_name || !vendor || ((attributes &EFI_VARIABLE_RUNTIME_ACCESS ) && !(attributes &EFI_VARIABLE_BOOTSERVICE_ACCESS ))) { ret =EFI_INVALID_PARAMETER ; - goto out; + goto err; } ret =efi_to_native (&native_name, variable_name, vendor);if (ret) - goto out; + goto err; + +/* check if a variable exists */ + old_size =0 ; + attr =0 ; + ret =EFI_CALL (efi_get_variable (variable_name, vendor, &attr, + &old_size,NULL )); +if (ret ==EFI_BUFFER_TOO_SMALL ) { +if ((is_non_volatile && !(attr &EFI_VARIABLE_NON_VOLATILE )) || + (!is_non_volatile && (attr &EFI_VARIABLE_NON_VOLATILE ))) { + ret =EFI_INVALID_PARAMETER ; + goto err; + } + } - old_val =env_get (native_name); -if (old_val) { - old_val =parse_attr (old_val, &attr); + append = !!(attributes &EFI_VARIABLE_APPEND_WRITE ); + attributes &= ~(u32 )EFI_VARIABLE_APPEND_WRITE ; + delete = !append && (!data_size || !attributes); -/* check read-only first */ -if (attr &READ_ONLY ) { +/* check attributes */ +if (old_size) { +if (ro_check && (attr &READ_ONLY )) { ret =EFI_WRITE_PROTECTED ; - goto out; - } - -if ((data_size ==0 && - !(attributes &EFI_VARIABLE_APPEND_WRITE )) || - !attributes) { -/* delete the variable: */ -env_set (native_name,NULL ); - ret =EFI_SUCCESS ; - goto out; + goto err; }/* attributes won't be changed */ -if (attr != (attributes & ~EFI_VARIABLE_APPEND_WRITE )) { +if (!delete && + ((ro_check && attr != attributes) || + (!ro_check && ((attr & ~(u32 )READ_ONLY ) + != (attributes & ~(u32 )READ_ONLY ))))) { ret =EFI_INVALID_PARAMETER ; - goto out; - } - -if (attributes &EFI_VARIABLE_APPEND_WRITE ) { -if (!prefix (old_val,"(blob)" )) { - ret =EFI_DEVICE_ERROR ; - goto out; - } - old_size =strlen (old_val); - }else { - old_size =0 ; + goto err; } }else { -if (data_size ==0 || !attributes || - (attributes &EFI_VARIABLE_APPEND_WRITE )) { +if (delete || append) {/* * Trying to delete or to update a non-existent * variable. */ ret =EFI_NOT_FOUND ; - goto out; + goto err; + } + } + +if (((!u16_strcmp (variable_name,L"PK" ) || + !u16_strcmp (variable_name,L"KEK" )) && + !guidcmp (vendor, &efi_global_variable_guid)) || + ((!u16_strcmp (variable_name,L"db" ) || + !u16_strcmp (variable_name,L"dbx" )) && + !guidcmp (vendor, &efi_guid_image_security_database))) { +/* authentication is mandatory */ +if (!(attributes & +EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS )) { +debug ("%ls: AUTHENTICATED_WRITE_ACCESS required\n" , + variable_name); + ret =EFI_INVALID_PARAMETER ; + goto err; } + } + +/* authenticate a variable */ +if (IS_ENABLED (CONFIG_EFI_SECURE_BOOT )) { +if (attributes &EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS ) { + ret =EFI_INVALID_PARAMETER ; + goto err; + } +if (attributes & +EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS ) { + ret =efi_variable_authenticate (variable_name, vendor, + &data_size, &data, + attributes, &attr, + &time); +if (ret !=EFI_SUCCESS ) + goto err; + +/* last chance to check for delete */ +if (!data_size) + delete = true; + } + }else { +if (attributes & + (EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS | +EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS )) { +debug ("Secure boot is not configured\n" ); + ret =EFI_INVALID_PARAMETER ; + goto err; + } + } + +/* delete a variable */ +if (delete) { +/* !old_size case has been handled before */ + val =NULL ; + ret =EFI_SUCCESS ; + goto out; + } +if (append) { + old_data =malloc (old_size); +if (!old_data) { +return EFI_OUT_OF_RESOURCES ; + goto err; + } + ret =EFI_CALL (efi_get_variable (variable_name, vendor, + &attr, &old_size, old_data)); +if (ret !=EFI_SUCCESS ) + goto err; + }else { old_size =0 ; } - val =malloc (old_size +2 * data_size - +strlen ("{ro,run,boot,nv}(blob)" ) +1 ); + val =malloc (2 * old_size +2 * data_size + +strlen ("{ro,run,boot,nv,time=0123456701234567}(blob)" ) + +1 );if (!val) { ret =EFI_OUT_OF_RESOURCES ; - goto out; + goto err; } s = val; -/* store attributes */ - attributes &= (EFI_VARIABLE_NON_VOLATILE | +/* +* store attributes +*/ + attributes &= (READ_ONLY | +EFI_VARIABLE_NON_VOLATILE |EFI_VARIABLE_BOOTSERVICE_ACCESS | -EFI_VARIABLE_RUNTIME_ACCESS ); +EFI_VARIABLE_RUNTIME_ACCESS | +EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS ); s +=sprintf (s,"{" );while (attributes) { -u32 attr =1 << (ffs (attributes) -1 ); + attr =1 << (ffs (attributes) -1 ); -if (attr ==EFI_VARIABLE_NON_VOLATILE ) +if (attr ==READ_ONLY ) { + s +=sprintf (s,"ro" ); + }else if (attr ==EFI_VARIABLE_NON_VOLATILE ) { s +=sprintf (s,"nv" ); -else if (attr ==EFI_VARIABLE_BOOTSERVICE_ACCESS ) + }else if (attr ==EFI_VARIABLE_BOOTSERVICE_ACCESS ) { s +=sprintf (s,"boot" ); -else if (attr ==EFI_VARIABLE_RUNTIME_ACCESS ) + }else if (attr ==EFI_VARIABLE_RUNTIME_ACCESS ) { s +=sprintf (s,"run" ); + }else if (attr == +EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS ) { + s +=sprintf (s,"time=" ); + s =bin2hex (s, (u8 *)&time,sizeof (time)); + } attributes &= ~attr;if (attributes) s +=sprintf (s,"," ); } s +=sprintf (s,"}" ); - -if (old_size) -/* APPEND_WRITE */ - s +=sprintf (s, old_val); -else - s +=sprintf (s,"(blob)" ); + s +=sprintf (s,"(blob)" );/* store payload: */ +if (append) + s =bin2hex (s, old_data, old_size); s =bin2hex (s, data, data_size); *s ='\0' ;EFI_PRINT ("setting: %s=%s\n" , native_name, val); +out:if (env_set (native_name, val)) ret =EFI_DEVICE_ERROR ; +else + ret =EFI_SUCCESS ; -out: +err:free (native_name); +free (old_data);free (val); -return EFI_EXIT (ret); +return ret; +} + +static +efi_status_t EFIAPI efi_set_volatile_variable(u16 *variable_name, +const efi_guid_t *vendor, +u32 attributes, +efi_uintn_t data_size, +const void *data, +bool ro_check) +{ +return efi_set_variable_common (variable_name, vendor, attributes, + data_size, data, ro_check, false); +} + +efi_status_t EFIAPI efi_set_nonvolatile_variable(u16 *variable_name, +const efi_guid_t *vendor, +u32 attributes, +efi_uintn_t data_size, +const void *data, +bool ro_check) +{ +efi_status_t ret; + + ret =efi_set_variable_common (variable_name, vendor, attributes, + data_size, data, ro_check, true); + +return ret; +} + +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_status_t ret; + +if (attributes &EFI_VARIABLE_NON_VOLATILE ) + ret =efi_set_nonvolatile_variable (variable_name, vendor, + attributes, + data_size, data, ro_check); +else + ret =efi_set_volatile_variable (variable_name, vendor, + attributes, data_size, data, + ro_check); + +return ret; +} + +/** +* efi_set_variable() - set value of a UEFI variable +* +* This function implements the SetVariable runtime service. +* +* See the Unified Extensible Firmware Interface (UEFI) specification for +* details. +* +* @variable_name: name of the variable +* @vendor: vendor GUID +* @attributes: attributes of the variable +* @data_size: size of the buffer with the variable value +* @data: buffer with the variable value +* Return: status code +*/ +efi_status_t EFIAPI efi_set_variable(u16 *variable_name, +const efi_guid_t *vendor,u32 attributes, +efi_uintn_t data_size,const void *data) +{ +EFI_ENTRY ("\"%ls\" %pUl %x %zu %p" , variable_name, vendor, attributes, + data_size, data); + +/* READ_ONLY bit is not part of API */ + attributes &= ~(u32 )READ_ONLY ; + +return EFI_EXIT (efi_set_variable_internal (variable_name, vendor, + attributes, data_size, data, + true)); }/**
PATCH 8/16 efi_loader: variable: add secure boot state transition
In reply to AKASHI TakahiroUEFI 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
@@ -15,8 +15,16 @@#include <linux/compat.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)
@@ -158,6 +166,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 *
@@ -906,10 +1118,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);
@@ -1094,5 +1315,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.21.0
PATCH 9/16 efi_loader: variable: add VendorKeys variable
In reply to AKASHI TakahiroThe 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
@@ -25,6 +25,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)
@@ -342,6 +343,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:
@@ -357,16 +360,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; }
@@ -1121,6 +1154,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(
@@ -1128,8 +1163,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.21.0
PATCH 10/16 efi_loader: image_loader: support image authentication
In reply to AKASHI TakahiroWith 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 specifiction defines the verification process in a bit ambiguous way. I tried to implement it as closely to as EDK2 does.
--- include/efi_loader.h | 7 +- lib/efi_loader/efi_boottime.c | 2 +- lib/efi_loader/efi_image_loader.c | 443 +++++++++++++++++++++++++++++- 3 files changed, 438 insertions(+), 14 deletions(-)
include/efi_loader.h +6 -1
@@ -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) {
@@ -398,7 +399,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 );
@@ -700,6 +702,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 +1 -1
@@ -1879,7 +1879,7 @@ 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,
lib/efi_loader/efi_image_loader.c +431 -12
520 lines not on this page · raw message
Signature · 1 line
2.21.0
PATCH 11/16 efi_loader: set up secure boot
In reply to AKASHI TakahiroThe 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
@@ -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 *
@@ -122,6 +155,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.21.0
PATCH 12/16 cmd: env: use appropriate guid for authenticated UEFI variable
In reply to AKASHI TakahiroA 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
@@ -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.21.0
PATCH 12/16 cmd: env: use appropriate guid for authenticated UEFI variable
Quoted 3 lines · 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.
If secure boot is enforced, users should not be able to change any security relevant variables. Instead we need a way to compile the security relevant data into the U-Boot binary and add a signature to the U-Boot binary which can be checked by the primary boot loader.
Best regards
Heinrich
Quoted 51 lines
Signed-off-by AKASHI Takahiro <[email protected]>--- cmd/nvedit_efi.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-)cmd/nvedit_efi.c +14
-4@@ -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 *)
PATCH 12/16 cmd: env: use appropriate guid for authenticated UEFI variable
Heinrich,
Quoted 7 lines · Heinrich Schuchardt
Quoted 3 lines · 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.
If secure boot is enforced, users should not be able to change any security relevant variables.
I disagree. In fact, UEFI specification allows users to modify security database variables if their signatures are verified. For example, "db" must be signed by one of certificates in PK or KEK, and updating its value will should be authenticated in SetVariable API. That is what my patch#7 exactly does.
Thanks,
-Takahiro Akashi
Quoted 60 lines
Instead we need a way to compile the
security relevant data into the U-Boot binary and add a signature to the U-Boot binary which can be checked by the primary boot loader.Best regards
Heinrich
Quoted 51 lines
Signed-off-by AKASHI Takahiro <[email protected]>--- cmd/nvedit_efi.c | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-)cmd/nvedit_efi.c +14
-4@@ -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 *)
PATCH 12/16 cmd: env: use appropriate guid for authenticated UEFI variable
Quoted 11 lines · AKASHI Takahiro
Heinrich,
Quoted 7 lines · Heinrich Schuchardt
Quoted 3 lines · 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.
If secure boot is enforced, users should not be able to change any security relevant variables.
Quoted 8 lines
I disagree. In fact, UEFI specification allows users to modify security database variables if their signatures are verified. For example, "db" must be signed by one of certificates in PK or KEK, and updating its value will should be authenticated in SetVariable API. That is what my patch#7 exactly does.
Thanks,
-Takahiro Akashi
I agree. It must be possible for any user of the EFI subsystem to be able to update db/KEK/PK *if* he provides a valid signatures. The thing is that keys are replaced and rerolled, not only because keys were com- promised, but also because some policies say it's useful to replace the keys regularly so that attempts to crack the key have less time to be successfull. There are more use-cases then that, but what is important is that it's possible to change them, if properly signed.
Thanks,
Patrick
PATCH 13/16 cmd: env: add "-at" option to "env set -e" command
In reply to AKASHI TakahiroWith "-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
@@ -1399,7 +1399,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" ;
@@ -1461,13 +1461,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
@@ -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.21.0
PATCH 14/16 efi_loader, pytest: set up secure boot environment
In reply to AKASHI TakahiroA 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.
--- .travis.yml | 4 + test/py/README.md | 4 + test/py/tests/test_efi_secboot/conftest.py | 128 +++++++++++++++++++++ test/py/tests/test_efi_secboot/defs.py | 21 ++++ 4 files changed, 157 insertions(+) create mode 100644 test/py/tests/test_efi_secboot/conftest.py create mode 100644 test/py/tests/test_efi_secboot/defs.py
.travis.yml +4 -0
@@ -38,6 +38,10 @@ addons: - libisl15 - clang-7 - srecord + - coreutils + - dosfstools + - efitools + - udisks2 install: # Clone uboot-test-hooks
test/py/README.md +4 -0
@@ -38,6 +38,10 @@ will be required. The following is an incomplete list: | sudo OR guestmount | | e2fsprogs | | dosfstools | +| coreutils | +| efitools | +| sbsigntools | +| 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 +128 -0
128 lines not on this page · raw message
test/py/tests/test_efi_secboot/defs.py new file +21 -0
@@ -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.21.0
PATCH 14/16 efi_loader, pytest: set up secure boot environment
Quoted 3 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.
Why do we need a file system? That seems overly complicated.
Can't we use tFTP to download the file you want to check like we do for helloworld.efi and grub.efi.
Quoted 56 lines
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.Signed-off-by AKASHI Takahiro <[email protected]>--- .travis.yml | 4 + test/py/README.md | 4 + test/py/tests/test_efi_secboot/conftest.py | 128 +++++++++++++++++++++ test/py/tests/test_efi_secboot/defs.py | 21 ++++ 4 files changed, 157 insertions(+)create mode 100644
test/py/tests/test_efi_secboot/conftest.pycreate mode 100644test/py/tests/test_efi_secboot/defs.py.travis.yml +4
-0@@ -38,6 +38,10 @@ addons: - libisl15 - clang-7 - srecord + - coreutils + - dosfstools + - efitools + - udisks2 install: # Clone uboot-test-hookstest/py/README.md +4
-0@@ -38,6 +38,10 @@ will be required. The following is an incomplete list: | sudo OR guestmount | | e2fsprogs | | dosfstools | +| coreutils | +| efitools | +| sbsigntools | +| 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 +6
-0@@ -0,0 +1,128 @@ +# SPDX-License-Identifier: GPL-2.0+ +# Copyright (c) 2019, Linaro Limited +# Author: AKASHI Takahiro <[email protected]> + +import os +import os.path
test/py/tests/test_efi_secboot/conftest.py line 16
Quoted 10 lines
test/py/tests/test_efi_secboot/conftest.py new file +10
-0+import pytest +import re +from subprocess import call, check_call, check_output, CalledProcessError +from defs import * + +# +# Fixture for UEFI secure boot test +# +# NOTE: yield_fixture was deprecated since pytest-3.0 + at pytest.yield_fixture()
If it is deprecated, don't use it.
https://docs.pytest.org/en/latest/yieldfixture.html
Best regards
Heinrich
Quoted 140 lines
test/py/tests/test_efi_secboot/conftest.py new file +112
-0+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: + # 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) + out_data = check_output('udisksctl loop-setup -f %s -o %d' + % (image_path, 1048576), shell=True).decode() + m = re.search('(?<= as )(.*)\.', out_data) + 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) + # 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) + + check_call('udisksctl unmount -b %s' % loop_dev, shell=True) + # check_call('udisksctl loop-delete -b %s' % loop_dev, shell=True) + except CalledProcessError as e: + pytest.skip('Setup failed: %s' % e.cmd) + return + else: + yield image_path + finally: + call('echo %s' % image_path, shell=True) + # call('rm -f %s' % image_path, shell=True)test/py/tests/test_efi_secboot/defs.py new file +21
-0@@ -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=''
PATCH 14/16 efi_loader, pytest: set up secure boot environment
Heinrich,
Quoted 6 lines · Heinrich Schuchardt
Quoted 3 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.
Why do we need a file system? That seems overly complicated.
I disagree. As UEFI requires a support for file system, fat, assuming that we can access a file system is fair enough.
Quoted 2 lines
Can't we use tFTP to download the file you want to check like we do for helloworld.efi and grub.efi.
Let me ask the same question as you did.
Why do we need a network device?
Quoted 60 lines
Quoted 60 lines
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.Signed-off-by AKASHI Takahiro <[email protected]>--- .travis.yml | 4 + test/py/README.md | 4 + test/py/tests/test_efi_secboot/conftest.py | 128 +++++++++++++++++++++ test/py/tests/test_efi_secboot/defs.py | 21 ++++ 4 files changed, 157 insertions(+) create mode 100644 test/py/tests/test_efi_secboot/conftest.py create mode 100644 test/py/tests/test_efi_secboot/defs.py.travis.yml +4
-0@@ -38,6 +38,10 @@ addons: - libisl15 - clang-7 - srecord + - coreutils + - dosfstools + - efitools + - udisks2 install: # Clone uboot-test-hookstest/py/README.md +4
-0@@ -38,6 +38,10 @@ will be required. The following is an incomplete list: | sudo OR guestmount | | e2fsprogs | | dosfstools | +| coreutils | +| efitools | +| sbsigntools | +| 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 +10
-0@@ -0,0 +1,128 @@ +# 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 *
Quoted 8 lines
test/py/tests/test_efi_secboot/conftest.py line 16
Quoted 6 lines
test/py/tests/test_efi_secboot/conftest.py new file +6
-0+ +# +# Fixture for UEFI secure boot test +# +# NOTE: yield_fixture was deprecated since pytest-3.0 + at pytest.yield_fixture()If it is deprecated, don't use it.
Okay, I have forgot to fix it.
-Takahiro Akashi
Quoted 147 lines
https://docs.pytest.org/en/latest/yieldfixture.html
Best regards
Heinrich
Quoted 140 lines
test/py/tests/test_efi_secboot/conftest.py new file +112
-0+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: + # 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) + out_data = check_output('udisksctl loop-setup -f %s -o %d' + % (image_path, 1048576), shell=True).decode() + m = re.search('(?<= as )(.*)\.', out_data) + 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) + # 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) + + check_call('udisksctl unmount -b %s' % loop_dev, shell=True) + # check_call('udisksctl loop-delete -b %s' % loop_dev, shell=True) + except CalledProcessError as e: + pytest.skip('Setup failed: %s' % e.cmd) + return + else: + yield image_path + finally: + call('echo %s' % image_path, shell=True) + # call('rm -f %s' % image_path, shell=True)test/py/tests/test_efi_secboot/defs.py new file +21
-0@@ -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=''
PATCH 15/16 efi_loader, pytest: add UEFI secure boot tests (authenticated variables)
In reply to AKASHI TakahiroProvide a couple of test cases for variable authentication.
--- .../py/tests/test_efi_secboot/test_authvar.py | 289 ++++++++++++++++++ 1 file changed, 289 insertions(+) create mode 100644 test/py/tests/test_efi_secboot/test_authvar.py
test/py/tests/test_efi_secboot/test_authvar.py new file +289 -0
@@ -0,0 +1,289 @@ +# 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 + """ + 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(re.search('00000000: 00', ''.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) + + with u_boot_console.log.section('Test Case 1b'): + # Test Case 1b, PK 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 -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 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 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 -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 -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 + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x329', ''.join(output))) + + def test_efi_var_auth3(self, u_boot_console, efi_boot_env): + """ + Test Case 3 - Append database + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x650', ''.join(output))) + + def test_efi_var_auth4(self, u_boot_console, efi_boot_env): + """ + Test Case 4 - Delete database without authentication + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'setenv -e -nv -bs -rt db', + 'printenv -e -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.join(output))) + + def test_efi_var_auth5(self, u_boot_console, efi_boot_env): + """ + Test Case 5 - Uninstall(delete) PK + """ + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 4a'): + # 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 PK']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('PK:', ''.join(output))) +# assert(re.search('DataSize = 0x31d', ''.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 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 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.21.0
PATCH 15/16 efi_loader, pytest: add UEFI secure boot tests (authenticated variables)
Quoted 1 line · AKASHI Takahiro
Provide a couple of test cases for variable authentication.
Please, tell us more in the commit message.
Quoted 18 lines
Signed-off-by AKASHI Takahiro <[email protected]>--- .../py/tests/test_efi_secboot/test_authvar.py | 289 ++++++++++++++++++ 1 file changed, 289 insertions(+)create mode 100644
test/py/tests/test_efi_secboot/test_authvar.pytest/py/tests/test_efi_secboot/test_authvar.py new file +5
-0@@ -0,0 +1,289 @@ +# SPDX-License-Identifier: GPL-2.0+ +# Copyright (c) 2019, Linaro Limited +# Author: AKASHI Takahiro <[email protected]> +# +# U-Boot UEFI: Variable Authentication Test
test/py/tests/test_efi_secboot/test_authvar.py line 15
Quoted 10 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +10
-0+ +""" +This test verifies variable authentication +""" + +import pytest +import re +from defs import * + + at pytest.mark.boardspec('sandbox')
Why can't we run this on other architectures?
The sandbox currently only runs in 64bit mode. This way we might miss errors that only occur on 32bit systems.
Quoted 173 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +173
-0+ 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 + """ + 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(re.search('00000000: 00', ''.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) + + with u_boot_console.log.section('Test Case 1b'): + # Test Case 1b, PK 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 -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 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 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 -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 -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 + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x329', ''.join(output))) + + def test_efi_var_auth3(self, u_boot_console, efi_boot_env): + """ + Test Case 3 - Append database + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.join(output)))
test/py/tests/test_efi_secboot/test_authvar.py line 198
Quoted 10 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +10
-0+ + 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',
Where do find all the files you try to load here?
You cannot assume that the sandbox is connected to any special file system while the test is running as there is no buildconfigspec requiring it.
Best regards
Heinrich
Quoted 92 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +91
-0+ '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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x650', ''.join(output))) + + def test_efi_var_auth4(self, u_boot_console, efi_boot_env): + """ + Test Case 4 - Delete database without authentication + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'setenv -e -nv -bs -rt db', + 'printenv -e -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.join(output))) + + def test_efi_var_auth5(self, u_boot_console, efi_boot_env): + """ + Test Case 5 - Uninstall(delete) PK + """ + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 4a'): + # 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 PK']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('PK:', ''.join(output))) +# assert(re.search('DataSize = 0x31d', ''.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 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 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)
PATCH 15/16 efi_loader, pytest: add UEFI secure boot tests (authenticated variables)
Quoted 4 lines · Heinrich Schuchardt
Quoted 1 line · AKASHI Takahiro
Provide a couple of test cases for variable authentication.
Please, tell us more in the commit message.
About what?
I have lots of 'text case' descriptions in *.py files.
Quoted 22 lines
Quoted 22 lines
Signed-off-by AKASHI Takahiro <[email protected]>--- .../py/tests/test_efi_secboot/test_authvar.py | 289 ++++++++++++++++++ 1 file changed, 289 insertions(+) create mode 100644 test/py/tests/test_efi_secboot/test_authvar.pytest/py/tests/test_efi_secboot/test_authvar.py new file +9
-0@@ -0,0 +1,289 @@ +# 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 +"""
Quoted 8 lines
test/py/tests/test_efi_secboot/test_authvar.py line 15
Quoted 6 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +6
-0+ +import pytest +import re +from defs import * + + at pytest.mark.boardspec('sandbox')Why can't we run this on other architectures?
As you see, we need some data files, most of which contain data for signature database variables, to run test cases. Using sandbox is the easiest way to minimize hardware requirements.
Quoted 2 lines
The sandbox currently only runs in 64bit mode. This way we might miss errors that only occur on 32bit systems.
Right, but this is not my patch-specific issue.
Quoted 186 lines
Quoted 173 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +173
-0+ 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 + """ + 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(re.search('00000000: 00', ''.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) + + with u_boot_console.log.section('Test Case 1b'): + # Test Case 1b, PK 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 -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 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 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 -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 -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 + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x329', ''.join(output))) + + def test_efi_var_auth3(self, u_boot_console, efi_boot_env): + """ + Test Case 3 - Append database + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.join(output)))test/py/tests/test_efi_secboot/test_authvar.py line 198
Quoted 10 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +10
-0+ + 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',Where do find all the files you try to load here?
Quoted 3 lines
You cannot assume that the sandbox is connected to any special file system while the test is running as there is no buildconfigspec requiring it.
Will add a dependency on 'fs_fat'
-Takahiro Akashi
Quoted 97 lines
Best regards
Heinrich
Quoted 92 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +91
-0+ '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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x650', ''.join(output))) + + def test_efi_var_auth4(self, u_boot_console, efi_boot_env): + """ + Test Case 4 - Delete database without authentication + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'setenv -e -nv -bs -rt db', + 'printenv -e -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.join(output))) + + def test_efi_var_auth5(self, u_boot_console, efi_boot_env): + """ + Test Case 5 - Uninstall(delete) PK + """ + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 4a'): + # 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 PK']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('PK:', ''.join(output))) +# assert(re.search('DataSize = 0x31d', ''.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 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 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)
PATCH 15/16 efi_loader, pytest: add UEFI secure boot tests (authenticated variables)
Heinrich,
Quoted 235 lines · AKASHI Takahiro
Quoted 4 lines · Heinrich Schuchardt
Quoted 1 line · AKASHI Takahiro
Provide a couple of test cases for variable authentication.
Please, tell us more in the commit message.
About what?
I have lots of 'text case' descriptions in *.py files.Quoted 22 lines
Quoted 22 lines
Signed-off-by AKASHI Takahiro <[email protected]>--- .../py/tests/test_efi_secboot/test_authvar.py | 289 ++++++++++++++++++ 1 file changed, 289 insertions(+) create mode 100644 test/py/tests/test_efi_secboot/test_authvar.pytest/py/tests/test_efi_secboot/test_authvar.py new file +9
-0@@ -0,0 +1,289 @@ +# 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 +"""Quoted 8 lines
test/py/tests/test_efi_secboot/test_authvar.py line 15
Quoted 6 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +6
-0+ +import pytest +import re +from defs import * + + at pytest.mark.boardspec('sandbox')Why can't we run this on other architectures?
As you see, we need some data files, most of which contain data for signature database variables, to run test cases. Using sandbox is the easiest way to minimize hardware requirements.
Quoted 2 lines
The sandbox currently only runs in 64bit mode. This way we might miss errors that only occur on 32bit systems.
Right, but this is not my patch-specific issue.
Quoted 186 lines
Quoted 173 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +173
-0+ 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 + """ + 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(re.search('00000000: 00', ''.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) + + with u_boot_console.log.section('Test Case 1b'): + # Test Case 1b, PK 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 -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 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 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 -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 -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 + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x329', ''.join(output))) + + def test_efi_var_auth3(self, u_boot_console, efi_boot_env): + """ + Test Case 3 - Append database + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.join(output)))test/py/tests/test_efi_secboot/test_authvar.py line 198
Quoted 10 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +10
-0+ + 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',Where do find all the files you try to load here?
Quoted 5 lines
Quoted 3 lines
You cannot assume that the sandbox is connected to any special file system while the test is running as there is no buildconfigspec requiring it.
Will add a dependency on '
fs_fat'
CMD_FAT already requires FS_FAT, so I won't make this change.
-Takahiro Akashi
Quoted 99 lines
-Takahiro Akashi
Quoted 97 lines
Best regards
Heinrich
Quoted 92 lines
test/py/tests/test_efi_secboot/test_authvar.py new file +91
-0+ '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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x650', ''.join(output))) + + def test_efi_var_auth4(self, u_boot_console, efi_boot_env): + """ + Test Case 4 - Delete database without authentication + """ + 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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.join(output))) + + output = u_boot_console.run_command_list([ + 'setenv -e -nv -bs -rt db', + 'printenv -e -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.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 -guid d719b2cb-3d3a-4596-a3bc-dad00e67656f db']) + assert(re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('db:', ''.join(output))) + assert(re.search('DataSize = 0x327', ''.join(output))) + + def test_efi_var_auth5(self, u_boot_console, efi_boot_env): + """ + Test Case 5 - Uninstall(delete) PK + """ + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 4a'): + # 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 PK']) + assert(not re.search('Failed to set EFI variable', ''.join(output))) + assert(re.search('PK:', ''.join(output))) +# assert(re.search('DataSize = 0x31d', ''.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 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 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)
PATCH 16/16 efi_loader, pytest: add UEFI secure boot tests (image)
In reply to AKASHI TakahiroProvide 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 | 97 +++++++++++++++++ .../tests/test_efi_secboot/test_unsigned.py | 100 ++++++++++++++++++ 2 files changed, 197 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 +97 -0
@@ -0,0 +1,97 @@ +# 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 + """ + 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))) + + 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 + """ + 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))) + + 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)))
test/py/tests/test_efi_secboot/test_unsigned.py new file +100 -0
100 lines not on this page · raw message
Signature · 1 line
2.21.0
PATCH 16/16 efi_loader, pytest: add UEFI secure boot tests (image)
Quoted 25 lines · 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)Signed-off-by AKASHI Takahiro <[email protected]>--- test/py/tests/test_efi_secboot/test_signed.py | 97 +++++++++++++++++ .../tests/test_efi_secboot/test_unsigned.py | 100 ++++++++++++++++++ 2 files changed, 197 insertions(+)create mode 100644
test/py/tests/test_efi_secboot/test_signed.pycreate mode 100644test/py/tests/test_efi_secboot/test_unsigned.pytest/py/tests/test_efi_secboot/test_signed.py new file +5
-0@@ -0,0 +1,97 @@ +# SPDX-License-Identifier: GPL-2.0+ +# Copyright (c) 2019, Linaro Limited +# Author: AKASHI Takahiro <[email protected]> +# +# U-Boot UEFI: Signed Image Authentication Test
test/py/tests/test_efi_secboot/test_signed.py line 15
Quoted 10 lines
test/py/tests/test_efi_secboot/test_signed.py new file +10
-0+ +""" +This test verifies image authentication for signed images. +""" + +import pytest +import re +from defs import * + + at pytest.mark.boardspec('sandbox')
Why would we only test on the sandbox? This leaves 32bit untested.
Quoted 162 lines
test/py/tests/test_efi_secboot/test_signed.py new file +82
-0+ 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 + """ + 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))) + + 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 + """ + 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))) + + 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)))test/py/tests/test_efi_secboot/test_unsigned.py new file +74
-0@@ -0,0 +1,100 @@ +# 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 unsigned 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 TestEfiUnsignedImage(object): + def test_efi_unsigned_image_auth1(self, u_boot_console, efi_boot_env): + """ + Test Case 1 - rejected when not digest in db or dbx + """ + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 1'): + # Test Case 1 + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + '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 ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('\'HELLO\' failed', ''.join(output))) + + def test_efi_unsigned_image_auth2(self, u_boot_console, efi_boot_env): + """ + Test Case 2 - authenticated by digest in db + """ + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 2'): + # Test Case 2 + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'fatload host 0:1 4000000 db_hello.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 add 1 HELLO host 0:1 /helloworld.efi ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('Hello, world!', ''.join(output))) + + def test_efi_unsigned_image_auth3(self, u_boot_console, efi_boot_env): + """ + Test Case 3 - rejected by digest in dbx + """ + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 3a'): + # Test Case 3a, rejected by dbx + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img,
test/py/tests/test_efi_secboot/test_unsigned.py line 84
Quoted 10 lines
test/py/tests/test_efi_secboot/test_unsigned.py new file +10
-0+ 'fatload host 0:1 4000000 db_hello.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 ""',
You cannot assume any host file system to be connected as nothing in you test definition requires this.
Best regards
Heinrich
Quoted 17 lines
test/py/tests/test_efi_secboot/test_unsigned.py new file +16
-0+ 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('\'HELLO\' failed', ''.join(output))) + + with u_boot_console.log.section('Test Case 3b'): + # Test Case 3b, rejected by dbx even if db allows + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db_hello.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 add 1 HELLO host 0:1 /helloworld.efi ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('\'HELLO\' failed', ''.join(output)))
PATCH 16/16 efi_loader, pytest: add UEFI secure boot tests (image)
Heinrich,
Quoted 30 lines · Heinrich Schuchardt
Quoted 29 lines · 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)Signed-off-by AKASHI Takahiro <[email protected]>--- test/py/tests/test_efi_secboot/test_signed.py | 97 +++++++++++++++++ .../tests/test_efi_secboot/test_unsigned.py | 100 ++++++++++++++++++ 2 files changed, 197 insertions(+) create mode 100644 test/py/tests/test_efi_secboot/test_signed.py create mode 100644 test/py/tests/test_efi_secboot/test_unsigned.pytest/py/tests/test_efi_secboot/test_signed.py new file +9
-0@@ -0,0 +1,97 @@ +# 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. +"""
Quoted 8 lines
test/py/tests/test_efi_secboot/test_signed.py line 15
Quoted 6 lines
test/py/tests/test_efi_secboot/test_signed.py new file +6
-0+ +import pytest +import re +from defs import * + + at pytest.mark.boardspec('sandbox')Why would we only test on the sandbox? This leaves 32bit untested.
I commented on this issue on patch#15.
Quoted 167 lines
Quoted 167 lines
test/py/tests/test_efi_secboot/test_signed.py new file +82
-0+ 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 + """ + 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))) + + 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 + """ + 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))) + + 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)))test/py/tests/test_efi_secboot/test_unsigned.py new file +79
-0@@ -0,0 +1,100 @@ +# 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 unsigned 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 TestEfiUnsignedImage(object): + def test_efi_unsigned_image_auth1(self, u_boot_console, efi_boot_env): + """ + Test Case 1 - rejected when not digest in db or dbx + """ + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 1'): + # Test Case 1 + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + '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 ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('\'HELLO\' failed', ''.join(output))) + + def test_efi_unsigned_image_auth2(self, u_boot_console, efi_boot_env): + """ + Test Case 2 - authenticated by digest in db + """ + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 2'): + # Test Case 2 + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'fatload host 0:1 4000000 db_hello.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 add 1 HELLO host 0:1 /helloworld.efi ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('Hello, world!', ''.join(output))) + + def test_efi_unsigned_image_auth3(self, u_boot_console, efi_boot_env): + """ + Test Case 3 - rejected by digest in dbx + """ + disk_img = efi_boot_env + with u_boot_console.log.section('Test Case 3a'): + # Test Case 3a, rejected by dbx + output = u_boot_console.run_command_list([ + 'host bind 0 %s' % disk_img, + 'fatload host 0:1 4000000 db_hello.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',
Quoted 8 lines
test/py/tests/test_efi_secboot/test_unsigned.py line 38
Quoted 5 lines
test/py/tests/test_efi_secboot/test_unsigned.py new file +5
-0+ '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 ""',You cannot assume any host file system to be connected as nothing in you test definition requires this.
ditto.
Thanks,
-Takahiro Akashi
Quoted 22 lines
Best regards
Heinrich
Quoted 17 lines
test/py/tests/test_efi_secboot/test_unsigned.py new file +16
-0+ 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('\'HELLO\' failed', ''.join(output))) + + with u_boot_console.log.section('Test Case 3b'): + # Test Case 3b, rejected by dbx even if db allows + output = u_boot_console.run_command_list([ + 'fatload host 0:1 4000000 db_hello.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 add 1 HELLO host 0:1 /helloworld.efi ""', + 'efidebug boot next 1', + 'bootefi bootmgr']) + assert(re.search('\'HELLO\' failed', ''.join(output)))
cover efi_loader: add secure boot support
In reply to AKASHI TakahiroHeinrich,
This patch set won't be applied cleanly to v2020.01-rc2 due to
bef18454044e ("freescale/powerpc: Rename the config CONFIG_SECURE_BOOT name") 5536c3c9d0d1 ("freescale/layerscape: Rename the config CONFIG_SECURE_BOOT
name")
Do you want to see another re-spin version right now? The necessary changes are
* remove my patch#3
* modify my patch#4 by removing "depends on SECURE_BOOT" from CONFIG_EFI_SECURE_BOOT
Since I haven't seen any comments on my v1, I'm rather reluctant to post another version so quickly.
-Takahiro Akashi
Quoted 171 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.)While this patch/RFC is still rough-edged, the aim here is to get early feedbacks from the community as the patch is quite huge (in total) and also as it's a security enhancement.
Please note, however, this patch doesn't work on its own; there are a couple of functional dependencies[2] and [3], that I have submitted before. For complete workable patch set, see my repository[4], which also contains exeperimental timestamp-based revocation suuport.
My "non-volatile" support[5], 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 and that UEFI variables are not separated from U-Boot environment. 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 areEFI_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 KEKEFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
* basic pytest test casesUnsupported 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 inEFI_IMAGE_EXECUTION_INFO_TABLE
* verification "policy", in particular, check against signature's owner
* private authenticated variables
* variable authentication withEFI_VARIABLE_ENHANCED_AUTHENTICATED_ACCESS
* real secure storage support, including hardware-specific PK (Platform Key) installationTODO's other than "Unsupported features": (won't be included in this series)
* structefi_image_regionscannot have arbitrary number of regions
* 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[6].Known issues:
* remove genericCONFIG_SECURE_BOOToption (on NXP/Freescale platforms) (I'm looking forward to fixes from NXP guys.)
* efitools is used in pytest, and its version must be v1.5.2 or later. (Solution: You can defineEFITOOLS_PATHindefs.pyfor your own efitools.)
* Pytest depends on standalone "helloworld" app for sandbox (Solution: You can defineHELLO_PATHindefs.pyor Heinrich's [7].)Test:
* my pytest, included in this patch set, passed.
*efi_selftestpassed. (At least no reguression.)
* Travis CI passed. (But pytest itself was skipped.)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/2019-November/390127.html
(import x509/pkcs7 parsers from linux)
[3] https://lists.denx.de/pipermail/u-boot/2019-November/390150.html
(extendrsa_verify()for UEFI secure boot)
[4] http://git.linaro.org/people/takahiro.akashi/u-boot.git/ efi/secboot
[5] https://lists.denx.de/pipermail/u-boot/2019-September/382835.html
(non-volatile variables support)
[6] https://bugzilla.tianocore.org/show_bug.cgi?id=2230
[7] https://lists.denx.de/pipermail/u-boot/2019-November/389593.htmlChanges 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 ofinit_secure_boot()intoinit_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)
* modifyconftest.pyto run under python3 (patch#14)
* use a partition on a disk instead of a whole disk without partition table (patch#14)
* reduce depencendy 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 (16):
include:pe.h: add signature-related definitions
include:image.h: export hash algorithm helper functions secure boot: renameCONFIG_SECURE_BOOTconfig option
efi_loader: addCONFIG_EFI_SECURE_BOOTconfig 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" commandefi_loader, pytest: set up secure boot environmentefi_loader, pytest: add UEFI secure boot tests (authenticated
variables)
efi_loader, pytest: add UEFI secure boot tests (image).travis.yml | 4 + Kconfig | 7 + arch/arm/cpu/armv7/ls102xa/Kconfig | 3 +- arch/arm/cpu/armv8/fsl-layerscape/Kconfig | 3 +- arch/powerpc/cpu/mpc85xx/Kconfig | 3 +- cmd/nvedit.c | 5 +- cmd/nvedit_efi.c | 23 +- include/efi_api.h | 47 + include/efi_loader.h | 59 +- include/image.h | 10 +- include/pe.h | 16 + lib/efi_loader/Kconfig | 13 + lib/efi_loader/Makefile | 1 + lib/efi_loader/efi_boottime.c | 2 +- lib/efi_loader/efi_image_loader.c | 443 +++++++- lib/efi_loader/efi_setup.c | 38 + lib/efi_loader/efi_signature.c | 827 +++++++++++++++ lib/efi_loader/efi_variable.c | 950 ++++++++++++++++-- test/py/README.md | 4 + test/py/tests/test_efi_secboot/conftest.py | 128 +++ test/py/tests/test_efi_secboot/defs.py | 21 + .../py/tests/test_efi_secboot/test_authvar.py | 289 ++++++ test/py/tests/test_efi_secboot/test_signed.py | 97 ++ .../tests/test_efi_secboot/test_unsigned.py | 100 ++ 24 files changed, 2958 insertions(+), 135 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.pySignature · 1 line
2.21.0