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