summaryrefslogtreecommitdiff
path: root/view/kernelcache/core/transformers/libDER/DER_Decode.c
blob: 3d08b616c2f8464b80748c97c64f5aecbac04267 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
/*
 * Copyright (c) 2005-2012 Apple Inc. All Rights Reserved.
 * 
 * @APPLE_LICENSE_HEADER_START@
 * 
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apple Public Source License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://www.opensource.apple.com/apsl/ and read it before using this
 * file.
 * 
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */

/* 
 * DER_Decode.c - DER decoding routines
 */
/*
 * NOTICE: This file was modified by xerub to reflect binary code.
 */
 
#include <libDER/DER_Decode.h>
#include <libDER/asn1Types.h>

#include <libDER/libDER_config.h>

#ifndef	DER_DECODE_ENABLE
#error Please define DER_DECODE_ENABLE.
#endif

#if		DER_DECODE_ENABLE

#define DER_DECODE_DEBUG	0
#if		DER_DECODE_DEBUG
#include <stdio.h>
#define derDecDbg(a)			iprintf(a)
#define derDecDbg1(a, b)		iprintf(a, b)
#define derDecDbg2(a, b, c)		iprintf(a, b, c)
#define derDecDbg3(a, b, c, d)	iprintf(a, b, c, d)
#else	
#define derDecDbg(a)	
#define derDecDbg1(a, b)	
#define derDecDbg2(a, b, c)	
#define derDecDbg3(a, b, c, d)
#endif	/* DER_DECODE_DEBUG */

/*
 *  Basic decoding primitive. Only works with:
 *
 *  -- definite length encoding 
 *  -- one-byte tags 
 *  -- max content length fits in a DERSize
 *
 * No malloc or copy of the contents is performed; the returned 
 * content->content.data is a pointer into the incoming der data.
 */
DERReturn DERDecodeItem(
	const DERItem	*der,			/* data to decode */
	DERDecodedInfo	*decoded)		/* RETURNED */
{
    return DERDecodeItemPartialBuffer(der, decoded, false);
}
DERReturn DERDecodeItemPartialBuffer(
	const DERItem	*der,			/* data to decode */
	DERDecodedInfo	*decoded,		/* RETURNED */
	bool partial)
{
	DERByte tag1;			/* first tag byte */
	DERByte len1;			/* first length byte */
	DERTag tagNumber;       /* tag number without class and method bits */
	DERByte *derPtr = der->data;
	DERSize derLen = der->length;
	
    /* The tag decoding below is fully BER complient.  We support a max tag
       value of 2 ^ ((sizeof(DERTag) * 8) - 3) - 1 so for tag size 1 byte we
       support tag values from 0 - 0x1F.  For tag size 2 tag values
       from 0 - 0x1FFF and for tag size 4 values from 0 - 0x1FFFFFFF. */
	if(derLen < 2) {
		return DR_DecodeError;
	}
    /* Grab the first byte of the tag. */
	tag1 = *derPtr++;
	derLen--;
	tagNumber = tag1 & 0x1F;
	if(tagNumber == 0x1F) {
#ifdef DER_MULTIBYTE_TAGS
	if (*derPtr == 0x80 || *derPtr < 0x1F) {
	    return DR_DecodeError;
	}
        /* Long tag form: bit 8 of each octet shall be set to one unless it is
           the last octet of the tag */
        const DERTag overflowMask = ((DERTag)0x7F << (sizeof(DERTag) * 8 - 7));
        DERByte tagByte;
        tagNumber = 0;
        do {
            if(derLen < 2 || (tagNumber & overflowMask) != 0) {
                return DR_DecodeError;
            }
            tagByte = *derPtr++;
            derLen--;
            tagNumber = (tagNumber << 7) | (tagByte & 0x7F);
        } while((tagByte & 0x80) != 0);
	
        /* Check for any of the top 3 reserved bits being set. */
        if ((tagNumber & (overflowMask << 4)) != 0)
#endif
            return DR_DecodeError;
	}
    /* Returned tag, top 3 bits are class/method remaining bits are number. */
    decoded->tag = ((DERTag)(tag1 & 0xE0) << ((sizeof(DERTag) - 1) * 8)) | tagNumber;

    /* Tag decoding above ensured we have at least one more input byte left. */
	len1 = *derPtr++;
	derLen--;
	if(len1 & 0x80) {
		/* long length form - first byte is length of length */
		DERSize longLen = 0;	/* long form length */
		unsigned dex;

		len1 &= 0x7f;
		if((len1 > sizeof(DERSize)) || (len1 > derLen) || len1 == 0 || *derPtr == 0) {
			/* no can do */
			return DR_DecodeError;
		}
		for(dex=0; dex<len1; dex++) {
			longLen <<= 8;
			longLen |= *derPtr++;
			derLen--;
		}
		if(longLen > derLen && !partial) {
			/* not enough data left for this encoding */
			return DR_DecodeError;
		}
		decoded->content.data = derPtr;
		decoded->content.length = longLen;
	}
	else {
		/* short length form, len1 is the length */
		if(len1 > derLen && !partial) {
			/* not enough data left for this encoding */
			return DR_DecodeError;
		}
		decoded->content.data = derPtr;
		decoded->content.length = len1;
	}

		return DR_Success;
	}

