Skip to contentSkip to conversation

Appended Signature Secure Boot Support for PowerPC

PATCH Superseded Sudhakar Kuppusamy 5 participants 83 messages Dec 18, 2024 – Feb 27, 2025 Page 1 of 3

v1 of 18 Superseded Latest is v18 →

lore
Share & tools
lore
#0 lore raw

cover Appended Signature Secure Boot Support for PowerPC

Linux on Power LPAR secure boot ensures the integrity of the Linux boot stack. The hypervisor and partition firmware are part of the core root of trust. The partition firmware verifies the signature on the GRUB image before handing control to GRUB. Similarly, GRUB verifies the signature on the kernel image before booting the OS. This ensures that every image running at the boot time is verified and trusted. UEFI platforms relies on PECOFF based signature scheme. Since Power is not a UEFI platform, an alternative mechanism is needed. Power already uses appended signatures on the Linux Kernel, and is now extended to sign the grub as well.

Linux on Power also allows multiple signers, and if any one of the signature passes, then the image passes the validation. Appended signature scheme uses CMS structure to contain signatures. On Power, the multiple signature support relies on the multiple signers features already supported by CMS standards. It does require that all the signers should sign at the same time and are not allowed to add or remove the signatures randomly.

By default, Linux LPAR secure boot uses static key management[1]. This means that each image embeds the keys it needs to verify the image it loads. For example, the keys used to verify the GRUB image are built into the firmware image. Similarly, the keys used for verifying the kernel image are built into the GRUB image. These are pre-defined keys and they cannot be modified at runtime. The drawback of this approach is that key rotations results in both firmware and OS updates. This is where dynamic key management is useful.

An admin can switch from static keys to dynamic keys by coordinating with Hardware Management Console(HMC) admin and enabling the required flags for the given LPAR.

The dynamic key management relies on the Platform KeyStore(PKS)[2] storage allocation for each LPAR with individually managed access controls to store sensitive information securely. Once switched to dynamic keys, HMC advertises this flag to the PowerVM, which then initializes the PKS with the default secvars. It also creates a variable SB_VERSION that represents the secure boot key management mode. The default secvars are used by Partition firmware, grub and the linux kernel to reads keys for verification. These secvars can be managed by user interface exposed via linux kernel. The linux kernel already supports this interface and it is available in the upstream kernel.

This patchset adds the appended signature support both for signing and verification and the key management to the grub component. The whole patchset can be split into following four main parts:

The series has following four main parts:

1.) Sign grub.elf with an appended signature. (Patches 1 - 3)

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.) Enable appended signature verification using builtin keys (Patches 4 - 10).

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 allows x509 certificates to be built in to the grub core in much the same way as PGP keys.

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

- patch 9 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 10 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 11 adds tests, and patch 12 adds documentation.

3.) Enable lockdown if secure boot is enabled (Patch 13)

If the 'ibm,secure-boot' property of the root node is 2 or greater, enter lockdown.The main appended signature module now tests for lockdown to enter 'forced' mode.

4.) Enable accessing keys dynamically from Platform KeyStore (Patch 14 - 21)

This part teaches grub how to read db and dbx variables from platform keystore using client interface call then load keys from those two variable, and use it to verify Linux kernel.

This section is composed of the following patches:

- patch 14 is an exposes an interface in ieee1275 for reading secure boot variable db and dbx from Platform Keystore.

- patch 15 is a read secure boot variables such as db and dbx from PKS and extract certificates from ESL.

- patch 16 is creates the trusted and distrusted lists.

- patch 17 is verify the kernel using trusted and distrusted lists

- patch 18 sets the use_static_keys flag if DB not available in PKS, and patch 19 is reads the DB default keys from ELF Note and store it in trusted lists if use_static_keys flag is set.

- patch 20 adds trusted and distrusted commands, and patch 21 adds documentation.

[1]https://www.ibm.com/docs/en/linux-on-systems?topic=servers-guest-secure-boot-static-keys [2]https://community.ibm.com/community/user/power/blogs/chris-engel1/2020/11/20/powervm-introduces-the-platform-keystore

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

Daniel Axtens (11):
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 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):
powerpc-ieee1275: Add support for signing grub with an appended
signature

Sudhakar Kuppusamy (8):
ieee1275: Platform Keystore (PKS) Support
ieee1275: Read the DB and DBX secure boot variables
appendedsig: The creation of trusted and distrusted lists
appendedsig: While verifying the kernel, use trusted and distrusted
lists
ieee1275: set use_static_keys flag
appendedsig: Reads the default DB keys from ELF Note
appendedsig: The grub command's trusted and distrusted support
appendedsig: documentation

 docs/grub.texi                                |  295 +++-
 grub-core/Makefile.am                         |    1 +
 grub-core/Makefile.core.def                   |   30 +
 grub-core/commands/appendedsig/appendedsig.c  | 1455 +++++++++++++++++
 grub-core/commands/appendedsig/appendedsig.h  |  110 ++
 grub-core/commands/appendedsig/asn1util.c     |   99 ++
 .../commands/appendedsig/gnutls_asn1_tab.c    |  121 ++
 grub-core/commands/appendedsig/pkcs7.c        |  473 ++++++
 .../commands/appendedsig/pkix_asn1_tab.c      |  484 ++++++
 grub-core/commands/appendedsig/x509.c         |  981 +++++++++++
 grub-core/commands/pgp.c                      |   34 +-
 grub-core/kern/ieee1275/ieee1275.c            |  117 ++
 grub-core/kern/ieee1275/init.c                |   38 +
 grub-core/kern/ieee1275/platform_keystore.c   |  350 ++++
 grub-core/lib/crypto.c                        |    4 +
 grub-core/lib/pkcs1_v15.c                     |   59 +
 grub-core/tests/appended_signature_test.c     |  258 +++
 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/ieee1275/ieee1275.h              |   14 +
 include/grub/kernel.h                         |    2 +
 include/grub/lockdown.h                       |    3 +-
 include/grub/pkcs1_v15.h                      |   27 +
 include/grub/platform_keystore.h              |  235 +++
 include/grub/util/install.h                   |   10 +-
 include/grub/util/mkimage.h                   |    4 +-
 util/grub-install-common.c                    |   34 +-
 util/grub-mkimage.c                           |   25 +-
 util/grub-mkimagexx.c                         |   38 +-
 util/mkimage.c                                |   39 +-
 32 files changed, 6260 insertions(+), 69 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/kern/ieee1275/platform_keystore.c
 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/pkcs1_v15.h
 create mode 100644 include/grub/platform_keystore.h
Signature · 7 lines
2.43.5


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

PATCH 1/21 powerpc-ieee1275: Add support 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.

---
 include/grub/util/install.h |  7 +++++--
 include/grub/util/mkimage.h |  4 ++--
 util/grub-install-common.c  | 15 ++++++++++++---
 util/grub-mkimage.c         | 11 +++++++++++
 util/grub-mkimagexx.c       | 38 ++++++++++++++++++++++++++++++++++++-
 util/mkimage.c              |  6 +++---
 6 files changed, 70 insertions(+), 11 deletions(-)
include/grub/util/install.h +5 -2
index 5c0a52ca2..3aabc4285 100644
@@ -69,6 +69,8 @@
       N_("disable shim_lock verifier"), 0 },				\
   { "disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0,		\
     N_("disabled command line interface access"), 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 }
 
@@ -132,7 +134,8 @@ enum grub_install_options {
   GRUB_INSTALL_OPTIONS_DTB,
   GRUB_INSTALL_OPTIONS_SBAT,
   GRUB_INSTALL_OPTIONS_DISABLE_SHIM_LOCK,
-  GRUB_INSTALL_OPTIONS_DISABLE_CLI
+  GRUB_INSTALL_OPTIONS_DISABLE_CLI,
+  GRUB_INSTALL_OPTIONS_APPENDED_SIGNATURE_SIZE
 };
 
 extern char *grub_install_source_directory;
@@ -192,7 +195,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,
 			     const int disable_cli);
include/grub/util/mkimage.h +2 -2
index 9d74f82c5..0d40383eb 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 *sbat, char **core_img, size_t *core_size,
+			     int note, char *sbat, 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 *sbat, char **core_img, size_t *core_size,
+			     int note, char *sbat, 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 22bccb6a3..22f0e56cb 100644
@@ -467,10 +467,12 @@ static char *sbat;
 static int disable_shim_lock;
 static grub_compression_t compression;
 static int disable_cli;
+static size_t appsig_size;
 
 int
 grub_install_parse (int key, char *arg)
 {
+  const char *end;
   switch (key)
     {
     case GRUB_INSTALL_OPTIONS_INSTALL_CORE_COMPRESS:
@@ -571,6 +573,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;
     }
@@ -683,9 +691,10 @@ grub_install_make_image_wrap_file (const char *dir, const char *prefix,
   *p = '\0';
 
   grub_util_info ("grub-mkimage --directory '%s' --prefix '%s' --output '%s'"
-		  " --format '%s' --compression '%s'%s%s%s%s\n",
+		  " --format '%s' --compression '%s'"
+		  " --appended-signature-size %zu %s %s %s %s\n",
 		  dir, prefix, outname,
-		  mkimage_target, compnames[compression],
+		  mkimage_target, compnames[compression], appsig_size,
 		  note ? " --note" : "",
 		  disable_shim_lock ? " --disable-shim-lock" : "",
 		  disable_cli ? " --disable-cli" : "", s);
@@ -698,7 +707,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, disable_cli);
   while (dc--)
     grub_install_pop_module ();
util/grub-mkimage.c +11 -0
index 547f7310f..6c5063ac2 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},
   {"disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0, N_("disable command line interface access"), 0},
+  {"appended-signature-size", 'S', N_("SIZE"), 0, N_("Add a note segment reserving SIZE bytes for an appended signature"), 0},
   {"verbose",     'v', 0,      0, N_("print verbose messages."), 0},
   { 0, 0, 0, 0, 0, 0 }
 };
@@ -130,6 +131,7 @@ struct arguments
   int note;
   int disable_shim_lock;
   int disable_cli;
+  size_t appsig_size;
   const struct grub_install_image_target_desc *image_target;
   grub_compression_t comp;
 };
@@ -140,6 +142,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)
     {
@@ -172,6 +175,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);
@@ -330,6 +340,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,
 			       arguments.disable_cli);
util/grub-mkimagexx.c +37 -1
index 448862b2e..6fe348e5b 100644
@@ -115,6 +115,14 @@ struct grub_sbat_note {
   char name[ALIGN_UP(sizeof(GRUB_SBAT_NOTE_NAME), 4)];
 };
 
+#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)];
+};
+
 static int
 is_relocatable (const struct grub_install_image_target_desc *image_target)
 {
@@ -216,7 +224,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 *sbat, char **core_img, size_t *core_size,
+				    int note, char *sbat, size_t appsig_size, char **core_img, size_t *core_size,
 				    Elf_Addr target_addr,
 				    struct grub_mkimage_layout *layout)
 {
@@ -237,6 +245,12 @@ SUFFIX (grub_mkimage_generate_elf) (const struct grub_install_image_target_desc
       footer_size += ALIGN_UP (sizeof (struct grub_sbat_note) + layout->sbat_size, 4);
     }
 
+  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;
 
@@ -527,6 +541,28 @@ SUFFIX (grub_mkimage_generate_elf) (const struct grub_install_image_target_desc
       phdr->p_filesz = grub_host_to_target32 (note_size);
       phdr->p_memsz = 0;
       phdr->p_offset = grub_host_to_target32 (header_size + program_size + footer_offset);
+      footer += note_size;
+      footer_offset += note_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 *) footer;
+      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 + footer_offset);
     }
 
   {
util/mkimage.c +3 -3
index b46df2909..f5c59f563 100644
@@ -885,7 +885,7 @@ 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,
+			     int note, size_t appsig_size, grub_compression_t comp, const char *dtb_path,
 			     const char *sbat_path, int disable_shim_lock,
 			     int disable_cli)
 {
@@ -1833,10 +1833,10 @@ 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, sbat, &core_img, &core_size,
+	  grub_mkimage_generate_elf32 (image_target, note, sbat, appsig_size, &core_img, &core_size,
 				       target_addr, &layout);
 	else
-	  grub_mkimage_generate_elf64 (image_target, note, sbat, &core_img, &core_size,
+	  grub_mkimage_generate_elf64 (image_target, note, sbat, appsig_size, &core_img, &core_size,
 				       target_addr, &layout);
       }
       break;
Signature · 7 lines
2.43.5


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 1/21
#2 lore raw

Re: [PATCH v1 01/21] powerpc-ieee1275: Add support for signing grub with an appended signature

Quoted 166 lines · Sudhakar Kuppusamy

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.

---
  include/grub/util/install.h |  7 +++++--
  include/grub/util/mkimage.h |  4 ++--
  util/grub-install-common.c  | 15 ++++++++++++---
  util/grub-mkimage.c         | 11 +++++++++++
  util/grub-mkimagexx.c       | 38 ++++++++++++++++++++++++++++++++++++-
  util/mkimage.c              |  6 +++---
  6 files changed, 70 insertions(+), 11 deletions(-)
include/grub/util/install.h +5 -2
index 5c0a52ca2..3aabc4285 100644
@@ -69,6 +69,8 @@
        N_("disable shim_lock verifier"), 0 },				\
    { "disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0,		\
      N_("disabled command line interface access"), 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 }
 
@@ -132,7 +134,8 @@ enum grub_install_options {
    GRUB_INSTALL_OPTIONS_DTB,
    GRUB_INSTALL_OPTIONS_SBAT,
    GRUB_INSTALL_OPTIONS_DISABLE_SHIM_LOCK,
-  GRUB_INSTALL_OPTIONS_DISABLE_CLI
+  GRUB_INSTALL_OPTIONS_DISABLE_CLI,
+  GRUB_INSTALL_OPTIONS_APPENDED_SIGNATURE_SIZE
  };
 
  extern char *grub_install_source_directory;
@@ -192,7 +195,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,
  			     const int disable_cli);
include/grub/util/mkimage.h +2 -2
index 9d74f82c5..0d40383eb 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 *sbat, char **core_img, size_t *core_size,
+			     int note, char *sbat, 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 *sbat, char **core_img, size_t *core_size,
+			     int note, char *sbat, 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 22bccb6a3..22f0e56cb 100644
@@ -467,10 +467,12 @@ static char *sbat;
  static int disable_shim_lock;
  static grub_compression_t compression;
  static int disable_cli;
+static size_t appsig_size;
 
  int
  grub_install_parse (int key, char *arg)
  {
+  const char *end;
    switch (key)
      {
      case GRUB_INSTALL_OPTIONS_INSTALL_CORE_COMPRESS:
@@ -571,6 +573,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;
      }
@@ -683,9 +691,10 @@ grub_install_make_image_wrap_file (const char *dir, const char *prefix,
    *p = '\0';
 
    grub_util_info ("grub-mkimage --directory '%s' --prefix '%s' --output '%s'"
-		  " --format '%s' --compression '%s'%s%s%s%s\n",
+		  " --format '%s' --compression '%s'"
+		  " --appended-signature-size %zu %s %s %s %s\n",
  		  dir, prefix, outname,
-		  mkimage_target, compnames[compression],
+		  mkimage_target, compnames[compression], appsig_size,
  		  note ? " --note" : "",
  		  disable_shim_lock ? " --disable-shim-lock" : "",
  		  disable_cli ? " --disable-cli" : "", s);
@@ -698,7 +707,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, disable_cli);
    while (dc--)
      grub_install_pop_module ();
util/grub-mkimage.c +2 -0
index 547f7310f..6c5063ac2 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},
    {"disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0, N_("disable command line interface access"), 0},
+  {"appended-signature-size", 'S', N_("SIZE"), 0, N_("Add a note segment reserving SIZE bytes for an appended signature"), 0},
    {"verbose",     'v', 0,      0, N_("print verbose messages."), 0},
    { 0, 0, 0, 0, 0, 0 }
  };
@@ -130,6 +131,7 @@ struct arguments
    int note;
    int disable_shim_lock;
    int disable_cli;
+  size_t appsig_size;
    const struct grub_install_image_target_desc *image_target;
    grub_compression_t comp;
  };

util/grub-mkimage.c argp_parser (int key, char *arg, struct argp_state *state) · line 145

Quoted 4 lines
util/grub-mkimage.c +1 -0
@@ -140,6 +142,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;

const char *end;

Quoted 111 lines
util/grub-mkimage.c +8 -0
    switch (key)
      {
@@ -172,6 +175,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);
@@ -330,6 +340,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,
  			       arguments.disable_cli);
util/grub-mkimagexx.c +37 -1
index 448862b2e..6fe348e5b 100644
@@ -115,6 +115,14 @@ struct grub_sbat_note {
    char name[ALIGN_UP(sizeof(GRUB_SBAT_NOTE_NAME), 4)];
  };
 
+#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)];
+};
+
  static int
  is_relocatable (const struct grub_install_image_target_desc *image_target)
  {
@@ -216,7 +224,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 *sbat, char **core_img, size_t *core_size,
+				    int note, char *sbat, size_t appsig_size, char **core_img, size_t *core_size,
  				    Elf_Addr target_addr,
  				    struct grub_mkimage_layout *layout)
  {
@@ -237,6 +245,12 @@ SUFFIX (grub_mkimage_generate_elf) (const struct grub_install_image_target_desc
        footer_size += ALIGN_UP (sizeof (struct grub_sbat_note) + layout->sbat_size, 4);
      }
 
+  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;
 
@@ -527,6 +541,28 @@ SUFFIX (grub_mkimage_generate_elf) (const struct grub_install_image_target_desc
        phdr->p_filesz = grub_host_to_target32 (note_size);
        phdr->p_memsz = 0;
        phdr->p_offset = grub_host_to_target32 (header_size + program_size + footer_offset);
+      footer += note_size;
+      footer_offset += note_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 *) footer;
+      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 + footer_offset);
      }
 
    {
util/mkimage.c +1 -1
index b46df2909..f5c59f563 100644
@@ -885,7 +885,7 @@ 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,
+			     int note, size_t appsig_size, grub_compression_t comp, const char *dtb_path,
  			     const char *sbat_path, int disable_shim_lock,
  			     int disable_cli)
  {
@@ -1833,10 +1833,10 @@ grub_install_generate_image (const char *dir, const char *prefix,
  	else
  	  target_addr = image_target->link_addr;

util/mkimage.c grub_install_generate_image (const char *dir, const char *prefix, · line 1842

Quoted 10 lines
util/mkimage.c +2 -2
  	if (image_target->voidp_sizeof == 4)
-	  grub_mkimage_generate_elf32 (image_target, note, sbat, &core_img, &core_size,
+	  grub_mkimage_generate_elf32 (image_target, note, sbat, appsig_size, &core_img, &core_size,
  				       target_addr, &layout);
  	else
-	  grub_mkimage_generate_elf64 (image_target, note, sbat, &core_img, &core_size,
+	  grub_mkimage_generate_elf64 (image_target, note, sbat, appsig_size, &core_img, &core_size,
  				       target_addr, &layout);
        }
        break;

With nit fixed:

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

author
#3 lore raw

Re: [PATCH v1 01/21] powerpc-ieee1275: Add support for signing grub with an appended signature

Quoted 328 lines · Stefan Berger
Quoted 176 lines · Sudhakar Kuppusamy

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.

---
  include/grub/util/install.h |  7 +++++--
  include/grub/util/mkimage.h |  4 ++--
  util/grub-install-common.c  | 15 ++++++++++++---
  util/grub-mkimage.c         | 11 +++++++++++
  util/grub-mkimagexx.c       | 38 
++++++++++++++++++++++++++++++++++++-
  util/mkimage.c              |  6 +++---
  6 files changed, 70 insertions(+), 11 deletions(-)
include/grub/util/install.h +2 -0
index 5c0a52ca2..3aabc4285 100644
@@ -69,6 +69,8 @@
        N_("disable shim_lock verifier"), 0 },				\
    { "disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0,		\
      N_("disabled command line interface access"), 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 }

@@ -132,7 +134,8 @@ enum grub_install_options {
GRUB_INSTALL_OPTIONS_DTB,
GRUB_INSTALL_OPTIONS_SBAT,
GRUB_INSTALL_OPTIONS_DISABLE_SHIM_LOCK,

include/grub/util/install.h +3 -2
-  GRUB_INSTALL_OPTIONS_DISABLE_CLI
+  GRUB_INSTALL_OPTIONS_DISABLE_CLI,
+  GRUB_INSTALL_OPTIONS_APPENDED_SIGNATURE_SIZE
  };
    extern char *grub_install_source_directory;
@@ -192,7 +195,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,

const int disable_cli);

include/grub/util/mkimage.h +2 -2
index 9d74f82c5..0d40383eb 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 *sbat, char **core_img, size_t *core_size,
+			     int note, char *sbat, 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 *sbat, char **core_img, size_t *core_size,
+			     int note, char *sbat, size_t appsig_size, char **core_img, 

size_t *core_size,
Elf64_Addr target_addr,
struct grub_mkimage_layout *layout);
diff --git a/util/grub-install-common.c b/util/grub-install-common.c
index 22bccb6a3..22f0e56cb 100644

util/grub-install-common.c +12 -4
@@ -467,10 +467,12 @@ static char *sbat;
  static int disable_shim_lock;
  static grub_compression_t compression;
  static int disable_cli;
+static size_t appsig_size;
    int
  grub_install_parse (int key, char *arg)
  {
+  const char *end;
    switch (key)
      {
      case GRUB_INSTALL_OPTIONS_INSTALL_CORE_COMPRESS:
@@ -571,6 +573,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;
      }
@@ -683,9 +691,10 @@ grub_install_make_image_wrap_file (const char 
 *dir, const char *prefix,
    *p = '\0';
      grub_util_info ("grub-mkimage --directory '%s' --prefix '%s' 
--output '%s'"
-		  " --format '%s' --compression '%s'%s%s%s%s\n",
+		  " --format '%s' --compression '%s'"
+		  " --appended-signature-size %zu %s %s %s %s\n",
  		  dir, prefix, outname,
-		  mkimage_target, compnames[compression],
+		  mkimage_target, compnames[compression], appsig_size,
  		  note ? " --note" : "",
  		  disable_shim_lock ? " --disable-shim-lock" : "",
  		  disable_cli ? " --disable-cli" : "", s);
@@ -698,7 +707,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, disable_cli);
    while (dc--)
      grub_install_pop_module ();
util/grub-mkimage.c +1 -0
index 547f7310f..6c5063ac2 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},
    {"disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0, 
 N_("disable command line interface access"), 0},
+  {"appended-signature-size", 'S', N_("SIZE"), 0, N_("Add a note 
 segment reserving SIZE bytes for an appended signature"), 0},
    {"verbose",     'v', 0,      0, N_("print verbose messages."), 0},
    { 0, 0, 0, 0, 0, 0 }

};

util/grub-mkimage.c +1 -0
@@ -130,6 +131,7 @@ struct arguments
    int note;
    int disable_shim_lock;
    int disable_cli;
+  size_t appsig_size;
    const struct grub_install_image_target_desc *image_target;
    grub_compression_t comp;
  };

util/grub-mkimage.c argp_parser (int key, char *arg, struct argp_state · line 146

Quoted 5 lines
util/grub-mkimage.c +1 -0
@@ -140,6 +142,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;

const char *end;

Quoted 137 lines
util/grub-mkimage.c +7 -0
      switch (key)
      {
@@ -172,6 +175,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);
@@ -330,6 +340,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,
  			       arguments.disable_cli);
util/grub-mkimagexx.c +7 -0
index 448862b2e..6fe348e5b 100644
@@ -115,6 +115,14 @@ struct grub_sbat_note {
    char name[ALIGN_UP(sizeof(GRUB_SBAT_NOTE_NAME), 4)];
  };
  +#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)];
+};
+
  static int
  is_relocatable (const struct grub_install_image_target_desc 

*image_target)
{

util/grub-mkimagexx.c +1 -1
@@ -216,7 +224,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 *sbat, char **core_img, size_t *core_size,
+				    int note, char *sbat, size_t appsig_size, char **core_img, 
 size_t *core_size,
  				    Elf_Addr target_addr,
  				    struct grub_mkimage_layout *layout)
  {
util/grub-mkimagexx.c +0 -0
@@ -237,6 +245,12 @@ SUFFIX (grub_mkimage_generate_elf) (const struct 

grub_install_image_target_desc

        footer_size += ALIGN_UP (sizeof (struct grub_sbat_note) + 
layout->sbat_size, 4);
      }

+ if (appsig_size)

util/grub-mkimagexx.c +3 -0
+    {
+      phnum++;
+      footer_size += ALIGN_UP (sizeof (struct 

grub_appended_signature_note) + appsig_size, 4);

util/grub-mkimagexx.c +2 -0
+    }
+
    if (image_target->id != IMAGE_LOONGSON_ELF)
      phnum += 2;
  @@ -527,6 +541,28 @@ SUFFIX (grub_mkimage_generate_elf) (const 

struct grub_install_image_target_desc

        phdr->p_filesz = grub_host_to_target32 (note_size);
        phdr->p_memsz = 0;
        phdr->p_offset = grub_host_to_target32 (header_size + 

program_size + footer_offset);

util/grub-mkimagexx.c +7 -0
+      footer += note_size;
+      footer_offset += note_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 *) footer;
+ 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);

util/grub-mkimagexx.c +5 -0
+      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);

