Skip to contentSkip to conversation

Appended signature secure boot support

PATCH In review Daniel Axtens 3 participants 24 messages Apr 21, 2022 – May 17, 2022 Kbuild

lore
Share & tools
lore
#0 lore raw

v3 cover Appended signature secure boot support

This patch set contains the long-awaited v3 for secure boot using appended signatures on powerpc.

The v2 series is at https://lists.gnu.org/archive/html/grub-devel/2021-06/msg00044.html

This series is based on the latest memory rework series I sent
(https://lists.gnu.org/archive/html/grub-devel/2022-04/msg00064.html) minus the RFC. (See github.com/daxtens/grub branch mem+appsig-2204 for precise patches.) I have not included those patches in this posting.

The series consists of 3 main parts:

1) Patches 1-3: signing grub.elf with an appended signature

Part of a secure boot chain is allowing boot firmware to verify the grub core image. For UEFI platforms, this is done by signing the PE binary with a tool like pesign or sb-sign. However, for platforms that don't implement UEFI, an alternative scheme is required.

These patches provide some infrastructure and documentation for signing grub's core.elf with a Linux-kernel-module style appended signature.

An appended signature is a 'dumb' signature over the contents of a file. (It is distinct from schemes like Authenticode that are aware of the structure of the file and only sign certain parts.) The signature is wrapped in a PKCS#7 message, and is appended to the signed file along with some metadata and a magic string. The signatures are validated against a public key which is usually provided as an x509 certificate.

Because some platforms, such as powerpc-ieee1275, may load grub from a raw disk partition rather than a filesystem, we extend grub-install to add an ELF note that allows us to specify the size and location of the signature.

2) Patches 4 - 18: Teach grub to verify appended signatures

Part of a secure boot chain is allowing grub to verify the boot kernel. For UEFI platforms, this is usually delegated to the shim. However, for platforms that do not implement UEFI, an alternative scheme is required.

This part teaches grub how to verify Linux kernel-style appended signatures. Kernels on powerpc are already signed with this scheme and can be verified by IMA for kexec.

As PKCS#7 messages and x509 certificates are both based on ASN.1, we import libtasn1 to parse them. Because ASN.1 isn't self-documenting, we import from GNUTLS the information we need to navigate their structure.

This section is composed of the following patches:

- patch 4 is a small fix to allow persistent modules to work on the emu target.

- patches 5 and 6 are small refactorings.

- patch 7 prepares posix_wrap for importing libtasn1

- patches 8 through 12 import libtasn1 and add tests. I've taken a different approach from gcrypt. We import gcrypt via a script that transforms the code into something that works for grub. Rather than taking that approach, we import libtasn1 through first just copying a subset of the code in (patch 8), then disabling parts we don't need for grub (patch 9), making changes for grub compatibility (patch 10) and then compiling it into a module (patch 11) and testing it (patch 12).

This means that should we want to upgrade our version of libtasn1, we should be able to copy the new files in (repeat the process in patch 8) and then just cherry-pick/reapply patches 9 and 10 to repeat the process of disabling unused code and making grub compatiblity fixes.

- patch 13 allows x509 certificates to be built in to the grub core in much the same way as PGP keys.

- patch 14 brings in the code from GNUTLS that allows us to parse PKCS#7 and x509 with libtasn1.

- patch 15 is our PKCS#7 and x509 parser. They're minimal and fairly strict parsers that extract only the bits we need to verify the signatures.

- patch 16 is the guts of the appended signature verifier. It uses the verifier infrastructure like pgp, and adds a number of user-friendly commands that mirror the pgp module.

- patch 17 adds tests, and patch 18 adds documentation.

3) Patch 19: Enter lockdown if in powerpc secure boot

Detect if the DT property advertising SB is set, and enter lockdown if it is. The main appended signature module now tests for lockdown to enter 'forced' mode.

Thanks to Stefan Berger for providing further review comments on v2.

I've pushed this all to
https://github.com/daxtens/grub/tree/mem+appsig-2204

This patch series is easy to experiment with. In particular, the appended signature verifier doesn't require any particular platform.

Alastair D'Silva (1):
grub-install: support embedding x509 certificates

Daniel Axtens (17):
docs/grub: Document signing grub under UEFI
docs/grub: Document signing grub with an appended signature
dl: provide a fake grub_dl_set_persistent for the emu target
pgp: factor out rsa_pad
crypto: move storage for grub_crypto_pk_* to crypto.c
posix_wrap: tweaks in preparation for libtasn1
libtasn1: import libtasn1-4.18.0
libtasn1: disable code not needed in grub
libtasn1: changes for grub compatibility
libtasn1: compile into asn1 module
test_asn1: test module for libtasn1
appended signatures: import GNUTLS's ASN.1 description files appended signatures: parse PKCS#7 signedData and X.509 certificates appended signatures: support verifying appended signatures appended signatures: verification tests
appended signatures: documentation
ieee1275: enter lockdown based on /ibm,secure-boot

Rashmica Gupta (1):
Add suport for signing grub with an appended signature

 .gitignore                                    |    1 +
 Makefile.util.def                             |    6 +
 docs/grub.texi                                |  259 +-
 grub-core/Makefile.core.def                   |   57 +
 grub-core/commands/appendedsig/appendedsig.c  |  662 +++++
 grub-core/commands/appendedsig/appendedsig.h  |  119 +
 grub-core/commands/appendedsig/asn1util.c     |  104 +
 .../commands/appendedsig/gnutls_asn1_tab.c    |  121 +
 grub-core/commands/appendedsig/pkcs7.c        |  512 ++++
 .../commands/appendedsig/pkix_asn1_tab.c      |  484 ++++
 grub-core/commands/appendedsig/x509.c         | 1082 +++++++
 grub-core/commands/pgp.c                      |   34 +-
 grub-core/kern/ieee1275/init.c                |   27 +
 grub-core/lib/crypto.c                        |    4 +
 grub-core/lib/libtasn1/COPYING                |   16 +
 grub-core/lib/libtasn1/README.md              |   98 +
 grub-core/lib/libtasn1/lib/coding.c           | 1433 ++++++++++
 grub-core/lib/libtasn1/lib/decoding.c         | 2504 +++++++++++++++++
 grub-core/lib/libtasn1/lib/element.c          | 1110 ++++++++
 grub-core/lib/libtasn1/lib/element.h          |   42 +
 grub-core/lib/libtasn1/lib/errors.c           |  103 +
 grub-core/lib/libtasn1/lib/gstr.c             |   74 +
 grub-core/lib/libtasn1/lib/gstr.h             |   50 +
 grub-core/lib/libtasn1/lib/int.h              |  221 ++
 grub-core/lib/libtasn1/lib/parser_aux.c       | 1179 ++++++++
 grub-core/lib/libtasn1/lib/parser_aux.h       |  172 ++
 grub-core/lib/libtasn1/lib/structure.c        | 1227 ++++++++
 grub-core/lib/libtasn1/lib/structure.h        |   46 +
 .../tests/CVE-2018-1000654-1_asn1_tab.h       |   32 +
 .../tests/CVE-2018-1000654-2_asn1_tab.h       |   36 +
 .../libtasn1_wrap/tests/CVE-2018-1000654.c    |   61 +
 .../lib/libtasn1_wrap/tests/Test_overflow.c   |  138 +
 .../lib/libtasn1_wrap/tests/Test_simple.c     |  207 ++
 .../lib/libtasn1_wrap/tests/Test_strings.c    |  150 +
 .../libtasn1_wrap/tests/object-id-decoding.c  |  116 +
 .../libtasn1_wrap/tests/object-id-encoding.c  |  120 +
 .../lib/libtasn1_wrap/tests/octet-string.c    |  211 ++
 .../lib/libtasn1_wrap/tests/reproducers.c     |   81 +
 grub-core/lib/libtasn1_wrap/wrap.c            |   27 +
 grub-core/lib/libtasn1_wrap/wrap_tests.c      |   76 +
 grub-core/lib/libtasn1_wrap/wrap_tests.h      |   39 +
 grub-core/lib/pkcs1_v15.c                     |   59 +
 grub-core/lib/posix_wrap/limits.h             |    1 +
 grub-core/lib/posix_wrap/stdlib.h             |    8 +
 grub-core/lib/posix_wrap/sys/types.h          |    1 +
 grub-core/tests/appended_signature_test.c     |  275 ++
 grub-core/tests/appended_signatures.h         |  975 +++++++
 grub-core/tests/lib/functional_test.c         |    1 +
 include/grub/dl.h                             |   11 +
 include/grub/file.h                           |    2 +
 include/grub/kernel.h                         |    3 +-
 include/grub/libtasn1.h                       |  641 +++++
 include/grub/lockdown.h                       |    3 +-
 include/grub/pkcs1_v15.h                      |   27 +
 include/grub/util/install.h                   |   15 +-
 include/grub/util/mkimage.h                   |    4 +-
 tests/test_asn1.in                            |   12 +
 util/grub-install-common.c                    |   37 +-
 util/grub-mkimage.c                           |   26 +-
 util/grub-mkimagexx.c                         |   39 +-
 util/mkimage.c                                |   54 +-
 61 files changed, 15161 insertions(+), 74 deletions(-)
 create mode 100644 grub-core/commands/appendedsig/appendedsig.c
 create mode 100644 grub-core/commands/appendedsig/appendedsig.h
 create mode 100644 grub-core/commands/appendedsig/asn1util.c
 create mode 100644 grub-core/commands/appendedsig/gnutls_asn1_tab.c
 create mode 100644 grub-core/commands/appendedsig/pkcs7.c
 create mode 100644 grub-core/commands/appendedsig/pkix_asn1_tab.c
 create mode 100644 grub-core/commands/appendedsig/x509.c
 create mode 100644 grub-core/lib/libtasn1/COPYING
 create mode 100644 grub-core/lib/libtasn1/README.md
 create mode 100644 grub-core/lib/libtasn1/lib/coding.c
 create mode 100644 grub-core/lib/libtasn1/lib/decoding.c
 create mode 100644 grub-core/lib/libtasn1/lib/element.c
 create mode 100644 grub-core/lib/libtasn1/lib/element.h
 create mode 100644 grub-core/lib/libtasn1/lib/errors.c
 create mode 100644 grub-core/lib/libtasn1/lib/gstr.c
 create mode 100644 grub-core/lib/libtasn1/lib/gstr.h
 create mode 100644 grub-core/lib/libtasn1/lib/int.h
 create mode 100644 grub-core/lib/libtasn1/lib/parser_aux.c
 create mode 100644 grub-core/lib/libtasn1/lib/parser_aux.h
 create mode 100644 grub-core/lib/libtasn1/lib/structure.c
 create mode 100644 grub-core/lib/libtasn1/lib/structure.h
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-1_asn1_tab.h
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-2_asn1_tab.h
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_overflow.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_simple.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_strings.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/object-id-decoding.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/object-id-encoding.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/octet-string.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/reproducers.c
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap.c
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap_tests.c
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap_tests.h
 create mode 100644 grub-core/lib/pkcs1_v15.c
 create mode 100644 grub-core/tests/appended_signature_test.c
 create mode 100644 grub-core/tests/appended_signatures.h
 create mode 100644 include/grub/libtasn1.h
 create mode 100644 include/grub/pkcs1_v15.h
 create mode 100644 tests/test_asn1.in
Signature · 1 line
2.32.0
#1 lore raw

PATCH v3 1/19 Add suport for signing grub with an appended signature

From: Rashmica Gupta <[email protected]>

Add infrastructure to allow firmware to verify the integrity of grub by use of a Linux-kernel-module-style appended signature. We initially target powerpc-ieee1275, but the code should be extensible to other platforms.

Usually these signatures are appended to a file without modifying the ELF file itself. (This is what the 'sign-file' tool does, for example.) The verifier loads the signed file from the file system and looks at the end of the file for the appended signature. However, on powerpc-ieee1275 platforms, the bootloader is often stored directly in the PReP partition as raw bytes without a file-system. This makes determining the location of an appended signature more difficult.

To address this, we add a new ELF note.

The name field of shall be the string "Appended-Signature", zero-padded to 4 byte alignment. The type field shall be 0x41536967 (the ASCII values for the string "ASig"). It must be the final section in the ELF binary.

The description shall contain the appended signature structure as defined by the Linux kernel. The description will also be padded to be a multiple of 4 bytes. The padding shall be added before the appended signature structure (not at the end) so that the final bytes of a signed ELF file are the appended signature magic.

A subsequent patch documents how to create a grub core.img validly signed under this scheme.

---

You can experiment with this code with a patched version of SLOF that verifies these signatures. You can find one at:
https://github.com/daxtens/SLOF

I will be proposing this for inclusion in a future Power Architecture Platform Reference (PAPR).

v3: Fix a nit, thanks Stefan.

---
 include/grub/util/install.h |  8 ++++++--
 include/grub/util/mkimage.h |  4 ++--
 util/grub-install-common.c  | 15 +++++++++++---
 util/grub-mkimage.c         | 11 +++++++++++
 util/grub-mkimagexx.c       | 39 ++++++++++++++++++++++++++++++++++++-
 util/mkimage.c              | 13 +++++++------
 6 files changed, 76 insertions(+), 14 deletions(-)
include/grub/util/install.h +6 -2
index 7d7445af9815..fadcce0fea7e 100644
@@ -67,6 +67,9 @@
       N_("SBAT metadata"), 0 },						\
   { "disable-shim-lock", GRUB_INSTALL_OPTIONS_DISABLE_SHIM_LOCK, 0, 0,	\
       N_("disable shim_lock verifier"), 0 },				\
+  { "appended-signature-size", GRUB_INSTALL_OPTIONS_APPENDED_SIGNATURE_SIZE,\
+    "SIZE", 0, N_("Add a note segment reserving SIZE bytes for an appended signature"), \
+    1},                                                                 \
   { "verbose", 'v', 0, 0,						\
     N_("print verbose messages."), 1 }
 
@@ -128,7 +131,8 @@ enum grub_install_options {
   GRUB_INSTALL_OPTIONS_INSTALL_CORE_COMPRESS,
   GRUB_INSTALL_OPTIONS_DTB,
   GRUB_INSTALL_OPTIONS_SBAT,
-  GRUB_INSTALL_OPTIONS_DISABLE_SHIM_LOCK
+  GRUB_INSTALL_OPTIONS_DISABLE_SHIM_LOCK,
+  GRUB_INSTALL_OPTIONS_APPENDED_SIGNATURE_SIZE
 };
 
 extern char *grub_install_source_directory;
@@ -188,7 +192,7 @@ grub_install_generate_image (const char *dir, const char *prefix,
 			     size_t npubkeys,
 			     char *config_path,
 			     const struct grub_install_image_target_desc *image_target,
-			     int note,
+			     int note, size_t appsig_size,
 			     grub_compression_t comp, const char *dtb_file,
 			     const char *sbat_path, const int disable_shim_lock);
 
include/grub/util/mkimage.h +2 -2
index 3819a67441c8..6f1da89b9b65 100644
@@ -51,12 +51,12 @@ grub_mkimage_load_image64 (const char *kernel_path,
 			   const struct grub_install_image_target_desc *image_target);
 void
 grub_mkimage_generate_elf32 (const struct grub_install_image_target_desc *image_target,
-			     int note, char **core_img, size_t *core_size,
+			     int note, size_t appsig_size, char **core_img, size_t *core_size,
 			     Elf32_Addr target_addr,
 			     struct grub_mkimage_layout *layout);
 void
 grub_mkimage_generate_elf64 (const struct grub_install_image_target_desc *image_target,
-			     int note, char **core_img, size_t *core_size,
+			     int note, size_t appsig_size, char **core_img, size_t *core_size,
 			     Elf64_Addr target_addr,
 			     struct grub_mkimage_layout *layout);
 
util/grub-install-common.c +12 -3
index 347558bf5412..b552808df70f 100644
@@ -461,10 +461,12 @@ static size_t npubkeys;
 static char *sbat;
 static int disable_shim_lock;
 static grub_compression_t compression;
+static size_t appsig_size;
 
 int
 grub_install_parse (int key, char *arg)
 {
+  const char *end;
   switch (key)
     {
     case 'C':
@@ -562,6 +564,12 @@ grub_install_parse (int key, char *arg)
       grub_util_error (_("Unrecognized compression `%s'"), arg);
     case GRUB_INSTALL_OPTIONS_GRUB_MKIMAGE:
       return 1;
+    case GRUB_INSTALL_OPTIONS_APPENDED_SIGNATURE_SIZE:
+      grub_errno = 0;
+      appsig_size = grub_strtol(arg, &end, 10);
+      if (grub_errno)
+        return 0;
+      return 1;
     default:
       return 0;
     }
@@ -661,10 +669,11 @@ grub_install_make_image_wrap_file (const char *dir, const char *prefix,
 		  " --output '%s' "
 		  " --dtb '%s' "
 		  "--sbat '%s' "
-		  "--format '%s' --compression '%s' %s %s %s\n",
+		  "--format '%s' --compression '%s' "
+		  "--appended-signature-size %zu %s %s %s\n",
 		  dir, prefix,
 		  outname, dtb ? : "", sbat ? : "", mkimage_target,
-		  compnames[compression], note ? "--note" : "",
+		  compnames[compression], appsig_size, note ? "--note" : "",
 		  disable_shim_lock ? "--disable-shim-lock" : "", s);
   free (s);
 
@@ -675,7 +684,7 @@ grub_install_make_image_wrap_file (const char *dir, const char *prefix,
   grub_install_generate_image (dir, prefix, fp, outname,
 			       modules.entries, memdisk_path,
 			       pubkeys, npubkeys, config_path, tgt,
-			       note, compression, dtb, sbat,
+			       note, appsig_size, compression, dtb, sbat,
 			       disable_shim_lock);
   while (dc--)
     grub_install_pop_module ();
util/grub-mkimage.c +11 -0
index c0d559937020..49b9410c5fa3 100644
@@ -84,6 +84,7 @@ static struct argp_option options[] = {
   {"sbat", 's', N_("FILE"), 0, N_("SBAT metadata"), 0},
   {"disable-shim-lock", GRUB_INSTALL_OPTIONS_DISABLE_SHIM_LOCK, 0, 0, N_("disable shim_lock verifier"), 0},
   {"verbose",     'v', 0,      0, N_("print verbose messages."), 0},
+  {"appended-signature-size", 'S', N_("SIZE"), 0, N_("Add a note segment reserving SIZE bytes for an appended signature"), 0},
   { 0, 0, 0, 0, 0, 0 }
 };
 
@@ -128,6 +129,7 @@ struct arguments
   char *sbat;
   int note;
   int disable_shim_lock;
+  size_t appsig_size;
   const struct grub_install_image_target_desc *image_target;
   grub_compression_t comp;
 };
@@ -138,6 +140,7 @@ argp_parser (int key, char *arg, struct argp_state *state)
   /* Get the input argument from argp_parse, which we
      know is a pointer to our arguments structure. */
   struct arguments *arguments = state->input;
+  const char *end;
 
   switch (key)
     {
@@ -170,6 +173,13 @@ argp_parser (int key, char *arg, struct argp_state *state)
       arguments->note = 1;
       break;
 
+    case 'S':
+      grub_errno = 0;
+      arguments->appsig_size = grub_strtol(arg, &end, 10);
+      if (grub_errno)
+        return 0;
+      break;
+
     case 'm':
       if (arguments->memdisk)
 	free (arguments->memdisk);
@@ -324,6 +334,7 @@ main (int argc, char *argv[])
 			       arguments.memdisk, arguments.pubkeys,
 			       arguments.npubkeys, arguments.config,
 			       arguments.image_target, arguments.note,
+			       arguments.appsig_size,
 			       arguments.comp, arguments.dtb,
 			       arguments.sbat, arguments.disable_shim_lock);
 
util/grub-mkimagexx.c +38 -1
index 1e29e255e8d2..b857c133cb58 100644
@@ -84,6 +84,15 @@ struct grub_ieee1275_note
   struct grub_ieee1275_note_desc descriptor;
 };
 
+#define GRUB_APPENDED_SIGNATURE_NOTE_NAME "Appended-Signature"
+#define GRUB_APPENDED_SIGNATURE_NOTE_TYPE 0x41536967 /* "ASig" */
+
+struct grub_appended_signature_note
+{
+  Elf32_Nhdr header;
+  char name[ALIGN_UP(sizeof (GRUB_APPENDED_SIGNATURE_NOTE_NAME), 4)];
+};
+
 #define GRUB_XEN_NOTE_NAME "Xen"
 
 struct fixup_block_list