/* 
 * Given a BIT_STRING, in the form of its raw content bytes, 
 * obtain the number of unused bits and the raw bit string bytes.
 */
DERReturn DERParseBitString(
	const DERItem	*contents,
	DERItem			*bitStringBytes,	/* RETURNED */
	DERByte			*numUnusedBits)		/* RETURNED */
{
	if(contents->length < 2) {
		/* not enough room for actual bits after the unused bits field */
		*numUnusedBits = 0;
		bitStringBytes->data = NULL;
		bitStringBytes->length = 0;
		return DR_Success;
	}
	*numUnusedBits = contents->data[0];
	bitStringBytes->data = contents->data + 1;
	bitStringBytes->length = contents->length - 1;
	return DR_Success;
}

/* 
 * Given a BOOLEAN, in the form of its raw content bytes, 
 * obtain it's value.
 */
DERReturn DERParseBoolean(
	const DERItem	*contents,
	bool			*value) {	/* RETURNED */
    if (contents->length != 1 ||
        (contents->data[0] != 0 && contents->data[0] != 0xFF))
        return DR_DecodeError;

    *value = contents->data[0] != 0;
    return DR_Success;
}

DERReturn DERParseInteger(
	const DERItem	*contents,
	uint32_t        *result) {	/* RETURNED */
	uint64_t value;
	DERReturn drtn = DERParseInteger64(contents, &value);
	if (drtn) {
		return drtn;
	}
	if (value >> 32) {
		return DR_BufOverflow;
	}
	*result = value;
	return DR_Success;
}

DERReturn DERParseInteger64(
	const DERItem	*contents,
	uint64_t        *result) {	/* RETURNED */
    const char *data = (char *)contents->data;
    DERSize length = contents->length;
    uint64_t value = 0;

    if (length == 0 || data[0] < 0) {
        return DR_DecodeError;
    }

    if (data[0] == 0) {
        if (length >= 2) {
            if (data[1] >= 0) {
                return DR_DecodeError;
            }
            if (length > 9) {
                return DR_BufOverflow;
            }
        }
    } else if (length > 8) {
        return DR_BufOverflow;
    }

    while (length--) {
        value <<= 8;
        value += *(unsigned char *)data++;
    }
    *result = value;
    return DR_Success;
}

/* Sequence/set support */

/* 
 * To decode a set or sequence, call DERDecodeSeqInit once, then
 * call DERDecodeSeqNext to get each enclosed item.
 * DERDecodeSeqNext returns DR_EndOfSequence when no more
 * items are available. 
 */