util/grub-mkimagexx.c +5 -0
+      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 + footer_offset);
      }
      {
util/mkimage.c +1 -1
index b46df2909..f5c59f563 100644
@@ -885,7 +885,7 @@ 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,
+			     int note, size_t appsig_size, grub_compression_t comp, const 
 char *dtb_path,
  			     const char *sbat_path, int disable_shim_lock,
  			     int disable_cli)
  {
util/mkimage.c +1 -2
@@ -1833,10 +1833,10 @@ 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, sbat, &core_img, 
 &core_size,
+	  grub_mkimage_generate_elf32 (image_target, note, sbat, 
 appsig_size, &core_img, &core_size,
  				       target_addr, &layout);
  	else
-	  grub_mkimage_generate_elf64 (image_target, note, sbat, &core_img, 

&core_size,

util/mkimage.c +1 -0
+	  grub_mkimage_generate_elf64 (image_target, note, sbat, 

appsig_size, &core_img, &core_size,

Quoted 3 lines
  				       target_addr, &layout);
        }
        break;

With nit fixed:

Quoted 1 line

Thank you Stefan. fixed it.

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

#4 lore raw

Re: [PATCH v1 01/21] powerpc-ieee1275: Add support for signing grub with an appended signature

In reply to Sudhakar Kuppusamy

Passing signature size to the tools looks very clumsy. How does the user know the signature size? Can we somehow determine it programmatically ourselves?

Quoted 300 lines · Sudhakar Kuppusamy

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.

---
 include/grub/util/install.h |  7 +++++--
 include/grub/util/mkimage.h |  4 ++--
 util/grub-install-common.c  | 15 ++++++++++++---
 util/grub-mkimage.c         | 11 +++++++++++
 util/grub-mkimagexx.c       | 38 ++++++++++++++++++++++++++++++++++++-
 util/mkimage.c              |  6 +++---
 6 files changed, 70 insertions(+), 11 deletions(-)
include/grub/util/install.h +5 -2
index 5c0a52ca2..3aabc4285 100644
@@ -69,6 +69,8 @@
       N_("disable shim_lock verifier"), 0 },                           \
   { "disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0,             \
     N_("disabled command line interface access"), 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 }
 
@@ -132,7 +134,8 @@ enum grub_install_options {
   GRUB_INSTALL_OPTIONS_DTB,
   GRUB_INSTALL_OPTIONS_SBAT,
   GRUB_INSTALL_OPTIONS_DISABLE_SHIM_LOCK,
-  GRUB_INSTALL_OPTIONS_DISABLE_CLI
+  GRUB_INSTALL_OPTIONS_DISABLE_CLI,
+  GRUB_INSTALL_OPTIONS_APPENDED_SIGNATURE_SIZE
 };
 
 extern char *grub_install_source_directory;
@@ -192,7 +195,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,
                             const int disable_cli);
include/grub/util/mkimage.h +2 -2
index 9d74f82c5..0d40383eb 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 *sbat, char **core_img, size_t *core_size,
+                            int note, char *sbat, 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 *sbat, char **core_img, size_t *core_size,
+                            int note, char *sbat, 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 22bccb6a3..22f0e56cb 100644
@@ -467,10 +467,12 @@ static char *sbat;
 static int disable_shim_lock;
 static grub_compression_t compression;
 static int disable_cli;
+static size_t appsig_size;
 
 int
 grub_install_parse (int key, char *arg)
 {
+  const char *end;
   switch (key)
     {
     case GRUB_INSTALL_OPTIONS_INSTALL_CORE_COMPRESS:
@@ -571,6 +573,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;
     }
@@ -683,9 +691,10 @@ grub_install_make_image_wrap_file (const char *dir, const char *prefix,
   *p = '\0';
 
   grub_util_info ("grub-mkimage --directory '%s' --prefix '%s' --output '%s'"
-                 " --format '%s' --compression '%s'%s%s%s%s\n",
+                 " --format '%s' --compression '%s'"
+                 " --appended-signature-size %zu %s %s %s %s\n",
                  dir, prefix, outname,
-                 mkimage_target, compnames[compression],
+                 mkimage_target, compnames[compression], appsig_size,
                  note ? " --note" : "",
                  disable_shim_lock ? " --disable-shim-lock" : "",
                  disable_cli ? " --disable-cli" : "", s);
@@ -698,7 +707,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, disable_cli);
   while (dc--)
     grub_install_pop_module ();
util/grub-mkimage.c +11 -0
index 547f7310f..6c5063ac2 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},
   {"disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0, N_("disable command line interface access"), 0},
+  {"appended-signature-size", 'S', N_("SIZE"), 0, N_("Add a note segment reserving SIZE bytes for an appended signature"), 0},
   {"verbose",     'v', 0,      0, N_("print verbose messages."), 0},
   { 0, 0, 0, 0, 0, 0 }
 };
@@ -130,6 +131,7 @@ struct arguments
   int note;
   int disable_shim_lock;
   int disable_cli;
+  size_t appsig_size;
   const struct grub_install_image_target_desc *image_target;
   grub_compression_t comp;
 };
@@ -140,6 +142,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)
     {
@@ -172,6 +175,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);
@@ -330,6 +340,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,
                               arguments.disable_cli);
util/grub-mkimagexx.c +37 -1
index 448862b2e..6fe348e5b 100644
@@ -115,6 +115,14 @@ struct grub_sbat_note {
   char name[ALIGN_UP(sizeof(GRUB_SBAT_NOTE_NAME), 4)];
 };
 
+#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)];
+};
+
 static int
 is_relocatable (const struct grub_install_image_target_desc *image_target)
 {
@@ -216,7 +224,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 *sbat, char **core_img, size_t *core_size,
+                                   int note, char *sbat, size_t appsig_size, char **core_img, size_t *core_size,
                                    Elf_Addr target_addr,
                                    struct grub_mkimage_layout *layout)
 {
@@ -237,6 +245,12 @@ SUFFIX (grub_mkimage_generate_elf) (const struct grub_install_image_target_desc
       footer_size += ALIGN_UP (sizeof (struct grub_sbat_note) + layout->sbat_size, 4);
     }
 
+  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;
 
@@ -527,6 +541,28 @@ SUFFIX (grub_mkimage_generate_elf) (const struct grub_install_image_target_desc
       phdr->p_filesz = grub_host_to_target32 (note_size);
       phdr->p_memsz = 0;
       phdr->p_offset = grub_host_to_target32 (header_size + program_size + footer_offset);
+      footer += note_size;
+      footer_offset += note_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 *) footer;
+      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 + footer_offset);
     }
 
   {
util/mkimage.c +3 -4
index b46df2909..f5c59f563 100644
@@ -885,7 +885,7 @@ 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,
+                            int note, size_t appsig_size, grub_compression_t comp, const char *dtb_path,
                             const char *sbat_path, int disable_shim_lock,
                             int disable_cli)
 {
@@ -1833,10 +1833,10 @@ 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, sbat, &core_img, &core_size,
+         grub_mkimage_generate_elf32 (image_target, note, sbat, appsig_size, &core_img, &core_size,
                                       target_addr, &layout);
        else
-         grub_mkimage_generate_elf64 (image_target, note, sbat, &core_img, &core_size,
+         grub_mkimage_generate_elf64 (image_target, note, sbat, appsig_size, &core_img, &core_size,
                                       target_addr, &layout);
       }
       break;
--

2.43.5

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

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 1/21
#5 lore raw

Re: [PATCH v1 01/21] powerpc-ieee1275: Add support for signing grub with an appended signature

In reply to Sudhakar Kuppusamy
Quoted 327 lines · Sudhakar Kuppusamy

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.

---
 include/grub/util/install.h |  7 +++++--
 include/grub/util/mkimage.h |  4 ++--
 util/grub-install-common.c  | 15 ++++++++++++---
 util/grub-mkimage.c         | 11 +++++++++++
 util/grub-mkimagexx.c       | 38 ++++++++++++++++++++++++++++++++++++-
 util/mkimage.c              |  6 +++---
 6 files changed, 70 insertions(+), 11 deletions(-)
include/grub/util/install.h +2 -0
index 5c0a52ca2..3aabc4285 100644
@@ -69,6 +69,8 @@
       N_("disable shim_lock verifier"), 0 },				\
   { "disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0,		\
     N_("disabled command line interface access"), 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 }
include/grub/util/install.h +3 -2
@@ -132,7 +134,8 @@ enum grub_install_options {
   GRUB_INSTALL_OPTIONS_DTB,
   GRUB_INSTALL_OPTIONS_SBAT,
   GRUB_INSTALL_OPTIONS_DISABLE_SHIM_LOCK,
-  GRUB_INSTALL_OPTIONS_DISABLE_CLI
+  GRUB_INSTALL_OPTIONS_DISABLE_CLI,
+  GRUB_INSTALL_OPTIONS_APPENDED_SIGNATURE_SIZE
 };
 
 extern char *grub_install_source_directory;
@@ -192,7 +195,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/install.h +0 -0
 			     const int disable_cli);
include/grub/util/mkimage.h +2 -2
index 9d74f82c5..0d40383eb 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 *sbat, char **core_img, size_t *core_size,
+			     int note, char *sbat, 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 *sbat, char **core_img, size_t *core_size,
+			     int note, char *sbat, size_t appsig_size, char **core_img,

size_t *core_size,

include/grub/util/mkimage.h +0 -0
 			     Elf64_Addr target_addr,
 			     struct grub_mkimage_layout *layout);
util/grub-install-common.c +12 -4
index 22bccb6a3..22f0e56cb 100644
@@ -467,10 +467,12 @@ static char *sbat;
 static int disable_shim_lock;
 static grub_compression_t compression;
 static int disable_cli;
+static size_t appsig_size;
 
 int
 grub_install_parse (int key, char *arg)
 {
+  const char *end;
   switch (key)
     {
     case GRUB_INSTALL_OPTIONS_INSTALL_CORE_COMPRESS:
@@ -571,6 +573,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;
     }
@@ -683,9 +691,10 @@ grub_install_make_image_wrap_file (const char
 *dir, const char *prefix,
   *p = '\0';
 
   grub_util_info ("grub-mkimage --directory '%s' --prefix '%s' 
--output '%s'"
-		  " --format '%s' --compression '%s'%s%s%s%s\n",
+		  " --format '%s' --compression '%s'"
+		  " --appended-signature-size %zu %s %s %s %s\n",
 		  dir, prefix, outname,
-		  mkimage_target, compnames[compression],
+		  mkimage_target, compnames[compression], appsig_size,
 		  note ? " --note" : "",
 		  disable_shim_lock ? " --disable-shim-lock" : "",
 		  disable_cli ? " --disable-cli" : "", s);
@@ -698,7 +707,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, disable_cli);
   while (dc--)
     grub_install_pop_module ();
util/grub-mkimage.c +1 -0
index 547f7310f..6c5063ac2 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},
   {"disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0, N_("disable
 command line interface access"), 0},
+  {"appended-signature-size", 'S', N_("SIZE"), 0, N_("Add a note
 segment reserving SIZE bytes for an appended signature"), 0},
   {"verbose",     'v', 0,      0, N_("print verbose messages."), 0},
   { 0, 0, 0, 0, 0, 0 }

};

util/grub-mkimage.c +2 -0
@@ -130,6 +131,7 @@ struct arguments
   int note;
   int disable_shim_lock;
   int disable_cli;
+  size_t appsig_size;
   const struct grub_install_image_target_desc *image_target;
   grub_compression_t comp;
 };
@@ -140,6 +142,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)
     {
util/grub-mkimage.c +7 -0
@@ -172,6 +175,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)
util/grub-mkimage.c +1 -0
 	free (arguments->memdisk);
@@ -330,6 +340,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,
 			       arguments.disable_cli);
util/grub-mkimagexx.c +8 -0
index 448862b2e..6fe348e5b 100644
@@ -115,6 +115,14 @@ struct grub_sbat_note {
   char name[ALIGN_UP(sizeof(GRUB_SBAT_NOTE_NAME), 4)];
 };
 
+#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)];
+};
+
 static int
 is_relocatable (const struct grub_install_image_target_desc 
 *image_target)

{

util/grub-mkimagexx.c +1 -1
@@ -216,7 +224,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 *sbat, char **core_img, size_t *core_size,
+				    int note, char *sbat, size_t appsig_size, char **core_img,
 size_t *core_size,
util/grub-mkimagexx.c +0 -0
 				    Elf_Addr target_addr,
 				    struct grub_mkimage_layout *layout)
 {
@@ -237,6 +245,12 @@ SUFFIX (grub_mkimage_generate_elf) (const struct

grub_install_image_target_desc

       footer_size += ALIGN_UP (sizeof (struct grub_sbat_note) +
layout->sbat_size, 4);
     }
util/grub-mkimagexx.c +4 -0
+  if (appsig_size)
+    {
+      phnum++;
+      footer_size += ALIGN_UP (sizeof (struct

grub_appended_signature_note) + appsig_size, 4);

util/grub-mkimagexx.c +2 -0
+    }
+
   if (image_target->id != IMAGE_LOONGSON_ELF)
     phnum += 2;
@@ -527,6 +541,28 @@ SUFFIX (grub_mkimage_generate_elf) (const struct

grub_install_image_target_desc

       phdr->p_filesz = grub_host_to_target32 (note_size);
       phdr->p_memsz = 0;
       phdr->p_offset = grub_host_to_target32 (header_size +

program_size + footer_offset);

util/grub-mkimagexx.c +7 -0
+      footer += note_size;
+      footer_offset += note_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 *) footer;
+ 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);

util/grub-mkimagexx.c +5 -0
+      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);

util/grub-mkimagexx.c +5 -0
+      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 + footer_offset);
     }
   {
util/mkimage.c +1 -1
index b46df2909..f5c59f563 100644
@@ -885,7 +885,7 @@ 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,
+			     int note, size_t appsig_size, grub_compression_t comp, const
 char *dtb_path,
 			     const char *sbat_path, int disable_shim_lock,
util/mkimage.c +1 -2
 			     int disable_cli)
 {
@@ -1833,10 +1833,10 @@ 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, sbat, &core_img,
 &core_size,
+	  grub_mkimage_generate_elf32 (image_target, note, sbat,
 appsig_size, &core_img, &core_size,
 				       target_addr, &layout);
 	else
-	  grub_mkimage_generate_elf64 (image_target, note, sbat, &core_img,

&core_size,

util/mkimage.c +1 -0
+	  grub_mkimage_generate_elf64 (image_target, note, sbat,

appsig_size, &core_img, &core_size,

Quoted 3 lines
 				       target_addr, &layout);
       }
       break;

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

#6 lore raw

PATCH 2/21 docs/grub: Document signing grub under UEFI

In reply to Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 | 18 +++++++++++++++++-
 1 file changed, 17 insertions(+), 1 deletion(-)
docs/grub.texi +17 -1
index 200e747af..c07d5d0dc 100644
@@ -8572,6 +8572,7 @@ environment variables and commands are listed in the same order.
 * Measured Boot::                    Measuring boot components
 * Lockdown::                         Lockdown when booting on a secure setup
 * TPM2 key protector::               Managing disk key with TPM2 key protector
+* Signing GRUB itself::              Ensuring the integrity of the GRUB core image
 @end menu
 
 @node Authentication and authorisation
@@ -8652,7 +8653,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}
@@ -9119,6 +9120,21 @@ command through the swtpm control channel.
 # @kbd{swtpm_ioctl -s --unix swtpm-state/ctrl}
 @end example
 
+@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 · 7 lines
2.43.5


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 2/21
#7 lore raw

Re: [PATCH v1 02/21] docs/grub: Document signing grub under UEFI

Quoted 40 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 | 18 +++++++++++++++++-
  1 file changed, 17 insertions(+), 1 deletion(-)
docs/grub.texi +5 -1
index 200e747af..c07d5d0dc 100644
@@ -8572,6 +8572,7 @@ environment variables and commands are listed in the same order.
  * Measured Boot::                    Measuring boot components
  * Lockdown::                         Lockdown when booting on a secure setup
  * TPM2 key protector::               Managing disk key with TPM2 key protector
+* Signing GRUB itself::              Ensuring the integrity of the GRUB core image
  @end menu
 
  @node Authentication and authorisation
@@ -8652,7 +8653,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}
@@ -9119,6 +9120,21 @@ command through the swtpm control channel.
  # @kbd{swtpm_ioctl -s --unix swtpm-state/ctrl}
  @end example
 
+@node Signing GRUB itself
+@section Signing GRUB itself
+To ensure a complete secure-boot chain, there must be a way for the code that

docs/grub.texi command through the swtpm control channel. · line 9135

Quoted 10 lines
docs/grub.texi +10 -0
+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

s/enrol/enroll

docs/grub.texi command through the swtpm control channel. · line 9140

Quoted 5 lines
docs/grub.texi +2 -0
+key database.
+
  @node Platform limitations
  @chapter Platform limitations
 

With nit fixed:

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

#8 lore raw

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

In reply to Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 c07d5d0dc..6e483298d 100644
@@ -9135,6 +9135,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 · 7 lines
2.43.5


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 3/21
#9 lore raw

Re: [PATCH v1 03/21] docs/grub: Document signing grub with an appended signature

Quoted 49 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 +29 -0
index c07d5d0dc..6e483298d 100644
@@ -9135,6 +9135,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

docs/grub.texi image works under UEFI secure boot and can maintain the secure-boot chain. It · line 9176

Quoted 10 lines
docs/grub.texi +10 -0
+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,

to build-in (?)

docs/grub.texi image works under UEFI secure boot and can maintain the secure-boot chain. It · line 9182

Quoted 6 lines
docs/grub.texi +3 -0
+or sign them separately.
+
+
  @node Platform limitations
  @chapter Platform limitations
 

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

#10 lore raw

Re: [PATCH v1 03/21] docs/grub: Document signing grub with an appended signature

In reply to Sudhakar Kuppusamy

May we instead invoke sign-file from grub-mkimage as to spare the user the hassle?

Quoted 74 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 -1
index c07d5d0dc..6e483298d 100644
@@ -9135,6 +9135,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
 
--

2.43.5

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

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 3/21
#11 lore raw

Re: [PATCH v1 03/21] docs/grub: Document signing grub with an appended signature

In reply to Sudhakar Kuppusamy
Quoted 71 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 +0 -0
index c07d5d0dc..6e483298d 100644
@@ -9135,6 +9135,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

docs/grub.texi +2 -0
+
+The @file{core.img} itself can be signed with a Linux kernel 

module-style

docs/grub.texi +3 -0
+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

docs/grub.texi +3 -0
+note added by @command{grub-install}.
+
+An image can be signed this way using the @command{sign-file} command 

from

docs/grub.texi +7 -0
+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

docs/grub.texi +12 -0
+# 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

docs/grub.texi +7 -0
+
+# 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,

docs/grub.texi image works under UEFI secure boot and can maintain the secure-boot chain. It · line 9181

Quoted 5 lines
docs/grub.texi +3 -0
+or sign them separately.
+
+
 @node Platform limitations
 @chapter Platform limitations

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

#12 lore raw

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

In reply to Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 750fc8d3d..fb4476797 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 · 7 lines
2.43.5


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 4/21
#13 lore raw

Re: [PATCH v1 04/21] dl: provide a fake grub_dl_set_persistent for the emu target

Quoted 11 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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)
Quoted 21 lines
---
  include/grub/dl.h | 11 +++++++++++
  1 file changed, 11 insertions(+)
include/grub/dl.h +9 -0
index 750fc8d3d..fb4476797 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)))
+{
+}

include/grub/dl.h grub_dl_get (const char *name) · line 263

Quoted 10 lines
include/grub/dl.h +2 -0
+#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)

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

#14 lore raw

Re: [PATCH v1 04/21] dl: provide a fake grub_dl_set_persistent for the emu target

In reply to Sudhakar Kuppusamy

grub-emu has 2 modes: full with all modules compiled-in and lite with actual module loading (mostly useful for testing module loading itself.
So just adding if (mod) ... is going to fix all cases and avoids ifdef

Quoted 51 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 -1
index 750fc8d3d..fb4476797 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)
--

2.43.5

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

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 4/21
#15 lore raw

Re: [PATCH v1 04/21] dl: provide a fake grub_dl_set_persistent for the emu target

In reply to Sudhakar Kuppusamy
Quoted 33 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 +3 -0
index 750fc8d3d..fb4476797 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.
+ */

include/grub/dl.h +4 -0
+static inline void
+grub_dl_set_persistent (grub_dl_t mod __attribute__((unused)))
+{
+}

include/grub/dl.h grub_dl_get (const char *name) · line 263

Quoted 10 lines
include/grub/dl.h +2 -0
+#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)

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

#16 lore raw

PATCH 5/21 pgp: factor out rsa_pad

In reply to Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 f70e02e69..60db2adc5 100644
@@ -2540,6 +2540,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 c6766f044..b084dc9a2 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 000000000..5c338c84a
@@ -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 · 7 lines
2.43.5


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 5/21
#17 lore raw

Re: [PATCH v1 05/21] pgp: factor out rsa_pad

Quoted 12 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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.

Quoted 5 lines

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

Quoted 162 lines
---
  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 f70e02e69..60db2adc5 100644
