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