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