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