@@ -2540,6 +2540,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 c6766f044..b084dc9a2 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
new file mode 100644
index 000000000..dbacd563d
@@ -0,0 +1,59 @@
+/*
+ *  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/>.
+ */
+
+#include <grub/dl.h>
+#include <grub/gcrypt/gcrypt.h>
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+/*
+ * 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) and place the result in 'hmpi'.
+ */
+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)
+{
+  grub_size_t tlen, emlen, fflen;
+  grub_uint8_t *em, *emptr;
+  unsigned nbits = gcry_mpi_get_nbits (mod);
+  int ret;
+  tlen = hash->mdlen + hash->asnlen;
+  emlen = (nbits + 7) / 8;
+  if (emlen < tlen + 11)
+    return GPG_ERR_TOO_SHORT;
+
+  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;
+}
include/grub/pkcs1_v15.h new file +17 -0
new file mode 100644
index 000000000..5c338c84a
@@ -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/>.
+ */

include/grub/pkcs1_v15.h line 27

Quoted 10 lines
include/grub/pkcs1_v15.h new file +10 -0
+
+/*
+ * 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);
+

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

#18 lore raw

Re: [PATCH v1 05/21] pgp: factor out rsa_pad

In reply to Sudhakar Kuppusamy

rsa_pad will be removed when we update libgcrypt (see pending patch). Can we accommodate for this?

Quoted 198 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 f70e02e69..60db2adc5 100644
@@ -2540,6 +2540,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 c6766f044..b084dc9a2 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
new file mode 100644
index 000000000..dbacd563d
@@ -0,0 +1,59 @@
+/*
+ *  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/>.
+ */
+
+#include <grub/dl.h>
+#include <grub/gcrypt/gcrypt.h>
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+/*
+ * 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) and place the result in 'hmpi'.
+ */
+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)
+{
+  grub_size_t tlen, emlen, fflen;
+  grub_uint8_t *em, *emptr;
+  unsigned nbits = gcry_mpi_get_nbits (mod);
+  int ret;
+  tlen = hash->mdlen + hash->asnlen;
+  emlen = (nbits + 7) / 8;
+  if (emlen < tlen + 11)
+    return GPG_ERR_TOO_SHORT;
+
+  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;
+}
include/grub/pkcs1_v15.h new file +27 -1
new file mode 100644
index 000000000..5c338c84a
@@ -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);
+
--

2.43.5

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

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

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

Re: [PATCH v1 05/21] pgp: factor out rsa_pad

Quoted 202 lines · Vladimir 'phcoder' Serbinenko

rsa_pad will be removed when we update libgcrypt (see pending patch). Can we accommodate for this?

Quoted 197 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 f70e02e69..60db2adc5 100644
@@ -2540,6 +2540,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 c6766f044..b084dc9a2 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 +6 -0
new file mode 100644
index 000000000..dbacd563d
@@ -0,0 +1,59 @@
+/*
+ *  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/>.
+ */

grub-core/lib/pkcs1_v15.c new file +42 -0
+
+#include <grub/dl.h>
+#include <grub/gcrypt/gcrypt.h>
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+/*
+ * 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) and place the result in 'hmpi'.
+ */
+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)
+{
+  grub_size_t tlen, emlen, fflen;
+  grub_uint8_t *em, *emptr;
+  unsigned nbits = gcry_mpi_get_nbits (mod);
+  int ret;
+  tlen = hash->mdlen + hash->asnlen;
+  emlen = (nbits + 7) / 8;
+  if (emlen < tlen + 11)
+    return GPG_ERR_TOO_SHORT;
+
+  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;
+}
include/grub/pkcs1_v15.h new file +6 -0
new file mode 100644
index 000000000..5c338c84a
@@ -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/>.
+ */

include/grub/pkcs1_v15.h new file +10 -1
+
+/*
+ * 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);
+
--

2.43.5

Quoted 4 lines
Quoted 4 lines

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

Sure. we can accommodate for this. Thank you Vladimir for the information.

Thanks,
Sudhakar Kuppusamy

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

Reviewed-by on v1 5/21
#20 lore raw

Re: [PATCH v1 05/21] pgp: factor out rsa_pad

In reply to Sudhakar Kuppusamy

Indentation looks off in couple of places. Please fix it.

Quoted 181 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 f70e02e69..60db2adc5 100644
@@ -2540,6 +2540,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 c6766f044..b084dc9a2 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 +6 -0
new file mode 100644
index 000000000..dbacd563d
@@ -0,0 +1,59 @@
+/*
+ *  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/>.
+ */

grub-core/lib/pkcs1_v15.c new file +42 -0
+
+#include <grub/dl.h>
+#include <grub/gcrypt/gcrypt.h>
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+/*
+ * 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) and place the result in 'hmpi'.
+ */
+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)
+{
+  grub_size_t tlen, emlen, fflen;
+  grub_uint8_t *em, *emptr;
+  unsigned nbits = gcry_mpi_get_nbits (mod);
+  int ret;
+  tlen = hash->mdlen + hash->asnlen;
+  emlen = (nbits + 7) / 8;
+  if (emlen < tlen + 11)
+    return GPG_ERR_TOO_SHORT;
+
+  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;
+}
include/grub/pkcs1_v15.h new file +6 -0
new file mode 100644
index 000000000..5c338c84a
@@ -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/>.
+ */

include/grub/pkcs1_v15.h line 27

Quoted 10 lines
include/grub/pkcs1_v15.h new file +10 -0
+
+/*
+ * 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);
+

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

author
#21 lore raw

Re: [PATCH v1 05/21] pgp: factor out rsa_pad

Quoted 189 lines · Avnish Chouhan

Indentation looks off in couple of places. Please fix it.

Quoted 184 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 f70e02e69..60db2adc5 100644
@@ -2540,6 +2540,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 c6766f044..b084dc9a2 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 +6 -0
new file mode 100644
index 000000000..dbacd563d
@@ -0,0 +1,59 @@
+/*
+ *  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/>.
+ */

grub-core/lib/pkcs1_v15.c new file +42 -0
+
+#include <grub/dl.h>
+#include <grub/gcrypt/gcrypt.h>
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+/*
+ * 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) and place the result in 'hmpi'.
+ */
+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)
+{
+  grub_size_t tlen, emlen, fflen;
+  grub_uint8_t *em, *emptr;
+  unsigned nbits = gcry_mpi_get_nbits (mod);
+  int ret;
+  tlen = hash->mdlen + hash->asnlen;
+  emlen = (nbits + 7) / 8;
+  if (emlen < tlen + 11)
+    return GPG_ERR_TOO_SHORT;
+
+  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;
+}
include/grub/pkcs1_v15.h new file +6 -0
new file mode 100644
index 000000000..5c338c84a
@@ -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/>.
+ */

include/grub/pkcs1_v15.h new file +2 -0
+
+/*
Quoted 8 lines

include/grub/pkcs1_v15.h line 27

Quoted 8 lines

+ * 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)
+ */

include/grub/pkcs1_v15.h new file +4 -0
+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);
+

Addressed the above comments. thank you Avnish Chouhan

Thanks,
Sudhakar Kuppusamy

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

#22 lore raw

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

In reply to Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 b084dc9a2..a45c2213c 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 396f76410..d53ddbe2c 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 · 7 lines
2.43.5


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 6/21
#23 lore raw

Re: [PATCH v1 06/21] crypto: move storage for grub_crypto_pk_* to crypto.c

Quoted 59 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 b084dc9a2..a45c2213c 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 +0 -0
index 396f76410..d53ddbe2c 100644

grub-core/lib/crypto.c grub_md_unregister (gcry_md_spec_t *cipher) · line 130

Quoted 10 lines
grub-core/lib/crypto.c +4 -0
@@ -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)

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

Reviewed-by on v1 6/21
#24 lore raw

Re: [PATCH v1 06/21] crypto: move storage for grub_crypto_pk_* to crypto.c

In reply to Sudhakar Kuppusamy
Quoted 78 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 b084dc9a2..a45c2213c 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 -1
index 396f76410..d53ddbe2c 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)
--

2.43.5

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

Signature · 7 lines
Regards
Vladimir 'phcoder' Serbinenko

_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 6/21
#25 lore raw

Re: [PATCH v1 06/21] crypto: move storage for grub_crypto_pk_* to crypto.c

In reply to Sudhakar Kuppusamy
Quoted 69 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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 b084dc9a2..a45c2213c 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 396f76410..d53ddbe2c 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,
Quoted 1 line

grub_size_t inlen)

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

#26 lore raw

PATCH 7/21 grub-install: support embedding x509 certificates

In reply to Sudhakar Kuppusamy

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       |  2 ++
 include/grub/util/install.h |  3 +++
 util/grub-install-common.c  | 19 ++++++++++++++++++-
 util/grub-mkimage.c         | 14 ++++++++++++--
 util/mkimage.c              | 33 +++++++++++++++++++++++++++++++--
 6 files changed, 67 insertions(+), 6 deletions(-)
grub-core/commands/pgp.c +1 -1
index a45c2213c..847a5046a 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 -0
index 6121c1e66..5c5ac129d 100644
@@ -29,6 +29,8 @@ enum
   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,
   OBJ_TYPE_DISABLE_CLI
include/grub/util/install.h +3 -0
index 3aabc4285..52a667c37 100644
@@ -69,6 +69,8 @@
       N_("disable shim_lock verifier"), 0 },				\
   { "disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0,		\
     N_("disabled command line interface access"), 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}, \
   { "verbose", 'v', 0, 0,						\
@@ -193,6 +195,7 @@ grub_install_generate_image (const char *dir, const char *prefix,
 			     const char *outname, char *mods[],
 			     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 +18 -1
index 22f0e56cb..29c45e26e 100644
@@ -463,6 +463,8 @@ handle_install_list (struct install_list *il, const char *val,
 
 static char **pubkeys;
 static size_t npubkeys;
+static char **x509keys;
+static size_t nx509keys;
 static char *sbat;
 static int disable_shim_lock;
 static grub_compression_t compression;
@@ -510,6 +512,10 @@ grub_install_parse (int key, char *arg)
     case GRUB_INSTALL_OPTIONS_DISABLE_CLI:
       disable_cli = 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++;
@@ -640,6 +646,9 @@ grub_install_make_image_wrap_file (const char *dir, const char *prefix,
   for (pk = pubkeys; pk < pubkeys + npubkeys; pk++)
     slen += sizeof (" --pubkey ''") + grub_strlen (*pk);
 
+  for (pk = x509keys; pk < x509keys + nx509keys; pk++)
+    slen += sizeof (" --x509key ''") + grub_strlen (*pk);
+
   for (md = modules.entries; *md; md++)
     slen += sizeof (" ''") + grub_strlen (*md);
 
@@ -680,6 +689,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, "--x509key '");
+      p = grub_stpcpy (p, *pk);
+      *p++ = '\'';
+      *p++ = ' ';
+    }
+
   for (md = modules.entries; *md; md++)
     {
       *p++ = ' ';
@@ -706,7 +723,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,
+			       pubkeys, npubkeys,  x509keys, nx509keys, config_path, tgt,
 			       note, appsig_size, compression, dtb, sbat,
 			       disable_shim_lock, disable_cli);
   while (dc--)
util/grub-mkimage.c +12 -2
index 6c5063ac2..1f958e04b 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},
+  {"x509key",     '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},
@@ -125,6 +126,8 @@ struct arguments
   char *dtb;
   char **pubkeys;
   size_t npubkeys;
+  char **x509keys;
+  size_t nx509keys;
   char *font;
   char *config;
   char *sbat;
@@ -208,6 +211,12 @@ 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);
@@ -338,7 +347,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 +31 -2
index f5c59f563..7076d632b 100644
@@ -883,7 +883,7 @@ 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 *config_path,
+			     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, grub_compression_t comp, const char *dtb_path,
 			     const char *sbat_path, int disable_shim_lock,
@@ -929,6 +929,18 @@ grub_install_generate_image (const char *dir, const char *prefix,
       }
   }
 
+  {
+    size_t i;
+    for (i = 0; i < nx509keys; i++)
+      {
+        size_t curs;
+        curs = ALIGN_ADDR (grub_util_get_image_size (x509key_paths[i]));
+        grub_util_info ("the size of x509 public key %u is 0x%" GRUB_HOST_PRIxLONG_LONG,
+                        (unsigned) i, (unsigned long long) curs);
+        total_module_size += curs + sizeof (struct grub_module_header);
+      }
+  }
+
   if (memdisk_path)
     {
       memdisk_size = ALIGN_UP(grub_util_get_image_size (memdisk_path), 512);
@@ -1053,7 +1065,7 @@ grub_install_generate_image (const char *dir, const char *prefix,
 	curs = grub_util_get_image_size (pubkey_paths[i]);
 
 	header = (struct grub_module_header *) (kernel_img + offset);
-	header->type = grub_host_to_target32 (OBJ_TYPE_PUBKEY);
+	header->type = grub_host_to_target32 (OBJ_TYPE_GPG_PUBKEY);
 	header->size = grub_host_to_target32 (curs + sizeof (*header));
 	offset += sizeof (*header);
 
@@ -1062,6 +1074,23 @@ grub_install_generate_image (const char *dir, const char *prefix,
       }
   }
 
+  {
+    size_t i;
+    for (i = 0; i < nx509keys; i++)
+      {
+        size_t curs;
+        struct grub_module_header *header;
+
+        curs = grub_util_get_image_size (x509key_paths[i]);
+        header = (struct grub_module_header *) (kernel_img + offset);
+        header->type = grub_host_to_target32 (OBJ_TYPE_X509_PUBKEY);
+        header->size = grub_host_to_target32 (curs + sizeof (*header));
+        offset += sizeof (*header);
+        grub_util_load_image (x509key_paths[i], kernel_img + offset);
+        offset += ALIGN_ADDR (curs);
+      }
+  }
+
   if (memdisk_path)
     {
       struct grub_module_header *header;
Signature · 7 lines
2.43.5


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 7/21
#27 lore raw

Re: [PATCH v1 07/21] grub-install: support embedding x509 certificates

Quoted 10 lines · Sudhakar Kuppusamy

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.

Quoted 215 lines
---
  grub-core/commands/pgp.c    |  2 +-
  include/grub/kernel.h       |  2 ++
  include/grub/util/install.h |  3 +++
  util/grub-install-common.c  | 19 ++++++++++++++++++-
  util/grub-mkimage.c         | 14 ++++++++++++--
  util/mkimage.c              | 33 +++++++++++++++++++++++++++++++--
  6 files changed, 67 insertions(+), 6 deletions(-)
grub-core/commands/pgp.c +1 -1
index a45c2213c..847a5046a 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 -0
index 6121c1e66..5c5ac129d 100644
@@ -29,6 +29,8 @@ enum
    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,
    OBJ_TYPE_DISABLE_CLI
include/grub/util/install.h +3 -0
index 3aabc4285..52a667c37 100644
@@ -69,6 +69,8 @@
        N_("disable shim_lock verifier"), 0 },				\
    { "disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0,		\
      N_("disabled command line interface access"), 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}, \
    { "verbose", 'v', 0, 0,						\
@@ -193,6 +195,7 @@ grub_install_generate_image (const char *dir, const char *prefix,
  			     const char *outname, char *mods[],
  			     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 +18 -1
index 22f0e56cb..29c45e26e 100644
@@ -463,6 +463,8 @@ handle_install_list (struct install_list *il, const char *val,
 
  static char **pubkeys;
  static size_t npubkeys;
+static char **x509keys;
+static size_t nx509keys;
  static char *sbat;
  static int disable_shim_lock;
  static grub_compression_t compression;
@@ -510,6 +512,10 @@ grub_install_parse (int key, char *arg)
      case GRUB_INSTALL_OPTIONS_DISABLE_CLI:
        disable_cli = 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++;
@@ -640,6 +646,9 @@ grub_install_make_image_wrap_file (const char *dir, const char *prefix,
    for (pk = pubkeys; pk < pubkeys + npubkeys; pk++)
      slen += sizeof (" --pubkey ''") + grub_strlen (*pk);
 
+  for (pk = x509keys; pk < x509keys + nx509keys; pk++)
+    slen += sizeof (" --x509key ''") + grub_strlen (*pk);
+
    for (md = modules.entries; *md; md++)
      slen += sizeof (" ''") + grub_strlen (*md);
 
@@ -680,6 +689,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, "--x509key '");
+      p = grub_stpcpy (p, *pk);
+      *p++ = '\'';
+      *p++ = ' ';
+    }
+
    for (md = modules.entries; *md; md++)
      {
        *p++ = ' ';
@@ -706,7 +723,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,
+			       pubkeys, npubkeys,  x509keys, nx509keys, config_path, tgt,
  			       note, appsig_size, compression, dtb, sbat,
  			       disable_shim_lock, disable_cli);
    while (dc--)
util/grub-mkimage.c +12 -2
index 6c5063ac2..1f958e04b 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},
+  {"x509key",     '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},
@@ -125,6 +126,8 @@ struct arguments
    char *dtb;
    char **pubkeys;
    size_t npubkeys;
+  char **x509keys;
+  size_t nx509keys;
    char *font;
    char *config;
    char *sbat;
@@ -208,6 +211,12 @@ 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);
@@ -338,7 +347,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 +24 -2
index f5c59f563..7076d632b 100644
@@ -883,7 +883,7 @@ 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 *config_path,
+			     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, grub_compression_t comp, const char *dtb_path,
  			     const char *sbat_path, int disable_shim_lock,
@@ -929,6 +929,18 @@ grub_install_generate_image (const char *dir, const char *prefix,
        }
    }
 
