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