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