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