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