@@ -207,7 +216,7 @@ grub_arm_reloc_jump24 (grub_uint32_t *target, Elf32_Addr sym_addr)
 
 void
 SUFFIX (grub_mkimage_generate_elf) (const struct grub_install_image_target_desc *image_target,
-				    int note, char **core_img, size_t *core_size,
+				    int note, size_t appsig_size, char **core_img, size_t *core_size,
 				    Elf_Addr target_addr,
 				    struct grub_mkimage_layout *layout)
 {
@@ -221,6 +230,12 @@ SUFFIX (grub_mkimage_generate_elf) (const struct grub_install_image_target_desc
   int shnum = 4;
   int string_size = sizeof (".text") + sizeof ("mods") + 1;
 
+  if (appsig_size)
+    {
+      phnum++;
+      footer_size += ALIGN_UP(sizeof (struct grub_appended_signature_note) + appsig_size, 4);
+    }
+
   if (image_target->id != IMAGE_LOONGSON_ELF)
     phnum += 2;
 
@@ -484,6 +499,28 @@ SUFFIX (grub_mkimage_generate_elf) (const struct grub_install_image_target_desc
       phdr->p_offset = grub_host_to_target32 (header_size + program_size);
     }
 
+  if (appsig_size) {
+    int note_size = ALIGN_UP(sizeof (struct grub_appended_signature_note) + appsig_size, 4);
+    struct grub_appended_signature_note *note_ptr = (struct grub_appended_signature_note *)
+      (elf_img + program_size + header_size + (note ? sizeof (struct grub_ieee1275_note) : 0));
+
+    note_ptr->header.n_namesz = grub_host_to_target32 (sizeof (GRUB_APPENDED_SIGNATURE_NOTE_NAME));
+    /* needs to sit at the end, so we round this up and sign some zero padding */
+    note_ptr->header.n_descsz = grub_host_to_target32 (ALIGN_UP(appsig_size, 4));
+    note_ptr->header.n_type = grub_host_to_target32 (GRUB_APPENDED_SIGNATURE_NOTE_TYPE);
+    strcpy (note_ptr->name, GRUB_APPENDED_SIGNATURE_NOTE_NAME);
+
+    phdr++;
+    phdr->p_type = grub_host_to_target32 (PT_NOTE);
+    phdr->p_flags = grub_host_to_target32 (PF_R);
+    phdr->p_align = grub_host_to_target32 (image_target->voidp_sizeof);
+    phdr->p_vaddr = 0;
+    phdr->p_paddr = 0;
+    phdr->p_filesz = grub_host_to_target32 (note_size);
+    phdr->p_memsz = 0;
+    phdr->p_offset = grub_host_to_target32 (header_size + program_size + (note ? sizeof (struct grub_ieee1275_note) : 0));
+  }
+
   {
     char *str_start = (elf_img + sizeof (*ehdr) + phnum * sizeof (*phdr)
 		       + shnum * sizeof (*shdr));
util/mkimage.c +7 -6
index 21c2db736283..3244ae403701 100644
@@ -869,8 +869,9 @@ grub_install_generate_image (const char *dir, const char *prefix,
 			     char *memdisk_path, char **pubkey_paths,
 			     size_t npubkeys, char *config_path,
 			     const struct grub_install_image_target_desc *image_target,
-			     int note, grub_compression_t comp, const char *dtb_path,
-			     const char *sbat_path, int disable_shim_lock)
+			     int note, size_t appsig_size, grub_compression_t comp,
+			     const char *dtb_path, const char *sbat_path, 
+			     int disable_shim_lock)
 {
   char *kernel_img, *core_img;
   size_t total_module_size, core_size;
@@ -1773,11 +1774,11 @@ grub_install_generate_image (const char *dir, const char *prefix,
 	else
 	  target_addr = image_target->link_addr;
 	if (image_target->voidp_sizeof == 4)
-	  grub_mkimage_generate_elf32 (image_target, note, &core_img, &core_size,
-				       target_addr, &layout);
+	  grub_mkimage_generate_elf32 (image_target, note, appsig_size, &core_img,
+				       &core_size, target_addr, &layout);
 	else
-	  grub_mkimage_generate_elf64 (image_target, note, &core_img, &core_size,
-				       target_addr, &layout);
+	  grub_mkimage_generate_elf64 (image_target, note, appsig_size, &core_img,
+				       &core_size, target_addr, &layout);
       }
       break;
     }
Signature · 1 line
2.32.0
#2 lore raw

PATCH v3 2/19 docs/grub: Document signing grub under UEFI

In reply to Daniel Axtens

Before adding information about how grub is signed with an appended signature scheme, it's worth adding some information about how it can currently be signed for UEFI.

---
 docs/grub.texi | 22 +++++++++++++++++++++-
 1 file changed, 21 insertions(+), 1 deletion(-)
docs/grub.texi +21 -1
index 9835c878affc..fdf2884b814f 100644
@@ -5859,6 +5859,7 @@ environment variables and commands are listed in the same order.
 * Secure Boot Advanced Targeting::   Embedded information for generation number based revocation
 * Measured Boot::                    Measuring boot components
 * Lockdown::                         Lockdown when booting on a secure setup
+* Signing GRUB itself::              Ensuring the integrity of the GRUB core image
 @end menu
 
 @node Authentication and authorisation
@@ -5937,7 +5938,7 @@ commands.
 
 GRUB's @file{core.img} can optionally provide enforcement that all files
 subsequently read from disk are covered by a valid digital signature.
-This document does @strong{not} cover how to ensure that your
+This section does @strong{not} cover how to ensure that your
 platform's firmware (e.g., Coreboot) validates @file{core.img}.
 
 If environment variable @code{check_signatures}
@@ -6099,6 +6100,25 @@ be restricted and some operations/commands cannot be executed.
 The @samp{lockdown} variable is set to @samp{y} when the GRUB is locked down.
 Otherwise it does not exit.
 
+@node Signing GRUB itself
+@section Signing GRUB itself
+
+To ensure a complete secure-boot chain, there must be a way for the code that
+loads GRUB to verify the integrity of the core image.
+
+This is ultimately platform-specific and individual platforms can define their
+own mechanisms. However, there are general-purpose mechanisms that can be used
+with GRUB.
+
+@section Signing GRUB for UEFI secure boot
+
+On UEFI platforms, @file{core.img} is a PE binary. Therefore, it can be signed
+with a tool such as @command{pesign} or @command{sbsign}. Refer to the
+suggestions in @pxref{UEFI secure boot and shim} to ensure that the final
+image works under UEFI secure boot and can maintain the secure-boot chain. It
+will also be necessary to enrol the public key used into a relevant firmware
+key database.
+
 @node Platform limitations
 @chapter Platform limitations
 
Signature · 1 line
2.32.0
#3 lore raw

PATCH v3 3/19 docs/grub: Document signing grub with an appended signature

In reply to Daniel Axtens

Signing grub for firmware that verifies an appended signature is a bit fiddly. I don't want people to have to figure it out from scratch so document it here.

---
 docs/grub.texi | 42 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)
docs/grub.texi +42 -0
index fdf2884b814f..a7f5f6cd154c 100644
@@ -6119,6 +6119,48 @@ image works under UEFI secure boot and can maintain the secure-boot chain. It
 will also be necessary to enrol the public key used into a relevant firmware
 key database.
 
+@section Signing GRUB with an appended signature
+
+The @file{core.img} itself can be signed with a Linux kernel module-style
+appended signature.
+
+To support IEEE1275 platforms where the boot image is often loaded directly
+from a disk partition rather than from a file system, the @file{core.img}
+can specify the size and location of the appended signature with an ELF
+note added by @command{grub-install}.
+
+An image can be signed this way using the @command{sign-file} command from
+the Linux kernel:
+
+@example
+@group
+# grub.key is your private key and certificate.der is your public key
+
+# Determine the size of the appended signature. It depends on the signing
+# certificate and the hash algorithm
+touch empty
+sign-file SHA256 grub.key certificate.der empty empty.sig
+SIG_SIZE=`stat -c '%s' empty.sig`
+rm empty empty.sig
+
+# Build a grub image with $SIG_SIZE reserved for the signature
+grub-install --appended-signature-size $SIG_SIZE --modules="..." ...
+
+# Replace the reserved size with a signature:
+# cut off the last $SIG_SIZE bytes with truncate's minus modifier
+truncate -s -$SIG_SIZE /boot/grub/powerpc-ieee1275/core.elf core.elf.unsigned
+# sign the trimmed file with an appended signature, restoring the correct size
+sign-file SHA256 grub.key certificate.der core.elf.unsigned core.elf.signed
+
+# Don't forget to install the signed image as required
+# (e.g. on powerpc-ieee1275, to the PReP partition)
+@end group
+@end example
+
+As with UEFI secure boot, it is necessary to build in the required modules,
+or sign them separately.
+
+
 @node Platform limitations
 @chapter Platform limitations
 
Signature · 1 line
2.32.0
#4 lore raw

PATCH v3 4/19 dl: provide a fake grub_dl_set_persistent for the emu target

In reply to Daniel Axtens

Trying to start grub-emu with a module that calls grub_dl_set_persistent will crash because grub-emu fakes modules and passes NULL to the module init function.

Provide an empty function for the emu case.

Fixes ee7808e2197c (dl: Add support for persistent modules)
---
 include/grub/dl.h | 11 +++++++++++
 1 file changed, 11 insertions(+)
include/grub/dl.h +11 -0
index acb4d42327d7..ff1e291243a7 100644
@@ -242,11 +242,22 @@ grub_dl_get (const char *name)
   return 0;
 }
 
+#ifdef GRUB_MACHINE_EMU
+/*
+ * Under grub-emu, modules are faked and NULL is passed to GRUB_MOD_INIT.
+ * So we fake this out to avoid a NULL deref.
+ */
+static inline void
+grub_dl_set_persistent (grub_dl_t mod __attribute__((unused)))
+{
+}
+#else
 static inline void
 grub_dl_set_persistent (grub_dl_t mod)
 {
   mod->persistent = 1;
 }
+#endif
 
 static inline int
 grub_dl_is_persistent (grub_dl_t mod)
Signature · 1 line
2.32.0
#5 lore raw

PATCH v3 5/19 pgp: factor out rsa_pad

In reply to Daniel Axtens

rsa_pad does the PKCS#1 v1.5 padding for the RSA signature scheme. We want to use it in other RSA signature verification applications.

I considered and rejected putting it in lib/crypto.c. That file doesn't currently require any MPI functions, but rsa_pad does. That's not so much of a problem for the grub kernel and modules, but crypto.c also gets built into all the grub utilities. So - despite the utils not using any asymmetric ciphers - we would need to built the entire MPI infrastructure in to them.

A better and simpler solution is just to spin rsa_pad out into its own PKCS#1 v1.5 module.

---
 grub-core/Makefile.core.def |  8 +++++
 grub-core/commands/pgp.c    | 28 ++----------------
 grub-core/lib/pkcs1_v15.c   | 59 +++++++++++++++++++++++++++++++++++++
 include/grub/pkcs1_v15.h    | 27 +++++++++++++++++
 4 files changed, 96 insertions(+), 26 deletions(-)
 create mode 100644 grub-core/lib/pkcs1_v15.c
 create mode 100644 include/grub/pkcs1_v15.h
grub-core/Makefile.core.def +8 -0
index 7159948721e1..5af8b780c2a1 100644
@@ -2474,6 +2474,14 @@ module = {
   cppflags = '$(CPPFLAGS_GCRY)';
 };
 
+module = {
+  name = pkcs1_v15;
+  common = lib/pkcs1_v15.c;
+
+  cflags = '$(CFLAGS_GCRY) -Wno-redundant-decls -Wno-sign-compare';
+  cppflags = '$(CPPFLAGS_GCRY)';
+};
+
 module = {
   name = all_video;
   common = lib/fake_module.c;
grub-core/commands/pgp.c +2 -26
index c6766f044aaa..b084dc9a22f5 100644
@@ -24,6 +24,7 @@
 #include <grub/file.h>
 #include <grub/command.h>
 #include <grub/crypto.h>
+#include <grub/pkcs1_v15.h>
 #include <grub/i18n.h>
 #include <grub/gcrypt/gcrypt.h>
 #include <grub/pubkey.h>
@@ -411,32 +412,7 @@ static int
 rsa_pad (gcry_mpi_t *hmpi, grub_uint8_t *hval,
 	 const gcry_md_spec_t *hash, struct grub_public_subkey *sk)
 {
-  grub_size_t tlen, emlen, fflen;
-  grub_uint8_t *em, *emptr;
-  unsigned nbits = gcry_mpi_get_nbits (sk->mpis[0]);
-  int ret;
-  tlen = hash->mdlen + hash->asnlen;
-  emlen = (nbits + 7) / 8;
-  if (emlen < tlen + 11)
-    return 1;
-
-  em = grub_malloc (emlen);
-  if (!em)
-    return 1;
-
-  em[0] = 0x00;
-  em[1] = 0x01;
-  fflen = emlen - tlen - 3;
-  for (emptr = em + 2; emptr < em + 2 + fflen; emptr++)
-    *emptr = 0xff;
-  *emptr++ = 0x00;
-  grub_memcpy (emptr, hash->asnoid, hash->asnlen);
-  emptr += hash->asnlen;
-  grub_memcpy (emptr, hval, hash->mdlen);
-
-  ret = gcry_mpi_scan (hmpi, GCRYMPI_FMT_USG, em, emlen, 0);
-  grub_free (em);
-  return ret;
+  return grub_crypto_rsa_pad(hmpi, hval, hash, sk->mpis[0]);
 }
 
 struct grub_pubkey_context
grub-core/lib/pkcs1_v15.c new file +59 -0

59 lines not on this page · raw message

include/grub/pkcs1_v15.h new file +27 -0
new file mode 100644
index 000000000000..5c338c84a158
@@ -0,0 +1,27 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2013  Free Software Foundation, Inc.
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/*
+ * Given a hash value 'hval', of hash specification 'hash', perform
+ * the EMSA-PKCS1-v1_5 padding suitable for a key with modulus 'mod'
+ * (See RFC 8017 s 9.2)
+ */
+gcry_err_code_t
+grub_crypto_rsa_pad (gcry_mpi_t * hmpi, grub_uint8_t * hval,
+		     const gcry_md_spec_t * hash, gcry_mpi_t mod);
+
Signature · 1 line
2.32.0
#6 lore raw

PATCH v3 6/19 crypto: move storage for grub_crypto_pk_* to crypto.c

In reply to Daniel Axtens

The way gcry_rsa and friends (the asymmetric ciphers) are loaded for the pgp module is a bit quirky.

include/grub/crypto.h contains:
extern struct gcry_pk_spec *grub_crypto_pk_rsa;

commands/pgp.c contains the actual storage:
struct gcry_pk_spec *grub_crypto_pk_rsa;

And the module itself saves to the storage in pgp.c:
GRUB_MOD_INIT(gcry_rsa)

  {
    grub_crypto_pk_rsa = &_gcry_pubkey_spec_rsa;

}

This is annoying: gcry_rsa now has a dependency on pgp!

We want to be able to bring in gcry_rsa without bringing in PGP, so move the storage to crypto.c.

Previously, gcry_rsa depended on pgp and mpi. Now it depends on crypto and mpi. As pgp depends on crypto, this doesn't add any new module dependencies using the PGP verfier.

[FWIW, the story is different for the symmetric ciphers. cryptodisk and friends (zfs encryption etc) use grub_crypto_lookup_cipher_by_name() to get a cipher handle. That depends on grub_ciphers being populated by people calling grub_cipher_register. import_gcry.py ensures that the symmetric ciphers call it.]

---
 grub-core/commands/pgp.c | 4 ----
 grub-core/lib/crypto.c   | 4 ++++
 2 files changed, 4 insertions(+), 4 deletions(-)
grub-core/commands/pgp.c +0 -4
index b084dc9a22f5..a45c2213c4ac 100644
@@ -147,10 +147,6 @@ const char *hashes[] = {
   [0x0b] = "sha224"
 };
 
-struct gcry_pk_spec *grub_crypto_pk_dsa;
-struct gcry_pk_spec *grub_crypto_pk_ecdsa;
-struct gcry_pk_spec *grub_crypto_pk_rsa;
-
 static int
 dsa_pad (gcry_mpi_t *hmpi, grub_uint8_t *hval,
 	 const gcry_md_spec_t *hash, struct grub_public_subkey *sk);
grub-core/lib/crypto.c +4 -0
index 396f7641080f..d53ddbe2c441 100644
@@ -121,6 +121,10 @@ grub_md_unregister (gcry_md_spec_t *cipher)
       }
 }
 
+struct gcry_pk_spec *grub_crypto_pk_dsa;
+struct gcry_pk_spec *grub_crypto_pk_ecdsa;
+struct gcry_pk_spec *grub_crypto_pk_rsa;
+
 void
 grub_crypto_hash (const gcry_md_spec_t *hash, void *out, const void *in,
 		  grub_size_t inlen)
Signature · 1 line
2.32.0
#7 lore raw

PATCH v3 7/19 posix_wrap: tweaks in preparation for libtasn1

In reply to Daniel Axtens

- Define SIZEOF_UNSIGNED_LONG_INT, it's the same as SIZEOF_UNSIGNED_LONG.

- Define WORD_BIT, the size in bits of an int. This is a defined in the Single Unix Specification and in gnulib's limits.h. gnulib assumes it's 32 bits on all our platforms, including 64 bit platforms, so we also use that value.

- Provide strto[u]l[l] preprocessor macros that resolve to grub_strto[u]l[l]. To avoid gcrypt redefining strtoul, we also define HAVE_STRTOUL here.

---
 grub-core/lib/posix_wrap/limits.h    | 1 +
 grub-core/lib/posix_wrap/stdlib.h    | 8 ++++++++
 grub-core/lib/posix_wrap/sys/types.h | 1 +
 3 files changed, 10 insertions(+)
grub-core/lib/posix_wrap/limits.h +1 -0
index 26918c8a01bc..4be7b4080633 100644
@@ -41,5 +41,6 @@
 #define LONG_MAX GRUB_LONG_MAX
 
 #define CHAR_BIT 8
+#define WORD_BIT 32
 
 #endif
grub-core/lib/posix_wrap/stdlib.h +8 -0
index 148e9d94bde0..e5093a9ee545 100644
@@ -58,4 +58,12 @@ abs (int c)
   return (c >= 0) ? c : -c;
 }
 
+#define strtol grub_strtol
+
+/* for libgcrypt */
+#define HAVE_STRTOUL
+#define strtoul grub_strtoul
+
+#define strtoull grub_strtoull
+
 #endif
grub-core/lib/posix_wrap/sys/types.h +1 -0
index eeda543c47e2..2f3e865495ae 100644
@@ -50,6 +50,7 @@ typedef grub_uint8_t byte;
 typedef grub_addr_t uintptr_t;
 
 #define SIZEOF_UNSIGNED_LONG GRUB_CPU_SIZEOF_LONG
+#define SIZEOF_UNSIGNED_LONG_INT GRUB_CPU_SIZEOF_LONG
 #define SIZEOF_UNSIGNED_INT 4
 #define SIZEOF_UNSIGNED_LONG_LONG 8
 #define SIZEOF_UNSIGNED_SHORT 2
Signature · 1 line
2.32.0
#8 lore raw

PATCH v3 8/19 libtasn1: import libtasn1-4.18.0

In reply to Daniel Axtens

Import a very trimmed-down set of libtasn1 files:

pushd /tmp
wget https://ftp.gnu.org/gnu/libtasn1/libtasn1-4.18.0.tar.gz
tar -xf libtasn1-4.18.0.tar.gz
popd
pushd grub-core/lib
rm -rf libtasn1
mkdir libtasn1
cp /tmp/libtasn1-4.18.0/{README.md,COPYING} libtasn1/
mkdir libtasn1/lib
cp /tmp/libtasn1-4.18.0/lib/{coding.c,decoding.c,element.c,element.h,errors.c,gstr.c,gstr.h,int.h,parser_aux.c,parser_aux.h,structure.c,structure.h} libtasn1/lib cp /tmp/libtasn1-4.18.0/lib/includes/libtasn1.h ../../include/grub/
git add libtasn1/ ../../include/grub/libtasn1.h
popd

---
v3: move from libtasn1-4.16.0 to libtasn1-4.18.0 Thanks to the folks at SUSE for pointing this out.

---
 grub-core/lib/libtasn1/COPYING          |   16 +
 grub-core/lib/libtasn1/README.md        |   98 +
 grub-core/lib/libtasn1/lib/coding.c     | 1425 +++++++++++++
 grub-core/lib/libtasn1/lib/decoding.c   | 2501 +++++++++++++++++++++++
 grub-core/lib/libtasn1/lib/element.c    | 1109 ++++++++++
 grub-core/lib/libtasn1/lib/element.h    |   42 +
 grub-core/lib/libtasn1/lib/errors.c     |  100 +
 grub-core/lib/libtasn1/lib/gstr.c       |   74 +
 grub-core/lib/libtasn1/lib/gstr.h       |   50 +
 grub-core/lib/libtasn1/lib/int.h        |  221 ++
 grub-core/lib/libtasn1/lib/parser_aux.c | 1178 +++++++++++
 grub-core/lib/libtasn1/lib/parser_aux.h |  172 ++
 grub-core/lib/libtasn1/lib/structure.c  | 1225 +++++++++++
 grub-core/lib/libtasn1/lib/structure.h  |   46 +
 include/grub/libtasn1.h                 |  639 ++++++
 15 files changed, 8896 insertions(+)
 create mode 100644 grub-core/lib/libtasn1/COPYING
 create mode 100644 grub-core/lib/libtasn1/README.md
 create mode 100644 grub-core/lib/libtasn1/lib/coding.c
 create mode 100644 grub-core/lib/libtasn1/lib/decoding.c
 create mode 100644 grub-core/lib/libtasn1/lib/element.c
 create mode 100644 grub-core/lib/libtasn1/lib/element.h
 create mode 100644 grub-core/lib/libtasn1/lib/errors.c
 create mode 100644 grub-core/lib/libtasn1/lib/gstr.c
 create mode 100644 grub-core/lib/libtasn1/lib/gstr.h
 create mode 100644 grub-core/lib/libtasn1/lib/int.h
 create mode 100644 grub-core/lib/libtasn1/lib/parser_aux.c
 create mode 100644 grub-core/lib/libtasn1/lib/parser_aux.h
 create mode 100644 grub-core/lib/libtasn1/lib/structure.c
 create mode 100644 grub-core/lib/libtasn1/lib/structure.h
 create mode 100644 include/grub/libtasn1.h
grub-core/lib/libtasn1/COPYING new file +16 -0
new file mode 100644
index 000000000000..e8b3628db9b8
@@ -0,0 +1,16 @@
+LICENSING
+=========
+
+The libtasn1 library is released under the GNU Lesser General Public
+License (LGPL) version 2.1 or later; see [COPYING.LESSER](doc/COPYING.LESSER)
+for the license terms.
+
+The GNU LGPL applies to the main libtasn1 library, while the
+included applications library are under the GNU GPL version 3.
+The libtasn1 library is located in the lib directory, while the applications
+in src/.
+
+The documentation in doc/ is under the GNU FDL license 1.3.
+
+For any copyright year range specified as YYYY-ZZZZ in this package
+note that the range specifies every single year in that closed interval.
grub-core/lib/libtasn1/README.md new file +98 -0

98 lines not on this page · raw message

grub-core/lib/libtasn1/lib/coding.c new file +1425 -0

1,425 lines not on this page · raw message

grub-core/lib/libtasn1/lib/decoding.c new file +2501 -0

1,461 lines not on this page · raw message

grub-core/lib/libtasn1/lib/element.c new file +1109 -0

1,109 lines not on this page · raw message

grub-core/lib/libtasn1/lib/element.h new file +42 -0

42 lines not on this page · raw message

grub-core/lib/libtasn1/lib/errors.c new file +100 -0

100 lines not on this page · raw message

grub-core/lib/libtasn1/lib/gstr.c new file +74 -0

74 lines not on this page · raw message

grub-core/lib/libtasn1/lib/gstr.h new file +50 -0

50 lines not on this page · raw message

grub-core/lib/libtasn1/lib/int.h new file +221 -0

221 lines not on this page · raw message

grub-core/lib/libtasn1/lib/parser_aux.c new file +1178 -0

1,178 lines not on this page · raw message

grub-core/lib/libtasn1/lib/parser_aux.h new file +172 -0

172 lines not on this page · raw message

grub-core/lib/libtasn1/lib/structure.c new file +1225 -0

1,225 lines not on this page · raw message

grub-core/lib/libtasn1/lib/structure.h new file +46 -0

46 lines not on this page · raw message

include/grub/libtasn1.h new file +639 -0

639 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.32.0

Part of the diff is not shown here. View the raw message.

#9 lore raw

PATCH v3 9/19 libtasn1: disable code not needed in grub

In reply to Daniel Axtens

We don't expect to be able to write ASN.1, only read it, so we can disable some code.

Do that with #if 0/#endif, rather than deletion. This means that the difference between upstream and grub is smaller, which should make updating libtasn1 easier in the future.

With these exclusions we also avoid the need for minmax.h, which is convenient because it means we don't have to import it from gnulib.

