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