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