---
 grub-core/lib/libtasn1/lib/coding.c    | 12 ++++++++++--
 grub-core/lib/libtasn1/lib/decoding.c  |  2 ++
 grub-core/lib/libtasn1/lib/element.c   |  4 ++--
 grub-core/lib/libtasn1/lib/errors.c    |  3 +++
 grub-core/lib/libtasn1/lib/structure.c | 10 ++++++----
 include/grub/libtasn1.h                | 15 +++++++++++++++
 6 files changed, 38 insertions(+), 8 deletions(-)
grub-core/lib/libtasn1/lib/coding.c +10 -2
index 671104f63f56..b3d82671016d 100644
@@ -30,11 +30,11 @@
 #include "parser_aux.h"
 #include <gstr.h>
 #include "element.h"
-#include "minmax.h"
 #include <structure.h>
 
 #define MAX_TAG_LEN 16
 
+#if 0
 /******************************************************/
 /* Function : _asn1_error_description_value_not_found */
 /* Description: creates the ErrorDescription string   */
@@ -58,6 +58,7 @@ _asn1_error_description_value_not_found (asn1_node node,
   Estrcat (ErrorDescription, "' not found");
 
 }
+#endif
 
 /**
  * asn1_length_der:
@@ -244,6 +245,7 @@ asn1_encode_simple_der (unsigned int etype, const unsigned char *str,
   return ASN1_SUCCESS;
 }
 
+#if 0
 /******************************************************/
 /* Function : _asn1_time_der                          */
 /* Description: creates the DER coding for a TIME     */
@@ -278,7 +280,7 @@ _asn1_time_der (unsigned char *str, int str_len, unsigned char *der,
 
   return ASN1_SUCCESS;
 }
-
+#endif
 
 /*
 void
@@ -519,6 +521,7 @@ asn1_bit_der (const unsigned char *str, int bit_len,
 }
 
 
+#if 0
 /******************************************************/
 /* Function : _asn1_complete_explicit_tag             */
 /* Description: add the length coding to the EXPLICIT */
@@ -595,6 +598,7 @@ _asn1_complete_explicit_tag (asn1_node node, unsigned char *der,
 
   return ASN1_SUCCESS;
 }
+#endif
 
 const tag_and_class_st _asn1_tags[] = {
   [ASN1_ETYPE_GENERALSTRING] =
@@ -647,6 +651,8 @@ const tag_and_class_st _asn1_tags[] = {
 
 unsigned int _asn1_tags_size = sizeof (_asn1_tags) / sizeof (_asn1_tags[0]);
 
+
+#if 0
 /******************************************************/
 /* Function : _asn1_insert_tag_der                    */
 /* Description: creates the DER coding of tags of one */
@@ -1423,3 +1429,5 @@ error:
   asn1_delete_structure (&node);
   return err;
 }
+
+#endif
\ No newline at end of file
grub-core/lib/libtasn1/lib/decoding.c +2 -0
index b1a35356f88e..b8130b956459 100644
@@ -1620,6 +1620,7 @@ asn1_der_decoding (asn1_node * element, const void *ider, int ider_len,
   return asn1_der_decoding2 (element, ider, &ider_len, 0, errorDescription);
 }
 
+#if 0
 /**
  * asn1_der_decoding_element:
  * @structure: pointer to an ASN1 structure
@@ -1650,6 +1651,7 @@ asn1_der_decoding_element (asn1_node * structure, const char *elementName,
 {
   return asn1_der_decoding (structure, ider, len, errorDescription);
 }
+#endif
 
 /**
  * asn1_der_decoding_startEnd:
grub-core/lib/libtasn1/lib/element.c +2 -2
index 86e64f2cfc63..8cd6b662cc6b 100644
@@ -191,7 +191,7 @@ _asn1_append_sequence_set (asn1_node node, struct node_tail_cache_st *pcache)
   return ASN1_SUCCESS;
 }
 
-
+#if 0
 /**
  * asn1_write_value:
  * @node_root: pointer to a structure
@@ -646,7 +646,7 @@ asn1_write_value (asn1_node node_root, const char *name,
 
   return ASN1_SUCCESS;
 }
-
+#endif
 
 #define PUT_VALUE( ptr, ptr_size, data, data_size) \
 	*len = data_size; \
grub-core/lib/libtasn1/lib/errors.c +3 -0
index 4dadbd96d6b4..41921d813620 100644
@@ -57,6 +57,8 @@ static const libtasn1_error_entry error_algorithms[] = {
   {0, 0}
 };
 
+
+#if 0
 /**
  * asn1_perror:
  * @error: is an error returned by a libtasn1 function.
@@ -73,6 +75,7 @@ asn1_perror (int error)
   const char *str = asn1_strerror (error);
   fprintf (stderr, "LIBTASN1 ERROR: %s\n", str ? str : "(null)");
 }
+#endif
 
 /**
  * asn1_strerror:
grub-core/lib/libtasn1/lib/structure.c +6 -4
index c0802202e5b0..45435732ce90 100644
@@ -76,7 +76,7 @@ _asn1_find_left (asn1_node_const node)
   return node->left;
 }
 
-
+#if 0
 int
 _asn1_create_static_structure (asn1_node_const pointer,
 			       char *output_file_name, char *vector_name)
@@ -155,7 +155,7 @@ _asn1_create_static_structure (asn1_node_const pointer,
 
   return ASN1_SUCCESS;
 }
-
+#endif
 
 /**
  * asn1_array2tree:
@@ -721,7 +721,7 @@ asn1_create_element (asn1_node_const definitions, const char *source_name,
   return res;
 }
 
-
+#if 0
 /**
  * asn1_print_structure:
  * @out: pointer to the output file (e.g. stdout).
@@ -1062,7 +1062,7 @@ asn1_print_structure (FILE * out, asn1_node_const structure, const char *name,
 	}
     }
 }
-
+#endif
 
 
 /**
@@ -1158,6 +1158,7 @@ asn1_find_structure_from_oid (asn1_node_const definitions,
   return NULL;			/* ASN1_ELEMENT_NOT_FOUND; */
 }
 
+#if 0
 /**
  * asn1_copy_node:
  * @dst: Destination asn1 node.
@@ -1207,6 +1208,7 @@ asn1_copy_node (asn1_node dst, const char *dst_name,
 
   return result;
 }
+#endif
 
 /**
  * asn1_dup_node:
include/grub/libtasn1.h +15 -0
index fc695a28a295..0c3a4488101a 100644
@@ -314,6 +314,8 @@ extern "C"
 /*  Functions definitions          */
 /***********************************/
 
+/* These functions are not used in grub and should not be referenced. */
+# if 0
   extern ASN1_API int
     asn1_parser2tree (const char *file,
 		      asn1_node * definitions, char *error_desc);
@@ -322,14 +324,17 @@ extern "C"
     asn1_parser2array (const char *inputFileName,
 		       const char *outputFileName,
 		       const char *vectorName, char *error_desc);
+# endif
 
   extern ASN1_API int
     asn1_array2tree (const asn1_static_node * array,
 		     asn1_node * definitions, char *errorDescription);
 
+# if 0
   extern ASN1_API void
     asn1_print_structure (FILE * out, asn1_node_const structure,
 			  const char *name, int mode);