+  {
+    size_t i;
+    for (i = 0; i < nx509keys; i++)
+      {
+        size_t curs;
+        curs = ALIGN_ADDR (grub_util_get_image_size (x509key_paths[i]));
+        grub_util_info ("the size of x509 public key %u is 0x%" GRUB_HOST_PRIxLONG_LONG,
+                        (unsigned) i, (unsigned long long) curs);
+        total_module_size += curs + sizeof (struct grub_module_header);
+      }
+  }
+
    if (memdisk_path)
      {
        memdisk_size = ALIGN_UP(grub_util_get_image_size (memdisk_path), 512);
@@ -1053,7 +1065,7 @@ grub_install_generate_image (const char *dir, const char *prefix,
  	curs = grub_util_get_image_size (pubkey_paths[i]);
 
  	header = (struct grub_module_header *) (kernel_img + offset);
-	header->type = grub_host_to_target32 (OBJ_TYPE_PUBKEY);
+	header->type = grub_host_to_target32 (OBJ_TYPE_GPG_PUBKEY);
  	header->size = grub_host_to_target32 (curs + sizeof (*header));
  	offset += sizeof (*header);
 
@@ -1062,6 +1074,23 @@ grub_install_generate_image (const char *dir, const char *prefix,
        }
    }
 
+  {
+    size_t i;
+    for (i = 0; i < nx509keys; i++)
+      {
+        size_t curs;
+        struct grub_module_header *header;
+
+        curs = grub_util_get_image_size (x509key_paths[i]);
+        header = (struct grub_module_header *) (kernel_img + offset);
+        header->type = grub_host_to_target32 (OBJ_TYPE_X509_PUBKEY);

util/mkimage.c grub_install_generate_image (const char *dir, const char *prefix, · line 1096

Quoted 10 lines
util/mkimage.c +7 -0
+        header->size = grub_host_to_target32 (curs + sizeof (*header));
+        offset += sizeof (*header);
+        grub_util_load_image (x509key_paths[i], kernel_img + offset);
+        offset += ALIGN_ADDR (curs);
+      }
+  }
+
    if (memdisk_path)
      {
        struct grub_module_header *header;

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

Reviewed-by on v1 7/21
#28 lore raw

Re: [PATCH v1 07/21] grub-install: support embedding x509 certificates

In reply to Sudhakar Kuppusamy
Quoted 259 lines · Sudhakar Kuppusamy

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       |  2 ++
 include/grub/util/install.h |  3 +++
 util/grub-install-common.c  | 19 ++++++++++++++++++-
 util/grub-mkimage.c         | 14 ++++++++++++--
 util/mkimage.c              | 33 +++++++++++++++++++++++++++++++--
 6 files changed, 67 insertions(+), 6 deletions(-)
grub-core/commands/pgp.c +1 -1
index a45c2213c..847a5046a 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 -0
index 6121c1e66..5c5ac129d 100644
@@ -29,6 +29,8 @@ enum
   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,
   OBJ_TYPE_DISABLE_CLI
include/grub/util/install.h +2 -0
index 3aabc4285..52a667c37 100644
@@ -69,6 +69,8 @@
       N_("disable shim_lock verifier"), 0 },				\
   { "disable-cli", GRUB_INSTALL_OPTIONS_DISABLE_CLI, 0, 0,		\
     N_("disabled command line interface access"), 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}, \
   { "verbose", 'v', 0, 0,						\
include/grub/util/install.h +1 -0
@@ -193,6 +195,7 @@ grub_install_generate_image (const char *dir,
 const char *prefix,
 			     const char *outname, char *mods[],
 			     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,
include/grub/util/install.h +0 -0
 			     int note, size_t appsig_size,
util/grub-install-common.c +2 -0
index 22f0e56cb..29c45e26e 100644
@@ -463,6 +463,8 @@ handle_install_list (struct install_list *il,
 const char *val,
 
 static char **pubkeys;
 static size_t npubkeys;
+static char **x509keys;
+static size_t nx509keys;
 static char *sbat;
 static int disable_shim_lock;

static grub_compression_t compression;

util/grub-install-common.c +16 -0
@@ -510,6 +512,10 @@ grub_install_parse (int key, char *arg)
     case GRUB_INSTALL_OPTIONS_DISABLE_CLI:
       disable_cli = 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++;
@@ -640,6 +646,9 @@ grub_install_make_image_wrap_file (const char
 *dir, const char *prefix,
   for (pk = pubkeys; pk < pubkeys + npubkeys; pk++)
     slen += sizeof (" --pubkey ''") + grub_strlen (*pk);
 
+  for (pk = x509keys; pk < x509keys + nx509keys; pk++)
+    slen += sizeof (" --x509key ''") + grub_strlen (*pk);
+
   for (md = modules.entries; *md; md++)
     slen += sizeof (" ''") + grub_strlen (*md);
@@ -680,6 +689,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, "--x509key '");
+      p = grub_stpcpy (p, *pk);
+      *p++ = '\'';
+      *p++ = ' ';
+    }
+
   for (md = modules.entries; *md; md++)
     {
       *p++ = ' ';
util/grub-install-common.c +1 -1
@@ -706,7 +723,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,
+			       pubkeys, npubkeys,  x509keys, nx509keys, config_path, tgt,
 			       note, appsig_size, compression, dtb, sbat,
 			       disable_shim_lock, disable_cli);
   while (dc--)
util/grub-mkimage.c +2 -1
index 6c5063ac2..1f958e04b 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},
+  {"x509key",     '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},

util/grub-mkimage.c +8 -0
@@ -125,6 +126,8 @@ struct arguments
   char *dtb;
   char **pubkeys;
   size_t npubkeys;
+  char **x509keys;
+  size_t nx509keys;
   char *font;
   char *config;
   char *sbat;
@@ -208,6 +211,12 @@ 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)
util/grub-mkimage.c +2 -1
 	free (arguments->config);
@@ -338,7 +347,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 +1 -1
index f5c59f563..7076d632b 100644
@@ -883,7 +883,7 @@ 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 *config_path,
+			     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, grub_compression_t comp, const

char *dtb_path,

util/mkimage.c +9 -0
 			     const char *sbat_path, int disable_shim_lock,
@@ -929,6 +929,18 @@ grub_install_generate_image (const char *dir,
 const char *prefix,
       }
   }
 
+  {
+    size_t i;
+    for (i = 0; i < nx509keys; i++)
+      {
+        size_t curs;
+        curs = ALIGN_ADDR (grub_util_get_image_size 
 (x509key_paths[i]));
+        grub_util_info ("the size of x509 public key %u is 0x%"
 GRUB_HOST_PRIxLONG_LONG,
+                        (unsigned) i, (unsigned long long) curs);
+        total_module_size += curs + sizeof (struct 

grub_module_header);

util/mkimage.c +3 -0
+      }
+  }
+
   if (memdisk_path)
     {
       memdisk_size = ALIGN_UP(grub_util_get_image_size (memdisk_path), 

512);

util/mkimage.c +18 -1
@@ -1053,7 +1065,7 @@ grub_install_generate_image (const char *dir,
 const char *prefix,
 	curs = grub_util_get_image_size (pubkey_paths[i]);
 
 	header = (struct grub_module_header *) (kernel_img + offset);
-	header->type = grub_host_to_target32 (OBJ_TYPE_PUBKEY);
+	header->type = grub_host_to_target32 (OBJ_TYPE_GPG_PUBKEY);
 	header->size = grub_host_to_target32 (curs + sizeof (*header));
 	offset += sizeof (*header);
@@ -1062,6 +1074,23 @@ grub_install_generate_image (const char *dir,
 const char *prefix,
       }
   }
 
+  {
+    size_t i;
+    for (i = 0; i < nx509keys; i++)
+      {
+        size_t curs;
+        struct grub_module_header *header;
+
+        curs = grub_util_get_image_size (x509key_paths[i]);
+        header = (struct grub_module_header *) (kernel_img + offset);
+        header->type = grub_host_to_target32 (OBJ_TYPE_X509_PUBKEY);
+        header->size = grub_host_to_target32 (curs + sizeof 
 (*header));
+        offset += sizeof (*header);
+        grub_util_load_image (x509key_paths[i], kernel_img + offset);
+        offset += ALIGN_ADDR (curs);
+      }
+  }
+
   if (memdisk_path)
Quoted 2 lines
     {
       struct grub_module_header *header;

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

#29 lore raw

PATCH 8/21 appended signatures: import GNUTLS's ASN.1 description files

In reply to Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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.

---
 .../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 000000000..ddd1314e6
@@ -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 · 7 lines
2.43.5


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
Reviewed-by on v1 8/21
#30 lore raw

Re: [PATCH v1 08/21] appended signatures: import GNUTLS's ASN.1 description files

Quoted 10 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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:

Quoted 8 lines

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

Quoted 614 lines
---
  .../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 000000000..ddd1314e6
@@ -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 +474 -0
new file mode 100644
index 000000000..adef69d95
@@ -0,0 +1,484 @@
+#include <grub/mm.h>
+#include <grub/libtasn1.h>
+
+const asn1_static_node pkix_asn1_tab[] = {
+  { "PKIX1", 536875024, NULL },
+  { NULL, 1073741836, NULL },
+  { "PrivateKeyUsagePeriod", 1610612741, NULL },
+  { "notBefore", 1610637349, NULL },
+  { NULL, 4104, "0"},
+  { "notAfter", 536895525, NULL },
+  { NULL, 4104, "1"},
+  { "AuthorityKeyIdentifier", 1610612741, NULL },
+  { "keyIdentifier", 1610637319, NULL },
+  { NULL, 4104, "0"},
+  { "authorityCertIssuer", 1610637314, "GeneralNames"},
+  { NULL, 4104, "1"},
+  { "authorityCertSerialNumber", 536895490, "CertificateSerialNumber"},
+  { NULL, 4104, "2"},
+  { "SubjectKeyIdentifier", 1073741831, NULL },
+  { "KeyUsage", 1073741830, NULL },
+  { "DirectoryString", 1610612754, NULL },
+  { "teletexString", 1612709918, NULL },
+  { "MAX", 524298, "1"},
+  { "printableString", 1612709919, NULL },
+  { "MAX", 524298, "1"},
+  { "universalString", 1612709920, NULL },
+  { "MAX", 524298, "1"},
+  { "utf8String", 1612709922, NULL },
+  { "MAX", 524298, "1"},
+  { "bmpString", 1612709921, NULL },
+  { "MAX", 524298, "1"},
+  { "ia5String", 538968093, NULL },
+  { "MAX", 524298, "1"},
+  { "SubjectAltName", 1073741826, "GeneralNames"},
+  { "GeneralNames", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "GeneralName"},
+  { "GeneralName", 1610612754, NULL },
+  { "otherName", 1610620930, "AnotherName"},
+  { NULL, 4104, "0"},
+  { "rfc822Name", 1610620957, NULL },
+  { NULL, 4104, "1"},
+  { "dNSName", 1610620957, NULL },
+  { NULL, 4104, "2"},
+  { "x400Address", 1610620941, NULL },
+  { NULL, 4104, "3"},
+  { "directoryName", 1610620939, NULL },
+  { NULL, 1073743880, "4"},
+  { NULL, 2, "RelativeDistinguishedName"},
+  { "ediPartyName", 1610620941, NULL },
+  { NULL, 4104, "5"},
+  { "uniformResourceIdentifier", 1610620957, NULL },
+  { NULL, 4104, "6"},
+  { "iPAddress", 1610620935, NULL },
+  { NULL, 4104, "7"},
+  { "registeredID", 536879116, NULL },
+  { NULL, 4104, "8"},
+  { "AnotherName", 1610612741, NULL },
+  { "type-id", 1073741836, NULL },
+  { "value", 541073421, NULL },
+  { NULL, 1073743880, "0"},
+  { "type-id", 1, NULL },
+  { "IssuerAltName", 1073741826, "GeneralNames"},
+  { "BasicConstraints", 1610612741, NULL },
+  { "cA", 1610645508, NULL },
+  { NULL, 131081, NULL },
+  { "pathLenConstraint", 537411587, NULL },
+  { "0", 10, "MAX"},
+  { "CRLDistributionPoints", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "DistributionPoint"},
+  { "DistributionPoint", 1610612741, NULL },
+  { "distributionPoint", 1610637314, "DistributionPointName"},
+  { NULL, 2056, "0"},
+  { "reasons", 1610637314, "ReasonFlags"},
+  { NULL, 4104, "1"},
+  { "cRLIssuer", 536895490, "GeneralNames"},
+  { NULL, 4104, "2"},
+  { "DistributionPointName", 1610612754, NULL },
+  { "fullName", 1610620930, "GeneralNames"},
+  { NULL, 4104, "0"},
+  { "nameRelativeToCRLIssuer", 536879106, "RelativeDistinguishedName"},
+  { NULL, 4104, "1"},
+  { "ReasonFlags", 1073741830, NULL },
+  { "ExtKeyUsageSyntax", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 12, NULL },
+  { "AuthorityInfoAccessSyntax", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "AccessDescription"},
+  { "AccessDescription", 1610612741, NULL },
+  { "accessMethod", 1073741836, NULL },
+  { "accessLocation", 2, "GeneralName"},
+  { "Attribute", 1610612741, NULL },
+  { "type", 1073741836, NULL },
+  { "values", 536870927, NULL },
+  { NULL, 13, NULL },
+  { "AttributeTypeAndValue", 1610612741, NULL },
+  { "type", 1073741836, NULL },
+  { "value", 13, NULL },
+  { "Name", 1610612754, NULL },
+  { "rdnSequence", 536870923, NULL },
+  { NULL, 2, "RelativeDistinguishedName"},
+  { "DistinguishedName", 1610612747, NULL },
+  { NULL, 2, "RelativeDistinguishedName"},
+  { "RelativeDistinguishedName", 1612709903, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "AttributeTypeAndValue"},
+  { "Certificate", 1610612741, NULL },
+  { "tbsCertificate", 1073741826, "TBSCertificate"},
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 6, NULL },
+  { "TBSCertificate", 1610612741, NULL },
+  { "version", 1610653699, NULL },
+  { NULL, 1073741833, "0"},
+  { NULL, 2056, "0"},
+  { "serialNumber", 1073741826, "CertificateSerialNumber"},
+  { "signature", 1073741826, "AlgorithmIdentifier"},
+  { "issuer", 1073741826, "Name"},
+  { "validity", 1073741826, "Validity"},
+  { "subject", 1073741826, "Name"},
+  { "subjectPublicKeyInfo", 1073741826, "SubjectPublicKeyInfo"},
+  { "issuerUniqueID", 1610637314, "UniqueIdentifier"},
+  { NULL, 4104, "1"},
+  { "subjectUniqueID", 1610637314, "UniqueIdentifier"},
+  { NULL, 4104, "2"},
+  { "extensions", 536895490, "Extensions"},
+  { NULL, 2056, "3"},
+  { "CertificateSerialNumber", 1073741827, NULL },
+  { "Validity", 1610612741, NULL },
+  { "notBefore", 1073741826, "Time"},
+  { "notAfter", 2, "Time"},
+  { "Time", 1610612754, NULL },
+  { "utcTime", 1073741860, NULL },
+  { "generalTime", 37, NULL },
+  { "UniqueIdentifier", 1073741830, NULL },
+  { "SubjectPublicKeyInfo", 1610612741, NULL },
+  { "algorithm", 1073741826, "AlgorithmIdentifier"},
+  { "subjectPublicKey", 6, NULL },
+  { "Extensions", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "Extension"},
+  { "Extension", 1610612741, NULL },
+  { "extnID", 1073741836, NULL },
+  { "critical", 1610645508, NULL },
+  { NULL, 131081, NULL },
+  { "extnValue", 7, NULL },
+  { "CertificateList", 1610612741, NULL },
+  { "tbsCertList", 1073741826, "TBSCertList"},
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 6, NULL },
+  { "TBSCertList", 1610612741, NULL },
+  { "version", 1073758211, NULL },
+  { "signature", 1073741826, "AlgorithmIdentifier"},
+  { "issuer", 1073741826, "Name"},
+  { "thisUpdate", 1073741826, "Time"},
+  { "nextUpdate", 1073758210, "Time"},
+  { "revokedCertificates", 1610629131, NULL },
+  { NULL, 536870917, NULL },
+  { "userCertificate", 1073741826, "CertificateSerialNumber"},
+  { "revocationDate", 1073741826, "Time"},
+  { "crlEntryExtensions", 16386, "Extensions"},
+  { "crlExtensions", 536895490, "Extensions"},
+  { NULL, 2056, "0"},
+  { "AlgorithmIdentifier", 1610612741, NULL },
+  { "algorithm", 1073741836, NULL },
+  { "parameters", 541081613, NULL },
+  { "algorithm", 1, NULL },
+  { "Dss-Sig-Value", 1610612741, NULL },
+  { "r", 1073741827, NULL },
+  { "s", 3, NULL },
+  { "Dss-Parms", 1610612741, NULL },
+  { "p", 1073741827, NULL },
+  { "q", 1073741827, NULL },
+  { "g", 3, NULL },
+  { "pkcs-7-ContentInfo", 1610612741, NULL },
+  { "contentType", 1073741836, NULL },
+  { "content", 541073421, NULL },
+  { NULL, 1073743880, "0"},
+  { "contentType", 1, NULL },
+  { "pkcs-7-DigestInfo", 1610612741, NULL },
+  { "digestAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "digest", 7, NULL },
+  { "pkcs-7-SignedData", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "digestAlgorithms", 1073741826, "pkcs-7-DigestAlgorithmIdentifiers"},
+  { "encapContentInfo", 1073741826, "pkcs-7-EncapsulatedContentInfo"},
+  { "certificates", 1610637314, "pkcs-7-CertificateSet"},
+  { NULL, 4104, "0"},
+  { "crls", 1610637314, "pkcs-7-CertificateRevocationLists"},
+  { NULL, 4104, "1"},
+  { "signerInfos", 2, "pkcs-7-SignerInfos"},
+  { "pkcs-7-DigestAlgorithmIdentifiers", 1610612751, NULL },
+  { NULL, 2, "AlgorithmIdentifier"},
+  { "pkcs-7-EncapsulatedContentInfo", 1610612741, NULL },
+  { "eContentType", 1073741836, NULL },
+  { "eContent", 536895501, NULL },
+  { NULL, 2056, "0"},
+  { "pkcs-7-CertificateRevocationLists", 1610612751, NULL },
+  { NULL, 13, NULL },
+  { "pkcs-7-CertificateChoices", 1610612754, NULL },
+  { "certificate", 13, NULL },
+  { "pkcs-7-CertificateSet", 1610612751, NULL },
+  { NULL, 2, "pkcs-7-CertificateChoices"},
+  { "IssuerAndSerialNumber", 1610612741, NULL },
+  { "issuer", 1073741826, "Name"},
+  { "serialNumber", 2, "CertificateSerialNumber"},
+  { "pkcs-7-SignerInfo", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "sid", 1073741826, "SignerIdentifier"},
+  { "digestAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signedAttrs", 1610637314, "SignedAttributes"},
+  { NULL, 4104, "0"},
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 1073741831, NULL },
+  { "unsignedAttrs", 536895490, "SignedAttributes"},
+  { NULL, 4104, "1"},
+  { "SignedAttributes", 1612709903, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "Attribute"},
+  { "SignerIdentifier", 1610612754, NULL },
+  { "issuerAndSerialNumber", 1073741826, "IssuerAndSerialNumber"},
+  { "subjectKeyIdentifier", 536879111, NULL },
+  { NULL, 4104, "0"},
+  { "pkcs-7-SignerInfos", 1610612751, NULL },
+  { NULL, 2, "pkcs-7-SignerInfo"},
+  { "pkcs-10-CertificationRequestInfo", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "subject", 1073741826, "Name"},
+  { "subjectPKInfo", 1073741826, "SubjectPublicKeyInfo"},
+  { "attributes", 536879106, "Attributes"},
+  { NULL, 4104, "0"},
+  { "Attributes", 1610612751, NULL },
+  { NULL, 2, "Attribute"},
+  { "pkcs-10-CertificationRequest", 1610612741, NULL },
+  { "certificationRequestInfo", 1073741826, "pkcs-10-CertificationRequestInfo"},
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 6, NULL },
+  { "pkcs-9-at-challengePassword", 1879048204, NULL },
+  { "iso", 1073741825, "1"},
+  { "member-body", 1073741825, "2"},
+  { "us", 1073741825, "840"},
+  { "rsadsi", 1073741825, "113549"},
+  { "pkcs", 1073741825, "1"},
+  { NULL, 1073741825, "9"},
+  { NULL, 1, "7"},
+  { "pkcs-9-challengePassword", 1610612754, NULL },
+  { "printableString", 1073741855, NULL },
+  { "utf8String", 34, NULL },
+  { "pkcs-9-localKeyId", 1073741831, NULL },
+  { "pkcs-8-PrivateKeyInfo", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "privateKeyAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "privateKey", 1073741831, NULL },
+  { "attributes", 536895490, "Attributes"},
+  { NULL, 4104, "0"},
+  { "pkcs-8-EncryptedPrivateKeyInfo", 1610612741, NULL },
+  { "encryptionAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "encryptedData", 2, "pkcs-8-EncryptedData"},
+  { "pkcs-8-EncryptedData", 1073741831, NULL },
+  { "pkcs-5-des-CBC-params", 1612709895, NULL },
+  { NULL, 1048586, "8"},
+  { "pkcs-5-des-EDE3-CBC-params", 1612709895, NULL },
+  { NULL, 1048586, "8"},
+  { "pkcs-5-aes128-CBC-params", 1612709895, NULL },
+  { NULL, 1048586, "16"},
+  { "pkcs-5-aes192-CBC-params", 1612709895, NULL },
+  { NULL, 1048586, "16"},
+  { "pkcs-5-aes256-CBC-params", 1612709895, NULL },
+  { NULL, 1048586, "16"},
+  { "Gost28147-89-Parameters", 1610612741, NULL },
+  { "iv", 1073741831, NULL },
+  { "encryptionParamSet", 12, NULL },
+  { "pkcs-5-PBE-params", 1610612741, NULL },
+  { "salt", 1073741831, NULL },
+  { "iterationCount", 3, NULL },
+  { "pkcs-5-PBES2-params", 1610612741, NULL },
+  { "keyDerivationFunc", 1073741826, "AlgorithmIdentifier"},
+  { "encryptionScheme", 2, "AlgorithmIdentifier"},
+  { "pkcs-5-PBKDF2-params", 1610612741, NULL },
+  { "salt", 1610612754, NULL },
+  { "specified", 1073741831, NULL },
+  { "otherSource", 2, "AlgorithmIdentifier"},
+  { "iterationCount", 1611137027, NULL },
+  { "1", 10, "MAX"},
+  { "keyLength", 1611153411, NULL },
+  { "1", 10, "MAX"},
+  { "prf", 16386, "AlgorithmIdentifier"},
+  { "pkcs-12-PFX", 1610612741, NULL },
+  { "version", 1610874883, NULL },
+  { "v3", 1, "3"},
+  { "authSafe", 1073741826, "pkcs-7-ContentInfo"},
+  { "macData", 16386, "pkcs-12-MacData"},
+  { "pkcs-12-PbeParams", 1610612741, NULL },
+  { "salt", 1073741831, NULL },
+  { "iterations", 3, NULL },
+  { "pkcs-12-MacData", 1610612741, NULL },
+  { "mac", 1073741826, "pkcs-7-DigestInfo"},
+  { "macSalt", 1073741831, NULL },
+  { "iterations", 536903683, NULL },
+  { NULL, 9, "1"},
+  { "pkcs-12-AuthenticatedSafe", 1610612747, NULL },
+  { NULL, 2, "pkcs-7-ContentInfo"},
+  { "pkcs-12-SafeContents", 1610612747, NULL },
+  { NULL, 2, "pkcs-12-SafeBag"},
+  { "pkcs-12-SafeBag", 1610612741, NULL },
+  { "bagId", 1073741836, NULL },
+  { "bagValue", 1614815245, NULL },
+  { NULL, 1073743880, "0"},
+  { "badId", 1, NULL },
+  { "bagAttributes", 536887311, NULL },
+  { NULL, 2, "Attribute"},
+  { "pkcs-12-CertBag", 1610612741, NULL },
+  { "certId", 1073741836, NULL },
+  { "certValue", 541073421, NULL },
+  { NULL, 1073743880, "0"},
+  { "certId", 1, NULL },
+  { "pkcs-12-CRLBag", 1610612741, NULL },
+  { "crlId", 1073741836, NULL },
+  { "crlValue", 541073421, NULL },
+  { NULL, 1073743880, "0"},
+  { "crlId", 1, NULL },
+  { "pkcs-12-SecretBag", 1610612741, NULL },
+  { "secretTypeId", 1073741836, NULL },
+  { "secretValue", 541073421, NULL },
+  { NULL, 1073743880, "0"},
+  { "secretTypeId", 1, NULL },
+  { "pkcs-7-Data", 1073741831, NULL },
+  { "pkcs-7-EncryptedData", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "encryptedContentInfo", 1073741826, "pkcs-7-EncryptedContentInfo"},
+  { "unprotectedAttrs", 536895490, "pkcs-7-UnprotectedAttributes"},
+  { NULL, 4104, "1"},
+  { "pkcs-7-EncryptedContentInfo", 1610612741, NULL },
+  { "contentType", 1073741836, NULL },
+  { "contentEncryptionAlgorithm", 1073741826, "pkcs-7-ContentEncryptionAlgorithmIdentifier"},
+  { "encryptedContent", 536895495, NULL },
+  { NULL, 4104, "0"},
+  { "pkcs-7-ContentEncryptionAlgorithmIdentifier", 1073741826, "AlgorithmIdentifier"},
+  { "pkcs-7-UnprotectedAttributes", 1612709903, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "Attribute"},
+  { "ProxyCertInfo", 1610612741, NULL },
+  { "pCPathLenConstraint", 1611153411, NULL },
+  { "0", 10, "MAX"},
+  { "proxyPolicy", 2, "ProxyPolicy"},
+  { "ProxyPolicy", 1610612741, NULL },
+  { "policyLanguage", 1073741836, NULL },
+  { "policy", 16391, NULL },
+  { "certificatePolicies", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "PolicyInformation"},
+  { "PolicyInformation", 1610612741, NULL },
+  { "policyIdentifier", 1073741836, NULL },
+  { "policyQualifiers", 538984459, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "PolicyQualifierInfo"},
+  { "PolicyQualifierInfo", 1610612741, NULL },
+  { "policyQualifierId", 1073741836, NULL },
+  { "qualifier", 541065229, NULL },
+  { "policyQualifierId", 1, NULL },
+  { "CPSuri", 1073741853, NULL },
+  { "UserNotice", 1610612741, NULL },
+  { "noticeRef", 1073758210, "NoticeReference"},
+  { "explicitText", 16386, "DisplayText"},
+  { "NoticeReference", 1610612741, NULL },
+  { "organization", 1073741826, "DisplayText"},
+  { "noticeNumbers", 536870923, NULL },
+  { NULL, 3, NULL },
+  { "DisplayText", 1610612754, NULL },
+  { "ia5String", 1612709917, NULL },
+  { "200", 524298, "1"},
+  { "visibleString", 1612709923, NULL },
+  { "200", 524298, "1"},
+  { "bmpString", 1612709921, NULL },
+  { "200", 524298, "1"},
+  { "utf8String", 538968098, NULL },
+  { "200", 524298, "1"},
+  { "OCSPRequest", 1610612741, NULL },
+  { "tbsRequest", 1073741826, "TBSRequest"},
+  { "optionalSignature", 536895490, "Signature"},
+  { NULL, 2056, "0"},
+  { "TBSRequest", 1610612741, NULL },
+  { "version", 1610653699, NULL },
+  { NULL, 1073741833, "0"},
+  { NULL, 2056, "0"},
+  { "requestorName", 1610637314, "GeneralName"},
+  { NULL, 2056, "1"},
+  { "requestList", 1610612747, NULL },
+  { NULL, 2, "Request"},
+  { "requestExtensions", 536895490, "Extensions"},
+  { NULL, 2056, "2"},
+  { "Signature", 1610612741, NULL },
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 1073741830, NULL },
+  { "certs", 536895499, NULL },
+  { NULL, 1073743880, "0"},
+  { NULL, 2, "Certificate"},
+  { "Request", 1610612741, NULL },
+  { "reqCert", 1073741826, "CertID"},
+  { "singleRequestExtensions", 536895490, "Extensions"},
+  { NULL, 2056, "0"},
+  { "CertID", 1610612741, NULL },
+  { "hashAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "issuerNameHash", 1073741831, NULL },
+  { "issuerKeyHash", 1073741831, NULL },
+  { "serialNumber", 2, "CertificateSerialNumber"},
+  { "OCSPResponse", 1610612741, NULL },
+  { "responseStatus", 1073741826, "OCSPResponseStatus"},
+  { "responseBytes", 536895490, "ResponseBytes"},
+  { NULL, 2056, "0"},
+  { "OCSPResponseStatus", 1610874901, NULL },
+  { "successful", 1073741825, "0"},
+  { "malformedRequest", 1073741825, "1"},
+  { "internalError", 1073741825, "2"},
+  { "tryLater", 1073741825, "3"},
+  { "sigRequired", 1073741825, "5"},
+  { "unauthorized", 1, "6"},
+  { "ResponseBytes", 1610612741, NULL },
+  { "responseType", 1073741836, NULL },
+  { "response", 7, NULL },
+  { "BasicOCSPResponse", 1610612741, NULL },
+  { "tbsResponseData", 1073741826, "ResponseData"},
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 1073741830, NULL },
+  { "certs", 536895499, NULL },
+  { NULL, 1073743880, "0"},
+  { NULL, 2, "Certificate"},
+  { "ResponseData", 1610612741, NULL },
+  { "version", 1610653699, NULL },
+  { NULL, 1073741833, "0"},
+  { NULL, 2056, "0"},
+  { "responderID", 1073741826, "ResponderID"},
+  { "producedAt", 1073741861, NULL },
+  { "responses", 1610612747, NULL },
+  { NULL, 2, "SingleResponse"},
+  { "responseExtensions", 536895490, "Extensions"},
+  { NULL, 2056, "1"},
+  { "ResponderID", 1610612754, NULL },
+  { "byName", 1610620939, NULL },
+  { NULL, 1073743880, "1"},
+  { NULL, 2, "RelativeDistinguishedName"},
+  { "byKey", 536879111, NULL },
+  { NULL, 2056, "2"},
+  { "SingleResponse", 1610612741, NULL },
+  { "certID", 1073741826, "CertID"},
+  { "certStatus", 1073741826, "CertStatus"},
+  { "thisUpdate", 1073741861, NULL },
+  { "nextUpdate", 1610637349, NULL },
+  { NULL, 2056, "0"},
+  { "singleExtensions", 536895490, "Extensions"},
+  { NULL, 2056, "1"},
+  { "CertStatus", 1610612754, NULL },
+  { "good", 1610620948, NULL },
+  { NULL, 4104, "0"},
+  { "revoked", 1610620930, "RevokedInfo"},
+  { NULL, 4104, "1"},
+  { "unknown", 536879106, "UnknownInfo"},
+  { NULL, 4104, "2"},
+  { "RevokedInfo", 1610612741, NULL },
+  { "revocationTime", 1073741861, NULL },
+  { "revocationReason", 537157653, NULL },
+  { NULL, 1073743880, "0"},
+  { "unspecified", 1, "0"},
+  { "UnknownInfo", 1073741844, NULL },
+  { "NameConstraints", 1610612741, NULL },
+  { "permittedSubtrees", 1610637314, "GeneralSubtrees"},
+  { NULL, 4104, "0"},
+  { "excludedSubtrees", 536895490, "GeneralSubtrees"},
+  { NULL, 4104, "1"},
+  { "GeneralSubtrees", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "GeneralSubtree"},
+  { "GeneralSubtree", 1610612741, NULL },

grub-core/commands/appendedsig/pkix_asn1_tab.c line 484

Quoted 10 lines
grub-core/commands/appendedsig/pkix_asn1_tab.c new file +10 -0
+  { "base", 1073741826, "GeneralName"},
+  { "minimum", 1610653699, NULL },
+  { NULL, 1073741833, "0"},
+  { NULL, 4104, "0"},
+  { "maximum", 536895491, NULL },
+  { NULL, 4104, "1"},
+  { "TlsFeatures", 536870923, NULL },
+  { NULL, 3, NULL },
+  { NULL, 0, NULL }
+};

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

Reviewed-by on v1 8/21
#31 lore raw

Re: [PATCH v1 08/21] appended signatures: import GNUTLS's ASN.1 description files

In reply to Sudhakar Kuppusamy
Quoted 644 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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.

---
 .../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 +118 -0
new file mode 100644
index 000000000..ddd1314e6
@@ -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"},

grub-core/commands/appendedsig/gnutls_asn1_tab.c new file +3 -0
+  { NULL, 4104, "0"},
+  { NULL, 0, NULL }
+};
grub-core/commands/appendedsig/pkix_asn1_tab.c new file +17 -0
new file mode 100644
index 000000000..adef69d95
@@ -0,0 +1,484 @@
+#include <grub/mm.h>
+#include <grub/libtasn1.h>
+
+const asn1_static_node pkix_asn1_tab[] = {
+  { "PKIX1", 536875024, NULL },
+  { NULL, 1073741836, NULL },
+  { "PrivateKeyUsagePeriod", 1610612741, NULL },
+  { "notBefore", 1610637349, NULL },
+  { NULL, 4104, "0"},
+  { "notAfter", 536895525, NULL },
+  { NULL, 4104, "1"},
+  { "AuthorityKeyIdentifier", 1610612741, NULL },
+  { "keyIdentifier", 1610637319, NULL },
+  { NULL, 4104, "0"},
+  { "authorityCertIssuer", 1610637314, "GeneralNames"},
+  { NULL, 4104, "1"},
+  { "authorityCertSerialNumber", 536895490, 

"CertificateSerialNumber"},

grub-core/commands/appendedsig/pkix_asn1_tab.c new file +65 -0
+  { NULL, 4104, "2"},
+  { "SubjectKeyIdentifier", 1073741831, NULL },
+  { "KeyUsage", 1073741830, NULL },
+  { "DirectoryString", 1610612754, NULL },
+  { "teletexString", 1612709918, NULL },
+  { "MAX", 524298, "1"},
+  { "printableString", 1612709919, NULL },
+  { "MAX", 524298, "1"},
+  { "universalString", 1612709920, NULL },
+  { "MAX", 524298, "1"},
+  { "utf8String", 1612709922, NULL },
+  { "MAX", 524298, "1"},
+  { "bmpString", 1612709921, NULL },
+  { "MAX", 524298, "1"},
+  { "ia5String", 538968093, NULL },
+  { "MAX", 524298, "1"},
+  { "SubjectAltName", 1073741826, "GeneralNames"},
+  { "GeneralNames", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "GeneralName"},
+  { "GeneralName", 1610612754, NULL },
+  { "otherName", 1610620930, "AnotherName"},
+  { NULL, 4104, "0"},
+  { "rfc822Name", 1610620957, NULL },
+  { NULL, 4104, "1"},
+  { "dNSName", 1610620957, NULL },
+  { NULL, 4104, "2"},
+  { "x400Address", 1610620941, NULL },
+  { NULL, 4104, "3"},
+  { "directoryName", 1610620939, NULL },
+  { NULL, 1073743880, "4"},
+  { NULL, 2, "RelativeDistinguishedName"},
+  { "ediPartyName", 1610620941, NULL },
+  { NULL, 4104, "5"},
+  { "uniformResourceIdentifier", 1610620957, NULL },
+  { NULL, 4104, "6"},
+  { "iPAddress", 1610620935, NULL },
+  { NULL, 4104, "7"},
+  { "registeredID", 536879116, NULL },
+  { NULL, 4104, "8"},
+  { "AnotherName", 1610612741, NULL },
+  { "type-id", 1073741836, NULL },
+  { "value", 541073421, NULL },
+  { NULL, 1073743880, "0"},
+  { "type-id", 1, NULL },
+  { "IssuerAltName", 1073741826, "GeneralNames"},
+  { "BasicConstraints", 1610612741, NULL },
+  { "cA", 1610645508, NULL },
+  { NULL, 131081, NULL },
+  { "pathLenConstraint", 537411587, NULL },
+  { "0", 10, "MAX"},
+  { "CRLDistributionPoints", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "DistributionPoint"},
+  { "DistributionPoint", 1610612741, NULL },
+  { "distributionPoint", 1610637314, "DistributionPointName"},
+  { NULL, 2056, "0"},
+  { "reasons", 1610637314, "ReasonFlags"},
+  { NULL, 4104, "1"},
+  { "cRLIssuer", 536895490, "GeneralNames"},
+  { NULL, 4104, "2"},
+  { "DistributionPointName", 1610612754, NULL },
+  { "fullName", 1610620930, "GeneralNames"},
+  { NULL, 4104, "0"},
+  { "nameRelativeToCRLIssuer", 536879106, 

"RelativeDistinguishedName"},

grub-core/commands/appendedsig/pkix_asn1_tab.c new file +104 -0
+  { NULL, 4104, "1"},
+  { "ReasonFlags", 1073741830, NULL },
+  { "ExtKeyUsageSyntax", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 12, NULL },
+  { "AuthorityInfoAccessSyntax", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "AccessDescription"},
+  { "AccessDescription", 1610612741, NULL },
+  { "accessMethod", 1073741836, NULL },
+  { "accessLocation", 2, "GeneralName"},
+  { "Attribute", 1610612741, NULL },
+  { "type", 1073741836, NULL },
+  { "values", 536870927, NULL },
+  { NULL, 13, NULL },
+  { "AttributeTypeAndValue", 1610612741, NULL },
+  { "type", 1073741836, NULL },
+  { "value", 13, NULL },
+  { "Name", 1610612754, NULL },
+  { "rdnSequence", 536870923, NULL },
+  { NULL, 2, "RelativeDistinguishedName"},
+  { "DistinguishedName", 1610612747, NULL },
+  { NULL, 2, "RelativeDistinguishedName"},
+  { "RelativeDistinguishedName", 1612709903, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "AttributeTypeAndValue"},
+  { "Certificate", 1610612741, NULL },
+  { "tbsCertificate", 1073741826, "TBSCertificate"},
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 6, NULL },
+  { "TBSCertificate", 1610612741, NULL },
+  { "version", 1610653699, NULL },
+  { NULL, 1073741833, "0"},
+  { NULL, 2056, "0"},
+  { "serialNumber", 1073741826, "CertificateSerialNumber"},
+  { "signature", 1073741826, "AlgorithmIdentifier"},
+  { "issuer", 1073741826, "Name"},
+  { "validity", 1073741826, "Validity"},
+  { "subject", 1073741826, "Name"},
+  { "subjectPublicKeyInfo", 1073741826, "SubjectPublicKeyInfo"},
+  { "issuerUniqueID", 1610637314, "UniqueIdentifier"},
+  { NULL, 4104, "1"},
+  { "subjectUniqueID", 1610637314, "UniqueIdentifier"},
+  { NULL, 4104, "2"},
+  { "extensions", 536895490, "Extensions"},
+  { NULL, 2056, "3"},
+  { "CertificateSerialNumber", 1073741827, NULL },
+  { "Validity", 1610612741, NULL },
+  { "notBefore", 1073741826, "Time"},
+  { "notAfter", 2, "Time"},
+  { "Time", 1610612754, NULL },
+  { "utcTime", 1073741860, NULL },
+  { "generalTime", 37, NULL },
+  { "UniqueIdentifier", 1073741830, NULL },
+  { "SubjectPublicKeyInfo", 1610612741, NULL },
+  { "algorithm", 1073741826, "AlgorithmIdentifier"},
+  { "subjectPublicKey", 6, NULL },
+  { "Extensions", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "Extension"},
+  { "Extension", 1610612741, NULL },
+  { "extnID", 1073741836, NULL },
+  { "critical", 1610645508, NULL },
+  { NULL, 131081, NULL },
+  { "extnValue", 7, NULL },
+  { "CertificateList", 1610612741, NULL },
+  { "tbsCertList", 1073741826, "TBSCertList"},
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 6, NULL },
+  { "TBSCertList", 1610612741, NULL },
+  { "version", 1073758211, NULL },
+  { "signature", 1073741826, "AlgorithmIdentifier"},
+  { "issuer", 1073741826, "Name"},
+  { "thisUpdate", 1073741826, "Time"},
+  { "nextUpdate", 1073758210, "Time"},
+  { "revokedCertificates", 1610629131, NULL },
+  { NULL, 536870917, NULL },
+  { "userCertificate", 1073741826, "CertificateSerialNumber"},
+  { "revocationDate", 1073741826, "Time"},
+  { "crlEntryExtensions", 16386, "Extensions"},
+  { "crlExtensions", 536895490, "Extensions"},
+  { NULL, 2056, "0"},
+  { "AlgorithmIdentifier", 1610612741, NULL },
+  { "algorithm", 1073741836, NULL },
+  { "parameters", 541081613, NULL },
+  { "algorithm", 1, NULL },
+  { "Dss-Sig-Value", 1610612741, NULL },
+  { "r", 1073741827, NULL },
+  { "s", 3, NULL },
+  { "Dss-Parms", 1610612741, NULL },
+  { "p", 1073741827, NULL },
+  { "q", 1073741827, NULL },
+  { "g", 3, NULL },
+  { "pkcs-7-ContentInfo", 1610612741, NULL },
+  { "contentType", 1073741836, NULL },
+  { "content", 541073421, NULL },
+  { NULL, 1073743880, "0"},
+  { "contentType", 1, NULL },
+  { "pkcs-7-DigestInfo", 1610612741, NULL },
+  { "digestAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "digest", 7, NULL },
+  { "pkcs-7-SignedData", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "digestAlgorithms", 1073741826, 

"pkcs-7-DigestAlgorithmIdentifiers"},

grub-core/commands/appendedsig/pkix_asn1_tab.c new file +50 -0
+  { "encapContentInfo", 1073741826, "pkcs-7-EncapsulatedContentInfo"},
+  { "certificates", 1610637314, "pkcs-7-CertificateSet"},
+  { NULL, 4104, "0"},
+  { "crls", 1610637314, "pkcs-7-CertificateRevocationLists"},
+  { NULL, 4104, "1"},
+  { "signerInfos", 2, "pkcs-7-SignerInfos"},
+  { "pkcs-7-DigestAlgorithmIdentifiers", 1610612751, NULL },
+  { NULL, 2, "AlgorithmIdentifier"},
+  { "pkcs-7-EncapsulatedContentInfo", 1610612741, NULL },
+  { "eContentType", 1073741836, NULL },
+  { "eContent", 536895501, NULL },
+  { NULL, 2056, "0"},
+  { "pkcs-7-CertificateRevocationLists", 1610612751, NULL },
+  { NULL, 13, NULL },
+  { "pkcs-7-CertificateChoices", 1610612754, NULL },
+  { "certificate", 13, NULL },
+  { "pkcs-7-CertificateSet", 1610612751, NULL },
+  { NULL, 2, "pkcs-7-CertificateChoices"},
+  { "IssuerAndSerialNumber", 1610612741, NULL },
+  { "issuer", 1073741826, "Name"},
+  { "serialNumber", 2, "CertificateSerialNumber"},
+  { "pkcs-7-SignerInfo", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "sid", 1073741826, "SignerIdentifier"},
+  { "digestAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signedAttrs", 1610637314, "SignedAttributes"},
+  { NULL, 4104, "0"},
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 1073741831, NULL },
+  { "unsignedAttrs", 536895490, "SignedAttributes"},
+  { NULL, 4104, "1"},
+  { "SignedAttributes", 1612709903, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "Attribute"},
+  { "SignerIdentifier", 1610612754, NULL },
+  { "issuerAndSerialNumber", 1073741826, "IssuerAndSerialNumber"},
+  { "subjectKeyIdentifier", 536879111, NULL },
+  { NULL, 4104, "0"},
+  { "pkcs-7-SignerInfos", 1610612751, NULL },
+  { NULL, 2, "pkcs-7-SignerInfo"},
+  { "pkcs-10-CertificationRequestInfo", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "subject", 1073741826, "Name"},
+  { "subjectPKInfo", 1073741826, "SubjectPublicKeyInfo"},
+  { "attributes", 536879106, "Attributes"},
+  { NULL, 4104, "0"},
+  { "Attributes", 1610612751, NULL },
+  { NULL, 2, "Attribute"},
+  { "pkcs-10-CertificationRequest", 1610612741, NULL },
+  { "certificationRequestInfo", 1073741826,

"pkcs-10-CertificationRequestInfo"},

