Backport of:

From 69f3d3c405991b0d6eea78d554b6aab4daeb4514 Mon Sep 17 00:00:00 2001
From: Matt Caswell <matt@openssl.org>
Date: Thu, 12 Nov 2020 14:55:31 +0000
Subject: [PATCH] Complain if we are attempting to encode with an invalid ASN.1
 template

It never makes sense for multi-string or CHOICE types to have implicit
tagging. If we have a template that uses the in this way then we
should immediately fail.

Thanks to David Benjamin from Google for reporting this issue.
---
 crypto/asn1/asn1_err.c    |  3 ++-
 crypto/asn1/tasn_enc.c    | 16 ++++++++++++++++
 include/openssl/asn1err.h |  7 +++----
 3 files changed, 21 insertions(+), 5 deletions(-)

--- a/Cryptlib/OpenSSL/crypto/asn1/asn1_err.c
+++ b/Cryptlib/OpenSSL/crypto/asn1/asn1_err.c
@@ -103,6 +103,7 @@ static ERR_STRING_DATA ASN1_str_functs[]
     {ERR_FUNC(ASN1_F_ASN1_ITEM_DUP), "ASN1_item_dup"},
     {ERR_FUNC(ASN1_F_ASN1_ITEM_EX_COMBINE_NEW), "ASN1_ITEM_EX_COMBINE_NEW"},
     {ERR_FUNC(ASN1_F_ASN1_ITEM_EX_D2I), "ASN1_ITEM_EX_D2I"},
+    {ERR_FUNC(ASN1_F_ASN1_ITEM_EX_I2D), "ASN1_item_ex_i2d"},
     {ERR_FUNC(ASN1_F_ASN1_ITEM_I2D_BIO), "ASN1_item_i2d_bio"},
     {ERR_FUNC(ASN1_F_ASN1_ITEM_I2D_FP), "ASN1_item_i2d_fp"},
     {ERR_FUNC(ASN1_F_ASN1_ITEM_PACK), "ASN1_item_pack"},
--- a/Cryptlib/OpenSSL/crypto/asn1/tasn_enc.c
+++ b/Cryptlib/OpenSSL/crypto/asn1/tasn_enc.c
@@ -150,9 +150,25 @@ int ASN1_item_ex_i2d(ASN1_VALUE **pval,
         break;
 
     case ASN1_ITYPE_MSTRING:
+        /*
+         * It never makes sense for multi-strings to have implicit tagging, so
+         * if tag != -1, then this looks like an error in the template.
+         */
+        if (tag != -1) {
+            ASN1err(ASN1_F_ASN1_ITEM_EX_I2D, ASN1_R_BAD_TEMPLATE);
+            return -1;
+        }
         return asn1_i2d_ex_primitive(pval, out, it, -1, aclass);
 
     case ASN1_ITYPE_CHOICE:
+        /*
+         * It never makes sense for CHOICE types to have implicit tagging, so
+         * if tag != -1, then this looks like an error in the template.
+         */
+        if (tag != -1) {
+            ASN1err(ASN1_F_ASN1_ITEM_EX_I2D, ASN1_R_BAD_TEMPLATE);
+            return -1;
+        }
         if (asn1_cb && !asn1_cb(ASN1_OP_I2D_PRE, pval, it, NULL))
             return 0;
         i = asn1_get_choice_selector(pval, it);
--- a/Cryptlib/Include/openssl/asn1.h
+++ b/Cryptlib/Include/openssl/asn1.h
@@ -1210,6 +1210,7 @@ void ERR_load_ASN1_strings(void);
 # define ASN1_F_ASN1_ITEM_DUP                             191
 # define ASN1_F_ASN1_ITEM_EX_COMBINE_NEW                  121
 # define ASN1_F_ASN1_ITEM_EX_D2I                          120
+# define ASN1_F_ASN1_ITEM_EX_I2D                          144
 # define ASN1_F_ASN1_ITEM_I2D_BIO                         192
 # define ASN1_F_ASN1_ITEM_I2D_FP                          193
 # define ASN1_F_ASN1_ITEM_PACK                            198