+# endif
 
   extern ASN1_API int
     asn1_create_element (asn1_node_const definitions,
@@ -343,9 +348,11 @@ extern "C"
   extern ASN1_API int
     asn1_delete_element (asn1_node structure, const char *element_name);
 
+# if 0
   extern ASN1_API int
     asn1_write_value (asn1_node node_root, const char *name,
 		      const void *ivalue, int len);
+# endif
 
   extern ASN1_API int
     asn1_read_value (asn1_node_const root, const char *name,
@@ -362,9 +369,11 @@ extern "C"
     asn1_number_of_elements (asn1_node_const element, const char *name,
 			     int *num);
 
+# if 0
   extern ASN1_API int
     asn1_der_coding (asn1_node_const element, const char *name,
 		     void *ider, int *len, char *ErrorDescription);
+# endif
 
   extern ASN1_API int
     asn1_der_decoding2 (asn1_node * element, const void *ider,
@@ -375,6 +384,7 @@ extern "C"
     asn1_der_decoding (asn1_node * element, const void *ider,
 		       int ider_len, char *errorDescription);
 
+# if 0
 /* Do not use. Use asn1_der_decoding() instead. */
   extern ASN1_API int
     asn1_der_decoding_element (asn1_node * structure,
@@ -382,6 +392,7 @@ extern "C"
 			       const void *ider, int len,
 			       char *errorDescription)
     _ASN1_GCC_ATTR_DEPRECATED;
+# endif
 
   extern ASN1_API int
     asn1_der_decoding_startEnd (asn1_node element,
@@ -407,12 +418,16 @@ extern "C"
 							    const char
 							    *oidValue);
 
+# if 0
     __LIBTASN1_PURE__
     extern ASN1_API const char *asn1_check_version (const char *req_version);
+# endif
 
   __LIBTASN1_PURE__ extern ASN1_API const char *asn1_strerror (int error);
 
+# if 0
   extern ASN1_API void asn1_perror (int error);
+# endif
 
 # define ASN1_MAX_TAG_SIZE 4
 # define ASN1_MAX_LENGTH_SIZE 9
Signature · 1 line
2.32.0
#10 lore raw

PATCH v3 10/19 libtasn1: changes for grub compatibility

In reply to Daniel Axtens

Do a few things to make libtasn1 compile as part of grub:

- redefine _asn1_strcat. grub removed strcat so replace it with the appropriate calls to memcpy and strlen. Use this internally where strcat was used.

- replace c_isdigit with grub_isdigit (and don't import c-ctype from gnulib) grub_isdigit provides the same functionality as c_isdigit: it determines if the input is an ASCII digit without regard for locale.

- replace GL_ATTRIBUTE_PURE with __attribute__((pure)) which been supported since gcc-2.96. This avoids messing around with gnulib.

- adjust libtasn1.h: drop the ASN1_API logic, it's not needed for our modules. Unconditionally support const and pure attributes and adjust header paths.

- adjust header paths to "grub/libtasn1.h".

- replace a 64 bit division with a call to grub_divmod64, preventing creation of __udivdi3 calls on 32 bit platforms.

---

v2: Clean up strcat handling, thanks Stefan Berger.

---
 grub-core/lib/libtasn1/lib/decoding.c   | 11 +++++-----
 grub-core/lib/libtasn1/lib/element.c    |  3 ++-
 grub-core/lib/libtasn1/lib/gstr.c       |  4 ++--
 grub-core/lib/libtasn1/lib/int.h        |  4 ++--
 grub-core/lib/libtasn1/lib/parser_aux.c |  7 +++---
 include/grub/libtasn1.h                 | 29 +++++++------------------
 6 files changed, 24 insertions(+), 34 deletions(-)
grub-core/lib/libtasn1/lib/decoding.c +6 -5
index b8130b956459..beeb6a176d6f 100644
@@ -32,7 +32,8 @@
 #include <element.h>
 #include <limits.h>
 #include <intprops.h>
-#include "c-ctype.h"
+
+#define c_isdigit grub_isdigit
 
 #ifdef DEBUG
 # define warn() fprintf(stderr, "%s: %d\n", __func__, __LINE__)
@@ -2016,8 +2017,8 @@ asn1_expand_octet_string (asn1_node_const definitions, asn1_node * element,
 	  (p2->type & CONST_ASSIGN))
 	{
 	  strcpy (name, definitions->name);
-	  strcat (name, ".");
-	  strcat (name, p2->name);
+	  _asn1_strcat (name, ".");
+	  _asn1_strcat (name, p2->name);
 
 	  len = sizeof (value);
 	  result = asn1_read_value (definitions, name, value, &len);
@@ -2034,8 +2035,8 @@ asn1_expand_octet_string (asn1_node_const definitions, asn1_node * element,
 	      if (p2)
 		{
 		  strcpy (name, definitions->name);
-		  strcat (name, ".");
-		  strcat (name, p2->name);
+		  _asn1_strcat (name, ".");
+		  _asn1_strcat (name, p2->name);
 
 		  result = asn1_create_element (definitions, name, &aux);
 		  if (result == ASN1_SUCCESS)
grub-core/lib/libtasn1/lib/element.c +2 -1
index 8cd6b662cc6b..150b9b3772b3 100644
@@ -30,9 +30,10 @@
 #include "parser_aux.h"
 #include <gstr.h>
 #include "structure.h"
-#include "c-ctype.h"
 #include "element.h"
 
+#define c_isdigit grub_isdigit
+
 void
 _asn1_hierarchical_name (asn1_node_const node, char *name, int name_size)
 {
grub-core/lib/libtasn1/lib/gstr.c +2 -2
index 1475ed51b74c..b729089db298 100644
@@ -36,13 +36,13 @@ _asn1_str_cat (char *dest, size_t dest_tot_size, const char *src)
 
   if (dest_tot_size - dest_size > str_size)
     {
-      strcat (dest, src);
+      _asn1_strcat (dest, src);
     }
   else
     {
       if (dest_tot_size > dest_size)
 	{
-	  strncat (dest, src, (dest_tot_size - dest_size) - 1);
+	  memcpy (dest + dest_size, src, (dest_tot_size - dest_size) - 1);
 	  dest[dest_tot_size - 1] = 0;
 	}
     }
grub-core/lib/libtasn1/lib/int.h +2 -2
index 404cd156232e..edfe84a0e2d6 100644
@@ -35,7 +35,7 @@
 #  include <sys/types.h>
 # endif
 
-# include <libtasn1.h>
+# include "grub/libtasn1.h"
 
 # define ASN1_SMALL_VALUE_SIZE 16
 
@@ -115,7 +115,7 @@ extern const tag_and_class_st _asn1_tags[];
 # define _asn1_strtoul(n,e,b) strtoul((const char *) n, e, b)
 # define _asn1_strcmp(a,b) strcmp((const char *)a, (const char *)b)
 # define _asn1_strcpy(a,b) strcpy((char *)a, (const char *)b)
-# define _asn1_strcat(a,b) strcat((char *)a, (const char *)b)
+# define _asn1_strcat(a,b) memcpy((char *)a + strlen((const char *)a), (const char *)b, strlen((const char *)b) + 1)
 
 # if SIZEOF_UNSIGNED_LONG_INT == 8
 #  define _asn1_strtou64(n,e,b) strtoul((const char *) n, e, b)
grub-core/lib/libtasn1/lib/parser_aux.c +4 -3
index c99c5a4cb09b..a933f03edad7 100644
@@ -26,7 +26,8 @@
 #include "gstr.h"
 #include "structure.h"
 #include "element.h"
-#include "c-ctype.h"
+
+#define c_isdigit grub_isdigit
 
 char _asn1_identifierMissing[ASN1_MAX_NAME_SIZE + 1];	/* identifier name not found */
 
@@ -40,7 +41,7 @@ char _asn1_identifierMissing[ASN1_MAX_NAME_SIZE + 1];	/* identifier name not fou
 #ifdef __clang__
 __attribute__((no_sanitize ("integer")))
 #endif
-     _GL_ATTRIBUTE_PURE static unsigned int _asn1_hash_name (const char *x)
+     __attribute__((__pure__)) static unsigned int _asn1_hash_name (const char *x)
 {
   const unsigned char *s = (unsigned char *) x;
   unsigned h = 0;
@@ -632,7 +633,7 @@ _asn1_ltostr (int64_t v, char str[LTOSTR_MAX_SIZE])
   count = 0;
   do
     {
-      d = val / 10;
+      d = grub_divmod64(val, 10, NULL);
       r = val - d * 10;
       temp[start + count] = '0' + (char) r;
       count++;
include/grub/libtasn1.h +8 -21
index 0c3a4488101a..2ea058a3bc5d 100644
@@ -34,29 +34,16 @@
 #ifndef LIBTASN1_H
 # define LIBTASN1_H
 
-# ifndef ASN1_API
-#  if defined ASN1_BUILDING && defined HAVE_VISIBILITY && HAVE_VISIBILITY
-#   define ASN1_API __attribute__((__visibility__("default")))
-#  elif defined ASN1_BUILDING && defined _MSC_VER && ! defined ASN1_STATIC
-#   define ASN1_API __declspec(dllexport)
-#  elif defined _MSC_VER && ! defined ASN1_STATIC
-#   define ASN1_API __declspec(dllimport)
-#  else
-#   define ASN1_API
-#  endif
-# endif
+/* grub: ASN1_API is not used */
+# define ASN1_API
+
+/* grub: all our supported compilers support these attributes */
+# define __LIBTASN1_CONST__  __attribute__((const))
+# define __LIBTASN1_PURE__  __attribute__((pure))
 
-# ifdef __GNUC__
-#  define __LIBTASN1_CONST__  __attribute__((const))
-#  define __LIBTASN1_PURE__  __attribute__((pure))
-# else
-#  define __LIBTASN1_CONST__
-#  define __LIBTASN1_PURE__
-# endif
 
-# include <sys/types.h>
-# include <time.h>
-# include <stdio.h>		/* for FILE* */
+# include <grub/types.h>
+# include <grub/time.h>
 
 # ifdef __cplusplus
 extern "C"
Signature · 1 line
2.32.0
#11 lore raw

PATCH v3 11/19 libtasn1: compile into asn1 module

In reply to Daniel Axtens

Create a wrapper file that specifies the module license. Set up the makefile so it is built.

---

v3: Proper copyright headers.

---
 grub-core/Makefile.core.def        | 15 +++++++++++++++
 grub-core/lib/libtasn1_wrap/wrap.c | 27 +++++++++++++++++++++++++++
 2 files changed, 42 insertions(+)
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap.c
grub-core/Makefile.core.def +15 -0
index 5af8b780c2a1..2d73bb41bf42 100644
@@ -2540,3 +2540,18 @@ module = {
   common = commands/i386/wrmsr.c;
   enable = x86;
 };
+
+module = {
+  name = asn1;
+  common = lib/libtasn1/lib/decoding.c;
+  common = lib/libtasn1/lib/coding.c;
+  common = lib/libtasn1/lib/element.c;
+  common = lib/libtasn1/lib/structure.c;
+  common = lib/libtasn1/lib/parser_aux.c;
+  common = lib/libtasn1/lib/gstr.c;
+  common = lib/libtasn1/lib/errors.c;
+  common = lib/libtasn1_wrap/wrap.c;
+  cflags = '$(CFLAGS_POSIX) $(CFLAGS_GNULIB)';
+  // -Wno-type-limits comes from libtasn1's configure.ac
+  cppflags = '$(CPPFLAGS_POSIX) $(CPPFLAGS_GNULIB) -I$(srcdir)/lib/libtasn1/lib -Wno-type-limits';
+};
grub-core/lib/libtasn1_wrap/wrap.c new file +27 -0
new file mode 100644
index 000000000000..8f6bc5c12dff
@@ -0,0 +1,27 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2022 IBM Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/dl.h>
+
+/*
+ * libtasn1 is provided under LGPL2.1+, which is compatible
+ * with GPL3+. As Grub as a whole is under GPL3+, this module
+ * is therefore under GPL3+ also.
+ */
+GRUB_MOD_LICENSE ("GPLv3+");
Signature · 1 line
2.32.0
#12 lore raw

PATCH v3 12/19 test_asn1: test module for libtasn1

In reply to Daniel Axtens

Import tests from libtasn1 that don't use functionality we don't import. I have put them here rather than in the libtasn1 directory because:

- They need much more significant changes to run in the grub context. They are invoked via a test harness calling one after the other, rather than having a main fuction per file.

- I don't expect they will need to be changed when updating
libtasn1: I expect the old tests will usually continue to pass on new versions.

This doesn't test the full decoder but that will be exercised in test suites for coming patch sets.

---

v3: support the new native/nonnative distinction.
fix copyright headers

---
 .gitignore                                    |   1 +
 Makefile.util.def                             |   6 +
 grub-core/Makefile.core.def                   |  13 ++
 .../tests/CVE-2018-1000654-1_asn1_tab.h       |  32 +++
 .../tests/CVE-2018-1000654-2_asn1_tab.h       |  36 +++
 .../libtasn1_wrap/tests/CVE-2018-1000654.c    |  61 +++++
 .../lib/libtasn1_wrap/tests/Test_overflow.c   | 138 ++++++++++++
 .../lib/libtasn1_wrap/tests/Test_simple.c     | 207 +++++++++++++++++
 .../lib/libtasn1_wrap/tests/Test_strings.c    | 150 +++++++++++++
 .../libtasn1_wrap/tests/object-id-decoding.c  | 116 ++++++++++
 .../libtasn1_wrap/tests/object-id-encoding.c  | 120 ++++++++++
 .../lib/libtasn1_wrap/tests/octet-string.c    | 211 ++++++++++++++++++
 .../lib/libtasn1_wrap/tests/reproducers.c     |  81 +++++++
 grub-core/lib/libtasn1_wrap/wrap_tests.c      |  76 +++++++
 grub-core/lib/libtasn1_wrap/wrap_tests.h      |  39 ++++
 tests/test_asn1.in                            |  12 +
 16 files changed, 1299 insertions(+)
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-1_asn1_tab.h
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-2_asn1_tab.h
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_overflow.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_simple.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/Test_strings.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/object-id-decoding.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/object-id-encoding.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/octet-string.c
 create mode 100644 grub-core/lib/libtasn1_wrap/tests/reproducers.c
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap_tests.c
 create mode 100644 grub-core/lib/libtasn1_wrap/wrap_tests.h
 create mode 100644 tests/test_asn1.in
.gitignore +1 -0
index f6a1bd051752..c8fbf274cf1f 100644
@@ -264,6 +264,7 @@ widthspec.bin
 /stamp-h1
 /syslinux_test
 /tar_test
+/test_asn1
 /test_sha512sum
 /test_unset
 /tests/syslinux/ubuntu10.04_grub.cfg
Makefile.util.def +6 -0
index d919c562c4d1..cdc6fcaabfde 100644
@@ -1213,6 +1213,12 @@ script = {
   common = tests/syslinux_test.in;
 };
 
+script = {
+  testcase = nonnative;
+  name = test_asn1;
+  common = tests/test_asn1.in;
+};
+
 program = {
   testcase = native;
   name = example_unit_test;
grub-core/Makefile.core.def +13 -0
index 2d73bb41bf42..de5c763c64a0 100644
@@ -2555,3 +2555,16 @@ module = {
   // -Wno-type-limits comes from libtasn1's configure.ac
   cppflags = '$(CPPFLAGS_POSIX) $(CPPFLAGS_GNULIB) -I$(srcdir)/lib/libtasn1/lib -Wno-type-limits';
 };
+
+module = {
+  name = test_asn1;
+  common = lib/libtasn1_wrap/tests/CVE-2018-1000654.c;
+  common = lib/libtasn1_wrap/tests/object-id-decoding.c;
+  common = lib/libtasn1_wrap/tests/object-id-encoding.c;
+  common = lib/libtasn1_wrap/tests/octet-string.c;
+  common = lib/libtasn1_wrap/tests/reproducers.c;
+  common = lib/libtasn1_wrap/tests/Test_overflow.c;
+  common = lib/libtasn1_wrap/tests/Test_simple.c;
+  common = lib/libtasn1_wrap/tests/Test_strings.c;
+  common = lib/libtasn1_wrap/wrap_tests.c;
+};
grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-1_asn1_tab.h new file +32 -0
new file mode 100644
index 000000000000..1e7d3d64f55d
@@ -0,0 +1,32 @@
+#if HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include <grub/libtasn1.h>
+
+const asn1_static_node CVE_2018_1000654_1_asn1_tab[] = {
+  { "TEST_TREE", 536875024, NULL },
+  { NULL, 1610612748, NULL },
+  { "iso", 1073741825, "1"},
+  { "identified-organization", 1073741825, "3"},
+  { "dod", 1073741825, "6"},
+  { "internet", 1073741825, "1"},
+  { "security", 1073741825, "5"},
+  { "mechanisms", 1073741825, "5"},
+  { "pkix", 1073741825, "7"},
+  { "id-mod", 1073741825, "0"},
+  { "id-pkix1-implicit-88", 1, "2"},
+  { "id-xnyTest", 1879048204, NULL },
+  { NULL, 1073741825, "id-ix"},
+  { NULL, 1073741825, "29"},
+  { NULL, 1, "1"},
+  { "id-ix", 1880096780, "OBJECR"},
+  { NULL, 1073741825, "id-ix"},
+  { NULL, 1073741825, "29"},
+  { NULL, 1, "2"},
+  { "id-xnyTest", 805306380, NULL },
+  { NULL, 1073741825, "id-ix"},
+  { NULL, 1073741825, "29"},
+  { NULL, 1, "1"},
+  { NULL, 0, NULL }
+};
grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654-2_asn1_tab.h new file +36 -0
new file mode 100644
index 000000000000..e2561e5ec6dc
@@ -0,0 +1,36 @@
+#if HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include <grub/libtasn1.h>
+
+const asn1_static_node CVE_2018_1000654_2_asn1_tab[] = {
+  { "TEST_TREE", 536875024, NULL },
+  { NULL, 1610612748, NULL },
+  { "iso", 1073741825, "1"},
+  { "identified-organization", 1073741825, "3"},
+  { "dod", 1073741825, "6"},
+  { "internet", 1073741825, "1"},
+  { "security", 1073741825, "5"},
+  { "mechanisms", 1073741825, "5"},
+  { "pkix", 1073741825, "7"},
+  { "id-mod", 1073741825, "0"},
+  { "id-pkix1-implicit-88", 1, "2"},
+  { "id-oneTest", 1879048204, NULL },
+  { NULL, 1073741825, "id-two"},
+  { NULL, 1073741825, "9"},
+  { NULL, 1, "1"},
+  { "id-two", 1879048204, NULL },
+  { NULL, 1073741825, "id-three"},
+  { NULL, 1073741825, "2"},
+  { NULL, 1, "2"},
+  { "id-three", 1879048204, NULL },
+  { NULL, 1073741825, "id-four"},
+  { NULL, 1073741825, "3"},
+  { NULL, 1, "3"},
+  { "id-four", 805306380, NULL },
+  { NULL, 1073741825, "id-two"},
+  { NULL, 1073741825, "3"},
+  { NULL, 1, "3"},
+  { NULL, 0, NULL }
+};
grub-core/lib/libtasn1_wrap/tests/CVE-2018-1000654.c new file +61 -0

61 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/Test_overflow.c new file +138 -0

138 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/Test_simple.c new file +207 -0

207 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/Test_strings.c new file +150 -0

150 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/object-id-decoding.c new file +116 -0

116 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/object-id-encoding.c new file +120 -0

120 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/octet-string.c new file +211 -0

211 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/tests/reproducers.c new file +81 -0

81 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/wrap_tests.c new file +76 -0

76 lines not on this page · raw message

grub-core/lib/libtasn1_wrap/wrap_tests.h new file +39 -0
new file mode 100644
index 000000000000..3e1635cabcd1
@@ -0,0 +1,39 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2022 IBM Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef LIBTASN1_WRAP_TESTS_H
+#define LIBTASN1_WRAP_TESTS_H
+
+void test_CVE_2018_1000654 (void);
+
+void test_object_id_encoding (void);
+
+void test_object_id_decoding (void);
+
+void test_octet_string (void);
+
+void test_overflow (void);
+
+void test_reproducers (void);
+
+void test_simple (void);
+
+void test_strings (void);
+
+#endif
tests/test_asn1.in new file +12 -0
new file mode 100644
index 000000000000..8173c5c270e5
@@ -0,0 +1,12 @@
+#! @BUILD_SHEBANG@
+set -e
+
+. "@builddir@/grub-core/modinfo.sh"
+
+out=`echo test_asn1 | @builddir@/grub-shell`
+
+if [ "$(echo "$out" | tail -n 1)" != "ASN.1 self-tests passed" ]; then
+  echo "ASN.1 test failure: $out"
+  exit 1
+fi
+
Signature · 1 line
2.32.0
#13 lore raw

PATCH v3 13/19 grub-install: support embedding x509 certificates

In reply to Daniel Axtens

From: Alastair D'Silva <[email protected]>

To support verification of appended signatures, we need a way to embed the necessary public keys. Existing appended signature schemes in the Linux kernel use X.509 certificates, so allow certificates to be embedded in the grub core image in the same way as PGP keys.

---
 grub-core/commands/pgp.c    |  2 +-
 include/grub/kernel.h       |  3 ++-
 include/grub/util/install.h |  7 +++++--
 util/grub-install-common.c  | 22 +++++++++++++++++++-
 util/grub-mkimage.c         | 15 ++++++++++++--
 util/mkimage.c              | 41 ++++++++++++++++++++++++++++++++++---
 6 files changed, 80 insertions(+), 10 deletions(-)
grub-core/commands/pgp.c +1 -1
index a45c2213c4ac..847a5046a5c4 100644
@@ -944,7 +944,7 @@ GRUB_MOD_INIT(pgp)
     grub_memset (&pseudo_file, 0, sizeof (pseudo_file));
 
     /* Not an ELF module, skip.  */
-    if (header->type != OBJ_TYPE_PUBKEY)
+    if (header->type != OBJ_TYPE_GPG_PUBKEY)
       continue;
 
     pseudo_file.fs = &pseudo_fs;
include/grub/kernel.h +2 -1
index abbca5ea3359..d3aafc8848d2 100644
@@ -28,7 +28,8 @@ enum
   OBJ_TYPE_MEMDISK,
   OBJ_TYPE_CONFIG,
   OBJ_TYPE_PREFIX,
-  OBJ_TYPE_PUBKEY,
+  OBJ_TYPE_GPG_PUBKEY,
+  OBJ_TYPE_X509_PUBKEY,
   OBJ_TYPE_DTB,
   OBJ_TYPE_DISABLE_SHIM_LOCK
 };
include/grub/util/install.h +5 -2
index fadcce0fea7e..bfaba0d09f33 100644
@@ -67,6 +67,8 @@
       N_("SBAT metadata"), 0 },						\
   { "disable-shim-lock", GRUB_INSTALL_OPTIONS_DISABLE_SHIM_LOCK, 0, 0,	\
       N_("disable shim_lock verifier"), 0 },				\
+  { "x509key",   'x', N_("FILE"), 0,					\
+      N_("embed FILE as an x509 certificate for signature checking"), 0}, \
   { "appended-signature-size", GRUB_INSTALL_OPTIONS_APPENDED_SIGNATURE_SIZE,\
     "SIZE", 0, N_("Add a note segment reserving SIZE bytes for an appended signature"), \
     1},                                                                 \
@@ -188,8 +190,9 @@ void
 grub_install_generate_image (const char *dir, const char *prefix,
 			     FILE *out,
 			     const char *outname, char *mods[],
-			     char *memdisk_path, char **pubkey_paths,
-			     size_t npubkeys,
+			     char *memdisk_path,
+			     char **pubkey_paths, size_t npubkeys,
+			     char **x509key_paths, size_t nx509keys,
 			     char *config_path,
 			     const struct grub_install_image_target_desc *image_target,
 			     int note, size_t appsig_size,
util/grub-install-common.c +21 -1
index b552808df70f..cbd868152457 100644
@@ -460,6 +460,8 @@ static char **pubkeys;
 static size_t npubkeys;
 static char *sbat;
 static int disable_shim_lock;
+static char **x509keys;
+static size_t nx509keys;
 static grub_compression_t compression;
 static size_t appsig_size;
 
@@ -501,6 +503,12 @@ grub_install_parse (int key, char *arg)
     case GRUB_INSTALL_OPTIONS_DISABLE_SHIM_LOCK:
       disable_shim_lock = 1;
       return 1;
+    case 'x':
+      x509keys = xrealloc (x509keys,
+			  sizeof (x509keys[0])
+			  * (nx509keys + 1));
+      x509keys[nx509keys++] = xstrdup (arg);
+      return 1;
 
     case GRUB_INSTALL_OPTIONS_VERBOSITY:
       verbosity++;
@@ -627,6 +635,9 @@ grub_install_make_image_wrap_file (const char *dir, const char *prefix,
   for (pk = pubkeys; pk < pubkeys + npubkeys; pk++)
     slen += 20 + grub_strlen (*pk);
 
+  for (pk = x509keys; pk < x509keys + nx509keys; pk++)
+    slen += 10 + grub_strlen (*pk);
+
   for (md = modules.entries; *md; md++)
     {
       slen += 10 + grub_strlen (*md);
@@ -655,6 +666,14 @@ grub_install_make_image_wrap_file (const char *dir, const char *prefix,
       *p++ = ' ';
     }
 
+  for (pk = x509keys; pk < x509keys + nx509keys; pk++)
+    {
+      p = grub_stpcpy (p, "--x509 '");
+      p = grub_stpcpy (p, *pk);
+      *p++ = '\'';
+      *p++ = ' ';
+    }
+
   for (md = modules.entries; *md; md++)
     {
       *p++ = '\'';
@@ -683,7 +702,8 @@ grub_install_make_image_wrap_file (const char *dir, const char *prefix,
 
   grub_install_generate_image (dir, prefix, fp, outname,
 			       modules.entries, memdisk_path,
-			       pubkeys, npubkeys, config_path, tgt,
+			       pubkeys, npubkeys, x509keys, nx509keys,
+			       config_path, tgt,
 			       note, appsig_size, compression, dtb, sbat,
 			       disable_shim_lock);
   while (dc--)
util/grub-mkimage.c +13 -2
index 49b9410c5fa3..d4ca35ff54a6 100644
@@ -75,7 +75,8 @@ static struct argp_option options[] = {
    /* TRANSLATORS: "embed" is a verb (command description).  "*/
   {"config",   'c', N_("FILE"), 0, N_("embed FILE as an early config"), 0},
    /* TRANSLATORS: "embed" is a verb (command description).  "*/
-  {"pubkey",   'k', N_("FILE"), 0, N_("embed FILE as public key for signature checking"), 0},
+  {"pubkey",   'k', N_("FILE"), 0, N_("embed FILE as public key for PGP signature checking"), 0},
+  {"x509",     'x', N_("FILE"), 0, N_("embed FILE as an x509 certificate for appended signature checking"), 0},
   /* TRANSLATORS: NOTE is a name of segment.  */
   {"note",   'n', 0, 0, N_("add NOTE segment for CHRP IEEE1275"), 0},
   {"output",  'o', N_("FILE"), 0, N_("output a generated image to FILE [default=stdout]"), 0},
@@ -124,6 +125,8 @@ struct arguments
   char *dtb;
   char **pubkeys;
   size_t npubkeys;
+  char **x509keys;
+  size_t nx509keys;
   char *font;
   char *config;
   char *sbat;
@@ -206,6 +209,13 @@ argp_parser (int key, char *arg, struct argp_state *state)
       arguments->pubkeys[arguments->npubkeys++] = xstrdup (arg);
       break;
 
+    case 'x':
+      arguments->x509keys = xrealloc (arguments->x509keys,
+				      sizeof (arguments->x509keys[0])
+				      * (arguments->nx509keys + 1));
+      arguments->x509keys[arguments->nx509keys++] = xstrdup (arg);
+      break;
+
     case 'c':
       if (arguments->config)
 	free (arguments->config);
@@ -332,7 +342,8 @@ main (int argc, char *argv[])
   grub_install_generate_image (arguments.dir, arguments.prefix, fp,
 			       arguments.output, arguments.modules,
 			       arguments.memdisk, arguments.pubkeys,
-			       arguments.npubkeys, arguments.config,
+			       arguments.npubkeys, arguments.x509keys,
+			       arguments.nx509keys, arguments.config,
 			       arguments.image_target, arguments.note,
 			       arguments.appsig_size,
 			       arguments.comp, arguments.dtb,
util/mkimage.c +38 -3

65 lines not on this page · raw message

Signature · 1 line
2.32.0
#14 lore raw

PATCH v3 14/19 appended signatures: import GNUTLS's ASN.1 description files

In reply to Daniel Axtens

In order to parse PKCS#7 messages and X.509 certificates with libtasn1, we need some information about how they are encoded.

We get these from GNUTLS, which has the benefit that they support the features we need and are well tested.

The GNUTLS files are from:

- https://github.com/gnutls/gnutls/blob/857543cc24114431dd5dde0e83c2c44b9b7e6050/lib/gnutls_asn1_tab.c
- https://github.com/gnutls/gnutls/blob/857543cc24114431dd5dde0e83c2c44b9b7e6050/lib/pkix_asn1_tab.c

The GNUTLS license is LGPLv2.1+, which is GPLv3 compatible, allowing us to import it without issue.

---

v3: Include links to GNUTLS source, thanks Stefan.

---
 .../commands/appendedsig/gnutls_asn1_tab.c    | 121 +++++
 .../commands/appendedsig/pkix_asn1_tab.c      | 484 ++++++++++++++++++
 2 files changed, 605 insertions(+)
 create mode 100644 grub-core/commands/appendedsig/gnutls_asn1_tab.c
 create mode 100644 grub-core/commands/appendedsig/pkix_asn1_tab.c
grub-core/commands/appendedsig/gnutls_asn1_tab.c new file +121 -0
new file mode 100644
index 000000000000..ddd1314e63b6
@@ -0,0 +1,121 @@
+#include <grub/mm.h>
+#include <grub/libtasn1.h>
+
+const asn1_static_node gnutls_asn1_tab[] = {
+  { "GNUTLS", 536872976, NULL },
+  { NULL, 1073741836, NULL },
+  { "RSAPublicKey", 1610612741, NULL },
+  { "modulus", 1073741827, NULL },
+  { "publicExponent", 3, NULL },
+  { "RSAPrivateKey", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "modulus", 1073741827, NULL },
+  { "publicExponent", 1073741827, NULL },
+  { "privateExponent", 1073741827, NULL },
+  { "prime1", 1073741827, NULL },
+  { "prime2", 1073741827, NULL },
+  { "exponent1", 1073741827, NULL },
+  { "exponent2", 1073741827, NULL },
+  { "coefficient", 1073741827, NULL },
+  { "otherPrimeInfos", 16386, "OtherPrimeInfos"},
+  { "ProvableSeed", 1610612741, NULL },
+  { "algorithm", 1073741836, NULL },
+  { "seed", 7, NULL },
+  { "OtherPrimeInfos", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "OtherPrimeInfo"},
+  { "OtherPrimeInfo", 1610612741, NULL },
+  { "prime", 1073741827, NULL },
+  { "exponent", 1073741827, NULL },
+  { "coefficient", 3, NULL },
+  { "AlgorithmIdentifier", 1610612741, NULL },
+  { "algorithm", 1073741836, NULL },
+  { "parameters", 541081613, NULL },
+  { "algorithm", 1, NULL },
+  { "DigestInfo", 1610612741, NULL },
+  { "digestAlgorithm", 1073741826, "DigestAlgorithmIdentifier"},
+  { "digest", 7, NULL },
+  { "DigestAlgorithmIdentifier", 1073741826, "AlgorithmIdentifier"},
+  { "DSAPublicKey", 1073741827, NULL },
+  { "DSAParameters", 1610612741, NULL },
+  { "p", 1073741827, NULL },
+  { "q", 1073741827, NULL },
+  { "g", 3, NULL },
+  { "DSASignatureValue", 1610612741, NULL },
+  { "r", 1073741827, NULL },
+  { "s", 3, NULL },
+  { "DSAPrivateKey", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "p", 1073741827, NULL },
+  { "q", 1073741827, NULL },
+  { "g", 1073741827, NULL },
+  { "Y", 1073741827, NULL },
+  { "priv", 3, NULL },
+  { "DHParameter", 1610612741, NULL },
+  { "prime", 1073741827, NULL },
+  { "base", 1073741827, NULL },
+  { "privateValueLength", 16387, NULL },
+  { "ECParameters", 1610612754, NULL },
+  { "namedCurve", 12, NULL },
+  { "ECPrivateKey", 1610612741, NULL },
+  { "Version", 1073741827, NULL },
+  { "privateKey", 1073741831, NULL },
+  { "parameters", 1610637314, "ECParameters"},
+  { NULL, 2056, "0"},
+  { "publicKey", 536895494, NULL },
+  { NULL, 2056, "1"},
+  { "PrincipalName", 1610612741, NULL },
+  { "name-type", 1610620931, NULL },
+  { NULL, 2056, "0"},
+  { "name-string", 536879115, NULL },
+  { NULL, 1073743880, "1"},
+  { NULL, 27, NULL },
+  { "KRB5PrincipalName", 1610612741, NULL },
+  { "realm", 1610620955, NULL },
+  { NULL, 2056, "0"},
+  { "principalName", 536879106, "PrincipalName"},
+  { NULL, 2056, "1"},
+  { "RSAPSSParameters", 1610612741, NULL },
+  { "hashAlgorithm", 1610637314, "AlgorithmIdentifier"},
+  { NULL, 2056, "0"},
+  { "maskGenAlgorithm", 1610637314, "AlgorithmIdentifier"},
+  { NULL, 2056, "1"},
+  { "saltLength", 1610653699, NULL },
+  { NULL, 1073741833, "20"},
+  { NULL, 2056, "2"},
+  { "trailerField", 536911875, NULL },
+  { NULL, 1073741833, "1"},
+  { NULL, 2056, "3"},
+  { "GOSTParameters", 1610612741, NULL },
+  { "publicKeyParamSet", 1073741836, NULL },
+  { "digestParamSet", 16396, NULL },
+  { "GOSTParametersOld", 1610612741, NULL },
+  { "publicKeyParamSet", 1073741836, NULL },
+  { "digestParamSet", 1073741836, NULL },
+  { "encryptionParamSet", 16396, NULL },
+  { "GOSTPrivateKey", 1073741831, NULL },
+  { "GOSTPrivateKeyOld", 1073741827, NULL },
+  { "IssuerSignTool", 1610612741, NULL },
+  { "signTool", 1073741858, NULL },
+  { "cATool", 1073741858, NULL },
+  { "signToolCert", 1073741858, NULL },
+  { "cAToolCert", 34, NULL },
+  { "Gost28147-89-EncryptedKey", 1610612741, NULL },
+  { "encryptedKey", 1073741831, NULL },
+  { "maskKey", 1610637319, NULL },
+  { NULL, 4104, "0"},
+  { "macKey", 7, NULL },
+  { "SubjectPublicKeyInfo", 1610612741, NULL },
+  { "algorithm", 1073741826, "AlgorithmIdentifier"},
+  { "subjectPublicKey", 6, NULL },
+  { "GostR3410-TransportParameters", 1610612741, NULL },
+  { "encryptionParamSet", 1073741836, NULL },
+  { "ephemeralPublicKey", 1610637314, "SubjectPublicKeyInfo"},
+  { NULL, 4104, "0"},
+  { "ukm", 7, NULL },
+  { "GostR3410-KeyTransport", 536870917, NULL },
+  { "sessionEncryptedKey", 1073741826, "Gost28147-89-EncryptedKey"},
+  { "transportParameters", 536895490, "GostR3410-TransportParameters"},
+  { NULL, 4104, "0"},
+  { NULL, 0, NULL }
+};
grub-core/commands/appendedsig/pkix_asn1_tab.c new file +484 -0

484 lines not on this page · raw message

Signature · 1 line
2.32.0
#15 lore raw

PATCH v3 15/19 appended signatures: parse PKCS#7 signedData and X.509 certificates

In reply to Daniel Axtens

This code allows us to parse:

- PKCS#7 signedData messages. Only a single signerInfo is supported, which is all that the Linux sign-file utility supports creating out-of-the-box. Only RSA, SHA-256 and SHA-512 are supported. Any certificate embedded in the PKCS#7 message will be ignored.

- X.509 certificates: at least enough to verify the signatures on the PKCS#7 messages. We expect that the certificates embedded in grub will be leaf certificates, not CA certificates. The parser enforces this.

- X.509 certificates support the Extended Key Usage extension and handle it by verifying that the certificate has a single purpose, that is code signing. This is required because Red Hat certificates have both Key Usage and Extended Key Usage extensions present.

---

v3 changes:
- fix nits from Stefan
- correct copyright headers
- fixes for libtasn1-4.18.0
- Roll in a fix for a bug reported by Michal:

Currently the x509 certificate parser for appended signature verification requires that the certificate have the Digitial Signature key usage and _only_ the Digitial Signature use. This is overly strict and becomes policy enforcement rather than a security property.

Require that the Digitial Signature usage is present, but do not require that it is the only usage present.

v2 changes:

- Handle the Extended Key Usage extension
- Fix 2 leaks in x509 cert parsing
- Improve x509 parser function name
- Constify the data parameter in parser signatures
- Support multiple signers in a pkcs7 message. Accept any passing sig.
- Allow padding after a pkcs7 message in an appended signature, required to support my model for signers separated in time.
- Fix a test that used GRUB_ERR_NONE rather than ASN1_SUCCESS. They're both 0 so no harm was done, but better to be correct.
- Various code and comment cleanups.

Thanks to Nayna Jain and Stefan Berger for their reviews.

---
 grub-core/commands/appendedsig/appendedsig.h |  119 ++
 grub-core/commands/appendedsig/asn1util.c    |  104 ++
 grub-core/commands/appendedsig/pkcs7.c       |  512 +++++++++
 grub-core/commands/appendedsig/x509.c        | 1082 ++++++++++++++++++
 4 files changed, 1817 insertions(+)
 create mode 100644 grub-core/commands/appendedsig/appendedsig.h
 create mode 100644 grub-core/commands/appendedsig/asn1util.c
 create mode 100644 grub-core/commands/appendedsig/pkcs7.c
 create mode 100644 grub-core/commands/appendedsig/x509.c
grub-core/commands/appendedsig/appendedsig.h new file +119 -0
new file mode 100644
index 000000000000..d3dfd4616862
@@ -0,0 +1,119 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2022 IBM Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/crypto.h>
+#include <grub/libtasn1.h>
+
+extern asn1_node _gnutls_gnutls_asn;
+extern asn1_node _gnutls_pkix_asn;
+
+#define MAX_OID_LEN 32
+
+/*
+ * One or more x509 certificates.
+ *
+ * We do limited parsing: extracting only the serial, CN and RSA public key.
+ */
+struct x509_certificate
+{
+  struct x509_certificate *next;
+
+  grub_uint8_t *serial;
+  grub_size_t serial_len;
+
+  char *subject;
+  grub_size_t subject_len;
+
+  /* We only support RSA public keys. This encodes [modulus, publicExponent] */
+  gcry_mpi_t mpis[2];
+};
+
+/*
+ * A PKCS#7 signedData signerInfo.
+ */
+struct pkcs7_signerInfo
+{
+  const gcry_md_spec_t *hash;
+  gcry_mpi_t sig_mpi;
+};
+
+/*
+ * A PKCS#7 signedData message.
+ *
+ * We make no attempt to match intelligently, so we don't save any info about
+ * the signer.
+ */
+struct pkcs7_signedData
+{
+  int signerInfo_count;
+  struct pkcs7_signerInfo *signerInfos;
+};
+
+
+/* Do libtasn1 init */
+int asn1_init (void);
+
+/*
+ * Import a DER-encoded certificate at 'data', of size 'size'.
+ *
+ * Place the results into 'results', which must be already allocated.
+ */
+grub_err_t
+parse_x509_certificate (const void *data, grub_size_t size,
+			struct x509_certificate *results);
+
+/*
+ * Release all the storage associated with the x509 certificate.
+ * If the caller dynamically allocated the certificate, it must free it.
+ * The caller is also responsible for maintenance of the linked list.
+ */
+void certificate_release (struct x509_certificate *cert);
+
+/*
+ * Parse a PKCS#7 message, which must be a signedData message.
+ *
+ * The message must be in 'sigbuf' and of size 'data_size'. The result is
+ * placed in 'msg', which must already be allocated.
+ */
+grub_err_t
+parse_pkcs7_signedData (const void *sigbuf, grub_size_t data_size,
+			struct pkcs7_signedData *msg);
+
+/*
+ * Release all the storage associated with the PKCS#7 message.
+ * If the caller dynamically allocated the message, it must free it.
+ */
+void pkcs7_signedData_release (struct pkcs7_signedData *msg);
+
+/*
+ * Read a value from an ASN1 node, allocating memory to store it.
+ *
+ * It will work for anything where the size libtasn1 returns is right:
+ *  - Integers
+ *  - Octet strings
+ *  - DER encoding of other structures
+ * It will _not_ work for things where libtasn1 size requires adjustment:
+ *  - Strings that require an extra NULL byte at the end
+ *  - Bit strings because libtasn1 returns the length in bits, not bytes.
+ *
+ * If the function returns a non-NULL value, the caller must free it.
+ */
+void *grub_asn1_allocate_and_read (asn1_node node, const char *name,
+				   const char *friendly_name,
+				   int *content_size);
grub-core/commands/appendedsig/asn1util.c new file +104 -0

104 lines not on this page · raw message

grub-core/commands/appendedsig/pkcs7.c new file +512 -0

512 lines not on this page · raw message

grub-core/commands/appendedsig/x509.c new file +1082 -0

1,082 lines not on this page · raw message

Signature · 1 line
2.32.0
#16 lore raw

Re: [PATCH v3 15/19] appended signatures: parse PKCS#7 signedData and X.509 certificates

Hello,

Quoted 10 lines · Daniel Axtens

This code allows us to parse:

- PKCS#7 signedData messages. Only a single signerInfo is supported, which is all that the Linux sign-file utility supports creating out-of-the-box. Only RSA, SHA-256 and SHA-512 are supported. Any certificate embedded in the PKCS#7 message will be ignored.

- X.509 certificates: at least enough to verify the signatures on the PKCS#7 messages. We expect that the certificates embedded in grub will be leaf certificates, not CA certificates. The parser enforces this.

Doesn't grub support CA certificates for EFI?

Why limit to leaf certificates here?

If this is technical limitation of the code in question could you fail the build when CA certificate is used rather than crashing the bootloader when it boots?

Quoted 3 lines

- X.509 certificates support the Extended Key Usage extension and handle it by verifying that the certificate has a single purpose, that is code

                                                ^^^^^^^^^^^^^^

This should be updated I suppose.

Thanks

Michal

Quoted 1,892 lines

signing. This is required because Red Hat certificates have both Key Usage and Extended Key Usage extensions present.

---

v3 changes:
- fix nits from Stefan
- correct copyright headers
- fixes for libtasn1-4.18.0
- Roll in a fix for a bug reported by Michal:

Currently the x509 certificate parser for appended signature verification requires that the certificate have the Digitial Signature key usage and _only_ the Digitial Signature use. This is overly strict and becomes policy enforcement rather than a security property.

Require that the Digitial Signature usage is present, but do not require that it is the only usage present.

v2 changes:

- Handle the Extended Key Usage extension
- Fix 2 leaks in x509 cert parsing
- Improve x509 parser function name
- Constify the data parameter in parser signatures
- Support multiple signers in a pkcs7 message. Accept any passing sig.
- Allow padding after a pkcs7 message in an appended signature, required to support my model for signers separated in time.
- Fix a test that used GRUB_ERR_NONE rather than ASN1_SUCCESS. They're both 0 so no harm was done, but better to be correct.
- Various code and comment cleanups.

Thanks to Nayna Jain and Stefan Berger for their reviews.

---
 grub-core/commands/appendedsig/appendedsig.h |  119 ++
 grub-core/commands/appendedsig/asn1util.c    |  104 ++
 grub-core/commands/appendedsig/pkcs7.c       |  512 +++++++++
 grub-core/commands/appendedsig/x509.c        | 1082 ++++++++++++++++++
 4 files changed, 1817 insertions(+)
 create mode 100644 grub-core/commands/appendedsig/appendedsig.h
 create mode 100644 grub-core/commands/appendedsig/asn1util.c
 create mode 100644 grub-core/commands/appendedsig/pkcs7.c
 create mode 100644 grub-core/commands/appendedsig/x509.c
grub-core/commands/appendedsig/appendedsig.h new file +119 -0
new file mode 100644
index 000000000000..d3dfd4616862
@@ -0,0 +1,119 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2022 IBM Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/crypto.h>
+#include <grub/libtasn1.h>
+
+extern asn1_node _gnutls_gnutls_asn;
+extern asn1_node _gnutls_pkix_asn;
+
+#define MAX_OID_LEN 32
+
+/*
+ * One or more x509 certificates.
+ *
+ * We do limited parsing: extracting only the serial, CN and RSA public key.
+ */
+struct x509_certificate
+{
+  struct x509_certificate *next;
+
+  grub_uint8_t *serial;
+  grub_size_t serial_len;
+
+  char *subject;
+  grub_size_t subject_len;
+
+  /* We only support RSA public keys. This encodes [modulus, publicExponent] */
+  gcry_mpi_t mpis[2];
+};
+
+/*
+ * A PKCS#7 signedData signerInfo.
+ */
+struct pkcs7_signerInfo
+{
+  const gcry_md_spec_t *hash;
+  gcry_mpi_t sig_mpi;
+};
+
+/*
+ * A PKCS#7 signedData message.
+ *
+ * We make no attempt to match intelligently, so we don't save any info about
+ * the signer.
+ */
+struct pkcs7_signedData
+{
+  int signerInfo_count;
+  struct pkcs7_signerInfo *signerInfos;
+};
+
+
+/* Do libtasn1 init */
+int asn1_init (void);
+
+/*
+ * Import a DER-encoded certificate at 'data', of size 'size'.
+ *
+ * Place the results into 'results', which must be already allocated.
+ */
+grub_err_t
+parse_x509_certificate (const void *data, grub_size_t size,
+			struct x509_certificate *results);
+
+/*
+ * Release all the storage associated with the x509 certificate.
+ * If the caller dynamically allocated the certificate, it must free it.
+ * The caller is also responsible for maintenance of the linked list.
+ */
+void certificate_release (struct x509_certificate *cert);
+
+/*
+ * Parse a PKCS#7 message, which must be a signedData message.
+ *
+ * The message must be in 'sigbuf' and of size 'data_size'. The result is
+ * placed in 'msg', which must already be allocated.
+ */
+grub_err_t
+parse_pkcs7_signedData (const void *sigbuf, grub_size_t data_size,
+			struct pkcs7_signedData *msg);
+
+/*
+ * Release all the storage associated with the PKCS#7 message.
+ * If the caller dynamically allocated the message, it must free it.
+ */
+void pkcs7_signedData_release (struct pkcs7_signedData *msg);
+
+/*
+ * Read a value from an ASN1 node, allocating memory to store it.
+ *
+ * It will work for anything where the size libtasn1 returns is right:
+ *  - Integers
+ *  - Octet strings
+ *  - DER encoding of other structures
+ * It will _not_ work for things where libtasn1 size requires adjustment:
+ *  - Strings that require an extra NULL byte at the end
+ *  - Bit strings because libtasn1 returns the length in bits, not bytes.
+ *
+ * If the function returns a non-NULL value, the caller must free it.
+ */
+void *grub_asn1_allocate_and_read (asn1_node node, const char *name,
+				   const char *friendly_name,
+				   int *content_size);
grub-core/commands/appendedsig/asn1util.c new file +104 -0
new file mode 100644
index 000000000000..f373b5fdcd68
@@ -0,0 +1,104 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2022 IBM Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/libtasn1.h>
+#include <grub/types.h>
+#include <grub/err.h>
+#include <grub/mm.h>
+#include <grub/crypto.h>
+#include <grub/misc.h>
+#include <grub/gcrypt/gcrypt.h>
+
+#include "appendedsig.h"
+
+asn1_node _gnutls_gnutls_asn = NULL;
+asn1_node _gnutls_pkix_asn = NULL;
+
+extern const asn1_static_node gnutls_asn1_tab[];
+extern const asn1_static_node pkix_asn1_tab[];
+
+/*
+ * Read a value from an ASN1 node, allocating memory to store it.
+ *
+ * It will work for anything where the size libtasn1 returns is right:
+ *  - Integers
+ *  - Octet strings
+ *  - DER encoding of other structures
+ * It will _not_ work for things where libtasn1 size requires adjustment:
+ *  - Strings that require an extra NULL byte at the end
+ *  - Bit strings because libtasn1 returns the length in bits, not bytes.
+ *
+ * If the function returns a non-NULL value, the caller must free it.
+ */
+void *
+grub_asn1_allocate_and_read (asn1_node node, const char *name,
+			     const char *friendly_name, int *content_size)
+{
+  int result;
+  grub_uint8_t *tmpstr = NULL;
+  int tmpstr_size = 0;
+
+  result = asn1_read_value (node, name, NULL, &tmpstr_size);
+  if (result != ASN1_MEM_ERROR)
+    {
+      grub_snprintf (grub_errmsg, sizeof (grub_errmsg),
+		     _
+		     ("Reading size of %s did not return expected status: %s"),
+		     friendly_name, asn1_strerror (result));
+      grub_errno = GRUB_ERR_BAD_FILE_TYPE;
+      return NULL;
+    }
+
+  tmpstr = grub_malloc (tmpstr_size);
+  if (tmpstr == NULL)
+    {
+      grub_snprintf (grub_errmsg, sizeof (grub_errmsg),
+		     "Could not allocate memory to store %s", friendly_name);
+      grub_errno = GRUB_ERR_OUT_OF_MEMORY;
+      return NULL;
+    }
+
+  result = asn1_read_value (node, name, tmpstr, &tmpstr_size);
+  if (result != ASN1_SUCCESS)
+    {
+      grub_free (tmpstr);
+      grub_snprintf (grub_errmsg, sizeof (grub_errmsg),
+		     "Error reading %s: %s",
+		     friendly_name, asn1_strerror (result));
+      grub_errno = GRUB_ERR_BAD_FILE_TYPE;
+      return NULL;
+    }
+
+  *content_size = tmpstr_size;
+
+  return tmpstr;
+}
+
+int
+asn1_init (void)
+{
+  int res;
+  res = asn1_array2tree (gnutls_asn1_tab, &_gnutls_gnutls_asn, NULL);
+  if (res != ASN1_SUCCESS)
+    {
+      return res;
+    }
+  res = asn1_array2tree (pkix_asn1_tab, &_gnutls_pkix_asn, NULL);
+  return res;
+}
grub-core/commands/appendedsig/pkcs7.c new file +512 -0
new file mode 100644
index 000000000000..e12c47454376
@@ -0,0 +1,512 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2022 IBM Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include "appendedsig.h"
+#include <grub/misc.h>
+#include <grub/crypto.h>
+#include <grub/gcrypt/gcrypt.h>
+#include <sys/types.h>
+
+static char asn1_error[ASN1_MAX_ERROR_DESCRIPTION_SIZE];
+
+/*
+ * RFC 5652 s 5.1
+ */
+static const char *signedData_oid = "1.2.840.113549.1.7.2";
+
+/*
+ * RFC 4055 s 2.1
+ */
+static const char *sha256_oid = "2.16.840.1.101.3.4.2.1";
+static const char *sha512_oid = "2.16.840.1.101.3.4.2.3";
+
+static grub_err_t
+process_content (grub_uint8_t * content, int size,
+		 struct pkcs7_signedData *msg)
+{
+  int res;
+  asn1_node signed_part;
+  grub_err_t err = GRUB_ERR_NONE;
+  char algo_oid[MAX_OID_LEN];
+  int algo_oid_size = sizeof (algo_oid);
+  int algo_count;
+  int signer_count;
+  int i;
+  char version;
+  int version_size = sizeof (version);
+  grub_uint8_t *result_buf;
+  int result_size = 0;
+  int crls_size = 0;
+  gcry_error_t gcry_err;
+  bool sha256_in_da, sha256_in_si, sha512_in_da, sha512_in_si;
+  char *da_path;
+  char *si_sig_path;
+  char *si_da_path;
+
+  res = asn1_create_element (_gnutls_pkix_asn, "PKIX1.pkcs-7-SignedData",
+			     &signed_part);
+  if (res != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			 "Could not create ASN.1 structure for PKCS#7 signed part.");
+    }
+
+  res = asn1_der_decoding2 (&signed_part, content, &size,
+			    ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
+  if (res != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_SIGNATURE,
+		    "Error reading PKCS#7 signed data: %s", asn1_error);
+      goto cleanup_signed_part;
+    }
+
+  /* SignedData ::= SEQUENCE {
+   *     version CMSVersion,
+   *     digestAlgorithms DigestAlgorithmIdentifiers,
+   *     encapContentInfo EncapsulatedContentInfo,
+   *     certificates [0] IMPLICIT CertificateSet OPTIONAL,
+   *     crls [1] IMPLICIT RevocationInfoChoices OPTIONAL,
+   *     signerInfos SignerInfos }
+   */
+
+  /* version per the algo in 5.1, must be 1 */
+  res = asn1_read_value (signed_part, "version", &version, &version_size);
+  if (res != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_SIGNATURE,
+		    "Error reading signedData version: %s",
+		    asn1_strerror (res));
+      goto cleanup_signed_part;
+    }
+
+  if (version != 1)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_SIGNATURE,
+		    "Unexpected signature version v%d, only v1 supported",
+		    version);
+      goto cleanup_signed_part;
+    }
+
+  /*
+   * digestAlgorithms DigestAlgorithmIdentifiers
+   *
+   * DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
+   * DigestAlgorithmIdentifer is an X.509 AlgorithmIdentifier (10.1.1)
+   *
+   * RFC 4055 s 2.1:
+   * sha256Identifier  AlgorithmIdentifier  ::=  { id-sha256, NULL }
+   * sha512Identifier  AlgorithmIdentifier  ::=  { id-sha512, NULL }
+   *
+   * We only support 1 element in the set, and we do not check parameters atm.
+   */
+  res =
+    asn1_number_of_elements (signed_part, "digestAlgorithms", &algo_count);
+  if (res != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_SIGNATURE,
+		    "Error counting number of digest algorithms: %s",
+		    asn1_strerror (res));
+      goto cleanup_signed_part;
+    }
+
+  if (algo_count <= 0)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_SIGNATURE,
+		    "A minimum of 1 digest algorithm is required");
+      goto cleanup_signed_part;
+    }
+
+  if (algo_count > 2)
+    {
+      err =
+	grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+		    "A maximum of 2 digest algorithms are supported");
+      goto cleanup_signed_part;
+    }
+
+  sha256_in_da = false;
+  sha512_in_da = false;
+
+  for (i = 0; i < algo_count; i++)
+    {
+      da_path = grub_xasprintf ("digestAlgorithms.?%d.algorithm", i + 1);
+      if (!da_path)
+	{
+	  err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			    "Could not allocate path for digest algorithm parsing path");
+	  goto cleanup_signed_part;
+	}
+
+      algo_oid_size = sizeof (algo_oid);
+      res = asn1_read_value (signed_part, da_path, algo_oid, &algo_oid_size);
+      if (res != ASN1_SUCCESS)
+	{
+	  err =
+	    grub_error (GRUB_ERR_BAD_SIGNATURE,
+			"Error reading digest algorithm: %s",
+			asn1_strerror (res));
+	  grub_free (da_path);
+	  goto cleanup_signed_part;
+	}
+
+      if (grub_strncmp (sha512_oid, algo_oid, algo_oid_size) == 0)
+	{
+	  if (!sha512_in_da)
+	    {
+	      sha512_in_da = true;
+	    }
+	  else
+	    {
+	      err =
+		grub_error (GRUB_ERR_BAD_SIGNATURE,
+			    "SHA-512 specified twice in digest algorithm list");
+	      grub_free (da_path);
+	      goto cleanup_signed_part;
+	    }
+	}
+      else if (grub_strncmp (sha256_oid, algo_oid, algo_oid_size) == 0)
+	{
+	  if (!sha256_in_da)
+	    {
+	      sha256_in_da = true;
+	    }
+	  else
+	    {
+	      err =
+		grub_error (GRUB_ERR_BAD_SIGNATURE,
+			    "SHA-256 specified twice in digest algorithm list");
+	      grub_free (da_path);
+	      goto cleanup_signed_part;
+	    }
+	}
+      else
+	{
+	  err =
+	    grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+			"Only SHA-256 and SHA-512 hashes are supported, found OID %s",
+			algo_oid);
+	  grub_free (da_path);
+	  goto cleanup_signed_part;
+	}
+
+      grub_free (da_path);
+    }
+
+  /* at this point, at least one of sha{256,512}_in_da must be true */
+
+  /*
+   * We ignore the certificates, but we don't permit CRLs.
+   * A CRL entry might be revoking the certificate we're using, and we have
+   * no way of dealing with that at the moment.
+   */
+  res = asn1_read_value (signed_part, "crls", NULL, &crls_size);
+  if (res != ASN1_ELEMENT_NOT_FOUND)
+    {
+      err =
+	grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+		    "PKCS#7 messages with embedded CRLs are not supported");
+      goto cleanup_signed_part;
+    }
+
+  /* read the signatures */
+
+  res = asn1_number_of_elements (signed_part, "signerInfos", &signer_count);
+  if (res != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_SIGNATURE,
+		    "Error counting number of signers: %s",
+		    asn1_strerror (res));
+      goto cleanup_signed_part;
+    }
+
+  if (signer_count <= 0)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_SIGNATURE,
+		    "A minimum of 1 signer is required");
+      goto cleanup_signed_part;
+    }
+
+  msg->signerInfos = grub_calloc (signer_count,
+				  sizeof (struct pkcs7_signerInfo));
+  if (!msg->signerInfos)
+    {
+      err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			"Could not allocate space for %d signers",
+			signer_count);
+      goto cleanup_signed_part;
+    }
+
+  msg->signerInfo_count = 0;
+  for (i = 0; i < signer_count; i++)
+    {
+      si_da_path =
+	grub_xasprintf ("signerInfos.?%d.digestAlgorithm.algorithm", i + 1);
+      if (!si_da_path)
+	{
+	  err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			    "Could not allocate path for signer %d's digest algorithm parsing path",
+			    i);
+	  goto cleanup_signerInfos;
+	}
+
+      algo_oid_size = sizeof (algo_oid);
+      res =
+	asn1_read_value (signed_part, si_da_path, algo_oid, &algo_oid_size);
+      if (res != ASN1_SUCCESS)
+	{
+	  err =
+	    grub_error (GRUB_ERR_BAD_SIGNATURE,
+			"Error reading signer %d's digest algorithm: %s",
+			i, asn1_strerror (res));
+	  grub_free (si_da_path);
+	  goto cleanup_signerInfos;
+	}
+
+      grub_free (si_da_path);
+
+      if (grub_strncmp (sha512_oid, algo_oid, algo_oid_size) == 0)
+	{
+	  if (!sha512_in_da)
+	    {
+	      err =
+		grub_error (GRUB_ERR_BAD_SIGNATURE,
+			    "Signer %d claims a SHA-512 signature which was not specified in the outer DigestAlgorithms",
+			    i);
+	      goto cleanup_signerInfos;
+	    }
+	  else
+	    {
+	      sha512_in_si = true;
+	      msg->signerInfos[i].hash =
+		grub_crypto_lookup_md_by_name ("sha512");
+	    }
+	}
+      else if (grub_strncmp (sha256_oid, algo_oid, algo_oid_size) == 0)
+	{
+	  if (!sha256_in_da)
+	    {
+	      err =
+		grub_error (GRUB_ERR_BAD_SIGNATURE,
+			    "Signer %d claims a SHA-256 signature which was not specified in the outer DigestAlgorithms",
+			    i);
+	      goto cleanup_signerInfos;
+	    }
+	  else
+	    {
+	      sha256_in_si = true;
+	      msg->signerInfos[i].hash =
+		grub_crypto_lookup_md_by_name ("sha256");
+	    }
+	}
+      else
+	{
+	  err =
+	    grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+			"Only SHA-256 and SHA-512 hashes are supported, found OID %s",
+			algo_oid);
+	  goto cleanup_signerInfos;
+	}
+
+      if (!msg->signerInfos[i].hash)
+	{
+	  err =
+	    grub_error (GRUB_ERR_BAD_SIGNATURE,
+			"Hash algorithm for signer %d (OID %s) not loaded", i,
+			algo_oid);
+	  goto cleanup_signerInfos;
+	}
+
+      si_sig_path = grub_xasprintf ("signerInfos.?%d.signature", i + 1);
+      if (!si_sig_path)
+	{
+	  err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			    "Could not allocate path for signer %d's signature parsing path",
+			    i);
+	  goto cleanup_signerInfos;
+	}
+
+      result_buf =
+	grub_asn1_allocate_and_read (signed_part, si_sig_path,
+				     "signature data", &result_size);
+      grub_free (si_sig_path);
+
+      if (!result_buf)
+	{
+	  err = grub_errno;
+	  goto cleanup_signerInfos;
+	}
+
+      gcry_err =
+	gcry_mpi_scan (&(msg->signerInfos[i].sig_mpi), GCRYMPI_FMT_USG,
+		       result_buf, result_size, NULL);
+
+      grub_free (result_buf);
+
+      if (gcry_err != GPG_ERR_NO_ERROR)
+	{
+	  err =
+	    grub_error (GRUB_ERR_BAD_SIGNATURE,
+			"Error loading signature %d into MPI structure: %d",
+			i, gcry_err);
+	  goto cleanup_signerInfos;
+	}
+
+
+      /* use msg->signerInfo_count to track fully populated signerInfos so we
+         know how many we need to clean up */
+      msg->signerInfo_count++;
+    }
+
+  /* Final consistency check of signerInfo.*.digestAlgorithm vs
+     digestAlgorithms.*.algorithm. An algorithm must be present in both
+     digestAlgorithms and signerInfo or in neither. We have already checked
+     for an algorithm in signerInfo that is not in digestAlgorithms, here we
+     check for algorithms in digestAlgorithms but not in signerInfos. */
+  if (sha512_in_da && !sha512_in_si)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+			"SHA-512 specified in DigestAlgorithms but did not appear in SignerInfos");
+      goto cleanup_signerInfos;
+    }
+
+  if (sha256_in_da && !sha256_in_si)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+			"SHA-256 specified in DigestAlgorithms but did not appear in SignerInfos");
+      goto cleanup_signerInfos;
+    }
+
+  asn1_delete_structure (&signed_part);
+  return GRUB_ERR_NONE;
+
+cleanup_signerInfos:
+  for (i = 0; i < msg->signerInfo_count; i++)
+    gcry_mpi_release (msg->signerInfos[i].sig_mpi);
+  grub_free (msg->signerInfos);
+cleanup_signed_part:
+  asn1_delete_structure (&signed_part);
+  return err;
+}
+
+grub_err_t
+parse_pkcs7_signedData (const void *sigbuf, grub_size_t data_size,
+			struct pkcs7_signedData *msg)
+{
+  int res;
+  asn1_node content_info;
+  grub_err_t err = GRUB_ERR_NONE;
+  char content_oid[MAX_OID_LEN];
+  grub_uint8_t *content;
+  int content_size;
+  int content_oid_size = sizeof (content_oid);
+  int size;
+
+  if (data_size > GRUB_INT_MAX)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+		       "Cannot parse a PKCS#7 message where data size > INT_MAX");
+  size = (int) data_size;
+
+  res = asn1_create_element (_gnutls_pkix_asn,
+			     "PKIX1.pkcs-7-ContentInfo", &content_info);
+  if (res != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			 "Could not create ASN.1 structure for PKCS#7 data: %s",
+			 asn1_strerror (res));
+    }
+
+  res = asn1_der_decoding2 (&content_info, sigbuf, &size,
+			    ASN1_DECODE_FLAG_STRICT_DER |
+			    ASN1_DECODE_FLAG_ALLOW_PADDING, asn1_error);
+  if (res != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_SIGNATURE,
+		    "Error decoding PKCS#7 message DER: %s", asn1_error);
+      goto cleanup;
+    }
+
+  /*
+   * ContentInfo ::= SEQUENCE {
+   *     contentType ContentType,
+   *     content [0] EXPLICIT ANY DEFINED BY contentType }
+   *
+   * ContentType ::= OBJECT IDENTIFIER
+   */
+  res =
+    asn1_read_value (content_info, "contentType", content_oid,
+		     &content_oid_size);
+  if (res != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_SIGNATURE,
+		    "Error reading PKCS#7 content type: %s",
+		    asn1_strerror (res));
+      goto cleanup;
+    }
+
+  /* OID for SignedData defined in 5.1 */
+  if (grub_strncmp (signedData_oid, content_oid, content_oid_size) != 0)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_SIGNATURE,
+		    "Unexpected content type in PKCS#7 message: OID %s",
+		    content_oid);
+      goto cleanup;
+    }
+
+  content =
+    grub_asn1_allocate_and_read (content_info, "content",
+				 "PKCS#7 message content", &content_size);
+  if (!content)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+
+  err = process_content (content, content_size, msg);
+  grub_free (content);
+
+cleanup:
+  asn1_delete_structure (&content_info);
+  return err;
+}
+
+/*
+ * Release all the storage associated with the PKCS#7 message.
+ * If the caller dynamically allocated the message, it must free it.
+ */
+void
+pkcs7_signedData_release (struct pkcs7_signedData *msg)
+{
+  grub_ssize_t i;
+
+  for (i = 0; i < msg->signerInfo_count; i++)
+    {
+      gcry_mpi_release (msg->signerInfos[i].sig_mpi);
+    }
+  grub_free (msg->signerInfos);
+}
grub-core/commands/appendedsig/x509.c new file +1082 -0
new file mode 100644
index 000000000000..1aea411905d1
@@ -0,0 +1,1082 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2022 IBM Corporation
+ *
+ *  GRUB is free software: you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation, either version 3 of the License, or
+ *  (at your option) any later version.
+ *
+ *  GRUB is distributed in the hope that it will be useful,
+ *  but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *  GNU General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <grub/libtasn1.h>
+#include <grub/types.h>
+#include <grub/err.h>
+#include <grub/mm.h>
+#include <grub/crypto.h>
+#include <grub/misc.h>
+#include <grub/gcrypt/gcrypt.h>
+
+#include "appendedsig.h"
+
+static char asn1_error[ASN1_MAX_ERROR_DESCRIPTION_SIZE];
+
+/*
+ * RFC 3279 2.3.1  RSA Keys
+ */
+static const char *rsaEncryption_oid = "1.2.840.113549.1.1.1";
+
+/*
+ * RFC 5280 Appendix A
+ */
+static const char *commonName_oid = "2.5.4.3";
+
+/*
+ * RFC 5280 4.2.1.3 Key Usage
+ */
+static const char *keyUsage_oid = "2.5.29.15";
+
+static const grub_uint8_t digitalSignatureUsage = 0x80;
+
+/*
+ * RFC 5280 4.2.1.9 Basic Constraints
+ */
+static const char *basicConstraints_oid = "2.5.29.19";
+
+/*
+ * RFC 5280 4.2.1.12 Extended Key Usage
+ */
+static const char *extendedKeyUsage_oid = "2.5.29.37";
+static const char *codeSigningUsage_oid = "1.3.6.1.5.5.7.3.3";
+
+/*
+ * RFC 3279 2.3.1
+ *
+ *  The RSA public key MUST be encoded using the ASN.1 type RSAPublicKey:
+ *
+ *     RSAPublicKey ::= SEQUENCE {
+ *        modulus            INTEGER,    -- n
+ *        publicExponent     INTEGER  }  -- e
+ *
+ *  where modulus is the modulus n, and publicExponent is the public
+ *  exponent e.
+ */
+static grub_err_t
+grub_parse_rsa_pubkey (grub_uint8_t *der, int dersize,
+		       struct x509_certificate *certificate)
+{
+  int result;
+  asn1_node spk = NULL;
+  grub_uint8_t *m_data, *e_data;
+  int m_size, e_size;
+  grub_err_t err = GRUB_ERR_NONE;
+  gcry_error_t gcry_err;
+
+  result =
+    asn1_create_element (_gnutls_gnutls_asn, "GNUTLS.RSAPublicKey", &spk);
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			 "Cannot create storage for public key ASN.1 data");
+    }
+
+  result = asn1_der_decoding2 (&spk, der, &dersize,
+			       ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
+  if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Cannot decode certificate public key DER: %s",
+		    asn1_error);
+      goto cleanup;
+    }
+
+  m_data =
+    grub_asn1_allocate_and_read (spk, "modulus", "RSA modulus", &m_size);
+  if (!m_data)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+
+  e_data =
+    grub_asn1_allocate_and_read (spk, "publicExponent", "RSA public exponent",
+				 &e_size);
+  if (!e_data)
+    {
+      err = grub_errno;
+      goto cleanup_m_data;
+    }
+
+  /*
+   * convert m, e to mpi
+   *
+   * nscanned is not set for FMT_USG, it's only set for FMT_PGP, 
+   * so we can't verify it
+   */
+  gcry_err =
+    gcry_mpi_scan (&certificate->mpis[0], GCRYMPI_FMT_USG, m_data, m_size,
+		   NULL);
+  if (gcry_err != GPG_ERR_NO_ERROR)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Error loading RSA modulus into MPI structure: %d",
+		    gcry_err);
+      goto cleanup_e_data;
+    }
+
+  gcry_err =
+    gcry_mpi_scan (&certificate->mpis[1], GCRYMPI_FMT_USG, e_data, e_size,
+		   NULL);
+  if (gcry_err != GPG_ERR_NO_ERROR)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Error loading RSA exponent into MPI structure: %d",
+		    gcry_err);
+      goto cleanup_m_mpi;
+    }
+
+  grub_free (e_data);
+  grub_free (m_data);
+  asn1_delete_structure (&spk);
+  return GRUB_ERR_NONE;
+
+cleanup_m_mpi:
+  gcry_mpi_release (certificate->mpis[0]);
+cleanup_e_data:
+  grub_free (e_data);
+cleanup_m_data:
+  grub_free (m_data);
+cleanup:
+  asn1_delete_structure (&spk);
+  return err;
+}
+
+
+/*
+ * RFC 5280:
+ *   SubjectPublicKeyInfo  ::=  SEQUENCE  {
+ *       algorithm            AlgorithmIdentifier,
+ *       subjectPublicKey     BIT STRING  }
+ *
+ * AlgorithmIdentifiers come from RFC 3279, we are not strictly compilant as we
+ * only support RSA Encryption.
+ */
+
+static grub_err_t
+grub_x509_read_subject_public_key (asn1_node asn,
+				   struct x509_certificate *results)
+{
+  int result;
+  grub_err_t err;
+  const char *algo_name =
+    "tbsCertificate.subjectPublicKeyInfo.algorithm.algorithm";
+  const char *params_name =
+    "tbsCertificate.subjectPublicKeyInfo.algorithm.parameters";
+  const char *pk_name =
+    "tbsCertificate.subjectPublicKeyInfo.subjectPublicKey";
+  char algo_oid[MAX_OID_LEN];
+  int algo_size = sizeof (algo_oid);
+  char params_value[2];
+  int params_size = sizeof (params_value);
+  grub_uint8_t *key_data = NULL;
+  int key_size = 0;
+  unsigned int key_type;
+
+  /* algorithm: see notes for rsaEncryption_oid */
+  result = asn1_read_value (asn, algo_name, algo_oid, &algo_size);
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			 "Error reading x509 public key algorithm: %s",
+			 asn1_strerror (result));
+    }
+
+  if (grub_strncmp (algo_oid, rsaEncryption_oid, sizeof (rsaEncryption_oid))
+      != 0)
+    {
+      return grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+			 "Unsupported x509 public key algorithm: %s",
+			 algo_oid);
+    }
+
+  /* 
+   * RFC 3279 2.3.1
+   * The rsaEncryption OID is intended to be used in the algorithm field
+   * of a value of type AlgorithmIdentifier.  The parameters field MUST
+   * have ASN.1 type NULL for this algorithm identifier.
+   */
+  result = asn1_read_value (asn, params_name, params_value, &params_size);
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			 "Error reading x509 public key parameters: %s",
+			 asn1_strerror (result));
+    }
+
+  if (params_value[0] != ASN1_TAG_NULL)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			 "Invalid x509 public key parameters: expected NULL");
+    }
+
+  /*
+   * RFC 3279 2.3.1:  The DER encoded RSAPublicKey is the value of the BIT
+   * STRING subjectPublicKey.
+   */
+  result = asn1_read_value_type (asn, pk_name, NULL, &key_size, &key_type);
+  if (result != ASN1_MEM_ERROR)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			 "Error reading size of x509 public key: %s",
+			 asn1_strerror (result));
+    }
+  if (key_type != ASN1_ETYPE_BIT_STRING)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			 "Unexpected ASN.1 type when reading x509 public key: %x",
+			 key_type);
+    }
+
+  /* length is in bits */
+  key_size = (key_size + 7) / 8;
+
+  key_data = grub_malloc (key_size);
+  if (!key_data)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			 "Out of memory for x509 public key");
+    }
+
+  result = asn1_read_value (asn, pk_name, key_data, &key_size);
+  if (result != ASN1_SUCCESS)
+    {
+      grub_free (key_data);
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			 "Error reading public key data");
+    }
+  key_size = (key_size + 7) / 8;
+
+  err = grub_parse_rsa_pubkey (key_data, key_size, results);
+  grub_free (key_data);
+
+  return err;
+}
+
+/* Decode a string as defined in Appendix A */
+static grub_err_t
+decode_string (char *der, int der_size, char **string,
+	       grub_size_t *string_size)
+{
+  asn1_node strasn;
+  int result;
+  char *choice;
+  int choice_size = 0;
+  int tmp_size = 0;
+  grub_err_t err = GRUB_ERR_NONE;
+
+  result =
+    asn1_create_element (_gnutls_pkix_asn, "PKIX1.DirectoryString", &strasn);
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			 "Could not create ASN.1 structure for certificate: %s",
+			 asn1_strerror (result));
+    }
+
+  result = asn1_der_decoding2 (&strasn, der, &der_size,
+			       ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
+  if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Could not parse DER for DirectoryString: %s",
+		    asn1_error);
+      goto cleanup;
+    }
+
+  choice =
+    grub_asn1_allocate_and_read (strasn, "", "DirectoryString choice",
+				 &choice_size);
+  if (!choice)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+
+  if (grub_strncmp ("utf8String", choice, choice_size) == 0)
+    {
+      result = asn1_read_value (strasn, "utf8String", NULL, &tmp_size);
+      if (result != ASN1_MEM_ERROR)
+	{
+	  err =
+	    grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			"Error reading size of UTF-8 string: %s",
+			asn1_strerror (result));
+	  goto cleanup_choice;
+	}
+    }
+  else if (grub_strncmp ("printableString", choice, choice_size) == 0)
+    {
+      result = asn1_read_value (strasn, "printableString", NULL, &tmp_size);
+      if (result != ASN1_MEM_ERROR)
+	{
+	  err =
+	    grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			"Error reading size of UTF-8 string: %s",
+			asn1_strerror (result));
+	  goto cleanup_choice;
+	}
+    }
+  else
+    {
+      err =
+	grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+		    "Only UTF-8 and printable DirectoryStrings are supported, got %s",
+		    choice);
+      goto cleanup_choice;
+    }
+
+  /* read size does not include trailing null */
+  tmp_size++;
+
+  *string = grub_malloc (tmp_size);
+  if (!*string)
+    {
+      err =
+	grub_error (GRUB_ERR_OUT_OF_MEMORY,
+		    "Cannot allocate memory for DirectoryString contents");
+      goto cleanup_choice;
+    }
+
+  result = asn1_read_value (strasn, choice, *string, &tmp_size);
+  if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Error reading out %s in DirectoryString: %s",
+		    choice, asn1_strerror (result));
+      grub_free (*string);
+      goto cleanup_choice;
+    }
+  *string_size = tmp_size + 1;
+  (*string)[tmp_size] = '\0';
+
+cleanup_choice:
+  grub_free (choice);
+cleanup:
+  asn1_delete_structure (&strasn);
+  return err;
+}
+
+/*
+ * TBSCertificate  ::=  SEQUENCE  {
+ *       version         [0]  EXPLICIT Version DEFAULT v1,
+ * ...
+ * 
+ * Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
+ */
+static grub_err_t
+check_version (asn1_node certificate)
+{
+  int rc;
+  const char *name = "tbsCertificate.version";
+  grub_uint8_t version;
+  int len = sizeof (version);
+
+  rc = asn1_read_value (certificate, name, &version, &len);
+
+  /* require version 3 */
+  if (rc != ASN1_SUCCESS || len != 1)
+    return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		       "Error reading certificate version");
+
+  if (version != 0x02)
+    return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		       "Invalid x509 certificate version, expected v3 (0x02), got 0x%02x",
+		       version);
+
+  return GRUB_ERR_NONE;
+}
+
+/*
+ * This is an X.501 Name, which is complex.
+ *
+ * For simplicity, we extract only the CN.
+ */
+static grub_err_t
+read_name (asn1_node asn, const char *name_path, char **name,
+	   grub_size_t *name_size)
+{
+  int seq_components, set_components;
+  int result;
+  int i, j;
+  char *top_path, *set_path, *type_path, *val_path;
+  char type[MAX_OID_LEN];
+  int type_len = sizeof (type);
+  int string_size = 0;
+  char *string_der;
+  grub_err_t err;
+
+  *name = NULL;
+
+  top_path = grub_xasprintf ("%s.rdnSequence", name_path);
+  if (!top_path)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+		       "Could not allocate memory for %s name parsing path",
+		       name_path);
+
+  result = asn1_number_of_elements (asn, top_path, &seq_components);
+  if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Error counting name components: %s",
+		    asn1_strerror (result));
+      goto cleanup;
+    }
+
+  for (i = 1; i <= seq_components; i++)
+    {
+      set_path = grub_xasprintf ("%s.?%d", top_path, i);
+      if (!set_path)
+	{
+	  err =
+	    grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			"Could not allocate memory for %s name set parsing path",
+			name_path);
+	  goto cleanup_set;
+	}
+      /* this brings us, hopefully, to a set */
+      result = asn1_number_of_elements (asn, set_path, &set_components);
+      if (result != ASN1_SUCCESS)
+	{
+	  err =
+	    grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			"Error counting name sub-components components (element %d): %s",
+			i, asn1_strerror (result));
+	  goto cleanup_set;
+	}
+      for (j = 1; j <= set_components; j++)
+	{
+	  type_path = grub_xasprintf ("%s.?%d.?%d.type", top_path, i, j);
+	  if (!type_path)
+	    {
+	      err =
+		grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			    "Could not allocate memory for %s name component type path",
+			    name_path);
+	      goto cleanup_set;
+	    }
+	  type_len = sizeof (type);
+	  result = asn1_read_value (asn, type_path, type, &type_len);
+	  if (result != ASN1_SUCCESS)
+	    {
+	      err =
+		grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			    "Error reading %s name component type: %s",
+			    name_path, asn1_strerror (result));
+	      goto cleanup_type;
+	    }
+
+	  if (grub_strncmp (type, commonName_oid, type_len) != 0)
+	    {
+	      grub_free (type_path);
+	      continue;
+	    }
+
+	  val_path = grub_xasprintf ("%s.?%d.?%d.value", top_path, i, j);
+	  if (!val_path)
+	    {
+	      err =
+		grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			    "Could not allocate memory for %s name component value path",
+			    name_path);
+	      goto cleanup_set;
+	    }
+
+	  string_der =
+	    grub_asn1_allocate_and_read (asn, val_path, name_path,
+					 &string_size);
+	  if (!string_der)
+	    {
+	      err = grub_errno;
+	      goto cleanup_val_path;
+	    }
+
+	  err = decode_string (string_der, string_size, name, name_size);
+	  if (err)
+	    goto cleanup_string;
+
+	  grub_free (string_der);
+	  grub_free (type_path);
+	  grub_free (val_path);
+	  break;
+	}
+      grub_free (set_path);
+
+      if (*name)
+	break;
+    }
+
+  grub_free (top_path);
+
+  return GRUB_ERR_NONE;
+
+cleanup_string:
+  grub_free (string_der);
+cleanup_val_path:
+  grub_free (val_path);
+cleanup_type:
+  grub_free (type_path);
+cleanup_set:
+  grub_free (set_path);
+cleanup:
+  grub_free (top_path);
+  return err;
+}
+
+/*
+ * Verify the Key Usage extension.
+ * We require the Digital signature usage.
+ */
+static grub_err_t
+verify_key_usage (grub_uint8_t *value, int value_size)
+{
+  asn1_node usageasn;
+  int result;
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_uint8_t usage = 0xff;
+  int usage_size = sizeof (usage_size);
+
+  result =
+    asn1_create_element (_gnutls_pkix_asn, "PKIX1.KeyUsage", &usageasn);
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			 "Could not create ASN.1 structure for key usage");
+    }
+
+  result = asn1_der_decoding2 (&usageasn, value, &value_size,
+			       ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
+  if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Error parsing DER for Key Usage: %s", asn1_error);
+      goto cleanup;
+    }
+
+  result = asn1_read_value (usageasn, "", &usage, &usage_size);
+  if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Error reading Key Usage value: %s",
+		    asn1_strerror (result));
+      goto cleanup;
+    }
+
+  if (!(usage & digitalSignatureUsage))
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE, "Key Usage (0x%x) missing Digital Signature usage",
+		    usage);
+      goto cleanup;
+    }
+
+cleanup:
+  asn1_delete_structure (&usageasn);
+  return err;
+}
+
+/*
+ * BasicConstraints ::= SEQUENCE {
+ *       cA                      BOOLEAN DEFAULT FALSE,
+ *       pathLenConstraint       INTEGER (0..MAX) OPTIONAL }
+ */
+static grub_err_t
+verify_basic_constraints (grub_uint8_t *value, int value_size)
+{
+  asn1_node basicasn;
+  int result;
+  grub_err_t err = GRUB_ERR_NONE;
+  char cA[6];			/* FALSE or TRUE */
+  int cA_size = sizeof (cA);
+
+  result =
+    asn1_create_element (_gnutls_pkix_asn, "PKIX1.BasicConstraints",
+			 &basicasn);
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			 "Could not create ASN.1 structure for Basic Constraints");
+    }
+
+  result = asn1_der_decoding2 (&basicasn, value, &value_size,
+			       ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
+  if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Error parsing DER for Basic Constraints: %s",
+		    asn1_error);
+      goto cleanup;
+    }
+
+  result = asn1_read_value (basicasn, "cA", cA, &cA_size);
+  if (result == ASN1_ELEMENT_NOT_FOUND)
+    {
+      /* Not present, default is False, so this is OK */
+      err = GRUB_ERR_NONE;
+      goto cleanup;
+    }
+  else if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Error reading Basic Constraints cA value: %s",
+		    asn1_strerror (result));
+      goto cleanup;
+    }
+
+  /* The certificate must not be a CA certificate */
+  if (grub_strncmp ("FALSE", cA, cA_size) != 0)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Unexpected CA value: %s",
+			cA);
+      goto cleanup;
+    }
+
+cleanup:
+  asn1_delete_structure (&basicasn);
+  return err;
+}
+
+/*
+ * ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
+ *
+ * KeyPurposeId ::= OBJECT IDENTIFIER
+ */
+static grub_err_t
+verify_extended_key_usage (grub_uint8_t *value, int value_size)
+{
+  asn1_node extendedasn;
+  int result, count;
+  grub_err_t err = GRUB_ERR_NONE;
+  char usage[MAX_OID_LEN];
+  int usage_size = sizeof (usage);
+
+  result =
+    asn1_create_element (_gnutls_pkix_asn, "PKIX1.ExtKeyUsageSyntax",
+			 &extendedasn);
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			 "Could not create ASN.1 structure for Extended Key Usage");
+    }
+
+  result = asn1_der_decoding2 (&extendedasn, value, &value_size,
+			       ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
+  if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Error parsing DER for Extended Key Usage: %s",
+		    asn1_error);
+      goto cleanup;
+    }
+
+  /*
+   * If EKUs are present, there must be exactly 1 usage and it must be a
+   * codeSigning usage. (If we get to this point, we are parsing an EKU
+   * extension and therefore must have a usage. The code that makes having an
+   * EKU extension optional is in verify_extensions.)
+   */
+  result = asn1_number_of_elements (extendedasn, "", &count);
+  if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Error counting number of Extended Key Usages: %s",
+		    asn1_strerror (result));
+      goto cleanup;
+    }
+
+  if (count != 1)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Unexpected number of Extended Key Usages: %d, 1 expected",
+		    count);
+      goto cleanup;
+    }
+
+  result = asn1_read_value (extendedasn, "?1", usage, &usage_size);
+  if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Error reading Extended Key Usage: %s",
+		    asn1_strerror (result));
+      goto cleanup;
+    }
+
+  if (grub_strncmp (codeSigningUsage_oid, usage, usage_size) != 0)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Unexpected Extended Key Usage OID, got: %s", usage);
+      goto cleanup;
+    }
+
+cleanup:
+  asn1_delete_structure (&extendedasn);
+  return err;
+}
+
+/*
+ * Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
+ *
+ * Extension  ::=  SEQUENCE  {
+ *      extnID      OBJECT IDENTIFIER,
+ *      critical    BOOLEAN DEFAULT FALSE,
+ *      extnValue   OCTET STRING
+ *                  -- contains the DER encoding of an ASN.1 value
+ *                  -- corresponding to the extension type identified
+ *                  -- by extnID
+ * }
+ *
+ * A certificate must:
+ *  - contain the Digital Signature usage only
+ *  - not be a CA
+ *  - contain no extended usages, or only a code signing extended usage
+ *  - not contain any other critical extensions (RFC 5280 s 4.2)
+ */
+static grub_err_t
+verify_extensions (asn1_node cert)
+{
+  int result;
+  int ext, num_extensions = 0;
+  int usage_present = 0, constraints_present = 0, extended_usage_present = 0;
+  char *oid_path, *critical_path, *value_path;
+  char extnID[MAX_OID_LEN];
+  int extnID_size;
+  grub_err_t err;
+  char critical[6];		/* we get either "TRUE" or "FALSE" */
+  int critical_size;
+  grub_uint8_t *value;
+  int value_size;
+
+  result =
+    asn1_number_of_elements (cert, "tbsCertificate.extensions",
+			     &num_extensions);
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			 "Error counting number of extensions: %s",
+			 asn1_strerror (result));
+    }
+
+  if (num_extensions < 2)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			 "Insufficient number of extensions for certificate, need at least 2, got %d",
+			 num_extensions);
+    }
+
+  for (ext = 1; ext <= num_extensions; ext++)
+    {
+      oid_path = grub_xasprintf ("tbsCertificate.extensions.?%d.extnID", ext);
+
+      extnID_size = sizeof (extnID);
+      result = asn1_read_value (cert, oid_path, extnID, &extnID_size);
+      if (result != ASN1_SUCCESS)
+	{
+	  err =
+	    grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			"Error reading extension OID: %s",
+			asn1_strerror (result));
+	  goto cleanup_oid_path;
+	}
+
+      critical_path =
+	grub_xasprintf ("tbsCertificate.extensions.?%d.critical", ext);
+      critical_size = sizeof (critical);
+      result =
+	asn1_read_value (cert, critical_path, critical, &critical_size);
+      if (result == ASN1_ELEMENT_NOT_FOUND)
+	{
+	  critical[0] = '\0';
+	}
+      else if (result != ASN1_SUCCESS)
+	{
+	  err =
+	    grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			"Error reading extension criticality: %s",
+			asn1_strerror (result));
+	  goto cleanup_critical_path;
+	}
+
+      value_path =
+	grub_xasprintf ("tbsCertificate.extensions.?%d.extnValue", ext);
+      value =
+	grub_asn1_allocate_and_read (cert, value_path,
+				     "certificate extension value",
+				     &value_size);
+      if (!value)
+	{
+	  err = grub_errno;
+	  goto cleanup_value_path;
+	}
+
+      /*
+       * Now we must see if we recognise the OID.
+       * If we have an unrecognised critical extension we MUST bail.
+       */
+      if (grub_strncmp (keyUsage_oid, extnID, extnID_size) == 0)
+	{
+	  err = verify_key_usage (value, value_size);
+	  if (err != GRUB_ERR_NONE)
+	    {
+	      goto cleanup_value;
+	    }
+	  usage_present++;
+	}
+      else if (grub_strncmp (basicConstraints_oid, extnID, extnID_size) == 0)
+	{
+	  err = verify_basic_constraints (value, value_size);
+	  if (err != GRUB_ERR_NONE)
+	    {
+	      goto cleanup_value;
+	    }
+	  constraints_present++;
+	}
+      else if (grub_strncmp (extendedKeyUsage_oid, extnID, extnID_size) == 0)
+	{
+	  err = verify_extended_key_usage (value, value_size);
+	  if (err != GRUB_ERR_NONE)
+	    {
+	      goto cleanup_value;
+	    }
+	  extended_usage_present++;
+	}
+      else if (grub_strncmp ("TRUE", critical, critical_size) == 0)
+	{
+	  /*
+	   * per the RFC, we must not process a certificate with
+	   * a critical extension we do not understand.
+	   */
+	  err =
+	    grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			"Unhandled critical x509 extension with OID %s",
+			extnID);
+	  goto cleanup_value;
+	}
+
+      grub_free (value);
+      grub_free (value_path);
+      grub_free (critical_path);
+      grub_free (oid_path);
+    }
+
+  if (usage_present != 1)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			 "Unexpected number of Key Usage extensions - expected 1, got %d",
+			 usage_present);
+    }
+  if (constraints_present != 1)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			 "Unexpected number of basic constraints extensions - expected 1, got %d",
+			 constraints_present);
+    }
+  if (extended_usage_present > 1)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE,
+			 "Unexpected number of Extended Key Usage extensions - expected 0 or 1, got %d",
+			 extended_usage_present);
+    }
+  return GRUB_ERR_NONE;
+
+cleanup_value:
+  grub_free (value);
+cleanup_value_path:
+  grub_free (value_path);
+cleanup_critical_path:
+  grub_free (critical_path);
+cleanup_oid_path:
+  grub_free (oid_path);
+  return err;
+}
+
+/*
+ * Parse a certificate whose DER-encoded form is in @data, of size @data_size.
+ * Return the results in @results, which must point to an allocated x509 certificate.
+ */
+grub_err_t
+parse_x509_certificate (const void *data, grub_size_t data_size,
+			struct x509_certificate *results)
+{
+  int result = 0;
+  asn1_node cert;
+  grub_err_t err;
+  int size;
+  int tmp_size;
+
+  if (data_size > GRUB_INT_MAX)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+		       "Cannot parse a certificate where data size > INT_MAX");
+  size = (int) data_size;
+
+  result = asn1_create_element (_gnutls_pkix_asn, "PKIX1.Certificate", &cert);
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+			 "Could not create ASN.1 structure for certificate: %s",
+			 asn1_strerror (result));
+    }
+
+  result = asn1_der_decoding2 (&cert, data, &size,
+			       ASN1_DECODE_FLAG_STRICT_DER, asn1_error);
+  if (result != ASN1_SUCCESS)
+    {
+      err =
+	grub_error (GRUB_ERR_BAD_FILE_TYPE,
+		    "Could not parse DER for certificate: %s", asn1_error);
+      goto cleanup;
+    }
+
+  /* 
+   * TBSCertificate  ::=  SEQUENCE {
+   *     version         [0]  EXPLICIT Version DEFAULT v1
+   */
+  err = check_version (cert);
+  if (err != GRUB_ERR_NONE)
+    {
+      goto cleanup;
+    }
+
+  /*
+   * serialNumber         CertificateSerialNumber,
+   *
+   * CertificateSerialNumber  ::=  INTEGER
+   */
+  results->serial =
+    grub_asn1_allocate_and_read (cert, "tbsCertificate.serialNumber",
+				 "certificate serial number", &tmp_size);
+  if (!results->serial)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+  /*
+   * It's safe to cast the signed int to an unsigned here, we know
+   * length is non-negative
+   */
+  results->serial_len = tmp_size;
+
+  /* 
+   * signature            AlgorithmIdentifier,
+   *
+   * We don't load the signature or issuer at the moment,
+   * as we don't attempt x509 verification.
+   */
+
+  /*
+   * issuer               Name,
+   *
+   * The RFC only requires the serial number to be unique within
+   * issuers, so to avoid ambiguity we _technically_ ought to make
+   * this available.
+   */
+
+  /*
+   * validity             Validity,
+   *
+   * Validity ::= SEQUENCE {
+   *     notBefore      Time,
+   *     notAfter       Time }
+   *
+   * We can't validate this reasonably, we have no true time source on several
+   * platforms. For now we do not parse them.
+   */
+
+  /*
+   * subject              Name,
+   * 
+   * This is an X501 name, we parse out just the CN.
+   */
+  err =
+    read_name (cert, "tbsCertificate.subject", &results->subject,
+	       &results->subject_len);
+  if (err != GRUB_ERR_NONE)
+    goto cleanup_serial;
+
+  /*
+   * TBSCertificate  ::=  SEQUENCE  {
+   *    ...
+   *    subjectPublicKeyInfo SubjectPublicKeyInfo,
+   *    ...
+   */
+  err = grub_x509_read_subject_public_key (cert, results);
+  if (err != GRUB_ERR_NONE)
+    goto cleanup_name;
+
+  /*
+   * TBSCertificate  ::=  SEQUENCE  {
+   *    ...
+   *    extensions      [3]  EXPLICIT Extensions OPTIONAL
+   *                         -- If present, version MUST be v3
+   * }
+   */
+
+  err = verify_extensions (cert);
+  if (err != GRUB_ERR_NONE)
+    goto cleanup_mpis;
+
+  /*
+   * We do not read or check the signature on the certificate:
+   * as discussed we do not try to validate the certificate but trust
+   * it implictly.
+   */
+
+  asn1_delete_structure (&cert);
+  return GRUB_ERR_NONE;
+
+cleanup_mpis:
+  gcry_mpi_release (results->mpis[0]);
+  gcry_mpi_release (results->mpis[1]);
+cleanup_name:
+  grub_free (results->subject);
+cleanup_serial:
+  grub_free (results->serial);
+cleanup:
+  asn1_delete_structure (&cert);
+  return err;
+}
+
+/*
+ * Release all the storage associated with the x509 certificate.
+ * If the caller dynamically allocated the certificate, it must free it.
+ * The caller is also responsible for maintenance of the linked list.
+ */
+void
+certificate_release (struct x509_certificate *cert)
+{
+  grub_free (cert->subject);
+  grub_free (cert->serial);
+  gcry_mpi_release (cert->mpis[0]);
+  gcry_mpi_release (cert->mpis[1]);
+}
Signature · 1 line
2.32.0
#17 lore raw

