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