Reject invalid constructed encodings.

According to X6.90 null, object identifier, boolean, integer and enumerated
types can only have primitive encodings: return an error if any of
these are received with a constructed encoding.

(Imported from upstream's 89f40f369f414b52e00f7230b0e3ce99e430a508.)

Change-Id: Ia5d15eef72e379119f50fdbac4e92c4761bf5eaf
Reviewed-on: https://boringssl-review.googlesource.com/2835
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/asn1/asn1_error.c b/crypto/asn1/asn1_error.c
index 8253322..87a7b64 100644
--- a/crypto/asn1/asn1_error.c
+++ b/crypto/asn1/asn1_error.c
@@ -182,6 +182,7 @@
   {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TIME_NOT_ASCII_FORMAT), "TIME_NOT_ASCII_FORMAT"},
   {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TOO_LONG), "TOO_LONG"},
   {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TYPE_NOT_CONSTRUCTED), "TYPE_NOT_CONSTRUCTED"},
+  {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_TYPE_NOT_PRIMITIVE), "TYPE_NOT_PRIMITIVE"},
   {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNABLE_TO_DECODE_RSA_KEY), "UNABLE_TO_DECODE_RSA_KEY"},
   {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNABLE_TO_DECODE_RSA_PRIVATE_KEY), "UNABLE_TO_DECODE_RSA_PRIVATE_KEY"},
   {ERR_PACK(ERR_LIB_ASN1, 0, ASN1_R_UNEXPECTED_EOC), "UNEXPECTED_EOC"},
diff --git a/crypto/asn1/tasn_dec.c b/crypto/asn1/tasn_dec.c
index 69bacec..e8c5cd8 100644
--- a/crypto/asn1/tasn_dec.c
+++ b/crypto/asn1/tasn_dec.c
@@ -835,6 +835,16 @@
 		}
 	else if (cst)
 		{
+		if (utype == V_ASN1_NULL || utype == V_ASN1_BOOLEAN
+			|| utype == V_ASN1_OBJECT || utype == V_ASN1_INTEGER
+			|| utype == V_ASN1_ENUMERATED)
+			{
+			/* These types only have primitive encodings. */
+			OPENSSL_PUT_ERROR(ASN1, asn1_d2i_ex_primitive,
+				ASN1_R_TYPE_NOT_PRIMITIVE);
+			return 0;
+			}
+
 		buf.length = 0;
 		buf.max = 0;
 		buf.data = NULL;
diff --git a/include/openssl/asn1.h b/include/openssl/asn1.h
index fc12a75..038d4e2 100644
--- a/include/openssl/asn1.h
+++ b/include/openssl/asn1.h
@@ -1258,5 +1258,6 @@
 #define ASN1_R_ERROR_PARSING_SET_ELEMENT 220
 #define ASN1_R_WRONG_TAG 221
 #define ASN1_R_BOOLEAN_IS_WRONG_LENGTH 222
+#define ASN1_R_TYPE_NOT_PRIMITIVE 223
 
 #endif