43e1db0f7621883141f7bb412b60b91c1a1e8f66
[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-2004 The OpenSSL Project.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer. 
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in
17  *    the documentation and/or other materials provided with the
18  *    distribution.
19  *
20  * 3. All advertising materials mentioning features or use of this
21  *    software must display the following acknowledgment:
22  *    "This product includes software developed by the OpenSSL Project
23  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
24  *
25  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
26  *    endorse or promote products derived from this software without
27  *    prior written permission. For written permission, please contact
28  *    licensing@OpenSSL.org.
29  *
30  * 5. Products derived from this software may not be called "OpenSSL"
31  *    nor may "OpenSSL" appear in their names without prior written
32  *    permission of the OpenSSL Project.
33  *
34  * 6. Redistributions of any form whatsoever must retain the following
35  *    acknowledgment:
36  *    "This product includes software developed by the OpenSSL Project
37  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
38  *
39  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
40  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
41  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
42  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
43  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
44  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
45  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
46  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
48  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
49  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
50  * OF THE POSSIBILITY OF SUCH DAMAGE.
51  * ====================================================================
52  *
53  * This product includes cryptographic software written by Eric Young
54  * (eay@cryptsoft.com).  This product includes software written by Tim
55  * Hudson (tjh@cryptsoft.com).
56  *
57  */
58
59
60 #include <stddef.h>
61 #include <string.h>
62 #include <openssl/asn1.h>
63 #include <openssl/asn1t.h>
64 #include <openssl/objects.h>
65 #include <openssl/buffer.h>
66 #include <openssl/err.h>
67
68 static int asn1_check_eoc(const unsigned char **in, long len);
69
70 static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
71                                 char inf, int tag, int aclass);
72
73 static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen);
74
75 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
76                                 char *inf, char *cst,
77                                 const unsigned char **in, long len,
78                                 int exptag, int expclass, char opt,
79                                 ASN1_TLC *ctx);
80
81 static int asn1_template_ex_d2i(ASN1_VALUE **pval,
82                                 const unsigned char **in, long len,
83                                 const ASN1_TEMPLATE *tt, char opt,
84                                 ASN1_TLC *ctx);
85 static int asn1_template_noexp_d2i(ASN1_VALUE **val,
86                                 const unsigned char **in, long len,
87                                 const ASN1_TEMPLATE *tt, char opt,
88                                 ASN1_TLC *ctx);
89 static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
90                                 const unsigned char **in, long len,
91                                 const ASN1_ITEM *it,
92                                 int tag, int aclass, char opt, ASN1_TLC *ctx);
93
94 /* Table to convert tags to bit values, used for MSTRING type */
95 static unsigned long tag2bit[32] = {
96 0,      0,      0,      B_ASN1_BIT_STRING,      /* tags  0 -  3 */
97 B_ASN1_OCTET_STRING,    0,      0,              B_ASN1_UNKNOWN,/* tags  4- 7 */
98 B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN, B_ASN1_UNKNOWN,/* tags  8-11 */
99 B_ASN1_UTF8STRING,B_ASN1_UNKNOWN,B_ASN1_UNKNOWN,B_ASN1_UNKNOWN,/* tags 12-15 */
100 0,      0,      B_ASN1_NUMERICSTRING,B_ASN1_PRINTABLESTRING,   /* tags 16-19 */
101 B_ASN1_T61STRING,B_ASN1_VIDEOTEXSTRING,B_ASN1_IA5STRING,       /* tags 20-22 */
102 B_ASN1_UTCTIME, B_ASN1_GENERALIZEDTIME,                        /* tags 23-24 */ 
103 B_ASN1_GRAPHICSTRING,B_ASN1_ISO64STRING,B_ASN1_GENERALSTRING,  /* tags 25-27 */
104 B_ASN1_UNIVERSALSTRING,B_ASN1_UNKNOWN,B_ASN1_BMPSTRING,B_ASN1_UNKNOWN, /* tags 28-31 */
105         };
106
107 unsigned long ASN1_tag2bit(int tag)
108         {
109         if ((tag < 0) || (tag > 30)) return 0;
110         return tag2bit[tag];
111         }
112
113 /* Macro to initialize and invalidate the cache */
114
115 #define asn1_tlc_clear(c)       if (c) (c)->valid = 0
116
117 /* Decode an ASN1 item, this currently behaves just 
118  * like a standard 'd2i' function. 'in' points to 
119  * a buffer to read the data from, in future we will
120  * have more advanced versions that can input data
121  * a piece at a time and this will simply be a special
122  * case.
123  */
124
125 ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval,
126                 const unsigned char **in, long len, const ASN1_ITEM *it)
127         {
128         ASN1_TLC c;
129         ASN1_VALUE *ptmpval = NULL;
130         if (!pval)
131                 pval = &ptmpval;
132         asn1_tlc_clear(&c);
133         if (ASN1_item_ex_d2i(pval, in, len, it, -1, 0, 0, &c) > 0) 
134                 return *pval;
135         return NULL;
136         }
137
138 int ASN1_template_d2i(ASN1_VALUE **pval,
139                 const unsigned char **in, long len, const ASN1_TEMPLATE *tt)
140         {
141         ASN1_TLC c;
142         asn1_tlc_clear(&c);
143         return asn1_template_ex_d2i(pval, in, len, tt, 0, &c);
144         }
145
146
147 /* Decode an item, taking care of IMPLICIT tagging, if any.
148  * If 'opt' set and tag mismatch return -1 to handle OPTIONAL
149  */
150
151 int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
152                         const ASN1_ITEM *it,
153                         int tag, int aclass, char opt, ASN1_TLC *ctx)
154         {
155         const ASN1_TEMPLATE *tt, *errtt = NULL;
156         const ASN1_COMPAT_FUNCS *cf;
157         const ASN1_EXTERN_FUNCS *ef;
158         const ASN1_AUX *aux = it->funcs;
159         ASN1_aux_cb *asn1_cb;
160         const unsigned char *p, *q;
161         unsigned char *wp=NULL; /* BIG FAT WARNING!  BREAKS CONST WHERE USED */
162         unsigned char imphack = 0, oclass;
163         char seq_eoc, seq_nolen, cst, isopt;
164         long tmplen;
165         int i;
166         int otag;
167         int ret = 0;
168         ASN1_VALUE *pchval, **pchptr, *ptmpval;
169         if (!pval)
170                 return 0;
171         if (aux && aux->asn1_cb)
172                 asn1_cb = aux->asn1_cb;
173         else asn1_cb = 0;
174
175         switch(it->itype)
176                 {
177                 case ASN1_ITYPE_PRIMITIVE:
178                 if (it->templates)
179                         {
180                         /* tagging or OPTIONAL is currently illegal on an item
181                          * template because the flags can't get passed down.
182                          * In practice this isn't a problem: we include the
183                          * relevant flags from the item template in the
184                          * template itself.
185                          */
186                         if ((tag != -1) || opt)
187                                 {
188                                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
189                                 ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
190                                 goto err;
191                                 }
192                         return asn1_template_ex_d2i(pval, in, len,
193                                         it->templates, opt, ctx);
194                 }
195                 return asn1_d2i_ex_primitive(pval, in, len, it,
196                                                 tag, aclass, opt, ctx);
197                 break;
198
199                 case ASN1_ITYPE_MSTRING:
200                 p = *in;
201                 /* Just read in tag and class */
202                 ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,
203                                                 &p, len, -1, 0, 1, ctx);
204                 if (!ret)
205                         {
206                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
207                                         ERR_R_NESTED_ASN1_ERROR);
208                         goto err;
209                         }
210
211                 /* Must be UNIVERSAL class */
212                 if (oclass != V_ASN1_UNIVERSAL)
213                         {
214                         /* If OPTIONAL, assume this is OK */
215                         if (opt) return -1;
216                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
217                                         ASN1_R_MSTRING_NOT_UNIVERSAL);
218                         goto err;
219                         }
220                 /* Check tag matches bit map */
221                 if (!(ASN1_tag2bit(otag) & it->utype))
222                         {
223                         /* If OPTIONAL, assume this is OK */
224                         if (opt)
225                                 return -1;
226                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
227                                         ASN1_R_MSTRING_WRONG_TAG);
228                         goto err;
229                         }
230                 return asn1_d2i_ex_primitive(pval, in, len,
231                                                 it, otag, 0, 0, ctx);
232
233                 case ASN1_ITYPE_EXTERN:
234                 /* Use new style d2i */
235                 ef = it->funcs;
236                 return ef->asn1_ex_d2i(pval, in, len,
237                                                 it, tag, aclass, opt, ctx);
238
239                 case ASN1_ITYPE_COMPAT:
240                 /* we must resort to old style evil hackery */
241                 cf = it->funcs;
242
243                 /* If OPTIONAL see if it is there */
244                 if (opt)
245                         {
246                         int exptag;
247                         p = *in;
248                         if (tag == -1)
249                                 exptag = it->utype;
250                         else exptag = tag;
251                         /* Don't care about anything other than presence
252                          * of expected tag */
253
254                         ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,
255                                         &p, len, exptag, aclass, 1, ctx);
256                         if (!ret)
257                                 {
258                                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
259                                         ERR_R_NESTED_ASN1_ERROR);
260                                 goto err;
261                                 }
262                         if (ret == -1)
263                                 return -1;
264                         }
265
266                 /* This is the old style evil hack IMPLICIT handling:
267                  * since the underlying code is expecting a tag and
268                  * class other than the one present we change the
269                  * buffer temporarily then change it back afterwards.
270                  * This doesn't and never did work for tags > 30.
271                  *
272                  * Yes this is *horrible* but it is only needed for
273                  * old style d2i which will hopefully not be around
274                  * for much longer.
275                  * FIXME: should copy the buffer then modify it so
276                  * the input buffer can be const: we should *always*
277                  * copy because the old style d2i might modify the
278                  * buffer.
279                  */
280
281                 if (tag != -1)
282                         {
283                         wp = *(unsigned char **)in;
284                         imphack = *wp;
285                         *wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)
286                                                                 | it->utype);
287                         }
288
289                 ptmpval = cf->asn1_d2i(pval, in, len);
290
291                 if (tag != -1)
292                         *wp = imphack;
293
294                 if (ptmpval)
295                         return 1;
296
297                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
298                 goto err;
299
300
301                 case ASN1_ITYPE_CHOICE:
302                 if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it))
303                                 goto auxerr;
304
305                 /* Allocate structure */
306                 if (!*pval && !ASN1_item_ex_new(pval, it))
307                         {
308                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
309                                                 ERR_R_NESTED_ASN1_ERROR);
310                         goto err;
311                         }
312                 /* CHOICE type, try each possibility in turn */
313                 pchval = NULL;
314                 p = *in;
315                 for (i = 0, tt=it->templates; i < it->tcount; i++, tt++)
316                         {
317                         pchptr = asn1_get_field_ptr(pval, tt);
318                         /* We mark field as OPTIONAL so its absence
319                          * can be recognised.
320                          */
321                         ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);
322                         /* If field not present, try the next one */
323                         if (ret == -1)
324                                 continue;
325                         /* If positive return, read OK, break loop */
326                         if (ret > 0)
327                                 break;
328                         /* Otherwise must be an ASN1 parsing error */
329                         errtt = tt;
330                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
331                                                 ERR_R_NESTED_ASN1_ERROR);
332                         goto err;
333                         }
334
335                 /* Did we fall off the end without reading anything? */
336                 if (i == it->tcount)
337                         {
338                         /* If OPTIONAL, this is OK */
339                         if (opt)
340                                 {
341                                 /* Free and zero it */
342                                 ASN1_item_ex_free(pval, it);
343                                 return -1;
344                                 }
345                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
346                                         ASN1_R_NO_MATCHING_CHOICE_TYPE);
347                         goto err;
348                         }
349
350                 asn1_set_choice_selector(pval, i, it);
351                 *in = p;
352                 if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it))
353                                 goto auxerr;
354                 return 1;
355
356                 case ASN1_ITYPE_NDEF_SEQUENCE:
357                 case ASN1_ITYPE_SEQUENCE:
358                 p = *in;
359                 tmplen = len;
360
361                 /* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
362                 if (tag == -1)
363                         {
364                         tag = V_ASN1_SEQUENCE;
365                         aclass = V_ASN1_UNIVERSAL;
366                         }
367                 /* Get SEQUENCE length and update len, p */
368                 ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,
369                                         &p, len, tag, aclass, opt, ctx);
370                 if (!ret)
371                         {
372                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
373                                         ERR_R_NESTED_ASN1_ERROR);
374                         goto err;
375                         }
376                 else if (ret == -1)
377                         return -1;
378                 if (aux && (aux->flags & ASN1_AFLG_BROKEN))
379                         {
380                         len = tmplen - (p - *in);
381                         seq_nolen = 1;
382                         }
383                 /* If indefinite we don't do a length check */
384                 else seq_nolen = seq_eoc;
385                 if (!cst)
386                         {
387                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
388                                 ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
389                         goto err;
390                         }
391
392                 if (!*pval && !!ASN1_item_ex_new(pval, it))
393                         {
394                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
395                                 ERR_R_NESTED_ASN1_ERROR);
396                         goto err;
397                         }
398
399                 if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it))
400                                 goto auxerr;
401
402                 /* Get each field entry */
403                 for (i = 0, tt = it->templates; i < it->tcount; i++, tt++)
404                         {
405                         const ASN1_TEMPLATE *seqtt;
406                         ASN1_VALUE **pseqval;
407                         seqtt = asn1_do_adb(pval, tt, 1);
408                         if (!seqtt)
409                                 goto err;
410                         pseqval = asn1_get_field_ptr(pval, seqtt);
411                         /* Have we ran out of data? */
412                         if (!len)
413                                 break;
414                         q = p;
415                         if (asn1_check_eoc(&p, len))
416                                 {
417                                 if (!seq_eoc)
418                                         {
419                                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
420                                                         ASN1_R_UNEXPECTED_EOC);
421                                         goto err;
422                                         }
423                                 len -= p - q;
424                                 seq_eoc = 0;
425                                 q = p;
426                                 break;
427                                 }
428                         /* This determines the OPTIONAL flag value. The field
429                          * cannot be omitted if it is the last of a SEQUENCE
430                          * and there is still data to be read. This isn't
431                          * strictly necessary but it increases efficiency in
432                          * some cases.
433                          */
434                         if (i == (it->tcount - 1))
435                                 isopt = 0;
436                         else isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
437                         /* attempt to read in field, allowing each to be
438                          * OPTIONAL */
439
440                         ret = asn1_template_ex_d2i(pseqval, &p, len,
441                                                         seqtt, isopt, ctx);
442                         if (!ret)
443                                 {
444                                 errtt = seqtt;
445                                 goto err;
446                                 }
447                         else if (ret == -1)
448                                 {
449                                 /* OPTIONAL component absent.
450                                  * Free and zero the field.
451                                  */
452                                 ASN1_template_free(pseqval, seqtt);
453                                 continue;
454                                 }
455                         /* Update length */
456                         len -= p - q;
457                         }
458
459                 /* Check for EOC if expecting one */
460                 if (seq_eoc && !asn1_check_eoc(&p, len))
461                         {
462                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);
463                         goto err;
464                         }
465                 /* Check all data read */
466                 if (!seq_nolen && len)
467                         {
468                         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
469                                         ASN1_R_SEQUENCE_LENGTH_MISMATCH);
470                         goto err;
471                         }
472
473                 /* If we get here we've got no more data in the SEQUENCE,
474                  * however we may not have read all fields so check all
475                  * remaining are OPTIONAL and clear any that are.
476                  */
477                 for (; i < it->tcount; tt++, i++)
478                         {
479                         const ASN1_TEMPLATE *seqtt;
480                         seqtt = asn1_do_adb(pval, tt, 1);
481                         if (!seqtt)
482                                 goto err;
483                         if (seqtt->flags & ASN1_TFLG_OPTIONAL)
484                                 {
485                                 ASN1_VALUE **pseqval;
486                                 pseqval = asn1_get_field_ptr(pval, seqtt);
487                                 ASN1_template_free(pseqval, seqtt);
488                                 }
489                         else
490                                 {
491                                 errtt = seqtt;
492                                 ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
493                                                         ASN1_R_FIELD_MISSING);
494                                 goto err;
495                                 }
496                         }
497                 /* Save encoding */
498                 if (!asn1_enc_save(pval, *in, p - *in, it))
499                         goto auxerr;
500                 *in = p;
501                 if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it))
502                                 goto auxerr;
503                 return 1;
504
505                 default:
506                 return 0;
507                 }
508         auxerr:
509         ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);
510         err:
511         ASN1_item_ex_free(pval, it);
512         if (errtt)
513                 ERR_add_error_data(4, "Field=", errtt->field_name,
514                                         ", Type=", it->sname);
515         else
516                 ERR_add_error_data(2, "Type=", it->sname);
517         return 0;
518         }
519
520 /* Templates are handled with two separate functions.
521  * One handles any EXPLICIT tag and the other handles the rest.
522  */
523
524 static int asn1_template_ex_d2i(ASN1_VALUE **val,
525                                 const unsigned char **in, long inlen,
526                                 const ASN1_TEMPLATE *tt, char opt,
527                                                         ASN1_TLC *ctx)
528         {
529         int flags, aclass;
530         int ret;
531         long len;
532         const unsigned char *p, *q;
533         char exp_eoc;
534         if (!val)
535                 return 0;
536         flags = tt->flags;
537         aclass = flags & ASN1_TFLG_TAG_CLASS;
538
539         p = *in;
540
541         /* Check if EXPLICIT tag expected */
542         if (flags & ASN1_TFLG_EXPTAG)
543                 {
544                 char cst;
545                 /* Need to work out amount of data available to the inner
546                  * content and where it starts: so read in EXPLICIT header to
547                  * get the info.
548                  */
549                 ret = asn1_check_tlen(&len, NULL, NULL, &exp_eoc, &cst,
550                                         &p, inlen, tt->tag, aclass, opt, ctx);
551                 q = p;
552                 if (!ret)
553                         {
554                         ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
555                                         ERR_R_NESTED_ASN1_ERROR);
556                         return 0;
557                         }
558                 else if (ret == -1)
559                         return -1;
560                 if (!cst)
561                         {
562                         ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
563                                         ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);
564                         return 0;
565                         }
566                 /* We've found the field so it can't be OPTIONAL now */
567                 ret = asn1_template_noexp_d2i(val, &p, len, tt, 0, ctx);
568                 if (!ret)
569                         {
570                         ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
571                                         ERR_R_NESTED_ASN1_ERROR);
572                         return 0;
573                         }
574                 /* We read the field in OK so update length */
575                 len -= p - q;
576                 if (exp_eoc)
577                         {
578                         /* If NDEF we must have an EOC here */
579                         if (!asn1_check_eoc(&p, len))
580                                 {
581                                 ASN1err(ASN1_F_ASN1_TEMPLATE_D2I,
582                                                 ASN1_R_MISSING_EOC);
583                                 goto err;
584                                 }
585                         }
586                 else
587                         {
588                         /* Otherwise we must hit the EXPLICIT tag end or its
589                          * an error */
590                         if (len)
591                                 {
592                                 ASN1err(ASN1_F_ASN1_TEMPLATE_D2I,
593                                         ASN1_R_EXPLICIT_LENGTH_MISMATCH);
594                                 goto err;
595                                 }
596                         }
597                 }
598                 else 
599                         return asn1_template_noexp_d2i(val, in, inlen,
600                                                                 tt, opt, ctx);
601
602         *in = p;
603         return 1;
604
605         err:
606         ASN1_template_free(val, tt);
607         *val = NULL;
608         return 0;
609         }
610
611 static int asn1_template_noexp_d2i(ASN1_VALUE **val,
612                                 const unsigned char **in, long len,
613                                 const ASN1_TEMPLATE *tt, char opt,
614                                 ASN1_TLC *ctx)
615         {
616         int flags, aclass;
617         int ret;
618         const unsigned char *p, *q;
619         if (!val)
620                 return 0;
621         flags = tt->flags;
622         aclass = flags & ASN1_TFLG_TAG_CLASS;
623
624         p = *in;
625         q = p;
626
627         if (flags & ASN1_TFLG_SK_MASK)
628                 {
629                 /* SET OF, SEQUENCE OF */
630                 int sktag, skaclass;
631                 char sk_eoc;
632                 /* First work out expected inner tag value */
633                 if (flags & ASN1_TFLG_IMPTAG)
634                         {
635                         sktag = tt->tag;
636                         skaclass = aclass;
637                         }
638                 else
639                         {
640                         skaclass = V_ASN1_UNIVERSAL;
641                         if (flags & ASN1_TFLG_SET_OF)
642                                 sktag = V_ASN1_SET;
643                         else
644                                 sktag = V_ASN1_SEQUENCE;
645                         }
646                 /* Get the tag */
647                 ret = asn1_check_tlen(&len, NULL, NULL, &sk_eoc, NULL,
648                                         &p, len, sktag, skaclass, opt, ctx);
649                 if (!ret)
650                         {
651                         ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
652                                                 ERR_R_NESTED_ASN1_ERROR);
653                         return 0;
654                         }
655                 else if (ret == -1)
656                         return -1;
657                 if (!*val)
658                         *val = (ASN1_VALUE *)sk_new_null();
659                 else
660                         {
661                         /* We've got a valid STACK: free up any items present */
662                         STACK *sktmp = (STACK *)*val;
663                         ASN1_VALUE *vtmp;
664                         while(sk_num(sktmp) > 0)
665                                 {
666                                 vtmp = (ASN1_VALUE *)sk_pop(sktmp);
667                                 ASN1_item_ex_free(&vtmp,
668                                                 ASN1_ITEM_ptr(tt->item));
669                                 }
670                         }
671                                 
672                 if (!*val)
673                         {
674                         ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
675                                                 ERR_R_MALLOC_FAILURE);
676                         goto err;
677                         }
678
679                 /* Read as many items as we can */
680                 while(len > 0)
681                         {
682                         ASN1_VALUE *skfield;
683                         q = p;
684                         /* See if EOC found */
685                         if (asn1_check_eoc(&p, len))
686                                 {
687                                 if (!sk_eoc)
688                                         {
689                                         ASN1err(ASN1_F_ASN1_TEMPLATE_D2I,
690                                                         ASN1_R_UNEXPECTED_EOC);
691                                         goto err;
692                                         }
693                                 len -= p - q;
694                                 sk_eoc = 0;
695                                 break;
696                                 }
697                         skfield = NULL;
698                         if (!ASN1_item_ex_d2i(&skfield, &p, len,
699                                                 ASN1_ITEM_ptr(tt->item),
700                                                 -1, 0, 0, ctx))
701                                 {
702                                 ASN1err(ASN1_F_ASN1_TEMPLATE_D2I,
703                                         ERR_R_NESTED_ASN1_ERROR);
704                                 goto err;
705                                 }
706                         len -= p - q;
707                         if (!sk_push((STACK *)*val, (char *)skfield))
708                                 {
709                                 ASN1err(ASN1_F_ASN1_TEMPLATE_D2I,
710                                                 ERR_R_MALLOC_FAILURE);
711                                 goto err;
712                                 }
713                         }
714                 if (sk_eoc)
715                         {
716                         ASN1err(ASN1_F_ASN1_TEMPLATE_D2I, ASN1_R_MISSING_EOC);
717                         goto err;
718                         }
719                 }
720         else if (flags & ASN1_TFLG_IMPTAG)
721                 {
722                 /* IMPLICIT tagging */
723                 ret = ASN1_item_ex_d2i(val, &p, len,
724                         ASN1_ITEM_ptr(tt->item), tt->tag, aclass, opt, ctx);
725                 if (!ret)
726                         {
727                         ASN1err(ASN1_F_ASN1_TEMPLATE_D2I,
728                                                 ERR_R_NESTED_ASN1_ERROR);
729                         goto err;
730                         }
731                 else if (ret == -1)
732                         return -1;
733                 }
734         else
735                 {
736                 /* Nothing special */
737                 ret = ASN1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item),
738                                                         -1, 0, opt, ctx);
739                 if (!ret)
740                         {
741                         ASN1err(ASN1_F_ASN1_TEMPLATE_D2I,
742                                         ERR_R_NESTED_ASN1_ERROR);
743                         goto err;
744                         }
745                 else if (ret == -1)
746                         return -1;
747                 }
748
749         *in = p;
750         return 1;
751
752         err:
753         ASN1_template_free(val, tt);
754         *val = NULL;
755         return 0;
756         }
757
758 static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
759                                 const unsigned char **in, long inlen, 
760                                 const ASN1_ITEM *it,
761                                 int tag, int aclass, char opt, ASN1_TLC *ctx)
762         {
763         int ret = 0, utype;
764         long plen;
765         char cst, inf, free_cont = 0;
766         const unsigned char *p;
767         BUF_MEM buf;
768         const unsigned char *cont = NULL;
769         long len; 
770         if (!pval)
771                 {
772                 ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_NULL);
773                 return 0; /* Should never happen */
774                 }
775
776         if (it->itype == ASN1_ITYPE_MSTRING)
777                 {
778                 utype = tag;
779                 tag = -1;
780                 }
781         else
782                 utype = it->utype;
783
784         if (utype == V_ASN1_ANY)
785                 {
786                 /* If type is ANY need to figure out type from tag */
787                 unsigned char oclass;
788                 if (tag >= 0)
789                         {
790                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
791                                         ASN1_R_ILLEGAL_TAGGED_ANY);
792                         return 0;
793                         }
794                 if (opt)
795                         {
796                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
797                                         ASN1_R_ILLEGAL_OPTIONAL_ANY);
798                         return 0;
799                         }
800                 p = *in;
801                 ret = asn1_check_tlen(NULL, &utype, &oclass, NULL, NULL,
802                                         &p, inlen, -1, 0, 0, ctx);
803                 if (!ret)
804                         {
805                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
806                                         ERR_R_NESTED_ASN1_ERROR);
807                         return 0;
808                         }
809                 if (oclass != V_ASN1_UNIVERSAL)
810                         utype = V_ASN1_OTHER;
811                 }
812         if (tag == -1)
813                 {
814                 tag = utype;
815                 aclass = V_ASN1_UNIVERSAL;
816                 }
817         p = *in;
818         /* Check header */
819         ret = asn1_check_tlen(&plen, NULL, NULL, &inf, &cst,
820                                 &p, inlen, tag, aclass, opt, ctx);
821         if (!ret)
822                 {
823                 ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
824                 return 0;
825                 }
826         else if (ret == -1)
827                 return -1;
828         /* SEQUENCE, SET and "OTHER" are left in encoded form */
829         if ((utype == V_ASN1_SEQUENCE)
830                 || (utype == V_ASN1_SET) || (utype == V_ASN1_OTHER))
831                 {
832                 /* Clear context cache for type OTHER because the auto clear
833                  * when we have a exact match wont work
834                  */
835                 if (utype == V_ASN1_OTHER)
836                         {
837                         asn1_tlc_clear(ctx);
838                         }
839                 /* SEQUENCE and SET must be constructed */
840                 else if (!cst)
841                         {
842                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
843                                 ASN1_R_TYPE_NOT_CONSTRUCTED);
844                         return 0;
845                         }
846
847                 cont = *in;
848                 /* If indefinite length constructed find the real end */
849                 if (inf)
850                         {
851                         if (!asn1_collect(NULL, &p, plen, inf, -1, -1))
852                                  goto err;
853                         len = p - cont;
854                         }
855                 else
856                         {
857                         len = p - cont + plen;
858                         p += plen;
859                         buf.data = NULL;
860                         }
861                 }
862         else if (cst)
863                 {
864                 buf.length = 0;
865                 buf.max = 0;
866                 buf.data = NULL;
867                 /* Should really check the internal tags are correct but
868                  * some things may get this wrong. The relevant specs
869                  * say that constructed string types should be OCTET STRINGs
870                  * internally irrespective of the type. So instead just check
871                  * for UNIVERSAL class and ignore the tag.
872                  */
873                 if (!asn1_collect(&buf, &p, plen, inf, -1, V_ASN1_UNIVERSAL))
874                         goto err;
875                 len = buf.length;
876                 /* Append a final null to string */
877                 if (!BUF_MEM_grow_clean(&buf, len + 1))
878                         {
879                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
880                                                 ERR_R_MALLOC_FAILURE);
881                         return 0;
882                         }
883                 buf.data[len] = 0;
884                 cont = (const unsigned char *)buf.data;
885                 free_cont = 1;
886                 }
887         else
888                 {
889                 cont = p;
890                 len = plen;
891                 p += plen;
892                 }
893
894         /* We now have content length and type: translate into a structure */
895         if (!asn1_ex_c2i(pval, cont, len, utype, &free_cont, it))
896                 goto err;
897
898         *in = p;
899         ret = 1;
900         err:
901         if (free_cont && buf.data) OPENSSL_free(buf.data);
902         return ret;
903         }
904
905 /* Translate ASN1 content octets into a structure */
906
907 int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
908                         int utype, char *free_cont, const ASN1_ITEM *it)
909         {
910         ASN1_VALUE **opval = NULL;
911         ASN1_STRING *stmp;
912         ASN1_TYPE *typ = NULL;
913         int ret = 0;
914         const ASN1_PRIMITIVE_FUNCS *pf;
915         ASN1_INTEGER **tint;
916         pf = it->funcs;
917
918         if (pf && pf->prim_c2i)
919                 return pf->prim_c2i(pval, cont, len, utype, free_cont, it);
920         /* If ANY type clear type and set pointer to internal value */
921         if (it->utype == V_ASN1_ANY)
922                 {
923                 if (!*pval)
924                         {
925                         typ = ASN1_TYPE_new();
926                         *pval = (ASN1_VALUE *)typ;
927                         }
928                 else
929                         typ = (ASN1_TYPE *)*pval;
930
931                 if (utype != typ->type)
932                         ASN1_TYPE_set(typ, utype, NULL);
933                 opval = pval;
934                 pval = (ASN1_VALUE **)&typ->value.ptr;
935                 }
936         switch(utype)
937                 {
938                 case V_ASN1_OBJECT:
939                 if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len))
940                         goto err;
941                 break;
942
943                 case V_ASN1_NULL:
944                 if (len)
945                         {
946                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
947                                                 ASN1_R_NULL_IS_WRONG_LENGTH);
948                         goto err;
949                         }
950                 *pval = (ASN1_VALUE *)1;
951                 break;
952
953                 case V_ASN1_BOOLEAN:
954                 if (len != 1)
955                         {
956                         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
957                                                 ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
958                         goto err;
959                         }
960                 else
961                         {
962                         ASN1_BOOLEAN *tbool;
963                         tbool = (ASN1_BOOLEAN *)pval;
964                         *tbool = *cont;
965                         }
966                 break;
967
968                 case V_ASN1_BIT_STRING:
969                 if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len))
970                         goto err;
971                 break;
972
973                 case V_ASN1_INTEGER:
974                 case V_ASN1_NEG_INTEGER:
975                 case V_ASN1_ENUMERATED:
976                 case V_ASN1_NEG_ENUMERATED:
977                 tint = (ASN1_INTEGER **)pval;
978                 if (!c2i_ASN1_INTEGER(tint, &cont, len))
979                         goto err;
980                 /* Fixup type to match the expected form */
981                 (*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
982                 break;
983
984                 case V_ASN1_OCTET_STRING:
985                 case V_ASN1_NUMERICSTRING:
986                 case V_ASN1_PRINTABLESTRING:
987                 case V_ASN1_T61STRING:
988                 case V_ASN1_VIDEOTEXSTRING:
989                 case V_ASN1_IA5STRING:
990                 case V_ASN1_UTCTIME:
991                 case V_ASN1_GENERALIZEDTIME:
992                 case V_ASN1_GRAPHICSTRING:
993                 case V_ASN1_VISIBLESTRING:
994                 case V_ASN1_GENERALSTRING:
995                 case V_ASN1_UNIVERSALSTRING:
996                 case V_ASN1_BMPSTRING:
997                 case V_ASN1_UTF8STRING:
998                 case V_ASN1_OTHER:
999                 case V_ASN1_SET:
1000                 case V_ASN1_SEQUENCE:
1001                 default:
1002                 /* All based on ASN1_STRING and handled the same */
1003                 if (!*pval)
1004                         {
1005                         stmp = ASN1_STRING_type_new(utype);
1006                         if (!stmp)
1007                                 {
1008                                 ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
1009                                                         ERR_R_MALLOC_FAILURE);
1010                                 goto err;
1011                                 }
1012                         *pval = (ASN1_VALUE *)stmp;
1013                         }
1014                 else
1015                         {
1016                         stmp = (ASN1_STRING *)*pval;
1017                         stmp->type = utype;
1018                         }
1019                 /* If we've already allocated a buffer use it */
1020                 if (*free_cont)
1021                         {
1022                         if (stmp->data)
1023                                 OPENSSL_free(stmp->data);
1024                         stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */
1025                         stmp->length = len;
1026                         *free_cont = 0;
1027                         }
1028                 else
1029                         {
1030                         if (!ASN1_STRING_set(stmp, cont, len))
1031                                 {
1032                                 ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
1033                                                         ERR_R_MALLOC_FAILURE);
1034                                 ASN1_STRING_free(stmp); 
1035                                 *pval = NULL;
1036                                 goto err;
1037                                 }
1038                         }
1039                 break;
1040                 }
1041         /* If ASN1_ANY and NULL type fix up value */
1042         if (typ && (utype == V_ASN1_NULL))
1043                  typ->value.ptr = NULL;
1044
1045         ret = 1;
1046         err:
1047         if (!ret)
1048                 {
1049                 ASN1_TYPE_free(typ);
1050                 if (opval)
1051                         *opval = NULL;
1052                 }
1053         return ret;
1054         }
1055
1056 /* This function collects the asn1 data from a constructred string
1057  * type into a buffer. The values of 'in' and 'len' should refer
1058  * to the contents of the constructed type and 'inf' should be set
1059  * if it is indefinite length. If 'buf' is NULL then we just want
1060  * to find the end of the current structure: useful for indefinite
1061  * length constructed stuff.
1062  */
1063
1064 static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
1065                                 char inf, int tag, int aclass)
1066         {
1067         const unsigned char *p, *q;
1068         long plen;
1069         char cst, ininf;
1070         p = *in;
1071         inf &= 1;
1072         /* If no buffer and not indefinite length constructed just pass over
1073          * the encoded data */
1074         if (!buf && !inf)
1075                 {
1076                 *in += len;
1077                 return 1;
1078                 }
1079         while(len > 0)
1080                 {
1081                 q = p;
1082                 /* Check for EOC */
1083                 if (asn1_check_eoc(&p, len))
1084                         {
1085                         /* EOC is illegal outside indefinite length
1086                          * constructed form */
1087                         if (!inf)
1088                                 {
1089                                 ASN1err(ASN1_F_ASN1_COLLECT,
1090                                         ASN1_R_UNEXPECTED_EOC);
1091                                 return 0;
1092                                 }
1093                         inf = 0;
1094                         break;
1095                         }
1096
1097                 if (!asn1_check_tlen(&plen, NULL, NULL, &ininf, &cst, &p,
1098                                         len, tag, aclass, 0, NULL))
1099                         {
1100                         ASN1err(ASN1_F_ASN1_COLLECT, ERR_R_NESTED_ASN1_ERROR);
1101                         return 0;
1102                         }
1103
1104                 /* If indefinite length constructed update max length */
1105                 if (cst)
1106                         {
1107                         if (!asn1_collect(buf, &p, plen, ininf, tag, aclass))
1108                                 return 0;
1109                         }
1110                 else if (!collect_data(buf, &p, plen))
1111                         return 0;
1112                 len -= p - q;
1113                 }
1114         if (inf)
1115                 {
1116                 ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_MISSING_EOC);
1117                 return 0;
1118                 }
1119         *in = p;
1120         return 1;
1121         }
1122
1123 static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen)
1124         {
1125         int len;
1126         if (buf)
1127                 {
1128                 len = buf->length;
1129                 if (!BUF_MEM_grow_clean(buf, len + plen))
1130                         {
1131                         ASN1err(ASN1_F_COLLECT_DATA, ERR_R_MALLOC_FAILURE);
1132                         return 0;
1133                         }
1134                 memcpy(buf->data + len, *p, plen);
1135                 }
1136         *p += plen;
1137         return 1;
1138         }
1139
1140 /* Check for ASN1 EOC and swallow it if found */
1141
1142 static int asn1_check_eoc(const unsigned char **in, long len)
1143         {
1144         const unsigned char *p;
1145         if (len < 2) return 0;
1146         p = *in;
1147         if (!p[0] && !p[1])
1148                 {
1149                 *in += 2;
1150                 return 1;
1151                 }
1152         return 0;
1153         }
1154
1155 /* Check an ASN1 tag and length: a bit like ASN1_get_object
1156  * but it sets the length for indefinite length constructed
1157  * form, we don't know the exact length but we can set an
1158  * upper bound to the amount of data available minus the
1159  * header length just read.
1160  */
1161
1162 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
1163                                 char *inf, char *cst,
1164                                 const unsigned char **in, long len,
1165                                 int exptag, int expclass, char opt,
1166                                 ASN1_TLC *ctx)
1167         {
1168         int i;
1169         int ptag, pclass;
1170         long plen;
1171         const unsigned char *p, *q;
1172         p = *in;
1173         q = p;
1174
1175         if (ctx && ctx->valid)
1176                 {
1177                 i = ctx->ret;
1178                 plen = ctx->plen;
1179                 pclass = ctx->pclass;
1180                 ptag = ctx->ptag;
1181                 p += ctx->hdrlen;
1182                 }
1183         else
1184                 {
1185                 i = ASN1_get_object(&p, &plen, &ptag, &pclass, len);
1186                 if (ctx)
1187                         {
1188                         ctx->ret = i;
1189                         ctx->plen = plen;
1190                         ctx->pclass = pclass;
1191                         ctx->ptag = ptag;
1192                         ctx->hdrlen = p - q;
1193                         ctx->valid = 1;
1194                         /* If definite length, and no error, length +
1195                          * header can't exceed total amount of data available. 
1196                          */
1197                         if (!(i & 0x81) && ((plen + ctx->hdrlen) > len))
1198                                 {
1199                                 ASN1err(ASN1_F_ASN1_CHECK_TLEN,
1200                                                         ASN1_R_TOO_LONG);
1201                                 asn1_tlc_clear(ctx);
1202                                 return 0;
1203                                 }
1204                         }
1205                 }
1206
1207         if (i & 0x80)
1208                 {
1209                 ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_BAD_OBJECT_HEADER);
1210                 asn1_tlc_clear(ctx);
1211                 return 0;
1212                 }
1213         if (exptag >= 0)
1214                 {
1215                 if ((exptag != ptag) || (expclass != pclass))
1216                         {
1217                         /* If type is OPTIONAL, not an error:
1218                          * indicate missing type.
1219                          */
1220                         if (opt) return -1;
1221                         asn1_tlc_clear(ctx);
1222                         ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_WRONG_TAG);
1223                         return 0;
1224                         }
1225                 /* We have a tag and class match:
1226                  * assume we are going to do something with it */
1227                 asn1_tlc_clear(ctx);
1228                 }
1229
1230         if (i & 1)
1231                 plen = len - (p - q);
1232
1233         if (inf)
1234                 *inf = i & 1;
1235
1236         if (cst)
1237                 *cst = i & V_ASN1_CONSTRUCTED;
1238
1239         if (olen)
1240                 *olen = plen;
1241
1242         if (oclass)
1243                 *oclass = pclass;
1244
1245         if (otag)
1246                 *otag = ptag;
1247
1248         *in = p;
1249         return 1;
1250         }