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