xref: /openbsd-src/lib/libcrypto/asn1/tasn_dec.c (revision 9f11ffb7133c203312a01e4b986886bc88c7d74b)
1 /* $OpenBSD: tasn_dec.c,v 1.36 2018/09/17 18:18:01 tb 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 	int ret = 0;
797 	const ASN1_PRIMITIVE_FUNCS *pf;
798 	ASN1_INTEGER **tint;
799 
800 	pf = it->funcs;
801 
802 	if (pf && pf->prim_c2i)
803 		return pf->prim_c2i(pval, cont, len, utype, free_cont, it);
804 	/* If ANY type clear type and set pointer to internal value */
805 	if (it->utype == V_ASN1_ANY) {
806 		if (!*pval) {
807 			typ = ASN1_TYPE_new();
808 			if (typ == NULL)
809 				goto err;
810 			*pval = (ASN1_VALUE *)typ;
811 		} else
812 			typ = (ASN1_TYPE *)*pval;
813 
814 		if (utype != typ->type)
815 			ASN1_TYPE_set(typ, utype, NULL);
816 		opval = pval;
817 		pval = &typ->value.asn1_value;
818 	}
819 	switch (utype) {
820 	case V_ASN1_OBJECT:
821 		if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len))
822 			goto err;
823 		break;
824 
825 	case V_ASN1_NULL:
826 		if (len) {
827 			ASN1error(ASN1_R_NULL_IS_WRONG_LENGTH);
828 			goto err;
829 		}
830 		*pval = (ASN1_VALUE *)1;
831 		break;
832 
833 	case V_ASN1_BOOLEAN:
834 		if (len != 1) {
835 			ASN1error(ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
836 			goto err;
837 		} else {
838 			ASN1_BOOLEAN *tbool;
839 			tbool = (ASN1_BOOLEAN *)pval;
840 			*tbool = *cont;
841 		}
842 		break;
843 
844 	case V_ASN1_BIT_STRING:
845 		if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len))
846 			goto err;
847 		break;
848 
849 	case V_ASN1_INTEGER:
850 	case V_ASN1_ENUMERATED:
851 		tint = (ASN1_INTEGER **)pval;
852 		if (!c2i_ASN1_INTEGER(tint, &cont, len))
853 			goto err;
854 		/* Fixup type to match the expected form */
855 		(*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
856 		break;
857 
858 	case V_ASN1_OCTET_STRING:
859 	case V_ASN1_NUMERICSTRING:
860 	case V_ASN1_PRINTABLESTRING:
861 	case V_ASN1_T61STRING:
862 	case V_ASN1_VIDEOTEXSTRING:
863 	case V_ASN1_IA5STRING:
864 	case V_ASN1_UTCTIME:
865 	case V_ASN1_GENERALIZEDTIME:
866 	case V_ASN1_GRAPHICSTRING:
867 	case V_ASN1_VISIBLESTRING:
868 	case V_ASN1_GENERALSTRING:
869 	case V_ASN1_UNIVERSALSTRING:
870 	case V_ASN1_BMPSTRING:
871 	case V_ASN1_UTF8STRING:
872 	case V_ASN1_OTHER:
873 	case V_ASN1_SET:
874 	case V_ASN1_SEQUENCE:
875 	default:
876 		if (utype == V_ASN1_BMPSTRING && (len & 1)) {
877 			ASN1error(ASN1_R_BMPSTRING_IS_WRONG_LENGTH);
878 			goto err;
879 		}
880 		if (utype == V_ASN1_UNIVERSALSTRING && (len & 3)) {
881 			ASN1error(ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH);
882 			goto err;
883 		}
884 		/* All based on ASN1_STRING and handled the same */
885 		if (!*pval) {
886 			stmp = ASN1_STRING_type_new(utype);
887 			if (!stmp) {
888 				ASN1error(ERR_R_MALLOC_FAILURE);
889 				goto err;
890 			}
891 			*pval = (ASN1_VALUE *)stmp;
892 		} else {
893 			stmp = (ASN1_STRING *)*pval;
894 			stmp->type = utype;
895 		}
896 		/* If we've already allocated a buffer use it */
897 		if (*free_cont) {
898 			free(stmp->data);
899 			stmp->data = (unsigned char *)cont; /* UGLY CAST! RL */
900 			stmp->length = len;
901 			*free_cont = 0;
902 		} else {
903 			if (!ASN1_STRING_set(stmp, cont, len)) {
904 				ASN1error(ERR_R_MALLOC_FAILURE);
905 				ASN1_STRING_free(stmp);
906 				*pval = NULL;
907 				goto err;
908 			}
909 		}
910 		break;
911 	}
912 	/* If ASN1_ANY and NULL type fix up value */
913 	if (typ && (utype == V_ASN1_NULL))
914 		typ->value.ptr = NULL;
915 
916 	ret = 1;
917 
918 err:
919 	if (!ret) {
920 		ASN1_TYPE_free(typ);
921 		if (opval)
922 			*opval = NULL;
923 	}
924 	return ret;
925 }
926 
927 
928 /* This function finds the end of an ASN1 structure when passed its maximum
929  * length, whether it is indefinite length and a pointer to the content.
930  * This is more efficient than calling asn1_collect because it does not
931  * recurse on each indefinite length header.
932  */
933 
934 static int
935 asn1_find_end(const unsigned char **in, long len, char inf)
936 {
937 	int expected_eoc;
938 	long plen;
939 	const unsigned char *p = *in, *q;
940 
941 	/* If not indefinite length constructed just add length */
942 	if (inf == 0) {
943 		*in += len;
944 		return 1;
945 	}
946 	expected_eoc = 1;
947 	/* Indefinite length constructed form. Find the end when enough EOCs
948 	 * are found. If more indefinite length constructed headers
949 	 * are encountered increment the expected eoc count otherwise just
950 	 * skip to the end of the data.
951 	 */
952 	while (len > 0) {
953 		if (asn1_check_eoc(&p, len)) {
954 			expected_eoc--;
955 			if (expected_eoc == 0)
956 				break;
957 			len -= 2;
958 			continue;
959 		}
960 		q = p;
961 		/* Just read in a header: only care about the length */
962 		if (!asn1_check_tlen(&plen, NULL, NULL, &inf, NULL, &p, len,
963 		    -1, 0, 0, NULL)) {
964 			ASN1error(ERR_R_NESTED_ASN1_ERROR);
965 			return 0;
966 		}
967 		if (inf)
968 			expected_eoc++;
969 		else
970 			p += plen;
971 		len -= p - q;
972 	}
973 	if (expected_eoc) {
974 		ASN1error(ASN1_R_MISSING_EOC);
975 		return 0;
976 	}
977 	*in = p;
978 	return 1;
979 }
980 /* This function collects the asn1 data from a constructred string
981  * type into a buffer. The values of 'in' and 'len' should refer
982  * to the contents of the constructed type and 'inf' should be set
983  * if it is indefinite length.
984  */
985 
986 #ifndef ASN1_MAX_STRING_NEST
987 /* This determines how many levels of recursion are permitted in ASN1
988  * string types. If it is not limited stack overflows can occur. If set
989  * to zero no recursion is allowed at all. Although zero should be adequate
990  * examples exist that require a value of 1. So 5 should be more than enough.
991  */
992 #define ASN1_MAX_STRING_NEST 5
993 #endif
994 
995 static int
996 asn1_collect(BUF_MEM *buf, const unsigned char **in, long len, char inf,
997     int tag, int aclass, int depth)
998 {
999 	const unsigned char *p, *q;
1000 	long plen;
1001 	char cst, ininf;
1002 
1003 	p = *in;
1004 	inf &= 1;
1005 	/* If no buffer and not indefinite length constructed just pass over
1006 	 * the encoded data */
1007 	if (!buf && !inf) {
1008 		*in += len;
1009 		return 1;
1010 	}
1011 	while (len > 0) {
1012 		q = p;
1013 		/* Check for EOC */
1014 		if (asn1_check_eoc(&p, len)) {
1015 			/* EOC is illegal outside indefinite length
1016 			 * constructed form */
1017 			if (!inf) {
1018 				ASN1error(ASN1_R_UNEXPECTED_EOC);
1019 				return 0;
1020 			}
1021 			inf = 0;
1022 			break;
1023 		}
1024 
1025 		if (!asn1_check_tlen(&plen, NULL, NULL, &ininf, &cst, &p,
1026 		    len, tag, aclass, 0, NULL)) {
1027 			ASN1error(ERR_R_NESTED_ASN1_ERROR);
1028 			return 0;
1029 		}
1030 
1031 		/* If indefinite length constructed update max length */
1032 		if (cst) {
1033 			if (depth >= ASN1_MAX_STRING_NEST) {
1034 				ASN1error(ASN1_R_NESTED_ASN1_STRING);
1035 				return 0;
1036 			}
1037 			if (!asn1_collect(buf, &p, plen, ininf, tag, aclass,
1038 			    depth + 1))
1039 				return 0;
1040 		} else if (plen && !collect_data(buf, &p, plen))
1041 			return 0;
1042 		len -= p - q;
1043 	}
1044 	if (inf) {
1045 		ASN1error(ASN1_R_MISSING_EOC);
1046 		return 0;
1047 	}
1048 	*in = p;
1049 	return 1;
1050 }
1051 
1052 static int
1053 collect_data(BUF_MEM *buf, const unsigned char **p, long plen)
1054 {
1055 	int len;
1056 	if (buf) {
1057 		len = buf->length;
1058 		if (!BUF_MEM_grow_clean(buf, len + plen)) {
1059 			ASN1error(ERR_R_MALLOC_FAILURE);
1060 			return 0;
1061 		}
1062 		memcpy(buf->data + len, *p, plen);
1063 	}
1064 	*p += plen;
1065 	return 1;
1066 }
1067 
1068 /* Check for ASN1 EOC and swallow it if found */
1069 
1070 static int
1071 asn1_check_eoc(const unsigned char **in, long len)
1072 {
1073 	const unsigned char *p;
1074 
1075 	if (len < 2)
1076 		return 0;
1077 	p = *in;
1078 	if (!p[0] && !p[1]) {
1079 		*in += 2;
1080 		return 1;
1081 	}
1082 	return 0;
1083 }
1084 
1085 /* Check an ASN1 tag and length: a bit like ASN1_get_object
1086  * but it sets the length for indefinite length constructed
1087  * form, we don't know the exact length but we can set an
1088  * upper bound to the amount of data available minus the
1089  * header length just read.
1090  */
1091 
1092 static int
1093 asn1_check_tlen(long *olen, int *otag, unsigned char *oclass, char *inf,
1094     char *cst, const unsigned char **in, long len, int exptag, int expclass,
1095     char opt, ASN1_TLC *ctx)
1096 {
1097 	int i;
1098 	int ptag, pclass;
1099 	long plen;
1100 	const unsigned char *p, *q;
1101 
1102 	p = *in;
1103 	q = p;
1104 
1105 	if (ctx && ctx->valid) {
1106 		i = ctx->ret;
1107 		plen = ctx->plen;
1108 		pclass = ctx->pclass;
1109 		ptag = ctx->ptag;
1110 		p += ctx->hdrlen;
1111 	} else {
1112 		i = ASN1_get_object(&p, &plen, &ptag, &pclass, len);
1113 		if (ctx) {
1114 			ctx->ret = i;
1115 			ctx->plen = plen;
1116 			ctx->pclass = pclass;
1117 			ctx->ptag = ptag;
1118 			ctx->hdrlen = p - q;
1119 			ctx->valid = 1;
1120 			/* If definite length, and no error, length +
1121 			 * header can't exceed total amount of data available.
1122 			 */
1123 			if (!(i & 0x81) && ((plen + ctx->hdrlen) > len)) {
1124 				ASN1error(ASN1_R_TOO_LONG);
1125 				asn1_tlc_clear(ctx);
1126 				return 0;
1127 			}
1128 		}
1129 	}
1130 
1131 	if (i & 0x80) {
1132 		ASN1error(ASN1_R_BAD_OBJECT_HEADER);
1133 		asn1_tlc_clear(ctx);
1134 		return 0;
1135 	}
1136 	if (exptag >= 0) {
1137 		if ((exptag != ptag) || (expclass != pclass)) {
1138 			/* If type is OPTIONAL, not an error:
1139 			 * indicate missing type.
1140 			 */
1141 			if (opt)
1142 				return -1;
1143 			asn1_tlc_clear(ctx);
1144 			ASN1error(ASN1_R_WRONG_TAG);
1145 			return 0;
1146 		}
1147 		/* We have a tag and class match:
1148 		 * assume we are going to do something with it */
1149 		asn1_tlc_clear(ctx);
1150 	}
1151 
1152 	if (i & 1)
1153 		plen = len - (p - q);
1154 	if (inf)
1155 		*inf = i & 1;
1156 	if (cst)
1157 		*cst = i & V_ASN1_CONSTRUCTED;
1158 	if (olen)
1159 		*olen = plen;
1160 	if (oclass)
1161 		*oclass = pclass;
1162 	if (otag)
1163 		*otag = ptag;
1164 
1165 	*in = p;
1166 	return 1;
1167 }
1168