Coverage Report

Created: 2024-11-21 07:03

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