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