crypto/x509: Make GENERAL_NAME_cmp a total order.

GENERAL_NAME_cmp returned -1 in both directions when the name types
differed, as did ASN1_TYPE_cmp (used for otherName values), and
edipartyname_cmp when the nameAssigner fields differed. This made them
unsuitable for sorting. Instead, order by type first, then by the
type-specific contents, with an absent nameAssigner sorting first.
Which non-NULL inputs compare equal is unchanged.

ASN1_TYPE_cmp now sorts NULL before non-NULL values, so two NULLs
compare equal. This lets X509_ALGOR_cmp drop its special case and also
become a total order, with an absent parameter sorting first. Which
inputs compare equal is unchanged.

The one remaining exception is X509_NAME_cmp's -2 return when a name
cannot be serialized, which cannot happen for unmodified parsed names.

While I'm here, remove NULL checks in GENERAL_NAME_cmp and othername_cmp
that cannot be hit.

Update-Note: ASN1_TYPE_cmp and X509_ALGOR_cmp now return a consistent
ordering. Callers that only compare the result against zero are
unaffected, except that ASN1_TYPE_cmp(NULL, NULL) now returns zero
instead of -1. Callers that checked for a specific non-zero value, such
as -1, should compare against zero instead.

Bug: 565047760
Change-Id: I7d8f98c25fe967afbe6ec518b4012a52b1c5e3ba
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/104768
Reviewed-by: David Benjamin <davidben@google.com>
Commit-Queue: Moreno Ambrosin <ambrosin@google.com>
diff --git a/crypto/asn1/a_type.cc b/crypto/asn1/a_type.cc
index 35e0534..9a8d762 100644
--- a/crypto/asn1/a_type.cc
+++ b/crypto/asn1/a_type.cc
@@ -147,24 +147,23 @@
   return 1;
 }
 
