xref: /openbsd-src/lib/libcrypto/asn1/tasn_dec.c (revision 25c4e8bd056e974b28f4a0ffd39d76c190a56013)
1 /* $OpenBSD: tasn_dec.c,v 1.78 2022/06/29 08:56:44 beck 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 "asn1_locl.h"
70 #include "bytestring.h"
71 
72 /*
73  * Constructed types with a recursive definition (such as can be found in PKCS7)
74  * could eventually exceed the stack given malicious input with excessive
75  * recursion. Therefore we limit the stack depth.
76  */
77 #define ASN1_MAX_CONSTRUCTED_NEST 30
78 
79 #ifndef ASN1_MAX_STRING_NEST
80 /*
81  * This determines how many levels of recursion are permitted in ASN.1 string
82  * types. If it is not limited stack overflows can occur. If set to zero no
83  * recursion is allowed at all.
84  */
85 #define ASN1_MAX_STRING_NEST 5
86 #endif
87 
88 static int asn1_template_d2i(ASN1_VALUE **pval, CBS *cbs,
89     const ASN1_TEMPLATE *at, int optional, int depth);
90 
91 static int
92 asn1_check_eoc(CBS *cbs)
93 {
94 	uint16_t eoc;
95 
96 	if (!CBS_peek_u16(cbs, &eoc))
97 		return 0;
98 	if (eoc != 0)
99 		return 0;
100 
101 	return CBS_skip(cbs, 2);
102 }
103 
104 static int
105 asn1_check_tag(CBS *cbs, size_t *out_len, int *out_tag, uint8_t *out_class,
106     int *out_indefinite, int *out_constructed, int expected_tag,
107     int expected_class, int optional)
108 {
109 	int constructed, indefinite;
110 	uint32_t tag_number;
111 	uint8_t tag_class;
112 	size_t length;
113 
114 	if (out_len != NULL)
115 		*out_len = 0;
116 	if (out_tag != NULL)
117 		*out_tag = 0;
118 	if (out_class != NULL)
119 		*out_class = 0;
120 	if (out_indefinite != NULL)
121 		*out_indefinite = 0;
122 	if (out_constructed != NULL)
123 		*out_constructed = 0;
124 
125 	if (!asn1_get_identifier_cbs(cbs, 0, &tag_class, &constructed,
126 	    &tag_number)) {
127 		ASN1error(ASN1_R_BAD_OBJECT_HEADER);
128 		return 0;
129 	}
130 	if (expected_tag >= 0) {
131 		if (expected_tag != tag_number ||
132 		    expected_class != tag_class << 6) {
133 			/* Indicate missing type if this is OPTIONAL. */
134 			if (optional)
135 				return -1;
136 
137 			ASN1error(ASN1_R_WRONG_TAG);
138 			return 0;
139 		}
140 	}
141 	if (!asn1_get_length_cbs(cbs, 0, &indefinite, &length)) {
142 		ASN1error(ASN1_R_BAD_OBJECT_HEADER);
143 		return 0;
144 	}
145 
146 	/* Indefinite length can only be used with constructed encoding. */
147 	if (indefinite && !constructed) {
148 		ASN1error(ASN1_R_BAD_OBJECT_HEADER);
149 		return 0;
150 	}
151 
152 	if (!indefinite && CBS_len(cbs) < length) {
153 		ASN1error(ASN1_R_TOO_LONG);
154 		return 0;
155 	}
156 
157 	if (tag_number > INT_MAX) {
158 		ASN1error(ASN1_R_TOO_LONG);
159 		return 0;
160 	}
161 
162 	if (indefinite)
163 		length = CBS_len(cbs);
164 
165 	if (out_len != NULL)
166 		*out_len = length;
167 	if (out_tag != NULL)
168 		*out_tag = tag_number;
169 	if (out_class != NULL)
170 		*out_class = tag_class << 6;
171 	if (out_indefinite != NULL)
172 		*out_indefinite = indefinite;
173 	if (out_constructed != NULL)
174 		*out_constructed = constructed;
175 
176 	return 1;
177 }
178 
179 /* Collect the contents from a constructed ASN.1 object. */
180 static int
181 asn1_collect(CBB *cbb, CBS *cbs, int indefinite, int expected_tag,
182     int expected_class, int depth)
183 {
184 	int constructed;
185 	size_t length;
186 	CBS content;
187 	int need_eoc;
188 
189 	if (depth > ASN1_MAX_STRING_NEST) {
190 		ASN1error(ASN1_R_NESTED_ASN1_STRING);
191 		return 0;
192 	}
193 
194 	need_eoc = indefinite;
195 
196 	while (CBS_len(cbs) > 0) {
197 		if (asn1_check_eoc(cbs)) {
198 			if (!need_eoc) {
199 				ASN1error(ASN1_R_UNEXPECTED_EOC);
200 				return 0;
201 			}
202 			return 1;
203 		}
204 		if (!asn1_check_tag(cbs, &length, NULL, NULL, &indefinite,
205 		    &constructed, expected_tag, expected_class, 0)) {
206 			ASN1error(ERR_R_NESTED_ASN1_ERROR);
207 			return 0;
208 		}
209 
210 		if (constructed) {
211 			if (!asn1_collect(cbb, cbs, indefinite, expected_tag,
212 			    expected_class, depth + 1))
213 				return 0;
214 			continue;
215 		}
216 
217 		if (!CBS_get_bytes(cbs, &content, length)) {
218 			ASN1error(ERR_R_NESTED_ASN1_ERROR);
219 			return 0;
220 		}
221 		if (!CBB_add_bytes(cbb, CBS_data(&content), CBS_len(&content)))
222 			return 0;
223 	}
224 
225 	if (need_eoc) {
226 		ASN1error(ASN1_R_MISSING_EOC);
227 		return 0;
228 	}
229 
230 	return 1;
231 }
232 
233 /* Find the end of an ASN.1 object. */
234 static int
235 asn1_find_end(CBS *cbs, size_t length, int indefinite)
236 {
237 	size_t eoc_count;
238 
239 	if (!indefinite) {
240 		if (!CBS_skip(cbs, length)) {
241 			ASN1error(ERR_R_NESTED_ASN1_ERROR);
242 			return 0;
243 		}
244 		return 1;
245 	}
246 
247 	eoc_count = 1;
248 
249 	while (CBS_len(cbs) > 0) {
250 		if (asn1_check_eoc(cbs)) {
251 			if (--eoc_count == 0)
252 				break;
253 			continue;
254 		}
255 		if (!asn1_check_tag(cbs, &length, NULL, NULL,
256 		    &indefinite, NULL, -1, 0, 0)) {
257 			ASN1error(ERR_R_NESTED_ASN1_ERROR);
258 			return 0;
259 		}
260 		if (indefinite) {
261 			eoc_count++;
262 			continue;
263 		}
264 		if (!CBS_skip(cbs, length))
265 			return 0;
266 	}
267 
268 	if (eoc_count > 0) {
269 		ASN1error(ASN1_R_MISSING_EOC);
270 		return 0;
271 	}
272 
273 	return 1;
274 }
275 
276 static int
277 asn1_c2i_primitive(ASN1_VALUE **pval, CBS *content, int utype, const ASN1_ITEM *it)
278 {
279 	ASN1_STRING *stmp;
280 	ASN1_INTEGER **tint;
281 	ASN1_BOOLEAN *tbool;
282 	uint8_t u8val;
283 	int ret = 0;
284 
285 	if (it->funcs != NULL)
286 		return 0;
287 
288 	if (CBS_len(content) > INT_MAX)
289 		return 0;
290 
291 	switch (utype) {
292 	case V_ASN1_OBJECT:
293 		if (!c2i_ASN1_OBJECT_cbs((ASN1_OBJECT **)pval, content))
294 			goto err;
295 		break;
296 
297 	case V_ASN1_NULL:
298 		if (CBS_len(content) != 0) {
299 			ASN1error(ASN1_R_NULL_IS_WRONG_LENGTH);
300 			goto err;
301 		}
302 		*pval = (ASN1_VALUE *)1;
303 		break;
304 
305 	case V_ASN1_BOOLEAN:
306 		tbool = (ASN1_BOOLEAN *)pval;
307 		if (CBS_len(content) != 1) {
308 			ASN1error(ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
309 			goto err;
310 		}
311 		if (!CBS_get_u8(content, &u8val))
312 			goto err;
313 		*tbool = u8val;
314 		break;
315 
316 	case V_ASN1_BIT_STRING:
317 		if (!c2i_ASN1_BIT_STRING_cbs((ASN1_BIT_STRING **)pval, content))
318 			goto err;
319 		break;
320 
321 	case V_ASN1_INTEGER:
322 	case V_ASN1_ENUMERATED:
323 		tint = (ASN1_INTEGER **)pval;
324 		if (!c2i_ASN1_INTEGER_cbs(tint, content))
325 			goto err;
326 		/* Fixup type to match the expected form */
327 		(*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
328 		break;
329 
330 	case V_ASN1_OCTET_STRING:
331 	case V_ASN1_NUMERICSTRING:
332 	case V_ASN1_PRINTABLESTRING:
333 	case V_ASN1_T61STRING:
334 	case V_ASN1_VIDEOTEXSTRING:
335 	case V_ASN1_IA5STRING:
336 	case V_ASN1_UTCTIME:
337 	case V_ASN1_GENERALIZEDTIME:
338 	case V_ASN1_GRAPHICSTRING:
339 	case V_ASN1_VISIBLESTRING:
340 	case V_ASN1_GENERALSTRING:
341 	case V_ASN1_UNIVERSALSTRING:
342 	case V_ASN1_BMPSTRING:
343 	case V_ASN1_UTF8STRING:
344 	case V_ASN1_OTHER:
345 	case V_ASN1_SET:
346 	case V_ASN1_SEQUENCE:
347 	default:
348 		if (utype == V_ASN1_BMPSTRING && (CBS_len(content) & 1)) {
349 			ASN1error(ASN1_R_BMPSTRING_IS_WRONG_LENGTH);
350 			goto err;
351 		}
352 		if (utype == V_ASN1_UNIVERSALSTRING && (CBS_len(content) & 3)) {
353 			ASN1error(ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH);
354 			goto err;
355 		}
356 		if (utype == V_ASN1_UTCTIME || utype == V_ASN1_GENERALIZEDTIME) {
357 			if (!asn1_time_parse_cbs(content,
358 			    utype == V_ASN1_GENERALIZEDTIME, NULL))  {
359 				ASN1error(ASN1_R_INVALID_TIME_FORMAT);
360 				goto err;
361 			}
362 		}
363 		/* All based on ASN1_STRING and handled the same way. */
364 		if (*pval == NULL) {
365 			if ((stmp = ASN1_STRING_type_new(utype)) == NULL) {
366 				ASN1error(ERR_R_MALLOC_FAILURE);
367 				goto err;
368 			}
369 			*pval = (ASN1_VALUE *)stmp;
370 		} else {
371 			stmp = (ASN1_STRING *)*pval;
372 			stmp->type = utype;
373 		}
374 		if (!ASN1_STRING_set(stmp, CBS_data(content), CBS_len(content))) {
375 			ASN1_STRING_free(stmp);
376 			*pval = NULL;
377 			goto err;
378 		}
379 		break;
380 	}
381 
382 	ret = 1;
383 
384  err:
385 	return ret;
386 }
387 
388 static int
389 asn1_c2i_any(ASN1_VALUE **pval, CBS *content, int utype, const ASN1_ITEM *it)
390 {
391 	ASN1_TYPE *atype;
392 
393 	if (it->utype != V_ASN1_ANY || it->funcs != NULL)
394 		return 0;
395 
396 	if (*pval != NULL) {
397 		ASN1_TYPE_free((ASN1_TYPE *)*pval);
398 		*pval = NULL;
399 	}
400 
401 	if ((atype = ASN1_TYPE_new()) == NULL)
402 		return 0;
403 
404 	if (!asn1_c2i_primitive(&atype->value.asn1_value, content, utype, it)) {
405 		ASN1_TYPE_free(atype);
406 		return 0;
407 	}
408 	atype->type = utype;
409 
410 	/* Fix up value for ASN.1 NULL. */
411 	if (atype->type == V_ASN1_NULL)
412 		atype->value.ptr = NULL;
413 
414 	*pval = (ASN1_VALUE *)atype;
415 
416 	return 1;
417 }
418 
419 static int
420 asn1_c2i(ASN1_VALUE **pval, CBS *content, int utype, const ASN1_ITEM *it)
421 {
422 	if (CBS_len(content) > INT_MAX)
423 		return 0;
424 
425 	if (it->funcs != NULL) {
426 		const ASN1_PRIMITIVE_FUNCS *pf = it->funcs;
427 		char free_content = 0;
428 
429 		if (pf->prim_c2i == NULL)
430 			return 0;
431 
432 		return pf->prim_c2i(pval, CBS_data(content), CBS_len(content),
433 		    utype, &free_content, it);
434 	}
435 
436 	if (it->utype == V_ASN1_ANY)
437 		return asn1_c2i_any(pval, content, utype, it);
438 
439 	return asn1_c2i_primitive(pval, content, utype, it);
440 }
441 
442 /*
443  * Decode ASN.1 content into a primitive type. There are three possible forms -
444  * a SEQUENCE/SET/OTHER that is stored verbatim (including the ASN.1 tag and
445  * length octets), constructed objects and non-constructed objects. In the
446  * first two cases indefinite length is permitted, which we may need to handle.
447  * When this function is called the *cbs should reference the start of the
448  * ASN.1 object (i.e. the tag/length header), while *cbs_object should
449  * reference the start of the object contents (i.e. after the tag/length
450  * header. Additionally, the *cbs_object offset should be relative to the
451  * ASN.1 object being parsed. On success the *cbs will point at the octet
452  * after the object.
453  */
454 static int
455 asn1_d2i_primitive_content(ASN1_VALUE **pval, CBS *cbs, CBS *cbs_object,
456     int utype, int constructed, int indefinite, size_t length,
457     const ASN1_ITEM *it)
458 {
459 	CBS cbs_content, cbs_initial;
460 	uint8_t *data = NULL;
461 	size_t data_len = 0;
462 	CBB cbb;
463 	int ret = 0;
464 
465 	memset(&cbb, 0, sizeof(cbb));
466 
467 	CBS_dup(cbs, &cbs_initial);
468 	CBS_init(&cbs_content, NULL, 0);
469 
470 	/* XXX - check primitive vs constructed based on utype. */
471 
472 	/* SEQUENCE and SET must be constructed. */
473 	if ((utype == V_ASN1_SEQUENCE || utype == V_ASN1_SET) && !constructed) {
474 		ASN1error(ASN1_R_TYPE_NOT_CONSTRUCTED);
475 		goto err;
476 	}
477 
478 	/* SEQUENCE, SET and "OTHER" are left in encoded form. */
479 	if (utype == V_ASN1_SEQUENCE || utype == V_ASN1_SET ||
480 	    utype == V_ASN1_OTHER) {
481 		if (!asn1_find_end(cbs_object, length, indefinite))
482 			goto err;
483 		if (!CBS_get_bytes(&cbs_initial, &cbs_content,
484 		    CBS_offset(cbs_object)))
485 			goto err;
486 	} else if (constructed) {
487 		/*
488 		 * Should really check the internal tags are correct but
489 		 * some things may get this wrong. The relevant specs
490 		 * say that constructed string types should be OCTET STRINGs
491 		 * internally irrespective of the type. So instead just check
492 		 * for UNIVERSAL class and ignore the tag.
493 		 */
494 		if (!CBB_init(&cbb, 0))
495 			goto err;
496 		if (!asn1_collect(&cbb, cbs_object, indefinite, -1,
497 		    V_ASN1_UNIVERSAL, 0))
498 			goto err;
499 		if (!CBB_finish(&cbb, &data, &data_len))
500 			goto err;
501 
502 		CBS_init(&cbs_content, data, data_len);
503 	} else {
504 		if (!CBS_get_bytes(cbs_object, &cbs_content, length))
505 			goto err;
506 	}
507 
508 	if (!asn1_c2i(pval, &cbs_content, utype, it))
509 		goto err;
510 
511 	if (!CBS_skip(cbs, CBS_offset(cbs_object)))
512 		goto err;
513 
514 	ret = 1;
515 
516  err:
517 	CBB_cleanup(&cbb);
518 	freezero(data, data_len);
519 
520 	return ret;
521 }
522 
523 static int
524 asn1_d2i_any(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it,
525     int tag_number, int tag_class, int optional)
526 {
527 	int constructed, indefinite;
528 	uint8_t object_class;
529 	int object_type;
530 	CBS cbs_object;
531 	size_t length;
532 
533 	CBS_init(&cbs_object, CBS_data(cbs), CBS_len(cbs));
534 
535 	if (it->utype != V_ASN1_ANY)
536 		return 0;
537 
538 	if (tag_number >= 0) {
539 		ASN1error(ASN1_R_ILLEGAL_TAGGED_ANY);
540 		return 0;
541 	}
542 	if (optional) {
543 		ASN1error(ASN1_R_ILLEGAL_OPTIONAL_ANY);
544 		return 0;
545 	}
546 
547 	/* Determine type from ASN.1 tag. */
548 	if (asn1_check_tag(&cbs_object, &length, &object_type, &object_class,
549 	    &indefinite, &constructed, -1, 0, 0) != 1) {
550 		ASN1error(ERR_R_NESTED_ASN1_ERROR);
551 		return 0;
552 	}
553 	if (object_class != V_ASN1_UNIVERSAL)
554 		object_type = V_ASN1_OTHER;
555 
556 	return asn1_d2i_primitive_content(pval, cbs, &cbs_object, object_type,
557 	    constructed, indefinite, length, it);
558 }
559 
560 static int
561 asn1_d2i_mstring(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it,
562     int tag_number, int tag_class, int optional)
563 {
564 	int constructed, indefinite;
565 	uint8_t object_class;
566 	int object_tag;
567 	CBS cbs_object;
568 	size_t length;
569 
570 	CBS_init(&cbs_object, CBS_data(cbs), CBS_len(cbs));
571 
572 	/*
573 	 * It never makes sense for multi-strings to have implicit tagging, so
574 	 * if tag_number != -1, then this looks like an error in the template.
575 	 */
576 	if (tag_number != -1) {
577 		ASN1error(ASN1_R_BAD_TEMPLATE);
578 		return 0;
579 	}
580 
581 	if (asn1_check_tag(&cbs_object, &length, &object_tag, &object_class,
582 	    &indefinite, &constructed, -1, 0, 1) != 1) {
583 		ASN1error(ERR_R_NESTED_ASN1_ERROR);
584 		return 0;
585 	}
586 
587 	/* Class must be UNIVERSAL. */
588 	if (object_class != V_ASN1_UNIVERSAL) {
589 		if (optional)
590 			return -1;
591 		ASN1error(ASN1_R_MSTRING_NOT_UNIVERSAL);
592 		return 0;
593 	}
594 	/* Check tag matches bit map. */
595 	if ((ASN1_tag2bit(object_tag) & it->utype) == 0) {
596 		if (optional)
597 			return -1;
598 		ASN1error(ASN1_R_MSTRING_WRONG_TAG);
599 		return 0;
600 	}
601 
602 	return asn1_d2i_primitive_content(pval, cbs, &cbs_object,
603 	    object_tag, constructed, indefinite, length, it);
604 }
605 
606 static int
607 asn1_d2i_primitive(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it,
608     int tag_number, int tag_class, int optional)
609 {
610 	CBS cbs_object;
611 	int constructed, indefinite;
612 	int utype = it->utype;
613 	size_t length;
614 	int ret;
615 
616 	CBS_init(&cbs_object, CBS_data(cbs), CBS_len(cbs));
617 
618 	if (it->itype == ASN1_ITYPE_MSTRING)
619 		return 0;
620 
621 	if (it->utype == V_ASN1_ANY)
622 		return asn1_d2i_any(pval, cbs, it, tag_number, tag_class, optional);
623 
624 	if (tag_number == -1) {
625 		tag_number = it->utype;
626 		tag_class = V_ASN1_UNIVERSAL;
627 	}
628 
629 	ret = asn1_check_tag(&cbs_object, &length, NULL, NULL, &indefinite,
630 	    &constructed, tag_number, tag_class, optional);
631 	if (ret == -1)
632 		return -1;
633 	if (ret != 1) {
634 		ASN1error(ERR_R_NESTED_ASN1_ERROR);
635 		return 0;
636 	}
637 
638 	return asn1_d2i_primitive_content(pval, cbs, &cbs_object, utype,
639 	    constructed, indefinite, length, it);
640 }
641 
642 static int
643 asn1_item_d2i_choice(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it,
644     int tag_number, int tag_class, int optional, int depth)
645 {
646 	const ASN1_TEMPLATE *at, *errat = NULL;
647 	const ASN1_AUX *aux;
648 	ASN1_aux_cb *asn1_cb = NULL;
649 	ASN1_VALUE *achoice = NULL;
650 	ASN1_VALUE **pchptr;
651 	int i, ret;
652 
653 	if ((aux = it->funcs) != NULL)
654 		asn1_cb = aux->asn1_cb;
655 
656 	if (it->itype != ASN1_ITYPE_CHOICE)
657 		goto err;
658 
659 	/*
660 	 * It never makes sense for CHOICE types to have implicit tagging, so
661 	 * if tag_number != -1, then this looks like an error in the template.
662 	 */
663 	if (tag_number != -1) {
664 		ASN1error(ASN1_R_BAD_TEMPLATE);
665 		goto err;
666 	}
667 
668 	if (*pval != NULL) {
669 		ASN1_item_ex_free(pval, it);
670 		*pval = NULL;
671 	}
672 
673 	if (!ASN1_item_ex_new(&achoice, it)) {
674 		ASN1error(ERR_R_NESTED_ASN1_ERROR);
675 		goto err;
676 	}
677 
678 	if (asn1_cb != NULL && !asn1_cb(ASN1_OP_D2I_PRE, &achoice, it, NULL)) {
679 		ASN1error(ASN1_R_AUX_ERROR);
680 		goto err;
681 	}
682 
683 	/* Try each possible CHOICE in turn. */
684 	for (i = 0; i < it->tcount; i++) {
685 		at = &it->templates[i];
686 
687 		pchptr = asn1_get_field_ptr(&achoice, at);
688 
689 		/* Mark field as OPTIONAL so its absence can be identified. */
690 		ret = asn1_template_d2i(pchptr, cbs, at, 1, depth);
691 		if (ret == -1)
692 			continue;
693 		if (ret != 1) {
694 			ASN1error(ERR_R_NESTED_ASN1_ERROR);
695 			errat = at;
696 			goto err;
697 		}
698 
699 		/* We've successfully decoded an ASN.1 object. */
700 		asn1_set_choice_selector(&achoice, i, it);
701 		break;
702 	}
703 
704 	/* Did we fall off the end without reading anything? */
705 	if (i == it->tcount) {
706 		if (optional) {
707 			ASN1_item_ex_free(&achoice, it);
708 			return -1;
709 		}
710 		ASN1error(ASN1_R_NO_MATCHING_CHOICE_TYPE);
711 		goto err;
712 	}
713 
714 	if (asn1_cb != NULL && !asn1_cb(ASN1_OP_D2I_POST, &achoice, it, NULL)) {
715 		ASN1error(ASN1_R_AUX_ERROR);
716 		goto err;
717 	}
718 
719 	*pval = achoice;
720 	achoice = NULL;
721 
722 	return 1;
723 
724  err:
725 	ASN1_item_ex_free(&achoice, it);
726 
727 	if (errat != NULL)
728 		ERR_asprintf_error_data("Field=%s, Type=%s", errat->field_name,
729 		    it->sname);
730 	else
731 		ERR_asprintf_error_data("Type=%s", it->sname);
732 
733 	return 0;
734 }
735 
736 static int
737 asn1_item_d2i_sequence(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it,
738     int tag_number, int tag_class, int optional, int depth)
739 {
740 	CBS cbs_seq, cbs_seq_content, cbs_object;
741 	int constructed, indefinite, optional_field;
742 	const ASN1_TEMPLATE *errat = NULL;
743 	const ASN1_TEMPLATE *seqat, *at;
744 	ASN1_aux_cb *asn1_cb = NULL;
745 	const ASN1_AUX *aux;
746 	ASN1_VALUE *aseq = NULL;
747 	ASN1_VALUE **pseqval;
748 	int eoc_needed, i;
749 	size_t length;
750 	int ret = 0;
751 
752 	CBS_init(&cbs_seq, CBS_data(cbs), CBS_len(cbs));
753 
754 	if ((aux = it->funcs) != NULL)
755 		asn1_cb = aux->asn1_cb;
756 
757 	if (it->itype != ASN1_ITYPE_NDEF_SEQUENCE &&
758 	    it->itype != ASN1_ITYPE_SEQUENCE)
759 		goto err;
760 
761 	if (*pval != NULL) {
762 		ASN1_item_ex_free(pval, it);
763 		*pval = NULL;
764 	}
765 
766 	/* If no IMPLICIT tagging use UNIVERSAL/SEQUENCE. */
767 	if (tag_number == -1) {
768 		tag_class = V_ASN1_UNIVERSAL;
769 		tag_number = V_ASN1_SEQUENCE;
770 	}
771 
772 	/* Read ASN.1 SEQUENCE header. */
773 	ret = asn1_check_tag(&cbs_seq, &length, NULL, NULL, &indefinite,
774 	    &constructed, tag_number, tag_class, optional);
775 	if (ret == -1)
776 		return -1;
777 	if (ret != 1) {
778 		ASN1error(ERR_R_NESTED_ASN1_ERROR);
779 		goto err;
780 	}
781 
782 	if (!constructed) {
783 		ASN1error(ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
784 		goto err;
785 	}
786 
787 	if (indefinite) {
788 		eoc_needed = 1;
789 		CBS_init(&cbs_seq_content, CBS_data(&cbs_seq), CBS_len(&cbs_seq));
790 	} else {
791 		eoc_needed = 0;
792 		if (!CBS_get_bytes(&cbs_seq, &cbs_seq_content, length))
793 			goto err;
794 	}
795 
796 	if (!ASN1_item_ex_new(&aseq, it)) {
797 		ASN1error(ERR_R_NESTED_ASN1_ERROR);
798 		goto err;
799 	}
800 
801 	if (asn1_cb != NULL && !asn1_cb(ASN1_OP_D2I_PRE, &aseq, it, NULL)) {
802 		ASN1error(ASN1_R_AUX_ERROR);
803 		goto err;
804 	}
805 
806 	for (i = 0; i < it->tcount; i++) {
807 		at = &it->templates[i];
808 
809 		if (asn1_check_eoc(&cbs_seq_content)) {
810 			if (!indefinite) {
811 				ASN1error(ASN1_R_UNEXPECTED_EOC);
812 				goto err;
813 			}
814 			eoc_needed = 0;
815 			break;
816 		}
817 		if (CBS_len(&cbs_seq_content) == 0)
818 			break;
819 
820 		if ((seqat = asn1_do_adb(&aseq, at, 1)) == NULL)
821 			goto err;
822 
823 		pseqval = asn1_get_field_ptr(&aseq, seqat);
824 
825 		/*
826 		 * This was originally implemented to "increase efficiency",
827 		 * however it currently needs to remain since it papers over
828 		 * the use of ASN.1 ANY with OPTIONAL in SEQUENCEs (which
829 		 * asn1_d2i_primitive() currently rejects).
830 		 */
831 		optional_field = (seqat->flags & ASN1_TFLG_OPTIONAL) != 0;
832 		if (i == it->tcount - 1)
833 			optional_field = 0;
834 
835 		ret = asn1_template_d2i(pseqval, &cbs_seq_content,
836 		    seqat, optional_field, depth);
837 		if (ret == -1) {
838 			/* Absent OPTIONAL component. */
839 			ASN1_template_free(pseqval, seqat);
840 			continue;
841 		}
842 		if (ret != 1) {
843 			errat = seqat;
844 			goto err;
845 		}
846 	}
847 
848 	if (eoc_needed && !asn1_check_eoc(&cbs_seq_content)) {
849 		ASN1error(ASN1_R_MISSING_EOC);
850 		goto err;
851 	}
852 
853 	if (indefinite) {
854 		if (!CBS_skip(&cbs_seq, CBS_offset(&cbs_seq_content)))
855 			goto err;
856 	} else if (CBS_len(&cbs_seq_content) != 0) {
857 		ASN1error(ASN1_R_SEQUENCE_LENGTH_MISMATCH);
858 		goto err;
859 	}
860 
861 	/*
862 	 * There is no more data in the ASN.1 SEQUENCE, however we may not have
863 	 * populated all fields - check that any remaining are OPTIONAL.
864 	 */
865 	for (; i < it->tcount; i++) {
866 		at = &it->templates[i];
867 
868 		if ((seqat = asn1_do_adb(&aseq, at, 1)) == NULL)
869 			goto err;
870 
871 		if ((seqat->flags & ASN1_TFLG_OPTIONAL) == 0) {
872 			ASN1error(ASN1_R_FIELD_MISSING);
873 			errat = seqat;
874 			goto err;
875 		}
876 
877 		/* XXX - this is probably unnecessary with earlier free. */
878 		pseqval = asn1_get_field_ptr(&aseq, seqat);
879 		ASN1_template_free(pseqval, seqat);
880 	}
881 
882 	if (!CBS_get_bytes(cbs, &cbs_object, CBS_offset(&cbs_seq)))
883 		goto err;
884 
885 	if (!asn1_enc_save(&aseq, &cbs_object, it)) {
886 		ASN1error(ERR_R_MALLOC_FAILURE);
887 		goto err;
888 	}
889 
890 	if (asn1_cb != NULL && !asn1_cb(ASN1_OP_D2I_POST, &aseq, it, NULL)) {
891 		ASN1error(ASN1_R_AUX_ERROR);
892 		goto err;
893 	}
894 
895 	*pval = aseq;
896 	aseq = NULL;
897 
898 	return 1;
899 
900  err:
901 	ASN1_item_ex_free(&aseq, it);
902 
903 	if (errat != NULL)
904 		ERR_asprintf_error_data("Field=%s, Type=%s", errat->field_name,
905 		    it->sname);
906 	else
907 		ERR_asprintf_error_data("Type=%s", it->sname);
908 
909 	return 0;
910 }
911 
912 static int
913 asn1_item_d2i_extern(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it,
914     int tag_number, int tag_class, int optional)
915 {
916 	const ASN1_EXTERN_FUNCS *ef = it->funcs;
917 	const unsigned char *p = NULL;
918 	ASN1_TLC ctx = { 0 };
919 	int ret = 0;
920 
921 	if (CBS_len(cbs) > LONG_MAX)
922 		return 0;
923 
924 	p = CBS_data(cbs);
925 
926 	if ((ret = ef->asn1_ex_d2i(pval, &p, (long)CBS_len(cbs), it,
927 	    tag_number, tag_class, optional, &ctx)) == 1) {
928 		if (!CBS_skip(cbs, p - CBS_data(cbs)))
929 			goto err;
930 	}
931 	return ret;
932 
933  err:
934 	ASN1_item_ex_free(pval, it);
935 
936 	ERR_asprintf_error_data("Type=%s", it->sname);
937 
938 	return 0;
939 }
940 
941 static int
942 asn1_item_d2i(ASN1_VALUE **pval, CBS *cbs, const ASN1_ITEM *it,
943     int tag_number, int tag_class, int optional, int depth)
944 {
945 	if (pval == NULL)
946 		return 0;
947 
948 	if (++depth > ASN1_MAX_CONSTRUCTED_NEST) {
949 		ASN1error(ASN1_R_NESTED_TOO_DEEP);
950 		goto err;
951 	}
952 
953 	switch (it->itype) {
954 	case ASN1_ITYPE_PRIMITIVE:
955 		if (it->templates != NULL) {
956 			/*
957 			 * Tagging or OPTIONAL is currently illegal on an item
958 			 * template because the flags can't get passed down.
959 			 * In practice this isn't a problem: we include the
960 			 * relevant flags from the item template in the
961 			 * template itself.
962 			 */
963 			if (tag_number != -1 || optional) {
964 				ASN1error(ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
965 				goto err;
966 			}
967 			return asn1_template_d2i(pval, cbs, it->templates,
968 			    optional, depth);
969 		}
970 		return asn1_d2i_primitive(pval, cbs, it, tag_number, tag_class,
971 		    optional);
972 
973 	case ASN1_ITYPE_MSTRING:
974 		return asn1_d2i_mstring(pval, cbs, it, tag_number, tag_class,
975 		    optional);
976 
977 	case ASN1_ITYPE_EXTERN:
978 		return asn1_item_d2i_extern(pval, cbs, it, tag_number,
979 		    tag_class, optional);
980 
981 	case ASN1_ITYPE_CHOICE:
982 		return asn1_item_d2i_choice(pval, cbs, it, tag_number,
983 		    tag_class, optional, depth);
984 
985 	case ASN1_ITYPE_NDEF_SEQUENCE:
986 	case ASN1_ITYPE_SEQUENCE:
987 		return asn1_item_d2i_sequence(pval, cbs, it, tag_number,
988 		    tag_class, optional, depth);
989 
990 	default:
991 		return 0;
992 	}
993 
994  err:
995 	ASN1_item_ex_free(pval, it);
996 
997 	ERR_asprintf_error_data("Type=%s", it->sname);
998 
999 	return 0;
1000 }
1001 
1002 static void
1003 asn1_template_stack_of_free(STACK_OF(ASN1_VALUE) *avals, const ASN1_TEMPLATE *at) {
1004 	ASN1_VALUE *aval;
1005 
1006 	if (avals == NULL)
1007 		return;
1008 
1009 	while (sk_ASN1_VALUE_num(avals) > 0) {
1010 		aval = sk_ASN1_VALUE_pop(avals);
1011 		ASN1_item_ex_free(&aval, at->item);
1012 	}
1013 	sk_ASN1_VALUE_free(avals);
1014 }
1015 
1016 static int
1017 asn1_template_stack_of_d2i(ASN1_VALUE **pval, CBS *cbs, const ASN1_TEMPLATE *at,
1018     int optional, int depth)
1019 {
1020 	CBS cbs_object, cbs_object_content;
1021 	STACK_OF(ASN1_VALUE) *avals = NULL;
1022 	ASN1_VALUE *aval = NULL;
1023 	int tag_number, tag_class;
1024 	int eoc_needed;
1025 	int indefinite;
1026 	size_t length;
1027 	int ret;
1028 
1029 	CBS_init(&cbs_object, CBS_data(cbs), CBS_len(cbs));
1030 
1031 	if (pval == NULL)
1032 		return 0;
1033 
1034 	asn1_template_stack_of_free((STACK_OF(ASN1_VALUE) *)*pval, at);
1035 	*pval = NULL;
1036 
1037 	tag_number = at->tag;
1038 	tag_class = at->flags & ASN1_TFLG_TAG_CLASS;
1039 
1040 	/* Determine the inner tag value for SET OF or SEQUENCE OF. */
1041 	if ((at->flags & ASN1_TFLG_IMPTAG) == 0) {
1042 		tag_number = V_ASN1_SEQUENCE;
1043 		tag_class = V_ASN1_UNIVERSAL;
1044 		if ((at->flags & ASN1_TFLG_SET_OF) != 0)
1045 			tag_number = V_ASN1_SET;
1046 	}
1047 
1048 	ret = asn1_check_tag(&cbs_object, &length, NULL, NULL, &indefinite,
1049 	    NULL, tag_number, tag_class, optional);
1050 	if (ret == -1)
1051 		return -1;
1052 	if (ret != 1) {
1053 		ASN1error(ERR_R_NESTED_ASN1_ERROR);
1054 		return 0;
1055 	}
1056 
1057 	if (indefinite) {
1058 		eoc_needed = 1;
1059 		CBS_init(&cbs_object_content, CBS_data(&cbs_object),
1060 		    CBS_len(&cbs_object));
1061 	} else {
1062 		eoc_needed = 0;
1063 		if (!CBS_get_bytes(&cbs_object, &cbs_object_content,
1064 		    length))
1065 			goto err;
1066 	}
1067 
1068 	if ((avals = sk_ASN1_VALUE_new_null()) == NULL) {
1069 		ASN1error(ERR_R_MALLOC_FAILURE);
1070 		goto err;
1071 	}
1072 
1073 	/* Read as many items as possible. */
1074 	while (CBS_len(&cbs_object_content) > 0) {
1075 		if (asn1_check_eoc(&cbs_object_content)) {
1076 			if (!eoc_needed) {
1077 				ASN1error(ASN1_R_UNEXPECTED_EOC);
1078 				goto err;
1079 			}
1080 			eoc_needed = 0;
1081 			break;
1082 		}
1083 		if (!asn1_item_d2i(&aval, &cbs_object_content, at->item,
1084 		    -1, 0, 0, depth)) {
1085 			ASN1error(ERR_R_NESTED_ASN1_ERROR);
1086 			goto err;
1087 		}
1088 		if (!sk_ASN1_VALUE_push(avals, aval)) {
1089 			ASN1error(ERR_R_MALLOC_FAILURE);
1090 			goto err;
1091 		}
1092 		aval = NULL;
1093 	}
1094 	if (eoc_needed) {
1095 		ASN1error(ASN1_R_MISSING_EOC);
1096 		goto err;
1097 	}
1098 
1099 	if (indefinite) {
1100 		if (!CBS_skip(&cbs_object, CBS_offset(&cbs_object_content)))
1101 			goto err;
1102 	}
1103 
1104 	if (!CBS_skip(cbs, CBS_offset(&cbs_object)))
1105 		goto err;
1106 
1107 	*pval = (ASN1_VALUE *)avals;
1108 	avals = NULL;
1109 
1110 	return 1;
1111 
1112  err:
1113 	asn1_template_stack_of_free(avals, at);
1114 	ASN1_item_ex_free(&aval, at->item);
1115 
1116 	return 0;
1117 }
1118 
1119 static int
1120 asn1_template_noexp_d2i(ASN1_VALUE **pval, CBS *cbs, const ASN1_TEMPLATE *at,
1121     int optional, int depth)
1122 {
1123 	int tag_number, tag_class;
1124 	int ret;
1125 
1126 	if (pval == NULL)
1127 		return 0;
1128 
1129 	if ((at->flags & ASN1_TFLG_SK_MASK) != 0)
1130 		return asn1_template_stack_of_d2i(pval, cbs, at, optional, depth);
1131 
1132 	tag_number = -1;
1133 	tag_class = V_ASN1_UNIVERSAL;
1134 
1135 	/* See if we need to use IMPLICIT tagging. */
1136 	if ((at->flags & ASN1_TFLG_IMPTAG) != 0) {
1137 		tag_number = at->tag;
1138 		tag_class = at->flags & ASN1_TFLG_TAG_CLASS;
1139 	}
1140 
1141 	ret = asn1_item_d2i(pval, cbs, at->item, tag_number, tag_class,
1142 	    optional, depth);
1143 	if (ret == -1)
1144 		return -1;
1145 	if (ret != 1) {
1146 		ASN1error(ERR_R_NESTED_ASN1_ERROR);
1147 		goto err;
1148 	}
1149 
1150 	return 1;
1151 
1152  err:
1153 	/* XXX - The called function should have freed already. */
1154 	ASN1_template_free(pval, at);
1155 	return 0;
1156 }
1157 
1158 static int
1159 asn1_template_d2i(ASN1_VALUE **pval, CBS *cbs, const ASN1_TEMPLATE *at,
1160     int optional, int depth)
1161 {
1162 	CBS cbs_exp, cbs_exp_content;
1163 	int constructed, indefinite;
1164 	size_t length;
1165 	int ret;
1166 
1167 	if (pval == NULL)
1168 		return 0;
1169 
1170 	/* Check if EXPLICIT tag is expected. */
1171 	if ((at->flags & ASN1_TFLG_EXPTAG) == 0)
1172 		return asn1_template_noexp_d2i(pval, cbs, at, optional, depth);
1173 
1174 	CBS_init(&cbs_exp, CBS_data(cbs), CBS_len(cbs));
1175 
1176 	/* Read ASN.1 header for EXPLICIT tagged object. */
1177 	ret = asn1_check_tag(&cbs_exp, &length, NULL, NULL, &indefinite,
1178 	    &constructed, at->tag, at->flags & ASN1_TFLG_TAG_CLASS, optional);
1179 	if (ret == -1)
1180 		return -1;
1181 	if (ret != 1) {
1182 		ASN1error(ERR_R_NESTED_ASN1_ERROR);
1183 		return 0;
1184 	}
1185 
1186 	if (!constructed) {
1187 		ASN1error(ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);
1188 		return 0;
1189 	}
1190 
1191 	if (indefinite) {
1192 		CBS_init(&cbs_exp_content, CBS_data(&cbs_exp), CBS_len(&cbs_exp));
1193 	} else {
1194 		if (!CBS_get_bytes(&cbs_exp, &cbs_exp_content, length))
1195 			goto err;
1196 	}
1197 
1198 	if ((ret = asn1_template_noexp_d2i(pval, &cbs_exp_content, at, 0,
1199 	    depth)) != 1) {
1200 		ASN1error(ERR_R_NESTED_ASN1_ERROR);
1201 		return 0;
1202 	}
1203 
1204 	if (indefinite) {
1205 		if (!asn1_check_eoc(&cbs_exp_content)) {
1206 			ASN1error(ASN1_R_MISSING_EOC);
1207 			goto err;
1208 		}
1209 		if (!CBS_skip(&cbs_exp, CBS_offset(&cbs_exp_content)))
1210 			goto err;
1211 	} else if (CBS_len(&cbs_exp_content) != 0) {
1212 		ASN1error(ASN1_R_SEQUENCE_LENGTH_MISMATCH);
1213 		goto err;
1214 	}
1215 
1216 	if (!CBS_skip(cbs, CBS_offset(&cbs_exp)))
1217 		goto err;
1218 
1219 	return 1;
1220 
1221  err:
1222 	ASN1_template_free(pval, at);
1223 	return 0;
1224 }
1225 
1226 ASN1_VALUE *
1227 ASN1_item_d2i(ASN1_VALUE **pval, const unsigned char **in, long inlen,
1228     const ASN1_ITEM *it)
1229 {
1230 	ASN1_VALUE *ptmpval = NULL;
1231 
1232 	if (pval == NULL)
1233 		pval = &ptmpval;
1234 	if (ASN1_item_ex_d2i(pval, in, inlen, it, -1, 0, 0, NULL) <= 0)
1235 		return NULL;
1236 
1237 	return *pval;
1238 }
1239 
1240 int
1241 ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long inlen,
1242     const ASN1_ITEM *it, int tag_number, int tag_class, char optional,
1243     ASN1_TLC *ctx)
1244 {
1245 	CBS cbs;
1246 	int ret;
1247 
1248 	if (inlen < 0)
1249 		return 0;
1250 
1251 	CBS_init(&cbs, *in, inlen);
1252 	if ((ret = asn1_item_d2i(pval, &cbs, it, tag_number, tag_class,
1253 	    (int)optional, 0)) == 1)
1254 		*in = CBS_data(&cbs);
1255 
1256 	return ret;
1257 }
1258 
1259 int
1260 ASN1_template_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
1261     const ASN1_TEMPLATE *at)
1262 {
1263 	CBS cbs;
1264 	int ret;
1265 
1266 	if (len < 0)
1267 		return 0;
1268 
1269 	CBS_init(&cbs, *in, len);
1270 	if ((ret = asn1_template_d2i(pval, &cbs, at, 0, 0)) == 1)
1271 		*in = CBS_data(&cbs);
1272 
1273 	return ret;
1274 }
1275