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