Fix typo in OCSP nonce extension.
[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 = (unsigned char)((*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 = (char)(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                         if(!asn1_collect(NULL, &p, plen, inf, -1, -1)) goto err;
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                 if(!asn1_collect(&buf, &p, plen, inf, -1, V_ASN1_UNIVERSAL)) goto err;
627                 len = buf.length;
628                 /* Append a final null to string */
629                 if(!BUF_MEM_grow(&buf, len + 1)) {
630                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_MALLOC_FAILURE);
631                         return 0;
632                 }
633                 buf.data[len] = 0;
634                 cont = (unsigned char *)buf.data;
635                 free_cont = 1;
636         } else {
637                 cont = p;
638                 len = plen;
639                 p += plen;
640         }
641
642         /* We now have content length and type: translate into a structure */
643         if(!asn1_ex_c2i(pval, cont, len, utype, &free_cont, it)) goto err;
644
645         *in = p;
646         ret = 1;
647         err:
648         if(free_cont && buf.data) OPENSSL_free(buf.data);
649         return ret;
650 }
651
652 /* Translate ASN1 content octets into a structure */
653
654 int asn1_ex_c2i(ASN1_VALUE **pval, unsigned char *cont, int len, int utype, char *free_cont, const ASN1_ITEM *it)
655 {
656         ASN1_STRING *stmp;
657         ASN1_TYPE *typ = NULL;
658         int ret = 0;
659         const ASN1_PRIMITIVE_FUNCS *pf;
660         ASN1_INTEGER **tint;
661         pf = it->funcs;
662         if(pf && pf->prim_c2i) return pf->prim_c2i(pval, cont, len, utype, free_cont, it);
663         /* If ANY type clear type and set pointer to internal value */
664         if(it->utype == V_ASN1_ANY) {
665                 if(!*pval) {
666                         typ = ASN1_TYPE_new();
667                         *pval = (ASN1_VALUE *)typ;
668                 } else typ = (ASN1_TYPE *)*pval;
669                 if(utype != typ->type) ASN1_TYPE_set(typ, utype, NULL);
670                 pval = (ASN1_VALUE **)&typ->value.ptr;
671         }
672         switch(utype) {
673                 case V_ASN1_OBJECT:
674                 if(!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len)) goto err;
675                 break;
676
677                 case V_ASN1_NULL:
678                 if(len) {
679                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_NULL_IS_WRONG_LENGTH);
680                         goto err;
681                 }
682                 *pval = (ASN1_VALUE *)1;
683                 break;
684
685                 case V_ASN1_BOOLEAN:
686                 if(len != 1) {
687                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
688                         goto err;
689                 } else {
690                         ASN1_BOOLEAN *tbool;
691                         tbool = (ASN1_BOOLEAN *)pval;
692                         *tbool = *cont;
693                 }
694                 break;
695
696                 case V_ASN1_BIT_STRING:
697                 if(!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len)) goto err;
698                 break;
699
700                 case V_ASN1_INTEGER:
701                 case V_ASN1_NEG_INTEGER:
702                 case V_ASN1_ENUMERATED:
703                 case V_ASN1_NEG_ENUMERATED:
704                 tint = (ASN1_INTEGER **)pval;
705                 if(!c2i_ASN1_INTEGER(tint, &cont, len)) goto err;
706                 /* Fixup type to match the expected form */
707                 (*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
708                 break;
709
710                 case V_ASN1_OCTET_STRING:
711                 case V_ASN1_NUMERICSTRING:
712                 case V_ASN1_PRINTABLESTRING:
713                 case V_ASN1_T61STRING:
714                 case V_ASN1_VIDEOTEXSTRING:
715                 case V_ASN1_IA5STRING:
716                 case V_ASN1_UTCTIME:
717                 case V_ASN1_GENERALIZEDTIME:
718                 case V_ASN1_GRAPHICSTRING:
719                 case V_ASN1_VISIBLESTRING:
720                 case V_ASN1_GENERALSTRING:
721                 case V_ASN1_UNIVERSALSTRING:
722                 case V_ASN1_BMPSTRING:
723                 case V_ASN1_UTF8STRING:
724                 case V_ASN1_OTHER:
725                 case V_ASN1_SET:
726                 case V_ASN1_SEQUENCE:
727                 default:
728                 /* All based on ASN1_STRING and handled the same */
729                 if(!*pval) {
730                         stmp = ASN1_STRING_type_new(utype);
731                         if(!stmp) {
732                                 ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_MALLOC_FAILURE);
733                                 goto err;
734                         }
735                         *pval = (ASN1_VALUE *)stmp;
736                 } else {
737                         stmp = (ASN1_STRING *)*pval;
738                         stmp->type = utype;
739                 }
740                 /* If we've already allocated a buffer use it */
741                 if(*free_cont) {
742                         if(stmp->data) OPENSSL_free(stmp->data);
743                         stmp->data = cont;
744                         stmp->length = len;
745                         *free_cont = 0;
746                 } else {
747                         if(!ASN1_STRING_set(stmp, cont, len)) {
748                                 ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_MALLOC_FAILURE);
749                                 ASN1_STRING_free(stmp); 
750                                 *pval = NULL;
751                                 goto err;
752                         }
753                 }
754                 break;
755         }
756         /* If ASN1_ANY and NULL type fix up value */
757         if(typ && utype==V_ASN1_NULL) typ->value.ptr = NULL;
758
759         ret = 1;
760         err:
761         if(!ret) ASN1_TYPE_free(typ);
762         return ret;
763 }
764
765 /* This function collects the asn1 data from a constructred string
766  * type into a buffer. The values of 'in' and 'len' should refer
767  * to the contents of the constructed type and 'inf' should be set
768  * if it is indefinite length. If 'buf' is NULL then we just want
769  * to find the end of the current structure: useful for indefinite
770  * length constructed stuff.
771  */
772
773 static int asn1_collect(BUF_MEM *buf, unsigned char **in, long len, char inf, int tag, int aclass)
774 {
775         unsigned char *p, *q;
776         long plen;
777         char cst, ininf;
778         p = *in;
779         inf &= 1;
780         /* If no buffer and not indefinite length constructed just pass over the encoded data */
781         if(!buf && !inf) {
782                 *in += len;
783                 return 1;
784         }
785         while(len > 0) {
786                 q = p;
787                 /* Check for EOC */
788                 if(asn1_check_eoc(&p, len)) {
789                         /* EOC is illegal outside indefinite length constructed form */
790                         if(!inf) {
791                                 ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_UNEXPECTED_EOC);
792                                 return 0;
793                         }
794                         inf = 0;
795                         break;
796                 }
797                 if(!asn1_check_tlen(&plen, NULL, NULL, &ininf, &cst, &p, len, tag, aclass, 0, NULL)) {
798                         ASN1err(ASN1_F_ASN1_COLLECT, ERR_R_NESTED_ASN1_ERROR);
799                         return 0;
800                 }
801                 /* If indefinite length constructed update max length */
802                 if(cst) {
803                         if(!asn1_collect(buf, &p, plen, ininf, tag, aclass)) return 0;
804                 } else {
805                         if(!collect_data(buf, &p, plen)) return 0;
806                 }
807                 len -= p - q;
808         }
809         if(inf) {
810                 ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_MISSING_EOC);
811                 return 0;
812         }
813         *in = p;
814         return 1;
815 }
816
817 static int collect_data(BUF_MEM *buf, unsigned char **p, long plen)
818 {
819                 int len;
820                 if(buf) {
821                         len = buf->length;
822                         if(!BUF_MEM_grow(buf, len + plen)) {
823                                 ASN1err(ASN1_F_COLLECT_DATA, ERR_R_MALLOC_FAILURE);
824                                 return 0;
825                         }
826                         memcpy(buf->data + len, *p, plen);
827                 }
828                 *p += plen;
829                 return 1;
830 }
831
832 /* Check for ASN1 EOC and swallow it if found */
833
834 static int asn1_check_eoc(unsigned char **in, long len)
835 {
836         unsigned char *p;
837         if(len < 2) return 0;
838         p = *in;
839         if(!p[0] && !p[1]) {
840                 *in += 2;
841                 return 1;
842         }
843         return 0;
844 }
845
846 /* Check an ASN1 tag and length: a bit like ASN1_get_object
847  * but it sets the length for indefinite length constructed
848  * form, we don't know the exact length but we can set an
849  * upper bound to the amount of data available minus the
850  * header length just read.
851  */
852
853 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass, char *inf, char *cst,
854                 unsigned char **in, long len, int exptag, int expclass, char opt, ASN1_TLC *ctx)
855 {
856         int i;
857         int ptag, pclass;
858         long plen;
859         unsigned char *p, *q;
860         p = *in;
861         q = p;
862
863         if(ctx && ctx->valid) {
864                 i = ctx->ret;
865                 plen = ctx->plen;
866                 pclass = ctx->pclass;
867                 ptag = ctx->ptag;
868                 p += ctx->hdrlen;
869         } else {
870                 i = ASN1_get_object(&p, &plen, &ptag, &pclass, len);
871                 if(ctx) {
872                         ctx->ret = i;
873                         ctx->plen = plen;
874                         ctx->pclass = pclass;
875                         ctx->ptag = ptag;
876                         ctx->hdrlen = p - q;
877                         ctx->valid = 1;
878                         /* If definite length, length + header can't exceed total
879                          * amount of data available.
880                          */
881                         if(!(i & 1) && ((plen + ctx->hdrlen) > len)) {
882                                 ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_TOO_LONG);
883                                 asn1_tlc_clear(ctx);
884                                 return 0;
885                         }
886                 }
887         }
888                 
889         if(i & 0x80) {
890                 ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_BAD_OBJECT_HEADER);
891                 asn1_tlc_clear(ctx);
892                 return 0;
893         }
894         if(exptag >= 0) {
895                 if((exptag != ptag) || (expclass != pclass)) {
896                         /* If type is OPTIONAL, not an error, but indicate missing
897                          * type.
898                          */
899                         if(opt) return -1;
900                         asn1_tlc_clear(ctx);
901                         ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_WRONG_TAG);
902                         return 0;
903                 }
904                 /* We have a tag and class match, so assume we are going to do something with it */
905                 asn1_tlc_clear(ctx);
906         }
907
908         if(i & 1) plen = len - (p - q);
909
910         if(inf) *inf = i & 1;
911
912         if(cst) *cst = i & V_ASN1_CONSTRUCTED;
913
914         if(olen) *olen = plen;
915         if(oclass) *oclass = pclass;
916         if(otag) *otag = ptag;
917
918         *in = p;
919         return 1;
920 }