Constify d2i, s2i, c2i and r2i functions and other associated
[oweals/openssl.git] / crypto / asn1 / tasn_dec.c
1 /* tasn_dec.c */
2 /* Written by Dr Stephen N Henson (shenson@bigfoot.com) for the OpenSSL
3  * project 2000.
4  */
5 /* ====================================================================
6  * Copyright (c) 2000 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
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_collect(BUF_MEM *buf, const unsigned char **in, long len, char inf, int tag, int aclass);
70 static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen);
71 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass, char *inf, char *cst,
72                         const unsigned char **in, long len, int exptag, int expclass, char opt, ASN1_TLC *ctx);
73 static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx);
74 static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx);
75 static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long len,
76                                         const ASN1_ITEM *it, int tag, int aclass, char opt, ASN1_TLC *ctx);
77
78 /* Table to convert tags to bit values, used for MSTRING type */
79 static unsigned long tag2bit[32]={
80 0,      0,      0,      B_ASN1_BIT_STRING,      /* tags  0 -  3 */
81 B_ASN1_OCTET_STRING,    0,      0,              B_ASN1_UNKNOWN,/* tags  4- 7 */
82 B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN,/* tags  8-11 */
83 B_ASN1_UTF8STRING,B_ASN1_UNKNOWN,B_ASN1_UNKNOWN,B_ASN1_UNKNOWN,/* tags 12-15 */
84 0,      0,      B_ASN1_NUMERICSTRING,B_ASN1_PRINTABLESTRING,   /* tags 16-19 */
85 B_ASN1_T61STRING,B_ASN1_VIDEOTEXSTRING,B_ASN1_IA5STRING,       /* tags 20-22 */
86 B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME,                        /* tags 23-24 */ 
87 B_ASN1_GRAPHICSTRING,B_ASN1_ISO64STRING,B_ASN1_GENERALSTRING,  /* tags 25-27 */
88 B_ASN1_UNIVERSALSTRING,B_ASN1_UNKNOWN,B_ASN1_BMPSTRING,B_ASN1_UNKNOWN, /* tags 28-31 */
89         };
90
91 unsigned long ASN1_tag2bit(int tag)
92 {
93         if((tag < 0) || (tag > 30)) return 0;
94         return tag2bit[tag];
95 }
96
97 /* Macro to initialize and invalidate the cache */
98
99 #define asn1_tlc_clear(c)       if(c) (c)->valid = 0
100
101 /* Decode an ASN1 item, this currently behaves just 
102  * like a standard 'd2i' function. 'in' points to 
103  * a buffer to read the data from, in future we will
104  * have more advanced versions that can input data
105  * a piece at a time and this will simply be a special
106  * case.
107  */
108
109 ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it)
110 {
111         ASN1_TLC c;
112         ASN1_VALUE *ptmpval = NULL;
113         if(!pval) pval = &ptmpval;
114         asn1_tlc_clear(&c);
115         if(ASN1_item_ex_d2i(pval, in, len, it, -1, 0, 0, &c) > 0) 
116                 return *pval;
117         return NULL;
118 }
119
120 int ASN1_template_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_TEMPLATE *tt)
121 {
122         ASN1_TLC c;
123         asn1_tlc_clear(&c);
124         return asn1_template_ex_d2i(pval, in, len, tt, 0, &c);
125 }
126
127
128 /* Decode an item, taking care of IMPLICIT tagging, if any.
129  * If 'opt' set and tag mismatch return -1 to handle OPTIONAL
130  */
131
132 int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len, const ASN1_ITEM *it,
133                                 int tag, int aclass, char opt, ASN1_TLC *ctx)
134 {
135         const ASN1_TEMPLATE *tt, *errtt = NULL;
136         const ASN1_COMPAT_FUNCS *cf;
137         const ASN1_EXTERN_FUNCS *ef;
138         const ASN1_AUX *aux = it->funcs;
139         ASN1_aux_cb *asn1_cb;
140         const unsigned char *p, *q;
141         unsigned char *wp=NULL; /* BIG FAT WARNING!  BREAKS CONST WHERE USED */
142         unsigned char imphack = 0, oclass;
143         char seq_eoc, seq_nolen, cst, isopt;
144         long tmplen;
145         int i;
146         int otag;
147         int ret = 0;
148         ASN1_VALUE *pchval, **pchptr, *ptmpval;
149         if(!pval) return 0;
150         if(aux && aux->asn1_cb) asn1_cb = aux->asn1_cb;
151         else asn1_cb = 0;
152
153         switch(it->itype) {
154
155                 case ASN1_ITYPE_PRIMITIVE:
156                 if(it->templates) {
157                         /* tagging or OPTIONAL is currently illegal on an item template
158                          * because the flags can't get passed down. In practice this isn't
159                          * a problem: we include the relevant flags from the item template
160                          * in the template itself.
161                          */
162                         if ((tag != -1) || opt) {
163                                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
164                                 goto err;
165                         }
166                         return asn1_template_ex_d2i(pval, in, len, it->templates, opt, ctx);
167                 }
168                 return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt, ctx);
169                 break;
170
171                 case ASN1_ITYPE_MSTRING:
172                 p = *in;
173                 /* Just read in tag and class */
174                 ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL, &p, len, -1, 0, 1, ctx);
175                 if(!ret) {
176                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
177                         goto err;
178                 } 
179                 /* Must be UNIVERSAL class */
180                 if(oclass != V_ASN1_UNIVERSAL) {
181                         /* If OPTIONAL, assume this is OK */
182                         if(opt) return -1;
183                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_NOT_UNIVERSAL);
184                         goto err;
185                 } 
186                 /* Check tag matches bit map */
187                 if(!(ASN1_tag2bit(otag) & it->utype)) {
188                         /* If OPTIONAL, assume this is OK */
189                         if(opt) return -1;
190                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MSTRING_WRONG_TAG);
191                         goto err;
192                 } 
193                 return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0, ctx);
194
195                 case ASN1_ITYPE_EXTERN:
196                 /* Use new style d2i */
197                 ef = it->funcs;
198                 return ef->asn1_ex_d2i(pval, in, len, it, tag, aclass, opt, ctx);
199
200                 case ASN1_ITYPE_COMPAT:
201                 /* we must resort to old style evil hackery */
202                 cf = it->funcs;
203
204                 /* If OPTIONAL see if it is there */
205                 if(opt) {
206                         int exptag;
207                         p = *in;
208                         if(tag == -1) exptag = it->utype;
209                         else exptag = tag;
210                         /* Don't care about anything other than presence of expected tag */
211                         ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL, &p, len, exptag, aclass, 1, ctx);
212                         if(!ret) {
213                                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
214                                 goto err;
215                         }
216                         if(ret == -1) return -1;
217                 }
218                 /* This is the old style evil hack IMPLICIT handling:
219                  * since the underlying code is expecting a tag and
220                  * class other than the one present we change the
221                  * buffer temporarily then change it back afterwards.
222                  * This doesn't and never did work for tags > 30.
223                  *
224                  * Yes this is *horrible* but it is only needed for
225                  * old style d2i which will hopefully not be around
226                  * for much longer.
227                  * FIXME: should copy the buffer then modify it so
228                  * the input buffer can be const: we should *always*
229                  * copy because the old style d2i might modify the
230                  * buffer.
231                  */
232
233                 if(tag != -1) {
234                         wp = *(unsigned char **)in;
235                         imphack = *wp;
236                         *wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED) | it->utype);
237                 }
238
239                 ptmpval = cf->asn1_d2i(pval, in, len);
240
241                 if(tag != -1) *wp = imphack;
242
243                 if(ptmpval) return 1;
244                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
245                 goto err;
246
247
248                 case ASN1_ITYPE_CHOICE:
249                 if(asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it))
250                                 goto auxerr;
251
252                 /* Allocate structure */
253                 if(!*pval) {
254                         if(!ASN1_item_ex_new(pval, it)) {
255                                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
256                                 goto err;
257                         }
258                 }
259                 /* CHOICE type, try each possibility in turn */
260                 pchval = NULL;
261                 p = *in;
262                 for(i = 0, tt=it->templates; i < it->tcount; i++, tt++) {
263                         pchptr = asn1_get_field_ptr(pval, tt);
264                         /* We mark field as OPTIONAL so its absence
265                          * can be recognised.
266                          */
267                         ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);
268                         /* If field not present, try the next one */
269                         if(ret == -1) continue;
270                         /* If positive return, read OK, break loop */
271                         if(ret > 0) break;
272                         /* Otherwise must be an ASN1 parsing error */
273                         errtt = tt;
274                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
275                         goto err;
276                 }
277                 /* Did we fall off the end without reading anything? */
278                 if(i == it->tcount) {
279                         /* If OPTIONAL, this is OK */
280                         if(opt) {
281                                 /* Free and zero it */
282                                 ASN1_item_ex_free(pval, it);
283                                 return -1;
284                         }
285                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);
286                         goto err;
287                 }
288                 asn1_set_choice_selector(pval, i, it);
289                 *in = p;
290                 if(asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it))
291                                 goto auxerr;
292                 return 1;
293
294                 case ASN1_ITYPE_NDEF_SEQUENCE:
295                 case ASN1_ITYPE_SEQUENCE:
296                 p = *in;
297                 tmplen = len;
298
299                 /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
300                 if(tag == -1) {
301                         tag = V_ASN1_SEQUENCE;
302                         aclass = V_ASN1_UNIVERSAL;
303                 }
304                 /* Get SEQUENCE length and update len, p */
305                 ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst, &p, len, tag, aclass, opt, ctx);
306                 if(!ret) {
307                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
308                         goto err;
309                 } else if(ret == -1) return -1;
310                 if(aux && (aux->flags & ASN1_AFLG_BROKEN)) {
311                         len = tmplen - (p - *in);
312                         seq_nolen = 1;
313                 } else seq_nolen = seq_eoc;     /* If indefinite we don't do a length check */
314                 if(!cst) {
315                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
316                         goto err;
317                 }
318
319                 if(!*pval) {
320                         if(!ASN1_item_ex_new(pval, it)) {
321                                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
322                                 goto err;
323                         }
324                 }
325                 if(asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it))
326                                 goto auxerr;
327
328                 /* Get each field entry */
329                 for(i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
330                         const ASN1_TEMPLATE *seqtt;
331                         ASN1_VALUE **pseqval;
332                         seqtt = asn1_do_adb(pval, tt, 1);
333                         if(!seqtt) goto err;
334                         pseqval = asn1_get_field_ptr(pval, seqtt);
335                         /* Have we ran out of data? */
336                         if(!len) break;
337                         q = p;
338                         if(asn1_check_eoc(&p, len)) {
339                                 if(!seq_eoc) {
340                                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_UNEXPECTED_EOC);
341                                         goto err;
342                                 }
343                                 len -= p - q;
344                                 seq_eoc = 0;
345                                 q = p;
346                                 break;
347                         }
348                         /* This determines the OPTIONAL flag value. The field cannot
349                          * be omitted if it is the last of a SEQUENCE and there is
350                          * still data to be read. This isn't strictly necessary but
351                          * it increases efficiency in some cases.
352                          */
353                         if(i == (it->tcount - 1)) isopt = 0;
354                         else isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
355                         /* attempt to read in field, allowing each to be OPTIONAL */
356                         ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx);
357                         if(!ret) {
358                                 errtt = seqtt;
359                                 goto err;
360                         } else if(ret == -1) {
361                                 /* OPTIONAL component absent. Free and zero the field
362                                  */
363                                 ASN1_template_free(pseqval, seqtt);
364                                 continue;
365                         }
366                         /* Update length */
367                         len -= p - q;
368                 }
369                 /* Check for EOC if expecting one */
370                 if(seq_eoc && !asn1_check_eoc(&p, len)) {
371                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);
372                         goto err;
373                 }
374                 /* Check all data read */
375                 if(!seq_nolen && len) {
376                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
377                         goto err;
378                 }
379
380                 /* If we get here we've got no more data in the SEQUENCE,
381                  * however we may not have read all fields so check all
382                  * remaining are OPTIONAL and clear any that are.
383                  */
384                 for(; i < it->tcount; tt++, i++) {
385                         const ASN1_TEMPLATE *seqtt;
386                         seqtt = asn1_do_adb(pval, tt, 1);
387                         if(!seqtt) goto err;
388                         if(seqtt->flags & ASN1_TFLG_OPTIONAL) {
389                                 ASN1_VALUE **pseqval;
390                                 pseqval = asn1_get_field_ptr(pval, seqtt);
391                                 ASN1_template_free(pseqval, seqtt);
392                         } else {
393                                 errtt = seqtt;
394                                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_FIELD_MISSING);
395                                 goto err;
396                         }
397                 }
398                 /* Save encoding */
399                 if(!asn1_enc_save(pval, *in, p - *in, it)) goto auxerr;
400                 *in = p;
401                 if(asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it))
402                                 goto auxerr;
403                 return 1;
404
405                 default:
406                 return 0;
407         }
408         auxerr:
409         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);
410         err:
411         ASN1_item_ex_free(pval, it);
412         if(errtt) ERR_add_error_data(4, "Field=", errtt->field_name, ", Type=", it->sname);
413         else ERR_add_error_data(2, "Type=", it->sname);
414         return 0;
415 }
416
417 /* Templates are handled with two separate functions. One handles any EXPLICIT tag and the other handles the
418  * rest.
419  */
420
421 static int asn1_template_ex_d2i(ASN1_VALUE **val, const unsigned char **in, long inlen, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx)
422 {
423         int flags, aclass;
424         int ret;
425         long len;
426         const unsigned char *p, *q;
427         char exp_eoc;
428         if(!val) return 0;
429         flags = tt->flags;
430         aclass = flags & ASN1_TFLG_TAG_CLASS;
431
432         p = *in;
433
434         /* Check if EXPLICIT tag expected */
435         if(flags & ASN1_TFLG_EXPTAG) {
436                 char cst;
437                 /* Need to work out amount of data available to the inner content and where it
438                  * starts: so read in EXPLICIT header to get the info.
439                  */
440                 ret = asn1_check_tlen(&len, NULL, NULL, &exp_eoc, &cst, &p, inlen, tt->tag, aclass, opt, ctx);
441                 q = p;
442                 if(!ret) {
443                         ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
444                         return 0;
445                 } else if(ret == -1) return -1;
446                 if(!cst) {
447                         ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);
448                         return 0;
449                 }
450                 /* We've found the field so it can't be OPTIONAL now */
451                 ret = asn1_template_noexp_d2i(val, &p, len, tt, 0, ctx);
452                 if(!ret) {
453                         ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
454                         return 0;
455                 }
456                 /* We read the field in OK so update length */
457                 len -= p - q;
458                 if(exp_eoc) {
459                         /* If NDEF we must have an EOC here */
460                         if(!asn1_check_eoc(&p, len)) {
461                                 ASN1err(ASN1_F_ASN1_TEMPLATE_D2I, ASN1_R_MISSING_EOC);
462                                 goto err;
463                         }
464                 } else {
465                         /* Otherwise we must hit the EXPLICIT tag end or its an error */
466                         if(len) {
467                                 ASN1err(ASN1_F_ASN1_TEMPLATE_D2I, ASN1_R_EXPLICIT_LENGTH_MISMATCH);
468                                 goto err;
469                         }
470                 }
471         } else 
472                 return asn1_template_noexp_d2i(val, in, inlen, tt, opt, ctx);
473
474         *in = p;
475         return 1;
476
477         err:
478         ASN1_template_free(val, tt);
479         *val = NULL;
480         return 0;
481 }
482
483 static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in, long len, const ASN1_TEMPLATE *tt, char opt, ASN1_TLC *ctx)
484 {
485         int flags, aclass;
486         int ret;
487         const unsigned char *p, *q;
488         if(!val) return 0;
489         flags = tt->flags;
490         aclass = flags & ASN1_TFLG_TAG_CLASS;
491
492         p = *in;
493         q = p;
494
495         if(flags & ASN1_TFLG_SK_MASK) {
496                 /* SET OF, SEQUENCE OF */
497                 int sktag, skaclass;
498                 char sk_eoc;
499                 /* First work out expected inner tag value */
500                 if(flags & ASN1_TFLG_IMPTAG) {
501                         sktag = tt->tag;
502                         skaclass = aclass;
503                 } else {
504                         skaclass = V_ASN1_UNIVERSAL;
505                         if(flags & ASN1_TFLG_SET_OF) sktag = V_ASN1_SET;
506                         else sktag = V_ASN1_SEQUENCE;
507                 }
508                 /* Get the tag */
509                 ret = asn1_check_tlen(&len, NULL, NULL, &sk_eoc, NULL, &p, len, sktag, skaclass, opt, ctx);
510                 if(!ret) {
511                         ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
512                         return 0;
513                 } else if(ret == -1) return -1;
514                 if(!*val) *val = (ASN1_VALUE *)sk_new_null();
515                 else {
516                         /* We've got a valid STACK: free up any items present */
517                         STACK *sktmp = (STACK *)*val;
518                         ASN1_VALUE *vtmp;
519                         while(sk_num(sktmp) > 0) {
520                                 vtmp = (ASN1_VALUE *)sk_pop(sktmp);
521                                 ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item));
522                         }
523                 }
524                                 
525                 if(!*val) {
526                         ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_MALLOC_FAILURE);
527                         goto err;
528                 }
529                 /* Read as many items as we can */
530                 while(len > 0) {
531                         ASN1_VALUE *skfield;
532                         q = p;
533                         /* See if EOC found */
534                         if(asn1_check_eoc(&p, len)) {
535                                 if(!sk_eoc) {
536                                         ASN1err(ASN1_F_ASN1_TEMPLATE_D2I, ASN1_R_UNEXPECTED_EOC);
537                                         goto err;
538                                 }
539                                 len -= p - q;
540                                 sk_eoc = 0;
541                                 break;
542                         }
543                         skfield = NULL;
544                         if(!ASN1_item_ex_d2i(&skfield, &p, len, ASN1_ITEM_ptr(tt->item), -1, 0, 0, ctx)) {
545                                 ASN1err(ASN1_F_ASN1_TEMPLATE_D2I, ERR_R_NESTED_ASN1_ERROR);
546                                 goto err;
547                         }
548                         len -= p - q;
549                         if(!sk_push((STACK *)*val, (char *)skfield)) {
550                                 ASN1err(ASN1_F_ASN1_TEMPLATE_D2I, ERR_R_MALLOC_FAILURE);
551                                 goto err;
552                         }
553                 }
554                 if(sk_eoc) {
555                         ASN1err(ASN1_F_ASN1_TEMPLATE_D2I, ASN1_R_MISSING_EOC);
556                         goto err;
557                 }
558         } else if(flags & ASN1_TFLG_IMPTAG) {
559                 /* IMPLICIT tagging */
560                 ret = ASN1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), tt->tag, aclass, opt, ctx);
561                 if(!ret) {
562                         ASN1err(ASN1_F_ASN1_TEMPLATE_D2I, ERR_R_NESTED_ASN1_ERROR);
563                         goto err;
564                 } else if(ret == -1) return -1;
565         } else {
566                 /* Nothing special */
567                 ret = ASN1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), -1, 0, opt, ctx);
568                 if(!ret) {
569                         ASN1err(ASN1_F_ASN1_TEMPLATE_D2I, ERR_R_NESTED_ASN1_ERROR);
570                         goto err;
571                 } else if(ret == -1) return -1;
572         }
573
574         *in = p;
575         return 1;
576
577         err:
578         ASN1_template_free(val, tt);
579         *val = NULL;
580         return 0;
581 }
582
583 static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in, long inlen, 
584                                                 const ASN1_ITEM *it,
585                                                 int tag, int aclass, char opt, ASN1_TLC *ctx)
586 {
587         int ret = 0, utype;
588         long plen;
589         char cst, inf, free_cont = 0;
590         const unsigned char *p;
591         BUF_MEM buf;
592         const unsigned char *cont = NULL;
593         long len; 
594         if(!pval) {
595                 ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_NULL);
596                 return 0; /* Should never happen */
597         }
598
599         if(it->itype == ASN1_ITYPE_MSTRING) {
600                 utype = tag;
601                 tag = -1;
602         } else utype = it->utype;
603
604         if(utype == V_ASN1_ANY) {
605                 /* If type is ANY need to figure out type from tag */
606                 unsigned char oclass;
607                 if(tag >= 0) {
608                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_TAGGED_ANY);
609                         return 0;
610                 }
611                 if(opt) {
612                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_OPTIONAL_ANY);
613                         return 0;
614                 }
615                 p = *in;
616                 ret = asn1_check_tlen(NULL, &utype, &oclass, NULL, NULL, &p, inlen, -1, 0, 0, ctx);
617                 if(!ret) {
618                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
619                         return 0;
620                 }
621                 if(oclass != V_ASN1_UNIVERSAL) utype = V_ASN1_OTHER;
622         }
623         if(tag == -1) {
624                 tag = utype;
625                 aclass = V_ASN1_UNIVERSAL;
626         }
627         p = *in;
628         /* Check header */
629         ret = asn1_check_tlen(&plen, NULL, NULL, &inf, &cst, &p, inlen, tag, aclass, opt, ctx);
630         if(!ret) {
631                 ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
632                 return 0;
633         } else if(ret == -1) return -1;
634         /* SEQUENCE, SET and "OTHER" are left in encoded form */
635         if((utype == V_ASN1_SEQUENCE) || (utype == V_ASN1_SET) || (utype == V_ASN1_OTHER)) {
636                 /* Clear context cache for type OTHER because the auto clear when
637                  * we have a exact match wont work
638                  */
639                 if(utype == V_ASN1_OTHER) {
640                         asn1_tlc_clear(ctx);
641                 /* SEQUENCE and SET must be constructed */
642                 } else if(!cst) {
643                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_TYPE_NOT_CONSTRUCTED);
644                         return 0;
645                 }
646
647                 cont = *in;
648                 /* If indefinite length constructed find the real end */
649                 if(inf) {
650                         if(!asn1_collect(NULL, &p, plen, inf, -1, -1)) goto err;
651                         len = p - cont;
652                 } else {
653                         len = p - cont + plen;
654                         p += plen;
655                         buf.data = NULL;
656                 }
657         } else if(cst) {
658                 buf.length = 0;
659                 buf.max = 0;
660                 buf.data = NULL;
661                 /* Should really check the internal tags are correct but
662                  * some things may get this wrong. The relevant specs
663                  * say that constructed string types should be OCTET STRINGs
664                  * internally irrespective of the type. So instead just check
665                  * for UNIVERSAL class and ignore the tag.
666                  */
667                 if(!asn1_collect(&buf, &p, plen, inf, -1, V_ASN1_UNIVERSAL)) goto err;
668                 len = buf.length;
669                 /* Append a final null to string */
670                 if(!BUF_MEM_grow_clean(&buf, len + 1)) {
671                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_MALLOC_FAILURE);
672                         return 0;
673                 }
674                 buf.data[len] = 0;
675                 cont = (const unsigned char *)buf.data;
676                 free_cont = 1;
677         } else {
678                 cont = p;
679                 len = plen;
680                 p += plen;
681         }
682
683         /* We now have content length and type: translate into a structure */
684         if(!asn1_ex_c2i(pval, cont, len, utype, &free_cont, it)) goto err;
685
686         *in = p;
687         ret = 1;
688         err:
689         if(free_cont && buf.data) OPENSSL_free(buf.data);
690         return ret;
691 }
692
693 /* Translate ASN1 content octets into a structure */
694
695 int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it)
696 {
697         ASN1_VALUE **opval = NULL;
698         ASN1_STRING *stmp;
699         ASN1_TYPE *typ = NULL;
700         int ret = 0;
701         const ASN1_PRIMITIVE_FUNCS *pf;
702         ASN1_INTEGER **tint;
703         pf = it->funcs;
704         if(pf && pf->prim_c2i) return pf->prim_c2i(pval, cont, len, utype, free_cont, it);
705         /* If ANY type clear type and set pointer to internal value */
706         if(it->utype == V_ASN1_ANY) {
707                 if(!*pval) {
708                         typ = ASN1_TYPE_new();
709                         *pval = (ASN1_VALUE *)typ;
710                 } else typ = (ASN1_TYPE *)*pval;
711                 if(utype != typ->type) ASN1_TYPE_set(typ, utype, NULL);
712                 opval = pval;
713                 pval = (ASN1_VALUE **)&typ->value.ptr;
714         }
715         switch(utype) {
716                 case V_ASN1_OBJECT:
717                 if(!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len)) goto err;
718                 break;
719
720                 case V_ASN1_NULL:
721                 if(len) {
722                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_NULL_IS_WRONG_LENGTH);
723                         goto err;
724                 }
725                 *pval = (ASN1_VALUE *)1;
726                 break;
727
728                 case V_ASN1_BOOLEAN:
729                 if(len != 1) {
730                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
731                         goto err;
732                 } else {
733                         ASN1_BOOLEAN *tbool;
734                         tbool = (ASN1_BOOLEAN *)pval;
735                         *tbool = *cont;
736                 }
737                 break;
738
739                 case V_ASN1_BIT_STRING:
740                 if(!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len)) goto err;
741                 break;
742
743                 case V_ASN1_INTEGER:
744                 case V_ASN1_NEG_INTEGER:
745                 case V_ASN1_ENUMERATED:
746                 case V_ASN1_NEG_ENUMERATED:
747                 tint = (ASN1_INTEGER **)pval;
748                 if(!c2i_ASN1_INTEGER(tint, &cont, len)) goto err;
749                 /* Fixup type to match the expected form */
750                 (*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
751                 break;
752
753                 case V_ASN1_OCTET_STRING:
754                 case V_ASN1_NUMERICSTRING:
755                 case V_ASN1_PRINTABLESTRING:
756                 case V_ASN1_T61STRING:
757                 case V_ASN1_VIDEOTEXSTRING:
758                 case V_ASN1_IA5STRING:
759                 case V_ASN1_UTCTIME:
760                 case V_ASN1_GENERALIZEDTIME:
761                 case V_ASN1_GRAPHICSTRING:
762                 case V_ASN1_VISIBLESTRING:
763                 case V_ASN1_GENERALSTRING:
764                 case V_ASN1_UNIVERSALSTRING:
765                 case V_ASN1_BMPSTRING:
766                 case V_ASN1_UTF8STRING:
767                 case V_ASN1_OTHER:
768                 case V_ASN1_SET:
769                 case V_ASN1_SEQUENCE:
770                 default:
771                 /* All based on ASN1_STRING and handled the same */
772                 if(!*pval) {
773                         stmp = ASN1_STRING_type_new(utype);
774                         if(!stmp) {
775                                 ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_MALLOC_FAILURE);
776                                 goto err;
777                         }
778                         *pval = (ASN1_VALUE *)stmp;
779                 } else {
780                         stmp = (ASN1_STRING *)*pval;
781                         stmp->type = utype;
782                 }
783                 /* If we've already allocated a buffer use it */
784                 if(*free_cont) {
785                         if(stmp->data) OPENSSL_free(stmp->data);
786                         stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */
787                         stmp->length = len;
788                         *free_cont = 0;
789                 } else {
790                         if(!ASN1_STRING_set(stmp, cont, len)) {
791                                 ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_MALLOC_FAILURE);
792                                 ASN1_STRING_free(stmp); 
793                                 *pval = NULL;
794                                 goto err;
795                         }
796                 }
797                 break;
798         }
799         /* If ASN1_ANY and NULL type fix up value */
800         if(typ && utype==V_ASN1_NULL) typ->value.ptr = NULL;
801
802         ret = 1;
803         err:
804         if(!ret)
805                 {
806                 ASN1_TYPE_free(typ);
807                 if (opval)
808                         *opval = NULL;
809                 }
810         return ret;
811 }
812
813 /* This function collects the asn1 data from a constructred string
814  * type into a buffer. The values of 'in' and 'len' should refer
815  * to the contents of the constructed type and 'inf' should be set
816  * if it is indefinite length. If 'buf' is NULL then we just want
817  * to find the end of the current structure: useful for indefinite
818  * length constructed stuff.
819  */
820
821 static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len, char inf, int tag, int aclass)
822 {
823         const unsigned char *p, *q;
824         long plen;
825         char cst, ininf;
826         p = *in;
827         inf &= 1;
828         /* If no buffer and not indefinite length constructed just pass over the encoded data */
829         if(!buf && !inf) {
830                 *in += len;
831                 return 1;
832         }
833         while(len > 0) {
834                 q = p;
835                 /* Check for EOC */
836                 if(asn1_check_eoc(&p, len)) {
837                         /* EOC is illegal outside indefinite length constructed form */
838                         if(!inf) {
839                                 ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_UNEXPECTED_EOC);
840                                 return 0;
841                         }
842                         inf = 0;
843                         break;
844                 }
845                 if(!asn1_check_tlen(&plen, NULL, NULL, &ininf, &cst, &p, len, tag, aclass, 0, NULL)) {
846                         ASN1err(ASN1_F_ASN1_COLLECT, ERR_R_NESTED_ASN1_ERROR);
847                         return 0;
848                 }
849                 /* If indefinite length constructed update max length */
850                 if(cst) {
851                         if(!asn1_collect(buf, &p, plen, ininf, tag, aclass)) return 0;
852                 } else {
853                         if(!collect_data(buf, &p, plen)) return 0;
854                 }
855                 len -= p - q;
856         }
857         if(inf) {
858                 ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_MISSING_EOC);
859                 return 0;
860         }
861         *in = p;
862         return 1;
863 }
864
865 static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen)
866 {
867                 int len;
868                 if(buf) {
869                         len = buf->length;
870                         if(!BUF_MEM_grow_clean(buf, len + plen)) {
871                                 ASN1err(ASN1_F_COLLECT_DATA, ERR_R_MALLOC_FAILURE);
872                                 return 0;
873                         }
874                         memcpy(buf->data + len, *p, plen);
875                 }
876                 *p += plen;
877                 return 1;
878 }
879
880 /* Check for ASN1 EOC and swallow it if found */
881
882 static int asn1_check_eoc(const unsigned char **in, long len)
883 {
884         const unsigned char *p;
885         if(len < 2) return 0;
886         p = *in;
887         if(!p[0] && !p[1]) {
888                 *in += 2;
889                 return 1;
890         }
891         return 0;
892 }
893
894 /* Check an ASN1 tag and length: a bit like ASN1_get_object
895  * but it sets the length for indefinite length constructed
896  * form, we don't know the exact length but we can set an
897  * upper bound to the amount of data available minus the
898  * header length just read.
899  */
900
901 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass, char *inf, char *cst,
902                 const unsigned char **in, long len, int exptag, int expclass, char opt, ASN1_TLC *ctx)
903 {
904         int i;
905         int ptag, pclass;
906         long plen;
907         const unsigned char *p, *q;
908         p = *in;
909         q = p;
910
911         if(ctx && ctx->valid) {
912                 i = ctx->ret;
913                 plen = ctx->plen;
914                 pclass = ctx->pclass;
915                 ptag = ctx->ptag;
916                 p += ctx->hdrlen;
917         } else {
918                 i = ASN1_get_object(&p, &plen, &ptag, &pclass, len);
919                 if(ctx) {
920                         ctx->ret = i;
921                         ctx->plen = plen;
922                         ctx->pclass = pclass;
923                         ctx->ptag = ptag;
924                         ctx->hdrlen = p - q;
925                         ctx->valid = 1;
926                         /* If definite length, and no error, length +
927                          * header can't exceed total amount of data available. 
928                          */
929                         if(!(i & 0x81) && ((plen + ctx->hdrlen) > len)) {
930                                 ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_TOO_LONG);
931                                 asn1_tlc_clear(ctx);
932                                 return 0;
933                         }
934                 }
935         }
936
937         if(i & 0x80) {
938                 ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_BAD_OBJECT_HEADER);
939                 asn1_tlc_clear(ctx);
940                 return 0;
941         }
942         if(exptag >= 0) {
943                 if((exptag != ptag) || (expclass != pclass)) {
944                         /* If type is OPTIONAL, not an error, but indicate missing
945                          * type.
946                          */
947                         if(opt) return -1;
948                         asn1_tlc_clear(ctx);
949                         ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_WRONG_TAG);
950                         return 0;
951                 }
952                 /* We have a tag and class match, so assume we are going to do something with it */
953                 asn1_tlc_clear(ctx);
954         }
955
956         if(i & 1) plen = len - (p - q);
957
958         if(inf) *inf = i & 1;
959
960         if(cst) *cst = i & V_ASN1_CONSTRUCTED;
961
962         if(olen) *olen = plen;
963         if(oclass) *oclass = pclass;
964         if(otag) *otag = ptag;
965
966         *in = p;
967         return 1;
968 }