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