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

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