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