make scrypt ASN.1 parameter functions public
[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             /* If positive return, read OK, break loop */
229             if (ret > 0)
230                 break;
231             /*
232              * Must be an ASN1 parsing error.
233              * Free up any partial choice value
234              */
235             asn1_template_free(pchptr, tt);
236             errtt = tt;
237             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ERR_R_NESTED_ASN1_ERROR);
238             goto err;
239         }
240
241         /* Did we fall off the end without reading anything? */
242         if (i == it->tcount) {
243             /* If OPTIONAL, this is OK */
244             if (opt) {
245                 /* Free and zero it */
246                 ASN1_item_ex_free(pval, it);
247                 return -1;
248             }
249             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_NO_MATCHING_CHOICE_TYPE);
250             goto err;
251         }
252
253         asn1_set_choice_selector(pval, i, it);
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, 0);
304                 if (seqtt == NULL)
305                     continue;
306                 pseqval = asn1_get_field_ptr(pval, seqtt);
307                 asn1_template_free(pseqval, seqtt);
308             }
309         }
310
311         /* Get each field entry */
312         for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
313             const ASN1_TEMPLATE *seqtt;
314             ASN1_VALUE **pseqval;
315             seqtt = asn1_do_adb(pval, tt, 1);
316             if (seqtt == NULL)
317                 goto err;
318             pseqval = asn1_get_field_ptr(pval, seqtt);
319             /* Have we ran out of data? */
320             if (!len)
321                 break;
322             q = p;
323             if (asn1_check_eoc(&p, len)) {
324                 if (!seq_eoc) {
325                     ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_UNEXPECTED_EOC);
326                     goto err;
327                 }
328                 len -= p - q;
329                 seq_eoc = 0;
330                 q = p;
331                 break;
332             }
333             /*
334              * This determines the OPTIONAL flag value. The field cannot be
335              * omitted if it is the last of a SEQUENCE and there is still
336              * data to be read. This isn't strictly necessary but it
337              * increases efficiency in some cases.
338              */
339             if (i == (it->tcount - 1))
340                 isopt = 0;
341             else
342                 isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
343             /*
344              * attempt to read in field, allowing each to be OPTIONAL
345              */
346
347             ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, ctx);
348             if (!ret) {
349                 errtt = seqtt;
350                 goto err;
351             } else if (ret == -1) {
352                 /*
353                  * OPTIONAL component absent. Free and zero the field.
354                  */
355                 asn1_template_free(pseqval, seqtt);
356                 continue;
357             }
358             /* Update length */
359             len -= p - q;
360         }
361
362         /* Check for EOC if expecting one */
363         if (seq_eoc && !asn1_check_eoc(&p, len)) {
364             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_MISSING_EOC);
365             goto err;
366         }
367         /* Check all data read */
368         if (!seq_nolen && len) {
369             ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
370             goto err;
371         }
372
373         /*
374          * If we get here we've got no more data in the SEQUENCE, however we
375          * may not have read all fields so check all remaining are OPTIONAL
376          * and clear any that are.
377          */
378         for (; i < it->tcount; tt++, i++) {
379             const ASN1_TEMPLATE *seqtt;
380             seqtt = asn1_do_adb(pval, tt, 1);
381             if (seqtt == NULL)
382                 goto err;
383             if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
384                 ASN1_VALUE **pseqval;
385                 pseqval = asn1_get_field_ptr(pval, seqtt);
386                 asn1_template_free(pseqval, seqtt);
387             } else {
388                 errtt = seqtt;
389                 ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_FIELD_MISSING);
390                 goto err;
391             }
392         }
393         /* Save encoding */
394         if (!asn1_enc_save(pval, *in, p - *in, it))
395             goto auxerr;
396         if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
397             goto auxerr;
398         *in = p;
399         return 1;
400
401     default:
402         return 0;
403     }
404  auxerr:
405     ASN1err(ASN1_F_ASN1_ITEM_EMBED_D2I, ASN1_R_AUX_ERROR);
406  err:
407     if (errtt)
408         ERR_add_error_data(4, "Field=", errtt->field_name,
409                            ", Type=", it->sname);
410     else
411         ERR_add_error_data(2, "Type=", it->sname);
412     return 0;
413 }
414
415 /*
416  * Templates are handled with two separate functions. One handles any
417  * EXPLICIT tag and the other handles the rest.
418  */
419
420 static int asn1_template_ex_d2i(ASN1_VALUE **val,
421                                 const unsigned char **in, long inlen,
422                                 const ASN1_TEMPLATE *tt, char opt,
423                                 ASN1_TLC *ctx)
424 {
425     int flags, aclass;
426     int ret;
427     long len;
428     const unsigned char *p, *q;
429     char exp_eoc;
430     if (!val)
431         return 0;
432     flags = tt->flags;
433     aclass = flags & ASN1_TFLG_TAG_CLASS;
434
435     p = *in;
436
437     /* Check if EXPLICIT tag expected */
438     if (flags & ASN1_TFLG_EXPTAG) {
439         char cst;
440         /*
441          * Need to work out amount of data available to the inner content and
442          * where it starts: so read in EXPLICIT header to get the info.
443          */
444         ret = asn1_check_tlen(&len, NULL, NULL, &exp_eoc, &cst,
445                               &p, inlen, tt->tag, aclass, opt, ctx);
446         q = p;
447         if (!ret) {
448             ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
449             return 0;
450         } else if (ret == -1)
451             return -1;
452         if (!cst) {
453             ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
454                     ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);
455             return 0;
456         }
457         /* We've found the field so it can't be OPTIONAL now */
458         ret = asn1_template_noexp_d2i(val, &p, len, tt, 0, ctx);
459         if (!ret) {
460             ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
461             return 0;
462         }
463         /* We read the field in OK so update length */
464         len -= p - q;
465         if (exp_eoc) {
466             /* If NDEF we must have an EOC here */
467             if (!asn1_check_eoc(&p, len)) {
468                 ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I, ASN1_R_MISSING_EOC);
469                 goto err;
470             }
471         } else {
472             /*
473              * Otherwise we must hit the EXPLICIT tag end or its an error
474              */
475             if (len) {
476                 ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
477                         ASN1_R_EXPLICIT_LENGTH_MISMATCH);
478                 goto err;
479             }
480         }
481     } else
482         return asn1_template_noexp_d2i(val, in, inlen, tt, opt, ctx);
483
484     *in = p;
485     return 1;
486
487  err:
488     return 0;
489 }
490
491 static int asn1_template_noexp_d2i(ASN1_VALUE **val,
492                                    const unsigned char **in, long len,
493                                    const ASN1_TEMPLATE *tt, char opt,
494                                    ASN1_TLC *ctx)
495 {
496     int flags, aclass;
497     int ret;
498     ASN1_VALUE *tval;
499     const unsigned char *p, *q;
500     if (!val)
501         return 0;
502     flags = tt->flags;
503     aclass = flags & ASN1_TFLG_TAG_CLASS;
504
505     p = *in;
506     q = p;
507
508     /*
509      * If field is embedded then val needs fixing so it is a pointer to
510      * a pointer to a field.
511      */
512     if (tt->flags & ASN1_TFLG_EMBED) {
513         tval = (ASN1_VALUE *)val;
514         val = &tval;
515     }
516
517     if (flags & ASN1_TFLG_SK_MASK) {
518         /* SET OF, SEQUENCE OF */
519         int sktag, skaclass;
520         char sk_eoc;
521         /* First work out expected inner tag value */
522         if (flags & ASN1_TFLG_IMPTAG) {
523             sktag = tt->tag;
524             skaclass = aclass;
525         } else {
526             skaclass = V_ASN1_UNIVERSAL;
527             if (flags & ASN1_TFLG_SET_OF)
528                 sktag = V_ASN1_SET;
529             else
530                 sktag = V_ASN1_SEQUENCE;
531         }
532         /* Get the tag */
533         ret = asn1_check_tlen(&len, NULL, NULL, &sk_eoc, NULL,
534                               &p, len, sktag, skaclass, opt, ctx);
535         if (!ret) {
536             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
537             return 0;
538         } else if (ret == -1)
539             return -1;
540         if (!*val)
541             *val = (ASN1_VALUE *)OPENSSL_sk_new_null();
542         else {
543             /*
544              * We've got a valid STACK: free up any items present
545              */
546             STACK_OF(ASN1_VALUE) *sktmp = (STACK_OF(ASN1_VALUE) *)*val;
547             ASN1_VALUE *vtmp;
548             while (sk_ASN1_VALUE_num(sktmp) > 0) {
549                 vtmp = sk_ASN1_VALUE_pop(sktmp);
550                 ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item));
551             }
552         }
553
554         if (!*val) {
555             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE);
556             goto err;
557         }
558
559         /* Read as many items as we can */
560         while (len > 0) {
561             ASN1_VALUE *skfield;
562             q = p;
563             /* See if EOC found */
564             if (asn1_check_eoc(&p, len)) {
565                 if (!sk_eoc) {
566                     ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
567                             ASN1_R_UNEXPECTED_EOC);
568                     goto err;
569                 }
570                 len -= p - q;
571                 sk_eoc = 0;
572                 break;
573             }
574             skfield = NULL;
575             if (!asn1_item_embed_d2i(&skfield, &p, len,
576                                      ASN1_ITEM_ptr(tt->item), -1, 0, 0, ctx)) {
577                 ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
578                         ERR_R_NESTED_ASN1_ERROR);
579                 /* |skfield| may be partially allocated despite failure. */
580                 ASN1_item_free(skfield, ASN1_ITEM_ptr(tt->item));
581                 goto err;
582             }
583             len -= p - q;
584             if (!sk_ASN1_VALUE_push((STACK_OF(ASN1_VALUE) *)*val, skfield)) {
585                 ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_MALLOC_FAILURE);
586                 ASN1_item_free(skfield, ASN1_ITEM_ptr(tt->item));
587                 goto err;
588             }
589         }
590         if (sk_eoc) {
591             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ASN1_R_MISSING_EOC);
592             goto err;
593         }
594     } else if (flags & ASN1_TFLG_IMPTAG) {
595         /* IMPLICIT tagging */
596         ret = asn1_item_embed_d2i(val, &p, len,
597                                   ASN1_ITEM_ptr(tt->item), tt->tag, aclass, opt,
598                                   ctx);
599         if (!ret) {
600             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
601             goto err;
602         } else if (ret == -1)
603             return -1;
604     } else {
605         /* Nothing special */
606         ret = asn1_item_embed_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item),
607                                   -1, 0, opt, ctx);
608         if (!ret) {
609             ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I, ERR_R_NESTED_ASN1_ERROR);
610             goto err;
611         } else if (ret == -1)
612             return -1;
613     }
614
615     *in = p;
616     return 1;
617
618  err:
619     return 0;
620 }
621
622 static int asn1_d2i_ex_primitive(ASN1_VALUE **pval,
623                                  const unsigned char **in, long inlen,
624                                  const ASN1_ITEM *it,
625                                  int tag, int aclass, char opt, ASN1_TLC *ctx)
626 {
627     int ret = 0, utype;
628     long plen;
629     char cst, inf, free_cont = 0;
630     const unsigned char *p;
631     BUF_MEM buf = { 0, NULL, 0, 0 };
632     const unsigned char *cont = NULL;
633     long len;
634     if (!pval) {
635         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_NULL);
636         return 0;               /* Should never happen */
637     }
638
639     if (it->itype == ASN1_ITYPE_MSTRING) {
640         utype = tag;
641         tag = -1;
642     } else
643         utype = it->utype;
644
645     if (utype == V_ASN1_ANY) {
646         /* If type is ANY need to figure out type from tag */
647         unsigned char oclass;
648         if (tag >= 0) {
649             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_ILLEGAL_TAGGED_ANY);
650             return 0;
651         }
652         if (opt) {
653             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
654                     ASN1_R_ILLEGAL_OPTIONAL_ANY);
655             return 0;
656         }
657         p = *in;
658         ret = asn1_check_tlen(NULL, &utype, &oclass, NULL, NULL,
659                               &p, inlen, -1, 0, 0, ctx);
660         if (!ret) {
661             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
662             return 0;
663         }
664         if (oclass != V_ASN1_UNIVERSAL)
665             utype = V_ASN1_OTHER;
666     }
667     if (tag == -1) {
668         tag = utype;
669         aclass = V_ASN1_UNIVERSAL;
670     }
671     p = *in;
672     /* Check header */
673     ret = asn1_check_tlen(&plen, NULL, NULL, &inf, &cst,
674                           &p, inlen, tag, aclass, opt, ctx);
675     if (!ret) {
676         ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_NESTED_ASN1_ERROR);
677         return 0;
678     } else if (ret == -1)
679         return -1;
680     ret = 0;
681     /* SEQUENCE, SET and "OTHER" are left in encoded form */
682     if ((utype == V_ASN1_SEQUENCE)
683         || (utype == V_ASN1_SET) || (utype == V_ASN1_OTHER)) {
684         /*
685          * Clear context cache for type OTHER because the auto clear when we
686          * have a exact match won't work
687          */
688         if (utype == V_ASN1_OTHER) {
689             asn1_tlc_clear(ctx);
690         }
691         /* SEQUENCE and SET must be constructed */
692         else if (!cst) {
693             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE,
694                     ASN1_R_TYPE_NOT_CONSTRUCTED);
695             return 0;
696         }
697
698         cont = *in;
699         /* If indefinite length constructed find the real end */
700         if (inf) {
701             if (!asn1_find_end(&p, plen, inf))
702                 goto err;
703             len = p - cont;
704         } else {
705             len = p - cont + plen;
706             p += plen;
707         }
708     } else if (cst) {
709         if (utype == V_ASN1_NULL || utype == V_ASN1_BOOLEAN
710             || utype == V_ASN1_OBJECT || utype == V_ASN1_INTEGER
711             || utype == V_ASN1_ENUMERATED) {
712             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ASN1_R_TYPE_NOT_PRIMITIVE);
713             return 0;
714         }
715
716         /* Free any returned 'buf' content */
717         free_cont = 1;
718         /*
719          * Should really check the internal tags are correct but some things
720          * may get this wrong. The relevant specs say that constructed string
721          * types should be OCTET STRINGs internally irrespective of the type.
722          * So instead just check for UNIVERSAL class and ignore the tag.
723          */
724         if (!asn1_collect(&buf, &p, plen, inf, -1, V_ASN1_UNIVERSAL, 0)) {
725             goto err;
726         }
727         len = buf.length;
728         /* Append a final null to string */
729         if (!BUF_MEM_grow_clean(&buf, len + 1)) {
730             ASN1err(ASN1_F_ASN1_D2I_EX_PRIMITIVE, ERR_R_MALLOC_FAILURE);
731             goto err;
732         }
733         buf.data[len] = 0;
734         cont = (const unsigned char *)buf.data;
735     } else {
736         cont = p;
737         len = plen;
738         p += plen;
739     }
740
741     /* We now have content length and type: translate into a structure */
742     /* asn1_ex_c2i may reuse allocated buffer, and so sets free_cont to 0 */
743     if (!asn1_ex_c2i(pval, cont, len, utype, &free_cont, it))
744         goto err;
745
746     *in = p;
747     ret = 1;
748  err:
749     if (free_cont)
750         OPENSSL_free(buf.data);
751     return ret;
752 }
753
754 /* Translate ASN1 content octets into a structure */
755
756 static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, int len,
757                        int utype, char *free_cont, const ASN1_ITEM *it)
758 {
759     ASN1_VALUE **opval = NULL;
760     ASN1_STRING *stmp;
761     ASN1_TYPE *typ = NULL;
762     int ret = 0;
763     const ASN1_PRIMITIVE_FUNCS *pf;
764     ASN1_INTEGER **tint;
765     pf = it->funcs;
766
767     if (pf && pf->prim_c2i)
768         return pf->prim_c2i(pval, cont, len, utype, free_cont, it);
769     /* If ANY type clear type and set pointer to internal value */
770     if (it->utype == V_ASN1_ANY) {
771         if (!*pval) {
772             typ = ASN1_TYPE_new();
773             if (typ == NULL)
774                 goto err;
775             *pval = (ASN1_VALUE *)typ;
776         } else
777             typ = (ASN1_TYPE *)*pval;
778
779         if (utype != typ->type)
780             ASN1_TYPE_set(typ, utype, NULL);
781         opval = pval;
782         pval = &typ->value.asn1_value;
783     }
784     switch (utype) {
785     case V_ASN1_OBJECT:
786         if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len))
787             goto err;
788         break;
789
790     case V_ASN1_NULL:
791         if (len) {
792             ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_NULL_IS_WRONG_LENGTH);
793             goto err;
794         }
795         *pval = (ASN1_VALUE *)1;
796         break;
797
798     case V_ASN1_BOOLEAN:
799         if (len != 1) {
800             ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
801             goto err;
802         } else {
803             ASN1_BOOLEAN *tbool;
804             tbool = (ASN1_BOOLEAN *)pval;
805             *tbool = *cont;
806         }
807         break;
808
809     case V_ASN1_BIT_STRING:
810         if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len))
811             goto err;
812         break;
813
814     case V_ASN1_INTEGER:
815     case V_ASN1_ENUMERATED:
816         tint = (ASN1_INTEGER **)pval;
817         if (!c2i_ASN1_INTEGER(tint, &cont, len))
818             goto err;
819         /* Fixup type to match the expected form */
820         (*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
821         break;
822
823     case V_ASN1_OCTET_STRING:
824     case V_ASN1_NUMERICSTRING:
825     case V_ASN1_PRINTABLESTRING:
826     case V_ASN1_T61STRING:
827     case V_ASN1_VIDEOTEXSTRING:
828     case V_ASN1_IA5STRING:
829     case V_ASN1_UTCTIME:
830     case V_ASN1_GENERALIZEDTIME:
831     case V_ASN1_GRAPHICSTRING:
832     case V_ASN1_VISIBLESTRING:
833     case V_ASN1_GENERALSTRING:
834     case V_ASN1_UNIVERSALSTRING:
835     case V_ASN1_BMPSTRING:
836     case V_ASN1_UTF8STRING:
837     case V_ASN1_OTHER:
838     case V_ASN1_SET:
839     case V_ASN1_SEQUENCE:
840     default:
841         if (utype == V_ASN1_BMPSTRING && (len & 1)) {
842             ASN1err(ASN1_F_ASN1_EX_C2I, ASN1_R_BMPSTRING_IS_WRONG_LENGTH);
843             goto err;
844         }
845         if (utype == V_ASN1_UNIVERSALSTRING && (len & 3)) {
846             ASN1err(ASN1_F_ASN1_EX_C2I,
847                     ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH);
848             goto err;
849         }
850         /* All based on ASN1_STRING and handled the same */
851         if (!*pval) {
852             stmp = ASN1_STRING_type_new(utype);
853             if (stmp == NULL) {
854                 ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
855                 goto err;
856             }
857             *pval = (ASN1_VALUE *)stmp;
858         } else {
859             stmp = (ASN1_STRING *)*pval;
860             stmp->type = utype;
861         }
862         /* If we've already allocated a buffer use it */
863         if (*free_cont) {
864             OPENSSL_free(stmp->data);
865             stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */
866             stmp->length = len;
867             *free_cont = 0;
868         } else {
869             if (!ASN1_STRING_set(stmp, cont, len)) {
870                 ASN1err(ASN1_F_ASN1_EX_C2I, ERR_R_MALLOC_FAILURE);
871                 ASN1_STRING_free(stmp);
872                 *pval = NULL;
873                 goto err;
874             }
875         }
876         break;
877     }
878     /* If ASN1_ANY and NULL type fix up value */
879     if (typ && (utype == V_ASN1_NULL))
880         typ->value.ptr = NULL;
881
882     ret = 1;
883  err:
884     if (!ret) {
885         ASN1_TYPE_free(typ);
886         if (opval)
887             *opval = NULL;
888     }
889     return ret;
890 }
891
892 /*
893  * This function finds the end of an ASN1 structure when passed its maximum
894  * length, whether it is indefinite length and a pointer to the content. This
895  * is more efficient than calling asn1_collect because it does not recurse on
896  * each indefinite length header.
897  */
898
899 static int asn1_find_end(const unsigned char **in, long len, char inf)
900 {
901     uint32_t expected_eoc;
902     long plen;
903     const unsigned char *p = *in, *q;
904     /* If not indefinite length constructed just add length */
905     if (inf == 0) {
906         *in += len;
907         return 1;
908     }
909     expected_eoc = 1;
910     /*
911      * Indefinite length constructed form. Find the end when enough EOCs are
912      * found. If more indefinite length constructed headers are encountered
913      * increment the expected eoc count otherwise just skip to the end of the
914      * data.
915      */
916     while (len > 0) {
917         if (asn1_check_eoc(&p, len)) {
918             expected_eoc--;
919             if (expected_eoc == 0)
920                 break;
921             len -= 2;
922             continue;
923         }
924         q = p;
925         /* Just read in a header: only care about the length */
926         if (!asn1_check_tlen(&plen, NULL, NULL, &inf, NULL, &p, len,
927                              -1, 0, 0, NULL)) {
928             ASN1err(ASN1_F_ASN1_FIND_END, ERR_R_NESTED_ASN1_ERROR);
929             return 0;
930         }
931         if (inf) {
932             if (expected_eoc == UINT32_MAX) {
933                 ASN1err(ASN1_F_ASN1_FIND_END, ERR_R_NESTED_ASN1_ERROR);
934                 return 0;
935             }
936             expected_eoc++;
937         } else {
938             p += plen;
939         }
940         len -= p - q;
941     }
942     if (expected_eoc) {
943         ASN1err(ASN1_F_ASN1_FIND_END, ASN1_R_MISSING_EOC);
944         return 0;
945     }
946     *in = p;
947     return 1;
948 }
949
950 /*
951  * This function collects the asn1 data from a constructed string type into
952  * a buffer. The values of 'in' and 'len' should refer to the contents of the
953  * constructed type and 'inf' should be set if it is indefinite length.
954  */
955
956 #ifndef ASN1_MAX_STRING_NEST
957 /*
958  * This determines how many levels of recursion are permitted in ASN1 string
959  * types. If it is not limited stack overflows can occur. If set to zero no
960  * recursion is allowed at all. Although zero should be adequate examples
961  * exist that require a value of 1. So 5 should be more than enough.
962  */
963 # define ASN1_MAX_STRING_NEST 5
964 #endif
965
966 static int asn1_collect(BUF_MEM *buf, const unsigned char **in, long len,
967                         char inf, int tag, int aclass, int depth)
968 {
969     const unsigned char *p, *q;
970     long plen;
971     char cst, ininf;
972     p = *in;
973     inf &= 1;
974     /*
975      * If no buffer and not indefinite length constructed just pass over the
976      * encoded data
977      */
978     if (!buf && !inf) {
979         *in += len;
980         return 1;
981     }
982     while (len > 0) {
983         q = p;
984         /* Check for EOC */
985         if (asn1_check_eoc(&p, len)) {
986             /*
987              * EOC is illegal outside indefinite length constructed form
988              */
989             if (!inf) {
990                 ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_UNEXPECTED_EOC);
991                 return 0;
992             }
993             inf = 0;
994             break;
995         }
996
997         if (!asn1_check_tlen(&plen, NULL, NULL, &ininf, &cst, &p,
998                              len, tag, aclass, 0, NULL)) {
999             ASN1err(ASN1_F_ASN1_COLLECT, ERR_R_NESTED_ASN1_ERROR);
1000             return 0;
1001         }
1002
1003         /* If indefinite length constructed update max length */
1004         if (cst) {
1005             if (depth >= ASN1_MAX_STRING_NEST) {
1006                 ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_NESTED_ASN1_STRING);
1007                 return 0;
1008             }
1009             if (!asn1_collect(buf, &p, plen, ininf, tag, aclass, depth + 1))
1010                 return 0;
1011         } else if (plen && !collect_data(buf, &p, plen))
1012             return 0;
1013         len -= p - q;
1014     }
1015     if (inf) {
1016         ASN1err(ASN1_F_ASN1_COLLECT, ASN1_R_MISSING_EOC);
1017         return 0;
1018     }
1019     *in = p;
1020     return 1;
1021 }
1022
1023 static int collect_data(BUF_MEM *buf, const unsigned char **p, long plen)
1024 {
1025     int len;
1026     if (buf) {
1027         len = buf->length;
1028         if (!BUF_MEM_grow_clean(buf, len + plen)) {
1029             ASN1err(ASN1_F_COLLECT_DATA, ERR_R_MALLOC_FAILURE);
1030             return 0;
1031         }
1032         memcpy(buf->data + len, *p, plen);
1033     }
1034     *p += plen;
1035     return 1;
1036 }
1037
1038 /* Check for ASN1 EOC and swallow it if found */
1039
1040 static int asn1_check_eoc(const unsigned char **in, long len)
1041 {
1042     const unsigned char *p;
1043     if (len < 2)
1044         return 0;
1045     p = *in;
1046     if (!p[0] && !p[1]) {
1047         *in += 2;
1048         return 1;
1049     }
1050     return 0;
1051 }
1052
1053 /*
1054  * Check an ASN1 tag and length: a bit like ASN1_get_object but it sets the
1055  * length for indefinite length constructed form, we don't know the exact
1056  * length but we can set an upper bound to the amount of data available minus
1057  * the header length just read.
1058  */
1059
1060 static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
1061                            char *inf, char *cst,
1062                            const unsigned char **in, long len,
1063                            int exptag, int expclass, char opt, ASN1_TLC *ctx)
1064 {
1065     int i;
1066     int ptag, pclass;
1067     long plen;
1068     const unsigned char *p, *q;
1069     p = *in;
1070     q = p;
1071
1072     if (ctx && ctx->valid) {
1073         i = ctx->ret;
1074         plen = ctx->plen;
1075         pclass = ctx->pclass;
1076         ptag = ctx->ptag;
1077         p += ctx->hdrlen;
1078     } else {
1079         i = ASN1_get_object(&p, &plen, &ptag, &pclass, len);
1080         if (ctx) {
1081             ctx->ret = i;
1082             ctx->plen = plen;
1083             ctx->pclass = pclass;
1084             ctx->ptag = ptag;
1085             ctx->hdrlen = p - q;
1086             ctx->valid = 1;
1087             /*
1088              * If definite length, and no error, length + header can't exceed
1089              * total amount of data available.
1090              */
1091             if (!(i & 0x81) && ((plen + ctx->hdrlen) > len)) {
1092                 ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_TOO_LONG);
1093                 asn1_tlc_clear(ctx);
1094                 return 0;
1095             }
1096         }
1097     }
1098
1099     if (i & 0x80) {
1100         ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_BAD_OBJECT_HEADER);
1101         asn1_tlc_clear(ctx);
1102         return 0;
1103     }
1104     if (exptag >= 0) {
1105         if ((exptag != ptag) || (expclass != pclass)) {
1106             /*
1107              * If type is OPTIONAL, not an error: indicate missing type.
1108              */
1109             if (opt)
1110                 return -1;
1111             asn1_tlc_clear(ctx);
1112             ASN1err(ASN1_F_ASN1_CHECK_TLEN, ASN1_R_WRONG_TAG);
1113             return 0;
1114         }
1115         /*
1116          * We have a tag and class match: assume we are going to do something
1117          * with it
1118          */
1119         asn1_tlc_clear(ctx);
1120     }
1121
1122     if (i & 1)
1123         plen = len - (p - q);
1124
1125     if (inf)
1126         *inf = i & 1;
1127
1128     if (cst)
1129         *cst = i & V_ASN1_CONSTRUCTED;
1130
1131     if (olen)
1132         *olen = plen;
1133
1134     if (oclass)
1135         *oclass = pclass;
1136
1137     if (otag)
1138         *otag = ptag;
1139
1140     *in = p;
1141     return 1;
1142 }