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