xref: /aosp_15_r20/external/boringssl/src/crypto/asn1/tasn_dec.c (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (C) 1995-1998 Eric Young ([email protected])
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young ([email protected]).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson ([email protected]).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young ([email protected])"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson ([email protected])"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.] */
56 
57 #include <openssl/asn1.h>
58 #include <openssl/asn1t.h>
59 #include <openssl/bytestring.h>
60 #include <openssl/err.h>
61 #include <openssl/mem.h>
62 #include <openssl/pool.h>
63 
64 #include <assert.h>
65 #include <limits.h>
66 #include <string.h>
67 
68 #include "../bytestring/internal.h"
69 #include "../internal.h"
70 #include "internal.h"
71 
72 // Constructed types with a recursive definition (such as can be found in PKCS7)
73 // could eventually exceed the stack given malicious input with excessive
74 // recursion. Therefore we limit the stack depth. This is the maximum number of
75 // recursive invocations of asn1_item_embed_d2i().
76 #define ASN1_MAX_CONSTRUCTED_NEST 30
77 
78 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
79                            char *cst, const unsigned char **in, long len,
80                            int exptag, int expclass, char opt);
81 
82 static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
83                                 long len, const ASN1_TEMPLATE *tt, char opt,
84                                 CRYPTO_BUFFER *buf, int depth);
85 static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
86                                    long len, const ASN1_TEMPLATE *tt, char opt,
87                                    CRYPTO_BUFFER *buf, int depth);
88 static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, long len,
89                        int utype, const ASN1_ITEM *it);
90 static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in,
91                                  long len, const ASN1_ITEM *it, int tag,
92                                  int aclass, char opt);
93 static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
94                             long len, const ASN1_ITEM *it, int tag, int aclass,
95                             char opt, CRYPTO_BUFFER *buf, int depth);
96 
97 // Table to convert tags to bit values, used for MSTRING type
98 static const unsigned long tag2bit[31] = {
99     0,  // (reserved)
100     0,  // BOOLEAN
101     0,  // INTEGER
102     B_ASN1_BIT_STRING,
103     B_ASN1_OCTET_STRING,
104     0,               // NULL
105     0,               // OBJECT IDENTIFIER
106     B_ASN1_UNKNOWN,  // ObjectDescriptor
107     B_ASN1_UNKNOWN,  // EXTERNAL
108     B_ASN1_UNKNOWN,  // REAL
109     B_ASN1_UNKNOWN,  // ENUMERATED
110     B_ASN1_UNKNOWN,  // EMBEDDED PDV
111     B_ASN1_UTF8STRING,
112     B_ASN1_UNKNOWN,  // RELATIVE-OID
113     B_ASN1_UNKNOWN,  // TIME
114     B_ASN1_UNKNOWN,  // (reserved)
115     B_ASN1_SEQUENCE,
116     0,  // SET
117     B_ASN1_NUMERICSTRING,
118     B_ASN1_PRINTABLESTRING,
119     B_ASN1_T61STRING,
120     B_ASN1_VIDEOTEXSTRING,
121     B_ASN1_IA5STRING,
122     B_ASN1_UTCTIME,
123     B_ASN1_GENERALIZEDTIME,
124     B_ASN1_GRAPHICSTRING,
125     B_ASN1_ISO64STRING,
126     B_ASN1_GENERALSTRING,
127     B_ASN1_UNIVERSALSTRING,
128     B_ASN1_UNKNOWN,  // CHARACTER STRING
129     B_ASN1_BMPSTRING,
130 };
131 
ASN1_tag2bit(int tag)132 unsigned long ASN1_tag2bit(int tag) {
133   if (tag < 0 || tag > 30) {
134     return 0;
135   }
136   return tag2bit[tag];
137 }
138 
is_supported_universal_type(int tag,int aclass)139 static int is_supported_universal_type(int tag, int aclass) {
140   if (aclass != V_ASN1_UNIVERSAL) {
141     return 0;
142   }
143   return tag == V_ASN1_OBJECT || tag == V_ASN1_NULL || tag == V_ASN1_BOOLEAN ||
144          tag == V_ASN1_BIT_STRING || tag == V_ASN1_INTEGER ||
145          tag == V_ASN1_ENUMERATED || tag == V_ASN1_OCTET_STRING ||
146          tag == V_ASN1_NUMERICSTRING || tag == V_ASN1_PRINTABLESTRING ||
147          tag == V_ASN1_T61STRING || tag == V_ASN1_VIDEOTEXSTRING ||
148          tag == V_ASN1_IA5STRING || tag == V_ASN1_UTCTIME ||
149          tag == V_ASN1_GENERALIZEDTIME || tag == V_ASN1_GRAPHICSTRING ||
150          tag == V_ASN1_VISIBLESTRING || tag == V_ASN1_GENERALSTRING ||
151          tag == V_ASN1_UNIVERSALSTRING || tag == V_ASN1_BMPSTRING ||
152          tag == V_ASN1_UTF8STRING || tag == V_ASN1_SET ||
153          tag == V_ASN1_SEQUENCE;
154 }
155 
156 // Macro to initialize and invalidate the cache
157 
158 // Decode an ASN1 item, this currently behaves just like a standard 'd2i'
159 // function. 'in' points to a buffer to read the data from, in future we
160 // will have more advanced versions that can input data a piece at a time and
161 // this will simply be a special case.
162 
ASN1_item_d2i(ASN1_VALUE ** pval,const unsigned char ** in,long len,const ASN1_ITEM * it)163 ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
164                           const ASN1_ITEM *it) {
165   ASN1_VALUE *ret = NULL;
166   if (asn1_item_ex_d2i(&ret, in, len, it, /*tag=*/-1, /*aclass=*/0, /*opt=*/0,
167                        /*buf=*/NULL, /*depth=*/0) <= 0) {
168     // Clean up, in case the caller left a partial object.
169     //
170     // TODO(davidben): I don't think it can leave one, but the codepaths below
171     // are a bit inconsistent. Revisit this when rewriting this function.
172     ASN1_item_ex_free(&ret, it);
173   }
174 
175   // If the caller supplied an output pointer, free the old one and replace it
176   // with |ret|. This differs from OpenSSL slightly in that we don't support
177   // object reuse. We run this on both success and failure. On failure, even
178   // with object reuse, OpenSSL destroys the previous object.
179   if (pval != NULL) {
180     ASN1_item_ex_free(pval, it);
181     *pval = ret;
182   }
183   return ret;
184 }
185 
186 // Decode an item, taking care of IMPLICIT tagging, if any. If 'opt' set and
187 // tag mismatch return -1 to handle OPTIONAL
188 //
189 // TODO(davidben): Historically, all functions in this file had to account for
190 // |*pval| containing an arbitrary existing value. This is no longer the case
191 // because |ASN1_item_d2i| now always starts from NULL. As part of rewriting
192 // this function, take the simplified assumptions into account. Though we must
193 // still account for the internal calls to |ASN1_item_ex_new|.
194 
asn1_item_ex_d2i(ASN1_VALUE ** pval,const unsigned char ** in,long len,const ASN1_ITEM * it,int tag,int aclass,char opt,CRYPTO_BUFFER * buf,int depth)195 static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
196                             long len, const ASN1_ITEM *it, int tag, int aclass,
197                             char opt, CRYPTO_BUFFER *buf, int depth) {
198   const ASN1_TEMPLATE *tt, *errtt = NULL;
199   const unsigned char *p = NULL, *q;
200   unsigned char oclass;
201   char cst, isopt;
202   int i;
203   int otag;
204   int ret = 0;
205   ASN1_VALUE **pchptr;
206   if (!pval) {
207     return 0;
208   }
209 
210   if (buf != NULL) {
211     assert(CRYPTO_BUFFER_data(buf) <= *in &&
212            *in + len <= CRYPTO_BUFFER_data(buf) + CRYPTO_BUFFER_len(buf));
213   }
214 
215   // Bound |len| to comfortably fit in an int. Lengths in this module often
216   // switch between int and long without overflow checks.
217   if (len > INT_MAX / 2) {
218     len = INT_MAX / 2;
219   }
220 
221   if (++depth > ASN1_MAX_CONSTRUCTED_NEST) {
222     OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_TOO_DEEP);
223     goto err;
224   }
225 
226   switch (it->itype) {
227     case ASN1_ITYPE_PRIMITIVE:
228       if (it->templates) {
229         // tagging or OPTIONAL is currently illegal on an item template
230         // because the flags can't get passed down. In practice this
231         // isn't a problem: we include the relevant flags from the item
232         // template in the template itself.
233         if ((tag != -1) || opt) {
234           OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
235           goto err;
236         }
237         return asn1_template_ex_d2i(pval, in, len, it->templates, opt, buf,
238                                     depth);
239       }
240       return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt);
241       break;
242 
243     case ASN1_ITYPE_MSTRING:
244       // It never makes sense for multi-strings to have implicit tagging, so
245       // if tag != -1, then this looks like an error in the template.
246       if (tag != -1) {
247         OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
248         goto err;
249       }
250 
251       p = *in;
252       // Just read in tag and class
253       ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, &p, len, -1, 0, 1);
254       if (!ret) {
255         OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
256         goto err;
257       }
258 
259       // Must be UNIVERSAL class
260       if (oclass != V_ASN1_UNIVERSAL) {
261         // If OPTIONAL, assume this is OK
262         if (opt) {
263           return -1;
264         }
265         OPENSSL_PUT_ERROR(ASN1, ASN1_R_MSTRING_NOT_UNIVERSAL);
266         goto err;
267       }
268       // Check tag matches bit map
269       if (!(ASN1_tag2bit(otag) & it->utype)) {
270         // If OPTIONAL, assume this is OK
271         if (opt) {
272           return -1;
273         }
274         OPENSSL_PUT_ERROR(ASN1, ASN1_R_MSTRING_WRONG_TAG);
275         goto err;
276       }
277       return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0);
278 
279     case ASN1_ITYPE_EXTERN: {
280       // We don't support implicit tagging with external types.
281       if (tag != -1) {
282         OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
283         goto err;
284       }
285       const ASN1_EXTERN_FUNCS *ef = it->funcs;
286       return ef->asn1_ex_d2i(pval, in, len, it, opt, NULL);
287     }
288 
289     case ASN1_ITYPE_CHOICE: {
290       // It never makes sense for CHOICE types to have implicit tagging, so if
291       // tag != -1, then this looks like an error in the template.
292       if (tag != -1) {
293         OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
294         goto err;
295       }
296 
297       const ASN1_AUX *aux = it->funcs;
298       ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
299       if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) {
300         goto auxerr;
301       }
302 
303       if (*pval) {
304         // Free up and zero CHOICE value if initialised
305         i = asn1_get_choice_selector(pval, it);
306         if ((i >= 0) && (i < it->tcount)) {
307           tt = it->templates + i;
308           pchptr = asn1_get_field_ptr(pval, tt);
309           ASN1_template_free(pchptr, tt);
310           asn1_set_choice_selector(pval, -1, it);
311         }
312       } else if (!ASN1_item_ex_new(pval, it)) {
313         OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
314         goto err;
315       }
316       // CHOICE type, try each possibility in turn
317       p = *in;
318       for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
319         pchptr = asn1_get_field_ptr(pval, tt);
320         // We mark field as OPTIONAL so its absence can be recognised.
321         ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, buf, depth);
322         // If field not present, try the next one
323         if (ret == -1) {
324           continue;
325         }
326         // If positive return, read OK, break loop
327         if (ret > 0) {
328           break;
329         }
330         // Otherwise must be an ASN1 parsing error
331         errtt = tt;
332         OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
333         goto err;
334       }
335 
336       // Did we fall off the end without reading anything?
337       if (i == it->tcount) {
338         // If OPTIONAL, this is OK
339         if (opt) {
340           // Free and zero it
341           ASN1_item_ex_free(pval, it);
342           return -1;
343         }
344         OPENSSL_PUT_ERROR(ASN1, ASN1_R_NO_MATCHING_CHOICE_TYPE);
345         goto err;
346       }
347 
348       asn1_set_choice_selector(pval, i, it);
349       if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) {
350         goto auxerr;
351       }
352       *in = p;
353       return 1;
354     }
355 
356     case ASN1_ITYPE_SEQUENCE: {
357       p = *in;
358 
359       // If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL
360       if (tag == -1) {
361         tag = V_ASN1_SEQUENCE;
362         aclass = V_ASN1_UNIVERSAL;
363       }
364       // Get SEQUENCE length and update len, p
365       ret = asn1_check_tlen(&len, NULL, NULL, &cst, &p, len, tag, aclass, opt);
366       if (!ret) {
367         OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
368         goto err;
369       } else if (ret == -1) {
370         return -1;
371       }
372       if (!cst) {
373         OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
374         goto err;
375       }
376 
377       if (!*pval && !ASN1_item_ex_new(pval, it)) {
378         OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
379         goto err;
380       }
381 
382       const ASN1_AUX *aux = it->funcs;
383       ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
384       if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) {
385         goto auxerr;
386       }
387 
388       // Free up and zero any ADB found
389       for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
390         if (tt->flags & ASN1_TFLG_ADB_MASK) {
391           const ASN1_TEMPLATE *seqtt;
392           ASN1_VALUE **pseqval;
393           seqtt = asn1_do_adb(pval, tt, 0);
394           if (seqtt == NULL) {
395             continue;
396           }
397           pseqval = asn1_get_field_ptr(pval, seqtt);
398           ASN1_template_free(pseqval, seqtt);
399         }
400       }
401 
402       // Get each field entry
403       for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
404         const ASN1_TEMPLATE *seqtt;
405         ASN1_VALUE **pseqval;
406         seqtt = asn1_do_adb(pval, tt, 1);
407         if (seqtt == NULL) {
408           goto err;
409         }
410         pseqval = asn1_get_field_ptr(pval, seqtt);
411         // Have we ran out of data?
412         if (!len) {
413           break;
414         }
415         q = p;
416         // This determines the OPTIONAL flag value. The field cannot be
417         // omitted if it is the last of a SEQUENCE and there is still
418         // data to be read. This isn't strictly necessary but it
419         // increases efficiency in some cases.
420         if (i == (it->tcount - 1)) {
421           isopt = 0;
422         } else {
423           isopt = (seqtt->flags & ASN1_TFLG_OPTIONAL) != 0;
424         }
425         // attempt to read in field, allowing each to be OPTIONAL
426 
427         ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, buf, depth);
428         if (!ret) {
429           errtt = seqtt;
430           goto err;
431         } else if (ret == -1) {
432           // OPTIONAL component absent. Free and zero the field.
433           ASN1_template_free(pseqval, seqtt);
434           continue;
435         }
436         // Update length
437         len -= p - q;
438       }
439 
440       // Check all data read
441       if (len) {
442         OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
443         goto err;
444       }
445 
446       // If we get here we've got no more data in the SEQUENCE, however we
447       // may not have read all fields so check all remaining are OPTIONAL
448       // and clear any that are.
449       for (; i < it->tcount; tt++, i++) {
450         const ASN1_TEMPLATE *seqtt;
451         seqtt = asn1_do_adb(pval, tt, 1);
452         if (seqtt == NULL) {
453           goto err;
454         }
455         if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
456           ASN1_VALUE **pseqval;
457           pseqval = asn1_get_field_ptr(pval, seqtt);
458           ASN1_template_free(pseqval, seqtt);
459         } else {
460           errtt = seqtt;
461           OPENSSL_PUT_ERROR(ASN1, ASN1_R_FIELD_MISSING);
462           goto err;
463         }
464       }
465       // Save encoding
466       if (!asn1_enc_save(pval, *in, p - *in, it, buf)) {
467         goto auxerr;
468       }
469       if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) {
470         goto auxerr;
471       }
472       *in = p;
473       return 1;
474     }
475 
476     default:
477       return 0;
478   }
479 auxerr:
480   OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR);
481 err:
482   ASN1_item_ex_free(pval, it);
483   if (errtt) {
484     ERR_add_error_data(4, "Field=", errtt->field_name, ", Type=", it->sname);
485   } else {
486     ERR_add_error_data(2, "Type=", it->sname);
487   }
488   return 0;
489 }
490 
ASN1_item_ex_d2i(ASN1_VALUE ** pval,const unsigned char ** in,long len,const ASN1_ITEM * it,int tag,int aclass,char opt,CRYPTO_BUFFER * buf)491 int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
492                      const ASN1_ITEM *it, int tag, int aclass, char opt,
493                      CRYPTO_BUFFER *buf) {
494   return asn1_item_ex_d2i(pval, in, len, it, tag, aclass, opt, buf,
495                           /*depth=*/0);
496 }
497 
498 // Templates are handled with two separate functions. One handles any
499 // EXPLICIT tag and the other handles the rest.
500 
asn1_template_ex_d2i(ASN1_VALUE ** val,const unsigned char ** in,long inlen,const ASN1_TEMPLATE * tt,char opt,CRYPTO_BUFFER * buf,int depth)501 static int asn1_template_ex_d2i(ASN1_VALUE **val, const unsigned char **in,
502                                 long inlen, const ASN1_TEMPLATE *tt, char opt,
503                                 CRYPTO_BUFFER *buf, int depth) {
504   int aclass;
505   int ret;
506   long len;
507   const unsigned char *p, *q;
508   if (!val) {
509     return 0;
510   }
511   uint32_t flags = tt->flags;
512   aclass = flags & ASN1_TFLG_TAG_CLASS;
513 
514   p = *in;
515 
516   // Check if EXPLICIT tag expected
517   if (flags & ASN1_TFLG_EXPTAG) {
518     char cst;
519     // Need to work out amount of data available to the inner content and
520     // where it starts: so read in EXPLICIT header to get the info.
521     ret = asn1_check_tlen(&len, NULL, NULL, &cst, &p, inlen, tt->tag, aclass,
522                           opt);
523     q = p;
524     if (!ret) {
525       OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
526       return 0;
527     } else if (ret == -1) {
528       return -1;
529     }
530     if (!cst) {
531       OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);
532       return 0;
533     }
534     // We've found the field so it can't be OPTIONAL now
535     ret = asn1_template_noexp_d2i(val, &p, len, tt, /*opt=*/0, buf, depth);
536     if (!ret) {
537       OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
538       return 0;
539     }
540     // We read the field in OK so update length
541     len -= p - q;
542     // Check for trailing data.
543     if (len) {
544       OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPLICIT_LENGTH_MISMATCH);
545       goto err;
546     }
547   } else {
548     return asn1_template_noexp_d2i(val, in, inlen, tt, opt, buf, depth);
549   }
550 
551   *in = p;
552   return 1;
553 
554 err:
555   ASN1_template_free(val, tt);
556   return 0;
557 }
558 
asn1_template_noexp_d2i(ASN1_VALUE ** val,const unsigned char ** in,long len,const ASN1_TEMPLATE * tt,char opt,CRYPTO_BUFFER * buf,int depth)559 static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
560                                    long len, const ASN1_TEMPLATE *tt, char opt,
561                                    CRYPTO_BUFFER *buf, int depth) {
562   int aclass;
563   int ret;
564   const unsigned char *p;
565   if (!val) {
566     return 0;
567   }
568   uint32_t flags = tt->flags;
569   aclass = flags & ASN1_TFLG_TAG_CLASS;
570 
571   p = *in;
572 
573   if (flags & ASN1_TFLG_SK_MASK) {
574     // SET OF, SEQUENCE OF
575     int sktag, skaclass;
576     // First work out expected inner tag value
577     if (flags & ASN1_TFLG_IMPTAG) {
578       sktag = tt->tag;
579       skaclass = aclass;
580     } else {
581       skaclass = V_ASN1_UNIVERSAL;
582       if (flags & ASN1_TFLG_SET_OF) {
583         sktag = V_ASN1_SET;
584       } else {
585         sktag = V_ASN1_SEQUENCE;
586       }
587     }
588     // Get the tag
589     ret =
590         asn1_check_tlen(&len, NULL, NULL, NULL, &p, len, sktag, skaclass, opt);
591     if (!ret) {
592       OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
593       return 0;
594     } else if (ret == -1) {
595       return -1;
596     }
597     if (!*val) {
598       *val = (ASN1_VALUE *)sk_ASN1_VALUE_new_null();
599     } else {
600       // We've got a valid STACK: free up any items present
601       STACK_OF(ASN1_VALUE) *sktmp = (STACK_OF(ASN1_VALUE) *)*val;
602       ASN1_VALUE *vtmp;
603       while (sk_ASN1_VALUE_num(sktmp) > 0) {
604         vtmp = sk_ASN1_VALUE_pop(sktmp);
605         ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item));
606       }
607     }
608 
609     if (!*val) {
610       goto err;
611     }
612 
613     // Read as many items as we can
614     while (len > 0) {
615       ASN1_VALUE *skfield;
616       const unsigned char *q = p;
617       skfield = NULL;
618       if (!asn1_item_ex_d2i(&skfield, &p, len, ASN1_ITEM_ptr(tt->item),
619                             /*tag=*/-1, /*aclass=*/0, /*opt=*/0, buf, depth)) {
620         OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
621         goto err;
622       }
623       len -= p - q;
624       if (!sk_ASN1_VALUE_push((STACK_OF(ASN1_VALUE) *)*val, skfield)) {
625         ASN1_item_ex_free(&skfield, ASN1_ITEM_ptr(tt->item));
626         goto err;
627       }
628     }
629   } else if (flags & ASN1_TFLG_IMPTAG) {
630     // IMPLICIT tagging
631     ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), tt->tag,
632                            aclass, opt, buf, depth);
633     if (!ret) {
634       OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
635       goto err;
636     } else if (ret == -1) {
637       return -1;
638     }
639   } else {
640     // Nothing special
641     ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), /*tag=*/-1,
642                            /*aclass=*/0, opt, buf, depth);
643     if (!ret) {
644       OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
645       goto err;
646     } else if (ret == -1) {
647       return -1;
648     }
649   }
650 
651   *in = p;
652   return 1;
653 
654 err:
655   ASN1_template_free(val, tt);
656   return 0;
657 }
658 
asn1_d2i_ex_primitive(ASN1_VALUE ** pval,const unsigned char ** in,long inlen,const ASN1_ITEM * it,int tag,int aclass,char opt)659 static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in,
660                                  long inlen, const ASN1_ITEM *it, int tag,
661                                  int aclass, char opt) {
662   int ret = 0, utype;
663   long plen;
664   char cst;
665   const unsigned char *p;
666   const unsigned char *cont = NULL;
667   long len;
668   if (!pval) {
669     OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_NULL);
670     return 0;  // Should never happen
671   }
672 
673   if (it->itype == ASN1_ITYPE_MSTRING) {
674     utype = tag;
675     tag = -1;
676   } else {
677     utype = it->utype;
678   }
679 
680   if (utype == V_ASN1_ANY) {
681     // If type is ANY need to figure out type from tag
682     unsigned char oclass;
683     if (tag >= 0) {
684       OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_TAGGED_ANY);
685       return 0;
686     }
687     if (opt) {
688       OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OPTIONAL_ANY);
689       return 0;
690     }
691     p = *in;
692     ret = asn1_check_tlen(NULL, &utype, &oclass, NULL, &p, inlen, -1, 0, 0);
693     if (!ret) {
694       OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
695       return 0;
696     }
697     if (!is_supported_universal_type(utype, oclass)) {
698       utype = V_ASN1_OTHER;
699     }
700   }
701   if (tag == -1) {
702     tag = utype;
703     aclass = V_ASN1_UNIVERSAL;
704   }
705   p = *in;
706   // Check header
707   ret = asn1_check_tlen(&plen, NULL, NULL, &cst, &p, inlen, tag, aclass, opt);
708   if (!ret) {
709     OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
710     return 0;
711   } else if (ret == -1) {
712     return -1;
713   }
714   ret = 0;
715   // SEQUENCE, SET and "OTHER" are left in encoded form
716   if ((utype == V_ASN1_SEQUENCE) || (utype == V_ASN1_SET) ||
717       (utype == V_ASN1_OTHER)) {
718     // SEQUENCE and SET must be constructed
719     if (utype != V_ASN1_OTHER && !cst) {
720       OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_CONSTRUCTED);
721       return 0;
722     }
723 
724     cont = *in;
725     len = p - cont + plen;
726     p += plen;
727   } else if (cst) {
728     // This parser historically supported BER constructed strings. We no
729     // longer do and will gradually tighten this parser into a DER
730     // parser. BER types should use |CBS_asn1_ber_to_der|.
731     OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE);
732     return 0;
733   } else {
734     cont = p;
735     len = plen;
736     p += plen;
737   }
738 
739   // We now have content length and type: translate into a structure
740   if (!asn1_ex_c2i(pval, cont, len, utype, it)) {
741     goto err;
742   }
743 
744   *in = p;
745   ret = 1;
746 err:
747   return ret;
748 }
749 
750 // Translate ASN1 content octets into a structure
751 
asn1_ex_c2i(ASN1_VALUE ** pval,const unsigned char * cont,long len,int utype,const ASN1_ITEM * it)752 static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, long len,
753                        int utype, const ASN1_ITEM *it) {
754   ASN1_VALUE **opval = NULL;
755   ASN1_STRING *stmp;
756   ASN1_TYPE *typ = NULL;
757   int ret = 0;
758   ASN1_INTEGER **tint;
759 
760   // Historically, |it->funcs| for primitive types contained an
761   // |ASN1_PRIMITIVE_FUNCS| table of callbacks.
762   assert(it->funcs == NULL);
763 
764   // If ANY type clear type and set pointer to internal value
765   if (it->utype == V_ASN1_ANY) {
766     if (!*pval) {
767       typ = ASN1_TYPE_new();
768       if (typ == NULL) {
769         goto err;
770       }
771       *pval = (ASN1_VALUE *)typ;
772     } else {
773       typ = (ASN1_TYPE *)*pval;
774     }
775 
776     if (utype != typ->type) {
777       ASN1_TYPE_set(typ, utype, NULL);
778     }
779     opval = pval;
780     pval = &typ->value.asn1_value;
781   }
782   switch (utype) {
783     case V_ASN1_OBJECT:
784       if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len)) {
785         goto err;
786       }
787       break;
788 
789     case V_ASN1_NULL:
790       if (len) {
791         OPENSSL_PUT_ERROR(ASN1, ASN1_R_NULL_IS_WRONG_LENGTH);
792         goto err;
793       }
794       *pval = (ASN1_VALUE *)1;
795       break;
796 
797     case V_ASN1_BOOLEAN:
798       if (len != 1) {
799         OPENSSL_PUT_ERROR(ASN1, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
800         goto err;
801       } else {
802         ASN1_BOOLEAN *tbool;
803         tbool = (ASN1_BOOLEAN *)pval;
804         *tbool = *cont;
805       }
806       break;
807 
808     case V_ASN1_BIT_STRING:
809       if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len)) {
810         goto err;
811       }
812       break;
813 
814     case V_ASN1_INTEGER:
815     case V_ASN1_ENUMERATED:
816       tint = (ASN1_INTEGER **)pval;
817       if (!c2i_ASN1_INTEGER(tint, &cont, len)) {
818         goto err;
819       }
820       // Fixup type to match the expected form
821       (*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
822       break;
823 
824     case V_ASN1_OCTET_STRING:
825     case V_ASN1_NUMERICSTRING:
826     case V_ASN1_PRINTABLESTRING:
827     case V_ASN1_T61STRING:
828     case V_ASN1_VIDEOTEXSTRING:
829     case V_ASN1_IA5STRING:
830     case V_ASN1_UTCTIME:
831     case V_ASN1_GENERALIZEDTIME:
832     case V_ASN1_GRAPHICSTRING:
833     case V_ASN1_VISIBLESTRING:
834     case V_ASN1_GENERALSTRING:
835     case V_ASN1_UNIVERSALSTRING:
836     case V_ASN1_BMPSTRING:
837     case V_ASN1_UTF8STRING:
838     case V_ASN1_OTHER:
839     case V_ASN1_SET:
840     case V_ASN1_SEQUENCE:
841     // TODO(crbug.com/boringssl/412): This default case should be removed, now
842     // that we've resolved https://crbug.com/boringssl/561. However, it is still
843     // needed to support some edge cases in |ASN1_PRINTABLE|. |ASN1_PRINTABLE|
844     // broadly doesn't tolerate unrecognized universal tags, but except for
845     // eight values that map to |B_ASN1_UNKNOWN| instead of zero. See the
846     // X509Test.NameAttributeValues test.
847     default: {
848       CBS cbs;
849       CBS_init(&cbs, cont, (size_t)len);
850       if (utype == V_ASN1_BMPSTRING) {
851         while (CBS_len(&cbs) != 0) {
852           uint32_t c;
853           if (!CBS_get_ucs2_be(&cbs, &c)) {
854             OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BMPSTRING);
855             goto err;
856           }
857         }
858       }
859       if (utype == V_ASN1_UNIVERSALSTRING) {
860         while (CBS_len(&cbs) != 0) {
861           uint32_t c;
862           if (!CBS_get_utf32_be(&cbs, &c)) {
863             OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_UNIVERSALSTRING);
864             goto err;
865           }
866         }
867       }
868       if (utype == V_ASN1_UTF8STRING) {
869         while (CBS_len(&cbs) != 0) {
870           uint32_t c;
871           if (!CBS_get_utf8(&cbs, &c)) {
872             OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_UTF8STRING);
873             goto err;
874           }
875         }
876       }
877       if (utype == V_ASN1_UTCTIME) {
878         if (!CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1)) {
879           OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_TIME_FORMAT);
880           goto err;
881         }
882       }
883       if (utype == V_ASN1_GENERALIZEDTIME) {
884         if (!CBS_parse_generalized_time(&cbs, NULL,
885                                         /*allow_timezone_offset=*/0)) {
886           OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_TIME_FORMAT);
887           goto err;
888         }
889       }
890       // TODO(https://crbug.com/boringssl/427): Check other string types.
891 
892       // All based on ASN1_STRING and handled the same
893       if (!*pval) {
894         stmp = ASN1_STRING_type_new(utype);
895         if (!stmp) {
896           goto err;
897         }
898         *pval = (ASN1_VALUE *)stmp;
899       } else {
900         stmp = (ASN1_STRING *)*pval;
901         stmp->type = utype;
902       }
903       if (!ASN1_STRING_set(stmp, cont, len)) {
904         ASN1_STRING_free(stmp);
905         *pval = NULL;
906         goto err;
907       }
908       break;
909     }
910   }
911   // If ASN1_ANY and NULL type fix up value
912   if (typ && (utype == V_ASN1_NULL)) {
913     typ->value.ptr = NULL;
914   }
915 
916   ret = 1;
917 err:
918   if (!ret) {
919     ASN1_TYPE_free(typ);
920     if (opval) {
921       *opval = NULL;
922     }
923   }
924   return ret;
925 }
926 
927 // Check an ASN1 tag and length: a bit like ASN1_get_object but it
928 // checks the expected tag.
929 
asn1_check_tlen(long * olen,int * otag,unsigned char * oclass,char * cst,const unsigned char ** in,long len,int exptag,int expclass,char opt)930 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
931                            char *cst, const unsigned char **in, long len,
932                            int exptag, int expclass, char opt) {
933   int i;
934   int ptag, pclass;
935   long plen;
936   const unsigned char *p;
937   p = *in;
938 
939   i = ASN1_get_object(&p, &plen, &ptag, &pclass, len);
940   if (i & 0x80) {
941     OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_OBJECT_HEADER);
942     return 0;
943   }
944   if (exptag >= 0) {
945     if ((exptag != ptag) || (expclass != pclass)) {
946       // If type is OPTIONAL, not an error: indicate missing type.
947       if (opt) {
948         return -1;
949       }
950       OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TAG);
951       return 0;
952     }
953   }
954 
955   if (cst) {
956     *cst = i & V_ASN1_CONSTRUCTED;
957   }
958 
959   if (olen) {
960     *olen = plen;
961   }
962 
963   if (oclass) {
964     *oclass = pclass;
965   }
966 
967   if (otag) {
968     *otag = ptag;
969   }
970 
971   *in = p;
972   return 1;
973 }
974