DERReturn DERDecodeSeqInit(
	const DERItem	*der,			/* data to decode */
	DERTag			*tag,			/* RETURNED tag of sequence/set. This will be
									 * either ASN1_CONSTR_SEQUENCE or ASN1_CONSTR_SET. */
	DERSequence		*derSeq)		/* RETURNED, to use in DERDecodeSeqNext */
{
	DERDecodedInfo decoded;
	DERReturn drtn;
	
	drtn = DERDecodeItem(der, &decoded);
	if(drtn) {
		return drtn;
	}
    *tag = decoded.tag;
	switch(decoded.tag) {
		case ASN1_CONSTR_SEQUENCE:
		case ASN1_CONSTR_SET:
			break;
		default:
			return DR_UnexpectedTag;
	}
	derSeq->nextItem = decoded.content.data;
	derSeq->end = decoded.content.data + decoded.content.length;
	return DR_Success;
}

/* 
 * Use this to start in on decoding a sequence's content, when 
 * the top-level tag and content have already been decoded. 
 */
DERReturn DERDecodeSeqContentInit(
	const DERItem	*content,
	DERSequence		*derSeq)		/* RETURNED, to use in DERDecodeSeqNext */
{
	/* just prepare for decoding items in content */
	derSeq->nextItem = content->data;
	derSeq->end = content->data + content->length;
	return DR_Success;
}

DERReturn DERDecodeSeqNext(
	DERSequence		*derSeq,
	DERDecodedInfo	*decoded)		/* RETURNED */
{
	DERReturn drtn;
	DERItem item;
	
	if(derSeq->nextItem >= derSeq->end) {
		/* normal termination, contents all used up */
		return DR_EndOfSequence;
	}
	
	/* decode next item */
	item.data = derSeq->nextItem;
	item.length = derSeq->end - derSeq->nextItem;
	drtn = DERDecodeItem(&item, decoded);
	if(drtn) {
		return drtn;
	}	
	
	/* skip over the item we just decoded */
	derSeq->nextItem = decoded->content.data + decoded->content.length;
	return DR_Success;
}

/* 
 * High level sequence parse, starting with top-level tag and content.
 * Top level tag must be ASN1_CONSTR_SEQUENCE - if it's not, and that's 
 * OK, use DERParseSequenceContent().
 */
DERReturn DERParseSequence(
	const DERItem			*der,
	DERShort				numItems,	/* size of itemSpecs[] */
	const DERItemSpec		*itemSpecs,
	void					*dest,		/* DERDecodedInfo(s) here RETURNED */
	DERSize					sizeToZero)	/* optional */
{
	DERReturn drtn;
	DERDecodedInfo topDecode;
	
	drtn = DERDecodeItem(der, &topDecode);
	if(drtn) {
		return drtn;
	}
	if(topDecode.tag != ASN1_CONSTR_SEQUENCE) {
		return DR_UnexpectedTag;
	}
	return DERParseSequenceContent(&topDecode.content,
		numItems, itemSpecs, dest, sizeToZero);
}

