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