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