/* high level sequence parse, starting with sequence's content */
DERReturn DERParseSequenceContent(
	const DERItem			*content,
	DERShort				numItems,	/* size of itemSpecs[] */
	const DERItemSpec		*itemSpecs,
	void					*dest,		/* DERDecodedInfo(s) here RETURNED */
	DERSize					sizeToZero)	/* optional */
{
	DERSequence			derSeq;
	DERReturn			drtn;
	DERShort			itemDex;
	DERByte				*currDER;	/* full DER encoding of current item */
	
	if(sizeToZero) {
		DERMemset(dest, 0, sizeToZero);
	}
	
	drtn = DERDecodeSeqContentInit(content, &derSeq);
	if(drtn) {
		return drtn;
	}
	
	/* main loop */
	for(itemDex=0 ; itemDex<numItems; ) {
		DERDecodedInfo currDecoded;
		DERShort i;
		DERTag foundTag;
		char foundMatch = 0;
		
		/* save this in case of DER_DEC_SAVE_DER */
		currDER = derSeq.nextItem;
		
		drtn = DERDecodeSeqNext(&derSeq, &currDecoded);
		if(drtn) {
			/* 
			 * One legal error here is DR_EndOfSequence when 
			 * all remaining DERSequenceItems are optional. 
			 */
			if(drtn == DR_EndOfSequence) {
				for(i=itemDex; i<numItems; i++) {
					if(!(itemSpecs[i].options & DER_DEC_OPTIONAL)) {
						/* unexpected end of sequence */
						return DR_IncompleteSeq;
					}
				}
				/* the rest are optional; success */
				return DR_Success;
			}
			else {
				/* any other error is fatal */
				return drtn;
			}
		}	/* decode error */
		
		/* 
		 * Seek matching tag or ASN_ANY in itemSpecs, skipping 
		 * over optional items.
		 */
		foundTag = currDecoded.tag;
		derDecDbg1("--- foundTag 0x%x\n", foundTag);
		
		for(i=itemDex; i<numItems; i++) {
			const DERItemSpec *currItemSpec = &itemSpecs[i];
			DERShort currOptions = currItemSpec->options;
			derDecDbg3("--- currItem %u expectTag 0x%x currOptions 0x%x\n", 
				i, currItemSpec->tag, currOptions);
			
			if((currOptions & DER_DEC_ASN_ANY) ||
			   (foundTag == currItemSpec->tag)) {
				/* 
				 * We're good with this one. Cook up destination address
				 * as appropriate. 
				 */
				if(!(currOptions & DER_DEC_SKIP)) {
					derDecDbg1("--- MATCH at currItem %u\n", i);
					DERByte *byteDst = (DERByte *)dest + currItemSpec->offset;
					DERItem *dst = (DERItem *)byteDst;
					*dst = currDecoded.content;
					if(currOptions & DER_DEC_SAVE_DER) {
						/* recreate full DER encoding of this item */
						derDecDbg1("--- SAVE_DER at currItem %u\n", i);
						dst->data = currDER;
						dst->length += (currDecoded.content.data - currDER);
					}
				}

				/* on to next item */
				itemDex = i + 1;
				
				/* is this the end? */
				if(itemDex == numItems) {
					/* normal termination if we consumed everything */
					if (derSeq.nextItem == derSeq.end)
						return DR_Success;
					else
						return DR_DecodeError;
				}
				else {
					/* on to next item */ 
					foundMatch = 1;
					break;
				}
			} /* ASN_ANY, or match */
			
			/* 
			 * If current itemSpec isn't optional, abort - else on to 
			 * next item
			 */
			if(!(currOptions & DER_DEC_OPTIONAL)) {
				derDecDbg1("--- MISMATCH at currItem %u, !OPTIONAL, abort\n", i);
				return DR_UnexpectedTag;
			}
			
			/* else this was optional, on to next item */
		} /* searching for tag match */
		
		if(foundMatch == 0) {
			/* 
			 * Found an item we couldn't match to any tag spec and we're at
			 * the end. 
			 */
			derDecDbg("--- TAG NOT FOUND, abort\n");
			return DR_UnexpectedTag;
		}
		
		/* else on to next item */
	}	/* main loop */
	
	/*
	 * If we get here, there appears to be more to process, but we've
	 * given the caller everything they want. 
	 */
	return (derSeq.nextItem == derSeq.end) ? DR_Success : DR_DecodeError;
}

#if 0
/* 
 * High level sequence parse, starting with top-level tag and content.
 * Top level tag must be ASN1_CONSTR_SEQUENCE - if it's not, and that's 
 * OK, use DERParseSequenceContent().
 */
DERReturn DERParseSequenceOf(
	const DERItem			*der,
	DERShort				numItems,	/* size of itemSpecs[] */
	const DERItemSpec		*itemSpecs,
	void					*dest,		/* DERDecodedInfo(s) here RETURNED */
	DERSize					*numDestItems)	/* output */
{
	DERReturn drtn;
	DERDecodedInfo topDecode;
	
	drtn = DERDecodeItem(der, &topDecode);
	if(drtn) {
		return drtn;
	}
	if(topDecode.tag != ASN1_CONSTR_SEQUENCE) {
		return DR_UnexpectedTag;
	}
	return DERParseSequenceContent(&topDecode.content,
		numItems, itemSpecs, dest, sizeToZero);
}

