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