]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_asn1/lib/secasn1d.c
Security-57740.1.18.tar.gz
[apple/security.git] / OSX / libsecurity_asn1 / lib / secasn1d.c
1 /*
2 * The contents of this file are subject to the Mozilla Public
3 * License Version 1.1 (the "License"); you may not use this file
4 * except in compliance with the License. You may obtain a copy of
5 * the License at http://www.mozilla.org/MPL/
6 *
7 * Software distributed under the License is distributed on an "AS
8 * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
9 * implied. See the License for the specific language governing
10 * rights and limitations under the License.
11 *
12 * The Original Code is the Netscape security libraries.
13 *
14 * The Initial Developer of the Original Code is Netscape
15 * Communications Corporation. Portions created by Netscape are
16 * Copyright (C) 1994-2000 Netscape Communications Corporation. All
17 * Rights Reserved.
18 *
19 * Contributor(s):
20 *
21 * Alternatively, the contents of this file may be used under the
22 * terms of the GNU General Public License Version 2 or later (the
23 * "GPL"), in which case the provisions of the GPL are applicable
24 * instead of those above. If you wish to allow use of your
25 * version of this file only under the terms of the GPL and not to
26 * allow others to use your version of this file under the MPL,
27 * indicate your decision by deleting the provisions above and
28 * replace them with the notice and other provisions required by
29 * the GPL. If you do not delete the provisions above, a recipient
30 * may use your version of this file under either the MPL or the
31 * GPL.
32 */
33
34 /*
35 * Support for DEcoding ASN.1 data based on BER/DER (Basic/Distinguished
36 * Encoding Rules).
37 *
38 * $Id: secasn1d.c,v 1.16 2004/05/13 15:29:13 dmitch Exp $
39 */
40 #include <limits.h>
41
42 #include "secasn1.h"
43 #include "secerr.h"
44 #include "assert.h"
45
46 #ifdef NDEBUG
47 #define DEBUG_DECASN1 0
48 #else
49 #define DEBUG_DECASN1 1
50 #endif
51
52 #if DEBUG_DECASN1
53 #include <stdio.h>
54 #define dprintf(args...) printf(args)
55 #else
56 #define dprintf(args...)
57 #endif /* DEBUG_DECASN1 */
58
59 typedef enum {
60 beforeIdentifier,
61 duringIdentifier,
62 afterIdentifier,
63 beforeLength,
64 duringLength,
65 afterLength,
66 beforeBitString,
67 duringBitString,
68 duringConstructedString,
69 duringGroup,
70 duringLeaf,
71 duringSaveEncoding,
72 duringSequence,
73 afterConstructedString,
74 afterGroup,
75 afterExplicit,
76 afterImplicit,
77 afterInline,
78 afterPointer,
79 afterSaveEncoding,
80 beforeEndOfContents,
81 duringEndOfContents,
82 afterEndOfContents,
83 beforeChoice,
84 duringChoice,
85 afterChoice,
86 notInUse
87 } sec_asn1d_parse_place;
88
89 #ifndef NDEBUG
90 #define DEBUG_ASN1D_STATES 1
91 /* tweakable by debugger, debug only */
92 int doDumpStates = 0;
93 #else /* DEBUG_ASN1D_STATES 0 */
94 #endif /* DEBUG_ASN1D_STATES */
95
96 #if DEBUG_ASN1D_STATES
97 static const char *place_names[] = {
98 "beforeIdentifier",
99 "duringIdentifier",
100 "afterIdentifier",
101 "beforeLength",
102 "duringLength",
103 "afterLength",
104 "beforeBitString",
105 "duringBitString",
106 "duringConstructedString",
107 "duringGroup",
108 "duringLeaf",
109 "duringSaveEncoding",
110 "duringSequence",
111 "afterConstructedString",
112 "afterGroup",
113 "afterExplicit",
114 "afterImplicit",
115 "afterInline",
116 "afterPointer",
117 "afterSaveEncoding",
118 "beforeEndOfContents",
119 "duringEndOfContents",
120 "afterEndOfContents",
121 "beforeChoice",
122 "duringChoice",
123 "afterChoice",
124 "notInUse"
125 };
126
127 static const char * const class_names[] = {
128 "UNIVERSAL",
129 "APPLICATION",
130 "CONTEXT_SPECIFIC",
131 "PRIVATE"
132 };
133
134 static const char * const method_names[] = { "PRIMITIVE", "CONSTRUCTED" };
135
136 static const char * const type_names[] = {
137 "END_OF_CONTENTS",
138 "BOOLEAN",
139 "INTEGER",
140 "BIT_STRING",
141 "OCTET_STRING",
142 "NULL",
143 "OBJECT_ID",
144 "OBJECT_DESCRIPTOR",
145 "(type 08)",
146 "REAL",
147 "ENUMERATED",
148 "EMBEDDED",
149 "UTF8_STRING",
150 "(type 0d)",
151 "(type 0e)",
152 "(type 0f)",
153 "SEQUENCE",
154 "SET",
155 "NUMERIC_STRING",
156 "PRINTABLE_STRING",
157 "T61_STRING",
158 "VIDEOTEXT_STRING",
159 "IA5_STRING",
160 "UTC_TIME",
161 "GENERALIZED_TIME",
162 "GRAPHIC_STRING",
163 "VISIBLE_STRING",
164 "GENERAL_STRING",
165 "UNIVERSAL_STRING",
166 "(type 1d)",
167 "BMP_STRING",
168 "HIGH_TAG_VALUE"
169 };
170
171 static const char * const flag_names[] = { /* flags, right to left */
172 "OPTIONAL",
173 "EXPLICIT",
174 "ANY",
175 "INLINE",
176 "POINTER",
177 "GROUP",
178 "DYNAMIC",
179 "SKIP",
180 "INNER",
181 "SAVE",
182 "", /* decoder ignores "MAY_STREAM", */
183 "SKIP_REST",
184 "CHOICE",
185 "NO_STREAM",
186 "DEBUG_BREAK",
187 "unknown 08",
188 "unknown 10",
189 "unknown 20",
190 "unknown 40",
191 "unknown 80"
192 };
193
194 static int /* bool */
195 formatKind(unsigned long kind, char * buf)
196 {
197 int i;
198 unsigned long k = kind & SEC_ASN1_TAGNUM_MASK;
199 unsigned long notag = kind & (SEC_ASN1_CHOICE | SEC_ASN1_POINTER |
200 SEC_ASN1_INLINE | SEC_ASN1_ANY | SEC_ASN1_SAVE);
201
202 buf[0] = 0;
203 if ((kind & SEC_ASN1_CLASS_MASK) != SEC_ASN1_UNIVERSAL) {
204 sprintf(buf, " %s", class_names[(kind & SEC_ASN1_CLASS_MASK) >> 6] );
205 buf += strlen(buf);
206 }
207 if (kind & SEC_ASN1_METHOD_MASK) {
208 sprintf(buf, " %s", method_names[1]);
209 buf += strlen(buf);
210 }
211 if ((kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL) {
212 if (k || !notag) {
213 sprintf(buf, " %s", type_names[k] );
214 if ((k == SEC_ASN1_SET || k == SEC_ASN1_SEQUENCE) &&
215 (kind & SEC_ASN1_GROUP)) {
216 buf += strlen(buf);
217 sprintf(buf, "_OF");
218 }
219 }
220 } else {
221 sprintf(buf, " [%lu]", k);
222 }
223 buf += strlen(buf);
224
225 for (k = kind >> 8, i = 0; k; k >>= 1, ++i) {
226 if (k & 1) {
227 sprintf(buf, " %s", flag_names[i]);
228 buf += strlen(buf);
229 }
230 }
231 return notag != 0;
232 }
233
234 #endif /* DEBUG_ASN1D_STATES */
235
236 typedef enum {
237 allDone,
238 decodeError,
239 keepGoing,
240 needBytes
241 } sec_asn1d_parse_status;
242
243 struct subitem {
244 const void *data;
245 unsigned long len; /* only used for substrings */
246 struct subitem *next;
247 };
248
249 typedef struct sec_asn1d_state_struct {
250 SEC_ASN1DecoderContext *top;
251 const SecAsn1Template *theTemplate;
252 void *dest;
253
254 void *our_mark; /* free on completion */
255
256 struct sec_asn1d_state_struct *parent; /* aka prev */
257 struct sec_asn1d_state_struct *child; /* aka next */
258
259 sec_asn1d_parse_place place;
260
261 /*
262 * XXX explain the next fields as clearly as possible...
263 */
264 unsigned char found_tag_modifiers;
265 unsigned char expect_tag_modifiers;
266 unsigned long check_tag_mask;
267 unsigned long found_tag_number;
268 unsigned long expect_tag_number;
269 unsigned long underlying_kind;
270
271 unsigned long contents_length;
272 unsigned long pending;
273 unsigned long consumed;
274
275 int depth;
276
277 /*
278 * Bit strings have their length adjusted -- the first octet of the
279 * contents contains a value between 0 and 7 which says how many bits
280 * at the end of the octets are not actually part of the bit string;
281 * when parsing bit strings we put that value here because we need it
282 * later, for adjustment of the length (when the whole string is done).
283 */
284 unsigned int bit_string_unused_bits;
285
286 /*
287 * The following are used for indefinite-length constructed strings.
288 */
289 struct subitem *subitems_head;
290 struct subitem *subitems_tail;
291
292 PRPackedBool
293 allocate, /* when true, need to allocate the destination */
294 endofcontents, /* this state ended up parsing end-of-contents octets */
295 explicit, /* we are handling an explicit header */
296 indefinite, /* the current item has indefinite-length encoding */
297 missing, /* an optional field that was not present */
298 optional, /* the template says this field may be omitted */
299 substring; /* this is a substring of a constructed string */
300 } sec_asn1d_state;
301
302 #define IS_HIGH_TAG_NUMBER(n) ((n) == SEC_ASN1_HIGH_TAG_NUMBER)
303 #define LAST_TAG_NUMBER_BYTE(b) (((b) & 0x80) == 0)
304 #define TAG_NUMBER_BITS 7
305 #define TAG_NUMBER_MASK 0x7f
306
307 #define LENGTH_IS_SHORT_FORM(b) (((b) & 0x80) == 0)
308 #define LONG_FORM_LENGTH(b) ((b) & 0x7f)
309
310 #define HIGH_BITS(field,cnt) ((field) >> ((sizeof(field) * 8) - (cnt)))
311
312
313 /*
314 * An "outsider" will have an opaque pointer to this, created by calling
315 * SEC_ASN1DecoderStart(). It will be passed back in to all subsequent
316 * calls to SEC_ASN1DecoderUpdate(), and when done it is passed to
317 * SEC_ASN1DecoderFinish().
318 */
319 struct sec_DecoderContext_struct {
320 PRArenaPool *our_pool; /* for our internal allocs */
321 PRArenaPool *their_pool; /* for destination structure allocs */
322 #ifdef SEC_ASN1D_FREE_ON_ERROR /*
323 * XXX see comment below (by same
324 * ifdef) that explains why this
325 * does not work (need more smarts
326 * in order to free back to mark)
327 */
328 /*
329 * XXX how to make their_mark work in the case where they do NOT
330 * give us a pool pointer?
331 */
332 void *their_mark; /* free on error */
333 #endif
334
335 sec_asn1d_state *current;
336 sec_asn1d_parse_status status;
337
338 SEC_ASN1NotifyProc notify_proc; /* call before/after handling field */
339 void *notify_arg; /* argument to notify_proc */
340 PRBool during_notify; /* true during call to notify_proc */
341
342 SEC_ASN1WriteProc filter_proc; /* pass field bytes to this */
343 void *filter_arg; /* argument to that function */
344 PRBool filter_only; /* do not allocate/store fields */
345 };
346
347
348 /*
349 * XXX this is a fairly generic function that may belong elsewhere
350 */
351 static void *
352 sec_asn1d_alloc (PRArenaPool *poolp, unsigned long len)
353 {
354 void *thing;
355
356 if (poolp != NULL) {
357 /*
358 * Allocate from the pool.
359 */
360 thing = PORT_ArenaAlloc (poolp, len);
361 } else {
362 /*
363 * Allocate generically.
364 */
365 thing = PORT_Alloc (len);
366 }
367
368 return thing;
369 }
370
371
372 /*
373 * XXX this is a fairly generic function that may belong elsewhere
374 */
375 static void *
376 sec_asn1d_zalloc (PRArenaPool *poolp, unsigned long len)
377 {
378 void *thing;
379
380 thing = sec_asn1d_alloc (poolp, len);
381 if (thing != NULL)
382 PORT_Memset (thing, 0, len);
383 return thing;
384 }
385
386
387 static sec_asn1d_state *
388 sec_asn1d_push_state (SEC_ASN1DecoderContext *cx,
389 const SecAsn1Template *theTemplate,
390 void *dest, PRBool new_depth)
391 {
392 sec_asn1d_state *state, *new_state;
393
394 state = cx->current;
395
396 PORT_Assert (state == NULL || state->child == NULL);
397
398 if (state != NULL) {
399 PORT_Assert (state->our_mark == NULL);
400 state->our_mark = PORT_ArenaMark (cx->our_pool);
401 }
402
403 new_state = (sec_asn1d_state*)sec_asn1d_zalloc (cx->our_pool,
404 sizeof(*new_state));
405 if (new_state == NULL) {
406 dprintf("decodeError: zalloc failure\n");
407 goto loser;
408 }
409
410 new_state->top = cx;
411 new_state->parent = state;
412 new_state->theTemplate = theTemplate;
413 new_state->place = notInUse;
414 if (dest != NULL)
415 new_state->dest = (char *)dest + theTemplate->offset;
416
417 if (state != NULL) {
418 new_state->depth = state->depth;
419 if (new_depth) {
420 if (++new_state->depth > SEC_ASN1D_MAX_DEPTH) {
421 PORT_SetError (SEC_ERROR_BAD_DER);
422 goto loser;
423 }
424 }
425 state->child = new_state;
426 }
427
428 cx->current = new_state;
429 return new_state;
430
431 loser:
432 cx->status = decodeError;
433 if (state != NULL) {
434 PORT_ArenaRelease(cx->our_pool, state->our_mark);
435 state->our_mark = NULL;
436 }
437 return NULL;
438 }
439
440
441 static void
442 sec_asn1d_scrub_state (sec_asn1d_state *state)
443 {
444 /*
445 * Some default "scrubbing".
446 * XXX right set of initializations?
447 */
448 state->place = beforeIdentifier;
449 state->endofcontents = PR_FALSE;
450 state->indefinite = PR_FALSE;
451 state->missing = PR_FALSE;
452
453 PORT_Assert (state->consumed == 0);
454 }
455
456
457 static sec_asn1d_state *
458 sec_asn1d_get_enclosing_construct(sec_asn1d_state *state)
459 {
460 for (state = state->parent; state; state = state->parent) {
461 sec_asn1d_parse_place place = state->place;
462 if (place != afterImplicit &&
463 place != afterPointer &&
464 place != afterInline &&
465 place != afterSaveEncoding &&
466 place != duringSaveEncoding &&
467 place != duringChoice) {
468
469 /* we've walked up the stack to a state that represents
470 ** the enclosing construct.
471 */
472 break;
473 }
474 }
475 return state;
476 }
477
478
479 static PRBool
480 sec_asn1d_parent_allows_EOC(sec_asn1d_state *state)
481 {
482 /* get state of enclosing construct. */
483 state = sec_asn1d_get_enclosing_construct(state);
484 if (state) {
485 sec_asn1d_parse_place place = state->place;
486 /* Is it one of the types that permits an unexpected EOC? */
487 int eoc_permitted =
488 (place == duringGroup ||
489 place == duringConstructedString ||
490 state->child->optional);
491 return (state->indefinite && eoc_permitted) ? PR_TRUE : PR_FALSE;
492 }
493 return PR_FALSE;
494 }
495
496
497 static void
498 sec_asn1d_notify_before (SEC_ASN1DecoderContext *cx, void *dest, int depth)
499 {
500 if (cx->notify_proc == NULL)
501 return;
502
503 cx->during_notify = PR_TRUE;
504 (* cx->notify_proc) (cx->notify_arg, PR_TRUE, dest, depth);
505 cx->during_notify = PR_FALSE;
506 }
507
508
509 static void
510 sec_asn1d_notify_after (SEC_ASN1DecoderContext *cx, void *dest, int depth)
511 {
512 if (cx->notify_proc == NULL)
513 return;
514
515 cx->during_notify = PR_TRUE;
516 (* cx->notify_proc) (cx->notify_arg, PR_FALSE, dest, depth);
517 cx->during_notify = PR_FALSE;
518 }
519
520
521 static sec_asn1d_state *
522 sec_asn1d_init_state_based_on_template (sec_asn1d_state *state,
523 #ifdef __APPLE__
524 const char *buf, /* for SEC_ASN1GetSubtemplate() */
525 size_t len
526 #endif
527 )
528 {
529 PRBool explicit, optional, universal;
530 unsigned char expect_tag_modifiers;
531 unsigned long encode_kind, under_kind;
532 unsigned long check_tag_mask, expect_tag_number;
533 #ifdef __APPLE__
534 unsigned long dynamic;
535 #endif
536
537
538 /* XXX Check that both of these tests are really needed/appropriate. */
539 if (state == NULL || state->top->status == decodeError || state->theTemplate == NULL)
540 return state;
541
542 encode_kind = state->theTemplate->kind;
543
544 if (encode_kind & SEC_ASN1_SAVE) {
545 /*
546 * This is a "magic" field that saves away all bytes, allowing
547 * the immediately following field to still be decoded from this
548 * same spot -- sort of a fork.
549 */
550 /* check that there are no extraneous bits */
551 PORT_Assert (encode_kind == SEC_ASN1_SAVE);
552 if (state->top->filter_only) {
553 /*
554 * If we are not storing, then we do not do the SAVE field
555 * at all. Just move ahead to the "real" field instead,
556 * doing the appropriate notify calls before and after.
557 */
558 sec_asn1d_notify_after (state->top, state->dest, state->depth);
559 /*
560 * Since we are not storing, allow for our current dest value
561 * to be NULL. (This might not actually occur, but right now I
562 * cannot convince myself one way or the other.) If it is NULL,
563 * assume that our parent dest can help us out.
564 */
565 if (state->dest == NULL)
566 state->dest = state->parent->dest;
567 else
568 state->dest =
569 (char *)state->dest - state->theTemplate->offset;
570 state->theTemplate++;
571 if (state->dest != NULL)
572 state->dest =
573 (char *)state->dest + state->theTemplate->offset;
574 sec_asn1d_notify_before (state->top, state->dest, state->depth);
575 encode_kind = state->theTemplate->kind;
576 PORT_Assert ((encode_kind & SEC_ASN1_SAVE) == 0);
577 } else {
578 sec_asn1d_scrub_state (state);
579 state->place = duringSaveEncoding;
580 state = sec_asn1d_push_state (state->top, kSecAsn1AnyTemplate,
581 state->dest, PR_FALSE);
582 if (state != NULL)
583 state = sec_asn1d_init_state_based_on_template (state,
584 buf /* __APPLE__ */, len /* __APPLE__ */);
585 return state;
586 }
587 }
588
589
590 universal = ((encode_kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL)
591 ? PR_TRUE : PR_FALSE;
592
593 explicit = (encode_kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE;
594 encode_kind &= ~SEC_ASN1_EXPLICIT;
595
596 optional = (encode_kind & SEC_ASN1_OPTIONAL) ? PR_TRUE : PR_FALSE;
597 encode_kind &= ~SEC_ASN1_OPTIONAL;
598
599 #ifdef __APPLE__
600 dynamic = (encode_kind & SEC_ASN1_DYNAMIC) ? PR_TRUE : PR_FALSE;
601 encode_kind &= ~SEC_ASN1_DYNAMIC;
602 #endif
603
604 PORT_Assert (!(explicit && universal)); /* bad templates */
605
606 encode_kind &= ~SEC_ASN1_DYNAMIC;
607 encode_kind &= ~SEC_ASN1_MAY_STREAM;
608
609 if( encode_kind & SEC_ASN1_CHOICE ) {
610 #if 0 /* XXX remove? */
611 sec_asn1d_state *child = sec_asn1d_push_state(state->top, state->theTemplate, state->dest, PR_FALSE);
612 if( (sec_asn1d_state *)NULL == child ) {
613 return (sec_asn1d_state *)NULL;
614 }
615
616 child->allocate = state->allocate;
617 child->place = beforeChoice;
618 return child;
619 #else
620 state->place = beforeChoice;
621 return state;
622 #endif
623 }
624
625 if ((encode_kind & (SEC_ASN1_POINTER | SEC_ASN1_INLINE)) || (!universal
626 && !explicit)) {
627 const SecAsn1Template *subt;
628 void *dest;
629 PRBool child_allocate;
630 void *subDest;
631
632 PORT_Assert ((encode_kind & (SEC_ASN1_ANY | SEC_ASN1_SKIP)) == 0);
633
634 sec_asn1d_scrub_state (state);
635 child_allocate = PR_FALSE;
636
637 if (encode_kind & SEC_ASN1_POINTER) {
638 /*
639 * A POINTER means we need to allocate the destination for
640 * this field. But, since it may also be an optional field,
641 * we defer the allocation until later; we just record that
642 * it needs to be done.
643 *
644 * There are two possible scenarios here -- one is just a
645 * plain POINTER (kind of like INLINE, except with allocation)
646 * and the other is an implicitly-tagged POINTER. We don't
647 * need to do anything special here for the two cases, but
648 * since the template definition can be tricky, we do check
649 * that there are no extraneous bits set in encode_kind.
650 *
651 * XXX The same conditions which assert should set an error.
652 */
653 if (universal) {
654 /*
655 * "universal" means this entry is a standalone POINTER;
656 * there should be no other bits set in encode_kind.
657 */
658 PORT_Assert (encode_kind == SEC_ASN1_POINTER);
659 } else {
660 /*
661 * If we get here we have an implicitly-tagged field
662 * that needs to be put into a POINTER. The subtemplate
663 * will determine how to decode the field, but encode_kind
664 * describes the (implicit) tag we are looking for.
665 * The non-tag bits of encode_kind will be ignored by
666 * the code below; none of them should be set, however,
667 * except for the POINTER bit itself -- so check that.
668 */
669 PORT_Assert ((encode_kind & ~SEC_ASN1_TAG_MASK)
670 == SEC_ASN1_POINTER);
671 }
672 if (!state->top->filter_only)
673 child_allocate = PR_TRUE;
674 dest = NULL;
675 state->place = afterPointer;
676 } else {
677 dest = state->dest;
678 if (encode_kind & SEC_ASN1_INLINE) {
679 /* check that there are no extraneous bits */
680 /* FIXME - why are optional and inline mutually
681 * exclusive? Delete this assert and see what happens...
682 PORT_Assert (encode_kind == SEC_ASN1_INLINE && !optional);
683 */
684 state->place = afterInline;
685 } else {
686 state->place = afterImplicit;
687 }
688 }
689
690 state->optional = optional;
691
692 subDest = state->dest;
693 #if defined(__APPLE__)
694 /*
695 * We might be starting the processing of a group or a
696 * set, in which case state->dest is NULL. Get parent's dest,
697 * or grandparent's, etc... just for the use by
698 * SEC_ASN1GetSubtemplate (specifically, by dynamic
699 * choosers)
700 */
701 sec_asn1d_state *tempState = state;
702 while(subDest == NULL) {
703 sec_asn1d_state *parent = tempState->parent;
704 if(parent == NULL) {
705 /* Oh well. Not going to work for this template. */
706 break;
707 }
708 subDest = parent->dest;
709 tempState = parent;
710 }
711 #endif /* __APPLE__ */
712 subt = SEC_ASN1GetSubtemplate (state->theTemplate, subDest,
713 PR_FALSE, buf /* __APPLE__ */, len /* __APPLE__ */);
714 state = sec_asn1d_push_state (state->top, subt, dest, PR_FALSE);
715 if (state == NULL)
716 return NULL;
717
718 state->allocate = child_allocate;
719
720 if (universal
721 #ifdef __APPLE__
722 /* Dynamic: restart with new template */
723 || dynamic
724 #endif
725 ) {
726 state = sec_asn1d_init_state_based_on_template (state,
727 buf /* __APPLE__ */, len /* __APPLE__ */);
728 if (state != NULL) {
729 /*
730 * If this field is optional, we need to record that on
731 * the pushed child so it won't fail if the field isn't
732 * found. I can't think of a way that this new state
733 * could already have optional set (which we would wipe
734 * out below if our local optional is not set) -- but
735 * just to be sure, assert that it isn't set.
736 */
737 PORT_Assert (!state->optional);
738 state->optional = optional;
739 }
740 return state;
741 }
742
743 under_kind = state->theTemplate->kind;
744 under_kind &= ~SEC_ASN1_MAY_STREAM;
745 } else if (explicit) {
746 /*
747 * For explicit, we only need to match the encoding tag next,
748 * then we will push another state to handle the entire inner
749 * part. In this case, there is no underlying kind which plays
750 * any part in the determination of the outer, explicit tag.
751 * So we just set under_kind to 0, which is not a valid tag,
752 * and the rest of the tag matching stuff should be okay.
753 */
754 under_kind = 0;
755 } else {
756 /*
757 * Nothing special; the underlying kind and the given encoding
758 * information are the same.
759 */
760 under_kind = encode_kind;
761 }
762
763 /* XXX is this the right set of bits to test here? */
764 PORT_Assert ((under_kind & (SEC_ASN1_EXPLICIT
765 | SEC_ASN1_MAY_STREAM
766 | SEC_ASN1_INLINE | SEC_ASN1_POINTER)) == 0);
767
768 if (encode_kind & (SEC_ASN1_ANY | SEC_ASN1_SKIP)) {
769 PORT_Assert (encode_kind == under_kind);
770 if (encode_kind & SEC_ASN1_SKIP) {
771 PORT_Assert (!optional);
772 PORT_Assert (encode_kind == SEC_ASN1_SKIP);
773 state->dest = NULL;
774 }
775 check_tag_mask = 0;
776 expect_tag_modifiers = 0;
777 expect_tag_number = 0;
778 } else {
779 check_tag_mask = SEC_ASN1_TAG_MASK;
780 expect_tag_modifiers = (unsigned char)encode_kind & SEC_ASN1_TAG_MASK
781 & ~SEC_ASN1_TAGNUM_MASK;
782 /*
783 * XXX This assumes only single-octet identifiers. To handle
784 * the HIGH TAG form we would need to do some more work, especially
785 * in how to specify them in the template, because right now we
786 * do not provide a way to specify more *tag* bits in encode_kind.
787 */
788 expect_tag_number = encode_kind & SEC_ASN1_TAGNUM_MASK;
789
790 switch (under_kind & SEC_ASN1_TAGNUM_MASK) {
791 case SEC_ASN1_SET:
792 /*
793 * XXX A plain old SET (as opposed to a SET OF) is not
794 * implemented.
795 * If it ever is, remove this assert...
796 */
797 PORT_Assert ((under_kind & SEC_ASN1_GROUP) != 0);
798 /* fallthru */
799 case SEC_ASN1_SEQUENCE:
800 expect_tag_modifiers |= SEC_ASN1_CONSTRUCTED;
801 break;
802 case SEC_ASN1_BIT_STRING:
803 case SEC_ASN1_BMP_STRING:
804 case SEC_ASN1_GENERALIZED_TIME:
805 case SEC_ASN1_IA5_STRING:
806 case SEC_ASN1_OCTET_STRING:
807 case SEC_ASN1_PRINTABLE_STRING:
808 case SEC_ASN1_T61_STRING:
809 case SEC_ASN1_UNIVERSAL_STRING:
810 case SEC_ASN1_UTC_TIME:
811 case SEC_ASN1_UTF8_STRING:
812 case SEC_ASN1_VISIBLE_STRING:
813 check_tag_mask &= ~SEC_ASN1_CONSTRUCTED;
814 break;
815 }
816 }
817
818 state->check_tag_mask = check_tag_mask;
819 state->expect_tag_modifiers = expect_tag_modifiers;
820 state->expect_tag_number = expect_tag_number;
821 state->underlying_kind = under_kind;
822 state->explicit = explicit;
823 state->optional = optional;
824 sec_asn1d_scrub_state (state);
825
826 return state;
827 }
828
829
830 static unsigned long
831 sec_asn1d_parse_identifier (sec_asn1d_state *state,
832 const char *buf, unsigned long len)
833 {
834 unsigned char byte;
835 unsigned char tag_number;
836
837 PORT_Assert (state->place == beforeIdentifier);
838
839 if (len == 0) {
840 state->top->status = needBytes;
841 return 0;
842 }
843
844 byte = (unsigned char) *buf;
845 #ifdef DEBUG_ASN1D_STATES
846 if (doDumpStates > 0) {
847 char kindBuf[256];
848 formatKind(byte, kindBuf);
849 printf("Found tag %02x %s\n", byte, kindBuf);
850 }
851 #endif
852 tag_number = byte & SEC_ASN1_TAGNUM_MASK;
853
854 if (IS_HIGH_TAG_NUMBER (tag_number)) {
855 state->place = duringIdentifier;
856 state->found_tag_number = 0;
857 /*
858 * Actually, we have no idea how many bytes are pending, but we
859 * do know that it is at least 1. That is all we know; we have
860 * to look at each byte to know if there is another, etc.
861 */
862 state->pending = 1;
863 } else {
864 if (byte == 0 && sec_asn1d_parent_allows_EOC(state)) {
865 /*
866 * Our parent has indefinite-length encoding, and the
867 * entire tag found is 0, so it seems that we have hit the
868 * end-of-contents octets. To handle this, we just change
869 * our state to that which expects to get the bytes of the
870 * end-of-contents octets and let that code re-read this byte
871 * so that our categorization of field types is correct.
872 * After that, our parent will then deal with everything else.
873 */
874 state->place = duringEndOfContents;
875 state->pending = 2;
876 state->found_tag_number = 0;
877 state->found_tag_modifiers = 0;
878 /*
879 * We might be an optional field that is, as we now find out,
880 * missing. Give our parent a clue that this happened.
881 */
882 if (state->optional)
883 state->missing = PR_TRUE;
884 return 0;
885 }
886 state->place = afterIdentifier;
887 state->found_tag_number = tag_number;
888 }
889 state->found_tag_modifiers = byte & ~SEC_ASN1_TAGNUM_MASK;
890
891 return 1;
892 }
893
894
895 static unsigned long
896 sec_asn1d_parse_more_identifier (sec_asn1d_state *state,
897 const char *buf, unsigned long len)
898 {
899 unsigned char byte;
900 int count;
901
902 PORT_Assert (state->pending == 1);
903 PORT_Assert (state->place == duringIdentifier);
904
905 if (len == 0) {
906 state->top->status = needBytes;
907 return 0;
908 }
909
910 count = 0;
911
912 while (len && state->pending) {
913 if (HIGH_BITS (state->found_tag_number, TAG_NUMBER_BITS) != 0) {
914 /*
915 * The given high tag number overflows our container;
916 * just give up. This is not likely to *ever* happen.
917 */
918 PORT_SetError (SEC_ERROR_BAD_DER);
919 state->top->status = decodeError;
920 dprintf("decodeError: parse_more_id high bits oflow\n");
921 return 0;
922 }
923
924 state->found_tag_number <<= TAG_NUMBER_BITS;
925
926 byte = (unsigned char) buf[count++];
927 state->found_tag_number |= (byte & TAG_NUMBER_MASK);
928
929 len--;
930 if (LAST_TAG_NUMBER_BYTE (byte))
931 state->pending = 0;
932 }
933
934 if (state->pending == 0)
935 state->place = afterIdentifier;
936
937 return count;
938 }
939
940
941 static void
942 sec_asn1d_confirm_identifier (sec_asn1d_state *state)
943 {
944 PRBool match;
945
946 PORT_Assert (state->place == afterIdentifier);
947
948 match = (PRBool)(((state->found_tag_modifiers & state->check_tag_mask)
949 == state->expect_tag_modifiers)
950 && ((state->found_tag_number & state->check_tag_mask)
951 == state->expect_tag_number));
952 if (match) {
953 state->place = beforeLength;
954 } else {
955 if (state->optional) {
956 state->missing = PR_TRUE;
957 state->place = afterEndOfContents;
958 } else {
959 PORT_SetError (SEC_ERROR_BAD_DER);
960 state->top->status = decodeError;
961 //dprintf("decodeError: sec_asn1d_confirm_identifier\n");
962 }
963 }
964 }
965
966
967 static unsigned long
968 sec_asn1d_parse_length (sec_asn1d_state *state,
969 const char *buf, unsigned long len)
970 {
971 unsigned char byte;
972
973 PORT_Assert (state->place == beforeLength);
974
975 if (len == 0) {
976 state->top->status = needBytes;
977 return 0;
978 }
979
980 /*
981 * The default/likely outcome. It may get adjusted below.
982 */
983 state->place = afterLength;
984
985 byte = (unsigned char) *buf;
986
987 if (LENGTH_IS_SHORT_FORM (byte)) {
988 state->contents_length = byte;
989 } else {
990 state->contents_length = 0;
991 state->pending = LONG_FORM_LENGTH (byte);
992 if (state->pending == 0) {
993 state->indefinite = PR_TRUE;
994 } else {
995 state->place = duringLength;
996 }
997 }
998
999 /* If we're parsing an ANY, SKIP, or SAVE template, and
1000 ** the object being saved is definite length encoded and constructed,
1001 ** there's no point in decoding that construct's members.
1002 ** So, just forget it's constructed and treat it as primitive.
1003 ** (SAVE appears as an ANY at this point)
1004 */
1005 if (!state->indefinite &&
1006 (state->underlying_kind & (SEC_ASN1_ANY | SEC_ASN1_SKIP))) {
1007 state->found_tag_modifiers &= ~SEC_ASN1_CONSTRUCTED;
1008 }
1009
1010 return 1;
1011 }
1012
1013
1014 static unsigned long
1015 sec_asn1d_parse_more_length (sec_asn1d_state *state,
1016 const char *buf, unsigned long len)
1017 {
1018 int count;
1019
1020 PORT_Assert (state->pending > 0);
1021 PORT_Assert (state->place == duringLength);
1022
1023 if (len == 0) {
1024 state->top->status = needBytes;
1025 return 0;
1026 }
1027
1028 count = 0;
1029
1030 while (len && state->pending) {
1031 if (HIGH_BITS (state->contents_length, 9) != 0) {
1032 /*
1033 * The given full content length overflows our container;
1034 * just give up.
1035 */
1036 PORT_SetError (SEC_ERROR_BAD_DER);
1037 state->top->status = decodeError;
1038 dprintf("decodeError: sec_asn1d_parse_more_length\n");
1039 return 0;
1040 }
1041
1042 state->contents_length <<= 8;
1043 state->contents_length |= (unsigned char) buf[count++];
1044
1045 len--;
1046 state->pending--;
1047 }
1048
1049 if (state->pending == 0)
1050 state->place = afterLength;
1051
1052 return count;
1053 }
1054
1055
1056 /*
1057 * Helper function for sec_asn1d_prepare_for_contents.
1058 * Checks that a value representing a number of bytes consumed can be
1059 * subtracted from a remaining length. If so, returns PR_TRUE.
1060 * Otherwise, sets the error SEC_ERROR_BAD_DER, indicates that there was a
1061 * decoding error in the given SEC_ASN1DecoderContext, and returns PR_FALSE.
1062 */
1063 static PRBool
1064 sec_asn1d_check_and_subtract_length (unsigned long *remaining,
1065 unsigned long consumed,
1066 SEC_ASN1DecoderContext *cx)
1067 {
1068 PORT_Assert(remaining);
1069 PORT_Assert(cx);
1070 if (!remaining || !cx) {
1071 PORT_SetError (SEC_ERROR_INVALID_ARGS);
1072 if(cx) {
1073 cx->status = decodeError;
1074 }
1075 return PR_FALSE;
1076 }
1077 if (*remaining < consumed) {
1078 PORT_SetError (SEC_ERROR_BAD_DER);
1079 cx->status = decodeError;
1080 return PR_FALSE;
1081 }
1082 *remaining -= consumed;
1083 return PR_TRUE;
1084 }
1085
1086
1087 static void
1088 sec_asn1d_prepare_for_contents (sec_asn1d_state *state,
1089 #ifdef __APPLE__
1090 const char *buf, /* needed for SEC_ASN1GetSubtemplate */
1091 size_t len
1092 #endif
1093 )
1094 {
1095 SecAsn1Item *item=NULL;
1096 PRArenaPool *poolp;
1097 unsigned long alloc_len;
1098
1099 #ifdef DEBUG_ASN1D_STATES
1100 if (doDumpStates > 0) {
1101 printf("Found Length %lu %s\n", state->contents_length,
1102 state->indefinite ? "indefinite" : "");
1103 }
1104 #endif
1105
1106 /**
1107 * The maximum length for a child element should be constrained to the
1108 * length remaining in the first definite length element in the ancestor
1109 * stack. If there is no definite length element in the ancestor stack,
1110 * there's nothing to constrain the length of the child, so there's no
1111 * further processing necessary.
1112 *
1113 * It's necessary to walk the ancestor stack, because it's possible to have
1114 * definite length children that are part of an indefinite length element,
1115 * which is itself part of an indefinite length element, and which is
1116 * ultimately part of a definite length element. A simple example of this
1117 * would be the handling of constructed OCTET STRINGs in BER encoding.
1118 *
1119 * This algorithm finds the first definite length element in the ancestor
1120 * stack, if any, and if so, ensures that the length of the child element
1121 * is consistent with the number of bytes remaining in the constraining
1122 * ancestor element (that is, after accounting for any other sibling
1123 * elements that may have been read).
1124 *
1125 * It's slightly complicated by the need to account both for integer
1126 * underflow and overflow, as well as ensure that for indefinite length
1127 * encodings, there's also enough space for the End-of-Contents (EOC)
1128 * octets (Tag = 0x00, Length = 0x00, or two bytes).
1129 */
1130
1131 /* Determine the maximum length available for this element by finding the
1132 * first definite length ancestor, if any. */
1133 sec_asn1d_state *parent = sec_asn1d_get_enclosing_construct(state);
1134 while (parent && parent->indefinite) {
1135 parent = sec_asn1d_get_enclosing_construct(parent);
1136 }
1137 /* If parent is null, state is either the outermost state / at the top of
1138 * the stack, or the outermost state uses indefinite length encoding. In
1139 * these cases, there's nothing external to constrain this element, so
1140 * there's nothing to check. */
1141 if (parent) {
1142 unsigned long remaining = parent->pending;
1143 parent = state;
1144 do {
1145 if (!sec_asn1d_check_and_subtract_length(&remaining, parent->consumed, state->top) ||
1146 /* If parent->indefinite is true, parent->contents_length is
1147 * zero and this is a no-op. */
1148 !sec_asn1d_check_and_subtract_length(&remaining, parent->contents_length, state->top) ||
1149 /* If parent->indefinite is true, then ensure there is enough
1150 * space for an EOC tag of 2 bytes. */
1151 (parent->indefinite && !sec_asn1d_check_and_subtract_length(&remaining, 2, state->top))) {
1152 /* This element is larger than its enclosing element, which is
1153 * invalid. */
1154 return;
1155 }
1156 } while ((parent = sec_asn1d_get_enclosing_construct(parent)) &&
1157 parent->indefinite);
1158 }
1159
1160 /*
1161 * XXX I cannot decide if this allocation should exclude the case
1162 * where state->endofcontents is true -- figure it out!
1163 */
1164 if (state->allocate) {
1165 void *dest;
1166
1167 PORT_Assert (state->dest == NULL);
1168 /*
1169 * We are handling a POINTER or a member of a GROUP, and need to
1170 * allocate for the data structure.
1171 */
1172 dest = sec_asn1d_zalloc (state->top->their_pool,
1173 state->theTemplate->size);
1174 if (dest == NULL) {
1175 dprintf("decodeError: sec_asn1d_prepare_for_contents zalloc\n");
1176 state->top->status = decodeError;
1177 return;
1178 }
1179 /* FIXME _ we're losing the dest pointer after this! */
1180 state->dest = (char *)dest + state->theTemplate->offset;
1181
1182 /*
1183 * For a member of a GROUP, our parent will later put the
1184 * pointer wherever it belongs. But for a POINTER, we need
1185 * to record the destination now, in case notify or filter
1186 * procs need access to it -- they cannot find it otherwise,
1187 * until it is too late (for one-pass processing).
1188 */
1189 if (state->parent->place == afterPointer) {
1190 void **placep;
1191
1192 placep = state->parent->dest;
1193 *placep = dest;
1194 }
1195 }
1196
1197 /*
1198 * Remember, length may be indefinite here! In that case,
1199 * both contents_length and pending will be zero.
1200 */
1201 state->pending = state->contents_length;
1202
1203 /*
1204 * An EXPLICIT is nothing but an outer header, which we have
1205 * already parsed and accepted. Now we need to do the inner
1206 * header and its contents.
1207 */
1208 if (state->explicit) {
1209 state->place = afterExplicit;
1210 state = sec_asn1d_push_state (state->top,
1211 SEC_ASN1GetSubtemplate(state->theTemplate,
1212 state->dest,
1213 PR_FALSE,
1214 buf /* __APPLE__ */,
1215 len /* __APPLE__ */),
1216 state->dest, PR_TRUE);
1217 if (state != NULL)
1218 state = sec_asn1d_init_state_based_on_template (state,
1219 buf /* __APPLE__ */, len /* __APPLE__ */);
1220 (void) state;
1221 return;
1222 }
1223
1224 /*
1225 * For GROUP (SET OF, SEQUENCE OF), even if we know the length here
1226 * we cannot tell how many items we will end up with ... so push a
1227 * state that can keep track of "children" (the individual members
1228 * of the group; we will allocate as we go and put them all together
1229 * at the end.
1230 */
1231 if (state->underlying_kind & SEC_ASN1_GROUP) {
1232 /* XXX If this assertion holds (should be able to confirm it via
1233 * inspection, too) then move this code into the switch statement
1234 * below under cases SET_OF and SEQUENCE_OF; it will be cleaner.
1235 */
1236 PORT_Assert (state->underlying_kind == SEC_ASN1_SET_OF
1237 || state->underlying_kind == SEC_ASN1_SEQUENCE_OF
1238 || state->underlying_kind == (SEC_ASN1_SEQUENCE_OF|SEC_ASN1_DYNAMIC)
1239 || state->underlying_kind == (SEC_ASN1_SET_OF|SEC_ASN1_DYNAMIC)
1240 );
1241 if (state->contents_length != 0 || state->indefinite) {
1242 const SecAsn1Template *subt;
1243
1244 state->place = duringGroup;
1245 subt = SEC_ASN1GetSubtemplate (state->theTemplate, state->dest,
1246 PR_FALSE, buf /* __APPLE__ */, len /* __APPLE__ */);
1247 state = sec_asn1d_push_state (state->top, subt, NULL, PR_TRUE);
1248 if (state != NULL) {
1249 if (!state->top->filter_only)
1250 state->allocate = PR_TRUE; /* XXX propogate this? */
1251 /*
1252 * Do the "before" field notification for next in group.
1253 */
1254 sec_asn1d_notify_before (state->top, state->dest, state->depth);
1255 state = sec_asn1d_init_state_based_on_template (state,
1256 buf /* __APPLE__ */, len /* __APPLE__ */);
1257 }
1258 } else {
1259 /*
1260 * A group of zero; we are done.
1261 * Set state to afterGroup and let that code plant the NULL.
1262 */
1263 state->place = afterGroup;
1264 }
1265 (void) state;
1266 return;
1267 }
1268
1269 switch (state->underlying_kind) {
1270 case SEC_ASN1_SEQUENCE:
1271 /*
1272 * We need to push a child to handle the individual fields.
1273 */
1274 state->place = duringSequence;
1275 state = sec_asn1d_push_state (state->top, state->theTemplate + 1,
1276 state->dest, PR_TRUE);
1277 if (state != NULL) {
1278 /*
1279 * Do the "before" field notification.
1280 */
1281 sec_asn1d_notify_before (state->top, state->dest, state->depth);
1282 state = sec_asn1d_init_state_based_on_template (state,
1283 buf /* __APPLE__ */, len /* __APPLE__ */);
1284 }
1285 (void) state;
1286 break;
1287
1288 case SEC_ASN1_SET: /* XXX SET is not really implemented */
1289 /*
1290 * XXX A plain SET requires special handling; scanning of a
1291 * template to see where a field should go (because by definition,
1292 * they are not in any particular order, and you have to look at
1293 * each tag to disambiguate what the field is). We may never
1294 * implement this because in practice, it seems to be unused.
1295 */
1296 dprintf("decodeError: prepare for contents SEC_ASN1_SET\n");
1297 PORT_Assert(0);
1298 PORT_SetError (SEC_ERROR_BAD_DER); /* XXX */
1299 state->top->status = decodeError;
1300 break;
1301
1302 case SEC_ASN1_NULL:
1303 /*
1304 * The NULL type, by definition, is "nothing", content length of zero.
1305 * An indefinite-length encoding is not alloweed.
1306 */
1307 if (state->contents_length || state->indefinite) {
1308 dprintf("decodeError: prepare for contents indefinite NULL\n");
1309 PORT_SetError (SEC_ERROR_BAD_DER);
1310 state->top->status = decodeError;
1311 break;
1312 }
1313 if (state->dest != NULL) {
1314 item = (SecAsn1Item *)(state->dest);
1315 item->Data = NULL;
1316 item->Length = 0;
1317 }
1318 state->place = afterEndOfContents;
1319 break;
1320
1321 case SEC_ASN1_BMP_STRING:
1322 /* Error if length is not divisable by 2 */
1323 if (state->contents_length % 2) {
1324 dprintf("decodeError: prepare for contents odd length BMP_STRING\n");
1325 PORT_SetError (SEC_ERROR_BAD_DER);
1326 state->top->status = decodeError;
1327 break;
1328 }
1329 /* otherwise, handle as other string types */
1330 goto regular_string_type;
1331
1332 case SEC_ASN1_UNIVERSAL_STRING:
1333 /* Error if length is not divisable by 4 */
1334 if (state->contents_length % 4) {
1335 dprintf("decodeError: prepare for contents odd length UNIV_STRING\n");
1336 PORT_SetError (SEC_ERROR_BAD_DER);
1337 state->top->status = decodeError;
1338 break;
1339 }
1340 /* otherwise, handle as other string types */
1341 goto regular_string_type;
1342
1343 case SEC_ASN1_SKIP:
1344 case SEC_ASN1_ANY:
1345 case SEC_ASN1_ANY_CONTENTS:
1346 /*
1347 * These are not (necessarily) strings, but they need nearly
1348 * identical handling (especially when we need to deal with
1349 * constructed sub-pieces), so we pretend they are.
1350 */
1351 /* fallthru */
1352 regular_string_type:
1353 case SEC_ASN1_BIT_STRING:
1354 case SEC_ASN1_IA5_STRING:
1355 case SEC_ASN1_OCTET_STRING:
1356 case SEC_ASN1_PRINTABLE_STRING:
1357 case SEC_ASN1_T61_STRING:
1358 case SEC_ASN1_UTC_TIME:
1359 case SEC_ASN1_UTF8_STRING:
1360 case SEC_ASN1_VISIBLE_STRING:
1361 /*
1362 * We are allocating for a primitive or a constructed string.
1363 * If it is a constructed string, it may also be indefinite-length.
1364 * If it is primitive, the length can (legally) be zero.
1365 * Our first order of business is to allocate the memory for
1366 * the string, if we can (if we know the length).
1367 */
1368 item = (SecAsn1Item *)(state->dest);
1369
1370 /*
1371 * If the item is a definite-length constructed string, then
1372 * the contents_length is actually larger than what we need
1373 * (because it also counts each intermediate header which we
1374 * will be throwing away as we go), but it is a perfectly good
1375 * upper bound that we just allocate anyway, and then concat
1376 * as we go; we end up wasting a few extra bytes but save a
1377 * whole other copy.
1378 */
1379 alloc_len = state->contents_length;
1380 poolp = NULL; /* quiet compiler warnings about unused... */
1381
1382 if (item == NULL || state->top->filter_only) {
1383 if (item != NULL) {
1384 item->Data = NULL;
1385 item->Length = 0;
1386 }
1387 alloc_len = 0;
1388 } else if (state->substring) {
1389 /*
1390 * If we are a substring of a constructed string, then we may
1391 * not have to allocate anything (because our parent, the
1392 * actual constructed string, did it for us). If we are a
1393 * substring and we *do* have to allocate, that means our
1394 * parent is an indefinite-length, so we allocate from our pool;
1395 * later our parent will copy our string into the aggregated
1396 * whole and free our pool allocation.
1397 */
1398 if (item->Data == NULL) {
1399 PORT_Assert (item->Length == 0);
1400 poolp = state->top->our_pool;
1401 } else {
1402 alloc_len = 0;
1403 }
1404 } else {
1405 item->Length = 0;
1406 item->Data = NULL;
1407 poolp = state->top->their_pool;
1408 }
1409
1410 if (alloc_len || ((! state->indefinite)
1411 && (state->subitems_head != NULL))) {
1412 struct subitem *subitem;
1413 unsigned long len;
1414
1415 PORT_Assert (item!=NULL);
1416 if (item==NULL) {
1417 PORT_SetError (SEC_ERROR_BAD_DER);
1418 state->top->status = decodeError;
1419 return;
1420 }
1421 PORT_Assert (item->Length == 0 && item->Data == NULL);
1422 /*
1423 * Check for and handle an ANY which has stashed aside the
1424 * header (identifier and length) bytes for us to include
1425 * in the saved contents.
1426 */
1427 if (state->subitems_head != NULL) {
1428 PORT_Assert (state->underlying_kind == SEC_ASN1_ANY);
1429 for (subitem = state->subitems_head;
1430 subitem != NULL; subitem = subitem->next)
1431 alloc_len += subitem->len;
1432 }
1433
1434 item->Data = (unsigned char*)sec_asn1d_zalloc (poolp, alloc_len);
1435 if (item->Data == NULL) {
1436 dprintf("decodeError: prepare for contents zalloc\n");
1437 state->top->status = decodeError;
1438 break;
1439 }
1440
1441 len = 0;
1442 for (subitem = state->subitems_head;
1443 subitem != NULL; subitem = subitem->next) {
1444 PORT_Memcpy (item->Data + len, subitem->data, subitem->len);
1445 len += subitem->len;
1446 }
1447 item->Length = len;
1448
1449 /*
1450 * Because we use arenas and have a mark set, we later free
1451 * everything we have allocated, so this does *not* present
1452 * a memory leak (it is just temporarily left dangling).
1453 */
1454 state->subitems_head = state->subitems_tail = NULL;
1455 }
1456
1457 if (state->contents_length == 0 && (! state->indefinite)) {
1458 /*
1459 * A zero-length simple or constructed string; we are done.
1460 */
1461 state->place = afterEndOfContents;
1462 } else if (state->found_tag_modifiers & SEC_ASN1_CONSTRUCTED) {
1463 const SecAsn1Template *sub;
1464
1465 switch (state->underlying_kind) {
1466 case SEC_ASN1_ANY:
1467 case SEC_ASN1_ANY_CONTENTS:
1468 sub = kSecAsn1AnyTemplate;
1469 break;
1470 case SEC_ASN1_BIT_STRING:
1471 sub = kSecAsn1BitStringTemplate;
1472 break;
1473 case SEC_ASN1_BMP_STRING:
1474 sub = kSecAsn1BMPStringTemplate;
1475 break;
1476 case SEC_ASN1_GENERALIZED_TIME:
1477 sub = kSecAsn1GeneralizedTimeTemplate;
1478 break;
1479 case SEC_ASN1_IA5_STRING:
1480 sub = kSecAsn1IA5StringTemplate;
1481 break;
1482 case SEC_ASN1_OCTET_STRING:
1483 sub = kSecAsn1OctetStringTemplate;
1484 break;
1485 case SEC_ASN1_PRINTABLE_STRING:
1486 sub = kSecAsn1PrintableStringTemplate;
1487 break;
1488 case SEC_ASN1_T61_STRING:
1489 sub = kSecAsn1T61StringTemplate;
1490 break;
1491 case SEC_ASN1_UNIVERSAL_STRING:
1492 sub = kSecAsn1UniversalStringTemplate;
1493 break;
1494 case SEC_ASN1_UTC_TIME:
1495 sub = kSecAsn1UTCTimeTemplate;
1496 break;
1497 case SEC_ASN1_UTF8_STRING:
1498 sub = kSecAsn1UTF8StringTemplate;
1499 break;
1500 case SEC_ASN1_VISIBLE_STRING:
1501 sub = kSecAsn1VisibleStringTemplate;
1502 break;
1503 case SEC_ASN1_SKIP:
1504 sub = kSecAsn1SkipTemplate;
1505 break;
1506 default: /* redundant given outer switch cases, but */
1507 PORT_Assert(0); /* the compiler does not seem to know that, */
1508 sub = NULL; /* so just do enough to quiet it. */
1509 break;
1510 }
1511
1512 state->place = duringConstructedString;
1513 state = sec_asn1d_push_state (state->top, sub, item, PR_TRUE);
1514 if (state != NULL) {
1515 state->substring = PR_TRUE; /* XXX propogate? */
1516 state = sec_asn1d_init_state_based_on_template (state,
1517 buf /* __APPLE__ */, len /* __APPLE__ */);
1518 }
1519 } else if (state->indefinite) {
1520 /*
1521 * An indefinite-length string *must* be constructed!
1522 */
1523 dprintf("decodeError: prepare for contents indefinite not construncted\n");
1524 PORT_SetError (SEC_ERROR_BAD_DER);
1525 state->top->status = decodeError;
1526 } else {
1527 /*
1528 * A non-zero-length simple string.
1529 */
1530 if (state->underlying_kind == SEC_ASN1_BIT_STRING)
1531 state->place = beforeBitString;
1532 else
1533 state->place = duringLeaf;
1534 }
1535 (void) state;
1536 break;
1537
1538 default:
1539 /*
1540 * We are allocating for a simple leaf item.
1541 */
1542 if (state->contents_length) {
1543 if (state->dest != NULL) {
1544 item = (SecAsn1Item *)(state->dest);
1545 item->Length = 0;
1546 if (state->top->filter_only) {
1547 item->Data = NULL;
1548 } else {
1549 item->Data = (unsigned char*)
1550 sec_asn1d_zalloc (state->top->their_pool,
1551 state->contents_length);
1552 if (item->Data == NULL) {
1553 dprintf("decodeError: prepare for contents zalloc\n");
1554 state->top->status = decodeError;
1555 return;
1556 }
1557 }
1558 }
1559 state->place = duringLeaf;
1560 } else {
1561 /*
1562 * An indefinite-length or zero-length item is not allowed.
1563 * (All legal cases of such were handled above.)
1564 */
1565 dprintf("decodeError: prepare for contents indefinite zero len \n");
1566 PORT_SetError (SEC_ERROR_BAD_DER);
1567 state->top->status = decodeError;
1568 }
1569 }
1570 }
1571
1572
1573 static void
1574 sec_asn1d_free_child (sec_asn1d_state *state, PRBool error)
1575 {
1576 if (state->child != NULL) {
1577 PORT_Assert (error || state->child->consumed == 0);
1578 PORT_Assert (state->our_mark != NULL);
1579 PORT_ArenaRelease (state->top->our_pool, state->our_mark);
1580 if (error && state->top->their_pool == NULL) {
1581 /*
1582 * XXX We need to free anything allocated.
1583 * At this point, we failed in the middle of decoding. But we
1584 * can't free the data we previously allocated with PR_Malloc
1585 * unless we keep track of every pointer. So instead we have a
1586 * memory leak when decoding fails half-way, unless an arena is
1587 * used. See bug 95311 .
1588 */
1589 }
1590 state->child = NULL;
1591 state->our_mark = NULL;
1592 } else {
1593 /*
1594 * It is important that we do not leave a mark unreleased/unmarked.
1595 * But I do not think we should ever have one set in this case, only
1596 * if we had a child (handled above). So check for that. If this
1597 * assertion should ever get hit, then we probably need to add code
1598 * here to release back to our_mark (and then set our_mark to NULL).
1599 */
1600 PORT_Assert (state->our_mark == NULL);
1601 }
1602 state->place = beforeEndOfContents;
1603 }
1604
1605
1606 /* We have just saved an entire encoded ASN.1 object (type) for a SAVE
1607 ** template, and now in the next template, we are going to decode that
1608 ** saved data by calling SEC_ASN1DecoderUpdate recursively.
1609 ** If that recursive call fails with needBytes, it is a fatal error,
1610 ** because the encoded object should have been complete.
1611 ** If that recursive call fails with decodeError, it will have already
1612 ** cleaned up the state stack, so we must bail out quickly.
1613 **
1614 ** These checks of the status returned by the recursive call are now
1615 ** done in the caller of this function, immediately after it returns.
1616 */
1617 static void
1618 sec_asn1d_reuse_encoding (sec_asn1d_state *state)
1619 {
1620 sec_asn1d_state *child;
1621 unsigned long consumed;
1622 SecAsn1Item *item;
1623 void *dest;
1624
1625
1626 child = state->child;
1627 PORT_Assert (child != NULL);
1628
1629 consumed = child->consumed;
1630 child->consumed = 0;
1631
1632 item = (SecAsn1Item *)(state->dest);
1633 PORT_Assert (item != NULL);
1634
1635 PORT_Assert (item->Length == consumed);
1636
1637 /*
1638 * Free any grandchild.
1639 */
1640 sec_asn1d_free_child (child, PR_FALSE);
1641
1642 /*
1643 * Notify after the SAVE field.
1644 */
1645 sec_asn1d_notify_after (state->top, state->dest, state->depth);
1646
1647 /*
1648 * Adjust to get new dest and move forward.
1649 */
1650 dest = (char *)state->dest - state->theTemplate->offset;
1651 state->theTemplate++;
1652 child->dest = (char *)dest + state->theTemplate->offset;
1653 child->theTemplate = state->theTemplate;
1654
1655 /*
1656 * Notify before the "real" field.
1657 */
1658 PORT_Assert (state->depth == child->depth);
1659 sec_asn1d_notify_before (state->top, child->dest, child->depth);
1660
1661 /*
1662 * This will tell DecoderUpdate to return when it is done.
1663 */
1664 state->place = afterSaveEncoding;
1665
1666 /*
1667 * We already have a child; "push" it by making it current.
1668 */
1669 state->top->current = child;
1670
1671 /*
1672 * And initialize it so it is ready to parse.
1673 */
1674 (void) sec_asn1d_init_state_based_on_template(child,
1675 (char *) item->Data /* __APPLE__ */,
1676 item->Length /* __APPLE__ */);
1677
1678 /*
1679 * Now parse that out of our data.
1680 */
1681 if (SEC_ASN1DecoderUpdate (state->top,
1682 (char *) item->Data, item->Length) != SECSuccess)
1683 return;
1684 if (state->top->status == needBytes) {
1685 return;
1686 }
1687
1688 PORT_Assert (state->top->current == state);
1689 PORT_Assert (state->child == child);
1690
1691 /*
1692 * That should have consumed what we consumed before.
1693 */
1694 PORT_Assert (consumed == child->consumed);
1695 child->consumed = 0;
1696
1697 /*
1698 * Done.
1699 */
1700 state->consumed += consumed;
1701 child->place = notInUse;
1702 state->place = afterEndOfContents;
1703 }
1704
1705
1706 static unsigned long
1707 sec_asn1d_parse_leaf (sec_asn1d_state *state,
1708 const char *buf, unsigned long len)
1709 {
1710 SecAsn1Item *item;
1711 unsigned long bufLen;
1712
1713 if (len == 0) {
1714 state->top->status = needBytes;
1715 return 0;
1716 }
1717
1718 if (state->pending < len)
1719 len = state->pending;
1720
1721 bufLen = len;
1722
1723 item = (SecAsn1Item *)(state->dest);
1724 if (item != NULL && item->Data != NULL) {
1725 /* Strip leading zeroes when target is unsigned integer */
1726 if (state->underlying_kind == SEC_ASN1_INTEGER && /* INTEGER */
1727 item->Length == 0 && /* MSB */
1728 #ifdef __APPLE__
1729 !(state->underlying_kind & SEC_ASN1_SIGNED_INT))
1730 #else
1731 item->type == siUnsignedInteger) /* unsigned */
1732 #endif
1733 {
1734 while (len > 1 && buf[0] == 0) { /* leading 0 */
1735 buf++;
1736 len--;
1737 }
1738 }
1739 unsigned long offset = item->Length;
1740 if (state->underlying_kind == SEC_ASN1_BIT_STRING) {
1741 // The previous bit string must have no unused bits.
1742 if (item->Length & 0x7) {
1743 PORT_SetError (SEC_ERROR_BAD_DER);
1744 state->top->status = decodeError;
1745 return 0;
1746 }
1747 // If this is a bit string, the length is bits, not bytes.
1748 offset = item->Length >> 3;
1749 }
1750 if (state->underlying_kind == SEC_ASN1_BIT_STRING) {
1751 // Protect against overflow during the bytes-to-bits conversion.
1752 if (len >= (ULONG_MAX >> 3) + 1) {
1753 PORT_SetError (SEC_ERROR_BAD_DER);
1754 state->top->status = decodeError;
1755 return 0;
1756 }
1757 unsigned long len_in_bits = (len << 3) - state->bit_string_unused_bits;
1758 // Protect against overflow when computing the total length in bits.
1759 if (UINT_MAX - item->Length < len_in_bits) {
1760 PORT_SetError (SEC_ERROR_BAD_DER);
1761 state->top->status = decodeError;
1762 return 0;
1763 }
1764 item->Length += len_in_bits;
1765 } else {
1766 if (UINT_MAX - item->Length < len) {
1767 PORT_SetError (SEC_ERROR_BAD_DER);
1768 state->top->status = decodeError;
1769 return 0;
1770 }
1771 item->Length += len;
1772 }
1773 PORT_Memcpy (item->Data + offset, buf, len);
1774 }
1775 state->pending -= bufLen;
1776 if (state->pending == 0)
1777 state->place = beforeEndOfContents;
1778
1779 return bufLen;
1780 }
1781
1782
1783 static unsigned long
1784 sec_asn1d_parse_bit_string (sec_asn1d_state *state,
1785 const char *buf, unsigned long len)
1786 {
1787 unsigned char byte;
1788
1789 /*PORT_Assert (state->pending > 0); */
1790 PORT_Assert (state->place == beforeBitString);
1791
1792 if ((state->pending == 0) || (state->contents_length == 1)) {
1793 if (state->dest != NULL) {
1794 SecAsn1Item *item = (SecAsn1Item *)(state->dest);
1795 item->Data = NULL;
1796 item->Length = 0;
1797 state->place = beforeEndOfContents;
1798 }
1799 if(state->contents_length == 1) {
1800 /* skip over (unused) remainder byte */
1801 return 1;
1802 }
1803 else {
1804 return 0;
1805 }
1806 }
1807
1808 if (len == 0) {
1809 state->top->status = needBytes;
1810 return 0;
1811 }
1812
1813 byte = (unsigned char) *buf;
1814 if (byte > 7) {
1815 dprintf("decodeError: parse_bit_string remainder oflow\n");
1816 PORT_SetError (SEC_ERROR_BAD_DER);
1817 state->top->status = decodeError;
1818 return 0;
1819 }
1820
1821 state->bit_string_unused_bits = byte;
1822 state->place = duringBitString;
1823 state->pending -= 1;
1824
1825 return 1;
1826 }
1827
1828
1829 static unsigned long
1830 sec_asn1d_parse_more_bit_string (sec_asn1d_state *state,
1831 const char *buf, unsigned long len)
1832 {
1833 PORT_Assert (state->place == duringBitString);
1834 if (state->pending == 0) {
1835 /* An empty bit string with some unused bits is invalid. */
1836 if (state->bit_string_unused_bits) {
1837 PORT_SetError (SEC_ERROR_BAD_DER);
1838 state->top->status = decodeError;
1839 } else {
1840 /* An empty bit string with no unused bits is OK. */
1841 state->place = beforeEndOfContents;
1842 }
1843 return 0;
1844 }
1845
1846 len = sec_asn1d_parse_leaf (state, buf, len);
1847
1848 return len;
1849 }
1850
1851
1852 /*
1853 * XXX All callers should be looking at return value to detect
1854 * out-of-memory errors (and stop!).
1855 */
1856 static struct subitem *
1857 sec_asn1d_add_to_subitems (sec_asn1d_state *state,
1858 const void *data, unsigned long len,
1859 PRBool copy_data)
1860 {
1861 struct subitem *thing;
1862
1863 thing = (struct subitem*)sec_asn1d_zalloc (state->top->our_pool,
1864 sizeof (struct subitem));
1865 if (thing == NULL) {
1866 dprintf("decodeError: zalloc\n");
1867 state->top->status = decodeError;
1868 return NULL;
1869 }
1870
1871 if (copy_data) {
1872 void *copy;
1873 copy = sec_asn1d_alloc (state->top->our_pool, len);
1874 if (copy == NULL) {
1875 dprintf("decodeError: alloc\n");
1876 state->top->status = decodeError;
1877 if (!state->top->our_pool)
1878 PORT_Free(thing);
1879 return NULL;
1880 }
1881 PORT_Memcpy (copy, data, len);
1882 thing->data = copy;
1883 } else {
1884 thing->data = data;
1885 }
1886 thing->len = len;
1887 thing->next = NULL;
1888
1889 if (state->subitems_head == NULL) {
1890 PORT_Assert (state->subitems_tail == NULL);
1891 state->subitems_head = state->subitems_tail = thing;
1892 } else {
1893 state->subitems_tail->next = thing;
1894 state->subitems_tail = thing;
1895 }
1896
1897 return thing;
1898 }
1899
1900
1901 static void
1902 sec_asn1d_record_any_header (sec_asn1d_state *state,
1903 const char *buf,
1904 unsigned long len)
1905 {
1906 SecAsn1Item *item;
1907
1908 item = (SecAsn1Item *)(state->dest);
1909 if (item != NULL && item->Data != NULL) {
1910 PORT_Assert (state->substring);
1911 PORT_Memcpy (item->Data + item->Length, buf, len);
1912 item->Length += len;
1913 } else {
1914 sec_asn1d_add_to_subitems (state, buf, len, PR_TRUE);
1915 }
1916 }
1917
1918
1919 /*
1920 * We are moving along through the substrings of a constructed string,
1921 * and have just finished parsing one -- we need to save our child data
1922 * (if the child was not already writing directly into the destination)
1923 * and then move forward by one.
1924 *
1925 * We also have to detect when we are done:
1926 * - a definite-length encoding stops when our pending value hits 0
1927 * - an indefinite-length encoding stops when our child is empty
1928 * (which means it was the end-of-contents octets)
1929 */
1930 static void
1931 sec_asn1d_next_substring (sec_asn1d_state *state)
1932 {
1933 sec_asn1d_state *child;
1934 SecAsn1Item *item;
1935 unsigned long child_consumed;
1936 PRBool done;
1937
1938 PORT_Assert (state->place == duringConstructedString);
1939 PORT_Assert (state->child != NULL);
1940
1941 child = state->child;
1942
1943 child_consumed = child->consumed;
1944 child->consumed = 0;
1945 state->consumed += child_consumed;
1946
1947 done = PR_FALSE;
1948
1949 if (state->pending) {
1950 PORT_Assert (!state->indefinite);
1951 if( child_consumed > state->pending ) {
1952 dprintf("decodeError: next_substring consumed > pend\n");
1953 PORT_SetError (SEC_ERROR_BAD_DER);
1954 state->top->status = decodeError;
1955 return;
1956 }
1957
1958 state->pending -= child_consumed;
1959 if (state->pending == 0)
1960 done = PR_TRUE;
1961 } else {
1962 PORT_Assert (state->indefinite);
1963
1964 item = (SecAsn1Item *)(child->dest);
1965 /*
1966 * Iterate over ancestors to determine if any have definite length. If so,
1967 * space has already been allocated for the substrings and we don't need to
1968 * save them for concatenation.
1969 */
1970 PRBool copying_in_place = PR_FALSE;
1971 sec_asn1d_state *temp_state = state;
1972 while (temp_state && item == temp_state->dest && temp_state->indefinite) {
1973 sec_asn1d_state *parent = sec_asn1d_get_enclosing_construct(temp_state);
1974 if (!parent || parent->underlying_kind != temp_state->underlying_kind) {
1975 break;
1976 }
1977 if (!parent->indefinite) {
1978 copying_in_place = PR_TRUE;
1979 break;
1980 }
1981 temp_state = parent;
1982 }
1983 if (item != NULL && item->Data != NULL && !copying_in_place) {
1984 /*
1985 * Save the string away for later concatenation.
1986 */
1987 PORT_Assert (item->Data != NULL);
1988 sec_asn1d_add_to_subitems (state, item->Data, item->Length, PR_FALSE);
1989 /*
1990 * Clear the child item for the next round.
1991 */
1992 item->Data = NULL;
1993 item->Length = 0;
1994 }
1995
1996 /*
1997 * If our child was just our end-of-contents octets, we are done.
1998 */
1999 if (child->endofcontents)
2000 done = PR_TRUE;
2001 }
2002
2003 /*
2004 * Stop or do the next one.
2005 */
2006 if (done) {
2007 child->place = notInUse;
2008 state->place = afterConstructedString;
2009 } else {
2010 sec_asn1d_scrub_state (child);
2011 state->top->current = child;
2012 }
2013 }
2014
2015
2016 /*
2017 * We are doing a SET OF or SEQUENCE OF, and have just finished an item.
2018 */
2019 static void
2020 sec_asn1d_next_in_group (sec_asn1d_state *state,
2021 const char *buf, /* __APPLE__ */
2022 size_t len /* __APPLE__ */)
2023 {
2024 sec_asn1d_state *child;
2025 unsigned long child_consumed;
2026
2027 PORT_Assert (state->place == duringGroup);
2028 PORT_Assert (state->child != NULL);
2029
2030 child = state->child;
2031
2032 child_consumed = child->consumed;
2033 child->consumed = 0;
2034 state->consumed += child_consumed;
2035
2036 /*
2037 * If our child was just our end-of-contents octets, we are done.
2038 */
2039 #ifdef __APPLE__
2040 /*
2041 * Without the check for !child->indefinite, this path could
2042 * be taken erroneously if the child is indefinite!
2043 */
2044 if(child->endofcontents && !child->indefinite) {
2045 #else
2046 if (child->endofcontents) {
2047 #endif /* __APPLE__ */
2048 /* XXX I removed the PORT_Assert (child->dest == NULL) because there
2049 * was a bug in that a template that was a sequence of which also had
2050 * a child of a sequence of, in an indefinite group was not working
2051 * properly. This fix seems to work, (added the if statement below),
2052 * and nothing appears broken, but I am putting this note here just
2053 * in case. */
2054 /*
2055 * XXX No matter how many times I read that comment,
2056 * I cannot figure out what case he was fixing. I believe what he
2057 * did was deliberate, so I am loathe to touch it. I need to
2058 * understand how it could ever be that child->dest != NULL but
2059 * child->endofcontents is true, and why it is important to check
2060 * that state->subitems_head is NULL. This really needs to be
2061 * figured out, as I am not sure if the following code should be
2062 * compensating for "offset", as is done a little farther below
2063 * in the more normal case.
2064 */
2065 PORT_Assert (state->indefinite);
2066 PORT_Assert (state->pending == 0);
2067 if(child->dest && !state->subitems_head) {
2068 sec_asn1d_add_to_subitems (state, child->dest, 0, PR_FALSE);
2069 child->dest = NULL;
2070 }
2071
2072 child->place = notInUse;
2073 state->place = afterGroup;
2074 return;
2075 }
2076
2077 /*
2078 * Do the "after" field notification for next in group.
2079 */
2080 sec_asn1d_notify_after (state->top, child->dest, child->depth);
2081
2082 /*
2083 * Save it away (unless we are not storing).
2084 */
2085 if (child->dest != NULL) {
2086 void *dest;
2087
2088 dest = child->dest;
2089 dest = (char *)dest - child->theTemplate->offset;
2090 sec_asn1d_add_to_subitems (state, dest, 0, PR_FALSE);
2091 child->dest = NULL;
2092 }
2093
2094 /*
2095 * Account for those bytes; see if we are done.
2096 */
2097 if (state->pending) {
2098 PORT_Assert (!state->indefinite);
2099 if( child_consumed > state->pending ) {
2100 dprintf("decodeError: next_in_group consumed > pend\n");
2101 PORT_SetError (SEC_ERROR_BAD_DER);
2102 state->top->status = decodeError;
2103 return;
2104 }
2105
2106 state->pending -= child_consumed;
2107 if (state->pending == 0) {
2108 child->place = notInUse;
2109 state->place = afterGroup;
2110 return;
2111 }
2112 }
2113
2114 /*
2115 * Do the "before" field notification for next item in group.
2116 */
2117 sec_asn1d_notify_before (state->top, child->dest, child->depth);
2118
2119 /*
2120 * Now we do the next one.
2121 */
2122 sec_asn1d_scrub_state (child);
2123
2124 /* Initialize child state from the template */
2125 sec_asn1d_init_state_based_on_template(child, buf /* __APPLE__ */, len /* __APPLE__ */);
2126
2127 state->top->current = child;
2128 }
2129
2130
2131 /*
2132 * We are moving along through a sequence; move forward by one,
2133 * (detecting end-of-sequence when it happens).
2134 * XXX The handling of "missing" is ugly. Fix it.
2135 */
2136 static void
2137 sec_asn1d_next_in_sequence (sec_asn1d_state *state,
2138 const char *buf /* __APPLE__ */,
2139 size_t len /*__APPLE__*/)
2140 {
2141 sec_asn1d_state *child;
2142 unsigned long child_consumed;
2143 PRBool child_missing;
2144
2145 PORT_Assert (state->place == duringSequence);
2146 PORT_Assert (state->child != NULL);
2147
2148 child = state->child;
2149
2150 /*
2151 * Do the "after" field notification.
2152 */
2153 sec_asn1d_notify_after (state->top, child->dest, child->depth);
2154
2155 child_missing = (PRBool) child->missing;
2156 child_consumed = child->consumed;
2157 child->consumed = 0;
2158
2159 /*
2160 * Take care of accounting.
2161 */
2162 if (child_missing) {
2163 PORT_Assert (child->optional);
2164 } else {
2165 state->consumed += child_consumed;
2166 /*
2167 * Free any grandchild.
2168 */
2169 sec_asn1d_free_child (child, PR_FALSE);
2170 if (state->pending) {
2171 PORT_Assert (!state->indefinite);
2172 if( child_consumed > state->pending ) {
2173 dprintf("decodeError: next_in_seq consumed > pend\n");
2174 PORT_SetError (SEC_ERROR_BAD_DER);
2175 state->top->status = decodeError;
2176 return;
2177 }
2178 state->pending -= child_consumed;
2179 if (state->pending == 0) {
2180 child->theTemplate++;
2181 while (child->theTemplate->kind != 0) {
2182 if ((child->theTemplate->kind & SEC_ASN1_OPTIONAL) == 0) {
2183 dprintf("decodeError: next_in_seq child not opt\n");
2184 PORT_SetError (SEC_ERROR_BAD_DER);
2185 state->top->status = decodeError;
2186 return;
2187 }
2188 child->theTemplate++;
2189 }
2190 child->place = notInUse;
2191 state->place = afterEndOfContents;
2192 return;
2193 }
2194 }
2195 }
2196
2197 /*
2198 * Move forward.
2199 */
2200 child->theTemplate++;
2201 if (child->theTemplate->kind == 0) {
2202 /*
2203 * We are done with this sequence.
2204 */
2205 child->place = notInUse;
2206 if (state->pending) {
2207 dprintf("decodeError: next_in_seq notInUse still pending\n");
2208 PORT_SetError (SEC_ERROR_BAD_DER);
2209 state->top->status = decodeError;
2210 } else if (child_missing) {
2211 /*
2212 * We got to the end, but have a child that started parsing
2213 * and ended up "missing". The only legitimate reason for
2214 * this is that we had one or more optional fields at the
2215 * end of our sequence, and we were encoded indefinite-length,
2216 * so when we went looking for those optional fields we
2217 * found our end-of-contents octets instead.
2218 * (Yes, this is ugly; dunno a better way to handle it.)
2219 * So, first confirm the situation, and then mark that we
2220 * are done.
2221 */
2222 if (state->indefinite && child->endofcontents) {
2223 PORT_Assert (child_consumed == 2);
2224 if( child_consumed != 2 ) {
2225 dprintf("decodeError: next_in_seq indef len != 2\n");
2226 PORT_SetError (SEC_ERROR_BAD_DER);
2227 state->top->status = decodeError;
2228 } else {
2229 state->consumed += child_consumed;
2230 state->place = afterEndOfContents;
2231 }
2232 } else {
2233 dprintf("decodeError: next_in_seq !indef, child missing\n");
2234 PORT_SetError (SEC_ERROR_BAD_DER);
2235 state->top->status = decodeError;
2236 }
2237 } else {
2238 /*
2239 * We have to finish out, maybe reading end-of-contents octets;
2240 * let the normal logic do the right thing.
2241 */
2242 state->place = beforeEndOfContents;
2243 }
2244 } else {
2245 unsigned char child_found_tag_modifiers = 0;
2246 unsigned long child_found_tag_number = 0;
2247
2248 /*
2249 * Reset state and push.
2250 */
2251 if (state->dest != NULL)
2252 child->dest = (char *)state->dest + child->theTemplate->offset;
2253
2254 /*
2255 * Do the "before" field notification.
2256 */
2257 sec_asn1d_notify_before (state->top, child->dest, child->depth);
2258
2259 if (child_missing) { /* if previous child was missing, copy the tag data we already have */
2260 child_found_tag_modifiers = child->found_tag_modifiers;
2261 child_found_tag_number = child->found_tag_number;
2262 }
2263 state->top->current = child;
2264 child = sec_asn1d_init_state_based_on_template (child,
2265 buf /* __APPLE__ */,
2266 len /* __APPLE__ */);
2267 if (child_missing && child) {
2268 child->place = afterIdentifier;
2269 child->found_tag_modifiers = child_found_tag_modifiers;
2270 child->found_tag_number = child_found_tag_number;
2271 child->consumed = child_consumed;
2272 if (child->underlying_kind == SEC_ASN1_ANY
2273 && !child->top->filter_only) {
2274 /*
2275 * If the new field is an ANY, and we are storing, then
2276 * we need to save the tag out. We would have done this
2277 * already in the normal case, but since we were looking
2278 * for an optional field, and we did not find it, we only
2279 * now realize we need to save the tag.
2280 */
2281 unsigned char identifier;
2282
2283 /*
2284 * Check that we did not end up with a high tag; for that
2285 * we need to re-encode the tag into multiple bytes in order
2286 * to store it back to look like what we parsed originally.
2287 * In practice this does not happen, but for completeness
2288 * sake it should probably be made to work at some point.
2289 */
2290 PORT_Assert (child_found_tag_number < SEC_ASN1_HIGH_TAG_NUMBER);
2291 identifier = (unsigned char)(child_found_tag_modifiers | child_found_tag_number);
2292 sec_asn1d_record_any_header (child, (char *) &identifier, 1);
2293 }
2294 }
2295 }
2296 }
2297
2298
2299 static void
2300 sec_asn1d_concat_substrings (sec_asn1d_state *state)
2301 {
2302 PORT_Assert (state->place == afterConstructedString);
2303
2304 if (state->subitems_head != NULL) {
2305 struct subitem *substring;
2306 unsigned long alloc_len, item_len;
2307 unsigned char *where;
2308 SecAsn1Item *item;
2309 PRBool is_bit_string;
2310
2311 item_len = 0;
2312 is_bit_string = (state->underlying_kind == SEC_ASN1_BIT_STRING)
2313 ? PR_TRUE : PR_FALSE;
2314
2315 substring = state->subitems_head;
2316 while (substring != NULL) {
2317 /*
2318 * All bit-string substrings except the last one should be
2319 * a clean multiple of 8 bits.
2320 */
2321 if (is_bit_string && (substring->next != NULL)
2322 && (substring->len & 0x7)) {
2323 dprintf("decodeError: sec_asn1d_concat_substrings align\n");
2324 PORT_SetError (SEC_ERROR_BAD_DER);
2325 state->top->status = decodeError;
2326 return;
2327 }
2328 item_len += substring->len;
2329 substring = substring->next;
2330 }
2331
2332 if (is_bit_string) {
2333 #ifdef XP_WIN16 /* win16 compiler gets an internal error otherwise */
2334 alloc_len = (((long)item_len + 7) / 8);
2335 #else
2336 alloc_len = ((item_len + 7) >> 3);
2337 #endif
2338 } else {
2339 /*
2340 * Add 2 for the end-of-contents octets of an indefinite-length
2341 * ANY that is *not* also an INNER. Because we zero-allocate
2342 * below, all we need to do is increase the length here.
2343 */
2344 if (state->underlying_kind == SEC_ASN1_ANY && state->indefinite)
2345 item_len += 2;
2346 alloc_len = item_len;
2347 }
2348
2349 item = (SecAsn1Item *)(state->dest);
2350 PORT_Assert (item != NULL);
2351 PORT_Assert (item->Data == NULL);
2352 item->Data = (unsigned char*)sec_asn1d_zalloc (state->top->their_pool,
2353 alloc_len);
2354 if (item->Data == NULL) {
2355 dprintf("decodeError: zalloc\n");
2356 state->top->status = decodeError;
2357 return;
2358 }
2359 item->Length = item_len;
2360
2361 where = item->Data;
2362 substring = state->subitems_head;
2363 while (substring != NULL) {
2364 if (is_bit_string)
2365 item_len = (substring->len + 7) >> 3;
2366 else
2367 item_len = substring->len;
2368 PORT_Memcpy (where, substring->data, item_len);
2369 where += item_len;
2370 substring = substring->next;
2371 }
2372
2373 /*
2374 * Because we use arenas and have a mark set, we later free
2375 * everything we have allocated, so this does *not* present
2376 * a memory leak (it is just temporarily left dangling).
2377 */
2378 state->subitems_head = state->subitems_tail = NULL;
2379 }
2380
2381 state->place = afterEndOfContents;
2382 }
2383
2384
2385 static void
2386 sec_asn1d_concat_group (sec_asn1d_state *state)
2387 {
2388 const void ***placep;
2389
2390 PORT_Assert (state->place == afterGroup);
2391
2392 placep = (const void***)state->dest;
2393 PORT_Assert(state->subitems_head == NULL || placep != NULL);
2394 if (placep != NULL) {
2395 struct subitem *item;
2396 const void **group;
2397 int count;
2398
2399 count = 0;
2400 item = state->subitems_head;
2401 while (item != NULL) {
2402 PORT_Assert (item->next != NULL || item == state->subitems_tail);
2403 count++;
2404 item = item->next;
2405 }
2406
2407 group = (const void**)sec_asn1d_zalloc (state->top->their_pool,
2408 (count + 1) * (sizeof(void *)));
2409 if (group == NULL) {
2410 dprintf("decodeError: zalloc\n");
2411 state->top->status = decodeError;
2412 return;
2413 }
2414
2415 *placep = group;
2416
2417 item = state->subitems_head;
2418 while (item != NULL) {
2419 *group++ = item->data;
2420 item = item->next;
2421 }
2422 *group = NULL;
2423
2424 /*
2425 * Because we use arenas and have a mark set, we later free
2426 * everything we have allocated, so this does *not* present
2427 * a memory leak (it is just temporarily left dangling).
2428 */
2429 state->subitems_head = state->subitems_tail = NULL;
2430 }
2431
2432 state->place = afterEndOfContents;
2433 }
2434
2435 /*
2436 * For those states that push a child to handle a subtemplate,
2437 * "absorb" that child (transfer necessary information).
2438 */
2439 static void
2440 sec_asn1d_absorb_child (sec_asn1d_state *state)
2441 {
2442 /*
2443 * There is absolutely supposed to be a child there.
2444 */
2445 PORT_Assert (state->child != NULL);
2446
2447 /*
2448 * Inherit the missing status of our child, and do the ugly
2449 * backing-up if necessary.
2450 */
2451 state->missing = state->child->missing;
2452 if (state->missing) {
2453 state->found_tag_number = state->child->found_tag_number;
2454 state->found_tag_modifiers = state->child->found_tag_modifiers;
2455 state->endofcontents = state->child->endofcontents;
2456 }
2457
2458 /*
2459 * Add in number of bytes consumed by child.
2460 * (Only EXPLICIT should have already consumed bytes itself.)
2461 */
2462 PORT_Assert (state->place == afterExplicit || state->consumed == 0);
2463 state->consumed += state->child->consumed;
2464
2465 /*
2466 * Subtract from bytes pending; this only applies to a definite-length
2467 * EXPLICIT field.
2468 */
2469 if (state->pending) {
2470 PORT_Assert (!state->indefinite);
2471 PORT_Assert (state->place == afterExplicit);
2472
2473 /*
2474 * If we had a definite-length explicit, then what the child
2475 * consumed should be what was left pending.
2476 */
2477 if (state->pending != state->child->consumed) {
2478 if (state->pending < state->child->consumed) {
2479 dprintf("decodeError: absorb_child pending < consumed\n");
2480 PORT_SetError (SEC_ERROR_BAD_DER);
2481 state->top->status = decodeError;
2482 return;
2483 }
2484 /*
2485 * Okay, this is a hack. It *should* be an error whether
2486 * pending is too big or too small, but it turns out that
2487 * we had a bug in our *old* DER encoder that ended up
2488 * counting an explicit header twice in the case where
2489 * the underlying type was an ANY. So, because we cannot
2490 * prevent receiving these (our own certificate server can
2491 * send them to us), we need to be lenient and accept them.
2492 * To do so, we need to pretend as if we read all of the
2493 * bytes that the header said we would find, even though
2494 * we actually came up short.
2495 */
2496 state->consumed += (state->pending - state->child->consumed);
2497 }
2498 state->pending = 0;
2499 }
2500
2501 /*
2502 * Indicate that we are done with child.
2503 */
2504 state->child->consumed = 0;
2505
2506 /*
2507 * And move on to final state.
2508 * (Technically everybody could move to afterEndOfContents except
2509 * for an indefinite-length EXPLICIT; for simplicity though we assert
2510 * that but let the end-of-contents code do the real determination.)
2511 */
2512 PORT_Assert (state->place == afterExplicit || (! state->indefinite));
2513 state->place = beforeEndOfContents;
2514 }
2515
2516
2517 static void
2518 sec_asn1d_prepare_for_end_of_contents (sec_asn1d_state *state)
2519 {
2520 PORT_Assert (state->place == beforeEndOfContents);
2521
2522 if (state->indefinite) {
2523 state->place = duringEndOfContents;
2524 state->pending = 2;
2525 } else {
2526 state->place = afterEndOfContents;
2527 }
2528 }
2529
2530
2531 static unsigned long
2532 sec_asn1d_parse_end_of_contents (sec_asn1d_state *state,
2533 const char *buf, unsigned long len)
2534 {
2535 unsigned int i;
2536
2537 PORT_Assert (state->pending <= 2);
2538 PORT_Assert (state->place == duringEndOfContents);
2539
2540 if (len == 0) {
2541 state->top->status = needBytes;
2542 return 0;
2543 }
2544
2545 if (state->pending < len)
2546 len = state->pending;
2547
2548 for (i = 0; i < len; i++) {
2549 if (buf[i] != 0) {
2550 /*
2551 * We expect to find only zeros; if not, just give up.
2552 */
2553 dprintf("decodeError: end of contents non zero\n");
2554 PORT_SetError (SEC_ERROR_BAD_DER);
2555 state->top->status = decodeError;
2556 return 0;
2557 }
2558 }
2559
2560 state->pending -= len;
2561
2562 if (state->pending == 0) {
2563 state->place = afterEndOfContents;
2564 state->endofcontents = PR_TRUE;
2565 }
2566
2567 return len;
2568 }
2569
2570
2571 static void
2572 sec_asn1d_pop_state (sec_asn1d_state *state)
2573 {
2574 #if 0 /* XXX I think this should always be handled explicitly by parent? */
2575 /*
2576 * Account for our child.
2577 */
2578 if (state->child != NULL) {
2579 state->consumed += state->child->consumed;
2580 if (state->pending) {
2581 PORT_Assert (!state->indefinite);
2582 if( state->child->consumed > state->pending ) {
2583 dprintf("decodeError: pop_state pending < consumed\n");
2584 PORT_SetError (SEC_ERROR_BAD_DER);
2585 state->top->status = decodeError;
2586 } else {
2587 state->pending -= state->child->consumed;
2588 }
2589 }
2590 state->child->consumed = 0;
2591 }
2592 #endif /* XXX */
2593
2594 /*
2595 * Free our child.
2596 */
2597 sec_asn1d_free_child (state, PR_FALSE);
2598
2599 /*
2600 * Just make my parent be the current state. It will then clean
2601 * up after me and free me (or reuse me).
2602 */
2603 state->top->current = state->parent;
2604 }
2605
2606 static sec_asn1d_state *
2607 sec_asn1d_before_choice (sec_asn1d_state *state,
2608 const char *buf /* __APPLE__ */,
2609 size_t len /* __APPLE__ */)
2610 {
2611 sec_asn1d_state *child;
2612
2613 if( state->allocate ) {
2614 void *dest;
2615
2616 dest = sec_asn1d_zalloc(state->top->their_pool,
2617 state->theTemplate->size);
2618 if( (void *)NULL == dest ) {
2619 dprintf("decodeError: zalloc\n");
2620 state->top->status = decodeError;
2621 return (sec_asn1d_state *)NULL;
2622 }
2623
2624 state->dest = (char *)dest + state->theTemplate->offset;
2625 }
2626
2627 child = sec_asn1d_push_state(state->top, state->theTemplate + 1,
2628 (char *)state->dest - state->theTemplate->offset,
2629 PR_FALSE);
2630 if( (sec_asn1d_state *)NULL == child ) {
2631 return (sec_asn1d_state *)NULL;
2632 }
2633
2634 sec_asn1d_scrub_state(child);
2635 child = sec_asn1d_init_state_based_on_template(child,
2636 buf /* __APPLE__ */, len /* __APPLE__ */);
2637 if( (sec_asn1d_state *)NULL == child ) {
2638 return (sec_asn1d_state *)NULL;
2639 }
2640
2641 child->optional = PR_TRUE;
2642
2643 state->place = duringChoice;
2644
2645 return child;
2646 }
2647
2648 static sec_asn1d_state *
2649 sec_asn1d_during_choice (sec_asn1d_state *state,
2650 const char *buf, /* __APPLE__ */
2651 size_t len /* __APPLE__ */)
2652 {
2653 sec_asn1d_state *child = state->child;
2654
2655 PORT_Assert((sec_asn1d_state *)NULL != child);
2656
2657 if( child->missing ) {
2658 unsigned char child_found_tag_modifiers = 0;
2659 unsigned long child_found_tag_number = 0;
2660 void * dest;
2661
2662 state->consumed += child->consumed;
2663
2664 if (child->endofcontents) {
2665 /* This choice is probably the first item in a GROUP
2666 ** (e.g. SET_OF) that was indefinite-length encoded.
2667 ** We're actually at the end of that GROUP.
2668 ** We look up the stack to be sure that we find
2669 ** a state with indefinite length encoding before we
2670 ** find a state (like a SEQUENCE) that is definite.
2671 */
2672 child->place = notInUse;
2673 state->place = afterChoice;
2674 state->endofcontents = PR_TRUE; /* propagate this up */
2675 if (sec_asn1d_parent_allows_EOC(state))
2676 return state;
2677 dprintf("decodeError: during_choice child at EOC by parent does not allow EOC\n");
2678 PORT_SetError(SEC_ERROR_BAD_DER);
2679 state->top->status = decodeError;
2680 return NULL;
2681 }
2682
2683 dest = (char *)child->dest - child->theTemplate->offset;
2684 child->theTemplate++;
2685
2686 if( 0 == child->theTemplate->kind ) {
2687 /* Ran out of choices */
2688 dprintf("decodeError: during_choice ran out of choice\n");
2689 PORT_SetError(SEC_ERROR_BAD_DER);
2690 state->top->status = decodeError;
2691 return (sec_asn1d_state *)NULL;
2692 }
2693 child->dest = (char *)dest + child->theTemplate->offset;
2694
2695 /* cargo'd from next_in_sequence innards */
2696 if( state->pending ) {
2697 PORT_Assert(!state->indefinite);
2698 if( child->consumed > state->pending ) {
2699 dprintf("decodeError: during_choice consumed > pending\n");
2700 PORT_SetError (SEC_ERROR_BAD_DER);
2701 state->top->status = decodeError;
2702 return NULL;
2703 }
2704 state->pending -= child->consumed;
2705 if( 0 == state->pending ) {
2706 /* XXX uh.. not sure if I should have stopped this
2707 * from happening before. */
2708 PORT_Assert(0);
2709 PORT_SetError(SEC_ERROR_BAD_DER);
2710 dprintf("decodeError: during_choice !pending\n");
2711 state->top->status = decodeError;
2712 return (sec_asn1d_state *)NULL;
2713 }
2714 }
2715
2716 child->consumed = 0;
2717 sec_asn1d_scrub_state(child);
2718
2719 /* move it on top again */
2720 state->top->current = child;
2721
2722 child_found_tag_modifiers = child->found_tag_modifiers;
2723 child_found_tag_number = child->found_tag_number;
2724
2725 child = sec_asn1d_init_state_based_on_template(child, buf /* __APPLE__*/, len /* __APPLE__ */);
2726 if( (sec_asn1d_state *)NULL == child ) {
2727 return (sec_asn1d_state *)NULL;
2728 }
2729
2730 /* copy our findings to the new top */
2731 child->found_tag_modifiers = child_found_tag_modifiers;
2732 child->found_tag_number = child_found_tag_number;
2733
2734 child->optional = PR_TRUE;
2735 child->place = afterIdentifier;
2736
2737 return child;
2738 }
2739 if( (void *)NULL != state->dest ) {
2740 /* Store the enum */
2741 int *which = (int *)state->dest;
2742 *which = (int)child->theTemplate->size;
2743 }
2744
2745 child->place = notInUse;
2746
2747 state->place = afterChoice;
2748 return state;
2749 }
2750
2751 static void
2752 sec_asn1d_after_choice (sec_asn1d_state *state)
2753 {
2754 state->consumed += state->child->consumed;
2755 state->child->consumed = 0;
2756 state->place = afterEndOfContents;
2757 sec_asn1d_pop_state(state);
2758 }
2759
2760 #if 0
2761 unsigned long
2762 sec_asn1d_uinteger(SecAsn1Item *src)
2763 {
2764 unsigned long value;
2765 int len;
2766
2767 if (src->Length > 5 || (src->Length > 4 && src->Data[0] == 0))
2768 return 0;
2769
2770 value = 0;
2771 len = src->Length;
2772 while (len) {
2773 value <<= 8;
2774 value |= src->Data[--len];
2775 }
2776 return value;
2777 }
2778 #endif
2779
2780 SECStatus
2781 SEC_ASN1DecodeInteger(SecAsn1Item *src, unsigned long *value)
2782 {
2783 unsigned long v;
2784 unsigned int i;
2785
2786 if (src == NULL) {
2787 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2788 return SECFailure;
2789 }
2790
2791 if (src->Length > sizeof(unsigned long)) {
2792 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2793 return SECFailure;
2794 }
2795
2796 if (src->Data == NULL) {
2797 PORT_SetError(SEC_ERROR_INVALID_ARGS);
2798 return SECFailure;
2799 }
2800
2801 if (src->Data[0] & 0x80)
2802 v = -1; /* signed and negative - start with all 1's */
2803 else
2804 v = 0;
2805
2806 for (i= 0; i < src->Length; i++) {
2807 /* shift in next byte */
2808 v <<= 8;
2809 v |= src->Data[i];
2810 }
2811 *value = v;
2812 return SECSuccess;
2813 }
2814
2815 #ifdef DEBUG_ASN1D_STATES
2816 static void
2817 dump_states(SEC_ASN1DecoderContext *cx)
2818 {
2819 sec_asn1d_state *state;
2820 char kindBuf[256];
2821
2822 for (state = cx->current; state->parent; state = state->parent) {
2823 ;
2824 }
2825
2826 for (; state; state = state->child) {
2827 int i;
2828 for (i = 0; i < state->depth; i++) {
2829 printf(" ");
2830 }
2831
2832 i = formatKind(state->theTemplate->kind, kindBuf);
2833 printf("%s: tmpl %p, kind%s",
2834 (state == cx->current) ? "STATE" : "State",
2835 state->theTemplate,
2836 kindBuf);
2837 printf(" %s", (state->place <= notInUse)
2838 ? place_names[ state->place ]
2839 : "(undefined)");
2840 if (!i)
2841 printf(", expect 0x%02lx",
2842 state->expect_tag_number | state->expect_tag_modifiers);
2843
2844 printf("%s%s%s %lu\n",
2845 state->indefinite ? ", indef" : "",
2846 state->missing ? ", miss" : "",
2847 state->endofcontents ? ", EOC" : "",
2848 state->pending
2849 );
2850 }
2851
2852 return;
2853 }
2854 #endif /* DEBUG_ASN1D_STATES */
2855
2856 SECStatus
2857 SEC_ASN1DecoderUpdate (SEC_ASN1DecoderContext *cx,
2858 const char *buf, size_t len)
2859 {
2860 sec_asn1d_state *state = NULL;
2861 unsigned long consumed;
2862 SEC_ASN1EncodingPart what;
2863 sec_asn1d_state *stateEnd = cx->current;
2864
2865 if (cx->status == needBytes)
2866 cx->status = keepGoing;
2867
2868 while (cx->status == keepGoing) {
2869 state = cx->current;
2870 what = SEC_ASN1_Contents;
2871 consumed = 0;
2872 #if DEBUG_ASN1D_STATES
2873 if (doDumpStates > 1) {
2874 printf("\nPLACE = %s, next byte = 0x%02x, %p[%lu]\n",
2875 (state->place <= notInUse) ?
2876 place_names[ state->place ] : "(undefined)",
2877 (unsigned int)((unsigned char *)buf)[ consumed ],
2878 buf, consumed);
2879 dump_states(cx);
2880 }
2881 #endif /* DEBUG_ASN1D_STATES */
2882 switch (state->place) {
2883 case beforeIdentifier:
2884 consumed = sec_asn1d_parse_identifier (state, buf, len);
2885 what = SEC_ASN1_Identifier;
2886 break;
2887 case duringIdentifier:
2888 consumed = sec_asn1d_parse_more_identifier (state, buf, len);
2889 what = SEC_ASN1_Identifier;
2890 break;
2891 case afterIdentifier:
2892 sec_asn1d_confirm_identifier (state);
2893 break;
2894 case beforeLength:
2895 consumed = sec_asn1d_parse_length (state, buf, len);
2896 what = SEC_ASN1_Length;
2897 break;
2898 case duringLength:
2899 consumed = sec_asn1d_parse_more_length (state, buf, len);
2900 what = SEC_ASN1_Length;
2901 break;
2902 case afterLength:
2903 sec_asn1d_prepare_for_contents (state, buf, len);
2904 break;
2905 case beforeBitString:
2906 consumed = sec_asn1d_parse_bit_string (state, buf, len);
2907 break;
2908 case duringBitString:
2909 consumed = sec_asn1d_parse_more_bit_string (state, buf, len);
2910 break;
2911 case duringConstructedString:
2912 sec_asn1d_next_substring (state);
2913 break;
2914 case duringGroup:
2915 sec_asn1d_next_in_group (state, buf, len);
2916 break;
2917 case duringLeaf:
2918 consumed = sec_asn1d_parse_leaf (state, buf, len);
2919 break;
2920 case duringSaveEncoding:
2921 sec_asn1d_reuse_encoding (state);
2922 if (cx->status == decodeError) {
2923 /* recursive call has already popped all states from stack.
2924 ** Bail out quickly.
2925 */
2926 return SECFailure;
2927 }
2928 if (cx->status == needBytes) {
2929 /* recursive call wanted more data. Fatal. Clean up below. */
2930 PORT_SetError (SEC_ERROR_BAD_DER);
2931 cx->status = decodeError;
2932 }
2933 break;
2934 case duringSequence:
2935 sec_asn1d_next_in_sequence (state, buf, len);
2936 break;
2937 case afterConstructedString:
2938 sec_asn1d_concat_substrings (state);
2939 break;
2940 case afterExplicit:
2941 case afterImplicit:
2942 case afterInline:
2943 case afterPointer:
2944 sec_asn1d_absorb_child (state);
2945 break;
2946 case afterGroup:
2947 sec_asn1d_concat_group (state);
2948 break;
2949 case afterSaveEncoding:
2950 /* SEC_ASN1DecoderUpdate has called itself recursively to
2951 ** decode SAVEd encoded data, and now is done decoding that.
2952 ** Return to the calling copy of SEC_ASN1DecoderUpdate.
2953 */
2954 return SECSuccess;
2955 case beforeEndOfContents:
2956 sec_asn1d_prepare_for_end_of_contents (state);
2957 break;
2958 case duringEndOfContents:
2959 consumed = sec_asn1d_parse_end_of_contents (state, buf, len);
2960 what = SEC_ASN1_EndOfContents;
2961 break;
2962 case afterEndOfContents:
2963 sec_asn1d_pop_state (state);
2964 break;
2965 case beforeChoice:
2966 state = sec_asn1d_before_choice(state, buf, len);
2967 break;
2968 case duringChoice:
2969 state = sec_asn1d_during_choice(state, buf, len);
2970 break;
2971 case afterChoice:
2972 sec_asn1d_after_choice(state);
2973 break;
2974 case notInUse:
2975 default:
2976 /* This is not an error, but rather a plain old BUG! */
2977 PORT_Assert (0);
2978 PORT_SetError (SEC_ERROR_BAD_DER);
2979 dprintf("decodeError: decoder update bad state->place\n");
2980 cx->status = decodeError;
2981 break;
2982 }
2983
2984 if (cx->status == decodeError)
2985 break;
2986
2987 /* We should not consume more than we have. */
2988 PORT_Assert (consumed <= len);
2989 if( consumed > len ) {
2990 dprintf("decodeError: decoder update consumed > len\n");
2991 PORT_SetError (SEC_ERROR_BAD_DER);
2992 cx->status = decodeError;
2993 break;
2994 }
2995
2996 /* It might have changed, so we have to update our local copy. */
2997 state = cx->current;
2998
2999 /* If it is NULL, we have popped all the way to the top. */
3000 if (state == NULL) {
3001 PORT_Assert (consumed == 0);
3002 #if 0
3003 /* XXX I want this here, but it seems that we have situations (like
3004 * downloading a pkcs7 cert chain from some issuers) that give us a
3005 * length which is greater than the entire encoding. So, we cannot
3006 * have this be an error.
3007 */
3008 if (len > 0) {
3009 dprintf("decodeError: decoder update nonzero len\n");
3010 PORT_SetError (SEC_ERROR_BAD_DER);
3011 cx->status = decodeError;
3012 }
3013 else
3014 #endif
3015 cx->status = allDone;
3016 break;
3017 }
3018 else if (state->theTemplate->kind == SEC_ASN1_SKIP_REST) {
3019 cx->status = allDone;
3020 break;
3021 }
3022
3023 if (consumed == 0)
3024 continue;
3025
3026 /*
3027 * The following check is specifically looking for an ANY
3028 * that is *not* also an INNER, because we need to save aside
3029 * all bytes in that case -- the contents parts will get
3030 * handled like all other contents, and the end-of-contents
3031 * bytes are added by the concat code, but the outer header
3032 * bytes need to get saved too, so we do them explicitly here.
3033 */
3034 if (state->underlying_kind == SEC_ASN1_ANY
3035 && !cx->filter_only && (what == SEC_ASN1_Identifier
3036 || what == SEC_ASN1_Length)) {
3037 sec_asn1d_record_any_header (state, buf, consumed);
3038 }
3039
3040 /*
3041 * We had some number of good, accepted bytes. If the caller
3042 * has registered to see them, pass them along.
3043 */
3044 if (state->top->filter_proc != NULL) {
3045 int depth;
3046
3047 depth = state->depth;
3048 if (what == SEC_ASN1_EndOfContents && !state->indefinite) {
3049 PORT_Assert (state->parent != NULL
3050 && state->parent->indefinite);
3051 depth--;
3052 PORT_Assert (depth == state->parent->depth);
3053 }
3054 (* state->top->filter_proc) (state->top->filter_arg,
3055 buf, consumed, depth, what);
3056 }
3057
3058 state->consumed += consumed;
3059 buf += consumed;
3060 len -= consumed;
3061 } /* main decode loop */
3062
3063 if (cx->status == decodeError) {
3064 while (state != NULL && stateEnd->parent!=state) {
3065 sec_asn1d_free_child (state, PR_TRUE);
3066 state = state->parent;
3067 }
3068 #ifdef SEC_ASN1D_FREE_ON_ERROR /*
3069 * XXX This does not work because we can
3070 * end up leaving behind dangling pointers
3071 * to stuff that was allocated. In order
3072 * to make this really work (which would
3073 * be a good thing, I think), we need to
3074 * keep track of every place/pointer that
3075 * was allocated and make sure to NULL it
3076 * out before we then free back to the mark.
3077 */
3078 if (cx->their_pool != NULL) {
3079 PORT_Assert (cx->their_mark != NULL);
3080 PORT_ArenaRelease (cx->their_pool, cx->their_mark);
3081 }
3082 #endif
3083 return SECFailure;
3084 }
3085
3086 #if 0
3087 /* XXX This is what I want, but cannot have because it seems we
3088 * have situations (like when downloading a pkcs7 cert chain from
3089 * some issuers) that give us a total length which is greater than
3090 * the entire encoding. So, we have to allow allDone to have a
3091 * remaining length greater than zero. I wanted to catch internal
3092 * bugs with this, noticing when we do not have the right length.
3093 * Oh well.
3094 */
3095 PORT_Assert (len == 0
3096 && (cx->status == needBytes || cx->status == allDone));
3097 #else
3098 PORT_Assert ((len == 0 && cx->status == needBytes)
3099 || cx->status == allDone);
3100 #endif
3101 return SECSuccess;
3102 }
3103
3104
3105 SECStatus
3106 SEC_ASN1DecoderFinish (SEC_ASN1DecoderContext *cx)
3107 {
3108 SECStatus rv;
3109
3110 if (cx->status == needBytes) {
3111 #ifdef __APPLE__
3112 /*
3113 * Special case: need more bytes, but this field and all
3114 * subsequent fields are optional. I'm surprised this case is
3115 * not handled in the original NSS code, and this workaround
3116 * is a bit of a hack...
3117 */
3118 sec_asn1d_state *state = cx->current;
3119 assert(state != NULL);
3120 if(state->place == beforeIdentifier) {
3121 int allOptional = 1;
3122 const SecAsn1Template *templ = state->theTemplate;
3123 while(templ->kind != 0) {
3124 if(!(templ->kind & SEC_ASN1_OPTIONAL)) {
3125 allOptional = 0;
3126 break;
3127 }
3128 templ++;
3129 }
3130 if(allOptional) {
3131 /* letting this one slide */
3132 rv = SECSuccess;
3133 }
3134 else {
3135 PORT_SetError (SEC_ERROR_BAD_DER);
3136 rv = SECFailure;
3137 }
3138 }
3139 else {
3140 PORT_SetError (SEC_ERROR_BAD_DER);
3141 rv = SECFailure;
3142 }
3143 #else
3144 PORT_SetError (SEC_ERROR_BAD_DER);
3145 rv = SECFailure;
3146 #endif /* __APPLE__ */
3147 } else {
3148 rv = SECSuccess;
3149 }
3150
3151 /*
3152 * XXX anything else that needs to be finished?
3153 */
3154
3155 PORT_FreeArena (cx->our_pool, PR_FALSE);
3156
3157 return rv;
3158 }
3159
3160
3161 SEC_ASN1DecoderContext *
3162 SEC_ASN1DecoderStart (PRArenaPool *their_pool, void *dest,
3163 const SecAsn1Template *theTemplate
3164 #ifdef __APPLE__
3165 ,
3166 /* only needed if first element will be SEC_ASN1_DYNAMIC */
3167 const char *buf,
3168 size_t len /* __APPLE__ */
3169 #endif
3170 )
3171 {
3172 PRArenaPool *our_pool;
3173 SEC_ASN1DecoderContext *cx;
3174
3175 our_pool = PORT_NewArena (SEC_ASN1_DEFAULT_ARENA_SIZE);
3176 if (our_pool == NULL)
3177 return NULL;
3178
3179 cx = (SEC_ASN1DecoderContext*)PORT_ArenaZAlloc (our_pool, sizeof(*cx));
3180 if (cx == NULL) {
3181 PORT_FreeArena (our_pool, PR_FALSE);
3182 return NULL;
3183 }
3184
3185 cx->our_pool = our_pool;
3186 if (their_pool != NULL) {
3187 cx->their_pool = their_pool;
3188 #ifdef SEC_ASN1D_FREE_ON_ERROR
3189 cx->their_mark = PORT_ArenaMark (their_pool);
3190 #endif
3191 }
3192
3193 cx->status = needBytes;
3194
3195 if (sec_asn1d_push_state(cx, theTemplate, dest, PR_FALSE) == NULL
3196 || sec_asn1d_init_state_based_on_template (cx->current,
3197 buf /* __APPLE__ */, len /* __APPLE__ */) == NULL) {
3198 /*
3199 * Trouble initializing (probably due to failed allocations)
3200 * requires that we just give up.
3201 */
3202 PORT_FreeArena (our_pool, PR_FALSE);
3203 return NULL;
3204 }
3205
3206 return cx;
3207 }
3208
3209
3210 void
3211 SEC_ASN1DecoderSetFilterProc (SEC_ASN1DecoderContext *cx,
3212 SEC_ASN1WriteProc fn, void *arg,
3213 PRBool only)
3214 {
3215 /* check that we are "between" fields here */
3216 PORT_Assert (cx->during_notify);
3217
3218 cx->filter_proc = fn;
3219 cx->filter_arg = arg;
3220 cx->filter_only = only;
3221 }
3222
3223
3224 void
3225 SEC_ASN1DecoderClearFilterProc (SEC_ASN1DecoderContext *cx)
3226 {
3227 /* check that we are "between" fields here */
3228 PORT_Assert (cx->during_notify);
3229
3230 cx->filter_proc = NULL;
3231 cx->filter_arg = NULL;
3232 cx->filter_only = PR_FALSE;
3233 }
3234
3235
3236 void
3237 SEC_ASN1DecoderSetNotifyProc (SEC_ASN1DecoderContext *cx,
3238 SEC_ASN1NotifyProc fn, void *arg)
3239 {
3240 cx->notify_proc = fn;
3241 cx->notify_arg = arg;
3242 }
3243
3244
3245 void
3246 SEC_ASN1DecoderClearNotifyProc (SEC_ASN1DecoderContext *cx)
3247 {
3248 cx->notify_proc = NULL;
3249 cx->notify_arg = NULL; /* not necessary; just being clean */
3250 }
3251
3252
3253 void
3254 SEC_ASN1DecoderAbort(SEC_ASN1DecoderContext *cx, int error)
3255 {
3256 PORT_Assert(cx);
3257 PORT_SetError(error);
3258 cx->status = decodeError;
3259 }
3260
3261
3262 SECStatus
3263 SEC_ASN1Decode (PRArenaPool *poolp, void *dest,
3264 const SecAsn1Template *theTemplate,
3265 const char *buf, size_t len)
3266 {
3267 SEC_ASN1DecoderContext *dcx;
3268 SECStatus urv, frv;
3269
3270 dcx = SEC_ASN1DecoderStart (poolp, dest, theTemplate,
3271 buf /* __APPLE__ */, len /* __APPLE__ */);
3272 if (dcx == NULL)
3273 return SECFailure;
3274
3275 urv = SEC_ASN1DecoderUpdate (dcx, buf, len);
3276 frv = SEC_ASN1DecoderFinish (dcx);
3277
3278 if (urv != SECSuccess)
3279 return urv;
3280
3281 return frv;
3282 }
3283
3284
3285 SECStatus
3286 SEC_ASN1DecodeItem (PRArenaPool *poolp, void *dest,
3287 const SecAsn1Template *theTemplate,
3288 const SecAsn1Item *item)
3289 {
3290 return SEC_ASN1Decode (poolp, dest, theTemplate,
3291 (const char *) item->Data, item->Length);
3292 }
3293
3294