/* 
 * High level set of parse, starting with top-level tag and content.
 * Top level tag must be ASN1_CONSTR_SET - if it's not, and that's 
 * OK, use DERParseSetOrSequenceOfContent().
 */
DERReturn DERParseSetOf(
	const DERItem			*der,
	DERShort				numItems,	/* size of itemSpecs[] */
	const DERItemSpec		*itemSpecs,
	void					*dest,		/* DERDecodedInfo(s) here RETURNED */
	DERSize					*numDestItems)	/* output */
{
	DERReturn drtn;
	DERDecodedInfo topDecode;
	
	drtn = DERDecodeItem(der, &topDecode);
	if(drtn) {
		return drtn;
	}
	if(topDecode.tag != ASN1_CONSTR_SET) {
		return DR_UnexpectedTag;
	}
	return DERParseSetOrSequenceOfContent(&topDecode.content,
		numItems, itemSpecs, dest, numDestItems);
}

/* High level set of or sequence of parse, starting with set or
   sequence's content */
DERReturn DERParseSetOrSequenceOfContent(
    const DERItem			*content,
    void(*itemHandeler)(void *, const DERDecodedInfo *)
	void					*itemHandelerContext);
{
    DERSequence			derSeq;
    DERShort			itemDex;

    drtn = DERDecodeSeqContentInit(content, &derSeq);
    require_noerr_quiet(drtn, badCert);

    /* main loop */
    for (;;) {
        DERDecodedInfo currDecoded;
        DERShort i;
        DERByte foundTag;
        char foundMatch = 0;

        drtn = DERDecodeSeqNext(&derSeq, &currDecoded);
        if(drtn) {
            /* The only legal error here is DR_EndOfSequence. */
            if(drtn == DR_EndOfSequence) {
                /* no more items left in the sequence; success */
                return DR_Success;
            }
            else {
                /* any other error is fatal */
                require_noerr_quiet(drtn, badCert);
            }
        }	/* decode error */
        
        /* Each element can be anything. */
        foundTag = currDecoded.tag;

        /* 
         * We're good with this one. Cook up destination address
         * as appropriate. 
         */
        DERByte *byteDst = (DERByte *)dest + currItemSpec->offset;
        DERItem *dst = (DERItem *)byteDst;
        *dst = currDecoded.content;
        if(currOptions & DER_DEC_SAVE_DER) {
            /* recreate full DER encoding of this item */
            derDecDbg1("--- SAVE_DER at currItem %u\n", i);
            dst->data = currDER;
            dst->length += (currDecoded.content.data - currDER);
        }

        /* on to next item */
        itemDex = i + 1;
        
        /* is this the end? */
        if(itemDex == numItems) {
            /* normal termination */
            return DR_Success;
        }
        else {
            /* on to next item */ 
            foundMatch = 1;
            break;
        }
            
            /* 
             * If current itemSpec isn't optional, abort - else on to 
             * next item
             */
            if(!(currOptions & DER_DEC_OPTIONAL)) {
                derDecDbg1("--- MISMATCH at currItem %u, !OPTIONAL, abort\n", i);
                return DR_UnexpectedTag;
            }
            
            /* else this was optional, on to next item */
        } /* searching for tag match */
        
        if(foundMatch == 0) {
            /* 
             * Found an item we couldn't match to any tag spec and we're at
             * the end. 
             */
            derDecDbg("--- TAG NOT FOUND, abort\n");
            return DR_UnexpectedTag;
        }
        
        /* else on to next item */
    }	/* main loop */

    /*
     * If we get here, there appears to be more to process, but we've
     * given the caller everything they want. 
     */
    return DR_Success;
    }
}
#endif

#endif	/* DER_DECODE_ENABLE */