Re: [PATCH v3 15/19] appended signatures: parse PKCS#7 signedData and X.509 certificates

Hi,

Quoted 7 lines
Quoted 7 lines

This code allows us to parse:

- PKCS#7 signedData messages. Only a single signerInfo is supported, which is all that the Linux sign-file utility supports creating out-of-the-box. Only RSA, SHA-256 and SHA-512 are supported. Any certificate embedded in the PKCS#7 message will be ignored.

Quoted 6 lines
Quoted 3 lines

- X.509 certificates: at least enough to verify the signatures on the PKCS#7 messages. We expect that the certificates embedded in grub will be leaf certificates, not CA certificates. The parser enforces this.

Doesn't grub support CA certificates for EFI?

For EFI, the verification isn't done by grub, it's done by either the shim or by firmware. They do - per the spec - support certificate chaining. So you could validly put a CA cert into db or MokList and have a signature on an Authenticode signature chain back to that.

Quoted 1 line

Why limit to leaf certificates here?

Conventionally, appended signatures don't include embedded certificates whereas Authenticode signatures do. There's nothing stopping you putting one into the PKCS#7 message for an appended signature - it's just not the way they are used on kernel modules or kernel binaries. So if there's not an embedded certificate that can chain back to a CA certificate, grub has to have access to the leaf certificate.