grub-core/commands/appendedsig/pkix_asn1_tab.c new file +95 -0
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 6, NULL },
+  { "pkcs-9-at-challengePassword", 1879048204, NULL },
+  { "iso", 1073741825, "1"},
+  { "member-body", 1073741825, "2"},
+  { "us", 1073741825, "840"},
+  { "rsadsi", 1073741825, "113549"},
+  { "pkcs", 1073741825, "1"},
+  { NULL, 1073741825, "9"},
+  { NULL, 1, "7"},
+  { "pkcs-9-challengePassword", 1610612754, NULL },
+  { "printableString", 1073741855, NULL },
+  { "utf8String", 34, NULL },
+  { "pkcs-9-localKeyId", 1073741831, NULL },
+  { "pkcs-8-PrivateKeyInfo", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "privateKeyAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "privateKey", 1073741831, NULL },
+  { "attributes", 536895490, "Attributes"},
+  { NULL, 4104, "0"},
+  { "pkcs-8-EncryptedPrivateKeyInfo", 1610612741, NULL },
+  { "encryptionAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "encryptedData", 2, "pkcs-8-EncryptedData"},
+  { "pkcs-8-EncryptedData", 1073741831, NULL },
+  { "pkcs-5-des-CBC-params", 1612709895, NULL },
+  { NULL, 1048586, "8"},
+  { "pkcs-5-des-EDE3-CBC-params", 1612709895, NULL },
+  { NULL, 1048586, "8"},
+  { "pkcs-5-aes128-CBC-params", 1612709895, NULL },
+  { NULL, 1048586, "16"},
+  { "pkcs-5-aes192-CBC-params", 1612709895, NULL },
+  { NULL, 1048586, "16"},
+  { "pkcs-5-aes256-CBC-params", 1612709895, NULL },
+  { NULL, 1048586, "16"},
+  { "Gost28147-89-Parameters", 1610612741, NULL },
+  { "iv", 1073741831, NULL },
+  { "encryptionParamSet", 12, NULL },
+  { "pkcs-5-PBE-params", 1610612741, NULL },
+  { "salt", 1073741831, NULL },
+  { "iterationCount", 3, NULL },
+  { "pkcs-5-PBES2-params", 1610612741, NULL },
+  { "keyDerivationFunc", 1073741826, "AlgorithmIdentifier"},
+  { "encryptionScheme", 2, "AlgorithmIdentifier"},
+  { "pkcs-5-PBKDF2-params", 1610612741, NULL },
+  { "salt", 1610612754, NULL },
+  { "specified", 1073741831, NULL },
+  { "otherSource", 2, "AlgorithmIdentifier"},
+  { "iterationCount", 1611137027, NULL },
+  { "1", 10, "MAX"},
+  { "keyLength", 1611153411, NULL },
+  { "1", 10, "MAX"},
+  { "prf", 16386, "AlgorithmIdentifier"},
+  { "pkcs-12-PFX", 1610612741, NULL },
+  { "version", 1610874883, NULL },
+  { "v3", 1, "3"},
+  { "authSafe", 1073741826, "pkcs-7-ContentInfo"},
+  { "macData", 16386, "pkcs-12-MacData"},
+  { "pkcs-12-PbeParams", 1610612741, NULL },
+  { "salt", 1073741831, NULL },
+  { "iterations", 3, NULL },
+  { "pkcs-12-MacData", 1610612741, NULL },
+  { "mac", 1073741826, "pkcs-7-DigestInfo"},
+  { "macSalt", 1073741831, NULL },
+  { "iterations", 536903683, NULL },
+  { NULL, 9, "1"},
+  { "pkcs-12-AuthenticatedSafe", 1610612747, NULL },
+  { NULL, 2, "pkcs-7-ContentInfo"},
+  { "pkcs-12-SafeContents", 1610612747, NULL },
+  { NULL, 2, "pkcs-12-SafeBag"},
+  { "pkcs-12-SafeBag", 1610612741, NULL },
+  { "bagId", 1073741836, NULL },
+  { "bagValue", 1614815245, NULL },
+  { NULL, 1073743880, "0"},
+  { "badId", 1, NULL },
+  { "bagAttributes", 536887311, NULL },
+  { NULL, 2, "Attribute"},
+  { "pkcs-12-CertBag", 1610612741, NULL },
+  { "certId", 1073741836, NULL },
+  { "certValue", 541073421, NULL },
+  { NULL, 1073743880, "0"},
+  { "certId", 1, NULL },
+  { "pkcs-12-CRLBag", 1610612741, NULL },
+  { "crlId", 1073741836, NULL },
+  { "crlValue", 541073421, NULL },
+  { NULL, 1073743880, "0"},
+  { "crlId", 1, NULL },
+  { "pkcs-12-SecretBag", 1610612741, NULL },
+  { "secretTypeId", 1073741836, NULL },
+  { "secretValue", 541073421, NULL },
+  { NULL, 1073743880, "0"},
+  { "secretTypeId", 1, NULL },
+  { "pkcs-7-Data", 1073741831, NULL },
+  { "pkcs-7-EncryptedData", 1610612741, NULL },
+  { "version", 1073741827, NULL },
+  { "encryptedContentInfo", 1073741826, 

"pkcs-7-EncryptedContentInfo"},

grub-core/commands/appendedsig/pkix_asn1_tab.c new file +5 -0
+  { "unprotectedAttrs", 536895490, "pkcs-7-UnprotectedAttributes"},
+  { NULL, 4104, "1"},
+  { "pkcs-7-EncryptedContentInfo", 1610612741, NULL },
+  { "contentType", 1073741836, NULL },
+  { "contentEncryptionAlgorithm", 1073741826,

"pkcs-7-ContentEncryptionAlgorithmIdentifier"},

grub-core/commands/appendedsig/pkix_asn1_tab.c new file +3 -0
+  { "encryptedContent", 536895495, NULL },
+  { NULL, 4104, "0"},
+  { "pkcs-7-ContentEncryptionAlgorithmIdentifier", 1073741826,

"AlgorithmIdentifier"},

grub-core/commands/appendedsig/pkix_asn1_tab.c new file +135 -0
+  { "pkcs-7-UnprotectedAttributes", 1612709903, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "Attribute"},
+  { "ProxyCertInfo", 1610612741, NULL },
+  { "pCPathLenConstraint", 1611153411, NULL },
+  { "0", 10, "MAX"},
+  { "proxyPolicy", 2, "ProxyPolicy"},
+  { "ProxyPolicy", 1610612741, NULL },
+  { "policyLanguage", 1073741836, NULL },
+  { "policy", 16391, NULL },
+  { "certificatePolicies", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "PolicyInformation"},
+  { "PolicyInformation", 1610612741, NULL },
+  { "policyIdentifier", 1073741836, NULL },
+  { "policyQualifiers", 538984459, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "PolicyQualifierInfo"},
+  { "PolicyQualifierInfo", 1610612741, NULL },
+  { "policyQualifierId", 1073741836, NULL },
+  { "qualifier", 541065229, NULL },
+  { "policyQualifierId", 1, NULL },
+  { "CPSuri", 1073741853, NULL },
+  { "UserNotice", 1610612741, NULL },
+  { "noticeRef", 1073758210, "NoticeReference"},
+  { "explicitText", 16386, "DisplayText"},
+  { "NoticeReference", 1610612741, NULL },
+  { "organization", 1073741826, "DisplayText"},
+  { "noticeNumbers", 536870923, NULL },
+  { NULL, 3, NULL },
+  { "DisplayText", 1610612754, NULL },
+  { "ia5String", 1612709917, NULL },
+  { "200", 524298, "1"},
+  { "visibleString", 1612709923, NULL },
+  { "200", 524298, "1"},
+  { "bmpString", 1612709921, NULL },
+  { "200", 524298, "1"},
+  { "utf8String", 538968098, NULL },
+  { "200", 524298, "1"},
+  { "OCSPRequest", 1610612741, NULL },
+  { "tbsRequest", 1073741826, "TBSRequest"},
+  { "optionalSignature", 536895490, "Signature"},
+  { NULL, 2056, "0"},
+  { "TBSRequest", 1610612741, NULL },
+  { "version", 1610653699, NULL },
+  { NULL, 1073741833, "0"},
+  { NULL, 2056, "0"},
+  { "requestorName", 1610637314, "GeneralName"},
+  { NULL, 2056, "1"},
+  { "requestList", 1610612747, NULL },
+  { NULL, 2, "Request"},
+  { "requestExtensions", 536895490, "Extensions"},
+  { NULL, 2056, "2"},
+  { "Signature", 1610612741, NULL },
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 1073741830, NULL },
+  { "certs", 536895499, NULL },
+  { NULL, 1073743880, "0"},
+  { NULL, 2, "Certificate"},
+  { "Request", 1610612741, NULL },
+  { "reqCert", 1073741826, "CertID"},
+  { "singleRequestExtensions", 536895490, "Extensions"},
+  { NULL, 2056, "0"},
+  { "CertID", 1610612741, NULL },
+  { "hashAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "issuerNameHash", 1073741831, NULL },
+  { "issuerKeyHash", 1073741831, NULL },
+  { "serialNumber", 2, "CertificateSerialNumber"},
+  { "OCSPResponse", 1610612741, NULL },
+  { "responseStatus", 1073741826, "OCSPResponseStatus"},
+  { "responseBytes", 536895490, "ResponseBytes"},
+  { NULL, 2056, "0"},
+  { "OCSPResponseStatus", 1610874901, NULL },
+  { "successful", 1073741825, "0"},
+  { "malformedRequest", 1073741825, "1"},
+  { "internalError", 1073741825, "2"},
+  { "tryLater", 1073741825, "3"},
+  { "sigRequired", 1073741825, "5"},
+  { "unauthorized", 1, "6"},
+  { "ResponseBytes", 1610612741, NULL },
+  { "responseType", 1073741836, NULL },
+  { "response", 7, NULL },
+  { "BasicOCSPResponse", 1610612741, NULL },
+  { "tbsResponseData", 1073741826, "ResponseData"},
+  { "signatureAlgorithm", 1073741826, "AlgorithmIdentifier"},
+  { "signature", 1073741830, NULL },
+  { "certs", 536895499, NULL },
+  { NULL, 1073743880, "0"},
+  { NULL, 2, "Certificate"},
+  { "ResponseData", 1610612741, NULL },
+  { "version", 1610653699, NULL },
+  { NULL, 1073741833, "0"},
+  { NULL, 2056, "0"},
+  { "responderID", 1073741826, "ResponderID"},
+  { "producedAt", 1073741861, NULL },
+  { "responses", 1610612747, NULL },
+  { NULL, 2, "SingleResponse"},
+  { "responseExtensions", 536895490, "Extensions"},
+  { NULL, 2056, "1"},
+  { "ResponderID", 1610612754, NULL },
+  { "byName", 1610620939, NULL },
+  { NULL, 1073743880, "1"},
+  { NULL, 2, "RelativeDistinguishedName"},
+  { "byKey", 536879111, NULL },
+  { NULL, 2056, "2"},
+  { "SingleResponse", 1610612741, NULL },
+  { "certID", 1073741826, "CertID"},
+  { "certStatus", 1073741826, "CertStatus"},
+  { "thisUpdate", 1073741861, NULL },
+  { "nextUpdate", 1610637349, NULL },
+  { NULL, 2056, "0"},
+  { "singleExtensions", 536895490, "Extensions"},
+  { NULL, 2056, "1"},
+  { "CertStatus", 1610612754, NULL },
+  { "good", 1610620948, NULL },
+  { NULL, 4104, "0"},
+  { "revoked", 1610620930, "RevokedInfo"},
+  { NULL, 4104, "1"},
+  { "unknown", 536879106, "UnknownInfo"},
+  { NULL, 4104, "2"},
+  { "RevokedInfo", 1610612741, NULL },
+  { "revocationTime", 1073741861, NULL },
+  { "revocationReason", 537157653, NULL },
+  { NULL, 1073743880, "0"},
+  { "unspecified", 1, "0"},
+  { "UnknownInfo", 1073741844, NULL },
+  { "NameConstraints", 1610612741, NULL },
+  { "permittedSubtrees", 1610637314, "GeneralSubtrees"},
+  { NULL, 4104, "0"},
+  { "excludedSubtrees", 536895490, "GeneralSubtrees"},
+  { NULL, 4104, "1"},
+  { "GeneralSubtrees", 1612709899, NULL },
+  { "MAX", 1074266122, "1"},
+  { NULL, 2, "GeneralSubtree"},
+  { "GeneralSubtree", 1610612741, NULL },

grub-core/commands/appendedsig/pkix_asn1_tab.c line 484

Quoted 10 lines
grub-core/commands/appendedsig/pkix_asn1_tab.c new file +10 -0
+  { "base", 1073741826, "GeneralName"},
+  { "minimum", 1610653699, NULL },
+  { NULL, 1073741833, "0"},
+  { NULL, 4104, "0"},
+  { "maximum", 536895491, NULL },
+  { NULL, 4104, "1"},
+  { "TlsFeatures", 536870923, NULL },
+  { NULL, 3, NULL },
+  { NULL, 0, NULL }
+};

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

#32 lore raw

PATCH 9/21 appended signatures: parse PKCS#7 signedData and X.509 certificates

In reply to Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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.

---
 grub-core/commands/appendedsig/appendedsig.h | 110 +++
 grub-core/commands/appendedsig/asn1util.c    |  99 ++
 grub-core/commands/appendedsig/pkcs7.c       | 473 +++++++++
 grub-core/commands/appendedsig/x509.c        | 981 +++++++++++++++++++
 4 files changed, 1663 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 +110 -0
new file mode 100644
index 000000000..fa59302c8
@@ -0,0 +1,110 @@
+/*
+ *  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 +99 -0

99 lines not on this page · raw message

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

473 lines not on this page · raw message

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

981 lines not on this page · raw message

Signature · 7 lines
2.43.5


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

Re: [PATCH v1 09/21] appended signatures: parse PKCS#7 signedData and X.509 certificates

Quoted 133 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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.

---
  grub-core/commands/appendedsig/appendedsig.h | 110 +++
  grub-core/commands/appendedsig/asn1util.c    |  99 ++
  grub-core/commands/appendedsig/pkcs7.c       | 473 +++++++++
  grub-core/commands/appendedsig/x509.c        | 981 +++++++++++++++++++
  4 files changed, 1663 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 +94 -0
new file mode 100644
index 000000000..fa59302c8
@@ -0,0 +1,110 @@
+/*
+ *  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

grub-core/commands/appendedsig/appendedsig.h line 104

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.h new file +10 -0
+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

NUL byte.

Quoted 241 lines
grub-core/commands/appendedsig/appendedsig.h new file +6 -0
+ *  - 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 +99 -0
new file mode 100644
index 000000000..609d0ecf2
@@ -0,0 +1,99 @@
+/*
+ *  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 +124 -0
new file mode 100644
index 000000000..61e560854
@@ -0,0 +1,473 @@
+/*
+ *  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)

grub-core/commands/appendedsig/pkcs7.c line 134

Quoted 10 lines
grub-core/commands/appendedsig/pkcs7.c new file +10 -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");

s/are/is - it's the maximum that 'is' supported

Quoted 28 lines
grub-core/commands/appendedsig/pkcs7.c new file +28 -0
+      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)

grub-core/commands/appendedsig/pkcs7.c line 172

Quoted 10 lines
grub-core/commands/appendedsig/pkcs7.c new file +10 -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");

Move "list" to line above

Quoted 5 lines
grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+              grub_free (da_path);
+              goto cleanup_signed_part;
+            }
+        }
+      else if (grub_strncmp (sha256_oid, algo_oid, algo_oid_size) == 0)

grub-core/commands/appendedsig/pkcs7.c line 187

Quoted 10 lines
grub-core/commands/appendedsig/pkcs7.c new file +10 -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");

Same here

Quoted 75 lines
grub-core/commands/appendedsig/pkcs7.c new file +75 -0
+              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-core/commands/appendedsig/pkcs7.c line 272

Quoted 10 lines
grub-core/commands/appendedsig/pkcs7.c new file +10 -0
+        }
+
+      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);

Merge into one string.

grub-core/commands/appendedsig/pkcs7.c line 279

Quoted 7 lines
grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+              goto cleanup_signerInfos;
+            }
+          else
+            {
+              sha512_in_si = true;
+              msg->signerInfos[i].hash =
+                      grub_crypto_lookup_md_by_name ("sha512");

Not sure what the char-per-line limit is, but I have seen 87 chars, so probably can move this one up.

grub-core/commands/appendedsig/pkcs7.c line 287

Quoted 8 lines
grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+            }
+        }
+      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);

Merge the string?

grub-core/commands/appendedsig/pkcs7.c line 294

Quoted 7 lines
grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+              goto cleanup_signerInfos;
+            }
+          else
+            {
+              sha256_in_si = true;
+              msg->signerInfos[i].hash =
+                      grub_crypto_lookup_md_by_name ("sha256");

also this one up

Quoted 504 lines
grub-core/commands/appendedsig/pkcs7.c new file +179 -0
+            }
+        }
+      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 +319 -0
new file mode 100644
index 000000000..eb9a1ca0f
@@ -0,0 +1,981 @@
+/*
+ *  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,

grub-core/commands/appendedsig/x509.c line 329

Quoted 10 lines
grub-core/commands/appendedsig/x509.c new file +10 -0
+                        "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);

*string = NULL;

Quoted 111 lines
grub-core/commands/appendedsig/x509.c new file +111 -0
+      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-core/commands/appendedsig/x509.c line 450

Quoted 10 lines
grub-core/commands/appendedsig/x509.c new file +10 -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;

goto cleanup_type;

Quoted 259 lines
grub-core/commands/appendedsig/x509.c new file +259 -0
+            }
+
+          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));
+    }
+

grub-core/commands/appendedsig/x509.c line 719

Quoted 10 lines
grub-core/commands/appendedsig/x509.c new file +10 -0
+  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);

if (!oid_path) ...
err = ...
return err;

grub-core/commands/appendedsig/x509.c line 730

Quoted 11 lines
grub-core/commands/appendedsig/x509.c new file +11 -0
+
+      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);

if (!critical_path) ...
err =
goto cleanup_oid_path

Quoted 4 lines
grub-core/commands/appendedsig/x509.c new file +4 -0
+      critical_size = sizeof (critical);
+      result = asn1_read_value (cert, critical_path, critical, &critical_size);
+      if (result == ASN1_ELEMENT_NOT_FOUND)
+        {

grub-core/commands/appendedsig/x509.c line 744

Quoted 10 lines
grub-core/commands/appendedsig/x509.c new file +10 -0
+          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);

if (!value_path) ...
err = ...
goto cleanup_critical_path

Quoted 227 lines
grub-core/commands/appendedsig/x509.c new file +227 -0
+      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.

grub-core/commands/appendedsig/x509.c line 981

Quoted 10 lines
grub-core/commands/appendedsig/x509.c new file +10 -0
+ * 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]);
+}

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

author
#34 lore raw

Re: [PATCH v1 09/21] appended signatures: parse PKCS#7 signedData and X.509 certificates

Quoted 1,964 lines · Stefan Berger
Quoted 154 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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.

---
  grub-core/commands/appendedsig/appendedsig.h | 110 +++
  grub-core/commands/appendedsig/asn1util.c    |  99 ++
  grub-core/commands/appendedsig/pkcs7.c       | 473 +++++++++
  grub-core/commands/appendedsig/x509.c        | 981 
+++++++++++++++++++
  4 files changed, 1663 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 +7 -0
new file mode 100644
index 000000000..fa59302c8
@@ -0,0 +1,110 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +12 -0
+
+#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.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +8 -0
+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] */

grub-core/commands/appendedsig/appendedsig.h new file +15 -0
+  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.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +16 -0
+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);

