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