Quoted 3 lines

If this is technical limitation of the code in question could you fail the build when CA certificate is used rather than crashing the bootloader when it boots?

I guess. I think IBM has been reasonably open in saying that static key secure boot is not the end of the road for Power, so we expect that ultimately keys could be loaded from somewhere other than the binary like firmware storage. So even if we added this check in grub-mkimage, we'd still need to keep it at runtime as well.

Quoted 4 lines
Quoted 2 lines

- X.509 certificates support the Extended Key Usage extension and handle it by verifying that the certificate has a single purpose, that is code

                                                ^^^^^^^^^^^^^^

This should be updated I suppose.

So this is - surprisingly - still accurate! We still only support 1 _Extended_ Key Usage. The change that we made as a result of SUSE's bug report was to support additional regular, non-extended key usages. Here's the change broken out:

commit 6056d5fc59907c486309c401135757f00ebf7760

Author: Daniel Axtens <[email protected]>
Date:   Tue Nov 30 15:00:57 2021 +1100

x509: allow Digitial Signature plus other Key Usages

Currently the x509 certificate parser for appended signature verification requires that the certificate have the Digitial Signature key usage and _only_ the Digitial Signature use. This is overly strict and becomes policy enforcement rather than a security property.

Require that the Digitial Signature usage is present, but do not require that it is the only usage present.

