Normalize in-memory ASN1_BOOLEAN representations on parse

We should reject invalid BOOLEANs in the first place, but at least avoid
exposing callers to unexpected in-memory representations for no reason.

Bug: 42290221
Change-Id: Ie283292530d9875fd85adb8ea8eb24c80dce131e
Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/97387
Auto-Submit: David Benjamin <davidben@google.com>
Reviewed-by: Adam Langley <agl@google.com>
Commit-Queue: David Benjamin <davidben@google.com>
diff --git a/crypto/asn1/asn1_test.cc b/crypto/asn1/asn1_test.cc
index fd4e6cf..ed2a6ed 100644
--- a/crypto/asn1/asn1_test.cc
+++ b/crypto/asn1/asn1_test.cc
@@ -550,6 +550,12 @@
   val->ca = 0;
   TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kLeaf);
 
+  const uint8_t *inp = kLeaf;
+  UniquePtr<BASIC_CONSTRAINTS> parsed(
+      d2i_BASIC_CONSTRAINTS(nullptr, &inp, sizeof(kLeaf)));
+  ASSERT_TRUE(parsed);
+  EXPECT_EQ(parsed->ca, ASN1_BOOLEAN_FALSE);
+
   // TRUE should always be encoded as 0xff, independent of what value the caller
   // placed in the `ASN1_BOOLEAN`.
   static const uint8_t kCA[] = {0x30, 0x03, 0x01, 0x01, 0xff};
@@ -559,6 +565,19 @@
   TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kCA);
   val->ca = 0x100;
   TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kCA);
+
+  inp = kCA;
+  parsed.reset(d2i_BASIC_CONSTRAINTS(nullptr, &inp, sizeof(kCA)));
+  ASSERT_TRUE(parsed);
+  EXPECT_EQ(parsed->ca, ASN1_BOOLEAN_TRUE);
+
+  // We currently allow non-DER encodings of TRUE. (We should reject these.)
+  // When this happens, the in-memory representation is still uniform.
+  static const uint8_t kCAWrong[] = {0x30, 0x03, 0x01, 0x01, 0x01};
+  inp = kCAWrong;
+  parsed.reset(d2i_BASIC_CONSTRAINTS(nullptr, &inp, sizeof(kCAWrong)));
+  ASSERT_TRUE(parsed);
+  EXPECT_EQ(parsed->ca, ASN1_BOOLEAN_TRUE);
 }
 
 static std::vector<uint8_t> EmbedParamInAlgorithmIdentifier(
diff --git a/crypto/asn1/tasn_dec.cc b/crypto/asn1/tasn_dec.cc
index fbac8c4..57ce776 100644
--- a/crypto/asn1/tasn_dec.cc
+++ b/crypto/asn1/tasn_dec.cc
@@ -548,7 +548,8 @@
         OPENSSL_PUT_ERROR(ASN1, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
         return 0;
       }
-      *reinterpret_cast<ASN1_BOOLEAN *>(pval) = CBS_data(&child)[0];
+      *reinterpret_cast<ASN1_BOOLEAN *>(pval) =
+          CBS_data(&child)[0] ? ASN1_BOOLEAN_TRUE : ASN1_BOOLEAN_FALSE;
       return 1;
     }
   }