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