pki: Strictly parse MTCProof extensions

Add the missing check that the MTCProof's extensions field is a
well-formed list of MTCLogEntryExtension structures in strictly
ascending order by type, as required by section 5.2.1. This matches the
check added to crypto/x509 in
https://boringssl-review.googlesource.com/c/boringssl/+/104509. No
extension types are defined, so well-formed extensions are otherwise
still ignored.

Fixed: 589451105
Change-Id: If0e3be66229dc06c4a455293862511776a6a6964
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/106448
Presubmit-BoringSSL-Verified: boringssl-scoped@luci-project-accounts.iam.gserviceaccount.com <boringssl-scoped@luci-project-accounts.iam.gserviceaccount.com>
Auto-Submit: Lily Chen <chlily@google.com>
Reviewed-by: Matt Mueller <mattm@google.com>
Commit-Queue: Matt Mueller <mattm@google.com>
diff --git a/pki/path_builder_unittest.cc b/pki/path_builder_unittest.cc
index 742fdad..7146b26 100644
--- a/pki/path_builder_unittest.cc
+++ b/pki/path_builder_unittest.cc
@@ -3099,6 +3099,52 @@
       << path.errors.ToDebugString(path.certs);
 }
 
+TEST_F(PathBuilderMTCTest, EntryExtensions) {
+  std::shared_ptr<const ParsedCertificate> ca_cert =
+      ReadCryptoX509MTCTestCert("ca_cert.pem");
+  ASSERT_TRUE(ca_cert);
+  std::optional<MTCAnchor> anchor =
+      MTCAnchor::Create(ca_cert, CertificateTrust::ForTrustAnchor());
+  ASSERT_TRUE(anchor);
+  TrustStoreInMemory in_memory;
+  ASSERT_TRUE(in_memory.AddMTCTrustAnchor(
+      std::make_shared<MTCAnchor>(*std::move(anchor))));
+
+  // Well-formed extensions of unrecognized types are ignored.
+  {
+    std::shared_ptr<const ParsedCertificate> leaf =
+        ReadCryptoX509MTCTestCert("cert_34_0.pem");
+    ASSERT_TRUE(leaf);
+    MtcCosignersPathBuilderDelegate delegate;
+    EXPECT_CALL(delegate, IsMTCCosignatureVerificationResultAcceptable(
+                              Ref(*ca_cert), ElementsAre()))
+        .WillOnce(Return(true));
+    CertPathBuilder::Result result =
+        RunPathBuilder(leaf, &in_memory, nullptr, &delegate);
+    EXPECT_TRUE(result.HasValidPath());
+  }
+
+  for (const char *file_name : {"cert_35_0.pem" /* truncated extensions */,
+                                "cert_36_0.pem" /* duplicate extensions */,
+                                "cert_37_0.pem" /* misordered extensions */}) {
+    SCOPED_TRACE(file_name);
+    std::shared_ptr<const ParsedCertificate> leaf =
+        ReadCryptoX509MTCTestCert(file_name);
+    ASSERT_TRUE(leaf);
+    StrictMock<MtcCosignersPathBuilderDelegate> delegate;
+    CertPathBuilder::Result result =
+        RunPathBuilder(leaf, &in_memory, nullptr, &delegate);
+    EXPECT_FALSE(result.HasValidPath());
+    const auto &path = *result.GetBestPathPossiblyInvalid();
+    ASSERT_EQ(2u, path.certs.size());
+    EXPECT_EQ(leaf, path.certs[0]);
+    EXPECT_EQ(ca_cert, path.certs[1]);
+    EXPECT_TRUE(path.errors.GetErrorsForCert(0)->ContainsError(
+        cert_errors::kVerifySignedDataFailed))
+        << path.errors.ToDebugString(path.certs);
+  }
+}
+
 TEST(PathBuilderPrioritizationTest, DatePrioritization) {
   std::string test_dir =
       "testdata/path_builder_unittest/validity_date_prioritization/";
diff --git a/pki/verify_certificate_chain.cc b/pki/verify_certificate_chain.cc
index 7b3b762..8eae0c9 100644
--- a/pki/verify_certificate_chain.cc
+++ b/pki/verify_certificate_chain.cc
@@ -16,6 +16,7 @@
 
 #include <algorithm>
 #include <cassert>
+#include <optional>
 #include <string>
 
 #include <inttypes.h>
@@ -1223,6 +1224,26 @@
                           der::BitString(signature, 0), key_bytes, cache);
 }
 
+// CheckMTCLogEntryExtensions returns whether `extensions` is a well-formed list
+// of MTCLogEntryExtension structures, sorted in strictly ascending order by
+// extension type (see draft-ietf-plants-merkle-tree-certs section 5.2.1).
+static bool CheckMTCLogEntryExtensions(CBS extensions) {
+  std::optional<uint16_t> prev_type;
+  while (CBS_len(&extensions) > 0) {
+    uint16_t type;
+    CBS data;
+    if (!CBS_get_u16(&extensions, &type) ||
+        !CBS_get_u16_length_prefixed(&extensions, &data)) {
+      return false;
+    }
+    if (prev_type.has_value() && *prev_type >= type) {
+      return false;
+    }
+    prev_type = type;
+  }
+  return true;
+}
+
 enum class VerifyMTCResult {
   // Failed for any reason not covered by the more specific cases.
   kFailed,
@@ -1267,6 +1288,9 @@
       CBS_len(&mtc_proof) != 0) {
     return VerifyMTCResult::kFailed;
   }
+  if (!CheckMTCLogEntryExtensions(extensions)) {
+    return VerifyMTCResult::kFailed;
+  }
 
   // Step 3: Let serial be the certificate's serial number. If serial is
   // negative or greater than 2^64-1, abort this process and fail verification.