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