1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 /*
6  * Support for ENcoding ASN.1 data based on BER/DER (Basic/Distinguished
7  * Encoding Rules).
8  */
9 
10 #include "secasn1.h"
11 
12 typedef enum {
13     beforeHeader,
14     duringContents,
15     duringGroup,
16     duringSequence,
17     afterContents,
18     afterImplicit,
19     afterInline,
20     afterPointer,
21     afterChoice,
22     notInUse
23 } sec_asn1e_parse_place;
24 
25 typedef enum {
26     allDone,
27     encodeError,
28     keepGoing,
29     needBytes
30 } sec_asn1e_parse_status;
31 
32 typedef enum {
33     hdr_normal = 0,     /* encode header normally */
34     hdr_any = 1,        /* header already encoded in content */
35     hdr_decoder = 2,    /* template only used by decoder. skip it. */
36     hdr_optional = 3,   /* optional component, to be omitted */
37     hdr_placeholder = 4 /* place holder for from_buf content */
38 } sec_asn1e_hdr_encoding;
39 
40 typedef struct sec_asn1e_state_struct {
41     SEC_ASN1EncoderContext *top;
42     const SEC_ASN1Template *theTemplate;
43     void *src;
44 
45     struct sec_asn1e_state_struct *parent; /* aka prev */
46     struct sec_asn1e_state_struct *child;  /* aka next */
47 
48     sec_asn1e_parse_place place; /* where we are in encoding process */
49 
50     /*
51      * XXX explain the next fields as clearly as possible...
52      */
53     unsigned char tag_modifiers;
54     unsigned char tag_number;
55     unsigned long underlying_kind;
56 
57     int depth;
58 
59     PRBool isExplicit,     /* we are handling an isExplicit header */
60         indefinite,        /* need end-of-contents */
61         is_string,         /* encoding a simple string or an ANY */
62         may_stream,        /* when streaming, do indefinite encoding */
63         optional,          /* omit field if it has no contents */
64         disallowStreaming; /* disallow streaming in all sub-templates */
65 } sec_asn1e_state;
66 
67 /*
68  * An "outsider" will have an opaque pointer to this, created by calling
69  * SEC_ASN1EncoderStart().  It will be passed back in to all subsequent
70  * calls to SEC_ASN1EncoderUpdate() and related routines, and when done
71  * it is passed to SEC_ASN1EncoderFinish().
72  */
73 struct sec_EncoderContext_struct {
74     PLArenaPool *our_pool; /* for our internal allocs */
75 
76     sec_asn1e_state *current;
77     sec_asn1e_parse_status status;
78 
79     PRBool streaming;
80     PRBool from_buf;
81 
82     SEC_ASN1NotifyProc notify_proc; /* call before/after handling field */
83     void *notify_arg;               /* argument to notify_proc */
84     PRBool during_notify;           /* true during call to notify_proc */
85 
86     SEC_ASN1WriteProc output_proc; /* pass encoded bytes to this  */
87     void *output_arg;              /* argument to that function */
88 };
89 
90 static sec_asn1e_state *
sec_asn1e_push_state(SEC_ASN1EncoderContext * cx,const SEC_ASN1Template * theTemplate,const void * src,PRBool new_depth)91 sec_asn1e_push_state(SEC_ASN1EncoderContext *cx,
92                      const SEC_ASN1Template *theTemplate,
93                      const void *src, PRBool new_depth)
94 {
95     sec_asn1e_state *state, *new_state;
96 
97     state = cx->current;
98 
99     new_state = (sec_asn1e_state *)PORT_ArenaZAlloc(cx->our_pool,
100                                                     sizeof(*new_state));
101     if (new_state == NULL) {
102         cx->status = encodeError;
103         return NULL;
104     }
105 
106     new_state->top = cx;
107     new_state->parent = state;
108     new_state->theTemplate = theTemplate;
109     new_state->place = notInUse;
110     if (src != NULL)
111         new_state->src = (char *)src + theTemplate->offset;
112 
113     if (state != NULL) {
114         new_state->depth = state->depth;
115         if (new_depth)
116             new_state->depth++;
117         state->child = new_state;
118     }
119 
120     cx->current = new_state;
121     return new_state;
122 }
123 
124 static void
sec_asn1e_scrub_state(sec_asn1e_state * state)125 sec_asn1e_scrub_state(sec_asn1e_state *state)
126 {
127     /*
128      * Some default "scrubbing".
129      * XXX right set of initializations?
130      */
131     state->place = beforeHeader;
132     state->indefinite = PR_FALSE;
133 }
134 
135 static void
sec_asn1e_notify_before(SEC_ASN1EncoderContext * cx,void * src,int depth)136 sec_asn1e_notify_before(SEC_ASN1EncoderContext *cx, void *src, int depth)
137 {
138     if (cx->notify_proc == NULL)
139         return;
140 
141     cx->during_notify = PR_TRUE;
142     (*cx->notify_proc)(cx->notify_arg, PR_TRUE, src, depth);
143     cx->during_notify = PR_FALSE;
144 }
145 
146 static void
sec_asn1e_notify_after(SEC_ASN1EncoderContext * cx,void * src,int depth)147 sec_asn1e_notify_after(SEC_ASN1EncoderContext *cx, void *src, int depth)
148 {
149     if (cx->notify_proc == NULL)
150         return;
151 
152     cx->during_notify = PR_TRUE;
153     (*cx->notify_proc)(cx->notify_arg, PR_FALSE, src, depth);
154     cx->during_notify = PR_FALSE;
155 }
156 
157 static sec_asn1e_state *
sec_asn1e_init_state_based_on_template(sec_asn1e_state * state)158 sec_asn1e_init_state_based_on_template(sec_asn1e_state *state)
159 {
160     PRBool isExplicit, is_string, may_stream, optional, universal;
161     PRBool disallowStreaming;
162     unsigned char tag_modifiers;
163     unsigned long encode_kind, under_kind;
164     unsigned long tag_number;
165     PRBool isInline = PR_FALSE;
166 
167     encode_kind = state->theTemplate->kind;
168 
169     universal = ((encode_kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL)
170                     ? PR_TRUE
171                     : PR_FALSE;
172 
173     isExplicit = (encode_kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE;
174     encode_kind &= ~SEC_ASN1_EXPLICIT;
175 
176     optional = (encode_kind & SEC_ASN1_OPTIONAL) ? PR_TRUE : PR_FALSE;
177     encode_kind &= ~SEC_ASN1_OPTIONAL;
178 
179     PORT_Assert(!(isExplicit && universal)); /* bad templates */
180 
181     may_stream = (encode_kind & SEC_ASN1_MAY_STREAM) ? PR_TRUE : PR_FALSE;
182     encode_kind &= ~SEC_ASN1_MAY_STREAM;
183 
184     disallowStreaming = (encode_kind & SEC_ASN1_NO_STREAM) ? PR_TRUE : PR_FALSE;
185     encode_kind &= ~SEC_ASN1_NO_STREAM;
186 
187     /* Just clear this to get it out of the way; we do not need it here */
188     encode_kind &= ~SEC_ASN1_DYNAMIC;
189 
190     if (encode_kind & SEC_ASN1_CHOICE) {
191         under_kind = SEC_ASN1_CHOICE;
192     } else if ((encode_kind & (SEC_ASN1_POINTER | SEC_ASN1_INLINE)) ||
193                (!universal && !isExplicit)) {
194         const SEC_ASN1Template *subt;
195         void *src = NULL;
196 
197         PORT_Assert((encode_kind & (SEC_ASN1_ANY | SEC_ASN1_SKIP)) == 0);
198 
199         sec_asn1e_scrub_state(state);
200 
201         if (encode_kind & SEC_ASN1_POINTER) {
202             src = *(void **)state->src;
203             state->place = afterPointer;
204 
205             if (src == NULL) {
206                 /*
207                  * If this is optional, but NULL, then the field does
208                  * not need to be encoded.  In this case we are done;
209                  * we do not want to push a subtemplate.
210                  */
211                 if (optional)
212                     return state;
213 
214                 /*
215                  * XXX this is an error; need to figure out
216                  * how to handle this
217                  */
218             }
219         } else {
220             src = state->src;
221             if (encode_kind & SEC_ASN1_INLINE) {
222                 /* check that there are no extraneous bits */
223                 /* PORT_Assert (encode_kind == SEC_ASN1_INLINE && !optional); */
224                 state->place = afterInline;
225                 isInline = PR_TRUE;
226             } else {
227                 /*
228                  * Save the tag modifiers and tag number here before moving
229                  * on to the next state in case this is a member of a
230                  * SEQUENCE OF
231                  */
232                 state->tag_modifiers = (unsigned char)(encode_kind & (SEC_ASN1_TAG_MASK & ~SEC_ASN1_TAGNUM_MASK));
233                 state->tag_number = (unsigned char)(encode_kind & SEC_ASN1_TAGNUM_MASK);
234 
235                 state->place = afterImplicit;
236                 state->optional = optional;
237             }
238         }
239 
240         subt = SEC_ASN1GetSubtemplate(state->theTemplate, state->src, PR_TRUE);
241         if (isInline && optional) {
242             /* we only handle a very limited set of optional inline cases at
243                this time */
244             if (PR_FALSE != SEC_ASN1IsTemplateSimple(subt)) {
245                 /* we now know that the target is a SECItem*, so we can check
246                    if the source contains one */
247                 SECItem *target = (SECItem *)state->src;
248                 if (!target || !target->data || !target->len) {
249                     /* no valid data to encode subtemplate */
250                     return state;
251                 }
252             } else {
253                 PORT_Assert(0); /* complex templates are not handled as
254                                    inline optional */
255             }
256         }
257         state = sec_asn1e_push_state(state->top, subt, src, PR_FALSE);
258         if (state == NULL)
259             return state;
260 
261         if (universal) {
262             /*
263              * This is a POINTER or INLINE; just init based on that
264              * and we are done.
265              */
266             return sec_asn1e_init_state_based_on_template(state);
267         }
268 
269         /*
270          * This is an implicit, non-universal (meaning, application-private
271          * or context-specific) field.  This results in a "magic" tag but
272          * encoding based on the underlying type.  We pushed a new state
273          * that is based on the subtemplate (the underlying type), but
274          * now we will sort of alias it to give it some of our properties
275          * (tag, optional status, etc.).
276          *
277          * NB: ALL the following flags in the subtemplate are disallowed
278          *     and/or ignored: EXPLICIT, OPTIONAL, INNER, INLINE, POINTER.
279          */
280 
281         under_kind = state->theTemplate->kind;
282         if ((under_kind & SEC_ASN1_MAY_STREAM) && !disallowStreaming) {
283             may_stream = PR_TRUE;
284         }
285         under_kind &= ~(SEC_ASN1_MAY_STREAM | SEC_ASN1_DYNAMIC);
286     } else {
287         under_kind = encode_kind;
288     }
289 
290 /*
291      * Sanity check that there are no unwanted bits marked in under_kind.
292      * These bits were either removed above (after we recorded them) or
293      * they simply should not be found (signalling a bad/broken template).
294      * XXX is this the right set of bits to test here? (i.e. need to add
295      * or remove any?)
296      */
297 #define UNEXPECTED_FLAGS                                                      \
298     (SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_SKIP | SEC_ASN1_INNER | \
299      SEC_ASN1_DYNAMIC | SEC_ASN1_MAY_STREAM | SEC_ASN1_INLINE | SEC_ASN1_POINTER)
300 
301     PORT_Assert((under_kind & UNEXPECTED_FLAGS) == 0);
302     under_kind &= ~UNEXPECTED_FLAGS;
303 #undef UNEXPECTED_FLAGS
304 
305     if (encode_kind & SEC_ASN1_ANY) {
306         PORT_Assert(encode_kind == under_kind);
307         tag_modifiers = 0;
308         tag_number = 0;
309         is_string = PR_TRUE;
310     } else {
311         tag_modifiers = (unsigned char)(encode_kind & (SEC_ASN1_TAG_MASK & ~SEC_ASN1_TAGNUM_MASK));
312         /*
313          * XXX This assumes only single-octet identifiers.  To handle
314          * the HIGH TAG form we would need to do some more work, especially
315          * in how to specify them in the template, because right now we
316          * do not provide a way to specify more *tag* bits in encode_kind.
317          */
318         tag_number = encode_kind & SEC_ASN1_TAGNUM_MASK;
319 
320         is_string = PR_FALSE;
321         switch (under_kind & SEC_ASN1_TAGNUM_MASK) {
322             case SEC_ASN1_SET:
323                 /*
324                  * XXX A plain old SET (as opposed to a SET OF) is not implemented.
325                  * If it ever is, remove this assert...
326                  */
327                 PORT_Assert((under_kind & SEC_ASN1_GROUP) != 0);
328             /* fallthru */
329             case SEC_ASN1_SEQUENCE:
330                 tag_modifiers |= SEC_ASN1_CONSTRUCTED;
331                 break;
332             case SEC_ASN1_BIT_STRING:
333             case SEC_ASN1_BMP_STRING:
334             case SEC_ASN1_GENERALIZED_TIME:
335             case SEC_ASN1_IA5_STRING:
336             case SEC_ASN1_OCTET_STRING:
337             case SEC_ASN1_PRINTABLE_STRING:
338             case SEC_ASN1_T61_STRING:
339             case SEC_ASN1_UNIVERSAL_STRING:
340             case SEC_ASN1_UTC_TIME:
341             case SEC_ASN1_UTF8_STRING:
342             case SEC_ASN1_VISIBLE_STRING:
343                 /*
344                  * We do not yet know if we will be constructing the string,
345                  * so we have to wait to do this final tag modification.
346                  */
347                 is_string = PR_TRUE;
348                 break;
349         }
350     }
351 
352     state->tag_modifiers = tag_modifiers;
353     state->tag_number = (unsigned char)tag_number;
354     state->underlying_kind = under_kind;
355     state->isExplicit = isExplicit;
356     state->may_stream = may_stream;
357     state->is_string = is_string;
358     state->optional = optional;
359     state->disallowStreaming = disallowStreaming;
360 
361     sec_asn1e_scrub_state(state);
362 
363     return state;
364 }
365 
366 static void
sec_asn1e_write_part(sec_asn1e_state * state,const char * buf,unsigned long len,SEC_ASN1EncodingPart part)367 sec_asn1e_write_part(sec_asn1e_state *state,
368                      const char *buf, unsigned long len,
369                      SEC_ASN1EncodingPart part)
370 {
371     SEC_ASN1EncoderContext *cx;
372 
373     cx = state->top;
374     (*cx->output_proc)(cx->output_arg, buf, len, state->depth, part);
375 }
376 
377 /*
378  * XXX This assumes only single-octet identifiers.  To handle
379  * the HIGH TAG form we would need to modify this interface and
380  * teach it to properly encode the special form.
381  */
382 static void
sec_asn1e_write_identifier_bytes(sec_asn1e_state * state,unsigned char value)383 sec_asn1e_write_identifier_bytes(sec_asn1e_state *state, unsigned char value)
384 {
385     char byte;
386 
387     byte = (char)value;
388     sec_asn1e_write_part(state, &byte, 1, SEC_ASN1_Identifier);
389 }
390 
391 int
SEC_ASN1EncodeLength(unsigned char * buf,int value)392 SEC_ASN1EncodeLength(unsigned char *buf, int value)
393 {
394     int lenlen;
395 
396     lenlen = SEC_ASN1LengthLength(value);
397     if (lenlen == 1) {
398         buf[0] = value;
399     } else {
400         int i;
401 
402         i = lenlen - 1;
403         buf[0] = 0x80 | i;
404         while (i) {
405             buf[i--] = value;
406             value >>= 8;
407         }
408         PORT_Assert(value == 0);
409     }
410     return lenlen;
411 }
412 
413 static void
sec_asn1e_write_length_bytes(sec_asn1e_state * state,unsigned long value,PRBool indefinite)414 sec_asn1e_write_length_bytes(sec_asn1e_state *state, unsigned long value,
415                              PRBool indefinite)
416 {
417     int lenlen;
418     unsigned char buf[sizeof(unsigned long) + 1];
419 
420     if (indefinite) {
421         PORT_Assert(value == 0);
422         buf[0] = 0x80;
423         lenlen = 1;
424     } else {
425         lenlen = SEC_ASN1EncodeLength(buf, value);
426     }
427 
428     sec_asn1e_write_part(state, (char *)buf, lenlen, SEC_ASN1_Length);
429 }
430 
431 static void
sec_asn1e_write_contents_bytes(sec_asn1e_state * state,const char * buf,unsigned long len)432 sec_asn1e_write_contents_bytes(sec_asn1e_state *state,
433                                const char *buf, unsigned long len)
434 {
435     sec_asn1e_write_part(state, buf, len, SEC_ASN1_Contents);
436 }
437 
438 static void
sec_asn1e_write_end_of_contents_bytes(sec_asn1e_state * state)439 sec_asn1e_write_end_of_contents_bytes(sec_asn1e_state *state)
440 {
441     const char eoc[2] = { 0, 0 };
442 
443     sec_asn1e_write_part(state, eoc, 2, SEC_ASN1_EndOfContents);
444 }
445 
446 static int
sec_asn1e_which_choice(void * src,const SEC_ASN1Template * theTemplate)447 sec_asn1e_which_choice(
448     void *src,
449     const SEC_ASN1Template *theTemplate)
450 {
451     int rv;
452     unsigned int which = *(unsigned int *)src;
453 
454     for (rv = 1, theTemplate++; theTemplate->kind != 0; rv++, theTemplate++) {
455         if (which == theTemplate->size) {
456             return rv;
457         }
458     }
459 
460     return 0;
461 }
462 
463 static unsigned long
sec_asn1e_contents_length(const SEC_ASN1Template * theTemplate,void * src,PRBool disallowStreaming,PRBool insideIndefinite,sec_asn1e_hdr_encoding * pHdrException)464 sec_asn1e_contents_length(const SEC_ASN1Template *theTemplate, void *src,
465                           PRBool disallowStreaming, PRBool insideIndefinite,
466                           sec_asn1e_hdr_encoding *pHdrException)
467 {
468     unsigned long encode_kind, underlying_kind;
469     PRBool isExplicit, optional, universal, may_stream;
470     unsigned long len;
471 
472     /*
473      * This function currently calculates the length in all cases
474      * except the following: when writing out the contents of a
475      * template that belongs to a state where it was a sub-template
476      * with the SEC_ASN1_MAY_STREAM bit set and it's parent had the
477      * optional bit set.  The information that the parent is optional
478      * and that we should return the length of 0 when that length is
479      * present since that means the optional field is no longer present.
480      * So we add the disallowStreaming flag which is passed in when
481      * writing the contents, but for all recursive calls to
482      * sec_asn1e_contents_length, we pass PR_FALSE, because this
483      * function correctly calculates the length for children templates
484      * from that point on.  Confused yet?  At least you didn't have
485      * to figure it out.  ;)  -javi
486      */
487     encode_kind = theTemplate->kind;
488 
489     universal = ((encode_kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL)
490                     ? PR_TRUE
491                     : PR_FALSE;
492 
493     isExplicit = (encode_kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE;
494     encode_kind &= ~SEC_ASN1_EXPLICIT;
495 
496     optional = (encode_kind & SEC_ASN1_OPTIONAL) ? PR_TRUE : PR_FALSE;
497     encode_kind &= ~SEC_ASN1_OPTIONAL;
498 
499     PORT_Assert(!(isExplicit && universal)); /* bad templates */
500 
501     may_stream = (encode_kind & SEC_ASN1_MAY_STREAM) ? PR_TRUE : PR_FALSE;
502     encode_kind &= ~SEC_ASN1_MAY_STREAM;
503 
504     /* Just clear this to get it out of the way; we do not need it here */
505     encode_kind &= ~SEC_ASN1_DYNAMIC;
506 
507     if (encode_kind & SEC_ASN1_NO_STREAM) {
508         disallowStreaming = PR_TRUE;
509     }
510     encode_kind &= ~SEC_ASN1_NO_STREAM;
511 
512     if (encode_kind & SEC_ASN1_CHOICE) {
513         void *src2;
514         int indx = sec_asn1e_which_choice(src, theTemplate);
515         if (0 == indx) {
516             /* XXX set an error? "choice not found" */
517             /* state->top->status = encodeError; */
518             return 0;
519         }
520 
521         src2 = (void *)((char *)src - theTemplate->offset + theTemplate[indx].offset);
522 
523         return sec_asn1e_contents_length(&theTemplate[indx], src2,
524                                          disallowStreaming, insideIndefinite,
525                                          pHdrException);
526     }
527 
528     if ((encode_kind & (SEC_ASN1_POINTER | SEC_ASN1_INLINE)) || !universal) {
529         /* XXX any bits we want to disallow (PORT_Assert against) here? */
530         theTemplate = SEC_ASN1GetSubtemplate(theTemplate, src, PR_TRUE);
531         if (encode_kind & SEC_ASN1_POINTER) {
532             src = *(void **)src;
533             if (src == NULL) {
534                 *pHdrException = optional ? hdr_optional : hdr_normal;
535                 return 0;
536             }
537         } else if (encode_kind & SEC_ASN1_INLINE) {
538             /* check that there are no extraneous bits */
539             if (optional) {
540                 if (PR_FALSE != SEC_ASN1IsTemplateSimple(theTemplate)) {
541                     /* we now know that the target is a SECItem*, so we can check
542                        if the source contains one */
543                     SECItem *target = (SECItem *)src;
544                     if (!target || !target->data || !target->len) {
545                         /* no valid data to encode subtemplate */
546                         *pHdrException = hdr_optional;
547                         return 0;
548                     }
549                 } else {
550                     PORT_Assert(0); /* complex templates not handled as inline
551                                        optional */
552                 }
553             }
554         }
555 
556         src = (char *)src + theTemplate->offset;
557 
558         /* recurse to find the length of the subtemplate */
559         len = sec_asn1e_contents_length(theTemplate, src, disallowStreaming,
560                                         insideIndefinite, pHdrException);
561         if (len == 0 && optional) {
562             *pHdrException = hdr_optional;
563         } else if (isExplicit) {
564             if (*pHdrException == hdr_any) {
565                 /* *we* do not want to add in a header,
566                 ** but our caller still does.
567                 */
568                 *pHdrException = hdr_normal;
569             } else if (*pHdrException == hdr_normal) {
570                 /* if the inner content exists, our length is
571                  * len(identifier) + len(length) + len(innercontent)
572                  * XXX we currently assume len(identifier) == 1;
573                  * to support a high-tag-number this would need to be smarter.
574                  */
575                 len += 1 + SEC_ASN1LengthLength(len);
576             }
577         }
578         return len;
579     }
580     underlying_kind = encode_kind;
581 
582     /* This is only used in decoding; it plays no part in encoding.  */
583     if (underlying_kind & SEC_ASN1_SAVE) {
584         /* check that there are no extraneous bits */
585         PORT_Assert(underlying_kind == SEC_ASN1_SAVE);
586         *pHdrException = hdr_decoder;
587         return 0;
588     }
589 
590 #define UNEXPECTED_FLAGS                                                          \
591     (SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_INLINE | SEC_ASN1_POINTER | \
592      SEC_ASN1_DYNAMIC | SEC_ASN1_MAY_STREAM | SEC_ASN1_SAVE | SEC_ASN1_SKIP)
593 
594     /* Having any of these bits is not expected here...  */
595     PORT_Assert((underlying_kind & UNEXPECTED_FLAGS) == 0);
596     underlying_kind &= ~UNEXPECTED_FLAGS;
597 #undef UNEXPECTED_FLAGS
598 
599     if (underlying_kind & SEC_ASN1_CHOICE) {
600         void *src2;
601         int indx = sec_asn1e_which_choice(src, theTemplate);
602         if (0 == indx) {
603             /* XXX set an error? "choice not found" */
604             /* state->top->status = encodeError; */
605             return 0;
606         }
607 
608         src2 = (void *)((char *)src - theTemplate->offset + theTemplate[indx].offset);
609         len = sec_asn1e_contents_length(&theTemplate[indx], src2,
610                                         disallowStreaming, insideIndefinite,
611                                         pHdrException);
612     } else {
613         switch (underlying_kind) {
614             case SEC_ASN1_SEQUENCE_OF:
615             case SEC_ASN1_SET_OF: {
616                 const SEC_ASN1Template *tmpt;
617                 void *sub_src;
618                 unsigned long sub_len;
619                 void **group;
620 
621                 len = 0;
622 
623                 group = *(void ***)src;
624                 if (group == NULL)
625                     break;
626 
627                 tmpt = SEC_ASN1GetSubtemplate(theTemplate, src, PR_TRUE);
628 
629                 for (; *group != NULL; group++) {
630                     sub_src = (char *)(*group) + tmpt->offset;
631                     sub_len = sec_asn1e_contents_length(tmpt, sub_src,
632                                                         disallowStreaming,
633                                                         insideIndefinite,
634                                                         pHdrException);
635                     len += sub_len;
636                     /*
637                      * XXX The 1 below is the presumed length of the identifier;
638                      * to support a high-tag-number this would need to be smarter.
639                      */
640                     if (*pHdrException == hdr_normal)
641                         len += 1 + SEC_ASN1LengthLength(sub_len);
642                 }
643             } break;
644 
645             case SEC_ASN1_SEQUENCE:
646             case SEC_ASN1_SET: {
647                 const SEC_ASN1Template *tmpt;
648                 void *sub_src;
649                 unsigned long sub_len;
650 
651                 len = 0;
652                 for (tmpt = theTemplate + 1; tmpt->kind; tmpt++) {
653                     sub_src = (char *)src + tmpt->offset;
654                     sub_len = sec_asn1e_contents_length(tmpt, sub_src,
655                                                         disallowStreaming,
656                                                         insideIndefinite,
657                                                         pHdrException);
658                     len += sub_len;
659                     /*
660                      * XXX The 1 below is the presumed length of the identifier;
661                      * to support a high-tag-number this would need to be smarter.
662                      */
663                     if (*pHdrException == hdr_normal)
664                         len += 1 + SEC_ASN1LengthLength(sub_len);
665                 }
666             } break;
667 
668             case SEC_ASN1_BIT_STRING:
669                 /* convert bit length to byte */
670                 len = (((SECItem *)src)->len + 7) >> 3;
671                 /* bit string contents involve an extra octet */
672                 if (len)
673                     len++;
674                 break;
675 
676             case SEC_ASN1_INTEGER:
677                 /* ASN.1 INTEGERs are signed.
678                  * If the source is an unsigned integer, the encoder will need
679                  * to handle the conversion here.
680                  */
681                 {
682                     unsigned char *buf = ((SECItem *)src)->data;
683                     SECItemType integerType = ((SECItem *)src)->type;
684                     len = ((SECItem *)src)->len;
685                     while (len > 0) {
686                         if (*buf != 0) {
687                             if (*buf & 0x80 && integerType == siUnsignedInteger) {
688                                 len++; /* leading zero needed to make number signed */
689                             }
690                             break; /* reached beginning of number */
691                         }
692                         if (len == 1) {
693                             break; /* the number 0 */
694                         }
695                         if (buf[1] & 0x80) {
696                             break; /* leading zero already present */
697                         }
698                         /* extraneous leading zero, keep going */
699                         buf++;
700                         len--;
701                     }
702                 }
703                 break;
704 
705             default:
706                 len = ((SECItem *)src)->len;
707                 break;
708         } /* end switch */
709 
710 #ifndef WHAT_PROBLEM_DOES_THIS_SOLVE
711         /* if we're streaming, we may have a secitem w/len 0 as placeholder */
712         if (!len && insideIndefinite && may_stream && !disallowStreaming) {
713             len = 1;
714         }
715 #endif
716     } /* end else */
717 
718     if (len == 0 && optional)
719         *pHdrException = hdr_optional;
720     else if (underlying_kind == SEC_ASN1_ANY)
721         *pHdrException = hdr_any;
722     else
723         *pHdrException = hdr_normal;
724 
725     return len;
726 }
727 
728 static void
sec_asn1e_write_header(sec_asn1e_state * state)729 sec_asn1e_write_header(sec_asn1e_state *state)
730 {
731     unsigned long contents_length;
732     unsigned char tag_number, tag_modifiers;
733     sec_asn1e_hdr_encoding hdrException = hdr_normal;
734     PRBool indefinite = PR_FALSE;
735 
736     PORT_Assert(state->place == beforeHeader);
737 
738     tag_number = state->tag_number;
739     tag_modifiers = state->tag_modifiers;
740 
741     if (state->underlying_kind == SEC_ASN1_ANY) {
742         state->place = duringContents;
743         return;
744     }
745 
746     if (state->underlying_kind & SEC_ASN1_CHOICE) {
747         int indx = sec_asn1e_which_choice(state->src, state->theTemplate);
748         if (0 == indx) {
749             /* XXX set an error? "choice not found" */
750             state->top->status = encodeError;
751             return;
752         }
753         state->place = afterChoice;
754         state = sec_asn1e_push_state(state->top, &state->theTemplate[indx],
755                                      (char *)state->src - state->theTemplate->offset,
756                                      PR_TRUE);
757         if (state) {
758             /*
759              * Do the "before" field notification.
760              */
761             sec_asn1e_notify_before(state->top, state->src, state->depth);
762             (void)sec_asn1e_init_state_based_on_template(state);
763         }
764         return;
765     }
766 
767     /* The !isString test below is apparently intended to ensure that all
768     ** constructed types receive indefinite length encoding.
769     */
770     indefinite = (PRBool)(state->top->streaming && state->may_stream &&
771                           (state->top->from_buf || !state->is_string));
772 
773     /*
774      * If we are doing a definite-length encoding, first we have to
775      * walk the data structure to calculate the entire contents length.
776      * If we are doing an indefinite-length encoding, we still need to
777      * know if the contents is:
778      *    optional and to be omitted, or
779      *    an ANY (header is pre-encoded), or
780      *    a SAVE or some other kind of template used only by the decoder.
781      * So, we call this function either way.
782      */
783     contents_length = sec_asn1e_contents_length(state->theTemplate,
784                                                 state->src,
785                                                 state->disallowStreaming,
786                                                 indefinite,
787                                                 &hdrException);
788     /*
789      * We might be told explicitly not to put out a header.
790      * But it can also be the case, via a pushed subtemplate, that
791      * sec_asn1e_contents_length could not know that this field is
792      * really optional.  So check for that explicitly, too.
793      */
794     if (hdrException != hdr_normal ||
795         (contents_length == 0 && state->optional)) {
796         state->place = afterContents;
797         if (state->top->streaming &&
798             state->may_stream &&
799             state->top->from_buf) {
800             /* we did not find an optional indefinite string, so we
801              * don't encode it.  However, if TakeFromBuf is on, we stop
802              * here anyway to give our caller a chance to intercept at the
803              * same point where we would stop if the field were present.
804              */
805             state->top->status = needBytes;
806         }
807         return;
808     }
809 
810     if (indefinite) {
811         /*
812          * We need to put out an indefinite-length encoding.
813          * The only universal types that can be constructed are SETs,
814          * SEQUENCEs, and strings; so check that it is one of those,
815          * or that it is not universal (e.g. context-specific).
816          */
817         state->indefinite = PR_TRUE;
818         PORT_Assert((tag_number == SEC_ASN1_SET) || (tag_number == SEC_ASN1_SEQUENCE) || ((tag_modifiers & SEC_ASN1_CLASS_MASK) != 0) || state->is_string);
819         tag_modifiers |= SEC_ASN1_CONSTRUCTED;
820         contents_length = 0;
821     }
822 
823     sec_asn1e_write_identifier_bytes(state,
824                                      (unsigned char)(tag_number | tag_modifiers));
825     sec_asn1e_write_length_bytes(state, contents_length, state->indefinite);
826 
827     if (contents_length == 0 && !state->indefinite) {
828         /*
829          * If no real contents to encode, then we are done with this field.
830          */
831         state->place = afterContents;
832         return;
833     }
834 
835     /*
836      * An EXPLICIT is nothing but an outer header, which we have already
837      * written.  Now we need to do the inner header and contents.
838      */
839     if (state->isExplicit) {
840         const SEC_ASN1Template *subt =
841             SEC_ASN1GetSubtemplate(state->theTemplate, state->src, PR_TRUE);
842         state->place = afterContents;
843         state = sec_asn1e_push_state(state->top, subt, state->src, PR_TRUE);
844         if (state != NULL) {
845             (void)sec_asn1e_init_state_based_on_template(state);
846         }
847         return;
848     }
849 
850     switch (state->underlying_kind) {
851         case SEC_ASN1_SET_OF:
852         case SEC_ASN1_SEQUENCE_OF:
853             /*
854              * We need to push a child to handle each member.
855              */
856             {
857                 void **group;
858                 const SEC_ASN1Template *subt;
859 
860                 group = *(void ***)state->src;
861                 if (group == NULL || *group == NULL) {
862                     /*
863                      * Group is empty; we are done.
864                      */
865                     state->place = afterContents;
866                     return;
867                 }
868                 state->place = duringGroup;
869                 subt = SEC_ASN1GetSubtemplate(state->theTemplate, state->src,
870                                               PR_TRUE);
871                 state = sec_asn1e_push_state(state->top, subt, *group, PR_TRUE);
872                 if (state != NULL) {
873                     (void)sec_asn1e_init_state_based_on_template(state);
874                 }
875             }
876             break;
877 
878         case SEC_ASN1_SEQUENCE:
879         case SEC_ASN1_SET:
880             /*
881              * We need to push a child to handle the individual fields.
882              */
883             state->place = duringSequence;
884             state = sec_asn1e_push_state(state->top, state->theTemplate + 1,
885                                          state->src, PR_TRUE);
886             if (state != NULL) {
887                 /*
888                  * Do the "before" field notification.
889                  */
890                 sec_asn1e_notify_before(state->top, state->src, state->depth);
891                 (void)sec_asn1e_init_state_based_on_template(state);
892             }
893             break;
894 
895         default:
896             /*
897              * I think we do not need to do anything else.
898              * XXX Correct?
899              */
900             state->place = duringContents;
901             break;
902     }
903 }
904 
905 static void
sec_asn1e_write_contents_from_buf(sec_asn1e_state * state,const char * buf,unsigned long len)906 sec_asn1e_write_contents_from_buf(sec_asn1e_state *state,
907                                   const char *buf, unsigned long len)
908 {
909     PORT_Assert(state->place == duringContents);
910     PORT_Assert(state->top->from_buf);
911     PORT_Assert(state->may_stream && !state->disallowStreaming);
912 
913     /*
914      * Probably they just turned on "take from buf", but have not
915      * yet given us any bytes.  If there is nothing in the buffer
916      * then we have nothing to do but return and wait.
917      */
918     if (buf == NULL || len == 0) {
919         state->top->status = needBytes;
920         return;
921     }
922     /*
923      * We are streaming, reading from a passed-in buffer.
924      * This means we are encoding a simple string or an ANY.
925      * For the former, we need to put out a substring, with its
926      * own identifier and length.  For an ANY, we just write it
927      * out as is (our caller is required to ensure that it
928      * is a properly encoded entity).
929      */
930     PORT_Assert(state->is_string); /* includes ANY */
931     if (state->underlying_kind != SEC_ASN1_ANY) {
932         unsigned char identifier;
933 
934         /*
935          * Create the identifier based on underlying_kind.  We cannot
936          * use tag_number and tag_modifiers because this can be an
937          * implicitly encoded field.  In that case, the underlying
938          * substrings *are* encoded with their real tag.
939          */
940         identifier = (unsigned char)(state->underlying_kind & SEC_ASN1_TAG_MASK);
941         /*
942          * The underlying kind should just be a simple string; there
943          * should be no bits like CONTEXT_SPECIFIC or CONSTRUCTED set.
944          */
945         PORT_Assert((identifier & SEC_ASN1_TAGNUM_MASK) == identifier);
946         /*
947          * Write out the tag and length for the substring.
948          */
949         sec_asn1e_write_identifier_bytes(state, identifier);
950         if (state->underlying_kind == SEC_ASN1_BIT_STRING) {
951             char byte;
952             /*
953              * Assume we have a length in bytes but we need to output
954              * a proper bit string.  This interface only works for bit
955              * strings that are full multiples of 8.  If support for
956              * real, variable length bit strings is needed then the
957              * caller will have to know to pass in a bit length instead
958              * of a byte length and then this code will have to
959              * perform the encoding necessary (length written is length
960              * in bytes plus 1, and the first octet of string is the
961              * number of bits remaining between the end of the bit
962              * string and the next byte boundary).
963              */
964             sec_asn1e_write_length_bytes(state, len + 1, PR_FALSE);
965             byte = 0;
966             sec_asn1e_write_contents_bytes(state, &byte, 1);
967         } else {
968             sec_asn1e_write_length_bytes(state, len, PR_FALSE);
969         }
970     }
971     sec_asn1e_write_contents_bytes(state, buf, len);
972     state->top->status = needBytes;
973 }
974 
975 static void
sec_asn1e_write_contents(sec_asn1e_state * state)976 sec_asn1e_write_contents(sec_asn1e_state *state)
977 {
978     unsigned long len = 0;
979 
980     PORT_Assert(state->place == duringContents);
981 
982     switch (state->underlying_kind) {
983         case SEC_ASN1_SET:
984         case SEC_ASN1_SEQUENCE:
985             PORT_Assert(0);
986             break;
987 
988         case SEC_ASN1_BIT_STRING: {
989             SECItem *item;
990             char rem;
991 
992             item = (SECItem *)state->src;
993             len = (item->len + 7) >> 3;
994             rem = (unsigned char)((len << 3) - item->len); /* remaining bits */
995             sec_asn1e_write_contents_bytes(state, &rem, 1);
996             sec_asn1e_write_contents_bytes(state, (char *)item->data, len);
997         } break;
998 
999         case SEC_ASN1_BMP_STRING:
1000             /* The number of bytes must be divisable by 2 */
1001             if ((((SECItem *)state->src)->len) % 2) {
1002                 SEC_ASN1EncoderContext *cx;
1003 
1004                 cx = state->top;
1005                 cx->status = encodeError;
1006                 break;
1007             }
1008             /* otherwise, fall through to write the content */
1009             goto process_string;
1010 
1011         case SEC_ASN1_UNIVERSAL_STRING:
1012             /* The number of bytes must be divisable by 4 */
1013             if ((((SECItem *)state->src)->len) % 4) {
1014                 SEC_ASN1EncoderContext *cx;
1015 
1016                 cx = state->top;
1017                 cx->status = encodeError;
1018                 break;
1019             }
1020             /* otherwise, fall through to write the content */
1021             goto process_string;
1022 
1023         case SEC_ASN1_INTEGER:
1024             /* ASN.1 INTEGERs are signed.  If the source is an unsigned
1025              * integer, the encoder will need to handle the conversion here.
1026              */
1027             {
1028                 unsigned int blen;
1029                 unsigned char *buf;
1030                 SECItemType integerType;
1031                 blen = ((SECItem *)state->src)->len;
1032                 buf = ((SECItem *)state->src)->data;
1033                 integerType = ((SECItem *)state->src)->type;
1034                 while (blen > 0) {
1035                     if (*buf & 0x80 && integerType == siUnsignedInteger) {
1036                         char zero = 0; /* write a leading 0 */
1037                         sec_asn1e_write_contents_bytes(state, &zero, 1);
1038                         /* and then the remaining buffer */
1039                         sec_asn1e_write_contents_bytes(state,
1040                                                        (char *)buf, blen);
1041                         break;
1042                     }
1043                     /* Check three possibilities:
1044                      * 1.  No leading zeros, msb of MSB is not 1;
1045                      * 2.  The number is zero itself;
1046                      * 3.  Encoding a signed integer with a leading zero,
1047                      *     keep the zero so that the number is positive.
1048                      */
1049                     if (*buf != 0 ||
1050                         blen == 1 ||
1051                         (buf[1] & 0x80 && integerType != siUnsignedInteger)) {
1052                         sec_asn1e_write_contents_bytes(state,
1053                                                        (char *)buf, blen);
1054                         break;
1055                     }
1056                     /* byte is 0, continue */
1057                     buf++;
1058                     blen--;
1059                 }
1060             }
1061             /* done with this content */
1062             break;
1063 
1064         process_string:
1065         default: {
1066             SECItem *item;
1067 
1068             item = (SECItem *)state->src;
1069             sec_asn1e_write_contents_bytes(state, (char *)item->data,
1070                                            item->len);
1071         } break;
1072     }
1073     state->place = afterContents;
1074 }
1075 
1076 /*
1077  * We are doing a SET OF or SEQUENCE OF, and have just finished an item.
1078  */
1079 static void
sec_asn1e_next_in_group(sec_asn1e_state * state)1080 sec_asn1e_next_in_group(sec_asn1e_state *state)
1081 {
1082     sec_asn1e_state *child;
1083     void **group;
1084     void *member;
1085 
1086     PORT_Assert(state->place == duringGroup);
1087     PORT_Assert(state->child != NULL);
1088 
1089     child = state->child;
1090 
1091     group = *(void ***)state->src;
1092 
1093     /*
1094      * Find placement of current item.
1095      */
1096     member = (char *)(state->child->src) - child->theTemplate->offset;
1097     while (*group != member)
1098         group++;
1099 
1100     /*
1101      * Move forward to next item.
1102      */
1103     group++;
1104     if (*group == NULL) {
1105         /*
1106          * That was our last one; we are done now.
1107          */
1108         child->place = notInUse;
1109         state->place = afterContents;
1110         return;
1111     }
1112     child->src = (char *)(*group) + child->theTemplate->offset;
1113 
1114     /*
1115      * Re-"push" child.
1116      */
1117     sec_asn1e_scrub_state(child);
1118     state->top->current = child;
1119 }
1120 
1121 /*
1122  * We are moving along through a sequence; move forward by one,
1123  * (detecting end-of-sequence when it happens).
1124  */
1125 static void
sec_asn1e_next_in_sequence(sec_asn1e_state * state)1126 sec_asn1e_next_in_sequence(sec_asn1e_state *state)
1127 {
1128     sec_asn1e_state *child;
1129 
1130     PORT_Assert(state->place == duringSequence);
1131     PORT_Assert(state->child != NULL);
1132 
1133     child = state->child;
1134 
1135     /*
1136      * Do the "after" field notification.
1137      */
1138     sec_asn1e_notify_after(state->top, child->src, child->depth);
1139 
1140     /*
1141      * Move forward.
1142      */
1143     child->theTemplate++;
1144     if (child->theTemplate->kind == 0) {
1145         /*
1146          * We are done with this sequence.
1147          */
1148         child->place = notInUse;
1149         state->place = afterContents;
1150         return;
1151     }
1152 
1153     /*
1154      * Reset state and push.
1155      */
1156 
1157     child->src = (char *)state->src + child->theTemplate->offset;
1158 
1159     /*
1160      * Do the "before" field notification.
1161      */
1162     sec_asn1e_notify_before(state->top, child->src, child->depth);
1163 
1164     state->top->current = child;
1165     (void)sec_asn1e_init_state_based_on_template(child);
1166 }
1167 
1168 static void
sec_asn1e_after_contents(sec_asn1e_state * state)1169 sec_asn1e_after_contents(sec_asn1e_state *state)
1170 {
1171     PORT_Assert(state->place == afterContents);
1172 
1173     if (state->indefinite)
1174         sec_asn1e_write_end_of_contents_bytes(state);
1175 
1176     /*
1177      * Just make my parent be the current state.  It will then clean
1178      * up after me and free me (or reuse me).
1179      */
1180     state->top->current = state->parent;
1181 }
1182 
1183 /*
1184  * This function is called whether or not we are streaming; if we
1185  * *are* streaming, our caller can also instruct us to take bytes
1186  * from the passed-in buffer (at buf, for length len, which is likely
1187  * bytes but could even mean bits if the current field is a bit string).
1188  * If we have been so instructed, we will gobble up bytes from there
1189  * (rather than from our src structure) and output them, and then
1190  * we will just return, expecting to be called again -- either with
1191  * more bytes or after our caller has instructed us that we are done
1192  * (for now) with the buffer.
1193  */
1194 SECStatus
SEC_ASN1EncoderUpdate(SEC_ASN1EncoderContext * cx,const char * buf,unsigned long len)1195 SEC_ASN1EncoderUpdate(SEC_ASN1EncoderContext *cx,
1196                       const char *buf, unsigned long len)
1197 {
1198     sec_asn1e_state *state;
1199 
1200     if (cx->status == needBytes) {
1201         cx->status = keepGoing;
1202     }
1203 
1204     while (cx->status == keepGoing) {
1205         state = cx->current;
1206         switch (state->place) {
1207             case beforeHeader:
1208                 sec_asn1e_write_header(state);
1209                 break;
1210             case duringContents:
1211                 if (cx->from_buf)
1212                     sec_asn1e_write_contents_from_buf(state, buf, len);
1213                 else
1214                     sec_asn1e_write_contents(state);
1215                 break;
1216             case duringGroup:
1217                 sec_asn1e_next_in_group(state);
1218                 break;
1219             case duringSequence:
1220                 sec_asn1e_next_in_sequence(state);
1221                 break;
1222             case afterContents:
1223                 sec_asn1e_after_contents(state);
1224                 break;
1225             case afterImplicit:
1226             case afterInline:
1227             case afterPointer:
1228             case afterChoice:
1229                 /*
1230                  * These states are more documentation than anything.
1231                  * They just need to force a pop.
1232                  */
1233                 PORT_Assert(!state->indefinite);
1234                 state->place = afterContents;
1235                 break;
1236             case notInUse:
1237             default:
1238                 /* This is not an error, but rather a plain old BUG! */
1239                 PORT_Assert(0);
1240                 cx->status = encodeError;
1241                 break;
1242         }
1243 
1244         if (cx->status == encodeError)
1245             break;
1246 
1247         /* It might have changed, so we have to update our local copy.  */
1248         state = cx->current;
1249 
1250         /* If it is NULL, we have popped all the way to the top.  */
1251         if (state == NULL) {
1252             cx->status = allDone;
1253             break;
1254         }
1255     }
1256 
1257     if (cx->status == encodeError) {
1258         return SECFailure;
1259     }
1260 
1261     return SECSuccess;
1262 }
1263 
1264 void
SEC_ASN1EncoderFinish(SEC_ASN1EncoderContext * cx)1265 SEC_ASN1EncoderFinish(SEC_ASN1EncoderContext *cx)
1266 {
1267     /*
1268      * XXX anything else that needs to be finished?
1269      */
1270 
1271     PORT_FreeArena(cx->our_pool, PR_FALSE);
1272 }
1273 
1274 SEC_ASN1EncoderContext *
SEC_ASN1EncoderStart(const void * src,const SEC_ASN1Template * theTemplate,SEC_ASN1WriteProc output_proc,void * output_arg)1275 SEC_ASN1EncoderStart(const void *src, const SEC_ASN1Template *theTemplate,
1276                      SEC_ASN1WriteProc output_proc, void *output_arg)
1277 {
1278     PLArenaPool *our_pool;
1279     SEC_ASN1EncoderContext *cx;
1280 
1281     our_pool = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
1282     if (our_pool == NULL)
1283         return NULL;
1284 
1285     cx = (SEC_ASN1EncoderContext *)PORT_ArenaZAlloc(our_pool, sizeof(*cx));
1286     if (cx == NULL) {
1287         PORT_FreeArena(our_pool, PR_FALSE);
1288         return NULL;
1289     }
1290 
1291     cx->our_pool = our_pool;
1292     cx->output_proc = output_proc;
1293     cx->output_arg = output_arg;
1294 
1295     cx->status = keepGoing;
1296 
1297     if (sec_asn1e_push_state(cx, theTemplate, src, PR_FALSE) == NULL ||
1298         sec_asn1e_init_state_based_on_template(cx->current) == NULL) {
1299         /*
1300          * Trouble initializing (probably due to failed allocations)
1301          * requires that we just give up.
1302          */
1303         PORT_FreeArena(our_pool, PR_FALSE);
1304         return NULL;
1305     }
1306 
1307     return cx;
1308 }
1309 
1310 /*
1311  * XXX Do we need a FilterProc, too?
1312  */
1313 
1314 void
SEC_ASN1EncoderSetNotifyProc(SEC_ASN1EncoderContext * cx,SEC_ASN1NotifyProc fn,void * arg)1315 SEC_ASN1EncoderSetNotifyProc(SEC_ASN1EncoderContext *cx,
1316                              SEC_ASN1NotifyProc fn, void *arg)
1317 {
1318     cx->notify_proc = fn;
1319     cx->notify_arg = arg;
1320 }
1321 
1322 void
SEC_ASN1EncoderClearNotifyProc(SEC_ASN1EncoderContext * cx)1323 SEC_ASN1EncoderClearNotifyProc(SEC_ASN1EncoderContext *cx)
1324 {
1325     cx->notify_proc = NULL;
1326     cx->notify_arg = NULL; /* not necessary; just being clean */
1327 }
1328 
1329 void
SEC_ASN1EncoderAbort(SEC_ASN1EncoderContext * cx,int error)1330 SEC_ASN1EncoderAbort(SEC_ASN1EncoderContext *cx, int error)
1331 {
1332     PORT_Assert(cx);
1333     PORT_SetError(error);
1334     cx->status = encodeError;
1335 }
1336 
1337 void
SEC_ASN1EncoderSetStreaming(SEC_ASN1EncoderContext * cx)1338 SEC_ASN1EncoderSetStreaming(SEC_ASN1EncoderContext *cx)
1339 {
1340     /* XXX is there a way to check that we are "between" fields here? */
1341 
1342     cx->streaming = PR_TRUE;
1343 }
1344 
1345 void
SEC_ASN1EncoderClearStreaming(SEC_ASN1EncoderContext * cx)1346 SEC_ASN1EncoderClearStreaming(SEC_ASN1EncoderContext *cx)
1347 {
1348     /* XXX is there a way to check that we are "between" fields here? */
1349 
1350     cx->streaming = PR_FALSE;
1351 }
1352 
1353 void
SEC_ASN1EncoderSetTakeFromBuf(SEC_ASN1EncoderContext * cx)1354 SEC_ASN1EncoderSetTakeFromBuf(SEC_ASN1EncoderContext *cx)
1355 {
1356     /*
1357      * XXX is there a way to check that we are "between" fields here?  this
1358      * needs to include a check for being in between groups of items in
1359      * a SET_OF or SEQUENCE_OF.
1360      */
1361     PORT_Assert(cx->streaming);
1362 
1363     cx->from_buf = PR_TRUE;
1364 }
1365 
1366 void
SEC_ASN1EncoderClearTakeFromBuf(SEC_ASN1EncoderContext * cx)1367 SEC_ASN1EncoderClearTakeFromBuf(SEC_ASN1EncoderContext *cx)
1368 {
1369     /* we should actually be taking from buf *now* */
1370     PORT_Assert(cx->from_buf);
1371     if (!cx->from_buf) /* if not, just do nothing */
1372         return;
1373 
1374     cx->from_buf = PR_FALSE;
1375 
1376     if (cx->status == needBytes) {
1377         cx->status = keepGoing;
1378         cx->current->place = afterContents;
1379     }
1380 }
1381 
1382 SECStatus
SEC_ASN1Encode(const void * src,const SEC_ASN1Template * theTemplate,SEC_ASN1WriteProc output_proc,void * output_arg)1383 SEC_ASN1Encode(const void *src, const SEC_ASN1Template *theTemplate,
1384                SEC_ASN1WriteProc output_proc, void *output_arg)
1385 {
1386     SEC_ASN1EncoderContext *ecx;
1387     SECStatus rv;
1388 
1389     ecx = SEC_ASN1EncoderStart(src, theTemplate, output_proc, output_arg);
1390     if (ecx == NULL)
1391         return SECFailure;
1392 
1393     rv = SEC_ASN1EncoderUpdate(ecx, NULL, 0);
1394 
1395     SEC_ASN1EncoderFinish(ecx);
1396     return rv;
1397 }
1398 
1399 /*
1400  * XXX depth and data_kind are unused; is there a PC way to silence warnings?
1401  * (I mean "politically correct", not anything to do with intel/win platform)
1402  */
1403 static void
sec_asn1e_encode_item_count(void * arg,const char * buf,unsigned long len,int depth,SEC_ASN1EncodingPart data_kind)1404 sec_asn1e_encode_item_count(void *arg, const char *buf, unsigned long len,
1405                             int depth, SEC_ASN1EncodingPart data_kind)
1406 {
1407     unsigned long *count;
1408 
1409     count = (unsigned long *)arg;
1410     PORT_Assert(count != NULL);
1411 
1412     *count += len;
1413 }
1414 
1415 /* XXX depth and data_kind are unused; is there a PC way to silence warnings? */
1416 static void
sec_asn1e_encode_item_store(void * arg,const char * buf,unsigned long len,int depth,SEC_ASN1EncodingPart data_kind)1417 sec_asn1e_encode_item_store(void *arg, const char *buf, unsigned long len,
1418                             int depth, SEC_ASN1EncodingPart data_kind)
1419 {
1420     SECItem *dest;
1421 
1422     dest = (SECItem *)arg;
1423     PORT_Assert(dest != NULL);
1424 
1425     if (len > 0) {
1426         PORT_Memcpy(dest->data + dest->len, buf, len);
1427         dest->len += len;
1428     }
1429 }
1430 
1431 /*
1432  * Allocate an entire SECItem, or just the data part of it, to hold
1433  * "len" bytes of stuff.  Allocate from the given pool, if specified,
1434  * otherwise just do a vanilla PORT_Alloc.
1435  *
1436  * XXX This seems like a reasonable general-purpose function (for SECITEM_)?
1437  */
1438 static SECItem *
sec_asn1e_allocate_item(PLArenaPool * poolp,SECItem * dest,unsigned long len)1439 sec_asn1e_allocate_item(PLArenaPool *poolp, SECItem *dest, unsigned long len)
1440 {
1441     if (poolp != NULL) {
1442         void *release;
1443 
1444         release = PORT_ArenaMark(poolp);
1445         if (dest == NULL)
1446             dest = (SECItem *)PORT_ArenaAlloc(poolp, sizeof(SECItem));
1447         if (dest != NULL) {
1448             dest->data = (unsigned char *)PORT_ArenaAlloc(poolp, len);
1449             if (dest->data == NULL) {
1450                 dest = NULL;
1451             }
1452         }
1453         if (dest == NULL) {
1454             /* one or both allocations failed; release everything */
1455             PORT_ArenaRelease(poolp, release);
1456         } else {
1457             /* everything okay; unmark the arena */
1458             PORT_ArenaUnmark(poolp, release);
1459         }
1460     } else {
1461         SECItem *indest;
1462 
1463         indest = dest;
1464         if (dest == NULL)
1465             dest = (SECItem *)PORT_Alloc(sizeof(SECItem));
1466         if (dest != NULL) {
1467             dest->type = siBuffer;
1468             dest->data = (unsigned char *)PORT_Alloc(len);
1469             if (dest->data == NULL) {
1470                 if (indest == NULL)
1471                     PORT_Free(dest);
1472                 dest = NULL;
1473             }
1474         }
1475     }
1476 
1477     return dest;
1478 }
1479 
1480 SECItem *
SEC_ASN1EncodeItem(PLArenaPool * poolp,SECItem * dest,const void * src,const SEC_ASN1Template * theTemplate)1481 SEC_ASN1EncodeItem(PLArenaPool *poolp, SECItem *dest, const void *src,
1482                    const SEC_ASN1Template *theTemplate)
1483 {
1484     unsigned long encoding_length;
1485     SECStatus rv;
1486 
1487     PORT_Assert(dest == NULL || dest->data == NULL);
1488 
1489     encoding_length = 0;
1490     rv = SEC_ASN1Encode(src, theTemplate,
1491                         sec_asn1e_encode_item_count, &encoding_length);
1492     if (rv != SECSuccess)
1493         return NULL;
1494 
1495     dest = sec_asn1e_allocate_item(poolp, dest, encoding_length);
1496     if (dest == NULL)
1497         return NULL;
1498 
1499     /* XXX necessary?  This really just checks for a bug in the allocate fn */
1500     PORT_Assert(dest->data != NULL);
1501     if (dest->data == NULL)
1502         return NULL;
1503 
1504     dest->len = 0;
1505     (void)SEC_ASN1Encode(src, theTemplate, sec_asn1e_encode_item_store, dest);
1506 
1507     PORT_Assert(encoding_length == dest->len);
1508     return dest;
1509 }
1510 
1511 static SECItem *
sec_asn1e_integer(PLArenaPool * poolp,SECItem * dest,unsigned long value,PRBool is_unsigned)1512 sec_asn1e_integer(PLArenaPool *poolp, SECItem *dest, unsigned long value,
1513                   PRBool is_unsigned)
1514 {
1515     unsigned long copy;
1516     unsigned char sign;
1517     int len = 0;
1518 
1519     /*
1520      * Determine the length of the encoded value (minimum of 1).
1521      */
1522     copy = value;
1523     do {
1524         len++;
1525         sign = (unsigned char)(copy & 0x80);
1526         copy >>= 8;
1527     } while (copy);
1528 
1529     /*
1530      * If 'value' is non-negative, and the high bit of the last
1531      * byte we counted was set, we need to add one to the length so
1532      * we put a high-order zero byte in the encoding.
1533      */
1534     if (sign && (is_unsigned || (long)value >= 0))
1535         len++;
1536 
1537     /*
1538      * Allocate the item (if necessary) and the data pointer within.
1539      */
1540     dest = sec_asn1e_allocate_item(poolp, dest, len);
1541     if (dest == NULL)
1542         return NULL;
1543 
1544     /*
1545      * Store the value, byte by byte, in the item.
1546      */
1547     dest->len = len;
1548     while (len) {
1549         dest->data[--len] = (unsigned char)value;
1550         value >>= 8;
1551     }
1552     PORT_Assert(value == 0);
1553 
1554     return dest;
1555 }
1556 
1557 SECItem *
SEC_ASN1EncodeInteger(PLArenaPool * poolp,SECItem * dest,long value)1558 SEC_ASN1EncodeInteger(PLArenaPool *poolp, SECItem *dest, long value)
1559 {
1560     return sec_asn1e_integer(poolp, dest, (unsigned long)value, PR_FALSE);
1561 }
1562 
1563 SECItem *
SEC_ASN1EncodeUnsignedInteger(PLArenaPool * poolp,SECItem * dest,unsigned long value)1564 SEC_ASN1EncodeUnsignedInteger(PLArenaPool *poolp,
1565                               SECItem *dest, unsigned long value)
1566 {
1567     return sec_asn1e_integer(poolp, dest, value, PR_TRUE);
1568 }
1569