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