Update copyright year
[oweals/openssl.git] / crypto / asn1 / tasn_dec.c
1 /*
2  * Copyright 2000-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stddef.h>
11 #include <string.h>
12 #include <openssl/asn1.h>
13 #include <openssl/asn1t.h>
14 #include <openssl/objects.h>
15 #include <openssl/buffer.h>
16 #include <openssl/err.h>
17 #include "internal/numbers.h"
18 #include "asn1_locl.h"
19
20 /*
21  * Constructed types with a recursive definition (such as can be found in PKCS7)
22  * could eventually exceed the stack given malicious input with excessive
23  * recursion. Therefore we limit the stack depth. This is the maximum number of
24  * recursive invocations of asn1_item_embed_d2i().
25  */
26 #define ASN1_MAX_CONSTRUCTED_NEST 30
27
28 static int asn1_item_embed_d2i(ASN1_VALUE **pval, const unsigned char **in,
29                                long len, const ASN1_ITEM *it,
30                                int tag, int aclass, char opt, ASN1_TLC *ctx,
31                                int depth);
32
33 static int asn1_check_eoc(const unsigned char **in, long len);
34 static int asn1_find_end(const unsigned char **in, long len, char inf);
35
36 static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
37                         char inf, int tag, int aclass, int depth);
38
39 static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen);
40
41 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
42                            char *inf, char *cst,
43                            const unsigned char **in, long len,
44                            int exptag, int expclass, char opt, ASN1_TLC *ctx);
45
46 static int asn1_template_ex_d2i(ASN1_VALUE **pval,
47                                 const unsigned char **in, long len,
48                                 const ASN1_TEMPLATE *tt, char opt,
49                                 ASN1_TLC *ctx, int depth);
50 static int asn1_template_noexp_d2i(ASN1_VALUE **val,
51                                    const unsigned char **in, long len,
52                                    const ASN1_TEMPLATE *tt, char opt,
53                                    ASN1_TLC *ctx, int depth);
54 static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
55                                  const unsigned char **in, long len,
56                                  const ASN1_ITEM *it,
57                                  int tag, int aclass, char opt,
58                                  ASN1_TLC *ctx);
59 static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
60                        int utype, char *free_cont, const ASN1_ITEM *it);
61
62 /* Table to convert tags to bit values, used for MSTRING type */
63 static const unsigned long tag2bit[32] = {
64     /* tags  0 -  3 */
65     0, 0, 0, B_ASN1_BIT_STRING,
66     /* tags  4- 7 */
67     B_ASN1_OCTET_STRING, 0, 0, B_ASN1_UNKNOWN,
68     /* tags  8-11 */
69     B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN,
70     /* tags 12-15 */
71     B_ASN1_UTF8STRING, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN,
72     /* tags 16-19 */
73     B_ASN1_SEQUENCE, 0, B_ASN1_NUMERICSTRING, B_ASN1_PRINTABLESTRING,
74     /* tags 20-22 */
75     B_ASN1_T61STRING, B_ASN1_VIDEOTEXSTRING, B_ASN1_IA5STRING,
76     /* tags 23-24 */
77     B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME,
78     /* tags 25-27 */
79     B_ASN1_GRAPHICSTRING, B_ASN1_ISO64STRING, B_ASN1_GENERALSTRING,
80     /* tags 28-31 */
81     B_ASN1_UNIVERSALSTRING, B_ASN1_UNKNOWN, B_ASN1_BMPSTRING, B_ASN1_UNKNOWN,
82 };
83
84 unsigned long ASN1_tag2bit(int tag)
85 {
86     if ((tag < 0) || (tag > 30))
87         return 0;
88     return tag2bit[tag];
89 }
90
91 /* Macro to initialize and invalidate the cache */
92
93 #define asn1_tlc_clear(c)       if (c) (c)->valid = 0
94 /* Version to avoid compiler warning about 'c' always non-NULL */
95 #define asn1_tlc_clear_nc(c)    (c)->valid = 0
96
97 /*
98  * Decode an ASN1 item, this currently behaves just like a standard 'd2i'
99  * function. 'in' points to a buffer to read the data from, in future we
100  * will have more advanced versions that can input data a piece at a time and
101  * this will simply be a special case.
102  */
103
104 ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval,
105                           const unsigned char **in, long len,
106                           const ASN1_ITEM *it)
107 {
108     ASN1_TLC c;
109     ASN1_VALUE *ptmpval = NULL;
110     if (!pval)
111         pval = &ptmpval;
112     asn1_tlc_clear_nc(&c);
113     if (ASN1_item_ex_d2i(pval, in, len, it, -1, 0, 0, &c) > 0)
114         return *pval;
115     return NULL;
116 }
117
118 int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
119                      const ASN1_ITEM *it,
120                      int tag, int aclass, char opt, ASN1_TLC *ctx)
121 {
122     int rv;
123     rv = asn1_item_embed_d2i(pval, in, len, it, tag, aclass, opt, ctx, 0);
124     if (rv <= 0)
125         ASN1_item_ex_free(pval, it);
126     return rv;
127 }
128
129 /*
130  * Decode an item, taking care of IMPLICIT tagging, if any. If 'opt' set and
131  * tag mismatch return -1 to handle OPTIONAL
132  */
133
134 static int asn1_item_embed_d2i(ASN1_VALUE **pval, const unsigned char **in,
135                                long len, const ASN1_ITEM *it,
136                                int tag, int aclass, char opt, ASN1_TLC *ctx,
137                                int depth)
138 {
139     const ASN1_TEMPLATE *tt, *errtt = NULL;
140     const ASN1_EXTERN_FUNCS *ef;
141     const ASN1_AUX *aux = it->funcs;
142     ASN1_aux_cb *asn1_cb;
143     const unsigned char *p = NULL, *q;
144     unsigned char oclass;
145     char seq_eoc, seq_nolen, cst, isopt;
146     long tmplen;
147     int i;
148     int otag;
149     int ret = 0;
150     ASN1_VALUE **pchptr;
151     if (!pval)
152         return 0;
153     if (aux && aux->asn1_cb)
154         asn1_cb = aux->asn1_cb;
155     else
156         asn1_cb = 0;
157
158     if (++depth > ASN1_MAX_CONSTRUCTED_NEST) {
159         ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_NESTED_TOO_DEEP);
160         goto err;
161     }
162
163     switch (it->itype) {
164     case ASN1_ITYPE_PRIMITIVE:
165         if (it->templates) {
166             /*
167              * tagging or OPTIONAL is currently illegal on an item template
168              * because the flags can't get passed down. In practice this
169              * isn't a problem: we include the relevant flags from the item
170              * template in the template itself.
171              */
172             if ((tag != -1) || opt) {
173                 ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I,
174                         ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
175                 goto err;
176             }
177             return asn1_template_ex_d2i(pval, in, len,
178                                         it->templates, opt, ctx, depth);
179         }
180         return asn1_d2i_ex_primitive(pval, in, len, it,
181                                      tag, aclass, opt, ctx);
182
183     case ASN1_ITYPE_MSTRING:
184         p = *in;
185         /* Just read in tag and class */
186         ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,
187                               &p, len, -1, 0, 1, ctx);
188         if (!ret) {
189             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ERR_R_NESTED_ASN1_ERROR);
190             goto err;
191         }
192
193         /* Must be UNIVERSAL class */
194         if (oclass != V_ASN1_UNIVERSAL) {
195             /* If OPTIONAL, assume this is OK */
196             if (opt)
197                 return -1;
198             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL);
199             goto err;
200         }
201         /* Check tag matches bit map */
202         if (!(ASN1_tag2bit(otag) & it->utype)) {
203             /* If OPTIONAL, assume this is OK */
204             if (opt)
205                 return -1;
206             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_MSTRING_WRONG_TAG);
207             goto err;
208         }
209         return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx);
210
211     case ASN1_ITYPE_EXTERN:
212         /* Use new style d2i */
213         ef = it->funcs;
214         return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);
215
216     case ASN1_ITYPE_CHOICE:
217         if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
218             goto auxerr;
219         if (*pval) {
220             /* Free up and zero CHOICE value if initialised */
221             i = asn1_get_choice_selector(pval, it);
222             if ((i >= 0) && (i < it->tcount)) {
223                 tt = it->templates + i;
224                 pchptr = asn1_get_field_ptr(pval, tt);
225                 asn1_template_free(pchptr, tt);
226                 asn1_set_choice_selector(pval, -1, it);
227             }
228         } else if (!ASN1_item_ex_new(pval, it)) {
229             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ERR_R_NESTED_ASN1_ERROR);
230             goto err;
231         }
232         /* CHOICE type, try each possibility in turn */
233         p = *in;
234         for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
235             pchptr = asn1_get_field_ptr(pval, tt);
236             /*
237              * We mark field as OPTIONAL so its absence can be recognised.
238              */
239             ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx, depth);
240             /* If field not present, try the next one */
241             if (ret == -1)
242                 continue;
243             /* If positive return, read OK, break loop */
244             if (ret > 0)
245                 break;
246             /*
247              * Must be an ASN1 parsing error.
248              * Free up any partial choice value
249              */
250             asn1_template_free(pchptr, tt);
251             errtt = tt;
252             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ERR_R_NESTED_ASN1_ERROR);
253             goto err;
254         }
255
256         /* Did we fall off the end without reading anything? */
257         if (i == it->tcount) {
258             /* If OPTIONAL, this is OK */
259             if (opt) {
260                 /* Free and zero it */
261                 ASN1_item_ex_free(pval, it);
262                 return -1;
263             }
264             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);
265             goto err;
266         }
267
268         asn1_set_choice_selector(pval, i, it);
269
270         if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
271             goto auxerr;
272         *in = p;
273         return 1;
274
275     case ASN1_ITYPE_NDEF_SEQUENCE:
276     case ASN1_ITYPE_SEQUENCE:
277         p = *in;
278         tmplen = len;
279
280         /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
281         if (tag == -1) {
282             tag = V_ASN1_SEQUENCE;
283             aclass = V_ASN1_UNIVERSAL;
284         }
285         /* Get SEQUENCE length and update len, p */
286         ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,
287                               &p, len, tag, aclass, opt, ctx);
288         if (!ret) {
289             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ERR_R_NESTED_ASN1_ERROR);
290             goto err;
291         } else if (ret == -1)
292             return -1;
293         if (aux && (aux->flags & ASN1_AFLG_BROKEN)) {
294             len = tmplen - (p - *in);
295             seq_nolen = 1;
296         }
297         /* If indefinite we don't do a length check */
298         else
299             seq_nolen = seq_eoc;
300         if (!cst) {
301             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
302             goto err;
303         }
304
305         if (!*pval && !ASN1_item_ex_new(pval, it)) {
306             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ERR_R_NESTED_ASN1_ERROR);
307             goto err;
308         }
309
310         if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
311             goto auxerr;
312
313         /* Free up and zero any ADB found */
314         for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
315             if (tt->flags & ASN1_TFLG_ADB_MASK) {
316                 const ASN1_TEMPLATE *seqtt;
317                 ASN1_VALUE **pseqval;
318                 seqtt = asn1_do_adb(pval, tt, 0);
319                 if (seqtt == NULL)
320                     continue;
321                 pseqval = asn1_get_field_ptr(pval, seqtt);
322                 asn1_template_free(pseqval, seqtt);
323             }
324         }
325
326         /* Get each field entry */
327         for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
328             const ASN1_TEMPLATE *seqtt;
329             ASN1_VALUE **pseqval;
330             seqtt = asn1_do_adb(pval, tt, 1);
331             if (seqtt == NULL)
332                 goto err;
333             pseqval = asn1_get_field_ptr(pval, seqtt);
334             /* Have we ran out of data? */
335             if (!len)
336                 break;
337             q = p;
338             if (asn1_check_eoc(&p, len)) {
339                 if (!seq_eoc) {
340                     ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_UNEXPECTED_EOC);
341                     goto err;
342                 }
343                 len -= p - q;
344                 seq_eoc = 0;
345                 q = p;
346                 break;
347             }
348             /*
349              * This determines the OPTIONAL flag value. The field cannot be
350              * omitted if it is the last of a SEQUENCE and there is still
351              * data to be read. This isn't strictly necessary but it
352              * increases efficiency in some cases.
353              */
354             if (i == (it->tcount - 1))
355                 isopt = 0;
356             else
357                 isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
358             /*
359              * attempt to read in field, allowing each to be OPTIONAL
360              */
361
362             ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx,
363                                        depth);
364             if (!ret) {
365                 errtt = seqtt;
366                 goto err;
367             } else if (ret == -1) {
368                 /*
369                  * OPTIONAL component absent. Free and zero the field.
370                  */
371                 asn1_template_free(pseqval, seqtt);
372                 continue;
373             }
374             /* Update length */
375             len -= p - q;
376         }
377
378         /* Check for EOC if expecting one */
379         if (seq_eoc && !asn1_check_eoc(&p, len)) {
380             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_MISSING_EOC);
381             goto err;
382         }
383         /* Check all data read */
384         if (!seq_nolen && len) {
385             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
386             goto err;
387         }
388
389         /*
390          * If we get here we've got no more data in the SEQUENCE, however we
391          * may not have read all fields so check all remaining are OPTIONAL
392          * and clear any that are.
393          */
394         for (; i < it->tcount; tt++, i++) {
395             const ASN1_TEMPLATE *seqtt;
396             seqtt = asn1_do_adb(pval, tt, 1);
397             if (seqtt == NULL)
398                 goto err;
399             if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
400                 ASN1_VALUE **pseqval;
401                 pseqval = asn1_get_field_ptr(pval, seqtt);
402                 asn1_template_free(pseqval, seqtt);
403             } else {
404                 errtt = seqtt;
405                 ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_FIELD_MISSING);
406                 goto err;
407             }
408         }
409         /* Save encoding */
410         if (!asn1_enc_save(pval, *in, p - *in, it))
411             goto auxerr;
412         if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
413             goto auxerr;
414         *in = p;
415         return 1;
416
417     default:
418         return 0;
419     }
420  auxerr:
421     ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_AUX_ERROR);
422  err:
423     if (errtt)
424         ERR_add_error_data(4, "Field=", errtt->field_name,
425                            ", Type=", it->sname);
426     else
427         ERR_add_error_data(2, "Type=", it->sname);
428     return 0;
429 }
430
431 /*
432  * Templates are handled with two separate functions. One handles any
433  * EXPLICIT tag and the other handles the rest.
434  */
435
436 static int asn1_template_ex_d2i(ASN1_VALUE **val,
437                                 const unsigned char **in, long inlen,
438                                 const ASN1_TEMPLATE *tt, char opt,
439                                 ASN1_TLC *ctx, int depth)
440 {
441     int flags, aclass;
442     int ret;
443     long len;
444     const unsigned char *p, *q;
445     char exp_eoc;
446     if (!val)
447         return 0;
448     flags = tt->flags;
449     aclass = flags & ASN1_TFLG_TAG_CLASS;
450
451     p = *in;
452
453     /* Check if EXPLICIT tag expected */
454     if (flags & ASN1_TFLG_EXPTAG) {
455         char cst;
456         /*
457          * Need to work out amount of data available to the inner content and
458          * where it starts: so read in EXPLICIT header to get the info.
459          */
460         ret = asn1_check_tlen(&len, NULL, NULL, &exp_eoc, &cst,
461                               &p, inlen, tt->tag, aclass, opt, ctx);
462         q = p;
463         if (!ret) {
464             ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
465             return 0;
466         } else if (ret == -1)
467             return -1;
468         if (!cst) {
469             ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
470                     ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);
471             return 0;
472         }
473         /* We've found the field so it can't be OPTIONAL now */
474         ret = asn1_template_noexp_d2i(val, &p, len, tt, 0, ctx, depth);
475         if (!ret) {
476             ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
477             return 0;
478         }
479         /* We read the field in OK so update length */
480         len -= p - q;
481         if (exp_eoc) {
482             /* If NDEF we must have an EOC here */
483             if (!asn1_check_eoc(&p, len)) {
484                 ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ASN1_R_MISSING_EOC);
485                 goto err;
486             }
487         } else {
488             /*
489              * Otherwise we must hit the EXPLICIT tag end or its an error
490              */
491             if (len) {
492                 ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
493                         ASN1_R_EXPLICIT_LENGTH_MISMATCH);
494                 goto err;
495             }
496         }
497     } else
498         return asn1_template_noexp_d2i(val, in, inlen, tt, opt, ctx, depth);
499
500     *in = p;
501     return 1;
502
503  err:
504     return 0;
505 }
506
507 static int asn1_template_noexp_d2i(ASN1_VALUE **val,
508                                    const unsigned char **in, long len,
509                                    const ASN1_TEMPLATE *tt, char opt,
510                                    ASN1_TLC *ctx, int depth)
511 {
512     int flags, aclass;
513     int ret;
514     ASN1_VALUE *tval;
515     const unsigned char *p, *q;
516     if (!val)
517         return 0;
518     flags = tt->flags;
519     aclass = flags & ASN1_TFLG_TAG_CLASS;
520
521     p = *in;
522     q = p;
523
524     /*
525      * If field is embedded then val needs fixing so it is a pointer to
526      * a pointer to a field.
527      */
528     if (tt->flags & ASN1_TFLG_EMBED) {
529         tval = (ASN1_VALUE *)val;
530         val = &tval;
531     }
532
533     if (flags & ASN1_TFLG_SK_MASK) {
534         /* SET OF, SEQUENCE OF */
535         int sktag, skaclass;
536         char sk_eoc;
537         /* First work out expected inner tag value */
538         if (flags & ASN1_TFLG_IMPTAG) {
539             sktag = tt->tag;
540             skaclass = aclass;
541         } else {
542             skaclass = V_ASN1_UNIVERSAL;
543             if (flags & ASN1_TFLG_SET_OF)
544                 sktag = V_ASN1_SET;
545             else
546                 sktag = V_ASN1_SEQUENCE;
547         }
548         /* Get the tag */
549         ret = asn1_check_tlen(&len, NULL, NULL, &sk_eoc, NULL,
550                               &p, len, sktag, skaclass, opt, ctx);
551         if (!ret) {
552             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
553             return 0;
554         } else if (ret == -1)
555             return -1;
556         if (!*val)
557             *val = (ASN1_VALUE *)OPENSSL_sk_new_null();
558         else {
559             /*
560              * We've got a valid STACK: free up any items present
561              */
562             STACK_OF(ASN1_VALUE) *sktmp = (STACK_OF(ASN1_VALUE) *)*val;
563             ASN1_VALUE *vtmp;
564             while (sk_ASN1_VALUE_num(sktmp) > 0) {
565                 vtmp = sk_ASN1_VALUE_pop(sktmp);
566                 ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item));
567             }
568         }
569
570         if (!*val) {
571             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE);
572             goto err;
573         }
574
575         /* Read as many items as we can */
576         while (len > 0) {
577             ASN1_VALUE *skfield;
578             q = p;
579             /* See if EOC found */
580             if (asn1_check_eoc(&p, len)) {
581                 if (!sk_eoc) {
582                     ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
583                             ASN1_R_UNEXPECTED_EOC);
584                     goto err;
585                 }
586                 len -= p - q;
587                 sk_eoc = 0;
588                 break;
589             }
590             skfield = NULL;
591             if (!asn1_item_embed_d2i(&skfield, &p, len,
592                                      ASN1_ITEM_ptr(tt->item), -1, 0, 0, ctx,
593                                      depth)) {
594                 ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
595                         ERR_R_NESTED_ASN1_ERROR);
596                 /* |skfield| may be partially allocated despite failure. */
597                 ASN1_item_free(skfield, ASN1_ITEM_ptr(tt->item));
598                 goto err;
599             }
600             len -= p - q;
601             if (!sk_ASN1_VALUE_push((STACK_OF(ASN1_VALUE) *)*val, skfield)) {
602                 ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE);
603                 ASN1_item_free(skfield, ASN1_ITEM_ptr(tt->item));
604                 goto err;
605             }
606         }
607         if (sk_eoc) {
608             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ASN1_R_MISSING_EOC);
609             goto err;
610         }
611     } else if (flags & ASN1_TFLG_IMPTAG) {
612         /* IMPLICIT tagging */
613         ret = asn1_item_embed_d2i(val, &p, len,
614                                   ASN1_ITEM_ptr(tt->item), tt->tag, aclass, opt,
615                                   ctx, depth);
616         if (!ret) {
617             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
618             goto err;
619         } else if (ret == -1)
620             return -1;
621     } else {
622         /* Nothing special */
623         ret = asn1_item_embed_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item),
624                                   -1, 0, opt, ctx, depth);
625         if (!ret) {
626             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
627             goto err;
628         } else if (ret == -1)
629             return -1;
630     }
631
632     *in = p;
633     return 1;
634
635  err:
636     return 0;
637 }
638
639 static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
640                                  const unsigned char **in, long inlen,
641                                  const ASN1_ITEM *it,
642                                  int tag, int aclass, char opt, ASN1_TLC *ctx)
643 {
644     int ret = 0, utype;
645     long plen;
646     char cst, inf, free_cont = 0;
647     const unsigned char *p;
648     BUF_MEM buf = { 0, NULL, 0, 0 };
649     const unsigned char *cont = NULL;
650     long len;
651     if (!pval) {
652         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_NULL);
653         return 0;               /* Should never happen */
654     }
655
656     if (it->itype == ASN1_ITYPE_MSTRING) {
657         utype = tag;
658         tag = -1;
659     } else
660         utype = it->utype;
661
662     if (utype == V_ASN1_ANY) {
663         /* If type is ANY need to figure out type from tag */
664         unsigned char oclass;
665         if (tag >= 0) {
666             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_TAGGED_ANY);
667             return 0;
668         }
669         if (opt) {
670             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
671                     ASN1_R_ILLEGAL_OPTIONAL_ANY);
672             return 0;
673         }
674         p = *in;
675         ret = asn1_check_tlen(NULL, &utype, &oclass, NULL, NULL,
676                               &p, inlen, -1, 0, 0, ctx);
677         if (!ret) {
678             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
679             return 0;
680         }
681         if (oclass != V_ASN1_UNIVERSAL)
682             utype = V_ASN1_OTHER;
683     }
684     if (tag == -1) {
685         tag = utype;
686         aclass = V_ASN1_UNIVERSAL;
687     }
688     p = *in;
689     /* Check header */
690     ret = asn1_check_tlen(&plen, NULL, NULL, &inf, &cst,
691                           &p, inlen, tag, aclass, opt, ctx);
692     if (!ret) {
693         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
694         return 0;
695     } else if (ret == -1)
696         return -1;
697     ret = 0;
698     /* SEQUENCE, SET and "OTHER" are left in encoded form */
699     if ((utype == V_ASN1_SEQUENCE)
700         || (utype == V_ASN1_SET) || (utype == V_ASN1_OTHER)) {
701         /*
702          * Clear context cache for type OTHER because the auto clear when we
703          * have a exact match won't work
704          */
705         if (utype == V_ASN1_OTHER) {
706             asn1_tlc_clear(ctx);
707         }
708         /* SEQUENCE and SET must be constructed */
709         else if (!cst) {
710             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
711                     ASN1_R_TYPE_NOT_CONSTRUCTED);
712             return 0;
713         }
714
715         cont = *in;
716         /* If indefinite length constructed find the real end */
717         if (inf) {
718             if (!asn1_find_end(&p, plen, inf))
719                 goto err;
720             len = p - cont;
721         } else {
722             len = p - cont + plen;
723             p += plen;
724         }
725     } else if (cst) {
726         if (utype == V_ASN1_NULL || utype == V_ASN1_BOOLEAN
727             || utype == V_ASN1_OBJECT || utype == V_ASN1_INTEGER
728             || utype == V_ASN1_ENUMERATED) {
729             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_TYPE_NOT_PRIMITIVE);
730             return 0;
731         }
732
733         /* Free any returned 'buf' content */
734         free_cont = 1;
735         /*
736          * Should really check the internal tags are correct but some things
737          * may get this wrong. The relevant specs say that constructed string
738          * types should be OCTET STRINGs internally irrespective of the type.
739          * So instead just check for UNIVERSAL class and ignore the tag.
740          */
741         if (!asn1_collect(&buf, &p, plen, inf, -1, V_ASN1_UNIVERSAL, 0)) {
742             goto err;
743         }
744         len = buf.length;
745         /* Append a final null to string */
746         if (!BUF_MEM_grow_clean(&buf, len + 1)) {
747             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_MALLOC_FAILURE);
748             goto err;
749         }
750         buf.data[len] = 0;
751         cont = (const unsigned char *)buf.data;
752     } else {
753         cont = p;
754         len = plen;
755         p += plen;
756     }
757
758     /* We now have content length and type: translate into a structure */
759     /* asn1_ex_c2i may reuse allocated buffer, and so sets free_cont to 0 */
760     if (!asn1_ex_c2i(pval, cont, len, utype, &free_cont, it))
761         goto err;
762
763     *in = p;
764     ret = 1;
765  err:
766     if (free_cont)
767         OPENSSL_free(buf.data);
768     return ret;
769 }
770
771 /* Translate ASN1 content octets into a structure */
772
773 static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
774                        int utype, char *free_cont, const ASN1_ITEM *it)
775 {
776     ASN1_VALUE **opval = NULL;
777     ASN1_STRING *stmp;
778     ASN1_TYPE *typ = NULL;
779     int ret = 0;
780     const ASN1_PRIMITIVE_FUNCS *pf;
781     ASN1_INTEGER **tint;
782     pf = it->funcs;
783
784     if (pf && pf->prim_c2i)
785         return pf->prim_c2i(pval, cont, len, utype, free_cont, it);
786     /* If ANY type clear type and set pointer to internal value */
787     if (it->utype == V_ASN1_ANY) {
788         if (!*pval) {
789             typ = ASN1_TYPE_new();
790             if (typ == NULL)
791                 goto err;
792             *pval = (ASN1_VALUE *)typ;
793         } else
794             typ = (ASN1_TYPE *)*pval;
795
796         if (utype != typ->type)
797             ASN1_TYPE_set(typ, utype, NULL);
798         opval = pval;
799         pval = &typ->value.asn1_value;
800     }
801     switch (utype) {
802     case V_ASN1_OBJECT:
803         if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len))
804             goto err;
805         break;
806
807     case V_ASN1_NULL:
808         if (len) {
809             ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_NULL_IS_WRONG_LENGTH);
810             goto err;
811         }
812         *pval = (ASN1_VALUE *)1;
813         break;
814
815     case V_ASN1_BOOLEAN:
816         if (len != 1) {
817             ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
818             goto err;
819         } else {
820             ASN1_BOOLEAN *tbool;
821             tbool = (ASN1_BOOLEAN *)pval;
822             *tbool = *cont;
823         }
824         break;
825
826     case V_ASN1_BIT_STRING:
827         if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len))
828             goto err;
829         break;
830
831     case V_ASN1_INTEGER:
832     case V_ASN1_ENUMERATED:
833         tint = (ASN1_INTEGER **)pval;
834         if (!c2i_ASN1_INTEGER(tint, &cont, len))
835             goto err;
836         /* Fixup type to match the expected form */
837         (*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
838         break;
839
840     case V_ASN1_OCTET_STRING:
841     case V_ASN1_NUMERICSTRING:
842     case V_ASN1_PRINTABLESTRING:
843     case V_ASN1_T61STRING:
844     case V_ASN1_VIDEOTEXSTRING:
845     case V_ASN1_IA5STRING:
846     case V_ASN1_UTCTIME:
847     case V_ASN1_GENERALIZEDTIME:
848     case V_ASN1_GRAPHICSTRING:
849     case V_ASN1_VISIBLESTRING:
850     case V_ASN1_GENERALSTRING:
851     case V_ASN1_UNIVERSALSTRING:
852     case V_ASN1_BMPSTRING:
853     case V_ASN1_UTF8STRING:
854     case V_ASN1_OTHER:
855     case V_ASN1_SET:
856     case V_ASN1_SEQUENCE:
857     default:
858         if (utype == V_ASN1_BMPSTRING && (len & 1)) {
859             ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BMPSTRING_IS_WRONG_LENGTH);
860             goto err;
861         }
862         if (utype == V_ASN1_UNIVERSALSTRING && (len & 3)) {
863             ASN1err(ASN1_F_ASN1_EX_C2I,
864                     ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH);
865             goto err;
866         }
867         /* All based on ASN1_STRING and handled the same */
868         if (!*pval) {
869             stmp = ASN1_STRING_type_new(utype);
870             if (stmp == NULL) {
871                 ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
872                 goto err;
873             }
874             *pval = (ASN1_VALUE *)stmp;
875         } else {
876             stmp = (ASN1_STRING *)*pval;
877             stmp->type = utype;
878         }
879         /* If we've already allocated a buffer use it */
880         if (*free_cont) {
881             OPENSSL_free(stmp->data);
882             stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */
883             stmp->length = len;
884             *free_cont = 0;
885         } else {
886             if (!ASN1_STRING_set(stmp, cont, len)) {
887                 ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
888                 ASN1_STRING_free(stmp);
889                 *pval = NULL;
890                 goto err;
891             }
892         }
893         break;
894     }
895     /* If ASN1_ANY and NULL type fix up value */
896     if (typ && (utype == V_ASN1_NULL))
897         typ->value.ptr = NULL;
898
899     ret = 1;
900  err:
901     if (!ret) {
902         ASN1_TYPE_free(typ);
903         if (opval)
904             *opval = NULL;
905     }
906     return ret;
907 }
908
909 /*
910  * This function finds the end of an ASN1 structure when passed its maximum
911  * length, whether it is indefinite length and a pointer to the content. This
912  * is more efficient than calling asn1_collect because it does not recurse on
913  * each indefinite length header.
914  */
915
916 static int asn1_find_end(const unsigned char **in, long len, char inf)
917 {
918     uint32_t expected_eoc;
919     long plen;
920     const unsigned char *p = *in, *q;
921     /* If not indefinite length constructed just add length */
922     if (inf == 0) {
923         *in += len;
924         return 1;
925     }
926     expected_eoc = 1;
927     /*
928      * Indefinite length constructed form. Find the end when enough EOCs are
929      * found. If more indefinite length constructed headers are encountered
930      * increment the expected eoc count otherwise just skip to the end of the
931      * data.
932      */
933     while (len > 0) {
934         if (asn1_check_eoc(&p, len)) {
935             expected_eoc--;
936             if (expected_eoc == 0)
937                 break;
938             len -= 2;
939             continue;
940         }
941         q = p;
942         /* Just read in a header: only care about the length */
943         if (!asn1_check_tlen(&plen, NULL, NULL, &inf, NULL, &p, len,
944                              -1, 0, 0, NULL)) {
945             ASN1err(ASN1_F_ASN1_FIND_END, ERR_R_NESTED_ASN1_ERROR);
946             return 0;
947         }
948         if (inf) {
949             if (expected_eoc == UINT32_MAX) {
950                 ASN1err(ASN1_F_ASN1_FIND_END, ERR_R_NESTED_ASN1_ERROR);
951                 return 0;
952             }
953             expected_eoc++;
954         } else {
955             p += plen;
956         }
957         len -= p - q;
958     }
959     if (expected_eoc) {
960         ASN1err(ASN1_F_ASN1_FIND_END, ASN1_R_MISSING_EOC);
961         return 0;
962     }
963     *in = p;
964     return 1;
965 }
966
967 /*
968  * This function collects the asn1 data from a constructed string type into
969  * a buffer. The values of 'in' and 'len' should refer to the contents of the
970  * constructed type and 'inf' should be set if it is indefinite length.
971  */
972
973 #ifndef ASN1_MAX_STRING_NEST
974 /*
975  * This determines how many levels of recursion are permitted in ASN1 string
976  * types. If it is not limited stack overflows can occur. If set to zero no
977  * recursion is allowed at all. Although zero should be adequate examples
978  * exist that require a value of 1. So 5 should be more than enough.
979  */
980 # define ASN1_MAX_STRING_NEST 5
981 #endif
982
983 static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
984                         char inf, int tag, int aclass, int depth)
985 {
986     const unsigned char *p, *q;
987     long plen;
988     char cst, ininf;
989     p = *in;
990     inf &= 1;
991     /*
992      * If no buffer and not indefinite length constructed just pass over the
993      * encoded data
994      */
995     if (!buf && !inf) {
996         *in += len;
997         return 1;
998     }
999     while (len > 0) {
1000         q = p;
1001         /* Check for EOC */
1002         if (asn1_check_eoc(&p, len)) {
1003             /*
1004              * EOC is illegal outside indefinite length constructed form
1005              */
1006             if (!inf) {
1007                 ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_UNEXPECTED_EOC);
1008                 return 0;
1009             }
1010             inf = 0;
1011             break;
1012         }
1013
1014         if (!asn1_check_tlen(&plen, NULL, NULL, &ininf, &cst, &p,
1015                              len, tag, aclass, 0, NULL)) {
1016             ASN1err(ASN1_F_ASN1_COLLECT, ERR_R_NESTED_ASN1_ERROR);
1017             return 0;
1018         }
1019
1020         /* If indefinite length constructed update max length */
1021         if (cst) {
1022             if (depth >= ASN1_MAX_STRING_NEST) {
1023                 ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_NESTED_ASN1_STRING);
1024                 return 0;
1025             }
1026             if (!asn1_collect(buf, &p, plen, ininf, tag, aclass, depth + 1))
1027                 return 0;
1028         } else if (plen && !collect_data(buf, &p, plen))
1029             return 0;
1030         len -= p - q;
1031     }
1032     if (inf) {
1033         ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_MISSING_EOC);
1034         return 0;
1035     }
1036     *in = p;
1037     return 1;
1038 }
1039
1040 static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen)
1041 {
1042     int len;
1043     if (buf) {
1044         len = buf->length;
1045         if (!BUF_MEM_grow_clean(buf, len + plen)) {
1046             ASN1err(ASN1_F_COLLECT_DATA, ERR_R_MALLOC_FAILURE);
1047             return 0;
1048         }
1049         memcpy(buf->data + len, *p, plen);
1050     }
1051     *p += plen;
1052     return 1;
1053 }
1054
1055 /* Check for ASN1 EOC and swallow it if found */
1056
1057 static int asn1_check_eoc(const unsigned char **in, long len)
1058 {
1059     const unsigned char *p;
1060     if (len < 2)
1061         return 0;
1062     p = *in;
1063     if (!p[0] && !p[1]) {
1064         *in += 2;
1065         return 1;
1066     }
1067     return 0;
1068 }
1069
1070 /*
1071  * Check an ASN1 tag and length: a bit like ASN1_get_object but it sets the
1072  * length for indefinite length constructed form, we don't know the exact
1073  * length but we can set an upper bound to the amount of data available minus
1074  * the header length just read.
1075  */
1076
1077 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
1078                            char *inf, char *cst,
1079                            const unsigned char **in, long len,
1080                            int exptag, int expclass, char opt, ASN1_TLC *ctx)
1081 {
1082     int i;
1083     int ptag, pclass;
1084     long plen;
1085     const unsigned char *p, *q;
1086     p = *in;
1087     q = p;
1088
1089     if (ctx && ctx->valid) {
1090         i = ctx->ret;
1091         plen = ctx->plen;
1092         pclass = ctx->pclass;
1093         ptag = ctx->ptag;
1094         p += ctx->hdrlen;
1095     } else {
1096         i = ASN1_get_object(&p, &plen, &ptag, &pclass, len);
1097         if (ctx) {
1098             ctx->ret = i;
1099             ctx->plen = plen;
1100             ctx->pclass = pclass;
1101             ctx->ptag = ptag;
1102             ctx->hdrlen = p - q;
1103             ctx->valid = 1;
1104             /*
1105              * If definite length, and no error, length + header can't exceed
1106              * total amount of data available.
1107              */
1108             if (!(i & 0x81) && ((plen + ctx->hdrlen) > len)) {
1109                 ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_TOO_LONG);
1110                 asn1_tlc_clear(ctx);
1111                 return 0;
1112             }
1113         }
1114     }
1115
1116     if (i & 0x80) {
1117         ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_BAD_OBJECT_HEADER);
1118         asn1_tlc_clear(ctx);
1119         return 0;
1120     }
1121     if (exptag >= 0) {
1122         if ((exptag != ptag) || (expclass != pclass)) {
1123             /*
1124              * If type is OPTIONAL, not an error: indicate missing type.
1125              */
1126             if (opt)
1127                 return -1;
1128             asn1_tlc_clear(ctx);
1129             ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_WRONG_TAG);
1130             return 0;
1131         }
1132         /*
1133          * We have a tag and class match: assume we are going to do something
1134          * with it
1135          */
1136         asn1_tlc_clear(ctx);
1137     }
1138
1139     if (i & 1)
1140         plen = len - (p - q);
1141
1142     if (inf)
1143         *inf = i & 1;
1144
1145     if (cst)
1146         *cst = i & V_ASN1_CONSTRUCTED;
1147
1148     if (olen)
1149         *olen = plen;
1150
1151     if (oclass)
1152         *oclass = pclass;
1153
1154     if (otag)
1155         *otag = ptag;
1156
1157     *in = p;
1158     return 1;
1159 }