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