grub-core/commands/appendedsig/appendedsig.h new file +4 -0
+
+/*
+ * 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.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +6 -0
+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-core/commands/appendedsig/appendedsig.h new file +2 -0
+grub_err_t
+parse_pkcs7_signedData (const void *sigbuf, grub_size_t data_size, 

struct pkcs7_signedData *msg);

grub-core/commands/appendedsig/appendedsig.h new file +11 -0
+
+/*
+ * 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:

Quoted 6 lines
+ *  - 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

NUL byte.

Quoted 274 lines

+ * - Bit strings because libtasn1 returns the length in bits, not bytes.
+ *
+ * If the function returns a non-NULL value, the caller must free it.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +2 -0
+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 +7 -0
new file mode 100644
index 000000000..609d0ecf2
@@ -0,0 +1,99 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/asn1util.c new file +20 -0
+
+#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.
+ */

grub-core/commands/appendedsig/asn1util.c new file +2 -0
+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 +10 -0
+{
+  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"),

grub-core/commands/appendedsig/asn1util.c new file +10 -0
+                     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-core/commands/appendedsig/asn1util.c new file +9 -0
+      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",

grub-core/commands/appendedsig/asn1util.c new file +22 -0
+                     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 +7 -0
new file mode 100644
index 000000000..61e560854
@@ -0,0 +1,473 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/pkcs7.c new file +22 -0
+
+#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)

grub-core/commands/appendedsig/pkcs7.c new file +21 -0
+{
+  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);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+  if (res != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for PKCS#7 

signed "

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+                         "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);

grub-core/commands/appendedsig/pkcs7.c new file +15 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error reading 

signedData version: %s",

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+      goto cleanup_signed_part;
+    }
+
+  /*
+   * digestAlgorithms DigestAlgorithmIdentifiers
+   *
+   * DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
+   * DigestAlgorithmIdentifer is an X.509 AlgorithmIdentifier 

(10.1.1)

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+   *
+   * 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.

grub-core/commands/appendedsig/pkcs7.c new file +2 -0
+   */
+  res = asn1_number_of_elements (signed_part, "digestAlgorithms", 

&algo_count);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error counting 

number of digest algorithms: %s",

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                        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");

grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+      goto cleanup_signed_part;
+    }
+
+  if (algo_count > 2)
+    {
+      err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+                        "A maximum of 2 digest algorithms are 
Quoted 1 line

supported");

s/are/is - it's the maximum that 'is' supported

Quoted 41 lines
grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+      if (!da_path)
+        {
+          err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                            "Could not allocate path for digest 

algorithm "

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                            "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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+      if (res != ASN1_SUCCESS)
+        {
+          err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error reading 

digest algorithm: %s",

grub-core/commands/appendedsig/pkcs7.c new file +15 -0
+                            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 
Quoted 2 lines

algorithm "
+ "list");

Move "list" to line above

Quoted 15 lines
grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+              grub_free (da_path);
+              goto cleanup_signed_part;
+            }
+        }
+      else if (grub_strncmp (sha256_oid, algo_oid, algo_oid_size) == 

0)

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+        {
+          if (!sha256_in_da)
+            {
+              sha256_in_da = true;
+            }
+          else
+            {
+              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                "SHA-256 specified twice in digest 
Quoted 2 lines

algorithm "
+ "list");

Same here

Quoted 96 lines
grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+              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",

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+                            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 

*/

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+
+  /*
+   * We ignore the certificates, but we don't permit CRLs.
+   * A CRL entry might be revoking the certificate we're using, and 

we have

grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+   * 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");

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+      goto cleanup_signed_part;
+    }
+
+  /* read the signatures */
+
+  res = asn1_number_of_elements (signed_part, "signerInfos", 

&signer_count);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error counting 

number of signers: %s",

grub-core/commands/appendedsig/pkcs7.c new file +12 -0
+                        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));

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+  if (!msg->signerInfos)
+    {
+      err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                        "Could not allocate space for %d signers", 

signer_count);

grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+      if (!si_da_path)
+        {
+          err = grub_error (GRUB_ERR_OUT_OF_MEMORY, "Could not 

allocate path for signer %d's digest algorithm parsing path",

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                            i);
+          goto cleanup_signerInfos;
+        }
+
+      algo_oid_size = sizeof (algo_oid);
+      res = asn1_read_value (signed_part, si_da_path, algo_oid, 

&algo_oid_size);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+      if (res != ASN1_SUCCESS)
+        {
+          err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                            "Error reading signer %d's digest 

algorithm: %s", i,

grub-core/commands/appendedsig/pkcs7.c new file +12 -0
+                            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 
Quoted 3 lines

claims a SHA-512 signature "
+ "which was not specified in the outer
DigestAlgorithms", i);

Merge into one string.

grub-core/commands/appendedsig/pkcs7.c line 279

Quoted 7 lines
grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+              goto cleanup_signerInfos;
+            }
+          else
+            {
+              sha512_in_si = true;
+              msg->signerInfos[i].hash =
+                      grub_crypto_lookup_md_by_name ("sha512");

Not sure what the char-per-line limit is, but I have seen 87 chars, so probably can move this one up.

Quoted 11 lines
grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+            }
+        }
+      else if (grub_strncmp (sha256_oid, algo_oid, algo_oid_size) == 

0)

grub-core/commands/appendedsig/pkcs7.c new file +4 -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);

Merge the string?

grub-core/commands/appendedsig/pkcs7.c line 294

Quoted 7 lines
grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+              goto cleanup_signerInfos;
+            }
+          else
+            {
+              sha256_in_si = true;
+              msg->signerInfos[i].hash =
+                      grub_crypto_lookup_md_by_name ("sha256");

also this one up

Quoted 580 lines
grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+            }
+        }
+      else
+        {
+          err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+                            "Only SHA-256 and SHA-512 hashes are 

supported, found OID %s",

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                            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);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+          goto cleanup_signerInfos;
+        }
+
+      si_sig_path = grub_xasprintf ("signerInfos.?%d.signature", i + 

1);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+      if (!si_sig_path)
+        {
+          err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                            "Could not allocate path for signer %d's 

signature parsing path", i);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+          goto cleanup_signerInfos;
+        }
+
+      result_buf = grub_asn1_allocate_and_read (signed_part, 

si_sig_path,
+ "signature data",
&result_size);

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+      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,

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                                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",

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                            i, gcry_err);
+          goto cleanup_signerInfos;
+        }
+
+      /*
+       * use msg->signerInfo_count to track fully populated 

signerInfos so we

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+       * 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

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+   * 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 "

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                        "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 "

grub-core/commands/appendedsig/pkcs7.c new file +18 -0
+                        "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)

grub-core/commands/appendedsig/pkcs7.c new file +12 -0
+{
+  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");

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  size = (int) data_size;
+
+  res = asn1_create_element (_gnutls_pkix_asn, 

"PKIX1.pkcs-7-ContentInfo", &content_info);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+  if (res != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for PKCS#7 

data: %s",

grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+                         asn1_strerror (res));
+    }
+
+  res = asn1_der_decoding2 (&content_info, sigbuf, &size,
+                            ASN1_DECODE_FLAG_STRICT_DER | 

ASN1_DECODE_FLAG_ALLOW_PADDING,

grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+                            asn1_error);
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                        "Error decoding PKCS#7 message DER: %s", 

asn1_error);

grub-core/commands/appendedsig/pkcs7.c new file +11 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error reading PKCS#7 

content type: %s",

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                        asn1_strerror (res));
+      goto cleanup;
+    }
+
+  /* OID for SignedData defined in 5.1 */
+  if (grub_strncmp (signedData_oid, content_oid, content_oid_size) != 

0)

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                        "Unexpected content type in PKCS#7 message: 

OID %s", content_oid);

grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+      goto cleanup;
+    }
+
+  content = grub_asn1_allocate_and_read (content_info, "content",
+                                         "PKCS#7 message content", 

&content_size);

grub-core/commands/appendedsig/pkcs7.c new file +29 -0
+  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 +7 -0
new file mode 100644
index 000000000..eb9a1ca0f
@@ -0,0 +1,981 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/x509.c new file +45 -0
+
+#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.
+ */

grub-core/commands/appendedsig/x509.c new file +2 -0
+static grub_err_t
+grub_parse_rsa_pubkey (grub_uint8_t *der, int dersize, struct 

x509_certificate *certificate)

grub-core/commands/appendedsig/x509.c new file +9 -0
+{
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Cannot create storage for public key ASN.1 

data");

grub-core/commands/appendedsig/x509.c new file +3 -0
+    }
+
+  result = asn1_der_decoding2 (&spk, der, &dersize, 

ASN1_DECODE_FLAG_STRICT_DER, asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Cannot decode certificate public key DER: 

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+      goto cleanup;
+    }
+
+  m_data = grub_asn1_allocate_and_read (spk, "modulus", "RSA 

modulus", &m_size);

grub-core/commands/appendedsig/x509.c new file +8 -0
+  if (!m_data)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+
+  e_data = grub_asn1_allocate_and_read (spk, "publicExponent",
+                                        "RSA public exponent", 

&e_size);

grub-core/commands/appendedsig/x509.c new file +13 -0
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+      goto cleanup_e_data;
+    }
+
+  gcry_err = gcry_mpi_scan (&certificate->mpis[1], GCRYMPI_FMT_USG, 

e_data, e_size, NULL);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  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);

grub-core/commands/appendedsig/x509.c new file +26 -0
+      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.
+ */

grub-core/commands/appendedsig/x509.c new file +3 -0
+
+static grub_err_t
+grub_x509_read_subject_public_key (asn1_node asn, struct 

x509_certificate *results)

grub-core/commands/appendedsig/x509.c new file +8 -0
+{
+  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";

grub-core/commands/appendedsig/x509.c new file +13 -0
+  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",

grub-core/commands/appendedsig/x509.c new file +4 -0
+                         asn1_strerror (result));
+    }
+
+  if (grub_strncmp (algo_oid, rsaEncryption_oid, sizeof 

(rsaEncryption_oid)) != 0)

grub-core/commands/appendedsig/x509.c new file +3 -0
+    {
+      return grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+                         "Unsupported x509 public key algorithm: %s", 

algo_oid);

grub-core/commands/appendedsig/x509.c new file +5 -0
+    }
+
+  /*
+   * 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

grub-core/commands/appendedsig/x509.c new file +3 -0
+   * have ASN.1 type NULL for this algorithm identifier.
+   */
+  result = asn1_read_value (asn, params_name, params_value, 

&params_size);

grub-core/commands/appendedsig/x509.c new file +3 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading x509 

public key parameters: %s",

grub-core/commands/appendedsig/x509.c new file +7 -0
+                         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");

grub-core/commands/appendedsig/x509.c new file +4 -0
+    }
+
+  /*
+   * RFC 3279 2.3.1:  The DER encoded RSAPublicKey is the value of 

the BIT

grub-core/commands/appendedsig/x509.c new file +3 -0
+   * STRING subjectPublicKey.
+   */
+  result = asn1_read_value_type (asn, pk_name, NULL, &key_size, 

&key_type);

grub-core/commands/appendedsig/x509.c new file +3 -0
+  if (result != ASN1_MEM_ERROR)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading size 

