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