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