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