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