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