-// Returns 0 if they are equal, != 0 otherwise.
 int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b) {
-  int result = -1;
+  if (a == nullptr || b == nullptr) {
+    // NULL sorts before any non-NULL value. Two NULLs are equal.
+    return (a != nullptr) - (b != nullptr);
+  }
 
-  if (!a || !b || a->type != b->type) {
-    return -1;
+  if (a->type != b->type) {
+    return a->type < b->type ? -1 : 1;
   }
 
   switch (a->type) {
     case V_ASN1_OBJECT:
-      result = OBJ_cmp(a->value.object, b->value.object);
-      break;
+      return OBJ_cmp(a->value.object, b->value.object);
     case V_ASN1_NULL:
-      result = 0;  // They do not have content.
-      break;
+      return 0;  // They do not have content.
     case V_ASN1_BOOLEAN:
-      result = a->value.boolean - b->value.boolean;
-      break;
+      return a->value.boolean - b->value.boolean;
     case V_ASN1_INTEGER:
     case V_ASN1_ENUMERATED:
     case V_ASN1_BIT_STRING:
@@ -186,11 +185,8 @@
     case V_ASN1_UTF8STRING:
     case V_ASN1_OTHER:
     default:
-      result = ASN1_STRING_cmp(a->value.asn1_string, b->value.asn1_string);
-      break;
+      return ASN1_STRING_cmp(a->value.asn1_string, b->value.asn1_string);
   }
-
-  return result;
 }
 
 int bssl::asn1_parse_any(CBS *cbs, ASN1_TYPE *out) {
diff --git a/crypto/asn1/asn1_test.cc b/crypto/asn1/asn1_test.cc
index aa1e3bd..e746622 100644
--- a/crypto/asn1/asn1_test.cc
+++ b/crypto/asn1/asn1_test.cc
@@ -3503,4 +3503,97 @@
 
 #endif  // !WINDOWS || !SHARED_LIBRARY
 
+TEST(ASN1Test, TypeCmpNull) {
+  UniquePtr<ASN1_TYPE> null_value(ASN1_TYPE_new());
+  ASSERT_TRUE(null_value);
+  ASN1_TYPE_set(null_value.get(), V_ASN1_NULL, nullptr);
+
+  EXPECT_EQ(ASN1_TYPE_cmp(nullptr, nullptr), 0);
+  EXPECT_LT(ASN1_TYPE_cmp(nullptr, null_value.get()), 0);
+  EXPECT_GT(ASN1_TYPE_cmp(null_value.get(), nullptr), 0);
+  EXPECT_EQ(ASN1_TYPE_cmp(null_value.get(), null_value.get()), 0);
+}
+
+namespace {
+
+// ExpectTotalOrder checks that `cmp` is a three-way comparison consistent with
+// a total order. `a` and `b` must hold the same pairwise-distinct values,
+// parsed separately, so equality is not checked by pointer.
+template <typename T, typename Cmp>
+void ExpectTotalOrder(const std::vector<T> &a, const std::vector<T> &b,
+                      Cmp cmp) {
+  ASSERT_EQ(a.size(), b.size());
+  auto sign = [](int v) { return (v > 0) - (v < 0); };
+  for (size_t i = 0; i < a.size(); i++) {
+    SCOPED_TRACE(i);
+    for (size_t j = 0; j < a.size(); j++) {
+      SCOPED_TRACE(j);
+      int ij = cmp(a[i], b[j]);
+      if (i == j) {
+        EXPECT_EQ(ij, 0);
+      } else {
+        EXPECT_NE(ij, 0);
+      }
+      EXPECT_EQ(sign(ij), -sign(cmp(b[j], a[i])));
+      if (ij >= 0) {
+        continue;
+      }
+      for (size_t k = 0; k < a.size(); k++) {
+        if (cmp(b[j], a[k]) < 0) {
+          SCOPED_TRACE(k);
+          EXPECT_LT(cmp(a[i], b[k]), 0);
+        }
+      }
+    }
+  }
+}
+
+}  // namespace
+
+TEST(ASN1Test, TypeCmpTotalOrder) {
+  const std::vector<uint8_t> kValues[] = {
+      {0x05, 0x00},                    // NULL
+      {0x01, 0x01, 0x00},              // BOOLEAN { FALSE }
+      {0x01, 0x01, 0xff},              // BOOLEAN { TRUE }
+      {0x02, 0x01, 0x01},              // INTEGER { 1 }
+      {0x02, 0x01, 0xff},              // INTEGER { -1 }
+      {0x0a, 0x01, 0x01},              // ENUMERATED { 1 }
+      {0x03, 0x01, 0x00},              // BIT STRING {}
+      {0x03, 0x02, 0x01, 0x80},        // BIT STRING { `1000000` } (7 bits)
+      {0x03, 0x02, 0x07, 0x80},        // BIT STRING { `1` } (1 bit)
+      {0x04, 0x01, 0x61},              // OCTET STRING { "a" }
+      {0x04, 0x01, 0x62},              // OCTET STRING { "b" }
+      {0x06, 0x03, 0x2b, 0x06, 0x01},  // OBJECT_IDENTIFIER { 1.3.6.1 }
+      {0x06, 0x03, 0x2b, 0x06, 0x02},  // OBJECT_IDENTIFIER { 1.3.6.2 }
+      {0x0c, 0x00},                    // UTF8String { "" }
+      {0x0c, 0x01, 0x61},              // UTF8String { "a" }
+      {0x0c, 0x02, 0x61, 0x61},        // UTF8String { "aa" }
+      {0x13, 0x01, 0x61},              // PrintableString { "a" }
+      {0x16, 0x01, 0x61},              // IA5String { "a" }
+      {0x1e, 0x02, 0x00, 0x61},        // BMPString { "a" }
+      {0x30, 0x00},                    // SEQUENCE {}
+      {0x30, 0x02, 0x05, 0x00},        // SEQUENCE { NULL }
+      {0x31, 0x00},                    // SET {}
+      {0x60, 0x00},                    // [APPLICATION 0] {}
+      {0x80, 0x01, 0x61},              // [0 PRIMITIVE] { "a" }
+  };
+
+  auto parse_all = [&](std::vector<UniquePtr<ASN1_TYPE>> *out) {
+    for (const auto &der : kValues) {
+      SCOPED_TRACE(Bytes(der));
+      const uint8_t *ptr = der.data();
+      UniquePtr<ASN1_TYPE> value(d2i_ASN1_TYPE(nullptr, &ptr, der.size()));
+      ASSERT_TRUE(value);
+      ASSERT_EQ(ptr, der.data() + der.size());
+      out->push_back(std::move(value));
+    }
+  };
+  std::vector<UniquePtr<ASN1_TYPE>> a, b;
+  ASSERT_NO_FATAL_FAILURE(parse_all(&a));
+  ASSERT_NO_FATAL_FAILURE(parse_all(&b));
+  ExpectTotalOrder(a, b, [](const auto &x, const auto &y) {
+    return ASN1_TYPE_cmp(x.get(), y.get());
+  });
+}
+
 BSSL_NAMESPACE_END
diff --git a/crypto/x509/internal.h b/crypto/x509/internal.h
index ab44a62..eb35b9a 100644
--- a/crypto/x509/internal.h
+++ b/crypto/x509/internal.h
@@ -597,9 +597,12 @@
   ERR_add_error_data(6, "section:", (val)->section, ",name:", (val)->name, \
                      ",value:", (val)->value);
 
-// GENERAL_NAME_cmp returns zero if `a` and `b` are equal and a non-zero
-// value otherwise. Note this function does not provide a comparison suitable
-// for sorting.
+// GENERAL_NAME_cmp compares `a` and `b`. It returns zero if they are equal, and
+// a negative or positive value if `a` sorts before or after `b`, respectively.
+// Names are ordered first by type, then by type-specific contents. The order
+// is arbitrary but suitable for sorting, with one exception: if a directoryName
+// cannot be serialized, `X509_NAME_cmp`, and thus this function, returns -2.
+// This cannot happen for parsed names that have not since been modified.
 int GENERAL_NAME_cmp(const GENERAL_NAME *a, const GENERAL_NAME *b);
 
 // X509_VERIFY_PARAM_lookup returns a pre-defined `X509_VERIFY_PARAM` named by
diff --git a/crypto/x509/v3_genn.cc b/crypto/x509/v3_genn.cc
index ac839d5..1f0c9de 100644
--- a/crypto/x509/v3_genn.cc
+++ b/crypto/x509/v3_genn.cc
@@ -77,15 +77,16 @@
 namespace {
 
 int edipartyname_cmp(const EDIPARTYNAME *a, const EDIPARTYNAME *b) {
-  // nameAssigner is optional and may be NULL.
-  if (a->nameAssigner == nullptr) {
-    if (b->nameAssigner != nullptr) {
-      return -1;
+  // nameAssigner is optional and may be NULL. An absent nameAssigner sorts
+  // before a present one.
+  if (a->nameAssigner == nullptr || b->nameAssigner == nullptr) {
+    if (a->nameAssigner != b->nameAssigner) {
+      return a->nameAssigner == nullptr ? -1 : 1;
     }
   } else {
-    if (b->nameAssigner == nullptr ||
-        ASN1_STRING_cmp(a->nameAssigner, b->nameAssigner) != 0) {
-      return -1;
+    int ret = ASN1_STRING_cmp(a->nameAssigner, b->nameAssigner);
+    if (ret != 0) {
+      return ret;
     }
   }
 
@@ -93,28 +94,21 @@
   return ASN1_STRING_cmp(a->partyName, b->partyName);
 }
 
-// Returns 0 if they are equal, != 0 otherwise.
+// a and b are guaranteed to be non-NULL.
 int othername_cmp(const OTHERNAME *a, const OTHERNAME *b) {
-  int result = -1;
-
-  if (!a || !b) {
-    return -1;
-  }
   // Check their type first.
-  if ((result = OBJ_cmp(a->type_id, b->type_id)) != 0) {
-    return result;
+  int ret = OBJ_cmp(a->type_id, b->type_id);
+  if (ret != 0) {
+    return ret;
   }
-  // Check the value.
-  result = ASN1_TYPE_cmp(a->value, b->value);
-  return result;
+  return ASN1_TYPE_cmp(a->value, b->value);
 }
 
 }  // namespace
 
-// Returns 0 if they are equal, != 0 otherwise.
 int bssl::GENERAL_NAME_cmp(const GENERAL_NAME *a, const GENERAL_NAME *b) {
-  if (!a || !b || a->type != b->type) {
-    return -1;
+  if (a->type != b->type) {
+    return a->type < b->type ? -1 : 1;
   }
 
   switch (a->type) {
@@ -142,7 +136,8 @@
       return OBJ_cmp(a->d.rid, b->d.rid);
   }
 
-  return -1;
+  // Unreachable: `type` is always one of the CHOICE arms above.
+  abort();
 }
 
 void GENERAL_NAME_set0_value(GENERAL_NAME *a, int type, void *value) {
diff --git a/crypto/x509/x509_test.cc b/crypto/x509/x509_test.cc
index e2e669d..b3280fe 100644
--- a/crypto/x509/x509_test.cc
+++ b/crypto/x509/x509_test.cc
@@ -5061,6 +5061,42 @@
       ErrorEquals(ERR_get_error(), ERR_LIB_X509, X509_R_INVALID_PARAMETER));
 }
 
+namespace {
+
+// ExpectTotalOrder checks that `cmp` is a three-way comparison consistent with
+// a total order. `a` and `b` must hold the same pairwise-distinct values,
+// parsed separately, so equality is not checked by pointer.
+template <typename T, typename Cmp>
+void ExpectTotalOrder(const std::vector<T> &a, const std::vector<T> &b,
+                      Cmp cmp) {
+  ASSERT_EQ(a.size(), b.size());
+  auto sign = [](int v) { return (v > 0) - (v < 0); };
+  for (size_t i = 0; i < a.size(); i++) {
+    SCOPED_TRACE(i);
+    for (size_t j = 0; j < a.size(); j++) {
+      SCOPED_TRACE(j);
+      int ij = cmp(a[i], b[j]);
+      if (i == j) {
+        EXPECT_EQ(ij, 0);
+      } else {
+        EXPECT_NE(ij, 0);
+      }
+      EXPECT_EQ(sign(ij), -sign(cmp(b[j], a[i])));
+      if (ij >= 0) {
+        continue;
+      }
+      for (size_t k = 0; k < a.size(); k++) {
+        if (cmp(b[j], a[k]) < 0) {
+          SCOPED_TRACE(k);
+          EXPECT_LT(cmp(a[i], b[k]), 0);
+        }
+      }
+    }
+  }
+}
+
+}  // namespace
+
 #if !defined(BORINGSSL_SHARED_LIBRARY)
 TEST(X509Test, GeneralName) {
   const std::vector<uint8_t> kNames[] = {
@@ -5249,9 +5285,62 @@
       }
     }
   }
+
+  auto fill_names = [&](std::vector<UniquePtr<GENERAL_NAME>> &names) {
+    for (const auto &der : kNames) {
+      const uint8_t *ptr = der.data();
+      names.emplace_back(d2i_GENERAL_NAME(nullptr, &ptr, der.size()));
+      ASSERT_TRUE(names.back());
+    }
+  };
+  std::vector<UniquePtr<GENERAL_NAME>> a, b;
+  ASSERT_NO_FATAL_FAILURE(fill_names(a));
+  ASSERT_NO_FATAL_FAILURE(fill_names(b));
+  ExpectTotalOrder(a, b, [](const auto &x, const auto &y) {
+    return GENERAL_NAME_cmp(x.get(), y.get());
+  });
 }
+
 #endif  // !BORINGSSL_SHARED_LIBRARY
 
+TEST(X509Test, AlgorCmpTotalOrder) {
+  const std::vector<uint8_t> kAlgors[] = {
+      // SEQUENCE { sha256WithRSAEncryption }
+      {0x30, 0x0b, 0x06, 0x09, OBJ_ENC_sha256WithRSAEncryption},
+      // SEQUENCE { sha256WithRSAEncryption, NULL }
+      {0x30, 0x0d, 0x06, 0x09, OBJ_ENC_sha256WithRSAEncryption, 0x05, 0x00},
+      // SEQUENCE { sha256WithRSAEncryption, OCTET STRING {} }
+      {0x30, 0x0d, 0x06, 0x09, OBJ_ENC_sha256WithRSAEncryption, 0x04, 0x00},
+      // SEQUENCE { sha384WithRSAEncryption, NULL }
+      {0x30, 0x0d, 0x06, 0x09, OBJ_ENC_sha384WithRSAEncryption, 0x05, 0x00},
+      // SEQUENCE { id-ecPublicKey, prime256v1 }
+      {0x30, 0x13, 0x06, 0x07, OBJ_ENC_X9_62_id_ecPublicKey, 0x06, 0x08,
+       OBJ_ENC_X9_62_prime256v1},
+      // SEQUENCE { id-ecPublicKey, secp384r1 }
+      {0x30, 0x10, 0x06, 0x07, OBJ_ENC_X9_62_id_ecPublicKey, 0x06, 0x05,
+       OBJ_ENC_secp384r1},
+      // SEQUENCE { ecdsa-with-SHA256 }
+      {0x30, 0x0a, 0x06, 0x08, OBJ_ENC_ecdsa_with_SHA256},
+  };
+
+  auto parse_all = [&](std::vector<UniquePtr<X509_ALGOR>> &out) {
+    for (const auto &der : kAlgors) {
+      SCOPED_TRACE(Bytes(der));
+      const uint8_t *ptr = der.data();
+      UniquePtr<X509_ALGOR> algor(d2i_X509_ALGOR(nullptr, &ptr, der.size()));
+      ASSERT_TRUE(algor);
+      ASSERT_EQ(ptr, der.data() + der.size());
+      out.push_back(std::move(algor));
+    }
+  };
+  std::vector<UniquePtr<X509_ALGOR>> a, b;
+  ASSERT_NO_FATAL_FAILURE(parse_all(a));
+  ASSERT_NO_FATAL_FAILURE(parse_all(b));
+  ExpectTotalOrder(a, b, [](const auto &x, const auto &y) {
+    return X509_ALGOR_cmp(x.get(), y.get());
+  });
+}
+
 // Test that extracting fields of an `X509_ALGOR` works correctly.
 TEST(X509Test, X509AlgorExtract) {
   static const char kTestOID[] = "1.2.840.113554.4.1.72585.2";
diff --git a/crypto/x509/x_algor.cc b/crypto/x509/x_algor.cc
index b4591e5..93926c3 100644
--- a/crypto/x509/x_algor.cc
+++ b/crypto/x509/x_algor.cc
@@ -209,15 +209,10 @@
                          nullptr);
 }
 
-// X509_ALGOR_cmp returns 0 if `a` and `b` are equal and non-zero otherwise.
 int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b) {
-  int rv;
-  rv = OBJ_cmp(a->algorithm, b->algorithm);
-  if (rv) {
-    return rv;
-  }
-  if (!a->parameter && !b->parameter) {
-    return 0;
+  int ret = OBJ_cmp(a->algorithm, b->algorithm);
+  if (ret != 0) {
+    return ret;
   }
   return ASN1_TYPE_cmp(a->parameter, b->parameter);
 }
diff --git a/include/openssl/asn1.h b/include/openssl/asn1.h
index 2882a25..19f2629 100644
--- a/include/openssl/asn1.h
+++ b/include/openssl/asn1.h
@@ -1512,9 +1512,11 @@
 // of `value`. It returns one on success and zero on error.
 OPENSSL_EXPORT int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value);
 
-// ASN1_TYPE_cmp returns zero if `a` and `b` are equal and some non-zero value
-// otherwise. Note this function can only be used for equality checks, not an
-// ordering.
+// ASN1_TYPE_cmp compares `a` and `b`. It returns zero if they are equal, and a
+// negative or positive value if `a` sorts before or after `b`, respectively.
+// NULL sorts before any non-NULL value. Otherwise, values are ordered first by
+// type, then by contents. The order is arbitrary but suitable for sorting.
+// Callers should not rely on the exact order.
 OPENSSL_EXPORT int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b);
 
 typedef STACK_OF(ASN1_TYPE) ASN1_SEQUENCE_ANY;
diff --git a/include/openssl/x509.h b/include/openssl/x509.h
index cc2459a..5378ec5 100644
--- a/include/openssl/x509.h
+++ b/include/openssl/x509.h
@@ -2631,9 +2631,11 @@
 // constructing PSS and move on.
 OPENSSL_EXPORT int X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md);
 
-// X509_ALGOR_cmp returns zero if `a` and `b` are equal, and some non-zero value
-// otherwise. Note this function can only be used for equality checks, not an
-// ordering.
+// X509_ALGOR_cmp compares `a` and `b`. It returns zero if they are equal, and a
+// negative or positive value if `a` sorts before or after `b`, respectively.
+// Values are ordered first by algorithm, then by parameter, with an absent
+// parameter sorting before a present one. The order is arbitrary but suitable
+// for sorting. Callers should not rely on the exact order.
 OPENSSL_EXPORT int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b);