tasn_dec.c revision 291854
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	int combine = aclass & ASN1_TFLG_COMBINE;
173	aclass &= ~ASN1_TFLG_COMBINE;
174	if (!pval)
175		return 0;
176	if (aux && aux->asn1_cb)
177		asn1_cb = aux->asn1_cb;
178	else asn1_cb = 0;
179
180	switch(it->itype)
181		{
182		case ASN1_ITYPE_PRIMITIVE:
183		if (it->templates)
184			{
185			/* tagging or OPTIONAL is currently illegal on an item
186			 * template because the flags can't get passed down.
187			 * In practice this isn't a problem: we include the
188			 * relevant flags from the item template in the
189			 * template itself.
190			 */
191			if ((tag != -1) || opt)
192				{
193				ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
194				ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
195				goto err;
196				}
197			return asn1_template_ex_d2i(pval, in, len,
198					it->templates, opt, ctx);
199		}
200		return asn1_d2i_ex_primitive(pval, in, len, it,
201						tag, aclass, opt, ctx);
202		break;
203
204		case ASN1_ITYPE_MSTRING:
205		p = *in;
206		/* Just read in tag and class */
207		ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, NULL,
208						&p, len, -1, 0, 1, ctx);
209		if (!ret)
210			{
211			ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
212					ERR_R_NESTED_ASN1_ERROR);
213			goto err;
214			}
215
216		/* Must be UNIVERSAL class */
217		if (oclass != V_ASN1_UNIVERSAL)
218			{
219			/* If OPTIONAL, assume this is OK */
220			if (opt) return -1;
221			ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
222					ASN1_R_MSTRING_NOT_UNIVERSAL);
223			goto err;
224			}
225		/* Check tag matches bit map */
226		if (!(ASN1_tag2bit(otag) & it->utype))
227			{
228			/* If OPTIONAL, assume this is OK */
229			if (opt)
230				return -1;
231			ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
232					ASN1_R_MSTRING_WRONG_TAG);
233			goto err;
234			}
235		return asn1_d2i_ex_primitive(pval, in, len,
236						it, otag, 0, 0, ctx);
237
238		case ASN1_ITYPE_EXTERN:
239		/* Use new style d2i */
240		ef = it->funcs;
241		return ef->asn1_ex_d2i(pval, in, len,
242						it, tag, aclass, opt, ctx);
243
244		case ASN1_ITYPE_COMPAT:
245		/* we must resort to old style evil hackery */
246		cf = it->funcs;
247
248		/* If OPTIONAL see if it is there */
249		if (opt)
250			{
251			int exptag;
252			p = *in;
253			if (tag == -1)
254				exptag = it->utype;
255			else exptag = tag;
256			/* Don't care about anything other than presence
257			 * of expected tag */
258
259			ret = asn1_check_tlen(NULL, NULL, NULL, NULL, NULL,
260					&p, len, exptag, aclass, 1, ctx);
261			if (!ret)
262				{
263				ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
264					ERR_R_NESTED_ASN1_ERROR);
265				goto err;
266				}
267			if (ret == -1)
268				return -1;
269			}
270
271		/* This is the old style evil hack IMPLICIT handling:
272		 * since the underlying code is expecting a tag and
273		 * class other than the one present we change the
274		 * buffer temporarily then change it back afterwards.
275		 * This doesn't and never did work for tags > 30.
276		 *
277		 * Yes this is *horrible* but it is only needed for
278		 * old style d2i which will hopefully not be around
279		 * for much longer.
280		 * FIXME: should copy the buffer then modify it so
281		 * the input buffer can be const: we should *always*
282		 * copy because the old style d2i might modify the
283		 * buffer.
284		 */
285
286		if (tag != -1)
287			{
288			wp = *(unsigned char **)in;
289			imphack = *wp;
290			if (p == NULL)
291				{
292				ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
293					ERR_R_NESTED_ASN1_ERROR);
294				goto err;
295				}
296			*wp = (unsigned char)((*p & V_ASN1_CONSTRUCTED)
297								| it->utype);
298			}
299
300		ptmpval = cf->asn1_d2i(pval, in, len);
301
302		if (tag != -1)
303			*wp = imphack;
304
305		if (ptmpval)
306			return 1;
307
308		ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ERR_R_NESTED_ASN1_ERROR);
309		goto err;
310
311
312		case ASN1_ITYPE_CHOICE:
313		if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
314				goto auxerr;
315
316		if (*pval) {
317			/* Free up and zero CHOICE value if initialised */
318			i = asn1_get_choice_selector(pval, it);
319			if ((i >= 0) && (i < it->tcount)) {
320				tt = it->templates + i;
321				pchptr = asn1_get_field_ptr(pval, tt);
322				ASN1_template_free(pchptr, tt);
323				asn1_set_choice_selector(pval, -1, it);
324			}
325		} else if (!ASN1_item_ex_new(pval, it)) {
326			ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
327						ERR_R_NESTED_ASN1_ERROR);
328			goto err;
329		}
330		/* CHOICE type, try each possibility in turn */
331		p = *in;
332		for (i = 0, tt=it->templates; i < it->tcount; i++, tt++)
333			{
334			pchptr = asn1_get_field_ptr(pval, tt);
335			/* We mark field as OPTIONAL so its absence
336			 * can be recognised.
337			 */
338			ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, ctx);
339			/* If field not present, try the next one */
340			if (ret == -1)
341				continue;
342			/* If positive return, read OK, break loop */
343			if (ret > 0)
344				break;
345			/* Otherwise must be an ASN1 parsing error */
346			errtt = tt;
347			ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
348						ERR_R_NESTED_ASN1_ERROR);
349			goto err;
350			}
351
352		/* Did we fall off the end without reading anything? */
353		if (i == it->tcount)
354			{
355			/* If OPTIONAL, this is OK */
356			if (opt)
357				{
358				/* Free and zero it */
359				ASN1_item_ex_free(pval, it);
360				return -1;
361				}
362			ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
363					ASN1_R_NO_MATCHING_CHOICE_TYPE);
364			goto err;
365			}
366
367		asn1_set_choice_selector(pval, i, it);
368		*in = p;
369		if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
370				goto auxerr;
371		return 1;
372
373		case ASN1_ITYPE_NDEF_SEQUENCE:
374		case ASN1_ITYPE_SEQUENCE:
375		p = *in;
376		tmplen = len;
377
378		/* If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL */
379		if (tag == -1)
380			{
381			tag = V_ASN1_SEQUENCE;
382			aclass = V_ASN1_UNIVERSAL;
383			}
384		/* Get SEQUENCE length and update len, p */
385		ret = asn1_check_tlen(&len, NULL, NULL, &seq_eoc, &cst,
386					&p, len, tag, aclass, opt, ctx);
387		if (!ret)
388			{
389			ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
390					ERR_R_NESTED_ASN1_ERROR);
391			goto err;
392			}
393		else if (ret == -1)
394			return -1;
395		if (aux && (aux->flags & ASN1_AFLG_BROKEN))
396			{
397			len = tmplen - (p - *in);
398			seq_nolen = 1;
399			}
400		/* If indefinite we don't do a length check */
401		else seq_nolen = seq_eoc;
402		if (!cst)
403			{
404			ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
405				ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
406			goto err;
407			}
408
409		if (!*pval && !ASN1_item_ex_new(pval, it))
410			{
411			ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
412				ERR_R_NESTED_ASN1_ERROR);
413			goto err;
414			}
415
416		if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL))
417				goto auxerr;
418
419		/* Free up and zero any ADB found */
420		for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
421			if (tt->flags & ASN1_TFLG_ADB_MASK) {
422				const ASN1_TEMPLATE *seqtt;
423				ASN1_VALUE **pseqval;
424				seqtt = asn1_do_adb(pval, tt, 1);
425				pseqval = asn1_get_field_ptr(pval, seqtt);
426				ASN1_template_free(pseqval, seqtt);
427			}
428		}
429
430		/* Get each field entry */
431		for (i = 0, tt = it->templates; i < it->tcount; i++, tt++)
432			{
433			const ASN1_TEMPLATE *seqtt;
434			ASN1_VALUE **pseqval;
435			seqtt = asn1_do_adb(pval, tt, 1);
436			if (!seqtt)
437				goto err;
438			pseqval = asn1_get_field_ptr(pval, seqtt);
439			/* Have we ran out of data? */
440			if (!len)
441				break;
442			q = p;
443			if (asn1_check_eoc(&p, len))
444				{
445				if (!seq_eoc)
446					{
447					ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
448							ASN1_R_UNEXPECTED_EOC);
449					goto err;
450					}
451				len -= p - q;
452				seq_eoc = 0;
453				q = p;
454				break;
455				}
456			/* This determines the OPTIONAL flag value. The field
457			 * cannot be omitted if it is the last of a SEQUENCE
458			 * and there is still data to be read. This isn't
459			 * strictly necessary but it increases efficiency in
460			 * some cases.
461			 */
462			if (i == (it->tcount - 1))
463				isopt = 0;
464			else isopt = (char)(seqtt->flags & ASN1_TFLG_OPTIONAL);
465			/* attempt to read in field, allowing each to be
466			 * OPTIONAL */
467
468			ret = asn1_template_ex_d2i(pseqval, &p, len,
469							seqtt, isopt, ctx);
470			if (!ret)
471				{
472				errtt = seqtt;
473				goto err;
474				}
475			else if (ret == -1)
476				{
477				/* OPTIONAL component absent.
478				 * Free and zero the field.
479				 */
480				ASN1_template_free(pseqval, seqtt);
481				continue;
482				}
483			/* Update length */
484			len -= p - q;
485			}
486
487		/* Check for EOC if expecting one */
488		if (seq_eoc && !asn1_check_eoc(&p, len))
489			{
490			ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_MISSING_EOC);
491			goto err;
492			}
493		/* Check all data read */
494		if (!seq_nolen && len)
495			{
496			ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
497					ASN1_R_SEQUENCE_LENGTH_MISMATCH);
498			goto err;
499			}
500
501		/* If we get here we've got no more data in the SEQUENCE,
502		 * however we may not have read all fields so check all
503		 * remaining are OPTIONAL and clear any that are.
504		 */
505		for (; i < it->tcount; tt++, i++)
506			{
507			const ASN1_TEMPLATE *seqtt;
508			seqtt = asn1_do_adb(pval, tt, 1);
509			if (!seqtt)
510				goto err;
511			if (seqtt->flags & ASN1_TFLG_OPTIONAL)
512				{
513				ASN1_VALUE **pseqval;
514				pseqval = asn1_get_field_ptr(pval, seqtt);
515				ASN1_template_free(pseqval, seqtt);
516				}
517			else
518				{
519				errtt = seqtt;
520				ASN1err(ASN1_F_ASN1_ITEM_EX_D2I,
521							ASN1_R_FIELD_MISSING);
522				goto err;
523				}
524			}
525		/* Save encoding */
526		if (!asn1_enc_save(pval, *in, p - *in, it))
527			goto auxerr;
528		*in = p;
529		if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL))
530				goto auxerr;
531		return 1;
532
533		default:
534		return 0;
535		}
536	auxerr:
537	ASN1err(ASN1_F_ASN1_ITEM_EX_D2I, ASN1_R_AUX_ERROR);
538	err:
539	if (combine == 0)
540		ASN1_item_ex_free(pval, it);
541	if (errtt)
542		ERR_add_error_data(4, "Field=", errtt->field_name,
543					", Type=", it->sname);
544	else
545		ERR_add_error_data(2, "Type=", it->sname);
546	return 0;
547	}
548
549/* Templates are handled with two separate functions.
550 * One handles any EXPLICIT tag and the other handles the rest.
551 */
552
553static int asn1_template_ex_d2i(ASN1_VALUE **val,
554				const unsigned char **in, long inlen,
555				const ASN1_TEMPLATE *tt, char opt,
556							ASN1_TLC *ctx)
557	{
558	int flags, aclass;
559	int ret;
560	long len;
561	const unsigned char *p, *q;
562	char exp_eoc;
563	if (!val)
564		return 0;
565	flags = tt->flags;
566	aclass = flags & ASN1_TFLG_TAG_CLASS;
567
568	p = *in;
569
570	/* Check if EXPLICIT tag expected */
571	if (flags & ASN1_TFLG_EXPTAG)
572		{
573		char cst;
574		/* Need to work out amount of data available to the inner
575		 * content and where it starts: so read in EXPLICIT header to
576		 * get the info.
577		 */
578		ret = asn1_check_tlen(&len, NULL, NULL, &exp_eoc, &cst,
579					&p, inlen, tt->tag, aclass, opt, ctx);
580		q = p;
581		if (!ret)
582			{
583			ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
584					ERR_R_NESTED_ASN1_ERROR);
585			return 0;
586			}
587		else if (ret == -1)
588			return -1;
589		if (!cst)
590			{
591			ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
592					ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);
593			return 0;
594			}
595		/* We've found the field so it can't be OPTIONAL now */
596		ret = asn1_template_noexp_d2i(val, &p, len, tt, 0, ctx);
597		if (!ret)
598			{
599			ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
600					ERR_R_NESTED_ASN1_ERROR);
601			return 0;
602			}
603		/* We read the field in OK so update length */
604		len -= p - q;
605		if (exp_eoc)
606			{
607			/* If NDEF we must have an EOC here */
608			if (!asn1_check_eoc(&p, len))
609				{
610				ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
611						ASN1_R_MISSING_EOC);
612				goto err;
613				}
614			}
615		else
616			{
617			/* Otherwise we must hit the EXPLICIT tag end or its
618			 * an error */
619			if (len)
620				{
621				ASN1err(ASN1_F_ASN1_TEMPLATE_EX_D2I,
622					ASN1_R_EXPLICIT_LENGTH_MISMATCH);
623				goto err;
624				}
625			}
626		}
627		else
628			return asn1_template_noexp_d2i(val, in, inlen,
629								tt, opt, ctx);
630
631	*in = p;
632	return 1;
633
634	err:
635	ASN1_template_free(val, tt);
636	return 0;
637	}
638
639static int asn1_template_noexp_d2i(ASN1_VALUE **val,
640				const unsigned char **in, long len,
641				const ASN1_TEMPLATE *tt, char opt,
642				ASN1_TLC *ctx)
643	{
644	int flags, aclass;
645	int ret;
646	const unsigned char *p, *q;
647	if (!val)
648		return 0;
649	flags = tt->flags;
650	aclass = flags & ASN1_TFLG_TAG_CLASS;
651
652	p = *in;
653	q = p;
654
655	if (flags & ASN1_TFLG_SK_MASK)
656		{
657		/* SET OF, SEQUENCE OF */
658		int sktag, skaclass;
659		char sk_eoc;
660		/* First work out expected inner tag value */
661		if (flags & ASN1_TFLG_IMPTAG)
662			{
663			sktag = tt->tag;
664			skaclass = aclass;
665			}
666		else
667			{
668			skaclass = V_ASN1_UNIVERSAL;
669			if (flags & ASN1_TFLG_SET_OF)
670				sktag = V_ASN1_SET;
671			else
672				sktag = V_ASN1_SEQUENCE;
673			}
674		/* Get the tag */
675		ret = asn1_check_tlen(&len, NULL, NULL, &sk_eoc, NULL,
676					&p, len, sktag, skaclass, opt, ctx);
677		if (!ret)
678			{
679			ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
680						ERR_R_NESTED_ASN1_ERROR);
681			return 0;
682			}
683		else if (ret == -1)
684			return -1;
685		if (!*val)
686			*val = (ASN1_VALUE *)sk_new_null();
687		else
688			{
689			/* We've got a valid STACK: free up any items present */
690			STACK_OF(ASN1_VALUE) *sktmp
691			    = (STACK_OF(ASN1_VALUE) *)*val;
692			ASN1_VALUE *vtmp;
693			while(sk_ASN1_VALUE_num(sktmp) > 0)
694				{
695				vtmp = sk_ASN1_VALUE_pop(sktmp);
696				ASN1_item_ex_free(&vtmp,
697						ASN1_ITEM_ptr(tt->item));
698				}
699			}
700
701		if (!*val)
702			{
703			ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
704						ERR_R_MALLOC_FAILURE);
705			goto err;
706			}
707
708		/* Read as many items as we can */
709		while(len > 0)
710			{
711			ASN1_VALUE *skfield;
712			q = p;
713			/* See if EOC found */
714			if (asn1_check_eoc(&p, len))
715				{
716				if (!sk_eoc)
717					{
718					ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
719							ASN1_R_UNEXPECTED_EOC);
720					goto err;
721					}
722				len -= p - q;
723				sk_eoc = 0;
724				break;
725				}
726			skfield = NULL;
727			if (!ASN1_item_ex_d2i(&skfield, &p, len,
728						ASN1_ITEM_ptr(tt->item),
729						-1, 0, 0, ctx))
730				{
731				ASN1err(ASN1_F_ASN1_TEMPLATE_NOEXP_D2I,
732					ERR_R_NESTED_ASN1_ERROR);
733				goto err;
734				}
735			len -= p - q;
736			if (!sk_ASN1_VALUE_push((STACK_OF(ASN1_VALUE) *)*val,
737						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, tt->flags & ASN1_TFLG_COMBINE, 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