grub-core/commands/appendedsig/x509.c +3 -3
index 70480aa73c9d..6ae985b30ff8 100644
@@ -547,7 +547,7 @@ cleanup:
 
 /*
  * Verify the Key Usage extension.
- * We only permit the Digital signature usage.
+ * We require the Digital signature usage.
  */
 static grub_err_t
 verify_key_usage (grub_uint8_t *value, int value_size)
@@ -586,10 +586,10 @@ verify_key_usage (grub_uint8_t *value, int value_size)
       goto cleanup;
     }
 
-  if (usage != digitalSignatureUsage)
+  if (!(usage & digitalSignatureUsage))
     {
       err =
-	grub_error (GRUB_ERR_BAD_FILE_TYPE, "Unexpected Key Usage value: %x",
+	grub_error (GRUB_ERR_BAD_FILE_TYPE, "Key Usage (0x%x) missing Digital Signature usage",
 		    usage);
       goto cleanup;
     }

Kind regards,
Daniel

#18 lore raw

Re: [PATCH v3 15/19] appended signatures: parse PKCS#7 signedData and X.509 certificates

Quoted 39 lines · Daniel Axtens

Hi,

Quoted 7 lines
Quoted 7 lines

This code allows us to parse:

- PKCS#7 signedData messages. Only a single signerInfo is supported, which is all that the Linux sign-file utility supports creating out-of-the-box. Only RSA, SHA-256 and SHA-512 are supported. Any certificate embedded in the PKCS#7 message will be ignored.

Quoted 6 lines
Quoted 3 lines

- X.509 certificates: at least enough to verify the signatures on the PKCS#7 messages. We expect that the certificates embedded in grub will be leaf certificates, not CA certificates. The parser enforces this.

Doesn't grub support CA certificates for EFI?

For EFI, the verification isn't done by grub, it's done by either the shim or by firmware. They do - per the spec - support certificate chaining. So you could validly put a CA cert into db or MokList and have a signature on an Authenticode signature chain back to that.

Quoted 1 line

Why limit to leaf certificates here?

Conventionally, appended signatures don't include embedded certificates whereas Authenticode signatures do. There's nothing stopping you putting one into the PKCS#7 message for an appended signature - it's just not the way they are used on kernel modules or kernel binaries. So if there's not an embedded certificate that can chain back to a CA certificate, grub has to have access to the leaf certificate.

Quoted 3 lines

If this is technical limitation of the code in question could you fail the build when CA certificate is used rather than crashing the bootloader when it boots?

I guess. I think IBM has been reasonably open in saying that static key secure boot is not the end of the road for Power, so we expect that ultimately keys could be loaded from somewhere other than the binary like firmware storage. So even if we added this check in grub-mkimage, we'd still need to keep it at runtime as well.

Quoted 7 lines
Quoted 4 lines
Quoted 2 lines

- X.509 certificates support the Extended Key Usage extension and handle it by verifying that the certificate has a single purpose, that is code

                                                ^^^^^^^^^^^^^^

This should be updated I suppose.

So this is - surprisingly - still accurate! We still only support 1 _Extended_ Key Usage. The change that we made as a result of SUSE's bug

It is unclear to me OpenFirmware enforces such restriction as well ? My understanding is that the (single purpose) restriction is lifed in firmware becuase it happily accepts our cert and boots SUSE signed grub in secure boot without complaining Key Usage. If so I wonder why it is necessary for having the stricter check in grub ?

Quoted 2 lines

report was to support additional regular, non-extended key usages. Here's the change broken out:

Would this change be used next version ?

Thanks,
Michael

Quoted 52 lines

commit 6056d5fc59907c486309c401135757f00ebf7760

Author: Daniel Axtens <[email protected]>
Date:   Tue Nov 30 15:00:57 2021 +1100

x509: allow Digitial Signature plus other Key Usages

Currently the x509 certificate parser for appended signature verification requires that the certificate have the Digitial Signature key usage and _only_ the Digitial Signature use. This is overly strict and becomes policy enforcement rather than a security property.

Require that the Digitial Signature usage is present, but do not require that it is the only usage present.

grub-core/commands/appendedsig/x509.c +3 -3
index 70480aa73c9d..6ae985b30ff8 100644
@@ -547,7 +547,7 @@ cleanup:
 
 /*
  * Verify the Key Usage extension.
- * We only permit the Digital signature usage.
+ * We require the Digital signature usage.
  */
 static grub_err_t
 verify_key_usage (grub_uint8_t *value, int value_size)
@@ -586,10 +586,10 @@ verify_key_usage (grub_uint8_t *value, int value_size)
       goto cleanup;
     }
 
-  if (usage != digitalSignatureUsage)
+  if (!(usage & digitalSignatureUsage))
     {
       err =
-	grub_error (GRUB_ERR_BAD_FILE_TYPE, "Unexpected Key Usage value: %x",
+	grub_error (GRUB_ERR_BAD_FILE_TYPE, "Key Usage (0x%x) missing Digital Signature usage",
 		    usage);
       goto cleanup;
     }

Kind regards,
Daniel

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

#19 lore raw

Re: [PATCH v3 15/19] appended signatures: parse PKCS#7 signedData and X.509 certificates

Hi Michael,

apologies for the delay, I've left IBM and am taking a while to get back on my feet.

Quoted 45 lines · Daniel Axtens
Quoted 44 lines

Hi,

Quoted 7 lines
Quoted 7 lines

This code allows us to parse:

- PKCS#7 signedData messages. Only a single signerInfo is supported, which is all that the Linux sign-file utility supports creating out-of-the-box. Only RSA, SHA-256 and SHA-512 are supported. Any certificate embedded in the PKCS#7 message will be ignored.

Quoted 6 lines
Quoted 3 lines

- X.509 certificates: at least enough to verify the signatures on the PKCS#7 messages. We expect that the certificates embedded in grub will be leaf certificates, not CA certificates. The parser enforces this.

Doesn't grub support CA certificates for EFI?

For EFI, the verification isn't done by grub, it's done by either the shim or by firmware. They do - per the spec - support certificate chaining. So you could validly put a CA cert into db or MokList and have a signature on an Authenticode signature chain back to that.

Quoted 1 line

Why limit to leaf certificates here?

Conventionally, appended signatures don't include embedded certificates whereas Authenticode signatures do. There's nothing stopping you putting one into the PKCS#7 message for an appended signature - it's just not the way they are used on kernel modules or kernel binaries. So if there's not an embedded certificate that can chain back to a CA certificate, grub has to have access to the leaf certificate.

Quoted 3 lines

If this is technical limitation of the code in question could you fail the build when CA certificate is used rather than crashing the bootloader when it boots?

I guess. I think IBM has been reasonably open in saying that static key secure boot is not the end of the road for Power, so we expect that ultimately keys could be loaded from somewhere other than the binary like firmware storage. So even if we added this check in grub-mkimage, we'd still need to keep it at runtime as well.

Quoted 4 lines
Quoted 2 lines

- X.509 certificates support the Extended Key Usage extension and handle it by verifying that the certificate has a single purpose, that is code

                                                ^^^^^^^^^^^^^^

This should be updated I suppose.

Quoted 8 lines
Quoted 2 lines

So this is - surprisingly - still accurate! We still only support 1 _Extended_ Key Usage. The change that we made as a result of SUSE's bug

It is unclear to me OpenFirmware enforces such restriction as well ? My understanding is that the (single purpose) restriction is lifed in firmware becuase it happily accepts our cert and boots SUSE signed grub in secure boot without complaining Key Usage. If so I wonder why it is necessary for having the stricter check in grub ?

I suppose it depends on the particular OpenFirmware implementation. You would have to ask IBM via official channels what restrictions the proprietary firmware imposes. The SLOF prototype probably imposes no restrictions because it was thrown together very very quickly as a proof of concept and development tool.

I do still want to tease out (or repeat ad nauseum) the difference between Key Usage and Extended Key Usage. The original code permitted a Key Usage of only Digitial Signature and no critical Extended Key Usages. Subsequent versions, such as this one, support multiple Key Usages, so long as the Digital Signature Usage is present, and either zero or one Extended Key Usage sections, which permit only the Code Signing EKU.

AIUI/IIRC, SUSE OBS keys have Digital Signature and another Key Usage set - which was where we ran into issues with your keys.

Quoted 5 lines
Quoted 2 lines

report was to support additional regular, non-extended key usages. Here's the change broken out:

Would this change be used next version ?

The next proprietary firmware version, or the next revision of this series? I don't have any insights into the future firmware development. For grub, that change is part of this v3 series already.

Kind regards,
Daniel

Quoted 61 lines

Thanks,
Michael

Quoted 45 lines

commit 6056d5fc59907c486309c401135757f00ebf7760

Author: Daniel Axtens <[email protected]>
Date:   Tue Nov 30 15:00:57 2021 +1100

x509: allow Digitial Signature plus other Key Usages

Currently the x509 certificate parser for appended signature verification requires that the certificate have the Digitial Signature key usage and _only_ the Digitial Signature use. This is overly strict and becomes policy enforcement rather than a security property.

Require that the Digitial Signature usage is present, but do not require that it is the only usage present.

grub-core/commands/appendedsig/x509.c +3 -3
index 70480aa73c9d..6ae985b30ff8 100644
@@ -547,7 +547,7 @@ cleanup:
 
 /*
  * Verify the Key Usage extension.
- * We only permit the Digital signature usage.
+ * We require the Digital signature usage.
  */
 static grub_err_t
 verify_key_usage (grub_uint8_t *value, int value_size)
@@ -586,10 +586,10 @@ verify_key_usage (grub_uint8_t *value, int value_size)
       goto cleanup;
     }
 
