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