of x509 public key: %s",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         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",

grub-core/commands/appendedsig/x509.c new file +31 -0
+                         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)

grub-core/commands/appendedsig/x509.c new file +9 -0
+{
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for 

certificate: %s",

grub-core/commands/appendedsig/x509.c new file +4 -0
+                         asn1_strerror (result));
+    }
+
+  result = asn1_der_decoding2 (&strasn, der, &der_size, 

ASN1_DECODE_FLAG_STRICT_DER, asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Could not parse DER for DirectoryString: 

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+      goto cleanup;
+    }
+
+  choice = grub_asn1_allocate_and_read (strasn, "", "DirectoryString 

choice", &choice_size);

grub-core/commands/appendedsig/x509.c new file +9 -0
+  if (!choice)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+
+  if (grub_strncmp ("utf8String", choice, choice_size) == 0)
+    {
+      result = asn1_read_value (strasn, "utf8String", NULL, 

&tmp_size);

grub-core/commands/appendedsig/x509.c new file +3 -0
+      if (result != ASN1_MEM_ERROR)
+        {
+          err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading 

size of UTF-8 string: %s",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                            asn1_strerror (result));
+          goto cleanup_choice;
+        }
+    }
+  else if (grub_strncmp ("printableString", choice, choice_size) == 

0)

grub-core/commands/appendedsig/x509.c new file +2 -0
+    {
+      result = asn1_read_value (strasn, "printableString", NULL, 

&tmp_size);

grub-core/commands/appendedsig/x509.c new file +3 -0
+      if (result != ASN1_MEM_ERROR)
+        {
+          err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading 

size of UTF-8 string: %s",

grub-core/commands/appendedsig/x509.c new file +7 -0
+                            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",

grub-core/commands/appendedsig/x509.c new file +12 -0
+                        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");

grub-core/commands/appendedsig/x509.c new file +7 -0
+      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",

grub-core/commands/appendedsig/x509.c line 329

Quoted 2 lines
grub-core/commands/appendedsig/x509.c new file +2 -0
+                        choice, asn1_strerror (result));
+      grub_free (*string);

*string = NULL;

Quoted 131 lines
grub-core/commands/appendedsig/x509.c new file +36 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +12 -0
+                       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)

grub-core/commands/appendedsig/x509.c new file +17 -0
+{
+  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);

grub-core/commands/appendedsig/x509.c new file +5 -0
+
+  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",

grub-core/commands/appendedsig/x509.c new file +10 -0
+                        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",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                            name_path);
+          goto cleanup_set;
+        }
+      /* this brings us, hopefully, to a set */
+      result = asn1_number_of_elements (asn, set_path, 

&set_components);

grub-core/commands/appendedsig/x509.c new file +3 -0
+      if (result != ASN1_SUCCESS)
+        {
+          err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error counting 

name sub-components components (element %d): %s",

grub-core/commands/appendedsig/x509.c new file +6 -0
+                            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);

grub-core/commands/appendedsig/x509.c new file +3 -0
+          if (!type_path)
+            {
+              err = grub_error (GRUB_ERR_OUT_OF_MEMORY, "Could not 

allocate memory for %s name component type path",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                                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",

grub-core/commands/appendedsig/x509.c new file +11 -0
+                                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);

grub-core/commands/appendedsig/x509.c new file +3 -0
+          if (!val_path)
+            {
+              err = grub_error (GRUB_ERR_OUT_OF_MEMORY, "Could not 

allocate memory for %s name component value path",

grub-core/commands/appendedsig/x509.c

Quoted 2 lines
grub-core/commands/appendedsig/x509.c new file +2 -0
+                                name_path);
+              goto cleanup_set;

goto cleanup_type;

Quoted 299 lines
grub-core/commands/appendedsig/x509.c new file +3 -0
+            }
+
+          string_der = grub_asn1_allocate_and_read (asn, val_path, 

name_path, &string_size);

grub-core/commands/appendedsig/x509.c new file +7 -0
+          if (!string_der)
+            {
+              err = grub_errno;
+              goto cleanup_val_path;
+            }
+
+          err = decode_string (string_der, string_size, name, 

name_size);

grub-core/commands/appendedsig/x509.c new file +45 -0
+          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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for key 

usage");

grub-core/commands/appendedsig/x509.c new file +4 -0
+    }
+
+  result = asn1_der_decoding2 (&usageasn, value, &value_size,
+                               ASN1_DECODE_FLAG_STRICT_DER, 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Error parsing DER for Key Usage: %s", 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +7 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/x509.c new file +23 -0
+      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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for Basic 

"

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         "Constraints");
+    }
+
+  result = asn1_der_decoding2 (&basicasn, value, &value_size,
+                               ASN1_DECODE_FLAG_STRICT_DER, 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Error parsing DER for Basic Constraints: 

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +13 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/x509.c new file +23 -0
+      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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for 

Extended Key "

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         "Usage");
+    }
+
+  result = asn1_der_decoding2 (&extendedasn, value, &value_size,
+                               ASN1_DECODE_FLAG_STRICT_DER, 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Error parsing DER for Extended Key Usage: 

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +5 -0
+      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

grub-core/commands/appendedsig/x509.c new file +6 -0
+   * 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",

grub-core/commands/appendedsig/x509.c new file +7 -0
+                        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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/x509.c new file +24 -0
+      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)
+ */

grub-core/commands/appendedsig/x509.c new file +6 -0
+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;

grub-core/commands/appendedsig/x509.c new file +10 -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);

grub-core/commands/appendedsig/x509.c new file +3 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error counting 

number of extensions: %s",

grub-core/commands/appendedsig/x509.c new file +6 -0
+                         asn1_strerror (result));
+    }
+
+  if (num_extensions < 2)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Insufficient number 

of extensions for "

grub-core/commands/appendedsig/x509.c new file +7 -0
+                         "certificate, need at least 2, got %d",
+                         num_extensions);
+    }
+
+  for (ext = 1; ext <= num_extensions; ext++)
+    {
+      oid_path = grub_xasprintf 
Quoted 1 line

("tbsCertificate.extensions.?%d.extnID", ext);

if (!oid_path) ...
err = ...
return err;

Quoted 13 lines
grub-core/commands/appendedsig/x509.c new file +3 -0
+
+      extnID_size = sizeof (extnID);
+      result = asn1_read_value (cert, oid_path, extnID, 

&extnID_size);

grub-core/commands/appendedsig/x509.c new file +3 -0
+      if (result != ASN1_SUCCESS)
+        {
+          err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading 

extension OID: %s",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                            asn1_strerror (result));
+          goto cleanup_oid_path;
+        }
+
+      critical_path = grub_xasprintf 
Quoted 1 line

("tbsCertificate.extensions.?%d.critical", ext);

if (!critical_path) ...
err =
goto cleanup_oid_path

Quoted 16 lines
grub-core/commands/appendedsig/x509.c new file +2 -0
+      critical_size = sizeof (critical);
+      result = asn1_read_value (cert, critical_path, critical, 

&critical_size);

grub-core/commands/appendedsig/x509.c new file +7 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                            asn1_strerror (result));
+          goto cleanup_critical_path;
+        }
+
+      value_path = grub_xasprintf 
Quoted 1 line

("tbsCertificate.extensions.?%d.extnValue", ext);

if (!value_path) ...
err = ...
goto cleanup_critical_path

Quoted 251 lines
grub-core/commands/appendedsig/x509.c new file +2 -0
+      value = grub_asn1_allocate_and_read (cert, value_path,
+                                           "certificate extension 

value", &value_size);

grub-core/commands/appendedsig/x509.c new file +20 -0
+      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)

grub-core/commands/appendedsig/x509.c new file +9 -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)

grub-core/commands/appendedsig/x509.c new file +16 -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);

grub-core/commands/appendedsig/x509.c new file +12 -0
+          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 "

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         "- 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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+    }
+  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);

grub-core/commands/appendedsig/x509.c new file +16 -0
+    }
+  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-core/commands/appendedsig/x509.c new file +2 -0
+grub_err_t
+parse_x509_certificate (const void *data, grub_size_t data_size, 

struct x509_certificate *results)

grub-core/commands/appendedsig/x509.c new file +10 -0
+{
+  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");

grub-core/commands/appendedsig/x509.c new file +3 -0
+  size = (int) data_size;
+
+  result = asn1_create_element (_gnutls_pkix_asn, 

"PKIX1.Certificate", &cert);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for 

certificate: %s",

grub-core/commands/appendedsig/x509.c new file +4 -0
+                         asn1_strerror (result));
+    }
+
+  result = asn1_der_decoding2 (&cert, data, &size, 

ASN1_DECODE_FLAG_STRICT_DER, asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Could not parse DER for certificate: %s", 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +19 -0
+      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);

grub-core/commands/appendedsig/x509.c new file +34 -0
+  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

grub-core/commands/appendedsig/x509.c new file +9 -0
+   * 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);

grub-core/commands/appendedsig/x509.c new file +49 -0
+  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.
+ */

Quoted 8 lines

grub-core/commands/appendedsig/x509.c line 981

Quoted 8 lines
grub-core/commands/appendedsig/x509.c new file +8 -0
+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]);
+}

Thank you Stefan. fixed it.

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

Reviewed-by on v1 9/21
#35 lore raw

Re: [PATCH v1 09/21] appended signatures: parse PKCS#7 signedData and X.509 certificates

In reply to Sudhakar Kuppusamy

Suggestion : It will be good if we can remove the brackets in one liner if conditions and loops!

Quoted 1,908 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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.

---
 grub-core/commands/appendedsig/appendedsig.h | 110 +++
 grub-core/commands/appendedsig/asn1util.c    |  99 ++
 grub-core/commands/appendedsig/pkcs7.c       | 473 +++++++++
 grub-core/commands/appendedsig/x509.c        | 981 +++++++++++++++++++
 4 files changed, 1663 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 +7 -0
new file mode 100644
index 000000000..fa59302c8
@@ -0,0 +1,110 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +12 -0
+
+#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.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +8 -0
+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] */

grub-core/commands/appendedsig/appendedsig.h new file +15 -0
+  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.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +16 -0
+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);

grub-core/commands/appendedsig/appendedsig.h new file +4 -0
+
+/*
+ * 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.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +6 -0
+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-core/commands/appendedsig/appendedsig.h new file +2 -0
+grub_err_t
+parse_pkcs7_signedData (const void *sigbuf, grub_size_t data_size,

struct pkcs7_signedData *msg);

grub-core/commands/appendedsig/appendedsig.h new file +15 -0
+
+/*
+ * 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.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +2 -0
+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 +7 -0
new file mode 100644
index 000000000..609d0ecf2
@@ -0,0 +1,99 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/asn1util.c new file +24 -0
+
+#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.
+ */

grub-core/commands/appendedsig/asn1util.c new file +2 -0
+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 +10 -0
+{
+  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"),

grub-core/commands/appendedsig/asn1util.c new file +10 -0
+                     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-core/commands/appendedsig/asn1util.c new file +9 -0
+      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",

grub-core/commands/appendedsig/asn1util.c new file +22 -0
+                     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 +7 -0
new file mode 100644
index 000000000..61e560854
@@ -0,0 +1,473 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/pkcs7.c new file +22 -0
+
+#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)

grub-core/commands/appendedsig/pkcs7.c new file +21 -0
+{
+  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);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+  if (res != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for PKCS#7 

signed "

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+                         "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);

grub-core/commands/appendedsig/pkcs7.c new file +15 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error reading

signedData version: %s",

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/pkcs7.c new file +14 -0
+      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.

grub-core/commands/appendedsig/pkcs7.c new file +2 -0
+   */
+  res = asn1_number_of_elements (signed_part, "digestAlgorithms", 

&algo_count);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error counting

number of digest algorithms: %s",

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                        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");

grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+      goto cleanup_signed_part;
+    }
+
+  if (algo_count > 2)
+    {
+      err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+                        "A maximum of 2 digest algorithms are 

supported");

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+      if (!da_path)
+        {
+          err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                            "Could not allocate path for digest 

algorithm "

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                            "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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+      if (res != ASN1_SUCCESS)
+        {
+          err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error reading

digest algorithm: %s",

grub-core/commands/appendedsig/pkcs7.c new file +15 -0
+                            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 "

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                                "list");
+              grub_free (da_path);
+              goto cleanup_signed_part;
+            }
+        }
+      else if (grub_strncmp (sha256_oid, algo_oid, algo_oid_size) == 

0)

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+        {
+          if (!sha256_in_da)
+            {
+              sha256_in_da = true;
+            }
+          else
+            {
+              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                "SHA-256 specified twice in digest 

algorithm "

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                                "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",

grub-core/commands/appendedsig/pkcs7.c new file +13 -0
+                            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

grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+   * 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");

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+      goto cleanup_signed_part;
+    }
+
+  /* read the signatures */
+
+  res = asn1_number_of_elements (signed_part, "signerInfos", 

&signer_count);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error counting

number of signers: %s",

grub-core/commands/appendedsig/pkcs7.c new file +12 -0
+                        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));

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+  if (!msg->signerInfos)
+    {
+      err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                        "Could not allocate space for %d signers",

signer_count);

grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+      if (!si_da_path)
+        {
+          err = grub_error (GRUB_ERR_OUT_OF_MEMORY, "Could not

allocate path for signer %d's digest algorithm parsing path",

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                            i);
+          goto cleanup_signerInfos;
+        }
+
+      algo_oid_size = sizeof (algo_oid);
+      res = asn1_read_value (signed_part, si_da_path, algo_oid,

&algo_oid_size);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+      if (res != ASN1_SUCCESS)
+        {
+          err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                            "Error reading signer %d's digest

algorithm: %s", i,

grub-core/commands/appendedsig/pkcs7.c new file +12 -0
+                            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);

grub-core/commands/appendedsig/pkcs7.c new file +10 -0
+              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)

grub-core/commands/appendedsig/pkcs7.c new file +4 -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);

grub-core/commands/appendedsig/pkcs7.c new file +13 -0
+              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",

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                            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);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+          goto cleanup_signerInfos;
+        }
+
+      si_sig_path = grub_xasprintf ("signerInfos.?%d.signature", i + 

1);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+      if (!si_sig_path)
+        {
+          err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                            "Could not allocate path for signer %d's

signature parsing path", i);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+          goto cleanup_signerInfos;
+        }
+
+      result_buf = grub_asn1_allocate_and_read (signed_part, 

si_sig_path,
+ "signature data",
&result_size);

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+      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,

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                                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",

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                            i, gcry_err);
+          goto cleanup_signerInfos;
+        }
+
+      /*
+       * use msg->signerInfo_count to track fully populated 

signerInfos so we

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+       * 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

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+   * 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 "

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                        "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 "

grub-core/commands/appendedsig/pkcs7.c new file +18 -0
+                        "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)

grub-core/commands/appendedsig/pkcs7.c new file +12 -0
+{
+  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");

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  size = (int) data_size;
+
+  res = asn1_create_element (_gnutls_pkix_asn,

"PKIX1.pkcs-7-ContentInfo", &content_info);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+  if (res != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for PKCS#7

data: %s",

grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+                         asn1_strerror (res));
+    }
+
+  res = asn1_der_decoding2 (&content_info, sigbuf, &size,
+                            ASN1_DECODE_FLAG_STRICT_DER |

ASN1_DECODE_FLAG_ALLOW_PADDING,

grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+                            asn1_error);
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                        "Error decoding PKCS#7 message DER: %s", 

asn1_error);

grub-core/commands/appendedsig/pkcs7.c new file +11 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error reading PKCS#7

content type: %s",

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                        asn1_strerror (res));
+      goto cleanup;
+    }
+
+  /* OID for SignedData defined in 5.1 */
+  if (grub_strncmp (signedData_oid, content_oid, content_oid_size) != 

0)

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                        "Unexpected content type in PKCS#7 message:

OID %s", content_oid);

grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+      goto cleanup;
+    }
+
+  content = grub_asn1_allocate_and_read (content_info, "content",
+                                         "PKCS#7 message content",

&content_size);

grub-core/commands/appendedsig/pkcs7.c new file +29 -0
+  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 +7 -0
new file mode 100644
index 000000000..eb9a1ca0f
@@ -0,0 +1,981 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/x509.c new file +45 -0
+
+#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.
+ */

grub-core/commands/appendedsig/x509.c new file +2 -0
+static grub_err_t
+grub_parse_rsa_pubkey (grub_uint8_t *der, int dersize, struct

x509_certificate *certificate)

grub-core/commands/appendedsig/x509.c new file +9 -0
+{
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Cannot create storage for public key ASN.1 

data");

grub-core/commands/appendedsig/x509.c new file +3 -0
+    }
+
+  result = asn1_der_decoding2 (&spk, der, &dersize,

ASN1_DECODE_FLAG_STRICT_DER, asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Cannot decode certificate public key DER:

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+      goto cleanup;
+    }
+
+  m_data = grub_asn1_allocate_and_read (spk, "modulus", "RSA

modulus", &m_size);

grub-core/commands/appendedsig/x509.c new file +8 -0
+  if (!m_data)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+
+  e_data = grub_asn1_allocate_and_read (spk, "publicExponent",
+                                        "RSA public exponent", 

&e_size);

grub-core/commands/appendedsig/x509.c new file +13 -0
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+      goto cleanup_e_data;
+    }
+
+  gcry_err = gcry_mpi_scan (&certificate->mpis[1], GCRYMPI_FMT_USG,

e_data, e_size, NULL);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  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);

grub-core/commands/appendedsig/x509.c new file +26 -0
+      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.
+ */

grub-core/commands/appendedsig/x509.c new file +3 -0
+
+static grub_err_t
+grub_x509_read_subject_public_key (asn1_node asn, struct

x509_certificate *results)

grub-core/commands/appendedsig/x509.c new file +8 -0
+{
+  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";

grub-core/commands/appendedsig/x509.c new file +13 -0
+  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",

grub-core/commands/appendedsig/x509.c new file +4 -0
+                         asn1_strerror (result));
+    }
+
+  if (grub_strncmp (algo_oid, rsaEncryption_oid, sizeof

(rsaEncryption_oid)) != 0)

grub-core/commands/appendedsig/x509.c new file +3 -0
+    {
+      return grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+                         "Unsupported x509 public key algorithm: %s",

algo_oid);

grub-core/commands/appendedsig/x509.c new file +5 -0
+    }
+
+  /*
+   * 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

grub-core/commands/appendedsig/x509.c new file +3 -0
+   * have ASN.1 type NULL for this algorithm identifier.
+   */
+  result = asn1_read_value (asn, params_name, params_value, 

&params_size);

grub-core/commands/appendedsig/x509.c new file +3 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading x509

public key parameters: %s",

grub-core/commands/appendedsig/x509.c new file +7 -0
+                         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");

grub-core/commands/appendedsig/x509.c new file +4 -0
+    }
+
+  /*
+   * RFC 3279 2.3.1:  The DER encoded RSAPublicKey is the value of the 

BIT

grub-core/commands/appendedsig/x509.c new file +3 -0
+   * STRING subjectPublicKey.
+   */
+  result = asn1_read_value_type (asn, pk_name, NULL, &key_size, 

&key_type);

grub-core/commands/appendedsig/x509.c new file +3 -0
+  if (result != ASN1_MEM_ERROR)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading size

of x509 public key: %s",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         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",

grub-core/commands/appendedsig/x509.c new file +31 -0
+                         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)

grub-core/commands/appendedsig/x509.c new file +9 -0
+{
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for

certificate: %s",

grub-core/commands/appendedsig/x509.c new file +4 -0
+                         asn1_strerror (result));
+    }
+
+  result = asn1_der_decoding2 (&strasn, der, &der_size,

ASN1_DECODE_FLAG_STRICT_DER, asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Could not parse DER for DirectoryString:

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+      goto cleanup;
+    }
+
+  choice = grub_asn1_allocate_and_read (strasn, "", "DirectoryString

choice", &choice_size);

grub-core/commands/appendedsig/x509.c new file +9 -0
+  if (!choice)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+
+  if (grub_strncmp ("utf8String", choice, choice_size) == 0)
+    {
+      result = asn1_read_value (strasn, "utf8String", NULL, 

&tmp_size);

grub-core/commands/appendedsig/x509.c new file +3 -0
+      if (result != ASN1_MEM_ERROR)
+        {
+          err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading

size of UTF-8 string: %s",

grub-core/commands/appendedsig/x509.c new file +7 -0
+                            asn1_strerror (result));
+          goto cleanup_choice;
+        }
+    }
+  else if (grub_strncmp ("printableString", choice, choice_size) == 0)
+    {
+      result = asn1_read_value (strasn, "printableString", NULL, 

&tmp_size);

grub-core/commands/appendedsig/x509.c new file +3 -0
+      if (result != ASN1_MEM_ERROR)
+        {
+          err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading

size of UTF-8 string: %s",

grub-core/commands/appendedsig/x509.c new file +7 -0
+                            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",

grub-core/commands/appendedsig/x509.c new file +12 -0
+                        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");

grub-core/commands/appendedsig/x509.c new file +7 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +38 -0
+                        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",

grub-core/commands/appendedsig/x509.c new file +12 -0
+                       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)

grub-core/commands/appendedsig/x509.c new file +17 -0
+{
+  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);

grub-core/commands/appendedsig/x509.c new file +5 -0
+
+  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",

grub-core/commands/appendedsig/x509.c new file +10 -0
+                        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",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                            name_path);
+          goto cleanup_set;
+        }
+      /* this brings us, hopefully, to a set */
+      result = asn1_number_of_elements (asn, set_path, 

&set_components);

grub-core/commands/appendedsig/x509.c new file +3 -0
+      if (result != ASN1_SUCCESS)
+        {
+          err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error counting

name sub-components components (element %d): %s",

grub-core/commands/appendedsig/x509.c new file +6 -0
+                            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);

grub-core/commands/appendedsig/x509.c new file +3 -0
+          if (!type_path)
+            {
+              err = grub_error (GRUB_ERR_OUT_OF_MEMORY, "Could not

allocate memory for %s name component type path",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                                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",

grub-core/commands/appendedsig/x509.c new file +11 -0
+                                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);

grub-core/commands/appendedsig/x509.c new file +3 -0
+          if (!val_path)
+            {
+              err = grub_error (GRUB_ERR_OUT_OF_MEMORY, "Could not

allocate memory for %s name component value path",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                                name_path);
+              goto cleanup_set;
+            }
+
+          string_der = grub_asn1_allocate_and_read (asn, val_path,

name_path, &string_size);

grub-core/commands/appendedsig/x509.c new file +7 -0
+          if (!string_der)
+            {
+              err = grub_errno;
+              goto cleanup_val_path;
+            }
+
+          err = decode_string (string_der, string_size, name, 

name_size);

grub-core/commands/appendedsig/x509.c new file +45 -0
+          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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for key 

usage");

grub-core/commands/appendedsig/x509.c new file +4 -0
+    }
+
+  result = asn1_der_decoding2 (&usageasn, value, &value_size,
+                               ASN1_DECODE_FLAG_STRICT_DER, 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Error parsing DER for Key Usage: %s", 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +7 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/x509.c new file +23 -0
+      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);

grub-core/commands/appendedsig/x509.c new file +9 -0
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Error parsing DER for Basic Constraints:

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +13 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/x509.c new file +23 -0
+      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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for 

Extended Key "

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         "Usage");
+    }
+
+  result = asn1_der_decoding2 (&extendedasn, value, &value_size,
+                               ASN1_DECODE_FLAG_STRICT_DER, 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Error parsing DER for Extended Key Usage:

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +5 -0
+      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

grub-core/commands/appendedsig/x509.c new file +6 -0
+   * 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",

grub-core/commands/appendedsig/x509.c new file +7 -0
+                        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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/x509.c new file +24 -0
+      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)
+ */

