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/*
24 * Copyright (c) 1997 - 2007 Kungliga Tekniska Högskolan
25 * (Royal Institute of Technology, Stockholm, Sweden).
26 * All rights reserved.
27 *
28 * Redistribution and use in source and binary forms, with or without
29 * modification, are permitted provided that the following conditions
30 * are met:
31 *
32 * 1. Redistributions of source code must retain the above copyright
33 *    notice, this list of conditions and the following disclaimer.
34 *
35 * 2. Redistributions in binary form must reproduce the above copyright
36 *    notice, this list of conditions and the following disclaimer in the
37 *    documentation and/or other materials provided with the distribution.
38 *
39 * 3. Neither the name of the Institute nor the names of its contributors
40 *    may be used to endorse or promote products derived from this software
41 *    without specific prior written permission.
42 *
43 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
44 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
47 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * SUCH DAMAGE.
54 */
55
56#include "asn1-der_locl.h"
57
58/*
59 * All decoding functions take a pointer `p' to first position in
60 * which to read, from the left, `len' which means the maximum number
61 * of characters we are able to read, `ret' were the value will be
62 * returned and `size' where the number of used bytes is stored.
63 * Either 0 or an error code is returned.
64 */
65
66int
67der_get_unsigned (const unsigned char *p, size_t len,
68		  unsigned *ret, size_t *size)
69{
70    unsigned val = 0;
71    size_t oldlen = len;
72
73    if (len == sizeof(unsigned) + 1 && p[0] == 0)
74	;
75    else if (len > sizeof(unsigned))
76	return ASN1_OVERRUN;
77
78    while (len--)
79	val = val * 256 + *p++;
80    *ret = val;
81    if(size) *size = oldlen;
82    return 0;
83}
84
85int
86der_get_integer (const unsigned char *p, size_t len,
87		 int *ret, size_t *size)
88{
89    int val = 0;
90    size_t oldlen = len;
91
92    if (len > sizeof(int))
93	return ASN1_OVERRUN;
94
95    if (len > 0) {
96	val = (signed char)*p++;
97	while (--len)
98	    val = val * 256 + *p++;
99    }
100    *ret = val;
101    if(size) *size = oldlen;
102    return 0;
103}
104
105int
106der_get_length (const unsigned char *p, size_t len,
107		size_t *val, size_t *size)
108{
109    size_t v;
110
111    if (len <= 0)
112	return ASN1_OVERRUN;
113    --len;
114    v = *p++;
115    if (v < 128) {
116	*val = v;
117	if(size) *size = 1;
118    } else {
119	int e;
120	size_t l;
121	unsigned tmp;
122
123	if(v == 0x80){
124	    *val = ASN1_INDEFINITE;
125	    if(size) *size = 1;
126	    return 0;
127	}
128	v &= 0x7F;
129	if (len < v)
130	    return ASN1_OVERRUN;
131	e = der_get_unsigned (p, v, &tmp, &l);
132	if(e) return e;
133	*val = tmp;
134	if(size) *size = l + 1;
135    }
136    return 0;
137}
138
139int
140der_get_boolean(const unsigned char *p, size_t len, int *data, size_t *size)
141{
142    if(len < 1)
143	return ASN1_OVERRUN;
144    if(*p != 0)
145	*data = 1;
146    else
147	*data = 0;
148    *size = 1;
149    return 0;
150}
151
152int
153der_get_general_string (const unsigned char *p, size_t len,
154			heim_general_string *str, size_t *size)
155{
156    const unsigned char *p1;
157    char *s;
158
159    p1 = memchr(p, 0, len);
160    if (p1 != NULL) {
161	/*
162	 * Allow trailing NULs. We allow this since MIT Kerberos sends
163	 * an strings in the NEED_PREAUTH case that includes a
164	 * trailing NUL.
165	 */
166	while ((size_t)(p1 - p) < len && *p1 == '\0')
167	    p1++;
168	if ((size_t)(p1 - p) != len) {
169	    *str = NULL;
170	    return ASN1_BAD_CHARACTER;
171	}
172    }
173    if (len > len + 1) {
174	*str = NULL;
175	return ASN1_BAD_LENGTH;
176    }
177
178    *str = s = malloc (len + 1);
179    if (s == NULL)
180	return ENOMEM;
181    memcpy (s, p, len);
182    s[len] = '\0';
183
184    if(size) *size = len;
185    return 0;
186}
187
188int
189der_get_utf8string (const unsigned char *p, size_t len,
190		    heim_utf8_string *str, size_t *size)
191{
192    return der_get_general_string(p, len, str, size);
193}
194
195#define gen_data_zero(_data) \
196	do { (_data)->length = 0; (_data)->data = NULL; } while(0)
197
198int
199der_get_printable_string(const unsigned char *p, size_t len,
200			 heim_printable_string *str, size_t *size)
201{
202    if (len > len + 1) {
203	gen_data_zero(str);
204	return ASN1_BAD_LENGTH;
205    }
206    str->length = len;
207    str->data = malloc(len + 1);
208    if (str->data == NULL) {
209	gen_data_zero(str);
210	return ENOMEM;
211    }
212    memcpy(str->data, p, len);
213    ((char *)str->data)[len] = '\0';
214    if(size) *size = len;
215    return 0;
216}
217
218int
219der_get_ia5_string(const unsigned char *p, size_t len,
220		   heim_ia5_string *str, size_t *size)
221{
222    return der_get_printable_string(p, len, str, size);
223}
224
225int
226der_get_bmp_string (const unsigned char *p, size_t len,
227		    heim_bmp_string *data, size_t *size)
228{
229    size_t i;
230
231    if (len & 1) {
232	gen_data_zero(data);
233	return ASN1_BAD_FORMAT;
234    }
235    data->length = len / 2;
236    if (data->length > UINT_MAX/sizeof(data->data[0])) {
237	gen_data_zero(data);
238	return ERANGE;
239    }
240    data->data = malloc(data->length * sizeof(data->data[0]));
241    if (data->data == NULL && data->length != 0) {
242	gen_data_zero(data);
243	return ENOMEM;
244    }
245
246    for (i = 0; i < data->length; i++) {
247	data->data[i] = (p[0] << 8) | p[1];
248	p += 2;
249	/* check for NUL in the middle of the string */
250	if (data->data[i] == 0 && i != (data->length - 1)) {
251	    free(data->data);
252	    gen_data_zero(data);
253	    return ASN1_BAD_CHARACTER;
254	}
255    }
256    if (size) *size = len;
257
258    return 0;
259}
260
261int
262der_get_universal_string (const unsigned char *p, size_t len,
263			  heim_universal_string *data, size_t *size)
264{
265    size_t i;
266
267    if (len & 3) {
268	gen_data_zero(data);
269	return ASN1_BAD_FORMAT;
270    }
271    data->length = len / 4;
272    if (data->length > UINT_MAX/sizeof(data->data[0])) {
273	gen_data_zero(data);
274	return ERANGE;
275    }
276    data->data = malloc(data->length * sizeof(data->data[0]));
277    if (data->data == NULL && data->length != 0) {
278	gen_data_zero(data);
279	return ENOMEM;
280    }
281
282    for (i = 0; i < data->length; i++) {
283	data->data[i] = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
284	p += 4;
285	/* check for NUL in the middle of the string */
286	if (data->data[i] == 0 && i != (data->length - 1)) {
287	    free(data->data);
288	    gen_data_zero(data);
289	    return ASN1_BAD_CHARACTER;
290	}
291    }
292    if (size) *size = len;
293    return 0;
294}
295
296int
297der_get_visible_string (const unsigned char *p, size_t len,
298			heim_visible_string *str, size_t *size)
299{
300    return der_get_general_string(p, len, str, size);
301}
302
303int
304der_get_octet_string (const unsigned char *p, size_t len,
305		      heim_octet_string *data, size_t *size)
306{
307    data->length = len;
308    data->data = malloc(len);
309    if (data->data == NULL && data->length != 0)
310	return ENOMEM;
311    memcpy (data->data, p, len);
312    if(size) *size = len;
313    return 0;
314}
315
316int
317der_get_octet_string_ber (const unsigned char *p, size_t len,
318			  heim_octet_string *data, size_t *size)
319{
320    int e;
321    Der_type type;
322    Der_class class;
323    unsigned int tag, depth = 0;
324    size_t l, datalen, oldlen = len;
325
326    data->length = 0;
327    data->data = NULL;
328
329    while (len) {
330	e = der_get_tag (p, len, &class, &type, &tag, &l);
331	if (e) goto out;
332	if (class != ASN1_C_UNIV) {
333	    e = ASN1_BAD_ID;
334	    goto out;
335	}
336	if (type == PRIM && tag == UT_EndOfContent) {
337	    if (depth == 0)
338		break;
339	    depth--;
340	}
341	if (tag != UT_OctetString) {
342	    e = ASN1_BAD_ID;
343	    goto out;
344	}
345
346	p += l;
347	len -= l;
348	e = der_get_length (p, len, &datalen, &l);
349	if (e) goto out;
350	p += l;
351	len -= l;
352
353	if (datalen > len)
354	    return ASN1_OVERRUN;
355
356	if (type == PRIM) {
357	    void *ptr;
358
359	    ptr = realloc(data->data, data->length + datalen);
360	    if (ptr == NULL) {
361		e = ENOMEM;
362		goto out;
363	    }
364	    data->data = ptr;
365	    memcpy(((unsigned char *)data->data) + data->length, p, datalen);
366	    data->length += datalen;
367	} else
368	    depth++;
369
370	p += datalen;
371	len -= datalen;
372    }
373    if (depth != 0)
374	return ASN1_INDEF_OVERRUN;
375    if(size) *size = oldlen - len;
376    return 0;
377 out:
378    free(data->data);
379    data->data = NULL;
380    data->length = 0;
381    return e;
382}
383
384
385int
386der_get_heim_integer (const unsigned char *p, size_t len,
387		      heim_integer *data, size_t *size)
388{
389    data->length = 0;
390    data->negative = 0;
391    data->data = NULL;
392
393    if (len == 0) {
394	if (size)
395	    *size = 0;
396	return 0;
397    }
398    if (p[0] & 0x80) {
399	unsigned char *q;
400	int carry = 1;
401	data->negative = 1;
402
403	data->length = len;
404
405	if (p[0] == 0xff) {
406	    p++;
407	    data->length--;
408	}
409	data->data = malloc(data->length);
410	if (data->data == NULL) {
411	    data->length = 0;
412	    if (size)
413		*size = 0;
414	    return ENOMEM;
415	}
416	q = &((unsigned char*)data->data)[data->length - 1];
417	p += data->length - 1;
418	while (q >= (unsigned char*)data->data) {
419	    *q = *p ^ 0xff;
420	    if (carry)
421		carry = !++*q;
422	    p--;
423	    q--;
424	}
425    } else {
426	data->negative = 0;
427	data->length = len;
428
429	if (p[0] == 0) {
430	    p++;
431	    data->length--;
432	}
433	data->data = malloc(data->length);
434	if (data->data == NULL && data->length != 0) {
435	    data->length = 0;
436	    if (size)
437		*size = 0;
438	    return ENOMEM;
439	}
440	memcpy(data->data, p, data->length);
441    }
442    if (size)
443	*size = len;
444    return 0;
445}
446
447static int
448generalizedtime2time (const char *s, time_t *t)
449{
450    struct tm tm;
451
452    memset(&tm, 0, sizeof(tm));
453    if (sscanf (s, "%04d%02d%02d%02d%02d%02dZ",
454		&tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour,
455		&tm.tm_min, &tm.tm_sec) != 6) {
456	if (sscanf (s, "%02d%02d%02d%02d%02d%02dZ",
457		    &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &tm.tm_hour,
458		    &tm.tm_min, &tm.tm_sec) != 6)
459	    return ASN1_BAD_TIMEFORMAT;
460	if (tm.tm_year < 50)
461	    tm.tm_year += 2000;
462	else
463	    tm.tm_year += 1900;
464    }
465    tm.tm_year -= 1900;
466    tm.tm_mon -= 1;
467    *t = _der_timegm (&tm);
468    return 0;
469}
470
471static int
472der_get_time (const unsigned char *p, size_t len,
473	      time_t *data, size_t *size)
474{
475    char *times;
476    int e;
477
478    if (len > len + 1 || len == 0)
479	return ASN1_BAD_LENGTH;
480
481    times = malloc(len + 1);
482    if (times == NULL)
483	return ENOMEM;
484    memcpy(times, p, len);
485    times[len] = '\0';
486    e = generalizedtime2time(times, data);
487    free (times);
488    if(size) *size = len;
489    return e;
490}
491
492int
493der_get_generalized_time (const unsigned char *p, size_t len,
494			  time_t *data, size_t *size)
495{
496    return der_get_time(p, len, data, size);
497}
498
499int
500der_get_utctime (const unsigned char *p, size_t len,
501			  time_t *data, size_t *size)
502{
503    return der_get_time(p, len, data, size);
504}
505
506int
507der_get_oid (const unsigned char *p, size_t len,
508	     heim_oid *data, size_t *size)
509{
510    size_t n;
511    size_t oldlen = len;
512
513    if (len < 1)
514	return ASN1_OVERRUN;
515
516    if (len > len + 1)
517	return ASN1_BAD_LENGTH;
518
519    if (len + 1 > UINT_MAX/sizeof(data->components[0]))
520	return ERANGE;
521
522    data->components = malloc((len + 1) * sizeof(data->components[0]));
523    if (data->components == NULL)
524	return ENOMEM;
525    data->components[0] = (*p) / 40;
526    data->components[1] = (*p) % 40;
527    --len;
528    ++p;
529    for (n = 2; len > 0; ++n) {
530	unsigned u = 0, u1;
531
532	do {
533	    --len;
534	    u1 = u * 128 + (*p++ % 128);
535	    /* check that we don't overflow the element */
536	    if (u1 < u) {
537		der_free_oid(data);
538		return ASN1_OVERRUN;
539	    }
540	    u = u1;
541	} while (len > 0 && p[-1] & 0x80);
542	data->components[n] = u;
543    }
544    if (n > 2 && p[-1] & 0x80) {
545	der_free_oid (data);
546	return ASN1_OVERRUN;
547    }
548    data->length = n;
549    if (size)
550	*size = oldlen;
551    return 0;
552}
553
554int
555der_get_tag (const unsigned char *p, size_t len,
556	     Der_class *class, Der_type *type,
557	     unsigned int *tag, size_t *size)
558{
559    size_t ret = 0;
560    if (len < 1)
561	return ASN1_OVERRUN;
562    *class = (Der_class)(((*p) >> 6) & 0x03);
563    *type = (Der_type)(((*p) >> 5) & 0x01);
564    *tag = (*p) & 0x1f;
565    p++; len--; ret++;
566    if(*tag == 0x1f) {
567	unsigned int continuation;
568	unsigned int tag1;
569	*tag = 0;
570	do {
571	    if(len < 1)
572		return ASN1_OVERRUN;
573	    continuation = *p & 128;
574	    tag1 = *tag * 128 + (*p % 128);
575	    /* check that we don't overflow the tag */
576	    if (tag1 < *tag)
577		return ASN1_OVERFLOW;
578	    *tag = tag1;
579	    p++; len--; ret++;
580	} while(continuation);
581    }
582    if(size) *size = ret;
583    return 0;
584}
585
586int
587der_match_tag (const unsigned char *p, size_t len,
588	       Der_class class, Der_type type,
589	       unsigned int tag, size_t *size)
590{
591    Der_type thistype;
592    int e;
593
594    e = der_match_tag2(p, len, class, &thistype, tag, size);
595    if (e) return e;
596    if (thistype != type) return ASN1_BAD_ID;
597    return 0;
598}
599
600int
601der_match_tag2 (const unsigned char *p, size_t len,
602		Der_class class, Der_type *type,
603		unsigned int tag, size_t *size)
604{
605    size_t l;
606    Der_class thisclass;
607    unsigned int thistag;
608    int e;
609
610    e = der_get_tag (p, len, &thisclass, type, &thistag, &l);
611    if (e) return e;
612    if (class != thisclass)
613	return ASN1_BAD_ID;
614    if(tag > thistag)
615	return ASN1_MISPLACED_FIELD;
616    if(tag < thistag)
617	return ASN1_MISSING_FIELD;
618    if(size) *size = l;
619    return 0;
620}
621
622int
623der_match_tag_and_length (const unsigned char *p, size_t len,
624			  Der_class class, Der_type *type, unsigned int tag,
625			  size_t *length_ret, size_t *size)
626{
627    size_t l, ret = 0;
628    int e;
629
630    e = der_match_tag2 (p, len, class, type, tag, &l);
631    if (e) return e;
632    p += l;
633    len -= l;
634    ret += l;
635    e = der_get_length (p, len, length_ret, &l);
636    if (e) return e;
637    if(size) *size = ret + l;
638    return 0;
639}
640
641
642
643/*
644 * Old versions of DCE was based on a very early beta of the MIT code,
645 * which used MAVROS for ASN.1 encoding. MAVROS had the interesting
646 * feature that it encoded data in the forward direction, which has
647 * it's problems, since you have no idea how long the data will be
648 * until after you're done. MAVROS solved this by reserving one byte
649 * for length, and later, if the actual length was longer, it reverted
650 * to indefinite, BER style, lengths. The version of MAVROS used by
651 * the DCE people could apparently generate correct X.509 DER encodings, and
652 * did this by making space for the length after encoding, but
653 * unfortunately this feature wasn't used with Kerberos.
654 */
655
656int
657_heim_fix_dce(size_t reallen, size_t *len)
658{
659    if(reallen == ASN1_INDEFINITE)
660	return 1;
661    if(*len < reallen)
662	return -1;
663    *len = reallen;
664    return 0;
665}
666
667int
668der_get_bit_string (const unsigned char *p, size_t len,
669		    heim_bit_string *data, size_t *size)
670{
671    if (len < 1)
672	return ASN1_OVERRUN;
673    if (p[0] > 7)
674	return ASN1_BAD_FORMAT;
675    if (len - 1 == 0 && p[0] != 0)
676	return ASN1_BAD_FORMAT;
677    /* check if any of the three upper bits are set
678     * any of them will cause a interger overrun */
679    if ((len - 1) >> (sizeof(len) * 8 - 3))
680	return ASN1_OVERRUN;
681    /*
682     * If there is data to copy, do that now.
683     */
684    if (len - 1 > 0) {
685	data->length = (len - 1) * 8;
686	data->data = malloc(len - 1);
687	if (data->data == NULL)
688	    return ENOMEM;
689	memcpy (data->data, p + 1, len - 1);
690	data->length -= p[0];
691    } else {
692	data->data = NULL;
693	data->length = 0;
694    }
695    if(size) *size = len;
696    return 0;
697}
698