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