grub-core/commands/appendedsig/x509.c new file +6 -0
+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;

grub-core/commands/appendedsig/x509.c new file +10 -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);

grub-core/commands/appendedsig/x509.c new file +3 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error counting

number of extensions: %s",

grub-core/commands/appendedsig/x509.c new file +6 -0
+                         asn1_strerror (result));
+    }
+
+  if (num_extensions < 2)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Insufficient number

of extensions for "

grub-core/commands/appendedsig/x509.c new file +7 -0
+                         "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);

grub-core/commands/appendedsig/x509.c new file +6 -0
+
+      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",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                            asn1_strerror (result));
+          goto cleanup_oid_path;
+        }
+
+      critical_path = grub_xasprintf

("tbsCertificate.extensions.?%d.critical", ext);

grub-core/commands/appendedsig/x509.c new file +2 -0
+      critical_size = sizeof (critical);
+      result = asn1_read_value (cert, critical_path, critical, 

&critical_size);

grub-core/commands/appendedsig/x509.c new file +7 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                            asn1_strerror (result));
+          goto cleanup_critical_path;
+        }
+
+      value_path = grub_xasprintf

("tbsCertificate.extensions.?%d.extnValue", ext);

grub-core/commands/appendedsig/x509.c new file +2 -0
+      value = grub_asn1_allocate_and_read (cert, value_path,
+                                           "certificate extension

value", &value_size);

grub-core/commands/appendedsig/x509.c new file +20 -0
+      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)

grub-core/commands/appendedsig/x509.c new file +9 -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)

grub-core/commands/appendedsig/x509.c new file +16 -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);

grub-core/commands/appendedsig/x509.c new file +12 -0
+          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 "

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         "- expected 1, got %d", usage_present);
+    }
+  if (constraints_present != 1)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Unexpected number

of basic constraints extensions "

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         "- 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);

grub-core/commands/appendedsig/x509.c new file +16 -0
+    }
+  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-core/commands/appendedsig/x509.c new file +2 -0
+grub_err_t
+parse_x509_certificate (const void *data, grub_size_t data_size,

struct x509_certificate *results)

grub-core/commands/appendedsig/x509.c new file +10 -0
+{
+  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");

grub-core/commands/appendedsig/x509.c new file +3 -0
+  size = (int) data_size;
+
+  result = asn1_create_element (_gnutls_pkix_asn, "PKIX1.Certificate", 

&cert);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for

certificate: %s",

grub-core/commands/appendedsig/x509.c new file +4 -0
+                         asn1_strerror (result));
+    }
+
+  result = asn1_der_decoding2 (&cert, data, &size,

ASN1_DECODE_FLAG_STRICT_DER, asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Could not parse DER for certificate: %s", 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +19 -0
+      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);

grub-core/commands/appendedsig/x509.c new file +34 -0
+  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

grub-core/commands/appendedsig/x509.c new file +9 -0
+   * 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);

grub-core/commands/appendedsig/x509.c new file +49 -0
+  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.
+ */

grub-core/commands/appendedsig/x509.c line 981

Quoted 8 lines
grub-core/commands/appendedsig/x509.c new file +8 -0
+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]);
+}

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

author
#36 lore raw

Re: [PATCH v1 09/21] appended signatures: parse PKCS#7 signedData and X.509 certificates

Quoted 1,925 lines · Avnish Chouhan

Suggestion : It will be good if we can remove the brackets in one liner if conditions and loops!

Quoted 1,919 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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.

---
 grub-core/commands/appendedsig/appendedsig.h | 110 +++
 grub-core/commands/appendedsig/asn1util.c    |  99 ++
 grub-core/commands/appendedsig/pkcs7.c       | 473 +++++++++
 grub-core/commands/appendedsig/x509.c        | 981 
+++++++++++++++++++
 4 files changed, 1663 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 +7 -0
new file mode 100644
index 000000000..fa59302c8
@@ -0,0 +1,110 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +12 -0
+
+#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.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +8 -0
+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] */

grub-core/commands/appendedsig/appendedsig.h new file +15 -0
+  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.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +16 -0
+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);

grub-core/commands/appendedsig/appendedsig.h new file +4 -0
+
+/*
+ * 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.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +6 -0
+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-core/commands/appendedsig/appendedsig.h new file +2 -0
+grub_err_t
+parse_pkcs7_signedData (const void *sigbuf, grub_size_t data_size,

struct pkcs7_signedData *msg);

grub-core/commands/appendedsig/appendedsig.h new file +11 -0
+
+/*
+ * 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.
+ */

grub-core/commands/appendedsig/appendedsig.h new file +2 -0
+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 +7 -0
new file mode 100644
index 000000000..609d0ecf2
@@ -0,0 +1,99 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/asn1util.c new file +20 -0
+
+#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.
+ */

grub-core/commands/appendedsig/asn1util.c new file +2 -0
+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 +10 -0
+{
+  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"),

grub-core/commands/appendedsig/asn1util.c new file +10 -0
+                     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-core/commands/appendedsig/asn1util.c new file +9 -0
+      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",

grub-core/commands/appendedsig/asn1util.c new file +22 -0
+                     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 +7 -0
new file mode 100644
index 000000000..61e560854
@@ -0,0 +1,473 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/pkcs7.c new file +22 -0
+
+#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)

grub-core/commands/appendedsig/pkcs7.c new file +21 -0
+{
+  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);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+  if (res != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for PKCS#7 

signed "

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+                         "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);

grub-core/commands/appendedsig/pkcs7.c new file +15 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error reading

signedData version: %s",

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+      goto cleanup_signed_part;
+    }
+
+  /*
+   * digestAlgorithms DigestAlgorithmIdentifiers
+   *
+   * DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
+   * DigestAlgorithmIdentifer is an X.509 AlgorithmIdentifier 

(10.1.1)

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+   *
+   * 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.

grub-core/commands/appendedsig/pkcs7.c new file +2 -0
+   */
+  res = asn1_number_of_elements (signed_part, "digestAlgorithms", 

&algo_count);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error counting

number of digest algorithms: %s",

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                        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");

grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+      goto cleanup_signed_part;
+    }
+
+  if (algo_count > 2)
+    {
+      err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+                        "A maximum of 2 digest algorithms are 

supported");

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+      if (!da_path)
+        {
+          err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                            "Could not allocate path for digest 

algorithm "

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                            "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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+      if (res != ASN1_SUCCESS)
+        {
+          err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error reading

digest algorithm: %s",

grub-core/commands/appendedsig/pkcs7.c new file +15 -0
+                            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 "

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                                "list");
+              grub_free (da_path);
+              goto cleanup_signed_part;
+            }
+        }
+      else if (grub_strncmp (sha256_oid, algo_oid, algo_oid_size) == 

0)

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+        {
+          if (!sha256_in_da)
+            {
+              sha256_in_da = true;
+            }
+          else
+            {
+              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                "SHA-256 specified twice in digest 

algorithm "

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                                "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",

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+                            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 

*/

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+
+  /*
+   * We ignore the certificates, but we don't permit CRLs.
+   * A CRL entry might be revoking the certificate we're using, and 

we have

grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+   * 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");

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+      goto cleanup_signed_part;
+    }
+
+  /* read the signatures */
+
+  res = asn1_number_of_elements (signed_part, "signerInfos", 

&signer_count);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error counting

number of signers: %s",

grub-core/commands/appendedsig/pkcs7.c new file +12 -0
+                        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));

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+  if (!msg->signerInfos)
+    {
+      err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                        "Could not allocate space for %d signers",

signer_count);

grub-core/commands/appendedsig/pkcs7.c new file +7 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+      if (!si_da_path)
+        {
+          err = grub_error (GRUB_ERR_OUT_OF_MEMORY, "Could not

allocate path for signer %d's digest algorithm parsing path",

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                            i);
+          goto cleanup_signerInfos;
+        }
+
+      algo_oid_size = sizeof (algo_oid);
+      res = asn1_read_value (signed_part, si_da_path, algo_oid,

&algo_oid_size);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+      if (res != ASN1_SUCCESS)
+        {
+          err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                            "Error reading signer %d's digest

algorithm: %s", i,

grub-core/commands/appendedsig/pkcs7.c new file +12 -0
+                            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);

grub-core/commands/appendedsig/pkcs7.c new file +10 -0
+              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)

grub-core/commands/appendedsig/pkcs7.c new file +4 -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);

grub-core/commands/appendedsig/pkcs7.c new file +13 -0
+              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",

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                            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);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+          goto cleanup_signerInfos;
+        }
+
+      si_sig_path = grub_xasprintf ("signerInfos.?%d.signature", i + 

1);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+      if (!si_sig_path)
+        {
+          err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                            "Could not allocate path for signer %d's

signature parsing path", i);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+          goto cleanup_signerInfos;
+        }
+
+      result_buf = grub_asn1_allocate_and_read (signed_part, 

si_sig_path,
+ "signature data",
&result_size);

grub-core/commands/appendedsig/pkcs7.c new file +9 -0
+      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,

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                                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",

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                            i, gcry_err);
+          goto cleanup_signerInfos;
+        }
+
+      /*
+       * use msg->signerInfo_count to track fully populated 

signerInfos so we

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+       * 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

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+   * 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 "

grub-core/commands/appendedsig/pkcs7.c new file +8 -0
+                        "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 "

grub-core/commands/appendedsig/pkcs7.c new file +18 -0
+                        "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)

grub-core/commands/appendedsig/pkcs7.c new file +12 -0
+{
+  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");

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  size = (int) data_size;
+
+  res = asn1_create_element (_gnutls_pkix_asn,

"PKIX1.pkcs-7-ContentInfo", &content_info);

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+  if (res != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for PKCS#7

data: %s",

grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+                         asn1_strerror (res));
+    }
+
+  res = asn1_der_decoding2 (&content_info, sigbuf, &size,
+                            ASN1_DECODE_FLAG_STRICT_DER |

ASN1_DECODE_FLAG_ALLOW_PADDING,

grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+                            asn1_error);
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                        "Error decoding PKCS#7 message DER: %s", 

asn1_error);

grub-core/commands/appendedsig/pkcs7.c new file +11 -0
+      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);

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error reading PKCS#7

content type: %s",

grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+                        asn1_strerror (res));
+      goto cleanup;
+    }
+
+  /* OID for SignedData defined in 5.1 */
+  if (grub_strncmp (signedData_oid, content_oid, content_oid_size) != 

0)

grub-core/commands/appendedsig/pkcs7.c new file +3 -0
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                        "Unexpected content type in PKCS#7 message:

OID %s", content_oid);

grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+      goto cleanup;
+    }
+
+  content = grub_asn1_allocate_and_read (content_info, "content",
+                                         "PKCS#7 message content",

&content_size);

grub-core/commands/appendedsig/pkcs7.c new file +29 -0
+  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 +7 -0
new file mode 100644
index 000000000..eb9a1ca0f
@@ -0,0 +1,981 @@
+/*
+ *  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/>.
+ */

grub-core/commands/appendedsig/x509.c new file +45 -0
+
+#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.
+ */

grub-core/commands/appendedsig/x509.c new file +2 -0
+static grub_err_t
+grub_parse_rsa_pubkey (grub_uint8_t *der, int dersize, struct

x509_certificate *certificate)

grub-core/commands/appendedsig/x509.c new file +9 -0
+{
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Cannot create storage for public key ASN.1 

data");

grub-core/commands/appendedsig/x509.c new file +3 -0
+    }
+
+  result = asn1_der_decoding2 (&spk, der, &dersize,

ASN1_DECODE_FLAG_STRICT_DER, asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Cannot decode certificate public key DER:

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+      goto cleanup;
+    }
+
+  m_data = grub_asn1_allocate_and_read (spk, "modulus", "RSA

modulus", &m_size);

grub-core/commands/appendedsig/x509.c new file +8 -0
+  if (!m_data)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+
+  e_data = grub_asn1_allocate_and_read (spk, "publicExponent",
+                                        "RSA public exponent", 

&e_size);

grub-core/commands/appendedsig/x509.c new file +13 -0
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+      goto cleanup_e_data;
+    }
+
+  gcry_err = gcry_mpi_scan (&certificate->mpis[1], GCRYMPI_FMT_USG,

e_data, e_size, NULL);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  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);

grub-core/commands/appendedsig/x509.c new file +26 -0
+      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.
+ */

grub-core/commands/appendedsig/x509.c new file +3 -0
+
+static grub_err_t
+grub_x509_read_subject_public_key (asn1_node asn, struct

x509_certificate *results)

grub-core/commands/appendedsig/x509.c new file +8 -0
+{
+  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";

grub-core/commands/appendedsig/x509.c new file +13 -0
+  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",

grub-core/commands/appendedsig/x509.c new file +4 -0
+                         asn1_strerror (result));
+    }
+
+  if (grub_strncmp (algo_oid, rsaEncryption_oid, sizeof

(rsaEncryption_oid)) != 0)

grub-core/commands/appendedsig/x509.c new file +3 -0
+    {
+      return grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+                         "Unsupported x509 public key algorithm: %s",

algo_oid);

grub-core/commands/appendedsig/x509.c new file +5 -0
+    }
+
+  /*
+   * 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

grub-core/commands/appendedsig/x509.c new file +3 -0
+   * have ASN.1 type NULL for this algorithm identifier.
+   */
+  result = asn1_read_value (asn, params_name, params_value, 

&params_size);

grub-core/commands/appendedsig/x509.c new file +3 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading x509

public key parameters: %s",

grub-core/commands/appendedsig/x509.c new file +7 -0
+                         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");

grub-core/commands/appendedsig/x509.c new file +4 -0
+    }
+
+  /*
+   * RFC 3279 2.3.1:  The DER encoded RSAPublicKey is the value of 

the BIT

grub-core/commands/appendedsig/x509.c new file +3 -0
+   * STRING subjectPublicKey.
+   */
+  result = asn1_read_value_type (asn, pk_name, NULL, &key_size, 

&key_type);

grub-core/commands/appendedsig/x509.c new file +3 -0
+  if (result != ASN1_MEM_ERROR)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading size

of x509 public key: %s",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         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",

grub-core/commands/appendedsig/x509.c new file +31 -0
+                         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)

grub-core/commands/appendedsig/x509.c new file +9 -0
+{
+  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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for

certificate: %s",

grub-core/commands/appendedsig/x509.c new file +4 -0
+                         asn1_strerror (result));
+    }
+
+  result = asn1_der_decoding2 (&strasn, der, &der_size,

ASN1_DECODE_FLAG_STRICT_DER, asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Could not parse DER for DirectoryString:

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+      goto cleanup;
+    }
+
+  choice = grub_asn1_allocate_and_read (strasn, "", "DirectoryString

choice", &choice_size);

grub-core/commands/appendedsig/x509.c new file +9 -0
+  if (!choice)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+
+  if (grub_strncmp ("utf8String", choice, choice_size) == 0)
+    {
+      result = asn1_read_value (strasn, "utf8String", NULL, 

&tmp_size);

grub-core/commands/appendedsig/x509.c new file +3 -0
+      if (result != ASN1_MEM_ERROR)
+        {
+          err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading

size of UTF-8 string: %s",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                            asn1_strerror (result));
+          goto cleanup_choice;
+        }
+    }
+  else if (grub_strncmp ("printableString", choice, choice_size) == 

0)

grub-core/commands/appendedsig/x509.c new file +2 -0
+    {
+      result = asn1_read_value (strasn, "printableString", NULL, 

&tmp_size);

grub-core/commands/appendedsig/x509.c new file +3 -0
+      if (result != ASN1_MEM_ERROR)
+        {
+          err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading

size of UTF-8 string: %s",

grub-core/commands/appendedsig/x509.c new file +7 -0
+                            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",

grub-core/commands/appendedsig/x509.c new file +12 -0
+                        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");

grub-core/commands/appendedsig/x509.c new file +7 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +38 -0
+                        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",

grub-core/commands/appendedsig/x509.c new file +12 -0
+                       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)

grub-core/commands/appendedsig/x509.c new file +17 -0
+{
+  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);

grub-core/commands/appendedsig/x509.c new file +5 -0
+
+  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",

grub-core/commands/appendedsig/x509.c new file +10 -0
+                        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",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                            name_path);
+          goto cleanup_set;
+        }
+      /* this brings us, hopefully, to a set */
+      result = asn1_number_of_elements (asn, set_path, 

&set_components);

grub-core/commands/appendedsig/x509.c new file +3 -0
+      if (result != ASN1_SUCCESS)
+        {
+          err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error counting

name sub-components components (element %d): %s",

grub-core/commands/appendedsig/x509.c new file +6 -0
+                            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);

grub-core/commands/appendedsig/x509.c new file +3 -0
+          if (!type_path)
+            {
+              err = grub_error (GRUB_ERR_OUT_OF_MEMORY, "Could not

allocate memory for %s name component type path",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                                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",

grub-core/commands/appendedsig/x509.c new file +11 -0
+                                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);

grub-core/commands/appendedsig/x509.c new file +3 -0
+          if (!val_path)
+            {
+              err = grub_error (GRUB_ERR_OUT_OF_MEMORY, "Could not

allocate memory for %s name component value path",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                                name_path);
+              goto cleanup_set;
+            }
+
+          string_der = grub_asn1_allocate_and_read (asn, val_path,

name_path, &string_size);

grub-core/commands/appendedsig/x509.c new file +7 -0
+          if (!string_der)
+            {
+              err = grub_errno;
+              goto cleanup_val_path;
+            }
+
+          err = decode_string (string_der, string_size, name, 

name_size);

grub-core/commands/appendedsig/x509.c new file +45 -0
+          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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for key 

usage");

grub-core/commands/appendedsig/x509.c new file +4 -0
+    }
+
+  result = asn1_der_decoding2 (&usageasn, value, &value_size,
+                               ASN1_DECODE_FLAG_STRICT_DER, 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Error parsing DER for Key Usage: %s", 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +7 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/x509.c new file +23 -0
+      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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for Basic 

"

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         "Constraints");
+    }
+
+  result = asn1_der_decoding2 (&basicasn, value, &value_size,
+                               ASN1_DECODE_FLAG_STRICT_DER, 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Error parsing DER for Basic Constraints:

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +13 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/x509.c new file +23 -0
+      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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for 

Extended Key "

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         "Usage");
+    }
+
+  result = asn1_der_decoding2 (&extendedasn, value, &value_size,
+                               ASN1_DECODE_FLAG_STRICT_DER, 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Error parsing DER for Extended Key Usage:

%s", asn1_error);

grub-core/commands/appendedsig/x509.c new file +5 -0
+      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

grub-core/commands/appendedsig/x509.c new file +6 -0
+   * 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",

grub-core/commands/appendedsig/x509.c new file +7 -0
+                        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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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",

grub-core/commands/appendedsig/x509.c new file +8 -0
+                        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);

grub-core/commands/appendedsig/x509.c new file +24 -0
+      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)
+ */

grub-core/commands/appendedsig/x509.c new file +6 -0
+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;

grub-core/commands/appendedsig/x509.c new file +10 -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);

grub-core/commands/appendedsig/x509.c new file +3 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error counting

number of extensions: %s",

grub-core/commands/appendedsig/x509.c new file +6 -0
+                         asn1_strerror (result));
+    }
+
+  if (num_extensions < 2)
+    {
+      return grub_error (GRUB_ERR_BAD_FILE_TYPE, "Insufficient number

of extensions for "

grub-core/commands/appendedsig/x509.c new file +7 -0
+                         "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);

grub-core/commands/appendedsig/x509.c new file +3 -0
+
+      extnID_size = sizeof (extnID);
+      result = asn1_read_value (cert, oid_path, extnID, 

&extnID_size);

grub-core/commands/appendedsig/x509.c new file +3 -0
+      if (result != ASN1_SUCCESS)
+        {
+          err = grub_error (GRUB_ERR_BAD_FILE_TYPE, "Error reading

extension OID: %s",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                            asn1_strerror (result));
+          goto cleanup_oid_path;
+        }
+
+      critical_path = grub_xasprintf

("tbsCertificate.extensions.?%d.critical", ext);

grub-core/commands/appendedsig/x509.c new file +2 -0
+      critical_size = sizeof (critical);
+      result = asn1_read_value (cert, critical_path, critical, 

&critical_size);

grub-core/commands/appendedsig/x509.c new file +7 -0
+      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",

grub-core/commands/appendedsig/x509.c new file +5 -0
+                            asn1_strerror (result));
+          goto cleanup_critical_path;
+        }
+
+      value_path = grub_xasprintf

("tbsCertificate.extensions.?%d.extnValue", ext);

grub-core/commands/appendedsig/x509.c new file +2 -0
+      value = grub_asn1_allocate_and_read (cert, value_path,
+                                           "certificate extension

value", &value_size);

grub-core/commands/appendedsig/x509.c new file +20 -0
+      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)

grub-core/commands/appendedsig/x509.c new file +9 -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)

grub-core/commands/appendedsig/x509.c new file +16 -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);

grub-core/commands/appendedsig/x509.c new file +12 -0
+          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 "

grub-core/commands/appendedsig/x509.c new file +5 -0
+                         "- 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);

grub-core/commands/appendedsig/x509.c new file +4 -0
+    }
+  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);

grub-core/commands/appendedsig/x509.c new file +16 -0
+    }
+  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-core/commands/appendedsig/x509.c new file +2 -0
+grub_err_t
+parse_x509_certificate (const void *data, grub_size_t data_size,

struct x509_certificate *results)

grub-core/commands/appendedsig/x509.c new file +10 -0
+{
+  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");

grub-core/commands/appendedsig/x509.c new file +3 -0
+  size = (int) data_size;
+
+  result = asn1_create_element (_gnutls_pkix_asn, 

"PKIX1.Certificate", &cert);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                         "Could not create ASN.1 structure for

certificate: %s",

grub-core/commands/appendedsig/x509.c new file +4 -0
+                         asn1_strerror (result));
+    }
+
+  result = asn1_der_decoding2 (&cert, data, &size,

ASN1_DECODE_FLAG_STRICT_DER, asn1_error);

grub-core/commands/appendedsig/x509.c new file +4 -0
+  if (result != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_FILE_TYPE,
+                        "Could not parse DER for certificate: %s", 

asn1_error);

grub-core/commands/appendedsig/x509.c new file +19 -0
+      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);

grub-core/commands/appendedsig/x509.c new file +34 -0
+  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

grub-core/commands/appendedsig/x509.c new file +9 -0
+   * 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);

grub-core/commands/appendedsig/x509.c new file +49 -0
+  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.
+ */

Quoted 8 lines

grub-core/commands/appendedsig/x509.c line 981

Quoted 8 lines
grub-core/commands/appendedsig/x509.c new file +8 -0
+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]);
+}

Addressed your suggestion. thank you Avnish Chouhan.

Thanks,
Sudhakar Kuppusamy

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