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