-  if (usage != digitalSignatureUsage)
+  if (!(usage & digitalSignatureUsage))
     {
       err =
-	grub_error (GRUB_ERR_BAD_FILE_TYPE, "Unexpected Key Usage value: %x",
+	grub_error (GRUB_ERR_BAD_FILE_TYPE, "Key Usage (0x%x) missing Digital Signature usage",
 		    usage);
       goto cleanup;
     }
Quoted 7 lines

Kind regards,
Daniel

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel

#20 lore raw

PATCH v3 16/19 appended signatures: support verifying appended signatures

In reply to Daniel Axtens

Building on the parsers and the ability to embed x509 certificates, as well as the existing gcrypt functionality, add a module for verifying appended signatures.

This includes a verifier that requires that Linux kernels and grub modules have appended signatures, and commands to manage the list of trusted certificates for verification.

Verification must be enabled by setting check_appended_signatures. If GRUB is locked down when the module is loaded, verification will be enabled and locked automatically.

As with the PGP verifier, it is not a complete secure-boot solution:
other mechanisms, such as a password or lockdown, must be used to ensure that a user cannot drop to the grub shell and disable verification.

---

v3: Correct copyright header, fix some nits from Stefan.

v2 changes:

- Improve x509 parser function name
- Constify data parameters in function signatures
- Support multiple signers
- Use an enum rather than 0, 1 and 2 for various signature enforcement states.
- Spin out a file reading function that was duplicated.
- Fix some code style and clarity issues.

Thanks to Nayna Jain and Stefan Berger for their reviews.

---
 grub-core/Makefile.core.def                  |  14 +
 grub-core/commands/appendedsig/appendedsig.c | 662 +++++++++++++++++++
 include/grub/file.h                          |   2 +
 3 files changed, 678 insertions(+)
 create mode 100644 grub-core/commands/appendedsig/appendedsig.c
grub-core/Makefile.core.def +14 -0
index de5c763c64a0..2dc450a83398 100644
@@ -951,6 +951,20 @@ module = {
   cppflags = '-I$(srcdir)/lib/posix_wrap';
 };
 
+module = {
+  name = appendedsig;
+  common = commands/appendedsig/appendedsig.c;
+  common = commands/appendedsig/x509.c;
+  common = commands/appendedsig/pkcs7.c;
+  common = commands/appendedsig/asn1util.c;
+  common = commands/appendedsig/gnutls_asn1_tab.c;
+  common = commands/appendedsig/pkix_asn1_tab.c;
+
+  // posix wrapper required for gcry to get sys/types.h
+  cflags = '$(CFLAGS_POSIX)';
+  cppflags = '-I$(srcdir)/lib/posix_wrap';
+};
+
 module = {
   name = hdparm;
   common = commands/hdparm.c;
grub-core/commands/appendedsig/appendedsig.c new file +662 -0

662 lines not on this page · raw message

include/grub/file.h +2 -0
index 31567483ccfc..96827a4f8961 100644
@@ -80,6 +80,8 @@ enum grub_file_type
     GRUB_FILE_TYPE_PUBLIC_KEY,
     /* File holding public key to add to trused keys.  */
     GRUB_FILE_TYPE_PUBLIC_KEY_TRUST,
+    /* File holding x509 certificiate to add to trusted keys.  */
+    GRUB_FILE_TYPE_CERTIFICATE_TRUST,
     /* File of which we intend to print a blocklist to the user.  */
     GRUB_FILE_TYPE_PRINT_BLOCKLIST,
     /* File we intend to use for test loading or testing speed.  */
Signature · 1 line
2.32.0
#21 lore raw

PATCH v3 17/19 appended signatures: verification tests

In reply to Daniel Axtens

These tests are run through all_functional_test and test a range of commands and behaviours.

---

v3: clean up error codes at the start, fix copyright headers.

v2 changes:

- add a test for EKU
- add tests for files signed with multiple signers
- add a test of padded PKCS#7 messages
- use macros to reduce duplication for exposing certificate files to the test via procfs
- more useful comments

---
 grub-core/Makefile.core.def               |   6 +
 grub-core/tests/appended_signature_test.c | 275 ++++++
 grub-core/tests/appended_signatures.h     | 975 ++++++++++++++++++++++
 grub-core/tests/lib/functional_test.c     |   1 +
 4 files changed, 1257 insertions(+)
 create mode 100644 grub-core/tests/appended_signature_test.c
 create mode 100644 grub-core/tests/appended_signatures.h
grub-core/Makefile.core.def +6 -0
index 2dc450a83398..3bc10095d0fa 100644
@@ -2136,6 +2136,12 @@ module = {
   common = tests/setjmp_test.c;
 };
 
+module = {
+  name = appended_signature_test;
+  common = tests/appended_signature_test.c;
+  common = tests/appended_signatures.h;
+};
+
 module = {
   name = signature_test;
   common = tests/signature_test.c;
grub-core/tests/appended_signature_test.c new file +275 -0

275 lines not on this page · raw message

grub-core/tests/appended_signatures.h new file +975 -0

975 lines not on this page · raw message

grub-core/tests/lib/functional_test.c +1 -0
index 96781fb39b5f..403fa5c789ab 100644
@@ -73,6 +73,7 @@ grub_functional_all_tests (grub_extcmd_context_t ctxt __attribute__ ((unused)),
   grub_dl_load ("xnu_uuid_test");
   grub_dl_load ("pbkdf2_test");
   grub_dl_load ("signature_test");
+  grub_dl_load ("appended_signature_test");
   grub_dl_load ("sleep_test");
   grub_dl_load ("bswap_test");
   grub_dl_load ("ctz_test");
Signature · 1 line
2.32.0
#22 lore raw

PATCH v3 18/19 appended signatures: documentation

In reply to Daniel Axtens

This explains how appended signatures can be used to form part of a secure boot chain, and documents the commands and variables introduced.

---
v3: fix CR->LF, thanks Stefan Berger.
v2: fix a grammar issue, thanks Stefan Berger.

---
 docs/grub.texi | 193 ++++++++++++++++++++++++++++++++++++++++++++-----
 1 file changed, 176 insertions(+), 17 deletions(-)
docs/grub.texi +176 -17
index a7f5f6cd154c..605cac768e28 100644
@@ -3251,6 +3251,7 @@ These variables have special meaning to GRUB.
 
 @menu
 * biosnum::
+* check_appended_signatures::
 * check_signatures::
 * chosen::
 * cmdpath::
@@ -3310,11 +3311,18 @@ For an alternative approach which also changes BIOS drive mappings for the
 chain-loaded system, @pxref{drivemap}.
 
 
+@node check_appended_signatures
+@subsection check_appended_signatures
+
+This variable controls whether GRUB enforces appended signature validation on
+certain loaded files. @xref{Using appended signatures}.
+
+
 @node check_signatures
 @subsection check_signatures
 
-This variable controls whether GRUB enforces digital signature
-validation on loaded files. @xref{Using digital signatures}.
+This variable controls whether GRUB enforces GPG-style digital signature
+validation on loaded files. @xref{Using GPG-style digital signatures}.
 
 @node chosen
 @subsection chosen
@@ -4038,6 +4046,7 @@ you forget a command, you can run the command @command{help}
 * date::                        Display or set current date and time
 * devicetree::                  Load a device tree blob
 * distrust::                    Remove a pubkey from trusted keys
+* distrust_certificate::        Remove a certificate from the list of trusted certificates
 * drivemap::                    Map a drive to another
 * echo::                        Display a line of text
 * eval::                        Evaluate agruments as GRUB commands
@@ -4054,6 +4063,7 @@ you forget a command, you can run the command @command{help}
 * keystatus::                   Check key modifier status
 * linux::                       Load a Linux kernel
 * linux16::                     Load a Linux kernel (16-bit mode)
+* list_certificates::           List trusted certificates
 * list_env::                    List variables in environment block
 * list_trusted::                List trusted public keys
 * load_env::                    Load variables from environment block
@@ -4091,8 +4101,10 @@ you forget a command, you can run the command @command{help}
 * test::                        Check file types and compare values
 * true::                        Do nothing, successfully
 * trust::                       Add public key to list of trusted keys
+* trust_certificate::           Add an x509 certificate to the list of trusted certificates
 * unset::                       Unset an environment variable
 @comment * vbeinfo::                     List available video modes
+* verify_appended::             Verify appended digital signature
 * verify_detached::             Verify detached digital signature
 * videoinfo::                   List available video modes
 @comment * xen_*::              Xen boot commands for AArch64
@@ -4422,9 +4434,28 @@ These keys are used to validate signatures when environment variable
 @code{check_signatures} is set to @code{enforce}
 (@pxref{check_signatures}), and by some invocations of
 @command{verify_detached} (@pxref{verify_detached}).  @xref{Using
-digital signatures}, for more information.
+GPG-style digital signatures}, for more information.
+@end deffn
+
+
+@node distrust_certificate
+@subsection distrust_certificate
+
+@deffn Command distrust_certificate cert_number
+Remove the x509 certificate numbered @var{cert_number} from GRUB's keyring of
+trusted x509 certificates for verifying appended signatures.
+
+@var{cert_number} is the certificate number as listed by
+@command{list_certificates} (@pxref{list_certificates}).
+
+These certificates are used to validate appended signatures when environment
+variable @code{check_appended_signatures} is set to @code{enforce}
+(@pxref{check_appended_signatures}), and by @command{verify_appended}
+(@pxref{verify_appended}). See @xref{Using appended signatures} for more
+information.
 @end deffn
 
+
 @node drivemap
 @subsection drivemap
 
@@ -4682,6 +4713,21 @@ This command is only available on x86 systems.
 @end deffn
 
 
+@node list_certificates
+@subsection list_certificates
+
+@deffn Command list_certificates
+List all x509 certificates trusted by GRUB for validating appended signatures.
+The output is a numbered list of certificates, showing the certificate's serial
+number and Common Name.
+
+The certificate number can be used as an argument to
+@command{distrust_certificate} (@pxref{distrust_certificate}).
+
+See @xref{Using appended signatures} for more information.
+@end deffn
+
+
 @node list_env
 @subsection list_env
 
@@ -4701,7 +4747,7 @@ The output is in GPG's v4 key fingerprint format (i.e., the output of
 @code{gpg --fingerprint}).  The least significant four bytes (last
 eight hexadecimal digits) can be used as an argument to
 @command{distrust} (@pxref{distrust}).
-@xref{Using digital signatures}, for more information about uses for
+@xref{Using GPG-style digital signatures}, for more information about uses for
 these keys.
 @end deffn
 
@@ -4736,8 +4782,12 @@ When used with care, @option{--skip-sig} and the whitelist enable an
 administrator to configure a system to boot only signed
 configurations, but to allow the user to select from among multiple
 configurations, and to enable ``one-shot'' boot attempts and
-``savedefault'' behavior.  @xref{Using digital signatures}, for more
+``savedefault'' behavior.  @xref{Using GPG-style digital signatures}, for more
 information.
+
+Extra care should be taken when combining this command with appended signatures
+(@pxref{Using appended signatures}), as this file is not validated by an
+appended signature and could set @code{check_appended_signatures=no}.
 @end deffn
 
 
@@ -5034,7 +5084,7 @@ read.  It is possible to modify a digitally signed environment block
 file from within GRUB using this command, such that its signature will
 no longer be valid on subsequent boots.  Care should be taken in such
 advanced configurations to avoid rendering the system
-unbootable. @xref{Using digital signatures}, for more information.
+unbootable. @xref{Using GPG-style digital signatures}, for more information.
 @end deffn
 
 
@@ -5446,11 +5496,31 @@ signatures when environment variable @code{check_signatures} is set to
 must itself be properly signed.  The @option{--skip-sig} option can be
 used to disable signature-checking when reading @var{pubkey_file}
 itself. It is expected that @option{--skip-sig} is useful for testing
-and manual booting. @xref{Using digital signatures}, for more
+and manual booting. @xref{Using GPG-style digital signatures}, for more
 information.
 @end deffn
 
 
+@node trust_certificate
+@subsection trust_certificate
+
+@deffn Command trust_certificate x509_certificate
+Read a DER-formatted x509 certificate from the file @var{x509_certificate}
+and add it to GRUB's internal list of trusted x509 certificates. These
+certificates are used to validate appended signatures when the environment
+variable @code{check_appended_signatures} is set to @code{enforce}.
+
+Note that if @code{check_appended_signatures} is set to @code{enforce}
+when @command{trust_certificate} is executed, then @var{x509_certificate}
+must itself bear an appended signature. (It is not sufficient that
+@var{x509_certificate} be signed by a trusted certificate according to the
+x509 rules: grub does not include support for validating signatures within x509
+certificates themselves.)
+
+See @xref{Using appended signatures} for more information.
+@end deffn
+
+
 @node unset
 @subsection unset
 
@@ -5469,6 +5539,18 @@ only on PC BIOS platforms.
 @end deffn
 @end ignore
 
+@node verify_appended
+@subsection verify_appended
+
+@deffn Command verify_appended file
+Verifies an appended signature on @var{file} against the trusted certificates
+known to GRUB (See @pxref{list_certificates}, @pxref{trust_certificate}, and
+@pxref{distrust_certificate}).
+
+Exit code @code{$?} is set to 0 if the signature validates
+successfully.  If validation fails, it is set to a non-zero value.
+See @xref{Using appended signatures}, for more information.
+@end deffn
 
 @node verify_detached
 @subsection verify_detached
@@ -5487,7 +5569,7 @@ tried.
 
 Exit code @code{$?} is set to 0 if the signature validates
 successfully.  If validation fails, it is set to a non-zero value.
-@xref{Using digital signatures}, for more information.
+@xref{Using GPG-style digital signatures}, for more information.
 @end deffn
 
 @node videoinfo
@@ -5853,13 +5935,14 @@ environment variables and commands are listed in the same order.
 @chapter Security
 
 @menu
-* Authentication and authorisation:: Users and access control
-* Using digital signatures::         Booting digitally signed code
-* UEFI secure boot and shim::        Booting digitally signed PE files
-* Secure Boot Advanced Targeting::   Embedded information for generation number based revocation
-* Measured Boot::                    Measuring boot components
-* Lockdown::                         Lockdown when booting on a secure setup
-* Signing GRUB itself::              Ensuring the integrity of the GRUB core image
+* Authentication and authorisation::   Users and access control
+* Using GPG-style digital signatures:: Booting digitally signed code
+* Using appended signatures::          An alternative approach to booting digitally signed code
+* UEFI secure boot and shim::          Booting digitally signed PE files
+* Secure Boot Advanced Targeting::     Embedded information for generation number based revocation
+* Measured Boot::                      Measuring boot components
+* Lockdown::                           Lockdown when booting on a secure setup
+* Signing GRUB itself::                Ensuring the integrity of the GRUB core image
 @end menu
 
 @node Authentication and authorisation
@@ -5933,8 +6016,8 @@ generating configuration files with authentication.  You can use
 adding @kbd{set superusers=} and @kbd{password} or @kbd{password_pbkdf2}
 commands.
 
-@node Using digital signatures
-@section Using digital signatures in GRUB
+@node Using GPG-style digital signatures
+@section Using GPG-style digital signatures in GRUB
 
 GRUB's @file{core.img} can optionally provide enforcement that all files
 subsequently read from disk are covered by a valid digital signature.
@@ -6017,6 +6100,82 @@ or BIOS) configuration to cause the machine to boot from a different
 (attacker-controlled) device.  GRUB is at best only one link in a
 secure boot chain.
 
+@node Using appended signatures
+@section Using appended signatures in GRUB
+
+GRUB supports verifying Linux-style 'appended signatures' for secure boot.
+Appended signatures are PKCS#7 messages containing a signature over the
+contents of a file, plus some metadata, appended to the end of a file. A file
+with an appended signature ends with the magic string:
+
+@example
+~Module signature appended~\n
+@end example
+
+where @code{\n} represents the line-feed character, @code{0x0a}.
+
+To enable appended signature verification, load the appendedsig module and an
+x509 certificate for verification. Building the appendedsig module into the
+core grub image is recommended.
+
+Certificates can be managed at boot time using the @pxref{trust_certificate},
+@pxref{distrust_certificate} and @pxref{list_certificates} commands.
+Certificates can also be built in to the core image using the @code{--x509}
+parameter to @command{grub-install} or @command{grub-mkimage}.
+
+A file can be explictly verified using the @pxref{verify_appended} command.
+
+Only signatures made with the SHA-256 or SHA-512 hash algorithm are supported,
+and only RSA signatures are supported.
+
+A file can be signed with the @command{sign-file} utility supplied with the
+Linux kernel source. For example, if you have @code{signing.key} as the private
+key and @code{certificate.der} as the x509 certificate containing the public key:
+
+@example
+sign-file SHA256 signing.key certificate.der vmlinux vmlinux.signed
+@end example
+
+Enforcement of signature verification is controlled by the
+@code{check_appended_signatures} variable. Verification will only take place
+when files are loaded if the variable is set to @code{enforce}. If a
+certificate is built into the grub core image with the @code{--x509} parameter,
+the variable will be automatically set to @code{enforce} when the appendedsig
+module is loaded.
+
+Unlike GPG-style signatures, not all files loaded by GRUB are required to be
+signed. Once verification is turned on, the following file types must carry
+appended signatures:
+
+@enumerate
+@item Linux, Multiboot, BSD, XNU and Plan9 kernels
+@item Grub modules, except those built in to the core image
+@item Any new certificate files to be trusted
+@end enumerate
+
+ACPI tables and Device Tree images will not be checked for appended signatures
+but must be verified by another mechanism such as GPG-style signatures before
+they will be loaded.
+
+No attempt is made to validate any other file type. In particular,
+chain-loaded binaries are not verified - if your platform supports
+chain-loading and this cannot be disabled, consider an alternative secure
+boot mechanism.
+
+As with GPG-style appended signatures, signature checking does @strong{not}
+stop an attacker with console access from dropping manually to the GRUB
+console and executing:
+
+@example
+set check_appended_signatures=no
+@end example
+
+Refer to the section on password-protecting GRUB (@pxref{Authentication
+and authorisation}) for more information on preventing this.
+
+Additionally, special care must be taken around the @command{loadenv} command,
+which can be used to turn off @code{check_appended_signature}.
+
 @node UEFI secure boot and shim
 @section UEFI secure boot and shim support
 
Signature · 1 line
2.32.0
#23 lore raw

PATCH v3 19/19 ieee1275: enter lockdown based on /ibm,secure-boot

In reply to Daniel Axtens

If the 'ibm,secure-boot' property of the root node is 2 or greater, enter lockdown.

---
 docs/grub.texi                 |  4 ++--
 grub-core/Makefile.core.def    |  1 +
 grub-core/kern/ieee1275/init.c | 27 +++++++++++++++++++++++++++
 include/grub/lockdown.h        |  3 ++-
 4 files changed, 32 insertions(+), 3 deletions(-)
docs/grub.texi +2 -2
index 605cac768e28..f89c1e86214a 100644
@@ -6253,8 +6253,8 @@ Measured boot is currently only supported on EFI platforms.
 @section Lockdown when booting on a secure setup
 
 The GRUB can be locked down when booted on a secure boot environment, for example
-if the UEFI secure boot is enabled. On a locked down configuration, the GRUB will
-be restricted and some operations/commands cannot be executed.
+if UEFI or Power secure boot is enabled. On a locked down configuration, the
+GRUB will be restricted and some operations/commands cannot be executed.
 
 The @samp{lockdown} variable is set to @samp{y} when the GRUB is locked down.
 Otherwise it does not exit.
grub-core/Makefile.core.def +1 -0
index 3bc10095d0fa..67940de38943 100644
@@ -319,6 +319,7 @@ kernel = {
   powerpc_ieee1275 = kern/powerpc/cache.S;
   powerpc_ieee1275 = kern/powerpc/dl.c;
   powerpc_ieee1275 = kern/powerpc/compiler-rt.S;
+  powerpc_ieee1275 = kern/lockdown.c;
 
   sparc64_ieee1275 = kern/sparc64/cache.S;
   sparc64_ieee1275 = kern/sparc64/dl.c;
grub-core/kern/ieee1275/init.c +27 -0
index ec591e6e13ec..f59f08d980a1 100644
@@ -44,6 +44,7 @@
 #ifdef __sparc__
 #include <grub/machine/kernel.h>
 #endif
+#include <grub/lockdown.h>
 
 /* The maximum heap size we're going to claim at boot. Not used by sparc. */
 #ifdef __i386__
@@ -631,6 +632,30 @@ grub_parse_cmdline (void)
     }
 }
 
+static void
+grub_get_ieee1275_secure_boot (void)
+{
+  grub_ieee1275_phandle_t root;
+  int rc;
+  grub_uint32_t is_sb;
+
+  grub_ieee1275_finddevice ("/", &root);
+
+  rc = grub_ieee1275_get_integer_property (root, "ibm,secure-boot", &is_sb,
+                                           sizeof (is_sb), 0);
+
+  /* ibm,secure-boot:
+   * 0 - disabled
+   * 1 - audit
+   * 2 - enforce
+   * 3 - enforce + OS-specific behaviour
+   *
+   * We only support enforce.
+   */
+  if (rc >= 0 && is_sb >= 2)
+    grub_lockdown ();
+}
+
 grub_addr_t grub_modbase;
 
 void
@@ -656,6 +681,8 @@ grub_machine_init (void)
 #else
   grub_install_get_time_ms (grub_rtc_get_time_ms);
 #endif
+
+  grub_get_ieee1275_secure_boot ();
 }
 
 void
include/grub/lockdown.h +2 -1
index 40531fa823bf..ebfee4bf06e7 100644
@@ -24,7 +24,8 @@
 #define GRUB_LOCKDOWN_DISABLED       0
 #define GRUB_LOCKDOWN_ENABLED        1
 
-#ifdef GRUB_MACHINE_EFI
+#if defined(GRUB_MACHINE_EFI) || \
+    (defined(__powerpc__) && defined(GRUB_MACHINE_IEEE1275))
 extern void
 EXPORT_FUNC (grub_lockdown) (void);
 extern int
Signature · 1 line
2.32.0