Skip to contentSkip to conversation

Appended Signature Secure Boot Support for PowerPC

PATCH Superseded Sudhakar Kuppusamy 3 participants 48 messages Mar 26, 2025 – Jun 10, 2025

v2 of 18 Superseded Latest is v18 →

lore
Share & tools
lore
#0 lore raw

v2 cover Appended Signature Secure Boot Support for PowerPC

This patch set contains v2 of the consolidated version of the patch sets for secure boot using appended signatures on powerpc, rebased on top of git HEAD.

The v1 series is at https://lists.gnu.org/archive/html/grub-devel/2024-12/msg00071.html

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.

Thanks to Stefan Berger, Avnish Chouhan, Michal Suchanek, and Vladimir Serbinenko for providing review comments on v1.

I've pushed this all to
https://github.com/SudhakarKuppusamy1/grub/tree/appendedsig-2.13

[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
powerpc_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                                |  283 +++-
 grub-core/Makefile.am                         |    2 +
 grub-core/Makefile.core.def                   |   31 +
 grub-core/commands/appendedsig/appendedsig.c  | 1411 +++++++++++++++++
 grub-core/commands/appendedsig/appendedsig.h  |  110 ++
 grub-core/commands/appendedsig/asn1util.c     |   98 ++
 .../commands/appendedsig/gnutls_asn1_tab.c    |  121 ++
 grub-core/commands/appendedsig/pkcs7.c        |  460 ++++++
 .../commands/appendedsig/pkix_asn1_tab.c      |  484 ++++++
 grub-core/commands/appendedsig/x509.c         |  953 +++++++++++
 grub-core/commands/pgp.c                      |   34 +-
 grub-core/kern/file.c                         |   34 +
 grub-core/kern/ieee1275/init.c                |   46 +
 grub-core/kern/powerpc/ieee1275/ieee1275.c    |  140 ++
 .../kern/powerpc/ieee1275/platform_keystore.c |  346 ++++
 grub-core/lib/crypto.c                        |    4 +
 grub-core/lib/pkcs1_v15.c                     |   59 +
 grub-core/term/tparm.c                        |    1 -
 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                           |    3 +
 include/grub/kernel.h                         |    2 +
 include/grub/lockdown.h                       |    3 +-
 include/grub/pkcs1_v15.h                      |   27 +
 include/grub/powerpc/ieee1275/ieee1275.h      |   14 +
 .../grub/powerpc/ieee1275/platform_keystore.h |  226 +++
 include/grub/types.h                          |   11 +
 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 +-
 35 files changed, 6229 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/powerpc/ieee1275/ieee1275.c
 create mode 100644 grub-core/kern/powerpc/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/powerpc/ieee1275/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 v2 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..5b6c99d83 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
#2 lore raw

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

Quoted 100 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 +0 -0
index 22bccb6a3..22f0e56cb 100644

util/grub-install-common.c static char *sbat; · line 475

Quoted 9 lines
util/grub-install-common.c +2 -0
@@ -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;

Please add empty line after this. In general separate definitions from the code.

util/grub-install-common.c grub_install_parse (int key, char *arg) · line 577

Quoted 9 lines
util/grub-install-common.c +2 -0
   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;

If you have enum types please use them properly...

grub_errno = GRUB_ERR_NONE

util/grub-install-common.c grub_install_parse (int key, char *arg) · line 579

Quoted 2 lines
util/grub-install-common.c +2 -0
+      appsig_size = grub_strtol (arg, &end, 10);
+      if (grub_errno)

This check is not reliable. Good example how it should be done is in commit ac8a37dda (net/http: Allow use of non-standard TCP/IP ports).

... and if (grub_errno != GRUB_ERR_NONE)

Please fix above mentioned issues in all patches.

Quoted 56 lines
util/grub-install-common.c +6 -3
+        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 +3 -0
index 547f7310f..5b6c99d83 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)
     {

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

Quoted 6 lines
util/grub-mkimage.c +3 -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);

As above...

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

Quoted 1 line
util/grub-mkimage.c +1 -0
+      if (grub_errno)

Ditto.

Quoted 57 lines
util/grub-mkimage.c +4 -0
+        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 +15 -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);

util/grub-mkimagexx.c SUFFIX (grub_mkimage_generate_elf) (const struct grub_install_image_target_desc · line 551

Quoted 10 lines
util/grub-mkimagexx.c +8 -0
       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;

Again, missing empty line here...

Quoted 31 lines
util/grub-mkimagexx.c +14 -0
+      note_ptr->header.n_namesz = grub_host_to_target32 (sizeof (GRUB_APPENDED_SIGNATURE_NOTE_NAME));
+      /* needs to sit at the end, so we round this up and sign some zero padding */
+      note_ptr->header.n_descsz = grub_host_to_target32 (ALIGN_UP (appsig_size, 4));
+      note_ptr->header.n_type = grub_host_to_target32 (GRUB_APPENDED_SIGNATURE_NOTE_TYPE);
+      strcpy (note_ptr->name, GRUB_APPENDED_SIGNATURE_NOTE_NAME);
+      phdr++;
+      phdr->p_type = grub_host_to_target32 (PT_NOTE);
+      phdr->p_flags = grub_host_to_target32 (PF_R);
+      phdr->p_align = grub_host_to_target32 (image_target->voidp_sizeof);
+      phdr->p_vaddr = 0;
+      phdr->p_paddr = 0;
+      phdr->p_filesz = grub_host_to_target32 (note_size);
+      phdr->p_memsz = 0;
+      phdr->p_offset = grub_host_to_target32 (header_size + program_size + 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 grub_install_generate_image (const char *dir, const char *prefix, · line 1840

Quoted 10 lines
util/mkimage.c +2 -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,
+	  grub_mkimage_generate_elf64 (image_target, note, sbat, appsig_size, &core_img, &core_size,
 				       target_addr, &layout);

What will happen if somebody attempts to generate PE image with appended signature? I think GRUB utils should complain then loudly.

Daniel

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

author
#3 lore raw

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

Hi Daniel,

Thank you for your valuable review comments.

Quoted 355 lines · Daniel Kiper
Quoted 109 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 +0 -0
index 22bccb6a3..22f0e56cb 100644

util/grub-install-common.c static char *sbat; · line 475

Quoted 9 lines
util/grub-install-common.c +2 -0
@@ -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;

Please add empty line after this. In general separate definitions from the code.

util/grub-install-common.c grub_install_parse (int key, char *arg) · line 577

Quoted 9 lines
util/grub-install-common.c +2 -0
   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;

If you have enum types please use them properly...

grub_errno = GRUB_ERR_NONE

util/grub-install-common.c grub_install_parse (int key, char *arg) · line 579

Quoted 2 lines
util/grub-install-common.c +2 -0
+      appsig_size = grub_strtol (arg, &end, 10);
+      if (grub_errno)

This check is not reliable. Good example how it should be done is in commit ac8a37dda (net/http: Allow use of non-standard TCP/IP ports).

... and if (grub_errno != GRUB_ERR_NONE)

Please fix above mentioned issues in all patches.

Quoted 63 lines
util/grub-install-common.c +6 -4
+        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..5b6c99d83 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 argp_parser (int key, char *arg, struct · line 181

Quoted 7 lines
util/grub-mkimage.c +3 -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);

As above...

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

Quoted 1 line
util/grub-mkimage.c +1 -0
+      if (grub_errno)

Ditto.

Quoted 76 lines
util/grub-mkimage.c +3 -0
+        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 
Quoted 3 lines

grub_appended_signature_note) + appsig_size, 4);
+ struct grub_appended_signature_note *note_ptr = (struct
grub_appended_signature_note *) footer;

Again, missing empty line here...

Quoted 49 lines

+ 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 -1
 			     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
Quoted 8 lines
Quoted 5 lines
util/mkimage.c +0 -1
-	  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,
target_addr, &layout);

What will happen if somebody attempts to generate PE image with appended signature? I think GRUB utils should complain then loudly.

v2 won't complain if somebody attempts to generate PE image with appended signature.

In v3, I have added the check condition to complain loudly if somebody attempts to generate PE image with appended signature.

Thanks,
Sudhakar Kuppusamy

Quoted 1 line

Daniel

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

#4 lore raw

PATCH v2 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 d9b26fa36..0e877e026 100644
@@ -8632,6 +8632,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
@@ -8712,7 +8713,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}
@@ -9246,6 +9247,21 @@ which increases the risk of password leakage during the process. Moreover, the
 superuser list must be well maintained, and the password used cannot be
 synchronized with LUKS key rotation.
 
+@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 enroll 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 v2 2/21
#5 lore raw

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

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

Daniel

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

#6 lore raw

PATCH v2 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 | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
docs/grub.texi +32 -0
index 0e877e026..19bbe9b2b 100644
@@ -9262,6 +9262,38 @@ image works under UEFI secure boot and can maintain the secure-boot chain. It
 will also be necessary to enroll 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
#7 lore raw

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

Quoted 3 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

Signing grub for firmware that verifies an appended signature is a

s/grub/GRUB/

The project name is GRUB. Please fix it everywhere.

Quoted 25 lines

bit fiddly. I don't want people to have to figure it out from scratch so document it here.

---
 docs/grub.texi | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
docs/grub.texi +6 -0
index 0e877e026..19bbe9b2b 100644
@@ -9262,6 +9262,38 @@ image works under UEFI secure boot and can maintain the secure-boot chain. It
 will also be necessary to enroll 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

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

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

Would not signing /dev/null instead of empty work?

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

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

This could be possibly done by grub-install/grub-mkimage. Then you would have one step less. Or even automate signing process by calling sign-file from the GRUB utils.

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

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

Daniel

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

author
#8 lore raw

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

Hi Daniel,

Thank you for your valuable review comments. addressed all your comments.

Quoted 46 lines · Daniel Kiper
Quoted 3 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

Signing grub for firmware that verifies an appended signature is a

s/grub/GRUB/

The project name is GRUB. Please fix it everywhere.

Quoted 37 lines

bit fiddly. I don't want people to have to figure it out from scratch so document it here.

---
 docs/grub.texi | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
docs/grub.texi +0 -0
index 0e877e026..19bbe9b2b 100644
@@ -9262,6 +9262,38 @@ image works under UEFI secure boot and can 

maintain the secure-boot chain. It
will also be necessary to enroll 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

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

Quoted 8 lines

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

Quoted 6 lines
docs/grub.texi +2 -0
+# 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 +3 -0
+# certificate and the hash algorithm
+touch empty
+sign-file SHA256 grub.key certificate.der empty empty.sig

Would not signing /dev/null instead of empty work?

It is work for /dev/null. addressed this in v3

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

This could be possibly done by grub-install/grub-mkimage. Then you would have one step less. Or even automate signing process by calling sign-file from the GRUB utils.

In v3, I reduced the truncate step and added the same in grub-install/grub-mkimage. In future, I will add automate signing process in the GRUB utils

Quoted 5 lines
Quoted 5 lines

+# 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

Quoted 8 lines
Quoted 6 lines
docs/grub.texi +4 -0
+# (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.

Daniel

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

#9 lore raw

PATCH v2 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 84509c5c1..43e411fef 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
#10 lore raw

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

Quoted 34 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 +9 -0
index 84509c5c1..43e411fef 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)

You will have the same problem with this function...

Daniel

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

#11 lore raw

PATCH v2 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 5fadc33c4..5503d291a 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..7644ac9e0
@@ -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 v2 5/21
#12 lore raw

Re: [PATCH v2 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 7 lines

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

But a nit below...

Quoted 159 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 5fadc33c4..5503d291a 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..535ba5c18
@@ -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 +14 -0
new file mode 100644
index 000000000..7644ac9e0
@@ -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.
+ *

include/grub/pkcs1_v15.h line 24

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

extern gcry_err_code_t

Please prefix variables/functions declarations in header files with extern.

include/grub/pkcs1_v15.h line 27

Quoted 3 lines
include/grub/pkcs1_v15.h new file +3 -0
+grub_crypto_rsa_pad (gcry_mpi_t * hmpi, grub_uint8_t * hval,
+                     const gcry_md_spec_t * hash, gcry_mpi_t mod);
+

Daniel

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

#13 lore raw

PATCH v2 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 5503d291a..961abf775 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 v2 6/21
#14 lore raw

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

Quoted 32 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.]

Quoted 5 lines

Daniel

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

#15 lore raw

PATCH v2 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 961abf775..fa3ef5c75 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 5b6c99d83..4c0fe0b4a 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
#16 lore raw

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

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

s/grub/GRUB/

Quoted 19 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 +0 -0
index 961abf775..fa3ef5c75 100644

grub-core/commands/pgp.c GRUB_MOD_INIT(pgp) · line 947

Quoted 5 lines
grub-core/commands/pgp.c +1 -1
@@ -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)

This patch should be split into two. One should do required renames in existing code and another one should add X.509 code.

Daniel

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

author
#17 lore raw

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

Hi Daniel,

Thank you for your valuable review. splited this patch into two in v3.

Thanks,
Sudhakar Kuppusmay

Quoted 31 lines · Daniel Kiper
Quoted 6 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.

s/grub/GRUB/

Quoted 21 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 +0 -0
index 961abf775..fa3ef5c75 100644
@@ -944,7 +944,7 @@ GRUB_MOD_INIT(pgp)
     grub_memset (&pseudo_file, 0, sizeof (pseudo_file));
 
Quoted 8 lines

grub-core/commands/pgp.c GRUB_MOD_INIT(pgp) · line 947

Quoted 3 lines
grub-core/commands/pgp.c +1 -1
     /* Not an ELF module, skip.  */
-    if (header->type != OBJ_TYPE_PUBKEY)
+    if (header->type != OBJ_TYPE_GPG_PUBKEY)

This patch should be split into two. One should do required renames in existing code and another one should add X.509 code.

Daniel

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

#18 lore raw

PATCH v2 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
#19 lore raw

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

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

Quoted 7 lines

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

Do we import latest versions?

Quoted 20 lines

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 +0 -0
new file mode 100644
index 000000000..ddd1314e6

grub-core/commands/appendedsig/gnutls_asn1_tab.c line 4

Quoted 4 lines
grub-core/commands/appendedsig/gnutls_asn1_tab.c new file +4 -0
@@ -0,0 +1,121 @@
+#include <grub/mm.h>
+#include <grub/libtasn1.h>
+
+const asn1_static_node gnutls_asn1_tab[] = {

s/gnutls_asn1_tab/grub_gnutls_asn1_tab/g

[...]

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

Quoted 10 lines
grub-core/commands/appendedsig/pkix_asn1_tab.c new file +4 -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[] = {

s/gnutls_asn1_tab/grub_pkix_asn1_tab/g

Daniel

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

author
#20 lore raw

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

Hi Daniel,

Thank you for your valuable review. addressed all the below review comments in v3.

Thanks,
Sudhakar Kuppusmay

Quoted 9 lines · Daniel Kiper
Quoted 8 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.

Quoted 8 lines
Quoted 6 lines

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

Do we import latest versions?

imported latest version in v3

Quoted 43 lines
Quoted 21 lines

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 +0 -0
new file mode 100644
index 000000000..ddd1314e6

grub-core/commands/appendedsig/gnutls_asn1_tab.c line 4

Quoted 4 lines
grub-core/commands/appendedsig/gnutls_asn1_tab.c new file +4 -0
@@ -0,0 +1,121 @@
+#include <grub/mm.h>
+#include <grub/libtasn1.h>
+
+const asn1_static_node gnutls_asn1_tab[] = {

s/gnutls_asn1_tab/grub_gnutls_asn1_tab/g

[...]

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

Quoted 10 lines
grub-core/commands/appendedsig/pkix_asn1_tab.c new file +4 -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[] = {

s/gnutls_asn1_tab/grub_pkix_asn1_tab/g

Quoted 1 line

Daniel

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

#21 lore raw

PATCH v2 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 Code Signing usage.

---
 grub-core/commands/appendedsig/appendedsig.h | 110 +++
 grub-core/commands/appendedsig/asn1util.c    |  98 ++
 grub-core/commands/appendedsig/pkcs7.c       | 460 +++++++++
 grub-core/commands/appendedsig/x509.c        | 953 +++++++++++++++++++
 4 files changed, 1621 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..3f4d7002e
@@ -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 +98 -0

98 lines not on this page · raw message

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

460 lines not on this page · raw message

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

953 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
#22 lore raw

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

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

s/grub/GRUB/

Quoted 4 lines

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 Code Signing usage.

Could not you split this patch to 2 or 3 logical parts?

Quoted 23 lines
---
 grub-core/commands/appendedsig/appendedsig.h | 110 +++
 grub-core/commands/appendedsig/asn1util.c    |  98 ++
 grub-core/commands/appendedsig/pkcs7.c       | 460 +++++++++
 grub-core/commands/appendedsig/x509.c        | 953 +++++++++++++++++++
 4 files changed, 1621 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 +0 -0
new file mode 100644
index 000000000..3f4d7002e

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

Quoted 4 lines
grub-core/commands/appendedsig/appendedsig.h new file +4 -0
@@ -0,0 +1,110 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2022 IBM Corporation

s/2020, 2022/2020, 2022, 2025/ everywhere please...

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

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

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

s/_gnutls_gnutls_asn/grub_gnutls_gnutls_asn/

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

Quoted 1 line
grub-core/commands/appendedsig/appendedsig.h new file +1 -0
+extern asn1_node _gnutls_pkix_asn;

s/_gnutls_pkix_asn/grub_gnutls_pkix_asn/

Quoted 112 lines
grub-core/commands/appendedsig/appendedsig.h new file +85 -0
+#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 +21 -0
new file mode 100644
index 000000000..06c3b61c1
@@ -0,0 +1,98 @@
+/*
+ *  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>

grub-core/commands/appendedsig/asn1util.c line 31

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

Global variables should be prefixed with grub_...

grub-core/commands/appendedsig/asn1util.c line 34

Quoted 2 lines
grub-core/commands/appendedsig/asn1util.c new file +2 -0
+extern const asn1_static_node gnutls_asn1_tab[];
+extern const asn1_static_node pkix_asn1_tab[];

Ditto.

Quoted 13 lines
grub-core/commands/appendedsig/asn1util.c new file +13 -0
+/*
+ * 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 line 58

Quoted 10 lines
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"),

Please drop _().

grub-core/commands/appendedsig/asn1util.c line 58

Quoted 2 lines
grub-core/commands/appendedsig/asn1util.c new file +2 -0
+                     friendly_name, asn1_strerror (result));
+      grub_errno = GRUB_ERR_BAD_FILE_TYPE;

Why do not you use grub_error() here?

grub-core/commands/appendedsig/asn1util.c line 69

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

Ditto.

grub-core/commands/appendedsig/asn1util.c line 79

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

Ditto.

grub-core/commands/appendedsig/asn1util.c line 91

Quoted 12 lines
grub-core/commands/appendedsig/asn1util.c new file +12 -0
+      return NULL;
+    }
+
+  *content_size = tmpstr_size;
+
+  return tmpstr;
+}
+
+int
+asn1_init (void)
+{
+  int res;

Missing empty line.

Quoted 33 lines
grub-core/commands/appendedsig/asn1util.c new file +7 -0
+  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 +20 -0
new file mode 100644
index 000000000..31a5eab6a
@@ -0,0 +1,460 @@
+/*
+ *  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"

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

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

Please put this comment in one line and s/s/section/?

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

Quoted 5 lines
grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+static const char *signedData_oid = "1.2.840.113549.1.7.2";
+
+/*
+ * RFC 4055 s 2.1
+ */

Ditto. Please fix similar problems everywhere...

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

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

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

All error messages in the core GRUB code start with lowercase and do not have full stop at the end. Please fix it in all patches.

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

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

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

Could you expand this comment? It has to be clear.

Quoted 66 lines
grub-core/commands/appendedsig/pkcs7.c new file +66 -0
+  res = asn1_read_value (signed_part, "version", &version, &version_size);
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error reading signedData version: %s",
+                        asn1_strerror (res));
+      goto cleanup_signed_part;
+    }
+
+  if (version != 1)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                        "Unexpected signature version v%d, only v1 supported", version);
+      goto cleanup_signed_part;
+    }
+
+  /*
+   * digestAlgorithms DigestAlgorithmIdentifiers
+   *
+   * DigestAlgorithmIdentifiers ::= SET OF DigestAlgorithmIdentifier
+   * DigestAlgorithmIdentifer is an X.509 AlgorithmIdentifier (10.1.1)
+   *
+   * RFC 4055 s 2.1:
+   * sha256Identifier  AlgorithmIdentifier  ::=  { id-sha256, NULL }
+   * sha512Identifier  AlgorithmIdentifier  ::=  { id-sha512, NULL }
+   *
+   * We only support 1 element in the set, and we do not check parameters atm.
+   */
+  res = asn1_number_of_elements (signed_part, "digestAlgorithms", &algo_count);
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error counting number of digest algorithms: %s",
+                        asn1_strerror (res));
+      goto cleanup_signed_part;
+    }
+
+  if (algo_count <= 0)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                        "A minimum of 1 digest algorithm is required");
+      goto cleanup_signed_part;
+    }
+
+  if (algo_count > 2)
+    {
+      err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+                        "A maximum of 2 digest algorithms is supported");
+      goto cleanup_signed_part;
+    }
+
+  sha256_in_da = false;
+  sha512_in_da = false;
+
+  for (i = 0; i < algo_count; i++)
+    {
+      da_path = grub_xasprintf ("digestAlgorithms.?%d.algorithm", i + 1);
+      if (!da_path)
+        {
+          err = grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                            "Could not allocate path for digest algorithm "
+                            "parsing path");
+          goto cleanup_signed_part;
+        }
+
+      algo_oid_size = sizeof (algo_oid);
+      res = asn1_read_value (signed_part, da_path, algo_oid, &algo_oid_size);
+      if (res != ASN1_SUCCESS)

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

Quoted 10 lines
grub-core/commands/appendedsig/pkcs7.c new file +10 -0
+        {
+          err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error reading digest algorithm: %s",
+                            asn1_strerror (res));
+          grub_free (da_path);
+          goto cleanup_signed_part;
+        }
+
+      if (grub_strncmp (sha512_oid, algo_oid, algo_oid_size) == 0)
+        {
+          if (!sha512_in_da)

sha512_in_da == false (for bools) please everywhere...

Quoted 55 lines
grub-core/commands/appendedsig/pkcs7.c new file +55 -0
+            sha512_in_da = true;
+          else
+            {
+              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                "SHA-512 specified twice in digest algorithm list");
+              grub_free (da_path);
+              goto cleanup_signed_part;
+            }
+        }
+      else if (grub_strncmp (sha256_oid, algo_oid, algo_oid_size) == 0)
+        {
+          if (!sha256_in_da)
+            sha256_in_da = true;
+          else
+            {
+              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                "SHA-256 specified twice in digest algorithm list");
+              grub_free (da_path);
+              goto cleanup_signed_part;
+            }
+        }
+      else
+        {
+          err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET, "Only SHA-256 and SHA-512 hashes are supported, found OID %s",
+                            algo_oid);
+          grub_free (da_path);
+          goto cleanup_signed_part;
+        }
+
+      grub_free (da_path);
+    }
+
+  /* at this point, at least one of sha{256,512}_in_da must be true */
+
+  /*
+   * We ignore the certificates, but we don't permit CRLs.
+   * A CRL entry might be revoking the certificate we're using, and we have
+   * no way of dealing with that at the moment.
+   */
+  res = asn1_read_value (signed_part, "crls", NULL, &crls_size);
+  if (res != ASN1_ELEMENT_NOT_FOUND)
+    {
+      err = grub_error (GRUB_ERR_NOT_IMPLEMENTED_YET,
+                        "PKCS#7 messages with embedded CRLs are not supported");
+      goto cleanup_signed_part;
+    }
+
+  /* read the signatures */
+
+  res = asn1_number_of_elements (signed_part, "signerInfos", &signer_count);
+  if (res != ASN1_SUCCESS)
+    {
+      err = grub_error (GRUB_ERR_BAD_SIGNATURE, "Error counting number of signers: %s",
+                        asn1_strerror (res));
+      goto cleanup_signed_part;

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

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

msg->signerInfos == NULL (for pointers) everywhere please...

Additionally, all (goto) labels should be prefixed with one space.

Daniel

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

author
#23 lore raw

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

Hi Daniel,

Thank you for your valuable review. addressed all the below review comments in v3.

Thanks,
Sudhakar Kuppusmay

Quoted 589 lines · Daniel Kiper
Quoted 4 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

This code allows us to parse:

Quoted 8 lines

- 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

s/grub/GRUB/

Quoted 6 lines

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 Code Signing usage.

Could not you split this patch to 2 or 3 logical parts?

Quoted 24 lines
---
 grub-core/commands/appendedsig/appendedsig.h | 110 +++
 grub-core/commands/appendedsig/asn1util.c    |  98 ++
 grub-core/commands/appendedsig/pkcs7.c       | 460 +++++++++
 grub-core/commands/appendedsig/x509.c        | 953 
+++++++++++++++++++
 4 files changed, 1621 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 +0 -0
new file mode 100644
index 000000000..3f4d7002e

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

Quoted 4 lines
grub-core/commands/appendedsig/appendedsig.h new file +4 -0
@@ -0,0 +1,110 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2022 IBM Corporation

s/2020, 2022/2020, 2022, 2025/ everywhere please...

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

Quoted 5 lines
grub-core/commands/appendedsig/appendedsig.h new file +5 -0
+
+#include <grub/crypto.h>
+#include <grub/libtasn1.h>
+
+extern asn1_node _gnutls_gnutls_asn;

s/_gnutls_gnutls_asn/grub_gnutls_gnutls_asn/

Quoted 1 line

+extern asn1_node _gnutls_pkix_asn;

s/_gnutls_pkix_asn/grub_gnutls_pkix_asn/

Quoted 124 lines
grub-core/commands/appendedsig/appendedsig.h new file +5 -0
+#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..06c3b61c1
@@ -0,0 +1,98 @@
+/*
+ *  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 +3 -0
+
+#include <grub/libtasn1.h>
+#include <grub/types.h>

grub-core/commands/appendedsig/asn1util.c line 31

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

Global variables should be prefixed with grub_...

grub-core/commands/appendedsig/asn1util.c line 34

Quoted 2 lines
grub-core/commands/appendedsig/asn1util.c new file +2 -0
+extern const asn1_static_node gnutls_asn1_tab[];
+extern const asn1_static_node pkix_asn1_tab[];

Ditto.

Quoted 27 lines

+/*
+ * 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 
Quoted 1 line

status: %s"),

Please drop _().

grub-core/commands/appendedsig/asn1util.c

Quoted 2 lines
grub-core/commands/appendedsig/asn1util.c new file +2 -0
+                     friendly_name, asn1_strerror (result));
+      grub_errno = GRUB_ERR_BAD_FILE_TYPE;

Why do not you use grub_error() here?

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

Ditto.

grub-core/commands/appendedsig/asn1util.c

Quoted 11 lines
grub-core/commands/appendedsig/asn1util.c new file +8 -0
+      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 +2 -0
+                     friendly_name, asn1_strerror (result));
+      grub_errno = GRUB_ERR_BAD_FILE_TYPE;

Ditto.

grub-core/commands/appendedsig/asn1util.c line 91

Quoted 12 lines
grub-core/commands/appendedsig/asn1util.c new file +12 -0
+      return NULL;
+    }
+
+  *content_size = tmpstr_size;
+
+  return tmpstr;
+}
+
+int
+asn1_init (void)
+{
+  int res;

Missing empty line.

Quoted 34 lines
grub-core/commands/appendedsig/asn1util.c new file +7 -0
+  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..31a5eab6a
@@ -0,0 +1,460 @@
+/*
+ *  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 +2 -0
+
+#include "appendedsig.h"

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

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

Please put this comment in one line and s/s/section/?

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

Quoted 5 lines
grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+static const char *signedData_oid = "1.2.840.113549.1.7.2";
+
+/*
+ * RFC 4055 s 2.1
+ */

Ditto. Please fix similar problems everywhere...

Quoted 31 lines
grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+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 +3 -0
+  if (res != ASN1_SUCCESS)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                       "Could not create ASN.1 structure for PKCS#7 
Quoted 1 line

signed part.");

All error messages in the core GRUB code start with lowercase and do not have full stop at the end. Please fix it in all patches.

Quoted 11 lines
grub-core/commands/appendedsig/pkcs7.c new file +6 -0
+  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 +4 -0
+      goto cleanup_signed_part;
+    }
+
+  /*

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

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

Could you expand this comment? It has to be clear.

Quoted 81 lines

+ 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 is 

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 line 161

Quoted 8 lines
grub-core/commands/appendedsig/pkcs7.c new file +8 -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 == false (for bools) please everywhere...

Quoted 74 lines
grub-core/commands/appendedsig/pkcs7.c new file +5 -0
+            sha512_in_da = true;
+          else
+            {
+              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                "SHA-512 specified twice in digest 

algorithm list");

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 +7 -0
+        {
+          if (!sha256_in_da)
+            sha256_in_da = true;
+          else
+            {
+              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                "SHA-256 specified twice in digest 

algorithm list");

grub-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 +7 -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");

grub-core/commands/appendedsig/pkcs7.c new file +4 -0
+      goto cleanup_signed_part;
+    }
+
+  msg->signerInfos = grub_calloc (signer_count, sizeof (struct 
Quoted 2 lines

pkcs7_signerInfo));
+ if (!msg->signerInfos)

msg->signerInfos == NULL (for pointers) everywhere please...

Quoted 3 lines

Additionally, all (goto) labels should be prefixed with one space.

Daniel

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

#24 lore raw

PATCH v2 10/21 appended signatures: support verifying appended signatures

In reply to Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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

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

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

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

---
 grub-core/Makefile.core.def                   |  14 +
 grub-core/commands/appendedsig/appendedsig.c  | 618 ++++++++++++++++++
 grub-core/commands/appendedsig/appendedsig.h  |   2 +-
 grub-core/commands/appendedsig/asn1util.c     |   2 +-
 .../commands/appendedsig/gnutls_asn1_tab.c    |   2 +-
 .../commands/appendedsig/pkix_asn1_tab.c      |   2 +-
 grub-core/commands/appendedsig/x509.c         |   2 +-
 include/grub/file.h                           |   2 +
 8 files changed, 639 insertions(+), 5 deletions(-)
 create mode 100644 grub-core/commands/appendedsig/appendedsig.c
grub-core/Makefile.core.def +14 -0
index 60db2adc5..d693986c6 100644
@@ -979,6 +979,20 @@ module = {
   cppflags = '-I$(srcdir)/lib/posix_wrap';
 };
 
+module = {
+  name = appendedsig;
+  common = commands/appendedsig/appendedsig.c;
+  common = commands/appendedsig/x509.c;
+  common = commands/appendedsig/pkcs7.c;
+  common = commands/appendedsig/asn1util.c;
+  common = commands/appendedsig/gnutls_asn1_tab.c;
+  common = commands/appendedsig/pkix_asn1_tab.c;
+
+  // posix wrapper required for gcry to get sys/types.h
+  cflags = '$(CFLAGS_POSIX)';
+  cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/libtasn1-grub';
+};
+
 module = {
   name = hdparm;
   common = commands/hdparm.c;
grub-core/commands/appendedsig/appendedsig.c new file +618 -0

618 lines not on this page · raw message

grub-core/commands/appendedsig/appendedsig.h +1 -1
index 3f4d7002e..9a30c3885 100644
@@ -18,7 +18,7 @@
  */
 
 #include <grub/crypto.h>
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 
 extern asn1_node _gnutls_gnutls_asn;
 extern asn1_node _gnutls_pkix_asn;
grub-core/commands/appendedsig/asn1util.c +1 -1
index 06c3b61c1..2e683c892 100644
@@ -17,7 +17,7 @@
  *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 #include <grub/types.h>
 #include <grub/err.h>
 #include <grub/mm.h>
grub-core/commands/appendedsig/gnutls_asn1_tab.c +1 -1
index ddd1314e6..8c4eb81d7 100644
@@ -1,5 +1,5 @@
 #include <grub/mm.h>
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 
 const asn1_static_node gnutls_asn1_tab[] = {
   { "GNUTLS", 536872976, NULL },
grub-core/commands/appendedsig/pkix_asn1_tab.c +1 -1
index adef69d95..8eeeac047 100644
@@ -1,5 +1,5 @@
 #include <grub/mm.h>
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 
 const asn1_static_node pkix_asn1_tab[] = {
   { "PKIX1", 536875024, NULL },
grub-core/commands/appendedsig/x509.c +1 -1
index eb87025c2..316e3035a 100644
@@ -17,7 +17,7 @@
  *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 #include <grub/types.h>
 #include <grub/err.h>
 #include <grub/mm.h>
include/grub/file.h +2 -0
index a5bf3a792..d678de063 100644
@@ -80,6 +80,8 @@ enum grub_file_type
     GRUB_FILE_TYPE_PUBLIC_KEY,
     /* File holding public key to add to trused keys.  */
     GRUB_FILE_TYPE_PUBLIC_KEY_TRUST,
+    /* File holding x509 certificiate to add to trusted keys.  */
+    GRUB_FILE_TYPE_CERTIFICATE_TRUST,
     /* File of which we intend to print a blocklist to the user.  */
     GRUB_FILE_TYPE_PRINT_BLOCKLIST,
     /* File we intend to use for test loading or testing speed.  */
Signature · 7 lines
2.43.5


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

Re: [PATCH v2 10/21] appended signatures: support verifying appended signatures

Quoted 10 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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

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

Quoted 7 lines

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

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

IMO, the changes for libtasn1.h should be merged into the previous two patches since the path should be set correctly in the first place.

Gary Lin

Quoted 748 lines
---
 grub-core/Makefile.core.def                   |  14 +
 grub-core/commands/appendedsig/appendedsig.c  | 618 ++++++++++++++++++
 grub-core/commands/appendedsig/appendedsig.h  |   2 +-
 grub-core/commands/appendedsig/asn1util.c     |   2 +-
 .../commands/appendedsig/gnutls_asn1_tab.c    |   2 +-
 .../commands/appendedsig/pkix_asn1_tab.c      |   2 +-
 grub-core/commands/appendedsig/x509.c         |   2 +-
 include/grub/file.h                           |   2 +
 8 files changed, 639 insertions(+), 5 deletions(-)
 create mode 100644 grub-core/commands/appendedsig/appendedsig.c
grub-core/Makefile.core.def +14 -0
index 60db2adc5..d693986c6 100644
@@ -979,6 +979,20 @@ module = {
   cppflags = '-I$(srcdir)/lib/posix_wrap';
 };
 
+module = {
+  name = appendedsig;
+  common = commands/appendedsig/appendedsig.c;
+  common = commands/appendedsig/x509.c;
+  common = commands/appendedsig/pkcs7.c;
+  common = commands/appendedsig/asn1util.c;
+  common = commands/appendedsig/gnutls_asn1_tab.c;
+  common = commands/appendedsig/pkix_asn1_tab.c;
+
+  // posix wrapper required for gcry to get sys/types.h
+  cflags = '$(CFLAGS_POSIX)';
+  cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/libtasn1-grub';
+};
+
 module = {
   name = hdparm;
   common = commands/hdparm.c;
grub-core/commands/appendedsig/appendedsig.c new file +618 -0
new file mode 100644
index 000000000..cbd227a3c
@@ -0,0 +1,618 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2021, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2021, 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/types.h>
+#include <grub/misc.h>
+#include <grub/mm.h>
+#include <grub/err.h>
+#include <grub/dl.h>
+#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/kernel.h>
+#include <grub/extcmd.h>
+#include <grub/verify.h>
+#include <libtasn1.h>
+#include <grub/env.h>
+#include <grub/lockdown.h>
+
+#include "appendedsig.h"
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+const char magic[] = "~Module signature appended~\n";
+
+/*
+ * This structure is extracted from scripts/sign-file.c in the linux kernel
+ * source. It was licensed as LGPLv2.1+, which is GPLv3+ compatible.
+ */
+struct module_signature
+{
+  grub_uint8_t algo;       /* Public-key crypto algorithm [0] */
+  grub_uint8_t hash;       /* Digest algorithm [0] */
+  grub_uint8_t id_type;    /* Key identifier type [PKEY_ID_PKCS7] */
+  grub_uint8_t signer_len; /* Length of signer's name [0] */
+  grub_uint8_t key_id_len; /* Length of key identifier [0] */
+  grub_uint8_t __pad[3];
+  grub_uint32_t sig_len;   /* Length of signature data */
+} GRUB_PACKED;
+
+/* This represents an entire, parsed, appended signature */
+struct grub_appended_signature
+{
+  grub_size_t signature_len;            /* Length of PKCS#7 data + metadata + magic */
+  struct module_signature sig_metadata; /* Module signature metadata */
+  struct pkcs7_signedData pkcs7;        /* Parsed PKCS#7 data */
+};
+
+/* Trusted certificates for verifying appended signatures */
+struct x509_certificate *grub_trusted_key;
+
+/*
+ * Force gcry_rsa to be a module dependency.
+ *
+ * If we use grub_crypto_pk_rsa, then then the gcry_rsa module won't be built
+ * in if you add 'appendedsig' to grub-install --modules. You would need to
+ * add 'gcry_rsa' too. That's confusing and seems suboptimal, especially when
+ * we only support RSA.
+ *
+ * Dynamic loading also causes some concerns. We can't load gcry_rsa from the
+ * the filesystem after we install the verifier - we won't be able to verify
+ * it without having it already present. We also shouldn't load it before we
+ * install the verifier, because that would mean it wouldn't be verified - an
+ * attacker could insert any code they wanted into the module.
+ *
+ * So instead, reference the internal symbol from gcry_rsa. That creates a
+ * direct dependency on gcry_rsa, so it will be built in when this module
+ * is built in. Being built in (assuming the core image is itself signed!)
+ * also resolves our concerns about loading from the filesystem.
+ */
+extern gcry_pk_spec_t _gcry_pubkey_spec_rsa;
+
+static enum
+{
+  check_sigs_no = 0,
+  check_sigs_enforce = 1,
+  check_sigs_forced = 2
+} check_sigs = check_sigs_no;
+
+static const char *
+grub_env_read_sec (struct grub_env_var *var __attribute__ ((unused)),
+                   const char *val __attribute__ ((unused)))
+{
+  if (check_sigs == check_sigs_forced)
+    return "forced";
+  else if (check_sigs == check_sigs_enforce)
+    return "enforce";
+  else
+    return "no";
+}
+
+static char *
+grub_env_write_sec (struct grub_env_var *var __attribute__ ((unused)), const char *val)
+{
+  /* Do not allow the value to be changed if set to forced */
+  if (check_sigs == check_sigs_forced)
+    return grub_strdup ("forced");
+
+  if ((*val == '2') || (*val == 'f'))
+    check_sigs = check_sigs_forced;
+  else if ((*val == '1') || (*val == 'e'))
+    check_sigs = check_sigs_enforce;
+  else if ((*val == '0') || (*val == 'n'))
+    check_sigs = check_sigs_no;
+
+  return grub_strdup (grub_env_read_sec (NULL, NULL));
+}
+
+static grub_err_t
+file_read_all (grub_file_t file, grub_uint8_t **buf, grub_size_t *len)
+{
+  grub_off_t full_file_size;
+  grub_size_t file_size, total_read_size = 0;
+  grub_ssize_t read_size;
+
+  full_file_size = grub_file_size (file);
+  if (full_file_size == GRUB_FILE_SIZE_UNKNOWN)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("Cannot read a file of unknown size into a buffer"));
+
+  if (full_file_size > GRUB_SIZE_MAX)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+                       N_("File is too large to read: %" PRIuGRUB_UINT64_T " bytes"),
+                       full_file_size);
+
+  file_size = (grub_size_t) full_file_size;
+
+  *buf = grub_malloc (file_size);
+  if (!*buf)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                       N_("Could not allocate file data buffer size %" PRIuGRUB_SIZE),
+                       file_size);
+
+  while (total_read_size < file_size)
+    {
+      read_size = grub_file_read (file, *buf + total_read_size, file_size - total_read_size);
+
+      if (read_size < 0)
+        {
+          grub_free (*buf);
+          return grub_errno;
+        }
+      else if (read_size == 0)
+        {
+          grub_free (*buf);
+          return grub_error (GRUB_ERR_IO,
+                             N_("Could not read full file size "
+                                "(%" PRIuGRUB_SIZE "), only %" PRIuGRUB_SIZE " bytes read"),
+                             file_size, total_read_size);
+        }
+
+      total_read_size += read_size;
+    }
+  *len = file_size;
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+read_cert_from_file (grub_file_t f, struct x509_certificate *certificate)
+{
+  grub_err_t err;
+  grub_uint8_t *buf;
+  grub_size_t file_size;
+
+  err = file_read_all (f, &buf, &file_size);
+  if (err != GRUB_ERR_NONE)
+    return err;
+
+  err = parse_x509_certificate (buf, file_size, certificate);
+  grub_free (buf);
+
+  return err;
+}
+
+static grub_err_t
+extract_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize,
+                            struct grub_appended_signature *sig)
+{
+  grub_size_t pkcs7_size;
+  grub_size_t remaining_len;
+  const grub_uint8_t *appsigdata = buf + bufsize - grub_strlen (magic);
+
+  if (bufsize < grub_strlen (magic))
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for signature magic"));
+
+  if (grub_memcmp (appsigdata, (grub_uint8_t *) magic, grub_strlen (magic)))
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("Missing or invalid signature magic"));
+
+  remaining_len = bufsize - grub_strlen (magic);
+
+  if (remaining_len < sizeof (struct module_signature))
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for signature metadata"));
+
+  appsigdata -= sizeof (struct module_signature);
+
+  /* extract the metadata */
+  grub_memcpy (&(sig->sig_metadata), appsigdata, sizeof (struct module_signature));
+
+  remaining_len -= sizeof (struct module_signature);
+
+  if (sig->sig_metadata.id_type != 2)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("Wrong signature type"));
+
+  pkcs7_size = grub_be_to_cpu32 (sig->sig_metadata.sig_len);
+
+  if (pkcs7_size > remaining_len)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for PKCS#7 message"));
+
+  grub_dprintf ("appendedsig", "sig len %" PRIuGRUB_SIZE "\n", pkcs7_size);
+
+  sig->signature_len = grub_strlen (magic) + sizeof (struct module_signature) + pkcs7_size;
+
+  /* rewind pointer and parse pkcs7 data */
+  appsigdata -= pkcs7_size;
+
+  return parse_pkcs7_signedData (appsigdata, pkcs7_size, &sig->pkcs7);
+}
+
+static grub_err_t
+grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize)
+{
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_size_t datasize;
+  void *context;
+  unsigned char *hash;
+  gcry_mpi_t hashmpi;
+  gcry_err_code_t rc;
+  struct x509_certificate *pk;
+  struct grub_appended_signature sig;
+  struct pkcs7_signerInfo *si;
+  int i;
+
+  if (!grub_trusted_key)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("No trusted keys to verify against"));
+
+  err = extract_appended_signature (buf, bufsize, &sig);
+  if (err != GRUB_ERR_NONE)
+    return err;
+
+  datasize = bufsize - sig.signature_len;
+
+  for (i = 0; i < sig.pkcs7.signerInfo_count; i++)
+    {
+      /*
+       * This could be optimised in a couple of ways:
+       * - we could only compute hashes once per hash type
+       * - we could track signer information and only verify where IDs match
+       * For now we do the naive O(trusted keys * pkcs7 signers) approach.
+       */
+      si = &sig.pkcs7.signerInfos[i];
+      context = grub_zalloc (si->hash->contextsize);
+      if (!context)
+        return grub_errno;
+
+      si->hash->init (context);
+      si->hash->write (context, buf, datasize);
+      si->hash->final (context);
+      hash = si->hash->read (context);
+
+      grub_dprintf ("appendedsig", "data size %" PRIxGRUB_SIZE ", signer %d hash %02x%02x%02x%02x...\n",
+                    datasize, i, hash[0], hash[1], hash[2], hash[3]);
+
+      err = GRUB_ERR_BAD_SIGNATURE;
+      for (pk = grub_trusted_key; pk; pk = pk->next)
+        {
+          rc = grub_crypto_rsa_pad (&hashmpi, hash, si->hash, pk->mpis[0]);
+          if (rc)
+            {
+              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                N_("Error padding hash for RSA verification: %d"), rc);
+              grub_free (context);
+              goto cleanup;
+            }
+
+          rc = _gcry_pubkey_spec_rsa.verify (0, hashmpi, &si->sig_mpi, pk->mpis, NULL, NULL);
+          gcry_mpi_release (hashmpi);
+
+          if (rc == 0)
+            {
+              grub_dprintf ("appendedsig", "verify signer %d with key '%s' succeeded\n",
+                            i, pk->subject);
+              err = GRUB_ERR_NONE;
+              break;
+            }
+
+          grub_dprintf ("appendedsig", "verify signer %d with key '%s' failed with %d\n",
+                        i, pk->subject, rc);
+        }
+
+      grub_free (context);
+
+      if (err == GRUB_ERR_NONE)
+        break;
+    }
+
+  /* If we didn't verify, provide a neat message */
+  if (err != GRUB_ERR_NONE)
+    err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                      N_("Failed to verify signature against a trusted key"));
+
+cleanup:
+  pkcs7_signedData_release (&sig.pkcs7);
+
+  return err;
+}
+
+static grub_err_t
+grub_cmd_verify_signature (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
+{
+  grub_file_t f;
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_uint8_t *data;
+  grub_size_t file_size;
+
+  if (argc < 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument expected"));
+
+  grub_dprintf ("appendedsig", "verifying %s\n", args[0]);
+
+  f = grub_file_open (args[0], GRUB_FILE_TYPE_VERIFY_SIGNATURE);
+  if (!f)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+
+  err = file_read_all (f, &data, &file_size);
+  if (err != GRUB_ERR_NONE)
+    goto cleanup;
+
+  err = grub_verify_appended_signature (data, file_size);
+
+  grub_free (data);
+
+cleanup:
+  if (f)
+    grub_file_close (f);
+  return err;
+}
+
+static grub_err_t
+grub_cmd_distrust (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
+{
+  unsigned long cert_num, i;
+  struct x509_certificate *cert, *prev;
+
+  if (argc != 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("One argument expected"));
+
+  grub_errno = GRUB_ERR_NONE;
+  cert_num = grub_strtoul (args[0], NULL, 10);
+  if (grub_errno != GRUB_ERR_NONE)
+    return grub_errno;
+
+  if (cert_num < 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("Certificate number too small - numbers start at 1"));
+
+  if (cert_num == 1)
+    {
+      cert = grub_trusted_key;
+      grub_trusted_key = cert->next;
+
+      certificate_release (cert);
+      grub_free (cert);
+      return GRUB_ERR_NONE;
+    }
+  i = 2;
+  prev = grub_trusted_key;
+  cert = grub_trusted_key->next;
+  while (cert)
+    {
+      if (i == cert_num)
+        {
+          prev->next = cert->next;
+          certificate_release (cert);
+          grub_free (cert);
+          return GRUB_ERR_NONE;
+        }
+      i++;
+      prev = cert;
+      cert = cert->next;
+    }
+
+  return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                     N_("No certificate number %lu found - only %lu certificates in the store"),
+                     cert_num, i - 1);
+}
+
+static grub_err_t
+grub_cmd_trust (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
+{
+  grub_file_t certf;
+  struct x509_certificate *cert = NULL;
+  grub_err_t err;
+
+  if (argc != 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument expected"));
+
+  certf = grub_file_open (args[0], GRUB_FILE_TYPE_CERTIFICATE_TRUST | GRUB_FILE_TYPE_NO_DECOMPRESS);
+  if (!certf)
+    return grub_errno;
+
+  cert = grub_zalloc (sizeof (struct x509_certificate));
+  if (!cert)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("Could not allocate memory for certificate"));
+
+  err = read_cert_from_file (certf, cert);
+  grub_file_close (certf);
+  if (err != GRUB_ERR_NONE)
+    {
+      grub_free (cert);
+      return err;
+    }
+  grub_dprintf ("appendedsig", "Loaded certificate with CN: %s\n", cert->subject);
+
+  cert->next = grub_trusted_key;
+  grub_trusted_key = cert;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_cmd_list (grub_command_t cmd __attribute__ ((unused)), int argc __attribute__ ((unused)),
+               char **args __attribute__ ((unused)))
+{
+  struct x509_certificate *cert;
+  int cert_num = 1;
+  grub_size_t i;
+
+  for (cert = grub_trusted_key; cert; cert = cert->next)
+    {
+      grub_printf (N_("Certificate %d:\n"), cert_num);
+
+      grub_printf (N_("\tSerial: "));
+      for (i = 0; i < cert->serial_len - 1; i++)
+        {
+          grub_printf ("%02x:", cert->serial[i]);
+        }
+      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);
+
+      grub_printf ("\tCN: %s\n\n", cert->subject);
+      cert_num++;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+appendedsig_init (grub_file_t io __attribute__ ((unused)), enum grub_file_type type,
+                  void **context __attribute__ ((unused)), enum grub_verify_flags *flags)
+{
+  if (check_sigs == check_sigs_no)
+    {
+      *flags = GRUB_VERIFY_FLAGS_SKIP_VERIFICATION;
+      return GRUB_ERR_NONE;
+    }
+
+  switch (type & GRUB_FILE_TYPE_MASK)
+    {
+      case GRUB_FILE_TYPE_CERTIFICATE_TRUST:
+        /*
+         * This is a certificate to add to trusted keychain.
+         *
+         * This needs to be verified or blocked. Ideally we'd write an x509
+         * verifier, but we lack the hubris required to take this on. Instead,
+         * require that it have an appended signature.
+         */
+
+        /* Fall through */
+
+      case GRUB_FILE_TYPE_LINUX_KERNEL:
+      case GRUB_FILE_TYPE_GRUB_MODULE:
+        /*
+         * Appended signatures are only defined for ELF binaries.
+         * Out of an abundance of caution, we only verify Linux kernels and
+         * GRUB modules at this point.
+         */
+        *flags = GRUB_VERIFY_FLAGS_SINGLE_CHUNK;
+        return GRUB_ERR_NONE;
+
+      case GRUB_FILE_TYPE_ACPI_TABLE:
+      case GRUB_FILE_TYPE_DEVICE_TREE_IMAGE:
+        /*
+         * It is possible to use appended signature verification without
+         * lockdown - like the PGP verifier. When combined with an embedded
+         * config file in a signed grub binary, this could still be a meaningful
+         * secure-boot chain - so long as it isn't subverted by something like a
+         * rouge ACPI table or DT image. Defer them explicitly.
+         */
+        *flags = GRUB_VERIFY_FLAGS_DEFER_AUTH;
+        return GRUB_ERR_NONE;
+
+      default:
+        *flags = GRUB_VERIFY_FLAGS_SKIP_VERIFICATION;
+        return GRUB_ERR_NONE;
+    }
+}
+
+static grub_err_t
+appendedsig_write (void *ctxt __attribute__ ((unused)), void *buf, grub_size_t size)
+{
+  return grub_verify_appended_signature (buf, size);
+}
+
+struct grub_file_verifier grub_appendedsig_verifier = {
+  .name = "appendedsig",
+  .init = appendedsig_init,
+  .write = appendedsig_write,
+};
+
+static grub_ssize_t
+pseudo_read (struct grub_file *file, char *buf, grub_size_t len)
+{
+  grub_memcpy (buf, (grub_uint8_t *) file->data + file->offset, len);
+  return len;
+}
+
+/* Filesystem descriptor.  */
+static struct grub_fs pseudo_fs = { .name = "pseudo", .fs_read = pseudo_read };
+
+static grub_command_t cmd_verify, cmd_list, cmd_distrust, cmd_trust;
+
+GRUB_MOD_INIT (appendedsig)
+{
+  int rc;
+  struct grub_module_header *header;
+
+  /* If in lockdown, immediately enter forced mode */
+  if (grub_is_lockdown () == GRUB_LOCKDOWN_ENABLED)
+    check_sigs = check_sigs_forced;
+
+  grub_trusted_key = NULL;
+  grub_register_variable_hook ("check_appended_signatures", grub_env_read_sec, grub_env_write_sec);
+  grub_env_export ("check_appended_signatures");
+
+  rc = asn1_init ();
+  if (rc)
+    grub_fatal ("Error initing ASN.1 data structures: %d: %s\n", rc, asn1_strerror (rc));
+
+  FOR_MODULES (header)
+  {
+    struct grub_file pseudo_file;
+    struct x509_certificate *pk = NULL;
+    grub_err_t err;
+
+    /* Not an X.509 certificate, skip. */
+    if (header->type != OBJ_TYPE_X509_PUBKEY)
+      continue;
+
+    grub_memset (&pseudo_file, 0, sizeof (pseudo_file));
+    pseudo_file.fs = &pseudo_fs;
+    pseudo_file.size = header->size - sizeof (struct grub_module_header);
+    pseudo_file.data = (char *) header + sizeof (struct grub_module_header);
+
+    grub_dprintf ("appendedsig", "Found an x509 key, size=%" PRIuGRUB_UINT64_T "\n",
+                  pseudo_file.size);
+
+    pk = grub_zalloc (sizeof (struct x509_certificate));
+    if (!pk)
+      grub_fatal ("Out of memory loading initial certificates");
+
+    err = read_cert_from_file (&pseudo_file, pk);
+    if (err != GRUB_ERR_NONE)
+      grub_fatal ("Error loading initial key: %s", grub_errmsg);
+
+    grub_dprintf ("appendedsig", "loaded certificate CN='%s'\n", pk->subject);
+
+    pk->next = grub_trusted_key;
+    grub_trusted_key = pk;
+  }
+
+  cmd_trust = grub_register_command ("trust_certificate", grub_cmd_trust, N_("X509_CERTIFICATE"),
+                                     N_("Add X509_CERTIFICATE to trusted certificates."));
+  cmd_list = grub_register_command ("list_certificates", grub_cmd_list, 0,
+                                    N_("Show the list of trusted x509 certificates."));
+  cmd_verify = grub_register_command ("verify_appended", grub_cmd_verify_signature, N_("FILE"),
+                                      N_("Verify FILE against the trusted x509 certificates."));
+  cmd_distrust = grub_register_command ("distrust_certificate", grub_cmd_distrust,
+                                        N_("CERT_NUMBER"),
+                                        N_("Remove CERT_NUMBER (as listed by list_certificates)"
+                                           " from trusted certificates."));
+
+  grub_verifier_register (&grub_appendedsig_verifier);
+  grub_dl_set_persistent (mod);
+}
+
+GRUB_MOD_FINI (appendedsig)
+{
+  /*
+   * grub_dl_set_persistent should prevent this from actually running, but
+   * it does still run under emu.
+   */
+
+  grub_verifier_unregister (&grub_appendedsig_verifier);
+  grub_unregister_command (cmd_verify);
+  grub_unregister_command (cmd_list);
+  grub_unregister_command (cmd_trust);
+  grub_unregister_command (cmd_distrust);
+}
grub-core/commands/appendedsig/appendedsig.h +1 -1
index 3f4d7002e..9a30c3885 100644
@@ -18,7 +18,7 @@
  */
 
 #include <grub/crypto.h>
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 
 extern asn1_node _gnutls_gnutls_asn;
 extern asn1_node _gnutls_pkix_asn;
grub-core/commands/appendedsig/asn1util.c +1 -1
index 06c3b61c1..2e683c892 100644
@@ -17,7 +17,7 @@
  *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 #include <grub/types.h>
 #include <grub/err.h>
 #include <grub/mm.h>
grub-core/commands/appendedsig/gnutls_asn1_tab.c +1 -1
index ddd1314e6..8c4eb81d7 100644
@@ -1,5 +1,5 @@
 #include <grub/mm.h>
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 
 const asn1_static_node gnutls_asn1_tab[] = {
   { "GNUTLS", 536872976, NULL },
grub-core/commands/appendedsig/pkix_asn1_tab.c +1 -1
index adef69d95..8eeeac047 100644
@@ -1,5 +1,5 @@
 #include <grub/mm.h>
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 
 const asn1_static_node pkix_asn1_tab[] = {
   { "PKIX1", 536875024, NULL },
grub-core/commands/appendedsig/x509.c +1 -1
index eb87025c2..316e3035a 100644
@@ -17,7 +17,7 @@
  *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 #include <grub/types.h>
 #include <grub/err.h>
 #include <grub/mm.h>
include/grub/file.h +2 -0
index a5bf3a792..d678de063 100644
@@ -80,6 +80,8 @@ enum grub_file_type
     GRUB_FILE_TYPE_PUBLIC_KEY,
     /* File holding public key to add to trused keys.  */
     GRUB_FILE_TYPE_PUBLIC_KEY_TRUST,
+    /* File holding x509 certificiate to add to trusted keys.  */
+    GRUB_FILE_TYPE_CERTIFICATE_TRUST,
     /* File of which we intend to print a blocklist to the user.  */
     GRUB_FILE_TYPE_PRINT_BLOCKLIST,
     /* File we intend to use for test loading or testing speed.  */
Signature · 7 lines
2.43.5


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

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

author
#26 lore raw

Re: [PATCH v2 10/21] appended signatures: support verifying appended signatures

Quoted 15 lines · Gary Lin
Quoted 14 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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

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

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

Quoted 9 lines
Quoted 3 lines

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

IMO, the changes for libtasn1.h should be merged into the previous two patches since the path should be set correctly in the first place.

Gary Lin

Hi Gary Lin,
Thank you so much for a review!. I will do it.

Quoted 830 lines
Quoted 830 lines
---
 grub-core/Makefile.core.def                   |  14 +
 grub-core/commands/appendedsig/appendedsig.c  | 618 
++++++++++++++++++
 grub-core/commands/appendedsig/appendedsig.h  |   2 +-
 grub-core/commands/appendedsig/asn1util.c     |   2 +-
 .../commands/appendedsig/gnutls_asn1_tab.c    |   2 +-
 .../commands/appendedsig/pkix_asn1_tab.c      |   2 +-
 grub-core/commands/appendedsig/x509.c         |   2 +-
 include/grub/file.h                           |   2 +
 8 files changed, 639 insertions(+), 5 deletions(-)
 create mode 100644 grub-core/commands/appendedsig/appendedsig.c
grub-core/Makefile.core.def +14 -1
index 60db2adc5..d693986c6 100644
@@ -979,6 +979,20 @@ module = {
   cppflags = '-I$(srcdir)/lib/posix_wrap';
 };
 
+module = {
+  name = appendedsig;
+  common = commands/appendedsig/appendedsig.c;
+  common = commands/appendedsig/x509.c;
+  common = commands/appendedsig/pkcs7.c;
+  common = commands/appendedsig/asn1util.c;
+  common = commands/appendedsig/gnutls_asn1_tab.c;
+  common = commands/appendedsig/pkix_asn1_tab.c;
+
+  // posix wrapper required for gcry to get sys/types.h
+  cflags = '$(CFLAGS_POSIX)';
+  cppflags = '-I$(srcdir)/lib/posix_wrap 
-I$(srcdir)/lib/libtasn1-grub';
+};
+
 module = {
   name = hdparm;
   common = commands/hdparm.c;
grub-core/commands/appendedsig/appendedsig.c new file +7 -0
new file mode 100644
index 000000000..cbd227a3c
@@ -0,0 +1,618 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2021, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2021, 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.c new file +27 -0
+
+#include <grub/types.h>
+#include <grub/misc.h>
+#include <grub/mm.h>
+#include <grub/err.h>
+#include <grub/dl.h>
+#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/kernel.h>
+#include <grub/extcmd.h>
+#include <grub/verify.h>
+#include <libtasn1.h>
+#include <grub/env.h>
+#include <grub/lockdown.h>
+
+#include "appendedsig.h"
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+const char magic[] = "~Module signature appended~\n";
+
+/*
+ * This structure is extracted from scripts/sign-file.c in the linux 

kernel
+ * source. It was licensed as LGPLv2.1+, which is GPLv3+ compatible.
+ */

grub-core/commands/appendedsig/appendedsig.c new file +15 -0
+struct module_signature
+{
+  grub_uint8_t algo;       /* Public-key crypto algorithm [0] */
+  grub_uint8_t hash;       /* Digest algorithm [0] */
+  grub_uint8_t id_type;    /* Key identifier type [PKEY_ID_PKCS7] */
+  grub_uint8_t signer_len; /* Length of signer's name [0] */
+  grub_uint8_t key_id_len; /* Length of key identifier [0] */
+  grub_uint8_t __pad[3];
+  grub_uint32_t sig_len;   /* Length of signature data */
+} GRUB_PACKED;
+
+/* This represents an entire, parsed, appended signature */
+struct grub_appended_signature
+{
+  grub_size_t signature_len;            /* Length of PKCS#7 data + 

metadata + magic */
+ struct module_signature sig_metadata; /* Module signature metadata */

grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+  struct pkcs7_signedData pkcs7;        /* Parsed PKCS#7 data */
+};
+
+/* Trusted certificates for verifying appended signatures */
+struct x509_certificate *grub_trusted_key;
+
+/*
+ * Force gcry_rsa to be a module dependency.
+ *
+ * If we use grub_crypto_pk_rsa, then then the gcry_rsa module won't 

be built
+ * in if you add 'appendedsig' to grub-install --modules. You would need to
+ * add 'gcry_rsa' too. That's confusing and seems suboptimal, especially when
+ * we only support RSA.
+ *
+ * Dynamic loading also causes some concerns. We can't load gcry_rsa from the
+ * the filesystem after we install the verifier - we won't be able to verify
+ * it without having it already present. We also shouldn't load it before we
+ * install the verifier, because that would mean it wouldn't be verified - an
+ * attacker could insert any code they wanted into the module.
+ *
+ * So instead, reference the internal symbol from gcry_rsa. That creates a
+ * direct dependency on gcry_rsa, so it will be built in when this module
+ * is built in. Being built in (assuming the core image is itself signed!)
+ * also resolves our concerns about loading from the filesystem.
+ */

grub-core/commands/appendedsig/appendedsig.c new file +23 -0
+extern gcry_pk_spec_t _gcry_pubkey_spec_rsa;
+
+static enum
+{
+  check_sigs_no = 0,
+  check_sigs_enforce = 1,
+  check_sigs_forced = 2
+} check_sigs = check_sigs_no;
+
+static const char *
+grub_env_read_sec (struct grub_env_var *var __attribute__ ((unused)),
+                   const char *val __attribute__ ((unused)))
+{
+  if (check_sigs == check_sigs_forced)
+    return "forced";
+  else if (check_sigs == check_sigs_enforce)
+    return "enforce";
+  else
+    return "no";
+}
+
+static char *
+grub_env_write_sec (struct grub_env_var *var __attribute__ 

((unused)), const char *val)

grub-core/commands/appendedsig/appendedsig.c new file +17 -0
+{
+  /* Do not allow the value to be changed if set to forced */
+  if (check_sigs == check_sigs_forced)
+    return grub_strdup ("forced");
+
+  if ((*val == '2') || (*val == 'f'))
+    check_sigs = check_sigs_forced;
+  else if ((*val == '1') || (*val == 'e'))
+    check_sigs = check_sigs_enforce;
+  else if ((*val == '0') || (*val == 'n'))
+    check_sigs = check_sigs_no;
+
+  return grub_strdup (grub_env_read_sec (NULL, NULL));
+}
+
+static grub_err_t
+file_read_all (grub_file_t file, grub_uint8_t **buf, grub_size_t 

*len)

grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+{
+  grub_off_t full_file_size;
+  grub_size_t file_size, total_read_size = 0;
+  grub_ssize_t read_size;
+
+  full_file_size = grub_file_size (file);
+  if (full_file_size == GRUB_FILE_SIZE_UNKNOWN)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("Cannot read a file of unknown size into a 

buffer"));

grub-core/commands/appendedsig/appendedsig.c new file +4 -0
+
+  if (full_file_size > GRUB_SIZE_MAX)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+                       N_("File is too large to read: %" 

PRIuGRUB_UINT64_T " bytes"),

grub-core/commands/appendedsig/appendedsig.c new file +8 -0
+                       full_file_size);
+
+  file_size = (grub_size_t) full_file_size;
+
+  *buf = grub_malloc (file_size);
+  if (!*buf)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                       N_("Could not allocate file data buffer size 

%" PRIuGRUB_SIZE),

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+                       file_size);
+
+  while (total_read_size < file_size)
+    {
+      read_size = grub_file_read (file, *buf + total_read_size, 

file_size - total_read_size);

grub-core/commands/appendedsig/appendedsig.c new file +12 -0
+
+      if (read_size < 0)
+        {
+          grub_free (*buf);
+          return grub_errno;
+        }
+      else if (read_size == 0)
+        {
+          grub_free (*buf);
+          return grub_error (GRUB_ERR_IO,
+                             N_("Could not read full file size "
+                                "(%" PRIuGRUB_SIZE "), only %" 

PRIuGRUB_SIZE " bytes read"),

grub-core/commands/appendedsig/appendedsig.c new file +11 -0
+                             file_size, total_read_size);
+        }
+
+      total_read_size += read_size;
+    }
+  *len = file_size;
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+read_cert_from_file (grub_file_t f, struct x509_certificate 

*certificate)

grub-core/commands/appendedsig/appendedsig.c new file +17 -0
+{
+  grub_err_t err;
+  grub_uint8_t *buf;
+  grub_size_t file_size;
+
+  err = file_read_all (f, &buf, &file_size);
+  if (err != GRUB_ERR_NONE)
+    return err;
+
+  err = parse_x509_certificate (buf, file_size, certificate);
+  grub_free (buf);
+
+  return err;
+}
+
+static grub_err_t
+extract_appended_signature (const grub_uint8_t *buf, grub_size_t 

bufsize,

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+                            struct grub_appended_signature *sig)
+{
+  grub_size_t pkcs7_size;
+  grub_size_t remaining_len;
+  const grub_uint8_t *appsigdata = buf + bufsize - grub_strlen 

(magic);

grub-core/commands/appendedsig/appendedsig.c new file +3 -0
+
+  if (bufsize < grub_strlen (magic))
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for 

signature magic"));

grub-core/commands/appendedsig/appendedsig.c new file +2 -0
+
+  if (grub_memcmp (appsigdata, (grub_uint8_t *) magic, grub_strlen 

(magic)))
+ return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("Missing or invalid
signature magic"));

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+
+  remaining_len = bufsize - grub_strlen (magic);
+
+  if (remaining_len < sizeof (struct module_signature))
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for 

signature metadata"));

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+
+  appsigdata -= sizeof (struct module_signature);
+
+  /* extract the metadata */
+  grub_memcpy (&(sig->sig_metadata), appsigdata, sizeof (struct 

module_signature));

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+
+  remaining_len -= sizeof (struct module_signature);
+
+  if (sig->sig_metadata.id_type != 2)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("Wrong signature 

type"));

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+
+  pkcs7_size = grub_be_to_cpu32 (sig->sig_metadata.sig_len);
+
+  if (pkcs7_size > remaining_len)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for 

PKCS#7 message"));

grub-core/commands/appendedsig/appendedsig.c new file +2 -0
+
+  grub_dprintf ("appendedsig", "sig len %" PRIuGRUB_SIZE "\n", 

pkcs7_size);

grub-core/commands/appendedsig/appendedsig.c new file +2 -0
+
+  sig->signature_len = grub_strlen (magic) + sizeof (struct 

module_signature) + pkcs7_size;

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+
+  /* rewind pointer and parse pkcs7 data */
+  appsigdata -= pkcs7_size;
+
+  return parse_pkcs7_signedData (appsigdata, pkcs7_size, 

&sig->pkcs7);

grub-core/commands/appendedsig/appendedsig.c new file +4 -0
+}
+
+static grub_err_t
+grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t 

bufsize)

grub-core/commands/appendedsig/appendedsig.c new file +14 -0
+{
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_size_t datasize;
+  void *context;
+  unsigned char *hash;
+  gcry_mpi_t hashmpi;
+  gcry_err_code_t rc;
+  struct x509_certificate *pk;
+  struct grub_appended_signature sig;
+  struct pkcs7_signerInfo *si;
+  int i;
+
+  if (!grub_trusted_key)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("No trusted keys to 

verify against"));

grub-core/commands/appendedsig/appendedsig.c new file +13 -0
+
+  err = extract_appended_signature (buf, bufsize, &sig);
+  if (err != GRUB_ERR_NONE)
+    return err;
+
+  datasize = bufsize - sig.signature_len;
+
+  for (i = 0; i < sig.pkcs7.signerInfo_count; i++)
+    {
+      /*
+       * This could be optimised in a couple of ways:
+       * - we could only compute hashes once per hash type
+       * - we could track signer information and only verify where 

IDs match
+ * For now we do the naive O(trusted keys * pkcs7 signers)
approach.

grub-core/commands/appendedsig/appendedsig.c new file +12 -0
+       */
+      si = &sig.pkcs7.signerInfos[i];
+      context = grub_zalloc (si->hash->contextsize);
+      if (!context)
+        return grub_errno;
+
+      si->hash->init (context);
+      si->hash->write (context, buf, datasize);
+      si->hash->final (context);
+      hash = si->hash->read (context);
+
+      grub_dprintf ("appendedsig", "data size %" PRIxGRUB_SIZE ", 

signer %d hash %02x%02x%02x%02x...\n",

grub-core/commands/appendedsig/appendedsig.c new file +6 -0
+                    datasize, i, hash[0], hash[1], hash[2], hash[3]);
+
+      err = GRUB_ERR_BAD_SIGNATURE;
+      for (pk = grub_trusted_key; pk; pk = pk->next)
+        {
+          rc = grub_crypto_rsa_pad (&hashmpi, hash, si->hash, 

pk->mpis[0]);

grub-core/commands/appendedsig/appendedsig.c new file +4 -0
+          if (rc)
+            {
+              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                N_("Error padding hash for RSA 

verification: %d"), rc);

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+              grub_free (context);
+              goto cleanup;
+            }
+
+          rc = _gcry_pubkey_spec_rsa.verify (0, hashmpi, 

&si->sig_mpi, pk->mpis, NULL, NULL);

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+          gcry_mpi_release (hashmpi);
+
+          if (rc == 0)
+            {
+              grub_dprintf ("appendedsig", "verify signer %d with key 

'%s' succeeded\n",

grub-core/commands/appendedsig/appendedsig.c new file +6 -0
+                            i, pk->subject);
+              err = GRUB_ERR_NONE;
+              break;
+            }
+
+          grub_dprintf ("appendedsig", "verify signer %d with key 

'%s' failed with %d\n",

grub-core/commands/appendedsig/appendedsig.c new file +13 -0
+                        i, pk->subject, rc);
+        }
+
+      grub_free (context);
+
+      if (err == GRUB_ERR_NONE)
+        break;
+    }
+
+  /* If we didn't verify, provide a neat message */
+  if (err != GRUB_ERR_NONE)
+    err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                      N_("Failed to verify signature against a 

trusted key"));

grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+
+cleanup:
+  pkcs7_signedData_release (&sig.pkcs7);
+
+  return err;
+}
+
+static grub_err_t
+grub_cmd_verify_signature (grub_command_t cmd __attribute__ 

((unused)), int argc, char **args)

grub-core/commands/appendedsig/appendedsig.c new file +8 -0
+{
+  grub_file_t f;
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_uint8_t *data;
+  grub_size_t file_size;
+
+  if (argc < 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument 

expected"));

grub-core/commands/appendedsig/appendedsig.c new file +26 -0
+
+  grub_dprintf ("appendedsig", "verifying %s\n", args[0]);
+
+  f = grub_file_open (args[0], GRUB_FILE_TYPE_VERIFY_SIGNATURE);
+  if (!f)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }
+
+  err = file_read_all (f, &data, &file_size);
+  if (err != GRUB_ERR_NONE)
+    goto cleanup;
+
+  err = grub_verify_appended_signature (data, file_size);
+
+  grub_free (data);
+
+cleanup:
+  if (f)
+    grub_file_close (f);
+  return err;
+}
+
+static grub_err_t
+grub_cmd_distrust (grub_command_t cmd __attribute__ ((unused)), int 

argc, char **args)

grub-core/commands/appendedsig/appendedsig.c new file +6 -0
+{
+  unsigned long cert_num, i;
+  struct x509_certificate *cert, *prev;
+
+  if (argc != 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("One argument 

expected"));

grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+
+  grub_errno = GRUB_ERR_NONE;
+  cert_num = grub_strtoul (args[0], NULL, 10);
+  if (grub_errno != GRUB_ERR_NONE)
+    return grub_errno;
+
+  if (cert_num < 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("Certificate number too small - numbers 

start at 1"));

grub-core/commands/appendedsig/appendedsig.c new file +29 -0
+
+  if (cert_num == 1)
+    {
+      cert = grub_trusted_key;
+      grub_trusted_key = cert->next;
+
+      certificate_release (cert);
+      grub_free (cert);
+      return GRUB_ERR_NONE;
+    }
+  i = 2;
+  prev = grub_trusted_key;
+  cert = grub_trusted_key->next;
+  while (cert)
+    {
+      if (i == cert_num)
+        {
+          prev->next = cert->next;
+          certificate_release (cert);
+          grub_free (cert);
+          return GRUB_ERR_NONE;
+        }
+      i++;
+      prev = cert;
+      cert = cert->next;
+    }
+
+  return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                     N_("No certificate number %lu found - only %lu 

certificates in the store"),

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+                     cert_num, i - 1);
+}
+
+static grub_err_t
+grub_cmd_trust (grub_command_t cmd __attribute__ ((unused)), int 

argc, char **args)

grub-core/commands/appendedsig/appendedsig.c new file +7 -0
+{
+  grub_file_t certf;
+  struct x509_certificate *cert = NULL;
+  grub_err_t err;
+
+  if (argc != 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument 

expected"));

grub-core/commands/appendedsig/appendedsig.c new file +2 -0
+
+  certf = grub_file_open (args[0], GRUB_FILE_TYPE_CERTIFICATE_TRUST | 

GRUB_FILE_TYPE_NO_DECOMPRESS);

grub-core/commands/appendedsig/appendedsig.c new file +6 -0
+  if (!certf)
+    return grub_errno;
+
+  cert = grub_zalloc (sizeof (struct x509_certificate));
+  if (!cert)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("Could not allocate 

memory for certificate"));

grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+
+  err = read_cert_from_file (certf, cert);
+  grub_file_close (certf);
+  if (err != GRUB_ERR_NONE)
+    {
+      grub_free (cert);
+      return err;
+    }
+  grub_dprintf ("appendedsig", "Loaded certificate with CN: %s\n", 

cert->subject);

grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+
+  cert->next = grub_trusted_key;
+  grub_trusted_key = cert;
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_cmd_list (grub_command_t cmd __attribute__ ((unused)), int argc 

__attribute__ ((unused)),

grub-core/commands/appendedsig/appendedsig.c new file +26 -0
+               char **args __attribute__ ((unused)))
+{
+  struct x509_certificate *cert;
+  int cert_num = 1;
+  grub_size_t i;
+
+  for (cert = grub_trusted_key; cert; cert = cert->next)
+    {
+      grub_printf (N_("Certificate %d:\n"), cert_num);
+
+      grub_printf (N_("\tSerial: "));
+      for (i = 0; i < cert->serial_len - 1; i++)
+        {
+          grub_printf ("%02x:", cert->serial[i]);
+        }
+      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);
+
+      grub_printf ("\tCN: %s\n\n", cert->subject);
+      cert_num++;
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+appendedsig_init (grub_file_t io __attribute__ ((unused)), enum 

grub_file_type type,
+ void **context __attribute__ ((unused)), enum
grub_verify_flags *flags)

grub-core/commands/appendedsig/appendedsig.c new file +14 -0
+{
+  if (check_sigs == check_sigs_no)
+    {
+      *flags = GRUB_VERIFY_FLAGS_SKIP_VERIFICATION;
+      return GRUB_ERR_NONE;
+    }
+
+  switch (type & GRUB_FILE_TYPE_MASK)
+    {
+      case GRUB_FILE_TYPE_CERTIFICATE_TRUST:
+        /*
+         * This is a certificate to add to trusted keychain.
+         *
+         * This needs to be verified or blocked. Ideally we'd write 

an x509
+ * verifier, but we lack the hubris required to take this on.
Instead,

grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+         * require that it have an appended signature.
+         */
+
+        /* Fall through */
+
+      case GRUB_FILE_TYPE_LINUX_KERNEL:
+      case GRUB_FILE_TYPE_GRUB_MODULE:
+        /*
+         * Appended signatures are only defined for ELF binaries.
+         * Out of an abundance of caution, we only verify Linux 

kernels and

grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+         * GRUB modules at this point.
+         */
+        *flags = GRUB_VERIFY_FLAGS_SINGLE_CHUNK;
+        return GRUB_ERR_NONE;
+
+      case GRUB_FILE_TYPE_ACPI_TABLE:
+      case GRUB_FILE_TYPE_DEVICE_TREE_IMAGE:
+        /*
+         * It is possible to use appended signature verification 

without
+ * lockdown - like the PGP verifier. When combined with an
embedded
+ * config file in a signed grub binary, this could still be a
meaningful
+ * secure-boot chain - so long as it isn't subverted by
something like a

grub-core/commands/appendedsig/appendedsig.c new file +13 -0
+         * rouge ACPI table or DT image. Defer them explicitly.
+         */
+        *flags = GRUB_VERIFY_FLAGS_DEFER_AUTH;
+        return GRUB_ERR_NONE;
+
+      default:
+        *flags = GRUB_VERIFY_FLAGS_SKIP_VERIFICATION;
+        return GRUB_ERR_NONE;
+    }
+}
+
+static grub_err_t
+appendedsig_write (void *ctxt __attribute__ ((unused)), void *buf, 

grub_size_t size)

grub-core/commands/appendedsig/appendedsig.c new file +19 -0
+{
+  return grub_verify_appended_signature (buf, size);
+}
+
+struct grub_file_verifier grub_appendedsig_verifier = {
+  .name = "appendedsig",
+  .init = appendedsig_init,
+  .write = appendedsig_write,
+};
+
+static grub_ssize_t
+pseudo_read (struct grub_file *file, char *buf, grub_size_t len)
+{
+  grub_memcpy (buf, (grub_uint8_t *) file->data + file->offset, len);
+  return len;
+}
+
+/* Filesystem descriptor.  */
+static struct grub_fs pseudo_fs = { .name = "pseudo", .fs_read = 

pseudo_read };

grub-core/commands/appendedsig/appendedsig.c new file +14 -0
+
+static grub_command_t cmd_verify, cmd_list, cmd_distrust, cmd_trust;
+
+GRUB_MOD_INIT (appendedsig)
+{
+  int rc;
+  struct grub_module_header *header;
+
+  /* If in lockdown, immediately enter forced mode */
+  if (grub_is_lockdown () == GRUB_LOCKDOWN_ENABLED)
+    check_sigs = check_sigs_forced;
+
+  grub_trusted_key = NULL;
+  grub_register_variable_hook ("check_appended_signatures", 

grub_env_read_sec, grub_env_write_sec);

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+  grub_env_export ("check_appended_signatures");
+
+  rc = asn1_init ();
+  if (rc)
+    grub_fatal ("Error initing ASN.1 data structures: %d: %s\n", rc, 

asn1_strerror (rc));

grub-core/commands/appendedsig/appendedsig.c new file +14 -0
+
+  FOR_MODULES (header)
+  {
+    struct grub_file pseudo_file;
+    struct x509_certificate *pk = NULL;
+    grub_err_t err;
+
+    /* Not an X.509 certificate, skip. */
+    if (header->type != OBJ_TYPE_X509_PUBKEY)
+      continue;
+
+    grub_memset (&pseudo_file, 0, sizeof (pseudo_file));
+    pseudo_file.fs = &pseudo_fs;
+    pseudo_file.size = header->size - sizeof (struct 

grub_module_header);
+ pseudo_file.data = (char *) header + sizeof (struct
grub_module_header);

grub-core/commands/appendedsig/appendedsig.c new file +2 -0
+
+    grub_dprintf ("appendedsig", "Found an x509 key, size=%" 

PRIuGRUB_UINT64_T "\n",

grub-core/commands/appendedsig/appendedsig.c new file +11 -0
+                  pseudo_file.size);
+
+    pk = grub_zalloc (sizeof (struct x509_certificate));
+    if (!pk)
+      grub_fatal ("Out of memory loading initial certificates");
+
+    err = read_cert_from_file (&pseudo_file, pk);
+    if (err != GRUB_ERR_NONE)
+      grub_fatal ("Error loading initial key: %s", grub_errmsg);
+
+    grub_dprintf ("appendedsig", "loaded certificate CN='%s'\n", 

pk->subject);

grub-core/commands/appendedsig/appendedsig.c new file +6 -0
+
+    pk->next = grub_trusted_key;
+    grub_trusted_key = pk;
+  }
+
+  cmd_trust = grub_register_command ("trust_certificate", 

grub_cmd_trust, N_("X509_CERTIFICATE"),
+ N_("Add X509_CERTIFICATE to
trusted certificates."));
+ cmd_list = grub_register_command ("list_certificates", grub_cmd_list, 0,
+ N_("Show the list of trusted x509
certificates."));
+ cmd_verify = grub_register_command ("verify_appended", grub_cmd_verify_signature, N_("FILE"),
+ N_("Verify FILE against the
trusted x509 certificates."));
+ cmd_distrust = grub_register_command ("distrust_certificate", grub_cmd_distrust,

grub-core/commands/appendedsig/appendedsig.c new file +2 -0
+                                        N_("CERT_NUMBER"),
+                                        N_("Remove CERT_NUMBER (as 

listed by list_certificates)"
+ " from trusted
certificates."));

grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+
+  grub_verifier_register (&grub_appendedsig_verifier);
+  grub_dl_set_persistent (mod);
+}
+
+GRUB_MOD_FINI (appendedsig)
+{
+  /*
+   * grub_dl_set_persistent should prevent this from actually 

running, but

grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+   * it does still run under emu.
+   */
+
+  grub_verifier_unregister (&grub_appendedsig_verifier);
+  grub_unregister_command (cmd_verify);
+  grub_unregister_command (cmd_list);
+  grub_unregister_command (cmd_trust);
+  grub_unregister_command (cmd_distrust);
+}
grub-core/commands/appendedsig/appendedsig.h +1 -1
index 3f4d7002e..9a30c3885 100644
@@ -18,7 +18,7 @@
  */
 
 #include <grub/crypto.h>
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 
 extern asn1_node _gnutls_gnutls_asn;
 extern asn1_node _gnutls_pkix_asn;
grub-core/commands/appendedsig/asn1util.c +1 -1
index 06c3b61c1..2e683c892 100644
@@ -17,7 +17,7 @@
  *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 #include <grub/types.h>
 #include <grub/err.h>
 #include <grub/mm.h>
grub-core/commands/appendedsig/gnutls_asn1_tab.c +1 -1
index ddd1314e6..8c4eb81d7 100644
@@ -1,5 +1,5 @@
 #include <grub/mm.h>
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 
 const asn1_static_node gnutls_asn1_tab[] = {
   { "GNUTLS", 536872976, NULL },
grub-core/commands/appendedsig/pkix_asn1_tab.c +1 -1
index adef69d95..8eeeac047 100644
@@ -1,5 +1,5 @@
 #include <grub/mm.h>
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 
 const asn1_static_node pkix_asn1_tab[] = {
   { "PKIX1", 536875024, NULL },
grub-core/commands/appendedsig/x509.c +1 -1
index eb87025c2..316e3035a 100644
@@ -17,7 +17,7 @@
  *  along with GRUB.  If not, see <http://www.gnu.org/licenses/>.
  */
 
-#include <grub/libtasn1.h>
+#include <libtasn1.h>
 #include <grub/types.h>
 #include <grub/err.h>
 #include <grub/mm.h>
include/grub/file.h +2 -1
index a5bf3a792..d678de063 100644
@@ -80,6 +80,8 @@ enum grub_file_type
     GRUB_FILE_TYPE_PUBLIC_KEY,
     /* File holding public key to add to trused keys.  */
     GRUB_FILE_TYPE_PUBLIC_KEY_TRUST,
+    /* File holding x509 certificiate to add to trusted keys.  */
+    GRUB_FILE_TYPE_CERTIFICATE_TRUST,
     /* File of which we intend to print a blocklist to the user.  */
     GRUB_FILE_TYPE_PRINT_BLOCKLIST,
     /* File we intend to use for test loading or testing speed.  */
--

2.43.5

Quoted 4 lines
Quoted 4 lines

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

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

#27 lore raw

Re: [PATCH v2 10/21] appended signatures: support verifying appended signatures

In reply to Sudhakar Kuppusamy
Quoted 22 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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

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

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

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

Quoted 8 lines
---
 grub-core/Makefile.core.def                   |  14 +
 grub-core/commands/appendedsig/appendedsig.c  | 618 ++++++++++++++++++
 grub-core/commands/appendedsig/appendedsig.h  |   2 +-
 grub-core/commands/appendedsig/asn1util.c     |   2 +-
 .../commands/appendedsig/gnutls_asn1_tab.c    |   2 +-
 .../commands/appendedsig/pkix_asn1_tab.c      |   2 +-
 grub-core/commands/appendedsig/x509.c         |   2 +-

Please take into account Gary's comment...

Quoted 67 lines
 include/grub/file.h                           |   2 +
 8 files changed, 639 insertions(+), 5 deletions(-)
 create mode 100644 grub-core/commands/appendedsig/appendedsig.c
grub-core/Makefile.core.def +14 -0
index 60db2adc5..d693986c6 100644
@@ -979,6 +979,20 @@ module = {
   cppflags = '-I$(srcdir)/lib/posix_wrap';
 };
 
+module = {
+  name = appendedsig;
+  common = commands/appendedsig/appendedsig.c;
+  common = commands/appendedsig/x509.c;
+  common = commands/appendedsig/pkcs7.c;
+  common = commands/appendedsig/asn1util.c;
+  common = commands/appendedsig/gnutls_asn1_tab.c;
+  common = commands/appendedsig/pkix_asn1_tab.c;
+
+  // posix wrapper required for gcry to get sys/types.h
+  cflags = '$(CFLAGS_POSIX)';
+  cppflags = '-I$(srcdir)/lib/posix_wrap -I$(srcdir)/lib/libtasn1-grub';
+};
+
 module = {
   name = hdparm;
   common = commands/hdparm.c;
grub-core/commands/appendedsig/appendedsig.c new file +32 -0
new file mode 100644
index 000000000..cbd227a3c
@@ -0,0 +1,618 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2021, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2021, 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/types.h>
+#include <grub/misc.h>
+#include <grub/mm.h>
+#include <grub/err.h>
+#include <grub/dl.h>
+#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/kernel.h>
+#include <grub/extcmd.h>

grub-core/commands/appendedsig/appendedsig.c line 42

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+#include <grub/verify.h>
+#include <libtasn1.h>
+#include <grub/env.h>
+#include <grub/lockdown.h>
+
+#include "appendedsig.h"
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+const char magic[] = "~Module signature appended~\n";

static const char magic[]...?

Quoted 36 lines
grub-core/commands/appendedsig/appendedsig.c new file +36 -0
+/*
+ * This structure is extracted from scripts/sign-file.c in the linux kernel
+ * source. It was licensed as LGPLv2.1+, which is GPLv3+ compatible.
+ */
+struct module_signature
+{
+  grub_uint8_t algo;       /* Public-key crypto algorithm [0] */
+  grub_uint8_t hash;       /* Digest algorithm [0] */
+  grub_uint8_t id_type;    /* Key identifier type [PKEY_ID_PKCS7] */
+  grub_uint8_t signer_len; /* Length of signer's name [0] */
+  grub_uint8_t key_id_len; /* Length of key identifier [0] */
+  grub_uint8_t __pad[3];
+  grub_uint32_t sig_len;   /* Length of signature data */
+} GRUB_PACKED;
+
+/* This represents an entire, parsed, appended signature */
+struct grub_appended_signature
+{
+  grub_size_t signature_len;            /* Length of PKCS#7 data + metadata + magic */
+  struct module_signature sig_metadata; /* Module signature metadata */
+  struct pkcs7_signedData pkcs7;        /* Parsed PKCS#7 data */
+};
+
+/* Trusted certificates for verifying appended signatures */
+struct x509_certificate *grub_trusted_key;
+
+/*
+ * Force gcry_rsa to be a module dependency.
+ *
+ * If we use grub_crypto_pk_rsa, then then the gcry_rsa module won't be built
+ * in if you add 'appendedsig' to grub-install --modules. You would need to
+ * add 'gcry_rsa' too. That's confusing and seems suboptimal, especially when
+ * we only support RSA.
+ *
+ * Dynamic loading also causes some concerns. We can't load gcry_rsa from the
+ * the filesystem after we install the verifier - we won't be able to verify

grub-core/commands/appendedsig/appendedsig.c line 89

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+ * it without having it already present. We also shouldn't load it before we
+ * install the verifier, because that would mean it wouldn't be verified - an
+ * attacker could insert any code they wanted into the module.
+ *
+ * So instead, reference the internal symbol from gcry_rsa. That creates a
+ * direct dependency on gcry_rsa, so it will be built in when this module
+ * is built in. Being built in (assuming the core image is itself signed!)
+ * also resolves our concerns about loading from the filesystem.
+ */
+extern gcry_pk_spec_t _gcry_pubkey_spec_rsa;

Please take a look at the commit 6744840b1 (build: Track explicit module dependencies in Makefile.core.def) and use "depends" instead.

I think I saw similar things in earlier patches. If it is the same case please fix the other issues as above...

grub-core/commands/appendedsig/appendedsig.c line 95

Quoted 5 lines
grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+static enum
+{
+  check_sigs_no = 0,
+  check_sigs_enforce = 1,
+  check_sigs_forced = 2

Please use uppercase for all these constants.

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+} check_sigs = check_sigs_no;
+
+static const char *
+grub_env_read_sec (struct grub_env_var *var __attribute__ ((unused)),
+                   const char *val __attribute__ ((unused)))
+{
+  if (check_sigs == check_sigs_forced)
+    return "forced";
+  else if (check_sigs == check_sigs_enforce)
+    return "enforce";

grub-core/commands/appendedsig/appendedsig.c line 115

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+  else
+    return "no";
+}
+
+static char *
+grub_env_write_sec (struct grub_env_var *var __attribute__ ((unused)), const char *val)
+{
+  /* Do not allow the value to be changed if set to forced */
+  if (check_sigs == check_sigs_forced)
+    return grub_strdup ("forced");

grub_strdup() may fail...

grub-core/commands/appendedsig/appendedsig.c line 124

Quoted 9 lines
grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+
+  if ((*val == '2') || (*val == 'f'))
+    check_sigs = check_sigs_forced;
+  else if ((*val == '1') || (*val == 'e'))
+    check_sigs = check_sigs_enforce;
+  else if ((*val == '0') || (*val == 'n'))
+    check_sigs = check_sigs_no;
+
+  return grub_strdup (grub_env_read_sec (NULL, NULL));

Ditto...

Quoted 32 lines
grub-core/commands/appendedsig/appendedsig.c new file +32 -0
+}
+
+static grub_err_t
+file_read_all (grub_file_t file, grub_uint8_t **buf, grub_size_t *len)
+{
+  grub_off_t full_file_size;
+  grub_size_t file_size, total_read_size = 0;
+  grub_ssize_t read_size;
+
+  full_file_size = grub_file_size (file);
+  if (full_file_size == GRUB_FILE_SIZE_UNKNOWN)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("Cannot read a file of unknown size into a buffer"));
+
+  if (full_file_size > GRUB_SIZE_MAX)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+                       N_("File is too large to read: %" PRIuGRUB_UINT64_T " bytes"),
+                       full_file_size);
+
+  file_size = (grub_size_t) full_file_size;
+
+  *buf = grub_malloc (file_size);
+  if (!*buf)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                       N_("Could not allocate file data buffer size %" PRIuGRUB_SIZE),
+                       file_size);
+
+  while (total_read_size < file_size)
+    {
+      read_size = grub_file_read (file, *buf + total_read_size, file_size - total_read_size);
+
+      if (read_size < 0)

grub-core/commands/appendedsig/appendedsig.c line 166

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+        {
+          grub_free (*buf);
+          return grub_errno;
+        }
+      else if (read_size == 0)
+        {
+          grub_free (*buf);
+          return grub_error (GRUB_ERR_IO,
+                             N_("Could not read full file size "
+                                "(%" PRIuGRUB_SIZE "), only %" PRIuGRUB_SIZE " bytes read"),

Be careful, you cannot use PRIuGRUB_SIZE conversions in N_(). Though I would suggest to drop N_() here and from cryptic error messages which should be targeted only for experts. And probably it would be better to add file path to this error message.

Quoted 112 lines
grub-core/commands/appendedsig/appendedsig.c new file +112 -0
+                             file_size, total_read_size);
+        }
+
+      total_read_size += read_size;
+    }
+  *len = file_size;
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+read_cert_from_file (grub_file_t f, struct x509_certificate *certificate)
+{
+  grub_err_t err;
+  grub_uint8_t *buf;
+  grub_size_t file_size;
+
+  err = file_read_all (f, &buf, &file_size);
+  if (err != GRUB_ERR_NONE)
+    return err;
+
+  err = parse_x509_certificate (buf, file_size, certificate);
+  grub_free (buf);
+
+  return err;
+}
+
+static grub_err_t
+extract_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize,
+                            struct grub_appended_signature *sig)
+{
+  grub_size_t pkcs7_size;
+  grub_size_t remaining_len;
+  const grub_uint8_t *appsigdata = buf + bufsize - grub_strlen (magic);
+
+  if (bufsize < grub_strlen (magic))
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for signature magic"));
+
+  if (grub_memcmp (appsigdata, (grub_uint8_t *) magic, grub_strlen (magic)))
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("Missing or invalid signature magic"));
+
+  remaining_len = bufsize - grub_strlen (magic);
+
+  if (remaining_len < sizeof (struct module_signature))
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for signature metadata"));
+
+  appsigdata -= sizeof (struct module_signature);
+
+  /* extract the metadata */
+  grub_memcpy (&(sig->sig_metadata), appsigdata, sizeof (struct module_signature));
+
+  remaining_len -= sizeof (struct module_signature);
+
+  if (sig->sig_metadata.id_type != 2)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("Wrong signature type"));
+
+  pkcs7_size = grub_be_to_cpu32 (sig->sig_metadata.sig_len);
+
+  if (pkcs7_size > remaining_len)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for PKCS#7 message"));
+
+  grub_dprintf ("appendedsig", "sig len %" PRIuGRUB_SIZE "\n", pkcs7_size);
+
+  sig->signature_len = grub_strlen (magic) + sizeof (struct module_signature) + pkcs7_size;
+
+  /* rewind pointer and parse pkcs7 data */
+  appsigdata -= pkcs7_size;
+
+  return parse_pkcs7_signedData (appsigdata, pkcs7_size, &sig->pkcs7);
+}
+
+static grub_err_t
+grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize)
+{
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_size_t datasize;
+  void *context;
+  unsigned char *hash;
+  gcry_mpi_t hashmpi;
+  gcry_err_code_t rc;
+  struct x509_certificate *pk;
+  struct grub_appended_signature sig;
+  struct pkcs7_signerInfo *si;
+  int i;
+
+  if (!grub_trusted_key)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("No trusted keys to verify against"));
+
+  err = extract_appended_signature (buf, bufsize, &sig);
+  if (err != GRUB_ERR_NONE)
+    return err;
+
+  datasize = bufsize - sig.signature_len;
+
+  for (i = 0; i < sig.pkcs7.signerInfo_count; i++)
+    {
+      /*
+       * This could be optimised in a couple of ways:
+       * - we could only compute hashes once per hash type
+       * - we could track signer information and only verify where IDs match
+       * For now we do the naive O(trusted keys * pkcs7 signers) approach.
+       */
+      si = &sig.pkcs7.signerInfos[i];
+      context = grub_zalloc (si->hash->contextsize);
+      if (!context)
+        return grub_errno;
+
+      si->hash->init (context);
+      si->hash->write (context, buf, datasize);
+      si->hash->final (context);
+      hash = si->hash->read (context);
+
+      grub_dprintf ("appendedsig", "data size %" PRIxGRUB_SIZE ", signer %d hash %02x%02x%02x%02x...\n",

grub-core/commands/appendedsig/appendedsig.c line 288

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+                    datasize, i, hash[0], hash[1], hash[2], hash[3]);
+
+      err = GRUB_ERR_BAD_SIGNATURE;
+      for (pk = grub_trusted_key; pk; pk = pk->next)
+        {
+          rc = grub_crypto_rsa_pad (&hashmpi, hash, si->hash, pk->mpis[0]);
+          if (rc)
+            {
+              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                N_("Error padding hash for RSA verification: %d"), rc);

Is gcry_err_code_t always equal int type? Even if yes it would be nice to cast rc to int. And I would drop N_() here.

Quoted 21 lines
grub-core/commands/appendedsig/appendedsig.c new file +21 -0
+              grub_free (context);
+              goto cleanup;
+            }
+
+          rc = _gcry_pubkey_spec_rsa.verify (0, hashmpi, &si->sig_mpi, pk->mpis, NULL, NULL);
+          gcry_mpi_release (hashmpi);
+
+          if (rc == 0)
+            {
+              grub_dprintf ("appendedsig", "verify signer %d with key '%s' succeeded\n",
+                            i, pk->subject);
+              err = GRUB_ERR_NONE;
+              break;
+            }
+
+          grub_dprintf ("appendedsig", "verify signer %d with key '%s' failed with %d\n",
+                        i, pk->subject, rc);
+        }
+
+      grub_free (context);
+

grub-core/commands/appendedsig/appendedsig.c line 319

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+      if (err == GRUB_ERR_NONE)
+        break;
+    }
+
+  /* If we didn't verify, provide a neat message */
+  if (err != GRUB_ERR_NONE)
+    err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                      N_("Failed to verify signature against a trusted key"));
+
+cleanup:

Missing space before label.

Quoted 24 lines
grub-core/commands/appendedsig/appendedsig.c new file +24 -0
+  pkcs7_signedData_release (&sig.pkcs7);
+
+  return err;
+}
+
+static grub_err_t
+grub_cmd_verify_signature (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
+{
+  grub_file_t f;
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_uint8_t *data;
+  grub_size_t file_size;
+
+  if (argc < 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument expected"));
+
+  grub_dprintf ("appendedsig", "verifying %s\n", args[0]);
+
+  f = grub_file_open (args[0], GRUB_FILE_TYPE_VERIFY_SIGNATURE);
+  if (!f)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }

grub-core/commands/appendedsig/appendedsig.c line 353

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+
+  err = file_read_all (f, &data, &file_size);
+  if (err != GRUB_ERR_NONE)
+    goto cleanup;
+
+  err = grub_verify_appended_signature (data, file_size);
+
+  grub_free (data);
+
+cleanup:

Ditto...

Quoted 8 lines
grub-core/commands/appendedsig/appendedsig.c new file +8 -0
+  if (f)
+    grub_file_close (f);
+  return err;
+}
+
+static grub_err_t
+grub_cmd_distrust (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
+{

grub-core/commands/appendedsig/appendedsig.c line 371

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+  unsigned long cert_num, i;
+  struct x509_certificate *cert, *prev;
+
+  if (argc != 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("One argument expected"));
+
+  grub_errno = GRUB_ERR_NONE;
+  cert_num = grub_strtoul (args[0], NULL, 10);
+  if (grub_errno != GRUB_ERR_NONE)
+    return grub_errno;

This check is unreliable. Please take a look at commit ac8a37dda (net/http: Allow use of non-standard TCP/IP ports) and fix checks for all grub_strtoul() et consortes calls.

Daniel

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

author
#28 lore raw

Re: [PATCH v2 10/21] appended signatures: support verifying appended signatures

Hi Daniel,

Thank you for your valuable review.
addressed all your review comments in v3.

Thanks,
sudhakar Kuppusamy

Quoted 529 lines · Daniel Kiper
Quoted 22 lines · Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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

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

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

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

Quoted 9 lines
---
 grub-core/Makefile.core.def                   |  14 +
 grub-core/commands/appendedsig/appendedsig.c  | 618 
++++++++++++++++++
 grub-core/commands/appendedsig/appendedsig.h  |   2 +-
 grub-core/commands/appendedsig/asn1util.c     |   2 +-
 .../commands/appendedsig/gnutls_asn1_tab.c    |   2 +-
 .../commands/appendedsig/pkix_asn1_tab.c      |   2 +-
 grub-core/commands/appendedsig/x509.c         |   2 +-

Please take into account Gary's comment...

Quoted 69 lines
 include/grub/file.h                           |   2 +
 8 files changed, 639 insertions(+), 5 deletions(-)
 create mode 100644 grub-core/commands/appendedsig/appendedsig.c
grub-core/Makefile.core.def +14 -1
index 60db2adc5..d693986c6 100644
@@ -979,6 +979,20 @@ module = {
   cppflags = '-I$(srcdir)/lib/posix_wrap';
 };
 
+module = {
+  name = appendedsig;
+  common = commands/appendedsig/appendedsig.c;
+  common = commands/appendedsig/x509.c;
+  common = commands/appendedsig/pkcs7.c;
+  common = commands/appendedsig/asn1util.c;
+  common = commands/appendedsig/gnutls_asn1_tab.c;
+  common = commands/appendedsig/pkix_asn1_tab.c;
+
+  // posix wrapper required for gcry to get sys/types.h
+  cflags = '$(CFLAGS_POSIX)';
+  cppflags = '-I$(srcdir)/lib/posix_wrap 
-I$(srcdir)/lib/libtasn1-grub';
+};
+
 module = {
   name = hdparm;
   common = commands/hdparm.c;
grub-core/commands/appendedsig/appendedsig.c new file +7 -0
new file mode 100644
index 000000000..cbd227a3c
@@ -0,0 +1,618 @@
+/*
+ *  GRUB  --  GRand Unified Bootloader
+ *  Copyright (C) 2020, 2021, 2022 Free Software Foundation, Inc.
+ *  Copyright (C) 2020, 2021, 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.c new file +14 -0
+
+#include <grub/types.h>
+#include <grub/misc.h>
+#include <grub/mm.h>
+#include <grub/err.h>
+#include <grub/dl.h>
+#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/kernel.h>
+#include <grub/extcmd.h>

grub-core/commands/appendedsig/appendedsig.c line 42

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+#include <grub/verify.h>
+#include <libtasn1.h>
+#include <grub/env.h>
+#include <grub/lockdown.h>
+
+#include "appendedsig.h"
+
+GRUB_MOD_LICENSE ("GPLv3+");
+
+const char magic[] = "~Module signature appended~\n";

static const char magic[]...?

Quoted 51 lines

+/*
+ * This structure is extracted from scripts/sign-file.c in the linux kernel
+ * source. It was licensed as LGPLv2.1+, which is GPLv3+ compatible.
+ */

grub-core/commands/appendedsig/appendedsig.c new file +15 -0
+struct module_signature
+{
+  grub_uint8_t algo;       /* Public-key crypto algorithm [0] */
+  grub_uint8_t hash;       /* Digest algorithm [0] */
+  grub_uint8_t id_type;    /* Key identifier type [PKEY_ID_PKCS7] */
+  grub_uint8_t signer_len; /* Length of signer's name [0] */
+  grub_uint8_t key_id_len; /* Length of key identifier [0] */
+  grub_uint8_t __pad[3];
+  grub_uint32_t sig_len;   /* Length of signature data */
+} GRUB_PACKED;
+
+/* This represents an entire, parsed, appended signature */
+struct grub_appended_signature
+{
+  grub_size_t signature_len;            /* Length of PKCS#7 data + 

metadata + magic */
+ struct module_signature sig_metadata; /* Module signature metadata */

grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+  struct pkcs7_signedData pkcs7;        /* Parsed PKCS#7 data */
+};
+
+/* Trusted certificates for verifying appended signatures */
+struct x509_certificate *grub_trusted_key;
+
+/*
+ * Force gcry_rsa to be a module dependency.
+ *
+ * If we use grub_crypto_pk_rsa, then then the gcry_rsa module won't 

be built
+ * in if you add 'appendedsig' to grub-install --modules. You would need to
+ * add 'gcry_rsa' too. That's confusing and seems suboptimal, especially when
+ * we only support RSA.
+ *
+ * Dynamic loading also causes some concerns. We can't load gcry_rsa from the
+ * the filesystem after we install the verifier - we won't be able to verify
+ * it without having it already present. We also shouldn't load it before we
+ * install the verifier, because that would mean it wouldn't be verified - an
+ * attacker could insert any code they wanted into the module.
+ *
+ * So instead, reference the internal symbol from gcry_rsa. That

Quoted 8 lines

creates a
+ * direct dependency on gcry_rsa, so it will be built in when this module
+ * is built in. Being built in (assuming the core image is itself signed!)
+ * also resolves our concerns about loading from the filesystem.
+ */
+extern gcry_pk_spec_t _gcry_pubkey_spec_rsa;

Please take a look at the commit 6744840b1 (build: Track explicit module dependencies in Makefile.core.def) and use "depends" instead.

I think I saw similar things in earlier patches. If it is the same case please fix the other issues as above...

grub-core/commands/appendedsig/appendedsig.c line 95

Quoted 5 lines
grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+static enum
+{
+  check_sigs_no = 0,
+  check_sigs_enforce = 1,
+  check_sigs_forced = 2

Please use uppercase for all these constants.

Quoted 17 lines
grub-core/commands/appendedsig/appendedsig.c new file +16 -0
+} check_sigs = check_sigs_no;
+
+static const char *
+grub_env_read_sec (struct grub_env_var *var __attribute__ ((unused)),
+                   const char *val __attribute__ ((unused)))
+{
+  if (check_sigs == check_sigs_forced)
+    return "forced";
+  else if (check_sigs == check_sigs_enforce)
+    return "enforce";
+  else
+    return "no";
+}
+
+static char *
+grub_env_write_sec (struct grub_env_var *var __attribute__ 

((unused)), const char *val)

grub-core/commands/appendedsig/appendedsig.c line 115

Quoted 4 lines
grub-core/commands/appendedsig/appendedsig.c new file +4 -0
+{
+  /* Do not allow the value to be changed if set to forced */
+  if (check_sigs == check_sigs_forced)
+    return grub_strdup ("forced");

grub_strdup() may fail...

grub-core/commands/appendedsig/appendedsig.c line 124

Quoted 9 lines
grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+
+  if ((*val == '2') || (*val == 'f'))
+    check_sigs = check_sigs_forced;
+  else if ((*val == '1') || (*val == 'e'))
+    check_sigs = check_sigs_enforce;
+  else if ((*val == '0') || (*val == 'n'))
+    check_sigs = check_sigs_no;
+
+  return grub_strdup (grub_env_read_sec (NULL, NULL));

Ditto...

Quoted 47 lines
grub-core/commands/appendedsig/appendedsig.c new file +4 -0
+}
+
+static grub_err_t
+file_read_all (grub_file_t file, grub_uint8_t **buf, grub_size_t 

*len)

grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+{
+  grub_off_t full_file_size;
+  grub_size_t file_size, total_read_size = 0;
+  grub_ssize_t read_size;
+
+  full_file_size = grub_file_size (file);
+  if (full_file_size == GRUB_FILE_SIZE_UNKNOWN)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("Cannot read a file of unknown size into a 

buffer"));

grub-core/commands/appendedsig/appendedsig.c new file +4 -0
+
+  if (full_file_size > GRUB_SIZE_MAX)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE,
+                       N_("File is too large to read: %" 

PRIuGRUB_UINT64_T " bytes"),

grub-core/commands/appendedsig/appendedsig.c new file +8 -0
+                       full_file_size);
+
+  file_size = (grub_size_t) full_file_size;
+
+  *buf = grub_malloc (file_size);
+  if (!*buf)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
+                       N_("Could not allocate file data buffer size 

%" PRIuGRUB_SIZE),

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+                       file_size);
+
+  while (total_read_size < file_size)
+    {
+      read_size = grub_file_read (file, *buf + total_read_size, 

file_size - total_read_size);

grub-core/commands/appendedsig/appendedsig.c new file +12 -0
+
+      if (read_size < 0)
+        {
+          grub_free (*buf);
+          return grub_errno;
+        }
+      else if (read_size == 0)
+        {
+          grub_free (*buf);
+          return grub_error (GRUB_ERR_IO,
+                             N_("Could not read full file size "
+                                "(%" PRIuGRUB_SIZE "), only %" 
Quoted 1 line

PRIuGRUB_SIZE " bytes read"),

Be careful, you cannot use PRIuGRUB_SIZE conversions in N_(). Though I would suggest to drop N_() here and from cryptic error messages which should be targeted only for experts. And probably it would be better to add file path to this error message.

Quoted 141 lines
grub-core/commands/appendedsig/appendedsig.c new file +11 -0
+                             file_size, total_read_size);
+        }
+
+      total_read_size += read_size;
+    }
+  *len = file_size;
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+read_cert_from_file (grub_file_t f, struct x509_certificate 

*certificate)

grub-core/commands/appendedsig/appendedsig.c new file +17 -0
+{
+  grub_err_t err;
+  grub_uint8_t *buf;
+  grub_size_t file_size;
+
+  err = file_read_all (f, &buf, &file_size);
+  if (err != GRUB_ERR_NONE)
+    return err;
+
+  err = parse_x509_certificate (buf, file_size, certificate);
+  grub_free (buf);
+
+  return err;
+}
+
+static grub_err_t
+extract_appended_signature (const grub_uint8_t *buf, grub_size_t 

bufsize,

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+                            struct grub_appended_signature *sig)
+{
+  grub_size_t pkcs7_size;
+  grub_size_t remaining_len;
+  const grub_uint8_t *appsigdata = buf + bufsize - grub_strlen 

(magic);

grub-core/commands/appendedsig/appendedsig.c new file +3 -0
+
+  if (bufsize < grub_strlen (magic))
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for 

signature magic"));

grub-core/commands/appendedsig/appendedsig.c new file +2 -0
+
+  if (grub_memcmp (appsigdata, (grub_uint8_t *) magic, grub_strlen 

(magic)))
+ return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("Missing or invalid
signature magic"));

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+
+  remaining_len = bufsize - grub_strlen (magic);
+
+  if (remaining_len < sizeof (struct module_signature))
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for 

signature metadata"));

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+
+  appsigdata -= sizeof (struct module_signature);
+
+  /* extract the metadata */
+  grub_memcpy (&(sig->sig_metadata), appsigdata, sizeof (struct 

module_signature));

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+
+  remaining_len -= sizeof (struct module_signature);
+
+  if (sig->sig_metadata.id_type != 2)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("Wrong signature 

type"));

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+
+  pkcs7_size = grub_be_to_cpu32 (sig->sig_metadata.sig_len);
+
+  if (pkcs7_size > remaining_len)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("File too short for 

PKCS#7 message"));

grub-core/commands/appendedsig/appendedsig.c new file +2 -0
+
+  grub_dprintf ("appendedsig", "sig len %" PRIuGRUB_SIZE "\n", 

pkcs7_size);

grub-core/commands/appendedsig/appendedsig.c new file +2 -0
+
+  sig->signature_len = grub_strlen (magic) + sizeof (struct 

module_signature) + pkcs7_size;

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+
+  /* rewind pointer and parse pkcs7 data */
+  appsigdata -= pkcs7_size;
+
+  return parse_pkcs7_signedData (appsigdata, pkcs7_size, 

&sig->pkcs7);

grub-core/commands/appendedsig/appendedsig.c new file +4 -0
+}
+
+static grub_err_t
+grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t 

bufsize)

grub-core/commands/appendedsig/appendedsig.c new file +14 -0
+{
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_size_t datasize;
+  void *context;
+  unsigned char *hash;
+  gcry_mpi_t hashmpi;
+  gcry_err_code_t rc;
+  struct x509_certificate *pk;
+  struct grub_appended_signature sig;
+  struct pkcs7_signerInfo *si;
+  int i;
+
+  if (!grub_trusted_key)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("No trusted keys to 

verify against"));

grub-core/commands/appendedsig/appendedsig.c new file +13 -0
+
+  err = extract_appended_signature (buf, bufsize, &sig);
+  if (err != GRUB_ERR_NONE)
+    return err;
+
+  datasize = bufsize - sig.signature_len;
+
+  for (i = 0; i < sig.pkcs7.signerInfo_count; i++)
+    {
+      /*
+       * This could be optimised in a couple of ways:
+       * - we could only compute hashes once per hash type
+       * - we could track signer information and only verify where 

IDs match
+ * For now we do the naive O(trusted keys * pkcs7 signers)
approach.

grub-core/commands/appendedsig/appendedsig.c new file +12 -0
+       */
+      si = &sig.pkcs7.signerInfos[i];
+      context = grub_zalloc (si->hash->contextsize);
+      if (!context)
+        return grub_errno;
+
+      si->hash->init (context);
+      si->hash->write (context, buf, datasize);
+      si->hash->final (context);
+      hash = si->hash->read (context);
+
+      grub_dprintf ("appendedsig", "data size %" PRIxGRUB_SIZE ", 

signer %d hash %02x%02x%02x%02x...\n",

grub-core/commands/appendedsig/appendedsig.c new file +6 -0
+                    datasize, i, hash[0], hash[1], hash[2], hash[3]);
+
+      err = GRUB_ERR_BAD_SIGNATURE;
+      for (pk = grub_trusted_key; pk; pk = pk->next)
+        {
+          rc = grub_crypto_rsa_pad (&hashmpi, hash, si->hash, 

pk->mpis[0]);

grub-core/commands/appendedsig/appendedsig.c new file +4 -0
+          if (rc)
+            {
+              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                N_("Error padding hash for RSA 
Quoted 1 line

verification: %d"), rc);

Is gcry_err_code_t always equal int type? Even if yes it would be nice to cast rc to int. And I would drop N_() here.

Quoted 33 lines
grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+              grub_free (context);
+              goto cleanup;
+            }
+
+          rc = _gcry_pubkey_spec_rsa.verify (0, hashmpi, 

&si->sig_mpi, pk->mpis, NULL, NULL);

grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+          gcry_mpi_release (hashmpi);
+
+          if (rc == 0)
+            {
+              grub_dprintf ("appendedsig", "verify signer %d with key 

'%s' succeeded\n",

grub-core/commands/appendedsig/appendedsig.c new file +6 -0
+                            i, pk->subject);
+              err = GRUB_ERR_NONE;
+              break;
+            }
+
+          grub_dprintf ("appendedsig", "verify signer %d with key 

'%s' failed with %d\n",

grub-core/commands/appendedsig/appendedsig.c new file +13 -0
+                        i, pk->subject, rc);
+        }
+
+      grub_free (context);
+
+      if (err == GRUB_ERR_NONE)
+        break;
+    }
+
+  /* If we didn't verify, provide a neat message */
+  if (err != GRUB_ERR_NONE)
+    err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                      N_("Failed to verify signature against a 

trusted key"));

grub-core/commands/appendedsig/appendedsig.c

Quoted 2 lines
grub-core/commands/appendedsig/appendedsig.c new file +2 -0
+
+cleanup:

Missing space before label.

Quoted 26 lines
grub-core/commands/appendedsig/appendedsig.c new file +7 -0
+  pkcs7_signedData_release (&sig.pkcs7);
+
+  return err;
+}
+
+static grub_err_t
+grub_cmd_verify_signature (grub_command_t cmd __attribute__ 

((unused)), int argc, char **args)

grub-core/commands/appendedsig/appendedsig.c new file +8 -0
+{
+  grub_file_t f;
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_uint8_t *data;
+  grub_size_t file_size;
+
+  if (argc < 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument 

expected"));

grub-core/commands/appendedsig/appendedsig.c new file +9 -0
+
+  grub_dprintf ("appendedsig", "verifying %s\n", args[0]);
+
+  f = grub_file_open (args[0], GRUB_FILE_TYPE_VERIFY_SIGNATURE);
+  if (!f)
+    {
+      err = grub_errno;
+      goto cleanup;
+    }

grub-core/commands/appendedsig/appendedsig.c line 353

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c new file +10 -0
+
+  err = file_read_all (f, &data, &file_size);
+  if (err != GRUB_ERR_NONE)
+    goto cleanup;
+
+  err = grub_verify_appended_signature (data, file_size);
+
+  grub_free (data);
+
+cleanup:

Ditto...

Quoted 15 lines
grub-core/commands/appendedsig/appendedsig.c new file +7 -0
+  if (f)
+    grub_file_close (f);
+  return err;
+}
+
+static grub_err_t
+grub_cmd_distrust (grub_command_t cmd __attribute__ ((unused)), int 

argc, char **args)

grub-core/commands/appendedsig/appendedsig.c new file +6 -0
+{
+  unsigned long cert_num, i;
+  struct x509_certificate *cert, *prev;
+
+  if (argc != 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("One argument 

expected"));

grub-core/commands/appendedsig/appendedsig.c line 371

Quoted 5 lines
grub-core/commands/appendedsig/appendedsig.c new file +5 -0
+
+  grub_errno = GRUB_ERR_NONE;
+  cert_num = grub_strtoul (args[0], NULL, 10);
+  if (grub_errno != GRUB_ERR_NONE)
+    return grub_errno;

This check is unreliable. Please take a look at commit ac8a37dda (net/http: Allow use of non-standard TCP/IP ports) and fix checks for all grub_strtoul() et consortes calls.

Quoted 1 line

Daniel

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

#29 lore raw

PATCH v2 11/21 appended signatures: verification tests

In reply to Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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

---
 grub-core/Makefile.core.def               |   6 +
 grub-core/tests/appended_signature_test.c | 258 ++++++
 grub-core/tests/appended_signatures.h     | 975 ++++++++++++++++++++++
 grub-core/tests/lib/functional_test.c     |   1 +
 4 files changed, 1240 insertions(+)
 create mode 100644 grub-core/tests/appended_signature_test.c
 create mode 100644 grub-core/tests/appended_signatures.h
grub-core/Makefile.core.def +6 -0
index d693986c6..9cf4a6009 100644
@@ -2194,6 +2194,12 @@ module = {
   common = tests/setjmp_test.c;
 };
 
+module = {
+  name = appended_signature_test;
+  common = tests/appended_signature_test.c;
+  common = tests/appended_signatures.h;
+};
+
 module = {
   name = signature_test;
   common = tests/signature_test.c;
grub-core/tests/appended_signature_test.c new file +258 -0

258 lines not on this page · raw message

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

975 lines not on this page · raw message

grub-core/tests/lib/functional_test.c +1 -0
index 38e981f2c..23048919d 100644
@@ -73,6 +73,7 @@ grub_functional_all_tests (grub_extcmd_context_t ctxt __attribute__ ((unused)),
   grub_dl_load ("xnu_uuid_test");
   grub_dl_load ("pbkdf2_test");
   grub_dl_load ("signature_test");
+  grub_dl_load ("appended_signature_test");
   grub_dl_load ("sleep_test");
   grub_dl_load ("bswap_test");
   grub_dl_load ("ctz_test");
Signature · 7 lines
2.43.5


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

Re: [PATCH v2 11/21] appended signatures: verification tests

On Thu, Mar 27, 2025 at 01:02:32AM +0530, Sudhakar Kuppusamy wrote:

[...]

Quoted 114 lines
grub-core/tests/appended_signatures.h new file +108 -0
new file mode 100644
index 000000000..c6aa12d86
@@ -0,0 +1,975 @@
+unsigned char certificate_der[] = {
+  0x30, 0x82, 0x05, 0x5d, 0x30, 0x82, 0x03, 0x45, 0xa0, 0x03, 0x02, 0x01,
+  0x02, 0x02, 0x14, 0x5b, 0x5e, 0x59, 0xf2, 0x5f, 0x75, 0x4c, 0x8e, 0xc5,
+  0x3a, 0x91, 0x07, 0xe9, 0xe7, 0x6d, 0x3c, 0xd0, 0x7f, 0x92, 0x03, 0x30,
+  0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b,
+  0x05, 0x00, 0x30, 0x3d, 0x31, 0x3b, 0x30, 0x39, 0x06, 0x03, 0x55, 0x04,
+  0x03, 0x0c, 0x32, 0x47, 0x72, 0x75, 0x62, 0x20, 0x41, 0x70, 0x70, 0x65,
+  0x6e, 0x64, 0x65, 0x64, 0x20, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75,
+  0x72, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x65, 0x72, 0x74,
+  0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x20, 0x41, 0x75, 0x74, 0x68,
+  0x6f, 0x72, 0x69, 0x74, 0x79, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x31, 0x30,
+  0x36, 0x32, 0x39, 0x30, 0x38, 0x33, 0x36, 0x31, 0x33, 0x5a, 0x18, 0x0f,
+  0x32, 0x31, 0x32, 0x31, 0x30, 0x36, 0x30, 0x35, 0x30, 0x38, 0x33, 0x36,
+  0x31, 0x33, 0x5a, 0x30, 0x33, 0x31, 0x31, 0x30, 0x2f, 0x06, 0x03, 0x55,
+  0x04, 0x03, 0x0c, 0x28, 0x47, 0x72, 0x75, 0x62, 0x20, 0x41, 0x70, 0x70,
+  0x65, 0x6e, 0x64, 0x65, 0x64, 0x20, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74,
+  0x75, 0x72, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x53, 0x69, 0x67,
+  0x6e, 0x69, 0x6e, 0x67, 0x20, 0x4b, 0x65, 0x79, 0x30, 0x82, 0x02, 0x22,
+  0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
+  0x01, 0x05, 0x00, 0x03, 0x82, 0x02, 0x0f, 0x00, 0x30, 0x82, 0x02, 0x0a,
+  0x02, 0x82, 0x02, 0x01, 0x00, 0xb9, 0x09, 0xb2, 0xf6, 0x24, 0x34, 0xdc,
+  0x62, 0xe6, 0x4e, 0xee, 0x04, 0xdb, 0x29, 0xdc, 0x94, 0xcc, 0xee, 0x8a,
+  0x5b, 0xc3, 0x9e, 0x06, 0xba, 0xa7, 0x9b, 0xa4, 0x5f, 0x15, 0x59, 0x8e,
+  0xb8, 0x6e, 0x3c, 0xeb, 0x2e, 0xf2, 0xac, 0x21, 0x42, 0xbd, 0x30, 0xa1,
+  0x39, 0xe5, 0xb9, 0x4f, 0xa0, 0x53, 0xd5, 0x42, 0xdc, 0x8a, 0x87, 0x30,
+  0x38, 0x93, 0x44, 0x80, 0x3b, 0x1a, 0x7e, 0x9e, 0x8e, 0x3e, 0xea, 0x45,
+  0xa0, 0x11, 0x8b, 0xfb, 0x78, 0xe4, 0xbc, 0x65, 0x6b, 0x73, 0xea, 0x6e,
+  0xdf, 0x7c, 0x5b, 0x63, 0x7e, 0x5b, 0x0a, 0x1c, 0xe6, 0x76, 0x19, 0xb5,
+  0x01, 0xde, 0xf6, 0x65, 0x51, 0x30, 0x0a, 0x56, 0x69, 0x69, 0xe8, 0x20,
+  0xf9, 0x13, 0xf1, 0xbf, 0x6f, 0xdd, 0xce, 0x94, 0x96, 0x6e, 0x63, 0xd6,
+  0xfa, 0xa4, 0x91, 0x5f, 0xb3, 0x9c, 0xc7, 0xfa, 0xa9, 0xff, 0x66, 0x5f,
+  0xf3, 0xab, 0x5e, 0xdf, 0x4e, 0xca, 0x11, 0xcf, 0xbf, 0xf8, 0xad, 0x65,
+  0xb1, 0x49, 0x8b, 0xe9, 0x2a, 0xad, 0x7d, 0xf3, 0x0b, 0xfa, 0x5b, 0x6a,
+  0x6a, 0x20, 0x12, 0x77, 0xef, 0x4b, 0xb6, 0xbe, 0x92, 0xba, 0x14, 0x9c,
+  0x5e, 0xea, 0xdc, 0x56, 0x6d, 0x92, 0xd3, 0x64, 0x22, 0xf6, 0x12, 0xe8,
+  0x7d, 0x5e, 0x9c, 0xd6, 0xf9, 0x75, 0x68, 0x7f, 0x8f, 0xd3, 0x6e, 0x05,
+  0x94, 0x91, 0x4f, 0xa1, 0xd6, 0x50, 0x72, 0x3b, 0x11, 0x1f, 0x28, 0x13,
+  0xe8, 0x25, 0x6b, 0xdf, 0xff, 0x72, 0x46, 0x25, 0xe9, 0x05, 0x6f, 0x02,
+  0xc7, 0x1e, 0xc9, 0xcf, 0x99, 0xe9, 0xa7, 0xe2, 0xae, 0xbc, 0xc1, 0x22,
+  0x32, 0x73, 0x2d, 0xa3, 0x70, 0x8f, 0xa7, 0x8d, 0xbf, 0x5f, 0x74, 0x05,
+  0x1b, 0x5e, 0xfe, 0x97, 0x3c, 0xe7, 0x3b, 0x86, 0x0d, 0xf6, 0x38, 0xdb,
+  0xd2, 0x39, 0x47, 0x82, 0x00, 0x44, 0x6c, 0x7b, 0x40, 0x24, 0x0b, 0x3a,
+  0xd4, 0x19, 0x31, 0xba, 0x4e, 0x8e, 0xa3, 0x33, 0xa6, 0x78, 0xef, 0x72,
+  0x9f, 0x06, 0x37, 0x01, 0x9b, 0x79, 0x0d, 0x04, 0xbf, 0xba, 0xd5, 0x1f,
+  0x27, 0xdc, 0x85, 0xbb, 0xef, 0xd2, 0x60, 0xda, 0xa0, 0x3f, 0x66, 0xce,
+  0x9f, 0xa2, 0x7e, 0xa8, 0x8d, 0xee, 0x14, 0x4b, 0xcb, 0x93, 0xf1, 0x38,
+  0xac, 0x4f, 0xd8, 0x29, 0xf3, 0x6f, 0xd4, 0xfd, 0x4d, 0x34, 0x77, 0x58,
+  0x99, 0xdb, 0x16, 0xc1, 0xd0, 0xc7, 0x43, 0x41, 0x70, 0xc4, 0xad, 0x01,
+  0x29, 0x65, 0x22, 0x43, 0x00, 0x6f, 0xb3, 0x00, 0x27, 0x38, 0xc1, 0x4f,
+  0xda, 0x28, 0x96, 0x42, 0xdc, 0xbc, 0x3e, 0x34, 0x8e, 0x14, 0xb8, 0xf3,
+  0x86, 0x4a, 0xea, 0x16, 0x90, 0xf9, 0x0e, 0x9e, 0x8f, 0x66, 0x0c, 0xbf,
+  0x29, 0xd3, 0x8f, 0xfc, 0x4d, 0x38, 0x68, 0xe2, 0xe7, 0x64, 0x32, 0x47,
+  0xdd, 0x56, 0xc9, 0xe4, 0x47, 0x9f, 0x18, 0x89, 0xfc, 0x30, 0x7a, 0xae,
+  0x63, 0xe4, 0xec, 0x93, 0x04, 0xd4, 0x61, 0xe7, 0xbf, 0x0a, 0x06, 0x29,
+  0xc2, 0xa6, 0xd5, 0x53, 0x5d, 0x65, 0x6d, 0x4a, 0xd0, 0xb7, 0x68, 0x4d,
+  0x46, 0x0a, 0xb5, 0xff, 0x52, 0x5e, 0x92, 0x7e, 0x75, 0x08, 0xa4, 0x63,
+  0x0a, 0x6c, 0x31, 0x7a, 0xaa, 0x0c, 0x52, 0xf4, 0x2e, 0xcd, 0x08, 0xeb,
+  0xb3, 0xbd, 0xad, 0x8b, 0x8b, 0x9b, 0x8d, 0x71, 0x42, 0x30, 0x8e, 0xc7,
+  0xfd, 0xec, 0xb7, 0xe6, 0x26, 0x96, 0xf2, 0x74, 0x1b, 0x78, 0x95, 0x22,
+  0x14, 0xf3, 0xc9, 0xd3, 0x79, 0x11, 0xd9, 0xb7, 0x4d, 0x0d, 0x61, 0x60,
+  0x5c, 0x47, 0x50, 0xf3, 0xca, 0x84, 0x4c, 0x5c, 0x30, 0x2c, 0x6a, 0x18,
+  0x26, 0xb0, 0xf3, 0xd1, 0x15, 0x19, 0x39, 0xc3, 0x23, 0x13, 0x0f, 0x9c,
+  0x97, 0x2b, 0x97, 0x93, 0xf9, 0xf8, 0x18, 0x9b, 0x4a, 0x4d, 0xd6, 0xd3,
+  0xf5, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x5d, 0x30, 0x5b, 0x30, 0x0c,
+  0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00,
+  0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x07,
+  0x80, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14,
+  0x8f, 0xba, 0x8b, 0xf5, 0xf4, 0x77, 0xb2, 0xa4, 0x19, 0xef, 0x43, 0xb1,
+  0x8b, 0x03, 0x4b, 0x45, 0x47, 0xb5, 0x2a, 0x48, 0x30, 0x1f, 0x06, 0x03,
+  0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x59, 0x1c, 0xb5,
+  0x52, 0x62, 0x83, 0x05, 0x3b, 0x41, 0x4c, 0x63, 0x4d, 0x5b, 0xf4, 0x8c,
+  0xe6, 0xd7, 0xda, 0x87, 0x54, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48,
+  0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x02, 0x01,
+  0x00, 0x36, 0x2d, 0x0a, 0xcb, 0x49, 0x54, 0x75, 0xd7, 0xca, 0x21, 0x86,
+  0xae, 0x40, 0x0f, 0x63, 0x10, 0x35, 0xfd, 0xbc, 0xba, 0x28, 0x31, 0x33,
+  0x07, 0x08, 0x64, 0x03, 0x6c, 0xd3, 0xd5, 0xf7, 0xb7, 0x79, 0x11, 0x0c,
+  0xa8, 0x9e, 0xfd, 0x34, 0xa2, 0xba, 0x77, 0x15, 0x15, 0x2d, 0x2c, 0x96,
+  0xae, 0x47, 0xbb, 0x82, 0x89, 0x09, 0x7f, 0xd1, 0x95, 0x69, 0x9b, 0xfe,
+  0xd7, 0x6f, 0x4e, 0x68, 0xf6, 0xe7, 0x5f, 0x54, 0xa1, 0x3a, 0xeb, 0xa4,
+  0xbf, 0x7a, 0xb6, 0x7f, 0xaa, 0xd8, 0xd7, 0x99, 0xcb, 0xae, 0x88, 0x6d,
+  0x7a, 0xf3, 0xfa, 0x9e, 0x44, 0x2f, 0x30, 0xa8, 0xe6, 0xb9, 0x75, 0xa0,
+  0x82, 0xd6, 0xb0, 0xe3, 0x03, 0xb3, 0x12, 0xa3, 0xdc, 0xb9, 0x4d, 0x93,
+  0xd4, 0x30, 0xea, 0xce, 0x96, 0x92, 0x07, 0xf8, 0xba, 0xe4, 0x0f, 0x41,
+  0xe3, 0x04, 0xaa, 0x8c, 0x07, 0x1a, 0x34, 0x60, 0xfc, 0xc0, 0x05, 0xd2,
+  0x5a, 0xa8, 0x66, 0xef, 0xe0, 0x94, 0xc5, 0x2f, 0x0f, 0xff, 0xdc, 0x70,
+  0xfb, 0xe2, 0x9d, 0x61, 0x51, 0x25, 0x02, 0xff, 0x4b, 0x69, 0xfd, 0x66,
+  0xb9, 0xeb, 0x0c, 0xc8, 0x50, 0xd3, 0xb1, 0x08, 0x1e, 0x09, 0x54, 0x87,
+  0xe8, 0xa3, 0x4b, 0xef, 0x0c, 0x32, 0x0a, 0x6c, 0xec, 0x27, 0x22, 0xba,
+  0x7f, 0xdc, 0x52, 0x27, 0x31, 0x14, 0x9a, 0xa8, 0xf7, 0xf9, 0xeb, 0xc8,
+  0xb5, 0x8d, 0x12, 0xed, 0x94, 0xab, 0x3d, 0x9a, 0xfb, 0x4e, 0x04, 0x05,
+  0xd2, 0x3c, 0x7c, 0x8a, 0xed, 0x46, 0x1b, 0x7c, 0xb5, 0x6c, 0x40, 0xb8,
+  0xc1, 0xbf, 0xb0, 0xd2, 0x93, 0x8e, 0xa8, 0x0f, 0xde, 0x78, 0xf3, 0x8c,
+  0xd8, 0x9f, 0xf8, 0xdc, 0xa1, 0x23, 0x20, 0x40, 0x17, 0xb4, 0xdb, 0xb7,
+  0x09, 0x74, 0xa7, 0x80, 0xc2, 0x12, 0xd9, 0x76, 0x79, 0x5b, 0x71, 0xa9,
+  0x6c, 0xd4, 0x57, 0x48, 0xe8, 0xfe, 0xc5, 0xc2, 0x6e, 0xe7, 0x83, 0x5a,
+  0x07, 0xf0, 0x33, 0xc1, 0xc1, 0x1d, 0x34, 0xd4, 0xc8, 0xb0, 0xb7, 0xdb,
+  0xeb, 0xe9, 0xe3, 0x59, 0xdc, 0x7f, 0x36, 0x58, 0xa9, 0xb8, 0x52, 0xdd,
+  0xf9, 0xfd, 0x1c, 0x22, 0x2f, 0x93, 0x3d, 0x53, 0x89, 0x80, 0xde, 0xa2,
+  0xb5, 0xa5, 0x36, 0xbd, 0xc3, 0x92, 0x03, 0xf3, 0x93, 0xc8, 0xc7, 0x4a,
+  0x0b, 0x8b, 0x62, 0xfe, 0xd0, 0xf8, 0x0d, 0x7a, 0x32, 0xb4, 0x39, 0x1a,
+  0xb7, 0x4e, 0xaa, 0xc4, 0x33, 0x32, 0x90, 0x8c, 0xab, 0xd4, 0xae, 0xa5,
+  0xa4, 0x85, 0xcf, 0xba, 0xe1, 0x1b, 0x26, 0x7f, 0x74, 0x02, 0x12, 0x09,
+  0x89, 0x56, 0xe4, 0xe7, 0x9d, 0x91, 0xde, 0x88, 0xe7, 0x1c, 0xed, 0x80,
+  0x05, 0xa8, 0x58, 0x9a, 0x3e, 0x16, 0x97, 0xd5, 0xbc, 0x54, 0xcc, 0xf0,
+  0x32, 0xf2, 0x93, 0x09, 0x94, 0x9f, 0x3c, 0xd9, 0x58, 0xca, 0x68, 0x0b,
+  0xde, 0x3f, 0x73, 0x64, 0xb7, 0xf4, 0xd7, 0x5f, 0x2b, 0xe7, 0x7b, 0x06,
+  0xca, 0xb1, 0x3e, 0xed, 0xd2, 0xb9, 0x29, 0xc1, 0x95, 0x87, 0xad, 0xd6,
+  0x63, 0x69, 0xb8, 0x1f, 0x70, 0xdb, 0xeb, 0xc7, 0x11, 0x7d, 0xe2, 0x99,

grub-core/tests/appended_signatures.h line 118

Quoted 10 lines
grub-core/tests/appended_signatures.h new file +10 -0
+  0x64, 0x6a, 0xf5, 0x3f, 0x30, 0x74, 0x5f, 0x2a, 0x21, 0xda, 0xef, 0x44,
+  0x1d, 0xad, 0x97, 0xa1, 0xfe, 0x14, 0xa7, 0x88, 0x99, 0xd0, 0x1e, 0xb0,
+  0x61, 0x88, 0x09, 0xc9, 0xfa, 0xd1, 0xb3, 0xcb, 0x1d, 0x76, 0x04, 0xbe,
+  0x06, 0x44, 0xd2, 0x30, 0x5e, 0x95, 0x4b, 0x96, 0xc0, 0xd6, 0xbe, 0xd0,
+  0x4d, 0xf2, 0xf4, 0x71, 0x72, 0xa9, 0xbd, 0x07, 0x4f, 0xbc, 0xb3, 0x78,
+  0xb4, 0x8a, 0x44, 0xbd, 0x58, 0xd5, 0x21, 0xb6, 0x47, 0x9c, 0x88, 0x1f,
+  0xbc, 0xbd, 0x54, 0xfa, 0x1d, 0x49, 0xec, 0x51, 0xd9, 0x43, 0x49, 0x9c,
+  0x0c, 0xfa, 0x18, 0xdb, 0xeb, 0x05, 0x77, 0xa2, 0x9a
+};
+unsigned int certificate_der_len = 1377;

This and lenghts below do not seem used...

Daniel

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

author
#31 lore raw

Re: [PATCH v2 11/21] appended signatures: verification tests

Hi Daniel,

Thank you for your valuable review.

Quoted 236 lines · Daniel Kiper

On Thu, Mar 27, 2025 at 01:02:32AM +0530, Sudhakar Kuppusamy wrote:

[...]

Quoted 232 lines
grub-core/tests/appended_signatures.h new file +2 -0
new file mode 100644
index 000000000..c6aa12d86
@@ -0,0 +1,975 @@
+unsigned char certificate_der[] = {
+  0x30, 0x82, 0x05, 0x5d, 0x30, 0x82, 0x03, 0x45, 0xa0, 0x03, 0x02, 

0x01,
+ 0x02, 0x02, 0x14, 0x5b, 0x5e, 0x59, 0xf2, 0x5f, 0x75, 0x4c, 0x8e, 0xc5,
+ 0x3a, 0x91, 0x07, 0xe9, 0xe7, 0x6d, 0x3c, 0xd0, 0x7f, 0x92, 0x03, 0x30,
+ 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b,
+ 0x05, 0x00, 0x30, 0x3d, 0x31, 0x3b, 0x30, 0x39, 0x06, 0x03, 0x55, 0x04,
+ 0x03, 0x0c, 0x32, 0x47, 0x72, 0x75, 0x62, 0x20, 0x41, 0x70, 0x70, 0x65,
+ 0x6e, 0x64, 0x65, 0x64, 0x20, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74, 0x75,
+ 0x72, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x43, 0x65, 0x72, 0x74,
+ 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x65, 0x20, 0x41, 0x75, 0x74, 0x68,
+ 0x6f, 0x72, 0x69, 0x74, 0x79, 0x30, 0x20, 0x17, 0x0d, 0x32, 0x31, 0x30,
+ 0x36, 0x32, 0x39, 0x30, 0x38, 0x33, 0x36, 0x31, 0x33, 0x5a, 0x18, 0x0f,
+ 0x32, 0x31, 0x32, 0x31, 0x30, 0x36, 0x30, 0x35, 0x30, 0x38, 0x33, 0x36,
+ 0x31, 0x33, 0x5a, 0x30, 0x33, 0x31, 0x31, 0x30, 0x2f, 0x06, 0x03, 0x55,
+ 0x04, 0x03, 0x0c, 0x28, 0x47, 0x72, 0x75, 0x62, 0x20, 0x41, 0x70, 0x70,
+ 0x65, 0x6e, 0x64, 0x65, 0x64, 0x20, 0x53, 0x69, 0x67, 0x6e, 0x61, 0x74,
+ 0x75, 0x72, 0x65, 0x20, 0x54, 0x65, 0x73, 0x74, 0x20, 0x53, 0x69, 0x67,
+ 0x6e, 0x69, 0x6e, 0x67, 0x20, 0x4b, 0x65, 0x79, 0x30, 0x82, 0x02, 0x22,
+ 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
+ 0x01, 0x05, 0x00, 0x03, 0x82, 0x02, 0x0f, 0x00, 0x30, 0x82, 0x02, 0x0a,
+ 0x02, 0x82, 0x02, 0x01, 0x00, 0xb9, 0x09, 0xb2, 0xf6, 0x24, 0x34, 0xdc,
+ 0x62, 0xe6, 0x4e, 0xee, 0x04, 0xdb, 0x29, 0xdc, 0x94, 0xcc, 0xee, 0x8a,
+ 0x5b, 0xc3, 0x9e, 0x06, 0xba, 0xa7, 0x9b, 0xa4, 0x5f, 0x15, 0x59, 0x8e,
+ 0xb8, 0x6e, 0x3c, 0xeb, 0x2e, 0xf2, 0xac, 0x21, 0x42, 0xbd, 0x30, 0xa1,
+ 0x39, 0xe5, 0xb9, 0x4f, 0xa0, 0x53, 0xd5, 0x42, 0xdc, 0x8a, 0x87, 0x30,
+ 0x38, 0x93, 0x44, 0x80, 0x3b, 0x1a, 0x7e, 0x9e, 0x8e, 0x3e, 0xea, 0x45,
+ 0xa0, 0x11, 0x8b, 0xfb, 0x78, 0xe4, 0xbc, 0x65, 0x6b, 0x73, 0xea, 0x6e,
+ 0xdf, 0x7c, 0x5b, 0x63, 0x7e, 0x5b, 0x0a, 0x1c, 0xe6, 0x76, 0x19, 0xb5,
+ 0x01, 0xde, 0xf6, 0x65, 0x51, 0x30, 0x0a, 0x56, 0x69, 0x69, 0xe8, 0x20,
+ 0xf9, 0x13, 0xf1, 0xbf, 0x6f, 0xdd, 0xce, 0x94, 0x96, 0x6e, 0x63, 0xd6,
+ 0xfa, 0xa4, 0x91, 0x5f, 0xb3, 0x9c, 0xc7, 0xfa, 0xa9, 0xff, 0x66, 0x5f,
+ 0xf3, 0xab, 0x5e, 0xdf, 0x4e, 0xca, 0x11, 0xcf, 0xbf, 0xf8, 0xad, 0x65,
+ 0xb1, 0x49, 0x8b, 0xe9, 0x2a, 0xad, 0x7d, 0xf3, 0x0b, 0xfa, 0x5b, 0x6a,
+ 0x6a, 0x20, 0x12, 0x77, 0xef, 0x4b, 0xb6, 0xbe, 0x92, 0xba, 0x14, 0x9c,
+ 0x5e, 0xea, 0xdc, 0x56, 0x6d, 0x92, 0xd3, 0x64, 0x22, 0xf6, 0x12, 0xe8,
+ 0x7d, 0x5e, 0x9c, 0xd6, 0xf9, 0x75, 0x68, 0x7f, 0x8f, 0xd3, 0x6e, 0x05,
+ 0x94, 0x91, 0x4f, 0xa1, 0xd6, 0x50, 0x72, 0x3b, 0x11, 0x1f, 0x28, 0x13,
+ 0xe8, 0x25, 0x6b, 0xdf, 0xff, 0x72, 0x46, 0x25, 0xe9, 0x05, 0x6f, 0x02,
+ 0xc7, 0x1e, 0xc9, 0xcf, 0x99, 0xe9, 0xa7, 0xe2, 0xae, 0xbc, 0xc1, 0x22,
+ 0x32, 0x73, 0x2d, 0xa3, 0x70, 0x8f, 0xa7, 0x8d, 0xbf, 0x5f, 0x74, 0x05,
+ 0x1b, 0x5e, 0xfe, 0x97, 0x3c, 0xe7, 0x3b, 0x86, 0x0d, 0xf6, 0x38, 0xdb,
+ 0xd2, 0x39, 0x47, 0x82, 0x00, 0x44, 0x6c, 0x7b, 0x40, 0x24, 0x0b, 0x3a,
+ 0xd4, 0x19, 0x31, 0xba, 0x4e, 0x8e, 0xa3, 0x33, 0xa6, 0x78, 0xef, 0x72,
+ 0x9f, 0x06, 0x37, 0x01, 0x9b, 0x79, 0x0d, 0x04, 0xbf, 0xba, 0xd5, 0x1f,
+ 0x27, 0xdc, 0x85, 0xbb, 0xef, 0xd2, 0x60, 0xda, 0xa0, 0x3f, 0x66, 0xce,
+ 0x9f, 0xa2, 0x7e, 0xa8, 0x8d, 0xee, 0x14, 0x4b, 0xcb, 0x93, 0xf1, 0x38,
+ 0xac, 0x4f, 0xd8, 0x29, 0xf3, 0x6f, 0xd4, 0xfd, 0x4d, 0x34, 0x77, 0x58,
+ 0x99, 0xdb, 0x16, 0xc1, 0xd0, 0xc7, 0x43, 0x41, 0x70, 0xc4, 0xad, 0x01,
+ 0x29, 0x65, 0x22, 0x43, 0x00, 0x6f, 0xb3, 0x00, 0x27, 0x38, 0xc1, 0x4f,
+ 0xda, 0x28, 0x96, 0x42, 0xdc, 0xbc, 0x3e, 0x34, 0x8e, 0x14, 0xb8, 0xf3,
+ 0x86, 0x4a, 0xea, 0x16, 0x90, 0xf9, 0x0e, 0x9e, 0x8f, 0x66, 0x0c, 0xbf,
+ 0x29, 0xd3, 0x8f, 0xfc, 0x4d, 0x38, 0x68, 0xe2, 0xe7, 0x64, 0x32, 0x47,
+ 0xdd, 0x56, 0xc9, 0xe4, 0x47, 0x9f, 0x18, 0x89, 0xfc, 0x30, 0x7a, 0xae,
+ 0x63, 0xe4, 0xec, 0x93, 0x04, 0xd4, 0x61, 0xe7, 0xbf, 0x0a, 0x06, 0x29,
+ 0xc2, 0xa6, 0xd5, 0x53, 0x5d, 0x65, 0x6d, 0x4a, 0xd0, 0xb7, 0x68, 0x4d,
+ 0x46, 0x0a, 0xb5, 0xff, 0x52, 0x5e, 0x92, 0x7e, 0x75, 0x08, 0xa4, 0x63,
+ 0x0a, 0x6c, 0x31, 0x7a, 0xaa, 0x0c, 0x52, 0xf4, 0x2e, 0xcd, 0x08, 0xeb,
+ 0xb3, 0xbd, 0xad, 0x8b, 0x8b, 0x9b, 0x8d, 0x71, 0x42, 0x30, 0x8e, 0xc7,
+ 0xfd, 0xec, 0xb7, 0xe6, 0x26, 0x96, 0xf2, 0x74, 0x1b, 0x78, 0x95, 0x22,
+ 0x14, 0xf3, 0xc9, 0xd3, 0x79, 0x11, 0xd9, 0xb7, 0x4d, 0x0d, 0x61, 0x60,
+ 0x5c, 0x47, 0x50, 0xf3, 0xca, 0x84, 0x4c, 0x5c, 0x30, 0x2c, 0x6a, 0x18,
+ 0x26, 0xb0, 0xf3, 0xd1, 0x15, 0x19, 0x39, 0xc3, 0x23, 0x13, 0x0f, 0x9c,
+ 0x97, 0x2b, 0x97, 0x93, 0xf9, 0xf8, 0x18, 0x9b, 0x4a, 0x4d, 0xd6, 0xd3,
+ 0xf5, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x5d, 0x30, 0x5b, 0x30, 0x0c,
+ 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, 0x04, 0x02, 0x30, 0x00,
+ 0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x07,
+ 0x80, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14,
+ 0x8f, 0xba, 0x8b, 0xf5, 0xf4, 0x77, 0xb2, 0xa4, 0x19, 0xef, 0x43, 0xb1,
+ 0x8b, 0x03, 0x4b, 0x45, 0x47, 0xb5, 0x2a, 0x48, 0x30, 0x1f, 0x06, 0x03,
+ 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x59, 0x1c, 0xb5,
+ 0x52, 0x62, 0x83, 0x05, 0x3b, 0x41, 0x4c, 0x63, 0x4d, 0x5b, 0xf4, 0x8c,
+ 0xe6, 0xd7, 0xda, 0x87, 0x54, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48,
+ 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x02, 0x01,
+ 0x00, 0x36, 0x2d, 0x0a, 0xcb, 0x49, 0x54, 0x75, 0xd7, 0xca, 0x21, 0x86,
+ 0xae, 0x40, 0x0f, 0x63, 0x10, 0x35, 0xfd, 0xbc, 0xba, 0x28, 0x31, 0x33,
+ 0x07, 0x08, 0x64, 0x03, 0x6c, 0xd3, 0xd5, 0xf7, 0xb7, 0x79, 0x11, 0x0c,
+ 0xa8, 0x9e, 0xfd, 0x34, 0xa2, 0xba, 0x77, 0x15, 0x15, 0x2d, 0x2c, 0x96,
+ 0xae, 0x47, 0xbb, 0x82, 0x89, 0x09, 0x7f, 0xd1, 0x95, 0x69, 0x9b, 0xfe,
+ 0xd7, 0x6f, 0x4e, 0x68, 0xf6, 0xe7, 0x5f, 0x54, 0xa1, 0x3a, 0xeb, 0xa4,
+ 0xbf, 0x7a, 0xb6, 0x7f, 0xaa, 0xd8, 0xd7, 0x99, 0xcb, 0xae, 0x88, 0x6d,
+ 0x7a, 0xf3, 0xfa, 0x9e, 0x44, 0x2f, 0x30, 0xa8, 0xe6, 0xb9, 0x75, 0xa0,
+ 0x82, 0xd6, 0xb0, 0xe3, 0x03, 0xb3, 0x12, 0xa3, 0xdc, 0xb9, 0x4d, 0x93,
+ 0xd4, 0x30, 0xea, 0xce, 0x96, 0x92, 0x07, 0xf8, 0xba, 0xe4, 0x0f, 0x41,
+ 0xe3, 0x04, 0xaa, 0x8c, 0x07, 0x1a, 0x34, 0x60, 0xfc, 0xc0, 0x05, 0xd2,
+ 0x5a, 0xa8, 0x66, 0xef, 0xe0, 0x94, 0xc5, 0x2f, 0x0f, 0xff, 0xdc, 0x70,
+ 0xfb, 0xe2, 0x9d, 0x61, 0x51, 0x25, 0x02, 0xff, 0x4b, 0x69, 0xfd, 0x66,
+ 0xb9, 0xeb, 0x0c, 0xc8, 0x50, 0xd3, 0xb1, 0x08, 0x1e, 0x09, 0x54, 0x87,
+ 0xe8, 0xa3, 0x4b, 0xef, 0x0c, 0x32, 0x0a, 0x6c, 0xec, 0x27, 0x22, 0xba,
+ 0x7f, 0xdc, 0x52, 0x27, 0x31, 0x14, 0x9a, 0xa8, 0xf7, 0xf9, 0xeb, 0xc8,
+ 0xb5, 0x8d, 0x12, 0xed, 0x94, 0xab, 0x3d, 0x9a, 0xfb, 0x4e, 0x04, 0x05,
+ 0xd2, 0x3c, 0x7c, 0x8a, 0xed, 0x46, 0x1b, 0x7c, 0xb5, 0x6c, 0x40, 0xb8,
+ 0xc1, 0xbf, 0xb0, 0xd2, 0x93, 0x8e, 0xa8, 0x0f, 0xde, 0x78, 0xf3, 0x8c,
+ 0xd8, 0x9f, 0xf8, 0xdc, 0xa1, 0x23, 0x20, 0x40, 0x17, 0xb4, 0xdb, 0xb7,
+ 0x09, 0x74, 0xa7, 0x80, 0xc2, 0x12, 0xd9, 0x76, 0x79, 0x5b, 0x71, 0xa9,
+ 0x6c, 0xd4, 0x57, 0x48, 0xe8, 0xfe, 0xc5, 0xc2, 0x6e, 0xe7, 0x83, 0x5a,
+ 0x07, 0xf0, 0x33, 0xc1, 0xc1, 0x1d, 0x34, 0xd4, 0xc8, 0xb0, 0xb7, 0xdb,
+ 0xeb, 0xe9, 0xe3, 0x59, 0xdc, 0x7f, 0x36, 0x58, 0xa9, 0xb8, 0x52, 0xdd,
+ 0xf9, 0xfd, 0x1c, 0x22, 0x2f, 0x93, 0x3d, 0x53, 0x89, 0x80, 0xde, 0xa2,
+ 0xb5, 0xa5, 0x36, 0xbd, 0xc3, 0x92, 0x03, 0xf3, 0x93, 0xc8, 0xc7, 0x4a,
+ 0x0b, 0x8b, 0x62, 0xfe, 0xd0, 0xf8, 0x0d, 0x7a, 0x32, 0xb4, 0x39, 0x1a,
+ 0xb7, 0x4e, 0xaa, 0xc4, 0x33, 0x32, 0x90, 0x8c, 0xab, 0xd4, 0xae, 0xa5,
+ 0xa4, 0x85, 0xcf, 0xba, 0xe1, 0x1b, 0x26, 0x7f, 0x74, 0x02, 0x12, 0x09,
+ 0x89, 0x56, 0xe4, 0xe7, 0x9d, 0x91, 0xde, 0x88, 0xe7, 0x1c, 0xed, 0x80,
+ 0x05, 0xa8, 0x58, 0x9a, 0x3e, 0x16, 0x97, 0xd5, 0xbc, 0x54, 0xcc, 0xf0,
+ 0x32, 0xf2, 0x93, 0x09, 0x94, 0x9f, 0x3c, 0xd9, 0x58, 0xca, 0x68, 0x0b,
+ 0xde, 0x3f, 0x73, 0x64, 0xb7, 0xf4, 0xd7, 0x5f, 0x2b, 0xe7, 0x7b, 0x06,
+ 0xca, 0xb1, 0x3e, 0xed, 0xd2, 0xb9, 0x29, 0xc1, 0x95, 0x87, 0xad, 0xd6,
+ 0x63, 0x69, 0xb8, 0x1f, 0x70, 0xdb, 0xeb, 0xc7, 0x11, 0x7d, 0xe2, 0x99,
+ 0x64, 0x6a, 0xf5, 0x3f, 0x30, 0x74, 0x5f, 0x2a, 0x21, 0xda, 0xef, 0x44,
+ 0x1d, 0xad, 0x97, 0xa1, 0xfe, 0x14, 0xa7, 0x88, 0x99, 0xd0, 0x1e, 0xb0,
+ 0x61, 0x88, 0x09, 0xc9, 0xfa, 0xd1, 0xb3, 0xcb, 0x1d, 0x76, 0x04, 0xbe,
+ 0x06, 0x44, 0xd2, 0x30, 0x5e, 0x95, 0x4b, 0x96, 0xc0, 0xd6, 0xbe, 0xd0,
+ 0x4d, 0xf2, 0xf4, 0x71, 0x72, 0xa9, 0xbd, 0x07, 0x4f, 0xbc, 0xb3, 0x78,
+ 0xb4, 0x8a, 0x44, 0xbd, 0x58, 0xd5, 0x21, 0xb6, 0x47, 0x9c, 0x88,

Quoted 9 lines

grub-core/tests/appended_signatures.h line 118

Quoted 6 lines

0x1f,
+ 0xbc, 0xbd, 0x54, 0xfa, 0x1d, 0x49, 0xec, 0x51, 0xd9, 0x43, 0x49, 0x9c,

grub-core/tests/appended_signatures.h new file +3 -0
+  0x0c, 0xfa, 0x18, 0xdb, 0xeb, 0x05, 0x77, 0xa2, 0x9a
+};
+unsigned int certificate_der_len = 1377;

This and lenghts below do not seem used...

lengths used by appended_signature_test.c i.e *sz = identifier##_len;

#define PROC_FILE(identifier, file_name)
\
static char *get_##identifier (grub_size_t *sz)
\
{

   \
    char *ret;                                                           

\

   \
    *sz = identifier##_len;                                              
   \
    ret = grub_malloc (*sz);                                             
   \
    if (ret)                                                             
   \
      grub_memcpy (ret, identifier, *sz);                                
   \
    return ret;                                                          
   \
  }                                                                      
   \

\
static struct grub_procfs_entry identifier##_entry = { .name =
file_name, \
.get_contents =
get_##identifier };

#define DEFINE_TEST_CASE(case_name) PROC_FILE (case_name, #case_name)

#define DO_TEST(case_name, is_valid) \

  {                                                        \
    grub_procfs_register (#case_name, &case_name##_entry); \
    do_verify ("(proc)/" #case_name, is_valid);            \
    grub_procfs_unregister (&case_name##_entry);           \

}

DEFINE_TEST_CASE (hi_signed);
DEFINE_TEST_CASE (hi_signed_sha256);
DEFINE_TEST_CASE (hj_signed);
DEFINE_TEST_CASE (short_msg);
DEFINE_TEST_CASE (unsigned_msg);
DEFINE_TEST_CASE (hi_signed_2nd);
DEFINE_TEST_CASE (hi_double);
DEFINE_TEST_CASE (hi_double_extended);

PROC_FILE (certificate_der, "certificate.der") PROC_FILE (certificate2_der, "certificate2.der") PROC_FILE (certificate_printable_der, "certificate_printable.der") PROC_FILE (certificate_eku_der, "certificate_eku.der")

thanks,
Sudhakar Kuppusamy

Quoted 1 line

Daniel

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

#32 lore raw

PATCH v2 12/21 appended signatures: documentation

In reply to Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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

---
 docs/grub.texi | 185 ++++++++++++++++++++++++++++++++++++++++++++-----
 1 file changed, 167 insertions(+), 18 deletions(-)
docs/grub.texi +167 -18
index 19bbe9b2b..25a51dee8 100644
@@ -3281,6 +3281,7 @@ These variables have special meaning to GRUB.
 
 @menu
 * biosnum::
+* check_appended_signatures::
 * check_signatures::
 * chosen::
 * cmdpath::
@@ -3343,12 +3344,16 @@ this.
 For an alternative approach which also changes BIOS drive mappings for the
 chain-loaded system, @pxref{drivemap}.
 
+@node check_appended_signatures
+@subsection check_appended_signatures
+This variable controls whether GRUB enforces appended signature validation on
+certain loaded files. @xref{Using appended signatures}.
 
 @node check_signatures
 @subsection check_signatures
 
-This variable controls whether GRUB enforces digital signature
-validation on loaded files. @xref{Using digital signatures}.
+This variable controls whether GRUB enforces GPG-style digital signature
+validation on loaded files. @xref{Using GPG-style digital signatures}.
 
 @node chosen
 @subsection chosen
@@ -6432,6 +6437,7 @@ you forget a command, you can run the command @command{help}
 * date::                        Display or set current date and time
 * devicetree::                  Load a device tree blob
 * distrust::                    Remove a pubkey from trusted keys
+* distrust_certificate::        Remove a certificate from the list of trusted certificates
 * drivemap::                    Map a drive to another
 * echo::                        Display a line of text
 * efitextmode::                 Set/Get text output mode resolution
@@ -6450,6 +6456,7 @@ you forget a command, you can run the command @command{help}
 * hexdump::                     Show raw contents of a file or memory
 * insmod::                      Insert a module
 * keystatus::                   Check key modifier status
+* list_certificates::           List trusted certificates
 * list_env::                    List variables in environment block
 * list_trusted::                List trusted public keys
 * load_env::                    Load variables from environment block
@@ -6490,8 +6497,10 @@ you forget a command, you can run the command @command{help}
 * tpm2_key_protector_clear::    Clear the TPM2 key protector
 * true::                        Do nothing, successfully
 * trust::                       Add public key to list of trusted keys
+* trust_certificate::           Add an x509 certificate to the list of trusted certificates
 * unset::                       Unset an environment variable
 @comment * vbeinfo::                     List available video modes
+* verify_appended::             Verify appended digital signature
 * verify_detached::             Verify detached digital signature
 * videoinfo::                   List available video modes
 * wrmsr::                       Write values to model-specific registers
@@ -6833,7 +6842,24 @@ These keys are used to validate signatures when environment variable
 @code{check_signatures} is set to @code{enforce}
 (@pxref{check_signatures}), and by some invocations of
 @command{verify_detached} (@pxref{verify_detached}).  @xref{Using
-digital signatures}, for more information.
+GPG-style digital signatures}, for more information.
+@end deffn
+
+@node distrust_certificate
+@subsection distrust_certificate
+
+@deffn Command distrust_certificate cert_number
+Remove the x509 certificate numbered @var{cert_number} from GRUB's keyring of
+trusted x509 certificates for verifying appended signatures.
+
+@var{cert_number} is the certificate number as listed by
+@command{list_certificates} (@pxref{list_certificates}).
+
+These certificates are used to validate appended signatures when environment
+variable @code{check_appended_signatures} is set to @code{enforce}
+(@pxref{check_appended_signatures}), and by @command{verify_appended}
+(@pxref{verify_appended}). See @xref{Using appended signatures} for more
+information.
 @end deffn
 
 @node drivemap
@@ -7229,6 +7255,19 @@ without any options, the @command{keystatus} command returns true if and
 only if checking key modifier status is supported.
 @end deffn
 
+@node list_certificates
+@subsection list_certificates
+
+@deffn Command list_certificates
+List all x509 certificates trusted by GRUB for validating appended signatures.
+The output is a numbered list of certificates, showing the certificate's serial
+number and Common Name.
+
+The certificate number can be used as an argument to
+@command{distrust_certificate} (@pxref{distrust_certificate}).
+
+See @xref{Using appended signatures} for more information.
+@end deffn
 
 @node list_env
 @subsection list_env
@@ -7249,7 +7288,7 @@ The output is in GPG's v4 key fingerprint format (i.e., the output of
 @code{gpg --fingerprint}).  The least significant four bytes (last
 eight hexadecimal digits) can be used as an argument to
 @command{distrust} (@pxref{distrust}).
-@xref{Using digital signatures}, for more information about uses for
+@xref{Using GPG-style digital signatures}, for more information about uses for
 these keys.
 @end deffn
 
@@ -7284,8 +7323,11 @@ When used with care, @option{--skip-sig} and the whitelist enable an
 administrator to configure a system to boot only signed
 configurations, but to allow the user to select from among multiple
 configurations, and to enable ``one-shot'' boot attempts and
-``savedefault'' behavior.  @xref{Using digital signatures}, for more
+``savedefault'' behavior.  @xref{Using GPG-style digital signatures}, for more
 information.
+Extra care should be taken when combining this command with appended signatures
+(@pxref{Using appended signatures}), as this file is not validated by an
+appended signature and could set @code{check_appended_signatures=no}.
 @end deffn
 
 
@@ -7656,7 +7698,7 @@ read.  It is possible to modify a digitally signed environment block
 file from within GRUB using this command, such that its signature will
 no longer be valid on subsequent boots.  Care should be taken in such
 advanced configurations to avoid rendering the system
-unbootable. @xref{Using digital signatures}, for more information.
+unbootable. @xref{Using GPG-style digital signatures}, for more information.
 @end deffn
 
 
@@ -8124,11 +8166,30 @@ signatures when environment variable @code{check_signatures} is set to
 must itself be properly signed.  The @option{--skip-sig} option can be
 used to disable signature-checking when reading @var{pubkey_file}
 itself. It is expected that @option{--skip-sig} is useful for testing
-and manual booting. @xref{Using digital signatures}, for more
+and manual booting. @xref{Using GPG-style digital signatures}, for more
 information.
 @end deffn
 
 
+@node trust_certificate
+@subsection trust_certificate
+
+@deffn Command trust_certificate x509_certificate
+Read a DER-formatted x509 certificate from the file @var{x509_certificate}
+and add it to GRUB's internal list of trusted x509 certificates. These
+certificates are used to validate appended signatures when the environment
+variable @code{check_appended_signatures} is set to @code{enforce}.
+
+Note that if @code{check_appended_signatures} is set to @code{enforce}
+when @command{trust_certificate} is executed, then @var{x509_certificate}
+must itself bear an appended signature. (It is not sufficient that
+@var{x509_certificate} be signed by a trusted certificate according to the
+x509 rules: GRUB does not include support for validating signatures within x509
+certificates themselves.)
+
+See @xref{Using appended signatures} for more information.
+@end deffn
+
 @node unset
 @subsection unset
 
@@ -8147,6 +8208,18 @@ only on PC BIOS platforms.
 @end deffn
 @end ignore
 
+@node verify_appended
+@subsection verify_appended
+
+@deffn Command verify_appended file
+Verifies an appended signature on @var{file} against the trusted certificates
+known to GRUB (See @pxref{list_certificates}, @pxref{trust_certificate}, and
+@pxref{distrust_certificate}).
+Exit code @code{$?} is set to 0 if the signature validates
+successfully.  If validation fails, it is set to a non-zero value.
+
+See @xref{Using appended signatures}, for more information.
+@end deffn
 
 @node verify_detached
 @subsection verify_detached
@@ -8165,7 +8238,7 @@ tried.
 
 Exit code @code{$?} is set to 0 if the signature validates
 successfully.  If validation fails, it is set to a non-zero value.
-@xref{Using digital signatures}, for more information.
+@xref{Using GPG-style digital signatures}, for more information.
 @end deffn
 
 @node videoinfo
@@ -8625,14 +8698,15 @@ environment variables and commands are listed in the same order.
 @chapter Security
 
 @menu
-* Authentication and authorisation:: Users and access control
-* Using digital signatures::         Booting digitally signed code
-* UEFI secure boot and shim::        Booting digitally signed PE files
-* Secure Boot Advanced Targeting::   Embedded information for generation number based revocation
-* Measured Boot::                    Measuring boot components
-* Lockdown::                         Lockdown when booting on a secure setup
-* TPM2 key protector::               Managing disk key with TPM2 key protector
-* Signing GRUB itself::              Ensuring the integrity of the GRUB core image
+* Authentication and authorisation::   Users and access control
+* Using GPG-style digital signatures:: Booting digitally signed code
+* Using appended signatures::          An alternative approach to booting digitally signed code
+* UEFI secure boot and shim::          Booting digitally signed PE files
+* Secure Boot Advanced Targeting::     Embedded information for generation number based revocation
+* Measured Boot::                      Measuring boot components
+* Lockdown::                           Lockdown when booting on a secure setup
+* 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
@@ -8708,8 +8782,8 @@ generating configuration files with authentication.  You can use
 adding @kbd{set superusers=} and @kbd{password} or @kbd{password_pbkdf2}
 commands.
 
-@node Using digital signatures
-@section Using digital signatures in GRUB
+@node Using GPG-style digital signatures
+@section Using GPG-style digital signatures in GRUB
 
 GRUB's @file{core.img} can optionally provide enforcement that all files
 subsequently read from disk are covered by a valid digital signature.
@@ -8792,6 +8866,81 @@ or BIOS) configuration to cause the machine to boot from a different
 (attacker-controlled) device.  GRUB is at best only one link in a
 secure boot chain.
 
+@node Using appended signatures
+@section Using appended signatures in GRUB
+
+GRUB supports verifying Linux-style 'appended signatures' for secure boot.
+Appended signatures are PKCS#7 messages containing a signature over the
+contents of a file, plus some metadata, appended to the end of a file. A file
+with an appended signature ends with the magic string:
+
+@example
+~Module signature appended~\n
+@end example
+
+where @code{\n} represents the line feed character, @code{0x0a}.
+
+To enable appended signature verification, load the appendedsig module and an
+x509 certificate for verification. Building the appendedsig module into the
+core grub image is recommended.
+
+Certificates can be managed at boot time using the @pxref{trust_certificate},
+@pxref{distrust_certificate} and @pxref{list_certificates} commands.
+Certificates can also be built in to the core image using the @code{--x509}
+parameter to @command{grub-install} or @command{grub-mkimage}.
+A file can be explicitly verified using the @pxref{verify_appended} command.
+
+Only signatures made with the SHA-256 or SHA-512 hash algorithm are supported,
+and only RSA signatures are supported.
+
+A file can be signed with the @command{sign-file} utility supplied with the
+Linux kernel source. For example, if you have @code{signing.key} as the private
+key and @code{certificate.der} as the x509 certificate containing the public key:
+
+@example
+sign-file SHA256 signing.key certificate.der vmlinux vmlinux.signed
+@end example
+
+Enforcement of signature verification is controlled by the
+@code{check_appended_signatures} variable. Verification will only take place
+when files are loaded if the variable is set to @code{enforce}. If a
+certificate is built into the grub core image with the @code{--x509} parameter,
+the variable will be automatically set to @code{enforce} when the appendedsig
+module is loaded.
+
+Unlike GPG-style signatures, not all files loaded by GRUB are required to be
+signed. Once verification is turned on, the following file types must carry
+appended signatures:
+
+@enumerate
+@item Linux, Multiboot, BSD, XNU and Plan9 kernels
+@item Grub modules, except those built in to the core image
+@item Any new certificate files to be trusted
+@end enumerate
+
+ACPI tables and Device Tree images will not be checked for appended signatures
+but must be verified by another mechanism such as GPG-style signatures before
+they will be loaded.
+
+No attempt is made to validate any other file type. In particular,
+chain-loaded binaries are not verified - if your platform supports
+chain-loading and this cannot be disabled, consider an alternative secure
+boot mechanism.
+
+As with GPG-style appended signatures, signature checking does @strong{not}
+stop an attacker with console access from dropping manually to the GRUB
+console and executing:
+
+@example
+set check_appended_signatures=no
+@end example
+
+Refer to the section on password-protecting GRUB (@pxref{Authentication
+and authorisation}) for more information on preventing this.
+
+Additionally, special care must be taken around the @command{loadenv} command,
+which can be used to turn off @code{check_appended_signature}.
+
 @node UEFI secure boot and shim
 @section UEFI secure boot and shim support
 
Signature · 7 lines
2.43.5


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

PATCH v2 13/21 ieee1275: enter lockdown based on /ibm,secure-boot

In reply to Sudhakar Kuppusamy

From: Daniel Axtens <[email protected]>

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

---
 docs/grub.texi                 |  2 +-
 grub-core/Makefile.core.def    |  1 +
 grub-core/kern/ieee1275/init.c | 35 ++++++++++++++++++++++++++++++++++
 include/grub/lockdown.h        |  3 ++-
 4 files changed, 39 insertions(+), 2 deletions(-)
docs/grub.texi +1 -1
index 25a51dee8..52e26c8fd 100644
@@ -9019,7 +9019,7 @@ platforms.
 @section Lockdown when booting on a secure setup
 
 The GRUB can be locked down when booted on a secure boot environment, for example
-if the UEFI secure boot is enabled. On a locked down configuration, the GRUB will
+if the UEFI or Power secure boot is enabled. On a locked down configuration, the GRUB will
 be restricted and some operations/commands cannot be executed. This also includes
 limiting which filesystems are supported to those thought to be more robust and
 widely used within GRUB.
grub-core/Makefile.core.def +1 -0
index 9cf4a6009..1ed55b0e3 100644
@@ -331,6 +331,7 @@ kernel = {
   powerpc_ieee1275 = kern/powerpc/cache.S;
   powerpc_ieee1275 = kern/powerpc/dl.c;
   powerpc_ieee1275 = kern/powerpc/compiler-rt.S;
+  powerpc_ieee1275 = kern/lockdown.c;
 
   sparc64_ieee1275 = kern/sparc64/cache.S;
   sparc64_ieee1275 = kern/sparc64/dl.c;
grub-core/kern/ieee1275/init.c +35 -0
index dfbd0b899..ba3cb7cfa 100644
@@ -49,6 +49,7 @@
 #if defined(__powerpc__) || defined(__i386__)
 #include <grub/ieee1275/alloc.h>
 #endif
+#include <grub/lockdown.h>
 
 /* The maximum heap size we're going to claim at boot. Not used by sparc. */
 #ifdef __i386__
@@ -953,6 +954,38 @@ grub_parse_cmdline (void)
     }
 }
 
+static void
+grub_get_ieee1275_secure_boot (void)
+{
+  grub_ieee1275_phandle_t root;
+  int rc;
+  grub_uint32_t is_sb;
+
+  if (grub_ieee1275_finddevice ("/", &root))
+    {
+      grub_error (GRUB_ERR_UNKNOWN_DEVICE, "couldn't find / node");
+      return;
+    }
+
+  rc = grub_ieee1275_get_integer_property (root, "ibm,secure-boot", &is_sb, sizeof (is_sb), 0);
+  if (rc < 0)
+    {
+      grub_error (GRUB_ERR_UNKNOWN_DEVICE, "couldn't examine /ibm,secure-boot property");
+      return;
+    }
+  /*
+   * ibm,secure-boot:
+   * 0 - disabled
+   * 1 - audit
+   * 2 - enforce
+   * 3 - enforce + OS-specific behaviour
+   *
+   * We only support enforce.
+   */
+  if (is_sb >= 2)
+    grub_lockdown ();
+}
+
 grub_addr_t grub_modbase;
 
 void
@@ -978,6 +1011,8 @@ grub_machine_init (void)
 #else
   grub_install_get_time_ms (grub_rtc_get_time_ms);
 #endif
+
+  grub_get_ieee1275_secure_boot ();
 }
 
 void
include/grub/lockdown.h +2 -1
index 40531fa82..ebfee4bf0 100644
@@ -24,7 +24,8 @@
 #define GRUB_LOCKDOWN_DISABLED       0
 #define GRUB_LOCKDOWN_ENABLED        1
 
-#ifdef GRUB_MACHINE_EFI
+#if defined(GRUB_MACHINE_EFI) || \
+    (defined(__powerpc__) && defined(GRUB_MACHINE_IEEE1275))
 extern void
 EXPORT_FUNC (grub_lockdown) (void);
 extern int
Signature · 7 lines
2.43.5


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

PATCH v2 14/21 ieee1275: Platform Keystore (PKS) Support

In reply to Sudhakar Kuppusamy

enhancing the infrastructure to enable the Platform Keystore (PKS) feature, which provides access to the SB VERSION, DB, and DBX secure boot variables from PKS.

---
 grub-core/Makefile.am                      |   1 +
 grub-core/Makefile.core.def                |   1 +
 grub-core/kern/powerpc/ieee1275/ieee1275.c | 140 +++++++++++++++++++++
 include/grub/powerpc/ieee1275/ieee1275.h   |  14 +++
 4 files changed, 156 insertions(+)
 create mode 100644 grub-core/kern/powerpc/ieee1275/ieee1275.c
grub-core/Makefile.am +1 -0
index e50db8106..b516e139b 100644
@@ -241,6 +241,7 @@ KERNEL_HEADER_FILES += $(top_builddir)/include/grub/machine/kernel.h
 endif
 
 if COND_powerpc_ieee1275
+KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/powerpc/ieee1275/ieee1275.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/ieee1275/ieee1275.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/ieee1275/alloc.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/terminfo.h
grub-core/Makefile.core.def +1 -0
index 1ed55b0e3..95bccce5d 100644
@@ -328,6 +328,7 @@ kernel = {
   extra_dist = video/sis315_init.c;
   mips_loongson = commands/keylayouts.c;
 
+  powerpc_ieee1275 = kern/powerpc/ieee1275/ieee1275.c;
   powerpc_ieee1275 = kern/powerpc/cache.S;
   powerpc_ieee1275 = kern/powerpc/dl.c;
   powerpc_ieee1275 = kern/powerpc/compiler-rt.S;
grub-core/kern/powerpc/ieee1275/ieee1275.c new file +140 -0

140 lines not on this page · raw message

include/grub/powerpc/ieee1275/ieee1275.h +14 -0
index 4eb207018..0d48331c2 100644
@@ -28,4 +28,18 @@ typedef grub_uint32_t grub_ieee1275_cell_t;
 #define PRIxGRUB_IEEE1275_CELL_T	PRIxGRUB_UINT32_T
 #define PRIuGRUB_IEEE1275_CELL_T	PRIuGRUB_UINT32_T
 
+int EXPORT_FUNC (grub_ieee1275_test) (const char *name,
+                                      grub_ieee1275_cell_t *missing);
+
+int grub_ieee1275_pks_max_object_size (grub_size_t *result);
+
+int grub_ieee1275_pks_read_object (grub_uint8_t consumer, grub_uint8_t *label,
+                                   grub_size_t label_len, grub_uint8_t *buffer,
+                                   grub_size_t buffer_len, grub_size_t *data_len,
+                                   grub_uint32_t *policies);
+
+int grub_ieee1275_pks_read_sbvar (grub_uint8_t sbvarflags, grub_uint8_t sbvartype,
+                                  grub_uint8_t *buffer, grub_size_t buffer_len,
+                                  grub_size_t *data_len);
+
 #endif /* ! GRUB_IEEE1275_MACHINE_HEADER */
Signature · 7 lines
2.43.5


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

PATCH v2 15/21 ieee1275: Read the DB and DBX secure boot variables

In reply to Sudhakar Kuppusamy

If secure boot is enabled with PKS, it will read secure boot variables such as db and dbx from PKS and extract ESL's from it.
The ESL's would be saved in the platform keystore buffer, and the appendedsig (module) would read it later to extract
the certificate's details from ESL.

In the following scenarios, static key mode will be activated:
1. When Secure Boot is enabled with static keys
2. When SB Version is unavailable but Secure Boot is enabled
3. When PKS support is unavailable but Secure Boot is enabled

Note:-

SB Version - Secure Boot mode
1 - PKS
0 - static key (embeded key)

---
 grub-core/Makefile.am                         |   1 +
 grub-core/Makefile.core.def                   |   1 +
 grub-core/kern/ieee1275/init.c                |  15 +-
 .../kern/powerpc/ieee1275/platform_keystore.c | 332 ++++++++++++++++++
 .../grub/powerpc/ieee1275/platform_keystore.h | 225 ++++++++++++
 include/grub/types.h                          |   9 +
 6 files changed, 581 insertions(+), 2 deletions(-)
 create mode 100644 grub-core/kern/powerpc/ieee1275/platform_keystore.c
 create mode 100644 include/grub/powerpc/ieee1275/platform_keystore.h
grub-core/Makefile.am +1 -0
index b516e139b..cd6bb7c32 100644
@@ -247,6 +247,7 @@ KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/ieee1275/alloc.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/terminfo.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/extcmd.h
 KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/lib/arg.h
+KERNEL_HEADER_FILES += $(top_srcdir)/include/grub/powerpc/ieee1275/platform_keystore.h
 endif
 
 if COND_sparc64_ieee1275
grub-core/Makefile.core.def +1 -0
index 95bccce5d..2730b35f4 100644
@@ -333,6 +333,7 @@ kernel = {
   powerpc_ieee1275 = kern/powerpc/dl.c;
   powerpc_ieee1275 = kern/powerpc/compiler-rt.S;
   powerpc_ieee1275 = kern/lockdown.c;
+  powerpc_ieee1275 = kern/powerpc/ieee1275/platform_keystore.c;
 
   sparc64_ieee1275 = kern/sparc64/cache.S;
   sparc64_ieee1275 = kern/sparc64/dl.c;
grub-core/kern/ieee1275/init.c +13 -2
index ba3cb7cfa..d6ce9654d 100644
@@ -50,6 +50,8 @@
 #include <grub/ieee1275/alloc.h>
 #endif
 #include <grub/lockdown.h>
+#include <grub/powerpc/ieee1275/ieee1275.h>
+#include <grub/powerpc/ieee1275/platform_keystore.h>
 
 /* The maximum heap size we're going to claim at boot. Not used by sparc. */
 #ifdef __i386__
@@ -959,7 +961,7 @@ grub_get_ieee1275_secure_boot (void)
 {
   grub_ieee1275_phandle_t root;
   int rc;
-  grub_uint32_t is_sb;
+  grub_uint32_t is_sb = 0;
 
   if (grub_ieee1275_finddevice ("/", &root))
     {
@@ -983,7 +985,16 @@ grub_get_ieee1275_secure_boot (void)
    * We only support enforce.
    */
   if (is_sb >= 2)
-    grub_lockdown ();
+    {
+      grub_dprintf ("ieee1275", "Secure Boot Enabled\n");
+      rc = grub_pks_keystore_init ();
+      if (rc != GRUB_ERR_NONE)
+        grub_error (rc, "Initialization of the Platform Keystore failed!\n");
+
+      grub_lockdown ();
+    }
+  else
+      grub_dprintf ("ieee1275", "Secure Boot Disabled\n");
 }
 
 grub_addr_t grub_modbase;
grub-core/kern/powerpc/ieee1275/platform_keystore.c new file +332 -0

332 lines not on this page · raw message

include/grub/powerpc/ieee1275/platform_keystore.h new file +225 -0

225 lines not on this page · raw message

include/grub/types.h +9 -0
index 45079bf65..ce914decb 100644
@@ -388,4 +388,13 @@ struct grub_packed_guid
 } GRUB_PACKED;
 typedef struct grub_packed_guid grub_packed_guid_t;
 
+
+#define GRUB_UUID_SIZE 16
+typedef struct grub_uuid grub_uuid_t;
+/* The structure of a UUID.*/
+struct grub_uuid
+{
+  grub_uint8_t b[GRUB_UUID_SIZE];
+};
+
 #endif /* ! GRUB_TYPES_HEADER */
Signature · 7 lines
2.43.5


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

PATCH v2 16/21 appendedsig: The creation of trusted and distrusted lists

In reply to Sudhakar Kuppusamy

The trusted certificates and binary hashes, distrusted certificates and binary/certificate hashes will be extracted from the platform keystore buffer if Secure Boot is enabled with PKS.

In order to verify the integrity of the kernel, the extracted data needs to be stored stored in the buffer db and dbx.

The trusted certificates will be extracted from the grub ELFNOTE if Secure Boot is enabled with static key. In order to verify the integerity of the kernel, the extracted data needs to be stored in the buffer db.

Note:-

If neither the trusted certificate nor binary hash exists in the distrusted list (dbx), rejects it while extracting certificate/binary hash from the platform keystore buffer.

---
 grub-core/commands/appendedsig/appendedsig.c | 584 +++++++++++++++++--
 grub-core/kern/file.c                        |  34 ++
 include/grub/file.h                          |   1 +
 3 files changed, 577 insertions(+), 42 deletions(-)
grub-core/commands/appendedsig/appendedsig.c +542 -42
index cbd227a3c..b24112050 100644
@@ -34,7 +34,7 @@
 #include <libtasn1.h>
 #include <grub/env.h>
 #include <grub/lockdown.h>
-
+#include <grub/powerpc/ieee1275/platform_keystore.h>
 #include "appendedsig.h"
 
 GRUB_MOD_LICENSE ("GPLv3+");
@@ -64,8 +64,23 @@ struct grub_appended_signature
   struct pkcs7_signedData pkcs7;        /* Parsed PKCS#7 data */
 };
 
-/* Trusted certificates for verifying appended signatures */
-struct x509_certificate *grub_trusted_key;
+/* This represents a trusted/distrusted list*/
+struct grub_database
+{
+  struct x509_certificate *keys; /* Certificates */
+  grub_size_t key_entries;       /* Number of certificates */
+  grub_uint8_t **signatures;     /* Certificate/binary hashes */
+  grub_size_t *signature_size;   /* Size of certificate/binary hashes */
+  grub_size_t signature_entries; /* Number of certificate/binary hashes */
+};
+
+/* Trusted list */
+struct grub_database db = {.keys = NULL, .key_entries = 0, .signatures = NULL,
+                           .signature_size = NULL, .signature_entries = 0};
+
+/* Distrusted list */
+struct grub_database dbx = {.signatures = NULL, .signature_size = NULL,
+                            .signature_entries = 0};
 
 /*
  * Force gcry_rsa to be a module dependency.
@@ -87,6 +102,13 @@ struct x509_certificate *grub_trusted_key;
  * also resolves our concerns about loading from the filesystem.
  */
 extern gcry_pk_spec_t _gcry_pubkey_spec_rsa;
+extern gcry_md_spec_t _gcry_digest_spec_sha224;
+extern gcry_md_spec_t _gcry_digest_spec_sha384;
+
+/* Free trusted list memory */
+static void free_trusted_list (void);
+/* Free distrusted list memory */
+static void free_distrusted_list (void);
 
 static enum
 {
@@ -95,6 +117,204 @@ static enum
   check_sigs_forced = 2
 } check_sigs = check_sigs_no;
 
+/*
+ * GUID can be used to determine the hashing function and
+ * generate the hash using determined hashing function.
+ */
+static grub_err_t
+get_hash (const grub_uuid_t *guid, const grub_uint8_t *data, const grub_size_t data_size,
+          grub_uint8_t *hash, grub_size_t *hash_size)
+{
+  gcry_md_spec_t *hash_func = NULL;
+
+  if (guid == NULL)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE, "GUID is null");
+
+  if (grub_memcmp (guid, &GRUB_PKS_CERT_SHA256_GUID, GRUB_UUID_SIZE) == 0 ||
+           grub_memcmp (guid, &GRUB_PKS_CERT_X509_SHA256_GUID, GRUB_UUID_SIZE) == 0)
+    hash_func = &_gcry_digest_spec_sha256;
+  else if (grub_memcmp (guid, &GRUB_PKS_CERT_SHA384_GUID, GRUB_UUID_SIZE) == 0 ||
+           grub_memcmp (guid, &GRUB_PKS_CERT_X509_SHA384_GUID, GRUB_UUID_SIZE) == 0)
+    hash_func = &_gcry_digest_spec_sha384;
+  else if (grub_memcmp (guid, &GRUB_PKS_CERT_SHA512_GUID, GRUB_UUID_SIZE) == 0 ||
+           grub_memcmp (guid, &GRUB_PKS_CERT_X509_SHA512_GUID, GRUB_UUID_SIZE) == 0)
+    hash_func = &_gcry_digest_spec_sha512;
+  else
+    return grub_error (GRUB_ERR_OUT_OF_RANGE, "Unsupported GUID for hash");
+
+  grub_memset (hash, 0, GRUB_MAX_HASH_SIZE);
+  grub_crypto_hash (hash_func, hash, data, data_size);
+  *hash_size =  hash_func->mdlen;
+
+  return GRUB_ERR_NONE;
+}
+
+/* Add the certificate/binary hash into the trusted/distrusted list */
+static grub_err_t
+add_hash (const grub_uint8_t **data, const grub_size_t data_size,
+          grub_uint8_t ***signature_list, grub_size_t **signature_size_list,
+          grub_size_t *signature_list_entries)
+{
+  grub_uint8_t **signatures = *signature_list;
+  grub_size_t *signature_size = *signature_size_list;
+  grub_size_t signature_entries = *signature_list_entries;
+
+  if (*data == NULL || data_size == 0)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE, "certificate/binary hash data/size is null");
+
+  signatures = grub_realloc (signatures, sizeof (grub_uint8_t *) * (signature_entries + 1));
+  signature_size = grub_realloc (signature_size,
+                                 sizeof (grub_size_t) * (signature_entries + 1));
+
+  if (signatures == NULL || signature_size == NULL)
+    {
+      /*
+       * allocated memory will be freed by
+       * free_trusted_list/free_distrusted_list
+       */
+      if (signatures != NULL)
+        {
+          *signature_list = signatures;
+          *signature_list_entries = signature_entries + 1;
+        }
+
+      if (signature_size != NULL)
+        *signature_size_list = signature_size;
+
+      return grub_error (GRUB_ERR_OUT_OF_MEMORY, "out of memory");
+    }
+
+  signatures[signature_entries] = (grub_uint8_t *) *data;
+  signature_size[signature_entries] = data_size;
+  signature_entries++;
+  *data = NULL;
+
+  *signature_list = signatures;
+  *signature_size_list = signature_size;
+  *signature_list_entries = signature_entries;
+
+  return GRUB_ERR_NONE;
+}
+
+static int
+is_x509 (const grub_uuid_t *guid)
+{
+  if (grub_memcmp (guid, &GRUB_PKS_CERT_X509_GUID, GRUB_UUID_SIZE) == 0)
+    return GRUB_ERR_NONE;
+
+  return GRUB_ERR_UNKNOWN_COMMAND;
+}
+
+static int
+is_cert_match (const struct x509_certificate *distrusted_cert,
+               const struct x509_certificate *db_cert)
+{
+
+  if (grub_memcmp (distrusted_cert->subject, db_cert->subject, db_cert->subject_len) == 0
+      && grub_memcmp (distrusted_cert->serial, db_cert->serial, db_cert->serial_len) == 0
+      && grub_memcmp (distrusted_cert->mpis[0], db_cert->mpis[0], sizeof (db_cert->mpis[0])) == 0
+      && grub_memcmp (distrusted_cert->mpis[1], db_cert->mpis[1], sizeof (db_cert->mpis[1])) == 0)
+    return GRUB_ERR_NONE;
+
+  return GRUB_ERR_UNKNOWN_COMMAND;
+}
+
+/*
+ * Verify the certificate against the certificate from platform keystore buffer's
+ * distrusted list.
+ */
+static grub_err_t
+is_distrusted_cert (const struct x509_certificate *db_cert)
+{
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_size_t i = 0;
+  struct x509_certificate *distrusted_cert = NULL;
+
+  for (i = 0; i < grub_pks_keystore.dbx_entries; i++)
+    {
+      if (grub_pks_keystore.dbx[i].data == NULL)
+        continue;
+
+      if (is_x509 (&grub_pks_keystore.dbx[i].guid) == GRUB_ERR_NONE)
+        {
+          distrusted_cert = grub_zalloc (sizeof (struct x509_certificate));
+          if (distrusted_cert == NULL)
+            return grub_error (GRUB_ERR_OUT_OF_MEMORY, "out of memory");
+
+          rc = parse_x509_certificate (grub_pks_keystore.dbx[i].data,
+                                       grub_pks_keystore.dbx[i].data_size, distrusted_cert);
+          if (rc != GRUB_ERR_NONE)
+            {
+              grub_free (distrusted_cert);
+              continue;
+            }
+
+          if (is_cert_match (distrusted_cert, db_cert) == GRUB_ERR_NONE)
+            {
+              grub_printf ("Warning: a trusted certificate CN='%s' is ignored "
+                           "because it is on the distrusted list (dbx).\n", db_cert->subject);
+              grub_free (grub_pks_keystore.dbx[i].data);
+              grub_memset (&grub_pks_keystore.dbx[i], 0, sizeof (grub_pks_sd_t));
+              certificate_release (distrusted_cert);
+              grub_free (distrusted_cert);
+              return GRUB_ERR_ACCESS_DENIED;
+            }
+
+          certificate_release (distrusted_cert);
+          grub_free (distrusted_cert);
+        }
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+/* Add the certificate into the trusted/distrusted list */
+static grub_err_t
+add_certificate (const grub_uint8_t *data, const grub_size_t data_size,
+                 struct grub_database *database, const grub_size_t is_db)
+{
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_size_t key_entries = database->key_entries;
+  struct x509_certificate *cert = NULL;
+
+  if (data == NULL || data_size == 0)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE, "certificate data/size is null");
+
+  cert = grub_zalloc (sizeof (struct x509_certificate));
+  if (cert == NULL)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY, "out of memory");
+
+  rc = parse_x509_certificate (data, data_size, cert);
+  if (rc != GRUB_ERR_NONE)
+    {
+      grub_dprintf ("appendedsig", "skipping %s certificate (%d)\n",
+                    (is_db ? "trusted":"distrusted"), rc);
+      grub_free (cert);
+      return rc;
+    }
+
+  if (is_db)
+    {
+      rc = is_distrusted_cert (cert);
+      if (rc != GRUB_ERR_NONE)
+        {
+          certificate_release (cert);
+          grub_free (cert);
+          return rc;
+        }
+    }
+
+  grub_dprintf ("appendedsig", "add a %s certificate CN='%s'\n",
+                (is_db ? "trusted":"distrusted"), cert->subject);
+
+  key_entries++;
+  cert->next = database->keys;
+  database->keys = cert;
+  database->key_entries = key_entries;
+
+  return rc;
+}
+
 static const char *
 grub_env_read_sec (struct grub_env_var *var __attribute__ ((unused)),
                    const char *val __attribute__ ((unused)))
@@ -248,7 +468,7 @@ grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize)
   struct pkcs7_signerInfo *si;
   int i;
 
-  if (!grub_trusted_key)
+  if (!db.key_entries)
     return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("No trusted keys to verify against"));
 
   err = extract_appended_signature (buf, bufsize, &sig);
@@ -279,7 +499,7 @@ grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize)
                     datasize, i, hash[0], hash[1], hash[2], hash[3]);
 
       err = GRUB_ERR_BAD_SIGNATURE;
-      for (pk = grub_trusted_key; pk; pk = pk->next)
+      for (pk = db.keys; pk; pk = pk->next)
         {
           rc = grub_crypto_rsa_pad (&hashmpi, hash, si->hash, pk->mpis[0]);
           if (rc)
@@ -376,16 +596,16 @@ grub_cmd_distrust (grub_command_t cmd __attribute__ ((unused)), int argc, char *
 
   if (cert_num == 1)
     {
-      cert = grub_trusted_key;
-      grub_trusted_key = cert->next;
+      cert = db.keys;
+      db.keys = cert->next;
 
       certificate_release (cert);
       grub_free (cert);
       return GRUB_ERR_NONE;
     }
   i = 2;
-  prev = grub_trusted_key;
-  cert = grub_trusted_key->next;
+  prev = db.keys;
+  cert = db.keys->next;
   while (cert)
     {
       if (i == cert_num)
@@ -432,8 +652,8 @@ grub_cmd_trust (grub_command_t cmd __attribute__ ((unused)), int argc, char **ar
     }
   grub_dprintf ("appendedsig", "Loaded certificate with CN: %s\n", cert->subject);
 
-  cert->next = grub_trusted_key;
-  grub_trusted_key = cert;
+  cert->next = db.keys;
+  db.keys = cert;
 
   return GRUB_ERR_NONE;
 }
@@ -446,7 +666,7 @@ grub_cmd_list (grub_command_t cmd __attribute__ ((unused)), int argc __attribute
   int cert_num = 1;
   grub_size_t i;
 
-  for (cert = grub_trusted_key; cert; cert = cert->next)
+  for (cert = db.keys; cert; cert = cert->next)
     {
       grub_printf (N_("Certificate %d:\n"), cert_num);
 
@@ -539,6 +759,274 @@ static struct grub_fs pseudo_fs = { .name = "pseudo", .fs_read = pseudo_read };
 
 static grub_command_t cmd_verify, cmd_list, cmd_distrust, cmd_trust;
 
+/*
+ * Verify the trusted certificate against the certificate hashes from platform keystore buffer's
+ * distrusted list.
+ */
+static grub_err_t
+is_distrusted_cert_hash (const grub_uint8_t *data, const grub_size_t data_size)
+{
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_size_t i = 0, cert_hash_size = 0;
+  grub_uint8_t cert_hash[GRUB_MAX_HASH_SIZE] = { 0 };
+
+  if (data == NULL || data_size == 0)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE, "trusted certificate data/size is null");
+
+  for (i = 0; i < grub_pks_keystore.dbx_entries; i++)
+    {
+      if (grub_pks_keystore.dbx[i].data == NULL ||
+          grub_pks_keystore.dbx[i].data_size == 0)
+        continue;
+
+      rc = get_hash (&grub_pks_keystore.dbx[i].guid, data, data_size,
+                     cert_hash, &cert_hash_size);
+      if (rc != GRUB_ERR_NONE)
+        continue;
+
+      if (cert_hash_size == grub_pks_keystore.dbx[i].data_size &&
+          grub_memcmp (grub_pks_keystore.dbx[i].data, cert_hash, cert_hash_size) == 0)
+        {
+          grub_printf ("Warning: a trusted certificate (%02x%02x%02x%02x) is ignored "
+                       "because this certificate hash is on the distrusted list (dbx).\n",
+                       cert_hash[0], cert_hash[1], cert_hash[2], cert_hash[3]);
+          grub_free (grub_pks_keystore.dbx[i].data);
+          grub_memset (&grub_pks_keystore.dbx[i], 0, sizeof (grub_pks_keystore.dbx[i]));
+          return GRUB_ERR_BAD_SIGNATURE;
+        }
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+/*
+ * Verify the trusted binary hash against the platform keystore buffer's
+ * distrusted list.
+ */
+static grub_err_t
+is_distrusted_binary_hash (const grub_uint8_t *binary_hash,
+                           const grub_size_t binary_hash_size)
+{
+  grub_size_t i = 0;
+
+  for (i = 0; i < grub_pks_keystore.dbx_entries; i++)
+    {
+      if (grub_pks_keystore.dbx[i].data == NULL ||
+          grub_pks_keystore.dbx[i].data_size == 0)
+        continue;
+
+      if (binary_hash_size == grub_pks_keystore.dbx[i].data_size &&
+          grub_memcmp (grub_pks_keystore.dbx[i].data, binary_hash, binary_hash_size) == 0)
+        {
+          grub_printf ("Warning: a trusted binary hash (%02x%02x%02x%02x) is ignored"
+                       " because it is on the distrusted list (dbx).\n",
+                       binary_hash[0], binary_hash[1], binary_hash[2], binary_hash[3]);
+          grub_free (grub_pks_keystore.dbx[i].data);
+          grub_memset (&grub_pks_keystore.dbx[i], 0, sizeof(grub_pks_keystore.dbx[i]));
+          return GRUB_ERR_BAD_SIGNATURE;
+        }
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+/*
+ * Extract the binary hashes from the platform keystore buffer,
+ * and add it to the trusted list if it does not exist in the distrusted list.
+ */
+static grub_err_t
+add_trusted_binary_hash (const grub_uint8_t **data, const grub_size_t data_size)
+{
+  grub_err_t rc = GRUB_ERR_NONE;
+
+  if (*data == NULL || data_size == 0)
+    return grub_error (GRUB_ERR_OUT_OF_RANGE, "trusted binary hash data/size is null");
+
+  rc = is_distrusted_binary_hash (*data, data_size);
+  if (rc != GRUB_ERR_NONE)
+    return rc;
+
+  rc = add_hash (data, data_size, &db.signatures, &db.signature_size,
+                 &db.signature_entries);
+  return rc;
+}
+
+static int
+is_hash (const grub_uuid_t *guid)
+{
+  /* GUID type of the binary hash */
+  if (grub_memcmp (guid, &GRUB_PKS_CERT_SHA256_GUID, GRUB_UUID_SIZE) == 0 ||
+      grub_memcmp (guid, &GRUB_PKS_CERT_SHA384_GUID, GRUB_UUID_SIZE) == 0 ||
+      grub_memcmp (guid, &GRUB_PKS_CERT_SHA512_GUID, GRUB_UUID_SIZE) == 0)
+    return GRUB_ERR_NONE;
+
+  /* GUID type of the certificate hash */
+  if (grub_memcmp (guid, &GRUB_PKS_CERT_X509_SHA256_GUID, GRUB_UUID_SIZE) == 0 ||
+      grub_memcmp (guid, &GRUB_PKS_CERT_X509_SHA384_GUID, GRUB_UUID_SIZE) == 0 ||
+      grub_memcmp (guid, &GRUB_PKS_CERT_X509_SHA512_GUID, GRUB_UUID_SIZE) == 0)
+    return GRUB_ERR_NONE;
+
+  return GRUB_ERR_UNKNOWN_COMMAND;
+}
+
+/*
+ * Extract the x509 certificates/binary hashes from the platform keystore buffer,
+ * parse it, and add it to the trusted list.
+ */
+static grub_err_t
+create_trusted_list (void)
+{
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_size_t i = 0;
+
+  for (i = 0; i < grub_pks_keystore.db_entries; i++)
+    {
+      if (is_hash (&grub_pks_keystore.db[i].guid) == GRUB_ERR_NONE)
+        {
+          rc = add_trusted_binary_hash ((const grub_uint8_t **)
+                                        &grub_pks_keystore.db[i].data,
+                                        grub_pks_keystore.db[i].data_size);
+          if (rc == GRUB_ERR_OUT_OF_MEMORY)
+            return rc;
+        }
+      else if (is_x509 (&grub_pks_keystore.db[i].guid) == GRUB_ERR_NONE)
+        {
+          rc = is_distrusted_cert_hash (grub_pks_keystore.db[i].data,
+                                        grub_pks_keystore.db[i].data_size);
+          if (rc != GRUB_ERR_NONE)
+            continue;
+
+          rc = add_certificate (grub_pks_keystore.db[i].data,
+                                grub_pks_keystore.db[i].data_size, &db, 1);
+          if (rc == GRUB_ERR_OUT_OF_MEMORY)
+            return rc;
+          else if (rc != GRUB_ERR_NONE)
+            continue;
+        }
+      else
+        grub_dprintf ("appendedsig", "unsupported signature data type and "
+                      "skipping trusted data (%" PRIuGRUB_SIZE ")\n", i + 1);
+    }
+
+  return GRUB_ERR_NONE;
+}
+
+/*
+ * Extract the certificates, certificate/binary hashes out of the platform keystore buffer,
+ * and add it to the distrusted list.
+ */
+static grub_err_t
+create_distrusted_list (void)
+{
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_size_t i = 0;
+
+  for (i = 0; i < grub_pks_keystore.dbx_entries; i++)
+    {
+      if (grub_pks_keystore.dbx[i].data != NULL ||
+          grub_pks_keystore.dbx[i].data_size > 0)
+        {
+          if (is_x509 (&grub_pks_keystore.dbx[i].guid) == GRUB_ERR_NONE)
+            {
+              rc = add_certificate (grub_pks_keystore.dbx[i].data,
+                                    grub_pks_keystore.dbx[i].data_size, &dbx, 0);
+              if (rc == GRUB_ERR_OUT_OF_MEMORY)
+                return rc;
+            }
+          else if (is_hash (&grub_pks_keystore.dbx[i].guid) == GRUB_ERR_NONE)
+            {
+              rc = add_hash ((const grub_uint8_t **) &grub_pks_keystore.dbx[i].data,
+                             grub_pks_keystore.dbx[i].data_size,
+                             &dbx.signatures, &dbx.signature_size,
+                             &dbx.signature_entries);
+              if (rc != GRUB_ERR_NONE)
+                return rc;
+            }
+          else
+            grub_dprintf ("appendedsig", "unsupported signature data type and "
+                          "skipping distrusted data (%" PRIuGRUB_SIZE ")\n", i + 1);
+        }
+    }
+
+  return rc;
+}
+
+/*
+ * Extract the x509 certificates from the ELF note header,
+ * parse it, and add it to the trusted list.
+ */
+static grub_err_t
+build_static_trusted_list (const struct grub_module_header *header)
+{
+  grub_err_t err = GRUB_ERR_NONE;
+  struct grub_file pseudo_file;
+  grub_uint8_t *cert_data = NULL;
+  grub_ssize_t cert_data_size = 0;
+
+  grub_memset (&pseudo_file, 0, sizeof (pseudo_file));
+  pseudo_file.fs = &pseudo_fs;
+  pseudo_file.size = header->size - sizeof (struct grub_module_header);
+  pseudo_file.data = (char *) header + sizeof (struct grub_module_header);
+
+  grub_dprintf ("appendedsig", "found an x509 key, size=%" PRIuGRUB_UINT64_T "\n",
+                pseudo_file.size);
+
+  err = grub_read_file (&pseudo_file, &cert_data, &cert_data_size);
+  if (err != GRUB_ERR_NONE)
+    return err;
+
+  err = add_certificate (cert_data, cert_data_size, &db, 1);
+  grub_free (cert_data);
+
+  return err;
+}
+
+/* releasing memory */
+static void
+free_trusted_list (void)
+{
+  struct x509_certificate *cert;
+  grub_size_t i = 0;
+
+  while (db.keys != NULL)
+    {
+      cert = db.keys;
+      db.keys = db.keys->next;
+      certificate_release (cert);
+      grub_free (cert);
+    }
+
+  for (i = 0; i < db.signature_entries; i++)
+    grub_free (db.signatures[i]);
+
+  grub_free (db.signatures);
+  grub_free (db.signature_size);
+  grub_memset (&db, 0, sizeof (db));
+}
+
+/* releasing memory */
+static void
+free_distrusted_list (void)
+{
+  struct x509_certificate *cert;
+  grub_size_t i = 0;
+
+  while (dbx.keys != NULL)
+    {
+      cert = dbx.keys;
+      dbx.keys = dbx.keys->next;
+      certificate_release (cert);
+      grub_free (cert);
+    }
+
+  for (i = 0; i < dbx.signature_entries; i++)
+    grub_free (dbx.signatures[i]);
+
+  grub_free (dbx.signatures);
+  grub_free (dbx.signature_size);
+  grub_memset (&dbx, 0, sizeof (dbx));
+}
+
 GRUB_MOD_INIT (appendedsig)
 {
   int rc;
@@ -548,7 +1036,6 @@ GRUB_MOD_INIT (appendedsig)
   if (grub_is_lockdown () == GRUB_LOCKDOWN_ENABLED)
     check_sigs = check_sigs_forced;
 
-  grub_trusted_key = NULL;
   grub_register_variable_hook ("check_appended_signatures", grub_env_read_sec, grub_env_write_sec);
   grub_env_export ("check_appended_signatures");
 
@@ -556,37 +1043,50 @@ GRUB_MOD_INIT (appendedsig)
   if (rc)
     grub_fatal ("Error initing ASN.1 data structures: %d: %s\n", rc, asn1_strerror (rc));
 
-  FOR_MODULES (header)
-  {
-    struct grub_file pseudo_file;
-    struct x509_certificate *pk = NULL;
-    grub_err_t err;
-
-    /* Not an X.509 certificate, skip. */
-    if (header->type != OBJ_TYPE_X509_PUBKEY)
-      continue;
-
-    grub_memset (&pseudo_file, 0, sizeof (pseudo_file));
-    pseudo_file.fs = &pseudo_fs;
-    pseudo_file.size = header->size - sizeof (struct grub_module_header);
-    pseudo_file.data = (char *) header + sizeof (struct grub_module_header);
-
-    grub_dprintf ("appendedsig", "Found an x509 key, size=%" PRIuGRUB_UINT64_T "\n",
-                  pseudo_file.size);
-
-    pk = grub_zalloc (sizeof (struct x509_certificate));
-    if (!pk)
-      grub_fatal ("Out of memory loading initial certificates");
-
-    err = read_cert_from_file (&pseudo_file, pk);
-    if (err != GRUB_ERR_NONE)
-      grub_fatal ("Error loading initial key: %s", grub_errmsg);
+  if (!grub_pks_use_keystore && check_sigs == check_sigs_forced)
+    {
+      FOR_MODULES (header)
+        {
+          /* Not an ELF module, skip.  */
+          if (header->type != OBJ_TYPE_X509_PUBKEY)
+            continue;
 
-    grub_dprintf ("appendedsig", "loaded certificate CN='%s'\n", pk->subject);
+          rc = build_static_trusted_list (header);
+          if (rc != GRUB_ERR_NONE)
+            {
+              free_trusted_list ();
+              grub_error (rc, "static trusted list creation failed");
+            }
+          else
+            grub_dprintf ("appendedsig", "the trusted list now has %" PRIuGRUB_SIZE " static keys\n",
+                          db.key_entries);
+        }
+    }
+  else if (grub_pks_use_keystore && check_sigs == check_sigs_forced)
+    {
+      rc = create_trusted_list ();
+      if (rc != GRUB_ERR_NONE)
+        {
+          free_trusted_list ();
+          grub_error (rc, "trusted list creation failed");
+        }
+      else
+        {
+          rc = create_distrusted_list ();
+          if (rc != GRUB_ERR_NONE)
+            {
+              free_trusted_list ();
+              free_distrusted_list ();
+              grub_error (rc, "distrusted list creation failed");
+            }
+          else
+            grub_dprintf ("appendedsig", "the trusted list now has %" PRIuGRUB_SIZE " keys.\n"
+                          "the distrusted list now has %" PRIuGRUB_SIZE " keys.\n",
+                          db.signature_entries + db.key_entries, dbx.signature_entries);
+        }
 
-    pk->next = grub_trusted_key;
-    grub_trusted_key = pk;
-  }
+      grub_pks_free_keystore ();
+    }
 
   cmd_trust = grub_register_command ("trust_certificate", grub_cmd_trust, N_("X509_CERTIFICATE"),
                                      N_("Add X509_CERTIFICATE to trusted certificates."));
grub-core/kern/file.c +34 -0
index 6e7efe89a..7217a6ea7 100644
@@ -231,3 +231,37 @@ grub_file_seek (grub_file_t file, grub_off_t offset)
 
   return old;
 }
+
+grub_err_t
+grub_read_file (const grub_file_t file, grub_uint8_t **data, grub_ssize_t *data_size)
+{
+  grub_uint8_t *buffer = NULL;
+  grub_ssize_t read_size = 0;
+  grub_off_t total_read_size = 0;
+  grub_off_t file_size = grub_file_size (file);
+
+  if (file_size == GRUB_FILE_SIZE_UNKNOWN)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("could not determine the size of the file."));
+
+  buffer = grub_zalloc (file_size);
+  if (buffer == NULL)
+    return grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("out of memory"));
+
+  while (total_read_size < file_size)
+    {
+      read_size = grub_file_read (file, &buffer[total_read_size], file_size - total_read_size);
+      if (read_size < 0)
+        {
+          grub_free (buffer);
+          return grub_error (GRUB_ERR_READ_ERROR, N_("unable to read the file"));
+        }
+
+      total_read_size += read_size;
+    }
+
+  *data = buffer;
+  *data_size = total_read_size;
+
+  return GRUB_ERR_NONE;
+}
include/grub/file.h +1 -0
index d678de063..27e1a880e 100644
@@ -217,6 +217,7 @@ grub_ssize_t EXPORT_FUNC(grub_file_read) (grub_file_t file, void *buf,
 					  grub_size_t len);
 grub_off_t EXPORT_FUNC(grub_file_seek) (grub_file_t file, grub_off_t offset);
 grub_err_t EXPORT_FUNC(grub_file_close) (grub_file_t file);
+grub_err_t EXPORT_FUNC(grub_read_file) (const grub_file_t file, grub_uint8_t **data, grub_ssize_t *data_size);
 
 /* Return value of grub_file_size() in case file size is unknown. */
 #define GRUB_FILE_SIZE_UNKNOWN	 0xffffffffffffffffULL
Signature · 7 lines
2.43.5


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

PATCH v2 17/21 appendedsig: While verifying the kernel, use trusted and distrusted lists

In reply to Sudhakar Kuppusamy

To verify the kernel's signature: verify the kernel binary against lists of binary hashes that are either distrusted or trusted. If it is not list in either trusted or distrusted hashes list then the trusted keys from the trusted key list are used to verify the signature.

---
 grub-core/commands/appendedsig/appendedsig.c | 199 +++++++++++++------
 1 file changed, 142 insertions(+), 57 deletions(-)
grub-core/commands/appendedsig/appendedsig.c +142 -57
index b24112050..3abb45ae0 100644
@@ -454,6 +454,83 @@ extract_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize,
   return parse_pkcs7_signedData (appsigdata, pkcs7_size, &sig->pkcs7);
 }
 
+static grub_err_t
+get_binary_hash (const grub_size_t binary_hash_size, const grub_uint8_t *data,
+                 const grub_size_t data_size, grub_uint8_t *hash, grub_size_t *hash_size)
+{
+  grub_uuid_t guid = { 0 };
+
+  /* support SHA256, SHA384 and SHA512 for binary hash */
+  if (binary_hash_size == 32)
+    grub_memcpy (&guid, &GRUB_PKS_CERT_SHA256_GUID, GRUB_UUID_SIZE);
+  else if (binary_hash_size == 48)
+    grub_memcpy (&guid, &GRUB_PKS_CERT_SHA384_GUID, GRUB_UUID_SIZE);
+  else if (binary_hash_size == 64)
+    grub_memcpy (&guid, &GRUB_PKS_CERT_SHA512_GUID, GRUB_UUID_SIZE);
+  else
+    {
+      grub_dprintf ("appendedsig", "unsupported hash type (%" PRIuGRUB_SIZE ") and skipping binary hash\n",
+                    binary_hash_size);
+      return GRUB_ERR_UNKNOWN_COMMAND;
+    }
+
+  return get_hash (&guid, data, data_size, hash, hash_size);
+}
+
+/*
+ * Verify binary hash against the list of binary hashes that are distrusted
+ * and trusted.
+ * The following errors can occur:
+ *  - GRUB_ERR_BAD_SIGNATURE: indicates that the hash is distrusted.
+ *  - GRUB_ERR_NONE: the hash is trusted, since it was found in the trusted hashes list
+ *  - GRUB_ERR_EOF: the hash could not be found in the hashes list
+ */
+static grub_err_t
+verify_binary_hash (const grub_uint8_t *data, const grub_size_t data_size)
+{
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_size_t i = 0, hash_size = 0;
+  grub_uint8_t hash[GRUB_MAX_HASH_SIZE] = { 0 };
+
+  for (i = 0; i < dbx.signature_entries; i++)
+    {
+      rc = get_binary_hash (dbx.signature_size[i], data, data_size, hash, &hash_size);
+      if (rc != GRUB_ERR_NONE)
+        continue;
+
+      if (hash_size == dbx.signature_size[i] &&
+          grub_memcmp (dbx.signatures[i], hash, hash_size) == 0)
+        {
+          grub_dprintf ("appendedsig", "the binary hash (%02x%02x%02x%02x) was listed as distrusted\n",
+                        hash[0], hash[1], hash[2], hash[3]);
+          return GRUB_ERR_BAD_SIGNATURE;
+        }
+    }
+
+  for (i = 0; i < db.signature_entries; i++)
+    {
+      rc = get_binary_hash (db.signature_size[i], data, data_size, hash, &hash_size);
+      if (rc != GRUB_ERR_NONE)
+        continue;
+
+      if (hash_size == db.signature_size[i] &&
+          grub_memcmp (db.signatures[i], hash, hash_size) == 0)
+        {
+          grub_dprintf ("appendedsig", "verified with a trusted binary hash (%02x%02x%02x%02x)\n",
+                        hash[0], hash[1], hash[2], hash[3]);
+          return GRUB_ERR_NONE;
+        }
+    }
+
+  return GRUB_ERR_EOF;
+}
+
+
+/*
+ * Verify the kernel's integrity, the trusted key will be used from
+ * the trusted key list. If it fails, verify it against the list of binary hashes
+ * that are distrusted and trusted.
+ */
 static grub_err_t
 grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize)
 {
@@ -463,12 +540,12 @@ grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize)
   unsigned char *hash;
   gcry_mpi_t hashmpi;
   gcry_err_code_t rc;
-  struct x509_certificate *pk;
+  struct x509_certificate *cert;
   struct grub_appended_signature sig;
   struct pkcs7_signerInfo *si;
   int i;
 
-  if (!db.key_entries)
+  if (!db.key_entries && !db.signature_entries)
     return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("No trusted keys to verify against"));
 
   err = extract_appended_signature (buf, bufsize, &sig);
@@ -476,69 +553,77 @@ grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize)
     return err;
 
   datasize = bufsize - sig.signature_len;
-
-  for (i = 0; i < sig.pkcs7.signerInfo_count; i++)
+  err = verify_binary_hash (buf, datasize);
+  if (err != GRUB_ERR_EOF && err != GRUB_ERR_NONE)
     {
-      /*
-       * This could be optimised in a couple of ways:
-       * - we could only compute hashes once per hash type
-       * - we could track signer information and only verify where IDs match
-       * For now we do the naive O(trusted keys * pkcs7 signers) approach.
-       */
-      si = &sig.pkcs7.signerInfos[i];
-      context = grub_zalloc (si->hash->contextsize);
-      if (!context)
-        return grub_errno;
-
-      si->hash->init (context);
-      si->hash->write (context, buf, datasize);
-      si->hash->final (context);
-      hash = si->hash->read (context);
-
-      grub_dprintf ("appendedsig", "data size %" PRIxGRUB_SIZE ", signer %d hash %02x%02x%02x%02x...\n",
-                    datasize, i, hash[0], hash[1], hash[2], hash[3]);
-
-      err = GRUB_ERR_BAD_SIGNATURE;
-      for (pk = db.keys; pk; pk = pk->next)
+      err = grub_error (err, N_("failed to verify binary-hash/signature with any trusted binary-hash/key\n"));
+      pkcs7_signedData_release (&sig.pkcs7);
+      return err;
+    }
+  else if (err == GRUB_ERR_EOF)
+    {
+      /* Binary hash was not found in trusted and distrusted list: check signature now */
+      for (i = 0; i < sig.pkcs7.signerInfo_count; i++)
         {
-          rc = grub_crypto_rsa_pad (&hashmpi, hash, si->hash, pk->mpis[0]);
-          if (rc)
-            {
-              err = grub_error (GRUB_ERR_BAD_SIGNATURE,
-                                N_("Error padding hash for RSA verification: %d"), rc);
-              grub_free (context);
-              goto cleanup;
-            }
-
-          rc = _gcry_pubkey_spec_rsa.verify (0, hashmpi, &si->sig_mpi, pk->mpis, NULL, NULL);
-          gcry_mpi_release (hashmpi);
-
-          if (rc == 0)
+          /*
+           * This could be optimised in a couple of ways:
+           * - we could only compute hashes once per hash type
+           * - we could track signer information and only verify where IDs match
+           * For now we do the naive O(db.keys * pkcs7 signers) approach.
+           */
+          si = &sig.pkcs7.signerInfos[i];
+          context = grub_zalloc (si->hash->contextsize);
+          if (context == NULL)
+            return grub_errno;
+
+          si->hash->init (context);
+          si->hash->write (context, buf, datasize);
+          si->hash->final (context);
+          hash = si->hash->read (context);
+
+          grub_dprintf ("appendedsig",
+                        "data size %" PRIxGRUB_SIZE ", signer %d hash %02x%02x%02x%02x...\n",
+                        datasize, i, hash[0], hash[1], hash[2], hash[3]);
+
+          err = GRUB_ERR_BAD_SIGNATURE;
+          for (cert = db.keys; cert; cert = cert->next)
             {
-              grub_dprintf ("appendedsig", "verify signer %d with key '%s' succeeded\n",
-                            i, pk->subject);
-              err = GRUB_ERR_NONE;
-              break;
+              rc = grub_crypto_rsa_pad (&hashmpi, hash, si->hash, cert->mpis[0]);
+              if (rc != 0)
+                {
+                  err = grub_error (GRUB_ERR_BAD_SIGNATURE,
+                                    N_("Error padding hash for RSA verification: %d"), rc);
+                  grub_free (context);
+                  pkcs7_signedData_release (&sig.pkcs7);
+                  return err;
+                }
+
+              rc = _gcry_pubkey_spec_rsa.verify (0, hashmpi, &si->sig_mpi, cert->mpis, NULL, NULL);
+              gcry_mpi_release (hashmpi);
+              if (rc == 0)
+                {
+                  grub_dprintf ("appendedsig", "verify signer %d with key '%s' succeeded\n",
+                                i, cert->subject);
+                  err = GRUB_ERR_NONE;
+                  break;
+                }
+
+              grub_dprintf ("appendedsig", "verify signer %d with key '%s' failed with %d\n",
+                            i, cert->subject, rc);
             }
-
-          grub_dprintf ("appendedsig", "verify signer %d with key '%s' failed with %d\n",
-                        i, pk->subject, rc);
-        }
-
-      grub_free (context);
-
-      if (err == GRUB_ERR_NONE)
-        break;
+          grub_free (context);
+          if (err == GRUB_ERR_NONE)
+            break;
+      }
     }
 
-  /* If we didn't verify, provide a neat message */
-  if (err != GRUB_ERR_NONE)
-    err = grub_error (GRUB_ERR_BAD_SIGNATURE,
-                      N_("Failed to verify signature against a trusted key"));
-
-cleanup:
   pkcs7_signedData_release (&sig.pkcs7);
 
+  if (err != GRUB_ERR_NONE)
+    err = grub_error (err, N_("failed to verify signature with any trusted key\n"));
+  else
+    grub_dprintf ("appendedsig", "successfully verified the signature with a trusted key\n");
+
   return err;
 }
 
Signature · 7 lines
2.43.5


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

PATCH v2 18/21 powerpc_ieee1275: set use_static_keys flag

In reply to Sudhakar Kuppusamy

Introduce the use_static_keys flag to indicate that static keys are to be used rather than keys from the PKS storage's DB variable. This variable is set when Secure Boot is enabled with PKS but the DB variable is not present in the PKS storage. The appendedsig module would use this variable to extract the default DB keys from the ELF note and store the keys found there in the trustedlist.

---
 .../kern/powerpc/ieee1275/platform_keystore.c    | 16 +++++++++++++++-
 grub-core/term/tparm.c                           |  1 -
 .../grub/powerpc/ieee1275/platform_keystore.h    | 11 ++++++-----
 include/grub/types.h                             |  2 ++
 4 files changed, 23 insertions(+), 7 deletions(-)
grub-core/kern/powerpc/ieee1275/platform_keystore.c +15 -1
index cf1d0555e..a83fcf7cd 100644
@@ -34,7 +34,11 @@
 /* Platform Keystore */
 static grub_size_t pks_max_object_size;
 grub_uint8_t grub_pks_use_keystore = 0;
-grub_pks_t grub_pks_keystore = { .db = NULL, .dbx = NULL, .db_entries = 0, .dbx_entries = 0 };
+grub_pks_t grub_pks_keystore = { .db = NULL,
+                                 .dbx = NULL,
+                                 .db_entries = 0,
+                                 .dbx_entries = 0,
+                                 .use_static_keys = false };
 
 /* Convert the esl data into the ESL */
 static grub_esl_t *
@@ -312,6 +316,16 @@ grub_pks_keystore_init (void)
       grub_memset (&grub_pks_keystore, 0, sizeof (grub_pks_t));
       /* DB */
       rc = read_secure_boot_variables (0, DB, &grub_pks_keystore.db, &grub_pks_keystore.db_entries);
+      if (rc == PKS_OBJECT_NOT_FOUND)
+        {
+          rc = GRUB_ERR_NONE;
+          /*
+           * DB variable won't be available by default in PKS.
+           * So, it will load the Default Keys from ELF Note
+           */
+          grub_pks_keystore.use_static_keys = true;
+        }
+
       if (rc == GRUB_ERR_NONE)
         {
           /* DBX */
grub-core/term/tparm.c +0 -1
index fb5b15a88..f2db325f6 100644
@@ -46,7 +46,6 @@
 /*
  * Common/troublesome character definitions
  */
-typedef char grub_bool_t;
 #ifndef FALSE
 # define FALSE (0)
 #endif
include/grub/powerpc/ieee1275/platform_keystore.h +6 -5
index 0641adb0f..870fb8cc5 100644
@@ -199,10 +199,11 @@ struct grub_pks_sd
 /* The structure of a PKS.*/
 struct grub_pks
 {
-  grub_pks_sd_t *db;        /* signature database */
-  grub_pks_sd_t *dbx;       /* forbidden signature database */
-  grub_size_t db_entries;   /* size of signature database */
-  grub_size_t dbx_entries;  /* size of forbidden signature database */
+  grub_pks_sd_t *db;          /* signature database */
+  grub_pks_sd_t *dbx;         /* forbidden signature database */
+  grub_size_t db_entries;     /* size of signature database */
+  grub_size_t dbx_entries;    /* size of forbidden signature database */
+  grub_bool_t use_static_keys;/* flag to indicate use of static keys */
 } GRUB_PACKED;
 
 #ifdef __powerpc__
@@ -217,7 +218,7 @@ extern grub_pks_t EXPORT_VAR(grub_pks_keystore);
 #else
 
 #define grub_pks_use_keystore	0
-grub_pks_t grub_pks_keystore = {NULL, NULL, 0, 0};
+grub_pks_t grub_pks_keystore = {NULL, NULL, 0, 0, false};
 void grub_pks_free_keystore (void);
 
 #endif
include/grub/types.h +2 -0
index ce914decb..865d56a7e 100644
@@ -397,4 +397,6 @@ struct grub_uuid
   grub_uint8_t b[GRUB_UUID_SIZE];
 };
 
+typedef char grub_bool_t;
+
 #endif /* ! GRUB_TYPES_HEADER */
Signature · 7 lines
2.43.5


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

PATCH v2 19/21 appendedsig: Reads the default DB keys from ELF Note

In reply to Sudhakar Kuppusamy

If Secure Boot is enabled with PKS and the use_static_keys flag is set, then read the DB default keys from the ELF note and store them in the trusted list buffer.

---
 grub-core/commands/appendedsig/appendedsig.c | 56 ++++++++++++++------
 1 file changed, 40 insertions(+), 16 deletions(-)
grub-core/commands/appendedsig/appendedsig.c +40 -16
index 3abb45ae0..5631f0ab4 100644
@@ -1041,7 +1041,7 @@ create_distrusted_list (void)
  * parse it, and add it to the trusted list.
  */
 static grub_err_t
-build_static_trusted_list (const struct grub_module_header *header)
+build_static_trusted_list (const struct grub_module_header *header, const grub_bool_t is_pks)
 {
   grub_err_t err = GRUB_ERR_NONE;
   struct grub_file pseudo_file;
@@ -1060,6 +1060,13 @@ build_static_trusted_list (const struct grub_module_header *header)
   if (err != GRUB_ERR_NONE)
     return err;
 
+  if (is_pks)
+    {
+      err = is_distrusted_cert_hash (cert_data, cert_data_size);
+      if (err != GRUB_ERR_NONE)
+        return err;
+    }
+
   err = add_certificate (cert_data, cert_data_size, &db, 1);
   grub_free (cert_data);
 
@@ -1112,6 +1119,22 @@ free_distrusted_list (void)
   grub_memset (&dbx, 0, sizeof (dbx));
 }
 
+static grub_err_t
+load_static_keys (const struct grub_module_header *header, const grub_bool_t is_pks)
+{
+  int rc = GRUB_ERR_NONE;
+  FOR_MODULES (header)
+    {
+      /* Not an ELF module, skip.  */
+      if (header->type != OBJ_TYPE_X509_PUBKEY)
+        continue;
+      rc = build_static_trusted_list (header, is_pks);
+      if (rc != GRUB_ERR_NONE)
+        return rc;
+    }
+  return rc;
+}
+
 GRUB_MOD_INIT (appendedsig)
 {
   int rc;
@@ -1130,26 +1153,27 @@ GRUB_MOD_INIT (appendedsig)
 
   if (!grub_pks_use_keystore && check_sigs == check_sigs_forced)
     {
-      FOR_MODULES (header)
+      rc = load_static_keys (header, false);
+      if (rc != GRUB_ERR_NONE)
         {
-          /* Not an ELF module, skip.  */
-          if (header->type != OBJ_TYPE_X509_PUBKEY)
-            continue;
-
-          rc = build_static_trusted_list (header);
-          if (rc != GRUB_ERR_NONE)
-            {
-              free_trusted_list ();
-              grub_error (rc, "static trusted list creation failed");
-            }
-          else
-            grub_dprintf ("appendedsig", "the trusted list now has %" PRIuGRUB_SIZE " static keys\n",
-                          db.key_entries);
+          free_trusted_list ();
+          grub_error (rc, "static trusted list creation failed");
         }
+      else
+        grub_dprintf ("appendedsig", "the trusted list now has %" PRIuGRUB_SIZE " static keys\n",
+                      db.key_entries);
     }
   else if (grub_pks_use_keystore && check_sigs == check_sigs_forced)
     {
-      rc = create_trusted_list ();
+      if (grub_pks_keystore.use_static_keys)
+        {
+          grub_printf ("Warning: db variable is not available at PKS and using a static keys "
+                       "as a default key in trusted list\n");
+          rc = load_static_keys (header, grub_pks_keystore.use_static_keys);
+        }
+      else
+        rc = create_trusted_list ();
+
       if (rc != GRUB_ERR_NONE)
         {
           free_trusted_list ();
Signature · 7 lines
2.43.5


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

PATCH v2 20/21 appendedsig: The grub command's trusted and distrusted support

In reply to Sudhakar Kuppusamy

To support the following trusted and distrusted commands

1. trusted_list:
It will show the list of trusted certificates and binary hashes
2. distrusted_list:
It will show the list of distrusted certificates and binary/certificate hashes
3. trusted_certificate:
It will add the trusted certificate to the trusted list
4. trusted_signature:
It will add the certificate/binary hash to the trusted list
5. distrusted_certificate:
It will remove the trusted certificate from trsuted list
6. distrusted_signature:
It will add the certificate/binary hash to the distrsuted list

Note:-
The addition/deletion of trusted certificates and binary hashes
are not allowed in grub command prompt while secure boot is enabled.

---
 grub-core/commands/appendedsig/appendedsig.c | 518 +++++++++++++------
 1 file changed, 351 insertions(+), 167 deletions(-)
grub-core/commands/appendedsig/appendedsig.c +351 -167
index 5631f0ab4..6f665aab2 100644
@@ -117,6 +117,36 @@ static enum
   check_sigs_forced = 2
 } check_sigs = check_sigs_no;
 
+enum
+{
+  OPTION_BINARY_HASH = 0,
+  OPTION_CERT_HASH = 1
+};
+
+static const struct grub_arg_option options[] =
+{
+  {"binary-hash", 'b', 0, N_("hash file of the binary."), 0, ARG_TYPE_NONE},
+  {"cert-hash", 'c', 1, N_("hash file of the certificate."), 0, ARG_TYPE_NONE},
+  {0, 0, 0, 0, 0, 0}
+};
+
+static void
+print_hex (const grub_uint8_t *data, const grub_size_t length)
+{
+  grub_size_t i, count = 0;
+  for (i = 0; i < length-1; i++)
+    {
+      grub_printf ("%02x:", data[i]);
+      count++;
+      if (count == 16)
+        {
+          grub_printf ("\n\t      ");
+          count = 0;
+        }
+    }
+  grub_printf ("%02x\n", data[i]);
+}
+
 /*
  * GUID can be used to determine the hashing function and
  * generate the hash using determined hashing function.
@@ -344,72 +374,6 @@ grub_env_write_sec (struct grub_env_var *var __attribute__ ((unused)), const cha
   return grub_strdup (grub_env_read_sec (NULL, NULL));
 }
 
-static grub_err_t
-file_read_all (grub_file_t file, grub_uint8_t **buf, grub_size_t *len)
-{
-  grub_off_t full_file_size;
-  grub_size_t file_size, total_read_size = 0;
-  grub_ssize_t read_size;
-
-  full_file_size = grub_file_size (file);
-  if (full_file_size == GRUB_FILE_SIZE_UNKNOWN)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT,
-                       N_("Cannot read a file of unknown size into a buffer"));
-
-  if (full_file_size > GRUB_SIZE_MAX)
-    return grub_error (GRUB_ERR_OUT_OF_RANGE,
-                       N_("File is too large to read: %" PRIuGRUB_UINT64_T " bytes"),
-                       full_file_size);
-
-  file_size = (grub_size_t) full_file_size;
-
-  *buf = grub_malloc (file_size);
-  if (!*buf)
-    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
-                       N_("Could not allocate file data buffer size %" PRIuGRUB_SIZE),
-                       file_size);
-
-  while (total_read_size < file_size)
-    {
-      read_size = grub_file_read (file, *buf + total_read_size, file_size - total_read_size);
-
-      if (read_size < 0)
-        {
-          grub_free (*buf);
-          return grub_errno;
-        }
-      else if (read_size == 0)
-        {
-          grub_free (*buf);
-          return grub_error (GRUB_ERR_IO,
-                             N_("Could not read full file size "
-                                "(%" PRIuGRUB_SIZE "), only %" PRIuGRUB_SIZE " bytes read"),
-                             file_size, total_read_size);
-        }
-
-      total_read_size += read_size;
-    }
-  *len = file_size;
-  return GRUB_ERR_NONE;
-}
-
-static grub_err_t
-read_cert_from_file (grub_file_t f, struct x509_certificate *certificate)
-{
-  grub_err_t err;
-  grub_uint8_t *buf;
-  grub_size_t file_size;
-
-  err = file_read_all (f, &buf, &file_size);
-  if (err != GRUB_ERR_NONE)
-    return err;
-
-  err = parse_x509_certificate (buf, file_size, certificate);
-  grub_free (buf);
-
-  return err;
-}
-
 static grub_err_t
 extract_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize,
                             struct grub_appended_signature *sig)
@@ -630,145 +594,347 @@ grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize)
 static grub_err_t
 grub_cmd_verify_signature (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
 {
-  grub_file_t f;
   grub_err_t err = GRUB_ERR_NONE;
-  grub_uint8_t *data;
-  grub_size_t file_size;
+  grub_file_t signed_file = NULL;
+  grub_uint8_t *signed_data = NULL;
+  grub_ssize_t signed_data_size = 0;
 
-  if (argc < 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument expected"));
+  if (argc != 1)
+    {
+      grub_printf (N_("a signed file is expected\n"
+                      "Example:\n\tverify_appended <SIGNED FILE>\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
 
   grub_dprintf ("appendedsig", "verifying %s\n", args[0]);
 
-  f = grub_file_open (args[0], GRUB_FILE_TYPE_VERIFY_SIGNATURE);
-  if (!f)
-    {
-      err = grub_errno;
-      goto cleanup;
-    }
+  signed_file = grub_file_open (args[0], GRUB_FILE_TYPE_VERIFY_SIGNATURE);
+  if (signed_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND, N_("unable to open a signed file"));
 
-  err = file_read_all (f, &data, &file_size);
+  err = grub_read_file (signed_file, &signed_data, &signed_data_size);
   if (err != GRUB_ERR_NONE)
-    goto cleanup;
-
-  err = grub_verify_appended_signature (data, file_size);
+    {
+      grub_file_close (signed_file);
+      return err;
+    }
 
-  grub_free (data);
+  grub_file_close (signed_file);
+  err = grub_verify_appended_signature (signed_data, signed_data_size);
+  grub_free (signed_data);
 
-cleanup:
-  if (f)
-    grub_file_close (f);
   return err;
 }
 
 static grub_err_t
-grub_cmd_distrust (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
+grub_cmd_trusted_list (grub_command_t cmd __attribute__((unused)),
+                       int argc __attribute__((unused)), char **args __attribute__((unused)))
 {
-  unsigned long cert_num, i;
-  struct x509_certificate *cert, *prev;
+  struct x509_certificate *cert = NULL;
+  grub_size_t i = 0, cert_num = 1;
 
-  if (argc != 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("One argument expected"));
+  for (cert = db.keys; cert; cert = cert->next)
+    {
+      grub_printf (N_("trusted certificate %" PRIuGRUB_SIZE ":\n"), cert_num);
+      grub_printf (N_("\tserial: "));
 
-  grub_errno = GRUB_ERR_NONE;
-  cert_num = grub_strtoul (args[0], NULL, 10);
-  if (grub_errno != GRUB_ERR_NONE)
-    return grub_errno;
+      for (i = 0; i < cert->serial_len - 1; i++)
+        grub_printf ("%02x:", cert->serial[i]);
 
-  if (cert_num < 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT,
-                       N_("Certificate number too small - numbers start at 1"));
+      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);
+      grub_printf ("\tCN: %s\n\n", cert->subject);
+      cert_num++;
+    }
 
-  if (cert_num == 1)
+  for (i = 0; i < db.signature_entries; i++)
     {
-      cert = db.keys;
-      db.keys = cert->next;
+      grub_printf (N_("trusted binary hash %" PRIuGRUB_SIZE ":\n"), i+1);
+      grub_printf (N_("\thash: "));
+      print_hex (db.signatures[i], db.signature_size[i]);
+    }
 
-      certificate_release (cert);
-      grub_free (cert);
-      return GRUB_ERR_NONE;
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_cmd_distrusted_list (grub_command_t cmd __attribute__((unused)),
+                          int argc __attribute__((unused)),
+                          char **args __attribute__((unused)))
+{
+  struct x509_certificate *cert = NULL;
+  grub_size_t i = 0, cert_num = 1;
+
+  for (cert = dbx.keys; cert; cert = cert->next)
+    {
+      grub_printf (N_("distrusted certificate %" PRIuGRUB_SIZE ":\n"), cert_num);
+      grub_printf (N_("\tserial: "));
+
+      for (i = 0; i < cert->serial_len - 1; i++)
+        grub_printf ("%02x:", cert->serial[i]);
+
+      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);
+      grub_printf ("\tCN: %s\n\n", cert->subject);
+      cert_num++;
     }
-  i = 2;
-  prev = db.keys;
-  cert = db.keys->next;
-  while (cert)
+
+  for (i = 0; i < dbx.signature_entries; i++)
     {
-      if (i == cert_num)
-        {
-          prev->next = cert->next;
-          certificate_release (cert);
-          grub_free (cert);
-          return GRUB_ERR_NONE;
-        }
-      i++;
-      prev = cert;
-      cert = cert->next;
+      grub_printf (N_("distrusted certificate/binary hash %" PRIuGRUB_SIZE ":\n"), i+1);
+      grub_printf (N_("\thash: "));
+      print_hex (dbx.signatures[i], dbx.signature_size[i]);
     }
 
-  return grub_error (GRUB_ERR_BAD_ARGUMENT,
-                     N_("No certificate number %lu found - only %lu certificates in the store"),
-                     cert_num, i - 1);
+  return GRUB_ERR_NONE;
 }
 
 static grub_err_t
-grub_cmd_trust (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
+grub_cmd_trusted_cert (grub_command_t cmd __attribute__((unused)),
+                       int argc, char **args)
 {
-  grub_file_t certf;
-  struct x509_certificate *cert = NULL;
-  grub_err_t err;
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_file_t cert_file = NULL;
+  grub_uint8_t *cert_data = NULL;
+  grub_ssize_t cert_data_size = 0;
 
   if (argc != 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument expected"));
+    {
+      grub_printf (N_("a trusted X.509 certificate file is expected\n"
+                      "Example:\n\ttrusted_certificate <CERT FILE>\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
 
-  certf = grub_file_open (args[0], GRUB_FILE_TYPE_CERTIFICATE_TRUST | GRUB_FILE_TYPE_NO_DECOMPRESS);
-  if (!certf)
-    return grub_errno;
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "adding of trusted X.509 certificate is not permitted!\n");
+      return grub_errno;
+    }
 
-  cert = grub_zalloc (sizeof (struct x509_certificate));
-  if (!cert)
-    return grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("Could not allocate memory for certificate"));
+  if (grub_strlen (args[0]) == 0)
+    return grub_error (GRUB_ERR_BAD_FILENAME,
+                       N_("missing trusted X.509 certificate file"));
 
-  err = read_cert_from_file (certf, cert);
-  grub_file_close (certf);
+  cert_file = grub_file_open (args[0], GRUB_FILE_TYPE_CERTIFICATE_TRUST |
+                              GRUB_FILE_TYPE_NO_DECOMPRESS);
+  if (cert_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND,
+                       N_("unable to open the trusted X.509 certificate file"));
+
+  err = grub_read_file (cert_file, &cert_data, &cert_data_size);
   if (err != GRUB_ERR_NONE)
     {
-      grub_free (cert);
+      grub_file_close (cert_file);
       return err;
     }
-  grub_dprintf ("appendedsig", "Loaded certificate with CN: %s\n", cert->subject);
 
-  cert->next = db.keys;
-  db.keys = cert;
+  grub_file_close (cert_file);
+  err = add_certificate (cert_data, cert_data_size, &db, 1);
+  if (err != GRUB_ERR_NONE)
+    {
+      free_trusted_list ();
+      free_distrusted_list ();
+      grub_error (err, "adding of trusted certificate failed");
+    }
 
-  return GRUB_ERR_NONE;
+  grub_free (cert_data);
+
+  return err;
 }
 
 static grub_err_t
-grub_cmd_list (grub_command_t cmd __attribute__ ((unused)), int argc __attribute__ ((unused)),
-               char **args __attribute__ ((unused)))
+grub_cmd_trusted_hash (grub_command_t cmd __attribute__((unused)), int argc, char**args)
 {
-  struct x509_certificate *cert;
-  int cert_num = 1;
-  grub_size_t i;
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_file_t hash_file = NULL;
+  grub_uint8_t *hash_data = NULL;
+  grub_ssize_t hash_data_size = 0;
 
-  for (cert = db.keys; cert; cert = cert->next)
+  if (argc != 1)
     {
-      grub_printf (N_("Certificate %d:\n"), cert_num);
+      grub_printf (N_("a trusted binary hash file is expected\n"
+                      "Example:\n\ttrusted_signature <BINARY HASH FILE>\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
 
-      grub_printf (N_("\tSerial: "));
-      for (i = 0; i < cert->serial_len - 1; i++)
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "adding of trusted binary hash is not permitted!\n");
+      return grub_errno;
+    }
+
+  if (grub_strlen (args[0]) == 0)
+    return grub_error (GRUB_ERR_BAD_FILENAME, N_("missing trusted binary hash file"));
+
+  hash_file = grub_file_open (args[0], GRUB_FILE_TYPE_TO_HASH | GRUB_FILE_TYPE_NO_DECOMPRESS);
+  if (hash_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND,
+                       N_("unable to open the trusted binary hash file"));
+
+  rc = grub_read_file (hash_file, &hash_data, &hash_data_size);
+  if (rc != GRUB_ERR_NONE)
+    {
+      grub_file_close (hash_file);
+      return rc;
+    }
+
+  grub_file_close (hash_file);
+
+  grub_dprintf ("appendedsig", "adding a trusted binary hash %s\n with size of %" PRIuGRUB_SIZE "\n",
+                hash_data, hash_data_size);
+
+  /* only accept SHA256, SHA384 and SHA512 binary hash */
+  if (hash_data_size != 32 && hash_data_size != 48 && hash_data_size != 64)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("unacceptable trusted binary hash type"));
+
+  rc = add_hash ((const grub_uint8_t **) &hash_data, hash_data_size, &db.signatures,
+                 &db.signature_size, &db.signature_entries);
+  if (rc != GRUB_ERR_NONE)
+    {
+      free_trusted_list ();
+      free_distrusted_list ();
+      grub_error (rc, "adding of trusted binary hash failed");
+    }
+
+  grub_free (hash_data);
+
+  return rc;
+}
+
+static grub_err_t
+grub_cmd_distrusted_cert (grub_command_t cmd __attribute__((unused)), int argc, char **args)
+{
+  grub_size_t cert_num = 0, i = 1;
+  struct x509_certificate *current_cert = db.keys;
+  struct x509_certificate *previous_cert = db.keys;
+
+  if (argc != 1)
+    {
+      grub_printf (N_("trusted certificate number is expected\n"
+                      "Example:\n\tdistrusted_certificate <CERT_NUMER>\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "removing of trusted certificate is not permitted!\n");
+      return grub_errno;
+    }
+
+  cert_num = grub_strtoul (args[0], NULL, 10);
+  if (cert_num < 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("trusted certificate number should to begin with 1"));
+
+  if (cert_num > db.key_entries)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("trusted certificate number should not exceed %" PRIuGRUB_SIZE ""),
+                       db.key_entries);
+  else if (cert_num < db.key_entries)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("there is no certificate on the trusted list. so, not permitted"));
+
+  for (i = 1; i < db.key_entries; i++)
+    {
+      if (cert_num == 1)
         {
-          grub_printf ("%02x:", cert->serial[i]);
+          previous_cert = current_cert->next;
+          break;
+        }
+      else if (cert_num == i)
+        {
+          previous_cert->next = current_cert->next;
+          break;
         }
-      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);
 
-      grub_printf ("\tCN: %s\n\n", cert->subject);
-      cert_num++;
+      previous_cert = current_cert;
+      current_cert = current_cert->next;
     }
 
+  certificate_release (current_cert);
+  grub_free (current_cert);
+
   return GRUB_ERR_NONE;
 }
 
+static grub_err_t
+grub_cmd_distrusted_hash (grub_extcmd_context_t ctxt, int argc, char **args)
+{
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_file_t hash_file = NULL;
+  grub_uint8_t *hash_data = NULL;
+  grub_ssize_t hash_data_size = 0;
+
+  if (argc != 2)
+    {
+      grub_printf (N_("a distrusted certificate/binary hash file is expected\n"
+                      "Example:\n\tdistrusted_signature [option] <FILE>\n"
+                      "option:\n[-b|--binary-hash] FILE [BINARY HASH FILE]\n"
+                      "[-c|--cert-hash] FILE [CERTFICATE HASH FILE]\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "adding of distrusted certificate/binary hash is not permitted!\n");
+      return grub_errno;
+    }
+
+  if (!ctxt->state[OPTION_BINARY_HASH].set && !ctxt->state[OPTION_CERT_HASH].set)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("missing options and use --help to konw"));
+
+  if (grub_strlen (args[1]) == 0)
+    return grub_error (GRUB_ERR_BAD_FILENAME,
+                       N_("missing distrusted certificate/binary hash file"));
+
+  hash_file = grub_file_open (args[1], GRUB_FILE_TYPE_TO_HASH | GRUB_FILE_TYPE_NO_DECOMPRESS);
+  if (hash_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND,
+                       N_("unable to open the distrusted certificate/binary hash file"));
+
+  rc = grub_read_file (hash_file, &hash_data, &hash_data_size);
+  if (rc != GRUB_ERR_NONE)
+    {
+      grub_file_close (hash_file);
+      return rc;
+    }
+
+  grub_file_close (hash_file);
+
+  grub_dprintf ("appendedsig", "adding a distrusted certificate/binary hash %s\n"
+                " with size of %" PRIuGRUB_SIZE "\n", hash_data, hash_data_size);
+
+  if (ctxt->state[OPTION_BINARY_HASH].set)
+    {
+      /* only accept SHA256, SHA384 and SHA512 binary hash */
+      if (hash_data_size != 32 && hash_data_size != 48 && hash_data_size != 64)
+        return grub_error (GRUB_ERR_BAD_SIGNATURE,
+                           N_("unacceptable distrusted binary hash type"));
+    }
+  else if (ctxt->state[OPTION_CERT_HASH].set)
+    {
+      /* only accept SHA256, SHA384 and SHA512 certificate hash */
+      if (hash_data_size != 32 && hash_data_size != 48 && hash_data_size != 64)
+        return grub_error (GRUB_ERR_BAD_SIGNATURE,
+                           N_("unacceptable distrusted certificate hash type"));
+    }
+
+  rc = add_hash ((const grub_uint8_t **) &hash_data, hash_data_size, &dbx.signatures,
+                 &dbx.signature_size, &dbx.signature_entries);
+  if (rc != GRUB_ERR_NONE)
+    {
+      free_trusted_list ();
+      free_distrusted_list ();
+      grub_error (rc, "adding of distrusted binary/certificate hash failed");
+    }
+
+  grub_free (hash_data);
+
+  return rc;
+}
+
 static grub_err_t
 appendedsig_init (grub_file_t io __attribute__ ((unused)), enum grub_file_type type,
                   void **context __attribute__ ((unused)), enum grub_verify_flags *flags)
@@ -842,8 +1008,6 @@ pseudo_read (struct grub_file *file, char *buf, grub_size_t len)
 /* Filesystem descriptor.  */
 static struct grub_fs pseudo_fs = { .name = "pseudo", .fs_read = pseudo_read };
 
-static grub_command_t cmd_verify, cmd_list, cmd_distrust, cmd_trust;
-
 /*
  * Verify the trusted certificate against the certificate hashes from platform keystore buffer's
  * distrusted list.
@@ -1135,6 +1299,10 @@ load_static_keys (const struct grub_module_header *header, const grub_bool_t is_
   return rc;
 }
 
+static grub_extcmd_t cmd_distrusted_hash;
+static grub_command_t cmd_verify, cmd_trusted_list, cmd_trusted_cert, cmd_trusted_hash,
+                      cmd_distrusted_list, cmd_distrusted_cert;
+
 GRUB_MOD_INIT (appendedsig)
 {
   int rc;
@@ -1196,17 +1364,31 @@ GRUB_MOD_INIT (appendedsig)
 
       grub_pks_free_keystore ();
     }
-
-  cmd_trust = grub_register_command ("trust_certificate", grub_cmd_trust, N_("X509_CERTIFICATE"),
-                                     N_("Add X509_CERTIFICATE to trusted certificates."));
-  cmd_list = grub_register_command ("list_certificates", grub_cmd_list, 0,
-                                    N_("Show the list of trusted x509 certificates."));
+  cmd_trusted_cert = grub_register_command ("trusted_certificate", grub_cmd_trusted_cert,
+                                            N_("X509_CERTIFICATE"),
+                                            N_("Add X509_CERTIFICATE to trusted list."));
+  cmd_trusted_hash = grub_register_command ("trusted_signature", grub_cmd_trusted_hash,
+                                            N_("BINARY HASH FILE"),
+                                            N_("Add trusted BINARY HASH to trusted list."));
+  cmd_distrusted_cert = grub_register_command ("distrusted_certificate", grub_cmd_distrusted_cert,
+                                               N_("CERT_NUMBER"),
+                                               N_("Remove CERT_NUMBER (as listed by list_trusted)"
+                                                  " from trusted list."));
+  cmd_distrusted_hash = grub_register_extcmd ("distrusted_signature", grub_cmd_distrusted_hash, 0,
+                                              N_("[-b|--binary-hash] FILE [BINARY HASH FILE]\n"
+                                                 "[-c|--cert-hash] FILE [CERTFICATE HASH FILE]"),
+                                              N_("Add distrusted CERTFICATE/BINARY HASH "
+                                                 "to distrusted list."),
+			                                         options);
+  cmd_trusted_list = grub_register_command ("trusted_list", grub_cmd_trusted_list, 0,
+                                            N_("Show the list of trusted x509 certificates and"
+                                               " trusted binary hashes."));
+  cmd_distrusted_list = grub_register_command ("distrusted_list", grub_cmd_distrusted_list, 0,
+                                               N_("Show the list of distrusted certificates and"
+                                                  " certificate/binary hashes"));
   cmd_verify = grub_register_command ("verify_appended", grub_cmd_verify_signature, N_("FILE"),
-                                      N_("Verify FILE against the trusted x509 certificates."));
-  cmd_distrust = grub_register_command ("distrust_certificate", grub_cmd_distrust,
-                                        N_("CERT_NUMBER"),
-                                        N_("Remove CERT_NUMBER (as listed by list_certificates)"
-                                           " from trusted certificates."));
+                                      N_("Verify FILE against the trusted x509 certificates/"
+                                         "trusted binary hashes."));
 
   grub_verifier_register (&grub_appendedsig_verifier);
   grub_dl_set_persistent (mod);
@@ -1218,10 +1400,12 @@ GRUB_MOD_FINI (appendedsig)
    * grub_dl_set_persistent should prevent this from actually running, but
    * it does still run under emu.
    */
-
   grub_verifier_unregister (&grub_appendedsig_verifier);
   grub_unregister_command (cmd_verify);
-  grub_unregister_command (cmd_list);
-  grub_unregister_command (cmd_trust);
-  grub_unregister_command (cmd_distrust);
+  grub_unregister_command (cmd_trusted_list);
+  grub_unregister_command (cmd_distrusted_list);
+  grub_unregister_command (cmd_trusted_cert);
+  grub_unregister_command (cmd_distrusted_cert);
+  grub_unregister_command (cmd_trusted_hash);
+  grub_unregister_extcmd (cmd_distrusted_hash);
 }
Signature · 7 lines
2.43.5


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

Re: [PATCH v2 20/21] appendedsig: The grub command's trusted and distrusted support

Quoted 15 lines · Sudhakar Kuppusamy

To support the following trusted and distrusted commands

1. trusted_list:
It will show the list of trusted certificates and binary hashes
2. distrusted_list:
It will show the list of distrusted certificates and binary/certificate hashes
3. trusted_certificate:
It will add the trusted certificate to the trusted list
4. trusted_signature:
It will add the certificate/binary hash to the trusted list
5. distrusted_certificate:
It will remove the trusted certificate from trsuted list
6. distrusted_signature:
It will add the certificate/binary hash to the distrsuted list

Quoted 4 lines

Note:-
The addition/deletion of trusted certificates and binary hashes
are not allowed in grub command prompt while secure boot is enabled.

The test in PATCH 11 still relies on 'trust_certificate' and 'distrust_certificate'. Per the description, I guess the old test is not working anymore while secure boot is enabled? If so, we will need a new test for appendedsig.

Cheers,

Gary Lin

Quoted 640 lines
---
 grub-core/commands/appendedsig/appendedsig.c | 518 +++++++++++++------
 1 file changed, 351 insertions(+), 167 deletions(-)
grub-core/commands/appendedsig/appendedsig.c +351 -167
index 5631f0ab4..6f665aab2 100644
@@ -117,6 +117,36 @@ static enum
   check_sigs_forced = 2
 } check_sigs = check_sigs_no;
 
+enum
+{
+  OPTION_BINARY_HASH = 0,
+  OPTION_CERT_HASH = 1
+};
+
+static const struct grub_arg_option options[] =
+{
+  {"binary-hash", 'b', 0, N_("hash file of the binary."), 0, ARG_TYPE_NONE},
+  {"cert-hash", 'c', 1, N_("hash file of the certificate."), 0, ARG_TYPE_NONE},
+  {0, 0, 0, 0, 0, 0}
+};
+
+static void
+print_hex (const grub_uint8_t *data, const grub_size_t length)
+{
+  grub_size_t i, count = 0;
+  for (i = 0; i < length-1; i++)
+    {
+      grub_printf ("%02x:", data[i]);
+      count++;
+      if (count == 16)
+        {
+          grub_printf ("\n\t      ");
+          count = 0;
+        }
+    }
+  grub_printf ("%02x\n", data[i]);
+}
+
 /*
  * GUID can be used to determine the hashing function and
  * generate the hash using determined hashing function.
@@ -344,72 +374,6 @@ grub_env_write_sec (struct grub_env_var *var __attribute__ ((unused)), const cha
   return grub_strdup (grub_env_read_sec (NULL, NULL));
 }
 
-static grub_err_t
-file_read_all (grub_file_t file, grub_uint8_t **buf, grub_size_t *len)
-{
-  grub_off_t full_file_size;
-  grub_size_t file_size, total_read_size = 0;
-  grub_ssize_t read_size;
-
-  full_file_size = grub_file_size (file);
-  if (full_file_size == GRUB_FILE_SIZE_UNKNOWN)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT,
-                       N_("Cannot read a file of unknown size into a buffer"));
-
-  if (full_file_size > GRUB_SIZE_MAX)
-    return grub_error (GRUB_ERR_OUT_OF_RANGE,
-                       N_("File is too large to read: %" PRIuGRUB_UINT64_T " bytes"),
-                       full_file_size);
-
-  file_size = (grub_size_t) full_file_size;
-
-  *buf = grub_malloc (file_size);
-  if (!*buf)
-    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
-                       N_("Could not allocate file data buffer size %" PRIuGRUB_SIZE),
-                       file_size);
-
-  while (total_read_size < file_size)
-    {
-      read_size = grub_file_read (file, *buf + total_read_size, file_size - total_read_size);
-
-      if (read_size < 0)
-        {
-          grub_free (*buf);
-          return grub_errno;
-        }
-      else if (read_size == 0)
-        {
-          grub_free (*buf);
-          return grub_error (GRUB_ERR_IO,
-                             N_("Could not read full file size "
-                                "(%" PRIuGRUB_SIZE "), only %" PRIuGRUB_SIZE " bytes read"),
-                             file_size, total_read_size);
-        }
-
-      total_read_size += read_size;
-    }
-  *len = file_size;
-  return GRUB_ERR_NONE;
-}
-
-static grub_err_t
-read_cert_from_file (grub_file_t f, struct x509_certificate *certificate)
-{
-  grub_err_t err;
-  grub_uint8_t *buf;
-  grub_size_t file_size;
-
-  err = file_read_all (f, &buf, &file_size);
-  if (err != GRUB_ERR_NONE)
-    return err;
-
-  err = parse_x509_certificate (buf, file_size, certificate);
-  grub_free (buf);
-
-  return err;
-}
-
 static grub_err_t
 extract_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize,
                             struct grub_appended_signature *sig)
@@ -630,145 +594,347 @@ grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize)
 static grub_err_t
 grub_cmd_verify_signature (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
 {
-  grub_file_t f;
   grub_err_t err = GRUB_ERR_NONE;
-  grub_uint8_t *data;
-  grub_size_t file_size;
+  grub_file_t signed_file = NULL;
+  grub_uint8_t *signed_data = NULL;
+  grub_ssize_t signed_data_size = 0;
 
-  if (argc < 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument expected"));
+  if (argc != 1)
+    {
+      grub_printf (N_("a signed file is expected\n"
+                      "Example:\n\tverify_appended <SIGNED FILE>\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
 
   grub_dprintf ("appendedsig", "verifying %s\n", args[0]);
 
-  f = grub_file_open (args[0], GRUB_FILE_TYPE_VERIFY_SIGNATURE);
-  if (!f)
-    {
-      err = grub_errno;
-      goto cleanup;
-    }
+  signed_file = grub_file_open (args[0], GRUB_FILE_TYPE_VERIFY_SIGNATURE);
+  if (signed_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND, N_("unable to open a signed file"));
 
-  err = file_read_all (f, &data, &file_size);
+  err = grub_read_file (signed_file, &signed_data, &signed_data_size);
   if (err != GRUB_ERR_NONE)
-    goto cleanup;
-
-  err = grub_verify_appended_signature (data, file_size);
+    {
+      grub_file_close (signed_file);
+      return err;
+    }
 
-  grub_free (data);
+  grub_file_close (signed_file);
+  err = grub_verify_appended_signature (signed_data, signed_data_size);
+  grub_free (signed_data);
 
-cleanup:
-  if (f)
-    grub_file_close (f);
   return err;
 }
 
 static grub_err_t
-grub_cmd_distrust (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
+grub_cmd_trusted_list (grub_command_t cmd __attribute__((unused)),
+                       int argc __attribute__((unused)), char **args __attribute__((unused)))
 {
-  unsigned long cert_num, i;
-  struct x509_certificate *cert, *prev;
+  struct x509_certificate *cert = NULL;
+  grub_size_t i = 0, cert_num = 1;
 
-  if (argc != 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("One argument expected"));
+  for (cert = db.keys; cert; cert = cert->next)
+    {
+      grub_printf (N_("trusted certificate %" PRIuGRUB_SIZE ":\n"), cert_num);
+      grub_printf (N_("\tserial: "));
 
-  grub_errno = GRUB_ERR_NONE;
-  cert_num = grub_strtoul (args[0], NULL, 10);
-  if (grub_errno != GRUB_ERR_NONE)
-    return grub_errno;
+      for (i = 0; i < cert->serial_len - 1; i++)
+        grub_printf ("%02x:", cert->serial[i]);
 
-  if (cert_num < 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT,
-                       N_("Certificate number too small - numbers start at 1"));
+      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);
+      grub_printf ("\tCN: %s\n\n", cert->subject);
+      cert_num++;
+    }
 
-  if (cert_num == 1)
+  for (i = 0; i < db.signature_entries; i++)
     {
-      cert = db.keys;
-      db.keys = cert->next;
+      grub_printf (N_("trusted binary hash %" PRIuGRUB_SIZE ":\n"), i+1);
+      grub_printf (N_("\thash: "));
+      print_hex (db.signatures[i], db.signature_size[i]);
+    }
 
-      certificate_release (cert);
-      grub_free (cert);
-      return GRUB_ERR_NONE;
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_cmd_distrusted_list (grub_command_t cmd __attribute__((unused)),
+                          int argc __attribute__((unused)),
+                          char **args __attribute__((unused)))
+{
+  struct x509_certificate *cert = NULL;
+  grub_size_t i = 0, cert_num = 1;
+
+  for (cert = dbx.keys; cert; cert = cert->next)
+    {
+      grub_printf (N_("distrusted certificate %" PRIuGRUB_SIZE ":\n"), cert_num);
+      grub_printf (N_("\tserial: "));
+
+      for (i = 0; i < cert->serial_len - 1; i++)
+        grub_printf ("%02x:", cert->serial[i]);
+
+      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);
+      grub_printf ("\tCN: %s\n\n", cert->subject);
+      cert_num++;
     }
-  i = 2;
-  prev = db.keys;
-  cert = db.keys->next;
-  while (cert)
+
+  for (i = 0; i < dbx.signature_entries; i++)
     {
-      if (i == cert_num)
-        {
-          prev->next = cert->next;
-          certificate_release (cert);
-          grub_free (cert);
-          return GRUB_ERR_NONE;
-        }
-      i++;
-      prev = cert;
-      cert = cert->next;
+      grub_printf (N_("distrusted certificate/binary hash %" PRIuGRUB_SIZE ":\n"), i+1);
+      grub_printf (N_("\thash: "));
+      print_hex (dbx.signatures[i], dbx.signature_size[i]);
     }
 
-  return grub_error (GRUB_ERR_BAD_ARGUMENT,
-                     N_("No certificate number %lu found - only %lu certificates in the store"),
-                     cert_num, i - 1);
+  return GRUB_ERR_NONE;
 }
 
 static grub_err_t
-grub_cmd_trust (grub_command_t cmd __attribute__ ((unused)), int argc, char **args)
+grub_cmd_trusted_cert (grub_command_t cmd __attribute__((unused)),
+                       int argc, char **args)
 {
-  grub_file_t certf;
-  struct x509_certificate *cert = NULL;
-  grub_err_t err;
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_file_t cert_file = NULL;
+  grub_uint8_t *cert_data = NULL;
+  grub_ssize_t cert_data_size = 0;
 
   if (argc != 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument expected"));
+    {
+      grub_printf (N_("a trusted X.509 certificate file is expected\n"
+                      "Example:\n\ttrusted_certificate <CERT FILE>\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
 
-  certf = grub_file_open (args[0], GRUB_FILE_TYPE_CERTIFICATE_TRUST | GRUB_FILE_TYPE_NO_DECOMPRESS);
-  if (!certf)
-    return grub_errno;
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "adding of trusted X.509 certificate is not permitted!\n");
+      return grub_errno;
+    }
 
-  cert = grub_zalloc (sizeof (struct x509_certificate));
-  if (!cert)
-    return grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("Could not allocate memory for certificate"));
+  if (grub_strlen (args[0]) == 0)
+    return grub_error (GRUB_ERR_BAD_FILENAME,
+                       N_("missing trusted X.509 certificate file"));
 
-  err = read_cert_from_file (certf, cert);
-  grub_file_close (certf);
+  cert_file = grub_file_open (args[0], GRUB_FILE_TYPE_CERTIFICATE_TRUST |
+                              GRUB_FILE_TYPE_NO_DECOMPRESS);
+  if (cert_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND,
+                       N_("unable to open the trusted X.509 certificate file"));
+
+  err = grub_read_file (cert_file, &cert_data, &cert_data_size);
   if (err != GRUB_ERR_NONE)
     {
-      grub_free (cert);
+      grub_file_close (cert_file);
       return err;
     }
-  grub_dprintf ("appendedsig", "Loaded certificate with CN: %s\n", cert->subject);
 
-  cert->next = db.keys;
-  db.keys = cert;
+  grub_file_close (cert_file);
+  err = add_certificate (cert_data, cert_data_size, &db, 1);
+  if (err != GRUB_ERR_NONE)
+    {
+      free_trusted_list ();
+      free_distrusted_list ();
+      grub_error (err, "adding of trusted certificate failed");
+    }
 
-  return GRUB_ERR_NONE;
+  grub_free (cert_data);
+
+  return err;
 }
 
 static grub_err_t
-grub_cmd_list (grub_command_t cmd __attribute__ ((unused)), int argc __attribute__ ((unused)),
-               char **args __attribute__ ((unused)))
+grub_cmd_trusted_hash (grub_command_t cmd __attribute__((unused)), int argc, char**args)
 {
-  struct x509_certificate *cert;
-  int cert_num = 1;
-  grub_size_t i;
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_file_t hash_file = NULL;
+  grub_uint8_t *hash_data = NULL;
+  grub_ssize_t hash_data_size = 0;
 
-  for (cert = db.keys; cert; cert = cert->next)
+  if (argc != 1)
     {
-      grub_printf (N_("Certificate %d:\n"), cert_num);
+      grub_printf (N_("a trusted binary hash file is expected\n"
+                      "Example:\n\ttrusted_signature <BINARY HASH FILE>\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
 
-      grub_printf (N_("\tSerial: "));
-      for (i = 0; i < cert->serial_len - 1; i++)
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "adding of trusted binary hash is not permitted!\n");
+      return grub_errno;
+    }
+
+  if (grub_strlen (args[0]) == 0)
+    return grub_error (GRUB_ERR_BAD_FILENAME, N_("missing trusted binary hash file"));
+
+  hash_file = grub_file_open (args[0], GRUB_FILE_TYPE_TO_HASH | GRUB_FILE_TYPE_NO_DECOMPRESS);
+  if (hash_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND,
+                       N_("unable to open the trusted binary hash file"));
+
+  rc = grub_read_file (hash_file, &hash_data, &hash_data_size);
+  if (rc != GRUB_ERR_NONE)
+    {
+      grub_file_close (hash_file);
+      return rc;
+    }
+
+  grub_file_close (hash_file);
+
+  grub_dprintf ("appendedsig", "adding a trusted binary hash %s\n with size of %" PRIuGRUB_SIZE "\n",
+                hash_data, hash_data_size);
+
+  /* only accept SHA256, SHA384 and SHA512 binary hash */
+  if (hash_data_size != 32 && hash_data_size != 48 && hash_data_size != 64)
+    return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("unacceptable trusted binary hash type"));
+
+  rc = add_hash ((const grub_uint8_t **) &hash_data, hash_data_size, &db.signatures,
+                 &db.signature_size, &db.signature_entries);
+  if (rc != GRUB_ERR_NONE)
+    {
+      free_trusted_list ();
+      free_distrusted_list ();
+      grub_error (rc, "adding of trusted binary hash failed");
+    }
+
+  grub_free (hash_data);
+
+  return rc;
+}
+
+static grub_err_t
+grub_cmd_distrusted_cert (grub_command_t cmd __attribute__((unused)), int argc, char **args)
+{
+  grub_size_t cert_num = 0, i = 1;
+  struct x509_certificate *current_cert = db.keys;
+  struct x509_certificate *previous_cert = db.keys;
+
+  if (argc != 1)
+    {
+      grub_printf (N_("trusted certificate number is expected\n"
+                      "Example:\n\tdistrusted_certificate <CERT_NUMER>\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "removing of trusted certificate is not permitted!\n");
+      return grub_errno;
+    }
+
+  cert_num = grub_strtoul (args[0], NULL, 10);
+  if (cert_num < 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("trusted certificate number should to begin with 1"));
+
+  if (cert_num > db.key_entries)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("trusted certificate number should not exceed %" PRIuGRUB_SIZE ""),
+                       db.key_entries);
+  else if (cert_num < db.key_entries)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("there is no certificate on the trusted list. so, not permitted"));
+
+  for (i = 1; i < db.key_entries; i++)
+    {
+      if (cert_num == 1)
         {
-          grub_printf ("%02x:", cert->serial[i]);
+          previous_cert = current_cert->next;
+          break;
+        }
+      else if (cert_num == i)
+        {
+          previous_cert->next = current_cert->next;
+          break;
         }
-      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);
 
-      grub_printf ("\tCN: %s\n\n", cert->subject);
-      cert_num++;
+      previous_cert = current_cert;
+      current_cert = current_cert->next;
     }
 
+  certificate_release (current_cert);
+  grub_free (current_cert);
+
   return GRUB_ERR_NONE;
 }
 
+static grub_err_t
+grub_cmd_distrusted_hash (grub_extcmd_context_t ctxt, int argc, char **args)
+{
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_file_t hash_file = NULL;
+  grub_uint8_t *hash_data = NULL;
+  grub_ssize_t hash_data_size = 0;
+
+  if (argc != 2)
+    {
+      grub_printf (N_("a distrusted certificate/binary hash file is expected\n"
+                      "Example:\n\tdistrusted_signature [option] <FILE>\n"
+                      "option:\n[-b|--binary-hash] FILE [BINARY HASH FILE]\n"
+                      "[-c|--cert-hash] FILE [CERTFICATE HASH FILE]\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "adding of distrusted certificate/binary hash is not permitted!\n");
+      return grub_errno;
+    }
+
+  if (!ctxt->state[OPTION_BINARY_HASH].set && !ctxt->state[OPTION_CERT_HASH].set)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("missing options and use --help to konw"));
+
+  if (grub_strlen (args[1]) == 0)
+    return grub_error (GRUB_ERR_BAD_FILENAME,
+                       N_("missing distrusted certificate/binary hash file"));
+
+  hash_file = grub_file_open (args[1], GRUB_FILE_TYPE_TO_HASH | GRUB_FILE_TYPE_NO_DECOMPRESS);
+  if (hash_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND,
+                       N_("unable to open the distrusted certificate/binary hash file"));
+
+  rc = grub_read_file (hash_file, &hash_data, &hash_data_size);
+  if (rc != GRUB_ERR_NONE)
+    {
+      grub_file_close (hash_file);
+      return rc;
+    }
+
+  grub_file_close (hash_file);
+
+  grub_dprintf ("appendedsig", "adding a distrusted certificate/binary hash %s\n"
+                " with size of %" PRIuGRUB_SIZE "\n", hash_data, hash_data_size);
+
+  if (ctxt->state[OPTION_BINARY_HASH].set)
+    {
+      /* only accept SHA256, SHA384 and SHA512 binary hash */
+      if (hash_data_size != 32 && hash_data_size != 48 && hash_data_size != 64)
+        return grub_error (GRUB_ERR_BAD_SIGNATURE,
+                           N_("unacceptable distrusted binary hash type"));
+    }
+  else if (ctxt->state[OPTION_CERT_HASH].set)
+    {
+      /* only accept SHA256, SHA384 and SHA512 certificate hash */
+      if (hash_data_size != 32 && hash_data_size != 48 && hash_data_size != 64)
+        return grub_error (GRUB_ERR_BAD_SIGNATURE,
+                           N_("unacceptable distrusted certificate hash type"));
+    }
+
+  rc = add_hash ((const grub_uint8_t **) &hash_data, hash_data_size, &dbx.signatures,
+                 &dbx.signature_size, &dbx.signature_entries);
+  if (rc != GRUB_ERR_NONE)
+    {
+      free_trusted_list ();
+      free_distrusted_list ();
+      grub_error (rc, "adding of distrusted binary/certificate hash failed");
+    }
+
+  grub_free (hash_data);
+
+  return rc;
+}
+
 static grub_err_t
 appendedsig_init (grub_file_t io __attribute__ ((unused)), enum grub_file_type type,
                   void **context __attribute__ ((unused)), enum grub_verify_flags *flags)
@@ -842,8 +1008,6 @@ pseudo_read (struct grub_file *file, char *buf, grub_size_t len)
 /* Filesystem descriptor.  */
 static struct grub_fs pseudo_fs = { .name = "pseudo", .fs_read = pseudo_read };
 
-static grub_command_t cmd_verify, cmd_list, cmd_distrust, cmd_trust;
-
 /*
  * Verify the trusted certificate against the certificate hashes from platform keystore buffer's
  * distrusted list.
@@ -1135,6 +1299,10 @@ load_static_keys (const struct grub_module_header *header, const grub_bool_t is_
   return rc;
 }
 
+static grub_extcmd_t cmd_distrusted_hash;
+static grub_command_t cmd_verify, cmd_trusted_list, cmd_trusted_cert, cmd_trusted_hash,
+                      cmd_distrusted_list, cmd_distrusted_cert;
+
 GRUB_MOD_INIT (appendedsig)
 {
   int rc;
@@ -1196,17 +1364,31 @@ GRUB_MOD_INIT (appendedsig)
 
       grub_pks_free_keystore ();
     }
-
-  cmd_trust = grub_register_command ("trust_certificate", grub_cmd_trust, N_("X509_CERTIFICATE"),
-                                     N_("Add X509_CERTIFICATE to trusted certificates."));
-  cmd_list = grub_register_command ("list_certificates", grub_cmd_list, 0,
-                                    N_("Show the list of trusted x509 certificates."));
+  cmd_trusted_cert = grub_register_command ("trusted_certificate", grub_cmd_trusted_cert,
+                                            N_("X509_CERTIFICATE"),
+                                            N_("Add X509_CERTIFICATE to trusted list."));
+  cmd_trusted_hash = grub_register_command ("trusted_signature", grub_cmd_trusted_hash,
+                                            N_("BINARY HASH FILE"),
+                                            N_("Add trusted BINARY HASH to trusted list."));
+  cmd_distrusted_cert = grub_register_command ("distrusted_certificate", grub_cmd_distrusted_cert,
+                                               N_("CERT_NUMBER"),
+                                               N_("Remove CERT_NUMBER (as listed by list_trusted)"
+                                                  " from trusted list."));
+  cmd_distrusted_hash = grub_register_extcmd ("distrusted_signature", grub_cmd_distrusted_hash, 0,
+                                              N_("[-b|--binary-hash] FILE [BINARY HASH FILE]\n"
+                                                 "[-c|--cert-hash] FILE [CERTFICATE HASH FILE]"),
+                                              N_("Add distrusted CERTFICATE/BINARY HASH "
+                                                 "to distrusted list."),
+			                                         options);
+  cmd_trusted_list = grub_register_command ("trusted_list", grub_cmd_trusted_list, 0,
+                                            N_("Show the list of trusted x509 certificates and"
+                                               " trusted binary hashes."));
+  cmd_distrusted_list = grub_register_command ("distrusted_list", grub_cmd_distrusted_list, 0,
+                                               N_("Show the list of distrusted certificates and"
+                                                  " certificate/binary hashes"));
   cmd_verify = grub_register_command ("verify_appended", grub_cmd_verify_signature, N_("FILE"),
-                                      N_("Verify FILE against the trusted x509 certificates."));
-  cmd_distrust = grub_register_command ("distrust_certificate", grub_cmd_distrust,
-                                        N_("CERT_NUMBER"),
-                                        N_("Remove CERT_NUMBER (as listed by list_certificates)"
-                                           " from trusted certificates."));
+                                      N_("Verify FILE against the trusted x509 certificates/"
+                                         "trusted binary hashes."));
 
   grub_verifier_register (&grub_appendedsig_verifier);
   grub_dl_set_persistent (mod);
@@ -1218,10 +1400,12 @@ GRUB_MOD_FINI (appendedsig)
    * grub_dl_set_persistent should prevent this from actually running, but
    * it does still run under emu.
    */
-
   grub_verifier_unregister (&grub_appendedsig_verifier);
   grub_unregister_command (cmd_verify);
-  grub_unregister_command (cmd_list);
-  grub_unregister_command (cmd_trust);
-  grub_unregister_command (cmd_distrust);
+  grub_unregister_command (cmd_trusted_list);
+  grub_unregister_command (cmd_distrusted_list);
+  grub_unregister_command (cmd_trusted_cert);
+  grub_unregister_command (cmd_distrusted_cert);
+  grub_unregister_command (cmd_trusted_hash);
+  grub_unregister_extcmd (cmd_distrusted_hash);
 }
Signature · 7 lines
2.43.5


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

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

author
#42 lore raw

Re: [PATCH v2 20/21] appendedsig: The grub command's trusted and distrusted support

Quoted 22 lines · Gary Lin
Quoted 17 lines · Sudhakar Kuppusamy

To support the following trusted and distrusted commands

1. trusted_list:
It will show the list of trusted certificates and binary
hashes
2. distrusted_list:
It will show the list of distrusted certificates and
binary/certificate hashes
3. trusted_certificate:
It will add the trusted certificate to the trusted list
4. trusted_signature:
It will add the certificate/binary hash to the trusted list
5. distrusted_certificate:
It will remove the trusted certificate from trsuted list
6. distrusted_signature:
It will add the certificate/binary hash to the distrsuted list

Quoted 4 lines

Note:-
The addition/deletion of trusted certificates and binary hashes
are not allowed in grub command prompt while secure boot is enabled.

Quoted 9 lines

The test in PATCH 11 still relies on 'trust_certificate' and 'distrust_certificate'. Per the description, I guess the old test is not working anymore while secure boot is enabled? If so, we will need a new test for appendedsig.

Cheers,

Gary Lin

Hi Gary Lin,
Thank you so much for a review!. I will write new test for appendedsig.

Thanks,
Sudhakar Kuppusamy

Quoted 747 lines
Quoted 747 lines
---
 grub-core/commands/appendedsig/appendedsig.c | 518 
+++++++++++++------
 1 file changed, 351 insertions(+), 167 deletions(-)
grub-core/commands/appendedsig/appendedsig.c +30 -0
index 5631f0ab4..6f665aab2 100644
@@ -117,6 +117,36 @@ static enum
   check_sigs_forced = 2
 } check_sigs = check_sigs_no;
 
+enum
+{
+  OPTION_BINARY_HASH = 0,
+  OPTION_CERT_HASH = 1
+};
+
+static const struct grub_arg_option options[] =
+{
+  {"binary-hash", 'b', 0, N_("hash file of the binary."), 0, 
 ARG_TYPE_NONE},
+  {"cert-hash", 'c', 1, N_("hash file of the certificate."), 0, 
 ARG_TYPE_NONE},
+  {0, 0, 0, 0, 0, 0}
+};
+
+static void
+print_hex (const grub_uint8_t *data, const grub_size_t length)
+{
+  grub_size_t i, count = 0;
+  for (i = 0; i < length-1; i++)
+    {
+      grub_printf ("%02x:", data[i]);
+      count++;
+      if (count == 16)
+        {
+          grub_printf ("\n\t      ");
+          count = 0;
+        }
+    }
+  grub_printf ("%02x\n", data[i]);
+}
+
 /*

* GUID can be used to determine the hashing function and
* generate the hash using determined hashing function.

grub-core/commands/appendedsig/appendedsig.c +0 -0
@@ -344,72 +374,6 @@ grub_env_write_sec (struct grub_env_var *var 

__attribute__ ((unused)), const cha
return grub_strdup (grub_env_read_sec (NULL, NULL));
}

grub-core/commands/appendedsig/appendedsig.c +0 -2
-static grub_err_t
-file_read_all (grub_file_t file, grub_uint8_t **buf, grub_size_t 

*len)

grub-core/commands/appendedsig/appendedsig.c +0 -9
-{
-  grub_off_t full_file_size;
-  grub_size_t file_size, total_read_size = 0;
-  grub_ssize_t read_size;
-
-  full_file_size = grub_file_size (file);
-  if (full_file_size == GRUB_FILE_SIZE_UNKNOWN)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT,
-                       N_("Cannot read a file of unknown size into a 

buffer"));

grub-core/commands/appendedsig/appendedsig.c +0 -4
-
-  if (full_file_size > GRUB_SIZE_MAX)
-    return grub_error (GRUB_ERR_OUT_OF_RANGE,
-                       N_("File is too large to read: %" 

PRIuGRUB_UINT64_T " bytes"),

grub-core/commands/appendedsig/appendedsig.c +0 -8
-                       full_file_size);
-
-  file_size = (grub_size_t) full_file_size;
-
-  *buf = grub_malloc (file_size);
-  if (!*buf)
-    return grub_error (GRUB_ERR_OUT_OF_MEMORY,
-                       N_("Could not allocate file data buffer size 

%" PRIuGRUB_SIZE),

grub-core/commands/appendedsig/appendedsig.c +0 -5
-                       file_size);
-
-  while (total_read_size < file_size)
-    {
-      read_size = grub_file_read (file, *buf + total_read_size, 

file_size - total_read_size);

grub-core/commands/appendedsig/appendedsig.c +0 -12
-
-      if (read_size < 0)
-        {
-          grub_free (*buf);
-          return grub_errno;
-        }
-      else if (read_size == 0)
-        {
-          grub_free (*buf);
-          return grub_error (GRUB_ERR_IO,
-                             N_("Could not read full file size "
-                                "(%" PRIuGRUB_SIZE "), only %" 

PRIuGRUB_SIZE " bytes read"),

grub-core/commands/appendedsig/appendedsig.c +0 -11
-                             file_size, total_read_size);
-        }
-
-      total_read_size += read_size;
-    }
-  *len = file_size;
-  return GRUB_ERR_NONE;
-}
-
-static grub_err_t
-read_cert_from_file (grub_file_t f, struct x509_certificate 

*certificate)

grub-core/commands/appendedsig/appendedsig.c +0 -15
-{
-  grub_err_t err;
-  grub_uint8_t *buf;
-  grub_size_t file_size;
-
-  err = file_read_all (f, &buf, &file_size);
-  if (err != GRUB_ERR_NONE)
-    return err;
-
-  err = parse_x509_certificate (buf, file_size, certificate);
-  grub_free (buf);
-
-  return err;
-}
-
 static grub_err_t
 extract_appended_signature (const grub_uint8_t *buf, grub_size_t 

bufsize,
struct grub_appended_signature *sig)

grub-core/commands/appendedsig/appendedsig.c +75 -59
@@ -630,145 +594,347 @@ grub_verify_appended_signature (const 
 grub_uint8_t *buf, grub_size_t bufsize)
 static grub_err_t
 grub_cmd_verify_signature (grub_command_t cmd __attribute__ 
 ((unused)), int argc, char **args)
 {
-  grub_file_t f;
   grub_err_t err = GRUB_ERR_NONE;
-  grub_uint8_t *data;
-  grub_size_t file_size;
+  grub_file_t signed_file = NULL;
+  grub_uint8_t *signed_data = NULL;
+  grub_ssize_t signed_data_size = 0;
 
-  if (argc < 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument 
 expected"));
+  if (argc != 1)
+    {
+      grub_printf (N_("a signed file is expected\n"
+                      "Example:\n\tverify_appended <SIGNED 
 FILE>\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
 
   grub_dprintf ("appendedsig", "verifying %s\n", args[0]);
 
-  f = grub_file_open (args[0], GRUB_FILE_TYPE_VERIFY_SIGNATURE);
-  if (!f)
-    {
-      err = grub_errno;
-      goto cleanup;
-    }
+  signed_file = grub_file_open (args[0], 
 GRUB_FILE_TYPE_VERIFY_SIGNATURE);
+  if (signed_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND, N_("unable to open a 
 signed file"));
 
-  err = file_read_all (f, &data, &file_size);
+  err = grub_read_file (signed_file, &signed_data, 
 &signed_data_size);
   if (err != GRUB_ERR_NONE)
-    goto cleanup;
-
-  err = grub_verify_appended_signature (data, file_size);
+    {
+      grub_file_close (signed_file);
+      return err;
+    }
 
-  grub_free (data);
+  grub_file_close (signed_file);
+  err = grub_verify_appended_signature (signed_data, 
 signed_data_size);
+  grub_free (signed_data);
 
-cleanup:
-  if (f)
-    grub_file_close (f);
   return err;
 }
 
 static grub_err_t
-grub_cmd_distrust (grub_command_t cmd __attribute__ ((unused)), int 
 argc, char **args)
+grub_cmd_trusted_list (grub_command_t cmd __attribute__((unused)),
+                       int argc __attribute__((unused)), char **args 
 __attribute__((unused)))
 {
-  unsigned long cert_num, i;
-  struct x509_certificate *cert, *prev;
+  struct x509_certificate *cert = NULL;
+  grub_size_t i = 0, cert_num = 1;
 
-  if (argc != 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("One argument 
 expected"));
+  for (cert = db.keys; cert; cert = cert->next)
+    {
+      grub_printf (N_("trusted certificate %" PRIuGRUB_SIZE ":\n"), 
 cert_num);
+      grub_printf (N_("\tserial: "));
 
-  grub_errno = GRUB_ERR_NONE;
-  cert_num = grub_strtoul (args[0], NULL, 10);
-  if (grub_errno != GRUB_ERR_NONE)
-    return grub_errno;
+      for (i = 0; i < cert->serial_len - 1; i++)
+        grub_printf ("%02x:", cert->serial[i]);
 
-  if (cert_num < 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT,
-                       N_("Certificate number too small - numbers 
 start at 1"));
+      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);
+      grub_printf ("\tCN: %s\n\n", cert->subject);
+      cert_num++;
+    }
 
-  if (cert_num == 1)
+  for (i = 0; i < db.signature_entries; i++)
     {
-      cert = db.keys;
-      db.keys = cert->next;
+      grub_printf (N_("trusted binary hash %" PRIuGRUB_SIZE ":\n"), 
 i+1);
+      grub_printf (N_("\thash: "));
+      print_hex (db.signatures[i], db.signature_size[i]);
+    }
 
-      certificate_release (cert);
-      grub_free (cert);
-      return GRUB_ERR_NONE;
+  return GRUB_ERR_NONE;
+}
+
+static grub_err_t
+grub_cmd_distrusted_list (grub_command_t cmd __attribute__((unused)),
+                          int argc __attribute__((unused)),
+                          char **args __attribute__((unused)))
+{
+  struct x509_certificate *cert = NULL;
+  grub_size_t i = 0, cert_num = 1;
+
+  for (cert = dbx.keys; cert; cert = cert->next)
+    {
+      grub_printf (N_("distrusted certificate %" PRIuGRUB_SIZE 
 ":\n"), cert_num);
+      grub_printf (N_("\tserial: "));
+
+      for (i = 0; i < cert->serial_len - 1; i++)
+        grub_printf ("%02x:", cert->serial[i]);
+
+      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);
+      grub_printf ("\tCN: %s\n\n", cert->subject);
+      cert_num++;
     }
-  i = 2;
-  prev = db.keys;
-  cert = db.keys->next;
-  while (cert)
+
+  for (i = 0; i < dbx.signature_entries; i++)
     {
-      if (i == cert_num)
-        {
-          prev->next = cert->next;
-          certificate_release (cert);
-          grub_free (cert);
-          return GRUB_ERR_NONE;
-        }
-      i++;
-      prev = cert;
-      cert = cert->next;
+      grub_printf (N_("distrusted certificate/binary hash %" 
 PRIuGRUB_SIZE ":\n"), i+1);
+      grub_printf (N_("\thash: "));
+      print_hex (dbx.signatures[i], dbx.signature_size[i]);
     }
 
-  return grub_error (GRUB_ERR_BAD_ARGUMENT,
-                     N_("No certificate number %lu found - only %lu 
 certificates in the store"),
-                     cert_num, i - 1);
+  return GRUB_ERR_NONE;
 }
 
 static grub_err_t
-grub_cmd_trust (grub_command_t cmd __attribute__ ((unused)), int 
 argc, char **args)
+grub_cmd_trusted_cert (grub_command_t cmd __attribute__((unused)),
+                       int argc, char **args)
 {
-  grub_file_t certf;
-  struct x509_certificate *cert = NULL;
-  grub_err_t err;
+  grub_err_t err = GRUB_ERR_NONE;
+  grub_file_t cert_file = NULL;
+  grub_uint8_t *cert_data = NULL;
+  grub_ssize_t cert_data_size = 0;
 
   if (argc != 1)
-    return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("one argument 
 expected"));
+    {
+      grub_printf (N_("a trusted X.509 certificate file is 

expected\n"
+ "Example:\n\ttrusted_certificate <CERT
FILE>\n"));

grub-core/commands/appendedsig/appendedsig.c +2 -1
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
 
-  certf = grub_file_open (args[0], GRUB_FILE_TYPE_CERTIFICATE_TRUST | 

GRUB_FILE_TYPE_NO_DECOMPRESS);

grub-core/commands/appendedsig/appendedsig.c +4 -2
-  if (!certf)
-    return grub_errno;
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "adding of trusted X.509 certificate is not 

permitted!\n");

grub-core/commands/appendedsig/appendedsig.c +2 -3
+      return grub_errno;
+    }
 
-  cert = grub_zalloc (sizeof (struct x509_certificate));
-  if (!cert)
-    return grub_error (GRUB_ERR_OUT_OF_MEMORY, N_("Could not allocate 

memory for certificate"));

grub-core/commands/appendedsig/appendedsig.c +4 -2
+  if (grub_strlen (args[0]) == 0)
+    return grub_error (GRUB_ERR_BAD_FILENAME,
+                       N_("missing trusted X.509 certificate file"));
 
-  err = read_cert_from_file (certf, cert);
-  grub_file_close (certf);
+  cert_file = grub_file_open (args[0], 

GRUB_FILE_TYPE_CERTIFICATE_TRUST |

grub-core/commands/appendedsig/appendedsig.c +4 -0
+                              GRUB_FILE_TYPE_NO_DECOMPRESS);
+  if (cert_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND,
+                       N_("unable to open the trusted X.509 

certificate file"));

grub-core/commands/appendedsig/appendedsig.c +3 -2
+
+  err = grub_read_file (cert_file, &cert_data, &cert_data_size);
   if (err != GRUB_ERR_NONE)
     {
-      grub_free (cert);
+      grub_file_close (cert_file);
       return err;
     }
-  grub_dprintf ("appendedsig", "Loaded certificate with CN: %s\n", 

cert->subject);

grub-core/commands/appendedsig/appendedsig.c +11 -4
-  cert->next = db.keys;
-  db.keys = cert;
+  grub_file_close (cert_file);
+  err = add_certificate (cert_data, cert_data_size, &db, 1);
+  if (err != GRUB_ERR_NONE)
+    {
+      free_trusted_list ();
+      free_distrusted_list ();
+      grub_error (err, "adding of trusted certificate failed");
+    }
 
-  return GRUB_ERR_NONE;
+  grub_free (cert_data);
+
+  return err;
 }
 
 static grub_err_t
-grub_cmd_list (grub_command_t cmd __attribute__ ((unused)), int argc 

__attribute__ ((unused)),

grub-core/commands/appendedsig/appendedsig.c +1 -1
-               char **args __attribute__ ((unused)))
+grub_cmd_trusted_hash (grub_command_t cmd __attribute__((unused)), 

int argc, char**args)
{

grub-core/commands/appendedsig/appendedsig.c +7 -5
-  struct x509_certificate *cert;
-  int cert_num = 1;
-  grub_size_t i;
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_file_t hash_file = NULL;
+  grub_uint8_t *hash_data = NULL;
+  grub_ssize_t hash_data_size = 0;
 
-  for (cert = db.keys; cert; cert = cert->next)
+  if (argc != 1)
     {
-      grub_printf (N_("Certificate %d:\n"), cert_num);
+      grub_printf (N_("a trusted binary hash file is expected\n"
+                      "Example:\n\ttrusted_signature <BINARY HASH 

FILE>\n"));

grub-core/commands/appendedsig/appendedsig.c +6 -2
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
 
-      grub_printf (N_("\tSerial: "));
-      for (i = 0; i < cert->serial_len - 1; i++)
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "adding of trusted binary hash is not 

permitted!\n");

grub-core/commands/appendedsig/appendedsig.c +5 -0
+      return grub_errno;
+    }
+
+  if (grub_strlen (args[0]) == 0)
+    return grub_error (GRUB_ERR_BAD_FILENAME, N_("missing trusted 

binary hash file"));

grub-core/commands/appendedsig/appendedsig.c +2 -0
+
+  hash_file = grub_file_open (args[0], GRUB_FILE_TYPE_TO_HASH | 

GRUB_FILE_TYPE_NO_DECOMPRESS);

grub-core/commands/appendedsig/appendedsig.c +3 -0
+  if (hash_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND,
+                       N_("unable to open the trusted binary hash 

file"));

grub-core/commands/appendedsig/appendedsig.c +11 -0
+
+  rc = grub_read_file (hash_file, &hash_data, &hash_data_size);
+  if (rc != GRUB_ERR_NONE)
+    {
+      grub_file_close (hash_file);
+      return rc;
+    }
+
+  grub_file_close (hash_file);
+
+  grub_dprintf ("appendedsig", "adding a trusted binary hash %s\n 

with size of %" PRIuGRUB_SIZE "\n",

grub-core/commands/appendedsig/appendedsig.c +4 -0
+                hash_data, hash_data_size);
+
+  /* only accept SHA256, SHA384 and SHA512 binary hash */
+  if (hash_data_size != 32 && hash_data_size != 48 && hash_data_size 

!= 64)
+ return grub_error (GRUB_ERR_BAD_SIGNATURE, N_("unacceptable
trusted binary hash type"));

grub-core/commands/appendedsig/appendedsig.c +2 -0
+
+  rc = add_hash ((const grub_uint8_t **) &hash_data, hash_data_size, 

&db.signatures,

grub-core/commands/appendedsig/appendedsig.c +15 -0
+                 &db.signature_size, &db.signature_entries);
+  if (rc != GRUB_ERR_NONE)
+    {
+      free_trusted_list ();
+      free_distrusted_list ();
+      grub_error (rc, "adding of trusted binary hash failed");
+    }
+
+  grub_free (hash_data);
+
+  return rc;
+}
+
+static grub_err_t
+grub_cmd_distrusted_cert (grub_command_t cmd __attribute__((unused)), 

int argc, char **args)

grub-core/commands/appendedsig/appendedsig.c +9 -0
+{
+  grub_size_t cert_num = 0, i = 1;
+  struct x509_certificate *current_cert = db.keys;
+  struct x509_certificate *previous_cert = db.keys;
+
+  if (argc != 1)
+    {
+      grub_printf (N_("trusted certificate number is expected\n"
+                      "Example:\n\tdistrusted_certificate 

<CERT_NUMER>\n"));

grub-core/commands/appendedsig/appendedsig.c +7 -0
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "removing of trusted certificate is not 

permitted!\n");

grub-core/commands/appendedsig/appendedsig.c +7 -0
+      return grub_errno;
+    }
+
+  cert_num = grub_strtoul (args[0], NULL, 10);
+  if (cert_num < 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("trusted certificate number should to begin 

with 1"));

grub-core/commands/appendedsig/appendedsig.c +4 -0
+
+  if (cert_num > db.key_entries)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("trusted certificate number should not 

exceed %" PRIuGRUB_SIZE ""),

grub-core/commands/appendedsig/appendedsig.c +4 -0
+                       db.key_entries);
+  else if (cert_num < db.key_entries)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("there is no certificate on the trusted 

list. so, not permitted"));

grub-core/commands/appendedsig/appendedsig.c +18 -4
+
+  for (i = 1; i < db.key_entries; i++)
+    {
+      if (cert_num == 1)
         {
-          grub_printf ("%02x:", cert->serial[i]);
+          previous_cert = current_cert->next;
+          break;
+        }
+      else if (cert_num == i)
+        {
+          previous_cert->next = current_cert->next;
+          break;
         }
-      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);
 
-      grub_printf ("\tCN: %s\n\n", cert->subject);
-      cert_num++;
+      previous_cert = current_cert;
+      current_cert = current_cert->next;
     }
 
+  certificate_release (current_cert);
+  grub_free (current_cert);
+
   return GRUB_ERR_NONE;
 }
 
+static grub_err_t
+grub_cmd_distrusted_hash (grub_extcmd_context_t ctxt, int argc, char 

**args)

grub-core/commands/appendedsig/appendedsig.c +9 -0
+{
+  grub_err_t rc = GRUB_ERR_NONE;
+  grub_file_t hash_file = NULL;
+  grub_uint8_t *hash_data = NULL;
+  grub_ssize_t hash_data_size = 0;
+
+  if (argc != 2)
+    {
+      grub_printf (N_("a distrusted certificate/binary hash file is 

expected\n"
+ "Example:\n\tdistrusted_signature [option]
<FILE>\n"
+ "option:\n[-b|--binary-hash] FILE [BINARY HASH
FILE]\n"
+ "[-c|--cert-hash] FILE [CERTFICATE HASH
FILE]\n"));

grub-core/commands/appendedsig/appendedsig.c +7 -0
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "adding of distrusted certificate/binary hash is 

not permitted!\n");

grub-core/commands/appendedsig/appendedsig.c +4 -0
+      return grub_errno;
+    }
+
+  if (!ctxt->state[OPTION_BINARY_HASH].set && 

!ctxt->state[OPTION_CERT_HASH].set)
+ return grub_error (GRUB_ERR_BAD_ARGUMENT, N_("missing options and
use --help to konw"));

grub-core/commands/appendedsig/appendedsig.c +4 -0
+
+  if (grub_strlen (args[1]) == 0)
+    return grub_error (GRUB_ERR_BAD_FILENAME,
+                       N_("missing distrusted certificate/binary hash 

file"));

grub-core/commands/appendedsig/appendedsig.c +2 -0
+
+  hash_file = grub_file_open (args[1], GRUB_FILE_TYPE_TO_HASH | 

GRUB_FILE_TYPE_NO_DECOMPRESS);

grub-core/commands/appendedsig/appendedsig.c +3 -0
+  if (hash_file == NULL)
+    return grub_error (GRUB_ERR_FILE_NOT_FOUND,
+                       N_("unable to open the distrusted 

certificate/binary hash file"));

grub-core/commands/appendedsig/appendedsig.c +11 -0
+
+  rc = grub_read_file (hash_file, &hash_data, &hash_data_size);
+  if (rc != GRUB_ERR_NONE)
+    {
+      grub_file_close (hash_file);
+      return rc;
+    }
+
+  grub_file_close (hash_file);
+
+  grub_dprintf ("appendedsig", "adding a distrusted 

certificate/binary hash %s\n"
+ " with size of %" PRIuGRUB_SIZE "\n", hash_data,
hash_data_size);

grub-core/commands/appendedsig/appendedsig.c +5 -0
+
+  if (ctxt->state[OPTION_BINARY_HASH].set)
+    {
+      /* only accept SHA256, SHA384 and SHA512 binary hash */
+      if (hash_data_size != 32 && hash_data_size != 48 && 

hash_data_size != 64)

grub-core/commands/appendedsig/appendedsig.c +2 -0
+        return grub_error (GRUB_ERR_BAD_SIGNATURE,
+                           N_("unacceptable distrusted binary hash 

type"));

grub-core/commands/appendedsig/appendedsig.c +5 -0
+    }
+  else if (ctxt->state[OPTION_CERT_HASH].set)
+    {
+      /* only accept SHA256, SHA384 and SHA512 certificate hash */
+      if (hash_data_size != 32 && hash_data_size != 48 && 

hash_data_size != 64)

grub-core/commands/appendedsig/appendedsig.c +2 -0
+        return grub_error (GRUB_ERR_BAD_SIGNATURE,
+                           N_("unacceptable distrusted certificate 

hash type"));

grub-core/commands/appendedsig/appendedsig.c +3 -0
+    }
+
+  rc = add_hash ((const grub_uint8_t **) &hash_data, hash_data_size, 

&dbx.signatures,

grub-core/commands/appendedsig/appendedsig.c +6 -0
+                 &dbx.signature_size, &dbx.signature_entries);
+  if (rc != GRUB_ERR_NONE)
+    {
+      free_trusted_list ();
+      free_distrusted_list ();
+      grub_error (rc, "adding of distrusted binary/certificate hash 

failed");

grub-core/commands/appendedsig/appendedsig.c +7 -0
+    }
+
+  grub_free (hash_data);
+
+  return rc;
+}
+
 static grub_err_t
 appendedsig_init (grub_file_t io __attribute__ ((unused)), enum 

grub_file_type type,
void **context __attribute__ ((unused)), enum
grub_verify_flags *flags)

grub-core/commands/appendedsig/appendedsig.c +0 -2
@@ -842,8 +1008,6 @@ pseudo_read (struct grub_file *file, char *buf, 
 grub_size_t len)
 /* Filesystem descriptor.  */
 static struct grub_fs pseudo_fs = { .name = "pseudo", .fs_read = 
 pseudo_read };
 
-static grub_command_t cmd_verify, cmd_list, cmd_distrust, cmd_trust;
-
 /*

* Verify the trusted certificate against the certificate hashes from
platform keystore buffer's
* distrusted list.

grub-core/commands/appendedsig/appendedsig.c +0 -0
@@ -1135,6 +1299,10 @@ load_static_keys (const struct 

grub_module_header *header, const grub_bool_t is_
return rc;
}

grub-core/commands/appendedsig/appendedsig.c +2 -0
+static grub_extcmd_t cmd_distrusted_hash;
+static grub_command_t cmd_verify, cmd_trusted_list, cmd_trusted_cert, 

cmd_trusted_hash,

grub-core/commands/appendedsig/appendedsig.c +11 -5
+                      cmd_distrusted_list, cmd_distrusted_cert;
+
 GRUB_MOD_INIT (appendedsig)
 {
   int rc;
@@ -1196,17 +1364,31 @@ GRUB_MOD_INIT (appendedsig)
 
       grub_pks_free_keystore ();
     }
-
-  cmd_trust = grub_register_command ("trust_certificate", 
 grub_cmd_trust, N_("X509_CERTIFICATE"),
-                                     N_("Add X509_CERTIFICATE to 
 trusted certificates."));
-  cmd_list = grub_register_command ("list_certificates", 
 grub_cmd_list, 0,
-                                    N_("Show the list of trusted x509 
 certificates."));
+  cmd_trusted_cert = grub_register_command ("trusted_certificate", 
 grub_cmd_trusted_cert,
+                                            N_("X509_CERTIFICATE"),
+                                            N_("Add X509_CERTIFICATE 
 to trusted list."));
+  cmd_trusted_hash = grub_register_command ("trusted_signature", 
 grub_cmd_trusted_hash,
+                                            N_("BINARY HASH FILE"),
+                                            N_("Add trusted BINARY 
 HASH to trusted list."));
+  cmd_distrusted_cert = grub_register_command 
 ("distrusted_certificate", grub_cmd_distrusted_cert,
+                                               N_("CERT_NUMBER"),
+                                               N_("Remove CERT_NUMBER 

(as listed by list_trusted)"
+ " from trusted
list."));
+ cmd_distrusted_hash = grub_register_extcmd ("distrusted_signature", grub_cmd_distrusted_hash, 0,
+ N_("[-b|--binary-hash]
FILE [BINARY HASH FILE]\n"
+ "[-c|--cert-hash]
FILE [CERTFICATE HASH FILE]"),
+ N_("Add distrusted
CERTFICATE/BINARY HASH "
+ "to distrusted
list."),

grub-core/commands/appendedsig/appendedsig.c +2 -0
+			                                         options);
+  cmd_trusted_list = grub_register_command ("trusted_list", 

grub_cmd_trusted_list, 0,
+ N_("Show the list of
trusted x509 certificates and"
+ " trusted binary
hashes."));
+ cmd_distrusted_list = grub_register_command ("distrusted_list", grub_cmd_distrusted_list, 0,
+ N_("Show the list of
distrusted certificates and"
+ "
certificate/binary hashes"));
cmd_verify = grub_register_command ("verify_appended",
grub_cmd_verify_signature, N_("FILE"),
- N_("Verify FILE against the
trusted x509 certificates."));
- cmd_distrust = grub_register_command ("distrust_certificate", grub_cmd_distrust,

grub-core/commands/appendedsig/appendedsig.c +0 -2
-                                        N_("CERT_NUMBER"),
-                                        N_("Remove CERT_NUMBER (as 

listed by list_certificates)"
- " from trusted
certificates."));
+ N_("Verify FILE against the
trusted x509 certificates/"

grub-core/commands/appendedsig/appendedsig.c +1 -0
+                                         "trusted binary hashes."));
 
   grub_verifier_register (&grub_appendedsig_verifier);
   grub_dl_set_persistent (mod);
@@ -1218,10 +1400,12 @@ GRUB_MOD_FINI (appendedsig)
    * grub_dl_set_persistent should prevent this from actually 

running, but
* it does still run under emu.
*/

grub-core/commands/appendedsig/appendedsig.c +6 -5
-
   grub_verifier_unregister (&grub_appendedsig_verifier);
   grub_unregister_command (cmd_verify);
-  grub_unregister_command (cmd_list);
-  grub_unregister_command (cmd_trust);
-  grub_unregister_command (cmd_distrust);
+  grub_unregister_command (cmd_trusted_list);
+  grub_unregister_command (cmd_distrusted_list);
+  grub_unregister_command (cmd_trusted_cert);
+  grub_unregister_command (cmd_distrusted_cert);
+  grub_unregister_command (cmd_trusted_hash);
+  grub_unregister_extcmd (cmd_distrusted_hash);
 }
--

2.43.5

Quoted 4 lines
Quoted 4 lines

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

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

#43 lore raw

Re: [PATCH v2 20/21] appendedsig: The grub command's trusted and distrusted support

In reply to Sudhakar Kuppusamy
Quoted 8 lines · Sudhakar Kuppusamy

To support the following trusted and distrusted commands

1. trusted_list:
It will show the list of trusted certificates and binary hashes
2. distrusted_list:
It will show the list of distrusted certificates and binary/certificate hashes
3. trusted_certificate:
It will add the trusted certificate to the trusted list

There are a few bugs in grub_cmd_distrusted_cert().

grub-core/commands/appendedsig/appendedsig.c static enum

Quoted 22 lines

4. trusted_signature:
It will add the certificate/binary hash to the trusted list
5. distrusted_certificate:
It will remove the trusted certificate from trsuted list
6. distrusted_signature:
It will add the certificate/binary hash to the distrsuted list

Note:-
The addition/deletion of trusted certificates and binary hashes
are not allowed in grub command prompt while secure boot is enabled.

---
 grub-core/commands/appendedsig/appendedsig.c | 518 +++++++++++++------
 1 file changed, 351 insertions(+), 167 deletions(-)
grub-core/commands/appendedsig/appendedsig.c +0 -0
index 5631f0ab4..6f665aab2 100644
@@ -117,6 +117,36 @@ static enum

----->8-----

Quoted 24 lines
grub-core/commands/appendedsig/appendedsig.c +24 -0
+
+static grub_err_t
+grub_cmd_distrusted_cert (grub_command_t cmd __attribute__((unused)), int argc, char **args)
+{
+  grub_size_t cert_num = 0, i = 1;
+  struct x509_certificate *current_cert = db.keys;
+  struct x509_certificate *previous_cert = db.keys;
+
+  if (argc != 1)
+    {
+      grub_printf (N_("trusted certificate number is expected\n"
+                      "Example:\n\tdistrusted_certificate <CERT_NUMER>\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "removing of trusted certificate is not permitted!\n");
+      return grub_errno;
+    }
+
+  cert_num = grub_strtoul (args[0], NULL, 10);
+  if (cert_num < 1)

grub-core/commands/appendedsig/appendedsig.c grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize) · line 836

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c +10 -0
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("trusted certificate number should to begin with 1"));
+
+  if (cert_num > db.key_entries)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("trusted certificate number should not exceed %" PRIuGRUB_SIZE ""),
+                       db.key_entries);
+  else if (cert_num < db.key_entries)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("there is no certificate on the trusted list. so, not permitted"));

The 'else if' looks wrong since it's totally fine to have a cert number smaller than db.key_entries. Per the error message, it should be 'db.key_entries == 0'.

grub-core/commands/appendedsig/appendedsig.c static enum · line 152

Quoted 2 lines
grub-core/commands/appendedsig/appendedsig.c +2 -0
+
+  for (i = 1; i < db.key_entries; i++)

It has to be 'i <= db.key_entries'. Otherwise, the last certificate in the list is always ignored.

grub-core/commands/appendedsig/appendedsig.c grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize) · line 842

Quoted 5 lines
grub-core/commands/appendedsig/appendedsig.c +3 -1
+    {
+      if (cert_num == 1)
         {
-          grub_printf ("%02x:", cert->serial[i]);
+          previous_cert = current_cert->next;

Changing 'previous_cert' here won't affect 'db.keys', so the next user of 'db.keys' will get 'current_cert' instead of 'current_cert->next', and this leads to crash. I'd suggest to add:

	     db.keys = current_cert->next;
Quoted 8 lines
grub-core/commands/appendedsig/appendedsig.c +6 -1
+          break;
+        }
+      else if (cert_num == i)
+        {
+          previous_cert->next = current_cert->next;
+          break;
         }
-      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);

grub-core/commands/appendedsig/appendedsig.c grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize) · line 857

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c +5 -2
 
-      grub_printf ("\tCN: %s\n\n", cert->subject);
-      cert_num++;
+      previous_cert = current_cert;
+      current_cert = current_cert->next;
     }
 
+  certificate_release (current_cert);
+  grub_free (current_cert);
+

'db.key_entries' wasn't updated in the whole function.

     db.key_entries--;
Quoted 3 lines
   return GRUB_ERR_NONE;

}

Cheers,

Gary Lin

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

author
#44 lore raw

Re: [PATCH v2 20/21] appendedsig: The grub command's trusted and distrusted support

Hi Gary Lin,
Thank you so much for a review!. I wil fix the bug in the code mentioned by you.

Thanks,
Sudhakar Kuppusmay

Quoted 121 lines · Gary Lin
Quoted 10 lines · Sudhakar Kuppusamy

To support the following trusted and distrusted commands

1. trusted_list:
It will show the list of trusted certificates and binary
hashes
2. distrusted_list:
It will show the list of distrusted certificates and
binary/certificate hashes
3. trusted_certificate:
It will add the trusted certificate to the trusted list

There are a few bugs in grub_cmd_distrusted_cert().

grub-core/commands/appendedsig/appendedsig.c static enum

Quoted 23 lines

4. trusted_signature:
It will add the certificate/binary hash to the trusted list
5. distrusted_certificate:
It will remove the trusted certificate from trsuted list
6. distrusted_signature:
It will add the certificate/binary hash to the distrsuted list

Note:-
The addition/deletion of trusted certificates and binary hashes
are not allowed in grub command prompt while secure boot is enabled.

---
 grub-core/commands/appendedsig/appendedsig.c | 518 
+++++++++++++------
 1 file changed, 351 insertions(+), 167 deletions(-)
grub-core/commands/appendedsig/appendedsig.c +0 -0
index 5631f0ab4..6f665aab2 100644
@@ -117,6 +117,36 @@ static enum

----->8-----

Quoted 39 lines
grub-core/commands/appendedsig/appendedsig.c +34 -0
+
+static grub_err_t
+grub_cmd_distrusted_cert (grub_command_t cmd __attribute__((unused)), 
 int argc, char **args)
+{
+  grub_size_t cert_num = 0, i = 1;
+  struct x509_certificate *current_cert = db.keys;
+  struct x509_certificate *previous_cert = db.keys;
+
+  if (argc != 1)
+    {
+      grub_printf (N_("trusted certificate number is expected\n"
+                      "Example:\n\tdistrusted_certificate 
 <CERT_NUMER>\n"));
+      return GRUB_ERR_BAD_ARGUMENT;
+    }
+
+  if (check_sigs == check_sigs_forced)
+    {
+      grub_printf ("Warning: since secure boot is enabled, "
+                   "removing of trusted certificate is not 
 permitted!\n");
+      return grub_errno;
+    }
+
+  cert_num = grub_strtoul (args[0], NULL, 10);
+  if (cert_num < 1)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("trusted certificate number should to begin 
 with 1"));
+
+  if (cert_num > db.key_entries)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("trusted certificate number should not 
 exceed %" PRIuGRUB_SIZE ""),
+                       db.key_entries);
+  else if (cert_num < db.key_entries)
+    return grub_error (GRUB_ERR_BAD_ARGUMENT,
+                       N_("there is no certificate on the trusted 
Quoted 1 line

list. so, not permitted"));

The 'else if' looks wrong since it's totally fine to have a cert number smaller than db.key_entries. Per the error message, it should be 'db.key_entries == 0'.

grub-core/commands/appendedsig/appendedsig.c

Quoted 2 lines
grub-core/commands/appendedsig/appendedsig.c +2 -0
+
+  for (i = 1; i < db.key_entries; i++)

It has to be 'i <= db.key_entries'. Otherwise, the last certificate in the list is always ignored.

grub-core/commands/appendedsig/appendedsig.c grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize) · line 842

Quoted 5 lines
grub-core/commands/appendedsig/appendedsig.c +3 -1
+    {
+      if (cert_num == 1)
         {
-          grub_printf ("%02x:", cert->serial[i]);
+          previous_cert = current_cert->next;

Changing 'previous_cert' here won't affect 'db.keys', so the next user of 'db.keys' will get 'current_cert' instead of 'current_cert->next', and this leads to crash. I'd suggest to add:

	     db.keys = current_cert->next;
Quoted 8 lines
grub-core/commands/appendedsig/appendedsig.c +6 -1
+          break;
+        }
+      else if (cert_num == i)
+        {
+          previous_cert->next = current_cert->next;
+          break;
         }
-      grub_printf ("%02x\n", cert->serial[cert->serial_len - 1]);

grub-core/commands/appendedsig/appendedsig.c grub_verify_appended_signature (const grub_uint8_t *buf, grub_size_t bufsize) · line 857

Quoted 10 lines
grub-core/commands/appendedsig/appendedsig.c +5 -2
 
-      grub_printf ("\tCN: %s\n\n", cert->subject);
-      cert_num++;
+      previous_cert = current_cert;
+      current_cert = current_cert->next;
     }
 
+  certificate_release (current_cert);
+  grub_free (current_cert);
+

'db.key_entries' wasn't updated in the whole function.

     db.key_entries--;
Quoted 7 lines
Quoted 3 lines
   return GRUB_ERR_NONE;

}

Cheers,

Gary Lin

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

#45 lore raw

PATCH v2 21/21 appendedsig: documentation

In reply to Sudhakar Kuppusamy

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

---
 docs/grub.texi | 108 +++++++++++++++++++++++++++++++++++--------------
 1 file changed, 77 insertions(+), 31 deletions(-)
docs/grub.texi +77 -31
index 52e26c8fd..e0d6fe95e 100644
@@ -6437,7 +6437,9 @@ you forget a command, you can run the command @command{help}
 * date::                        Display or set current date and time
 * devicetree::                  Load a device tree blob
 * distrust::                    Remove a pubkey from trusted keys
-* distrust_certificate::        Remove a certificate from the list of trusted certificates
+* distrusted_certificate::      Remove a certificate from the trusted list
+* distrusted_list::             List distrusted certificates and binary/certificate hashes
+* distrusted_signature::        Add a binary hash to the distrusted list
 * drivemap::                    Map a drive to another
 * echo::                        Display a line of text
 * efitextmode::                 Set/Get text output mode resolution
@@ -6456,7 +6458,6 @@ you forget a command, you can run the command @command{help}
 * hexdump::                     Show raw contents of a file or memory
 * insmod::                      Insert a module
 * keystatus::                   Check key modifier status
-* list_certificates::           List trusted certificates
 * list_env::                    List variables in environment block
 * list_trusted::                List trusted public keys
 * load_env::                    Load variables from environment block
@@ -6497,7 +6498,9 @@ you forget a command, you can run the command @command{help}
 * tpm2_key_protector_clear::    Clear the TPM2 key protector
 * true::                        Do nothing, successfully
 * trust::                       Add public key to list of trusted keys
-* trust_certificate::           Add an x509 certificate to the list of trusted certificates
+* trusted_certificate::         Add an x509 certificate to the trusted list
+* trusted_list::                List trusted certificates and binary hashes
+* trusted_signature::           Add a binary hash to the trusted list.
 * unset::                       Unset an environment variable
 @comment * vbeinfo::                     List available video modes
 * verify_appended::             Verify appended digital signature
@@ -6845,15 +6848,15 @@ These keys are used to validate signatures when environment variable
 GPG-style digital signatures}, for more information.
 @end deffn
 
-@node distrust_certificate
-@subsection distrust_certificate
+@node distrusted_certificate
+@subsection distrusted_certificate
 
-@deffn Command distrust_certificate cert_number
+@deffn Command distrusted_certificate cert_number
 Remove the x509 certificate numbered @var{cert_number} from GRUB's keyring of
 trusted x509 certificates for verifying appended signatures.
 
 @var{cert_number} is the certificate number as listed by
-@command{list_certificates} (@pxref{list_certificates}).
+@command{trusted_list} (@pxref{trusted_list}).
 
 These certificates are used to validate appended signatures when environment
 variable @code{check_appended_signatures} is set to @code{enforce}
@@ -6862,6 +6865,28 @@ variable @code{check_appended_signatures} is set to @code{enforce}
 information.
 @end deffn
 
+@node distrusted_list
+@subsection distrusted_list
+
+@deffn Command distrusted_list
+List all the distrusted x509 certificates and binary/certificate hashes.
+The output is a numbered list of certificates and binary/certificate hashes,
+showing the certificate's serial number and Common Name.
+@end deffn
+
+@node distrusted_signature
+@subsection distrusted_signature
+
+@deffn Command distrusted_signature
+Read a binary hash from the file @var{binary hash file}
+and add it to GRUB's internal distrusted list. These hash are used to
+restrict validation of linux image integrity using trusted list if appended
+signatures validation failed when the environment variable
+@code{check_appended_signatures} is set to @code{enforce}.
+
+See @xref{Using appended signatures} for more information.
+@end deffn
+
 @node drivemap
 @subsection drivemap
 
@@ -7255,20 +7280,6 @@ without any options, the @command{keystatus} command returns true if and
 only if checking key modifier status is supported.
 @end deffn
 
-@node list_certificates
-@subsection list_certificates
-
-@deffn Command list_certificates
-List all x509 certificates trusted by GRUB for validating appended signatures.
-The output is a numbered list of certificates, showing the certificate's serial
-number and Common Name.
-
-The certificate number can be used as an argument to
-@command{distrust_certificate} (@pxref{distrust_certificate}).
-
-See @xref{Using appended signatures} for more information.
-@end deffn
-
 @node list_env
 @subsection list_env
 
@@ -8171,17 +8182,17 @@ information.
 @end deffn
 
 
-@node trust_certificate
-@subsection trust_certificate
+@node trusted_certificate
+@subsection trusted_certificate
 
-@deffn Command trust_certificate x509_certificate
+@deffn Command trusted_certificate x509_certificate
 Read a DER-formatted x509 certificate from the file @var{x509_certificate}
 and add it to GRUB's internal list of trusted x509 certificates. These
 certificates are used to validate appended signatures when the environment
 variable @code{check_appended_signatures} is set to @code{enforce}.
 
 Note that if @code{check_appended_signatures} is set to @code{enforce}
-when @command{trust_certificate} is executed, then @var{x509_certificate}
+when @command{trusted_certificate} is executed, then @var{x509_certificate}
 must itself bear an appended signature. (It is not sufficient that
 @var{x509_certificate} be signed by a trusted certificate according to the
 x509 rules: GRUB does not include support for validating signatures within x509
@@ -8190,6 +8201,33 @@ certificates themselves.)
 See @xref{Using appended signatures} for more information.
 @end deffn
 
+@node trusted_list
+@subsection trusted_list
+
+@deffn Command trusted_list
+List all x509 certificates and binary hases trusted by GRUB for validating
+appended signatures. The output is a numbered list of certificates and binary
+hashes, showing the certificate's serial number and Common Name.
+
+The certificate number can be used as an argument to
+@command{distrusted_certificate} (@pxref{distrusted_certificate}).
+
+See @xref{Using appended signatures} for more information.
+@end deffn
+
+@node trusted_signature
+@subsection trusted_signature
+
+@deffn Command trust_signature
+Read a binary hash from the file @var{binary hash file}
+and add it to GRUB's internal trusted list. These binary hash are used to
+validate linux image integrity if appended signatures validation failed
+when the environment variable @code{check_appended_signatures} is set
+to @code{enforce}.
+
+See @xref{Using appended signatures} for more information.
+@end deffn
+
 @node unset
 @subsection unset
 
@@ -8213,8 +8251,8 @@ only on PC BIOS platforms.
 
 @deffn Command verify_appended file
 Verifies an appended signature on @var{file} against the trusted certificates
-known to GRUB (See @pxref{list_certificates}, @pxref{trust_certificate}, and
-@pxref{distrust_certificate}).
+known to GRUB (See @pxref{trusted_list}, @pxref{trusted_certificate}, and
+@pxref{distrusted_certificate}).
 Exit code @code{$?} is set to 0 if the signature validates
 successfully.  If validation fails, it is set to a non-zero value.
 
@@ -8884,10 +8922,18 @@ To enable appended signature verification, load the appendedsig module and an
 x509 certificate for verification. Building the appendedsig module into the
 core grub image is recommended.
 
-Certificates can be managed at boot time using the @pxref{trust_certificate},
-@pxref{distrust_certificate} and @pxref{list_certificates} commands.
-Certificates can also be built in to the core image using the @code{--x509}
-parameter to @command{grub-install} or @command{grub-mkimage}.
+For static key, Certificates will be built in to the core image using
+the @code{--x509} parameter to @command{grub-install} or @command{grub-mkimage}.
+it can allow to list the trusted certificates and binary hashes at boot time using
+@pxref{trusted_list} and list distrusted certificates and binary/certificate hashes
+at boot time using @pxref{distrusted_list} commands.
+
+For dynamic key, loads the signature database (DB) and forbidden
+signature database (DBX) from platform keystore (PKS) and it can allow to list
+the trusted certificates and binary hashes at boot time using @pxref{trusted_list}
+and list distrusted certificates and binary/certificate hashes at boot time using
+@pxref{distrusted_list} commands.
+
 A file can be explicitly verified using the @pxref{verify_appended} command.
 
 Only signatures made with the SHA-256 or SHA-512 hash algorithm are supported,
Signature · 7 lines
2.43.5


_______________________________________________
Grub-devel mailing list
[email protected]
https://lists.gnu.org/mailman/listinfo/grub-devel
#46 lore raw
In reply to Sudhakar Kuppusamy

Red Hat has been carrying patches 1-13 of this set for like four years now. We would be willing to test the remainder, with the hope that at least those first 13 will get accepted sometime soon. Is that reasonable?

thanks,
marta

Quoted 243 lines · Sudhakar Kuppusamy

This patch set contains v2 of the consolidated version of the patch sets for secure boot using appended signatures on powerpc, rebased on top of git HEAD.

The v1 series is at
https://lists.gnu.org/archive/html/grub-devel/2024-12/msg00071.html

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.

Thanks to Stefan Berger, Avnish Chouhan, Michal Suchanek, and Vladimir Serbinenko for providing review comments on v1.

I've pushed this all to
https://github.com/SudhakarKuppusamy1/grub/tree/appendedsig-2.13

[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
powerpc_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                                |  283 +++-
 grub-core/Makefile.am                         |    2 +
 grub-core/Makefile.core.def                   |   31 +
 grub-core/commands/appendedsig/appendedsig.c  | 1411 +++++++++++++++++
 grub-core/commands/appendedsig/appendedsig.h  |  110 ++
 grub-core/commands/appendedsig/asn1util.c     |   98 ++
 .../commands/appendedsig/gnutls_asn1_tab.c    |  121 ++
 grub-core/commands/appendedsig/pkcs7.c        |  460 ++++++
 .../commands/appendedsig/pkix_asn1_tab.c      |  484 ++++++
 grub-core/commands/appendedsig/x509.c         |  953 +++++++++++
 grub-core/commands/pgp.c                      |   34 +-
 grub-core/kern/file.c                         |   34 +
 grub-core/kern/ieee1275/init.c                |   46 +
 grub-core/kern/powerpc/ieee1275/ieee1275.c    |  140 ++
 .../kern/powerpc/ieee1275/platform_keystore.c |  346 ++++
 grub-core/lib/crypto.c                        |    4 +
 grub-core/lib/pkcs1_v15.c                     |   59 +
 grub-core/term/tparm.c                        |    1 -
 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                           |    3 +
 include/grub/kernel.h                         |    2 +
 include/grub/lockdown.h                       |    3 +-
 include/grub/pkcs1_v15.h                      |   27 +
 include/grub/powerpc/ieee1275/ieee1275.h      |   14 +
 .../grub/powerpc/ieee1275/platform_keystore.h |  226 +++
 include/grub/types.h                          |   11 +
 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 +-
 35 files changed, 6229 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/powerpc/ieee1275/ieee1275.c
 create mode 100644 grub-core/kern/powerpc/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/powerpc/ieee1275/platform_keystore.h
Quoted 4 lines

--
2.43.5

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

author
#47 lore raw

Hi Marta,

Thanks Martha, yes that would be very helpful and I appreciate your consideration for that. Yes the patch-set is getting reviewed actively so I am also hopeful that these would be upstreamed soon.

Thanks,
Sudhakar Kuppusamy

Quoted 301 lines · Marta Lewandowska

Red Hat has been carrying patches 1-13 of this set for like four years now. We would be willing to test the remainder, with the hope that at least those first 13 will get accepted sometime soon. Is that reasonable? thanks, marta On Wed, Mar

Red Hat has been carrying patches 1-13 of this set for like four years now. We would be willing to test the remainder, with the hope that at least those first 13 will get accepted sometime soon. Is that reasonable?

thanks,
marta

Quoted 183 lines · Sudhakar Kuppusamy

This patch set contains v2 of the consolidated version of the patch sets for secure boot using appended signatures on powerpc, rebased on top of git HEAD.

The v1 series is at
https://lists.gnu.org/archive/html/grub-devel/2024-12/msg00071.html

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.

Quoted 10 lines

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

Thanks to Stefan Berger, Avnish Chouhan, Michal Suchanek, and Vladimir Serbinenko for providing review comments on v1.

I've pushed this all to
https://github.com/SudhakarKuppusamy1/grub/tree/appendedsig-2.13

[1]https://www.ibm.com/docs/en/linux-on-systems?topic=servers-guest-secure-boot-static-keys

Quoted 1 line

[2]https://community.ibm.com/community/user/power/blogs/chris-engel1/2020/11/20/powervm-introduces-the-platform-keystore

Quoted 88 lines

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
powerpc_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                                |  283 +++-
grub-core/Makefile.am                         |    2 +
grub-core/Makefile.core.def                   |   31 +
grub-core/commands/appendedsig/appendedsig.c  | 1411
+++++++++++++++++
grub-core/commands/appendedsig/appendedsig.h  |  110 ++
grub-core/commands/appendedsig/asn1util.c     |   98 ++
.../commands/appendedsig/gnutls_asn1_tab.c    |  121 ++
grub-core/commands/appendedsig/pkcs7.c        |  460 ++++++
.../commands/appendedsig/pkix_asn1_tab.c      |  484 ++++++
grub-core/commands/appendedsig/x509.c         |  953 +++++++++++
grub-core/commands/pgp.c                      |   34 +-
grub-core/kern/file.c                         |   34 +
grub-core/kern/ieee1275/init.c                |   46 +
grub-core/kern/powerpc/ieee1275/ieee1275.c    |  140 ++
.../kern/powerpc/ieee1275/platform_keystore.c |  346 ++++
grub-core/lib/crypto.c                        |    4 +
grub-core/lib/pkcs1_v15.c                     |   59 +
grub-core/term/tparm.c                        |    1 -
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                           |    3 +
include/grub/kernel.h                         |    2 +
include/grub/lockdown.h                       |    3 +-
include/grub/pkcs1_v15.h                      |   27 +
include/grub/powerpc/ieee1275/ieee1275.h      |   14 +
.../grub/powerpc/ieee1275/platform_keystore.h |  226 +++
include/grub/types.h                          |   11 +
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 +-
35 files changed, 6229 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/powerpc/ieee1275/ieee1275.c create mode 100644 grub-core/kern/powerpc/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/powerpc/ieee1275/platform_keystore.h

Quoted 7 lines
Quoted 2 lines

--
2.43.5

Links:
------
[1] https://us-phishalarm-ewt.proofpoint.com/EWT/v1/AdhS1Rd-!-XFVHHVa3OJT9VR5Za8gPdRF0zC5n_bZ0RUCAt27UE3C-XDLgiqLMbD2NUoiY_q9qtOF9O7ECQBRONUTavAThgVVsAFD2RS6-fQgO_NzvFzsuKo8HoOFcd8cU0ZJfQ$

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