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