nalika / rpms / grub2

Forked from rpms/grub2 2 years ago
Clone

Blame SOURCES/0193-appended-signatures-parse-PKCS-7-signedData-and-X.50.patch

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