Coverage Report

Created: 2026-05-19 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/nss/lib/util/secasn1e.c
Line
Count
Source
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
309k
{
95
309k
    sec_asn1e_state *state, *new_state;
96
97
309k
    if (theTemplate == NULL) {
98
0
        cx->status = encodeError;
99
0
        return NULL;
100
0
    }
101
102
309k
    state = cx->current;
103
309k
    new_state = (sec_asn1e_state *)PORT_ArenaZAlloc(cx->our_pool,
104
309k
                                                    sizeof(*new_state));
105
309k
    if (new_state == NULL) {
106
0
        cx->status = encodeError;
107
0
        return NULL;
108
0
    }
109
110
309k
    new_state->top = cx;
111
309k
    new_state->parent = state;
112
309k
    new_state->theTemplate = theTemplate;
113
309k
    new_state->place = notInUse;
114
309k
    if (src != NULL)
115
309k
        new_state->src = (char *)src + theTemplate->offset;
116
117
309k
    if (state != NULL) {
118
59.9k
        new_state->depth = state->depth;
119
59.9k
        if (new_depth)
120
49.2k
            new_state->depth++;
121
59.9k
        state->child = new_state;
122
59.9k
    }
123
124
309k
    cx->current = new_state;
125
309k
    return new_state;
126
309k
}
127
128
static void
129
sec_asn1e_scrub_state(sec_asn1e_state *state)
130
356k
{
131
    /*
132
     * Some default "scrubbing".
133
     * XXX right set of initializations?
134
     */
135
356k
    state->place = beforeHeader;
136
356k
    state->indefinite = PR_FALSE;
137
356k
}
138
139
static void
140
sec_asn1e_notify_before(SEC_ASN1EncoderContext *cx, void *src, int depth)
141
85.4k
{
142
85.4k
    if (cx->notify_proc == NULL)
143
85.4k
        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
85.4k
{
153
85.4k
    if (cx->notify_proc == NULL)
154
85.4k
        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
356k
{
164
356k
    PRBool isExplicit, is_string, may_stream, optional, universal;
165
356k
    PRBool disallowStreaming;
166
356k
    unsigned char tag_modifiers;
167
356k
    unsigned long encode_kind, under_kind;
168
356k
    unsigned long tag_number;
169
356k
    PRBool isInline = PR_FALSE;
170
171
356k
    encode_kind = state->theTemplate->kind;
172
173
356k
    universal = ((encode_kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL)
174
356k
                    ? PR_TRUE
175
356k
                    : PR_FALSE;
176
177
356k
    isExplicit = (encode_kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE;
178
356k
    encode_kind &= ~SEC_ASN1_EXPLICIT;
179
180
356k
    optional = (encode_kind & SEC_ASN1_OPTIONAL) ? PR_TRUE : PR_FALSE;
181
356k
    encode_kind &= ~SEC_ASN1_OPTIONAL;
182
183
356k
    PORT_Assert(!(isExplicit && universal)); /* bad templates */
184
185
356k
    may_stream = (encode_kind & SEC_ASN1_MAY_STREAM) ? PR_TRUE : PR_FALSE;
186
356k
    encode_kind &= ~SEC_ASN1_MAY_STREAM;
187
188
356k
    disallowStreaming = (encode_kind & SEC_ASN1_NO_STREAM) ? PR_TRUE : PR_FALSE;
189
356k
    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
356k
    encode_kind &= ~SEC_ASN1_DYNAMIC;
193
194
356k
    if (encode_kind & SEC_ASN1_CHOICE) {
195
0
        under_kind = SEC_ASN1_CHOICE;
196
356k
    } else if ((encode_kind & (SEC_ASN1_POINTER | SEC_ASN1_INLINE)) ||
197
345k
               (!universal && !isExplicit)) {
198
10.7k
        const SEC_ASN1Template *subt;
199
10.7k
        void *src = NULL;
200
201
10.7k
        PORT_Assert((encode_kind & (SEC_ASN1_ANY | SEC_ASN1_SKIP)) == 0);
202
203
10.7k
        sec_asn1e_scrub_state(state);
204
205
10.7k
        if (encode_kind & SEC_ASN1_POINTER) {
206
8.64k
            src = *(void **)state->src;
207
8.64k
            state->place = afterPointer;
208
209
8.64k
            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
8.64k
        } else {
224
2.06k
            src = state->src;
225
2.06k
            if (encode_kind & SEC_ASN1_INLINE) {
226
                /* check that there are no extraneous bits */
227
                /* PORT_Assert (encode_kind == SEC_ASN1_INLINE && !optional); */
228
2.06k
                state->place = afterInline;
229
2.06k
                isInline = PR_TRUE;
230
2.06k
            } 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
2.06k
        }
243
244
10.7k
        subt = SEC_ASN1GetSubtemplate(state->theTemplate, state->src, PR_TRUE);
245
10.7k
        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
10.7k
        state = sec_asn1e_push_state(state->top, subt, src, PR_FALSE);
262
10.7k
        if (state == NULL)
263
0
            return state;
264
265
10.7k
        if (universal) {
266
            /*
267
             * This is a POINTER or INLINE; just init based on that
268
             * and we are done.
269
             */
270
10.7k
            return sec_asn1e_init_state_based_on_template(state);
271
10.7k
        }
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
345k
    } else {
291
345k
        under_kind = encode_kind;
292
345k
    }
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
345k
#define UNEXPECTED_FLAGS                                                      \
302
345k
    (SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_SKIP | SEC_ASN1_INNER | \
303
345k
     SEC_ASN1_DYNAMIC | SEC_ASN1_MAY_STREAM | SEC_ASN1_INLINE | SEC_ASN1_POINTER)
304
305
345k
    PORT_Assert((under_kind & UNEXPECTED_FLAGS) == 0);
306
345k
    under_kind &= ~UNEXPECTED_FLAGS;
307
345k
#undef UNEXPECTED_FLAGS
308
309
345k
    if (encode_kind & SEC_ASN1_ANY) {
310
14.5k
        PORT_Assert(encode_kind == under_kind);
311
14.5k
        tag_modifiers = 0;
312
14.5k
        tag_number = 0;
313
14.5k
        is_string = PR_TRUE;
314
331k
    } else {
315
331k
        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
331k
        tag_number = encode_kind & SEC_ASN1_TAGNUM_MASK;
323
324
331k
        is_string = PR_FALSE;
325
331k
        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
37.8k
            case SEC_ASN1_SEQUENCE:
334
37.8k
                tag_modifiers |= SEC_ASN1_CONSTRUCTED;
335
37.8k
                break;
336
3.80k
            case SEC_ASN1_BIT_STRING:
337
3.80k
            case SEC_ASN1_BMP_STRING:
338
3.80k
            case SEC_ASN1_GENERALIZED_TIME:
339
3.80k
            case SEC_ASN1_IA5_STRING:
340
160k
            case SEC_ASN1_OCTET_STRING:
341
160k
            case SEC_ASN1_PRINTABLE_STRING:
342
160k
            case SEC_ASN1_T61_STRING:
343
160k
            case SEC_ASN1_UNIVERSAL_STRING:
344
160k
            case SEC_ASN1_UTC_TIME:
345
160k
            case SEC_ASN1_UTF8_STRING:
346
160k
            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
160k
                is_string = PR_TRUE;
352
160k
                break;
353
331k
        }
354
331k
    }
355
356
345k
    state->tag_modifiers = tag_modifiers;
357
345k
    state->tag_number = (unsigned char)tag_number;
358
345k
    state->underlying_kind = under_kind;
359
345k
    state->isExplicit = isExplicit;
360
345k
    state->may_stream = may_stream;
361
345k
    state->is_string = is_string;
362
345k
    state->optional = optional;
363
345k
    state->disallowStreaming = disallowStreaming;
364
365
345k
    sec_asn1e_scrub_state(state);
366
367
345k
    return state;
368
345k
}
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
919k
{
375
919k
    SEC_ASN1EncoderContext *cx;
376
377
919k
    cx = state->top;
378
919k
    (*cx->output_proc)(cx->output_arg, buf, len, state->depth, part);
379
919k
}
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
327k
{
389
327k
    char byte;
390
391
327k
    byte = (char)value;
392
327k
    sec_asn1e_write_part(state, &byte, 1, SEC_ASN1_Identifier);
393
327k
}
394
395
int
396
SEC_ASN1EncodeLength(unsigned char *buf, int value)
397
327k
{
398
327k
    int lenlen;
399
400
327k
    lenlen = SEC_ASN1LengthLength(value);
401
327k
    if (lenlen == 1) {
402
324k
        buf[0] = value;
403
324k
    } else {
404
3.20k
        int i;
405
406
3.20k
        i = lenlen - 1;
407
3.20k
        buf[0] = 0x80 | i;
408
7.92k
        while (i) {
409
4.72k
            buf[i--] = value;
410
4.72k
            value >>= 8;
411
4.72k
        }
412
3.20k
        PORT_Assert(value == 0);
413
3.20k
    }
414
327k
    return lenlen;
415
327k
}
416
417
static void
418
sec_asn1e_write_length_bytes(sec_asn1e_state *state, unsigned long value,
419
                             PRBool indefinite)
420
327k
{
421
327k
    int lenlen;
422
327k
    unsigned char buf[sizeof(unsigned long) + 1];
423
424
327k
    if (indefinite) {
425
0
        PORT_Assert(value == 0);
426
0
        buf[0] = 0x80;
427
0
        lenlen = 1;
428
327k
    } else {
429
327k
        lenlen = SEC_ASN1EncodeLength(buf, value);
430
327k
    }
431
432
327k
    sec_asn1e_write_part(state, (char *)buf, lenlen, SEC_ASN1_Length);
433
327k
}
434
435
static void
436
sec_asn1e_write_contents_bytes(sec_asn1e_state *state,
437
                               const char *buf, unsigned long len)
438
264k
{
439
264k
    sec_asn1e_write_part(state, buf, len, SEC_ASN1_Contents);
440
264k
}
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
502k
{
472
502k
    unsigned long encode_kind, underlying_kind;
473
502k
    PRBool isExplicit, optional, universal, may_stream;
474
502k
    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
502k
    encode_kind = theTemplate->kind;
492
493
502k
    universal = ((encode_kind & SEC_ASN1_CLASS_MASK) == SEC_ASN1_UNIVERSAL)
494
502k
                    ? PR_TRUE
495
502k
                    : PR_FALSE;
496
497
502k
    isExplicit = (encode_kind & SEC_ASN1_EXPLICIT) ? PR_TRUE : PR_FALSE;
498
502k
    encode_kind &= ~SEC_ASN1_EXPLICIT;
499
500
502k
    optional = (encode_kind & SEC_ASN1_OPTIONAL) ? PR_TRUE : PR_FALSE;
501
502k
    encode_kind &= ~SEC_ASN1_OPTIONAL;
502
503
502k
    PORT_Assert(!(isExplicit && universal)); /* bad templates */
504
505
502k
    may_stream = (encode_kind & SEC_ASN1_MAY_STREAM) ? PR_TRUE : PR_FALSE;
506
502k
    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
502k
    encode_kind &= ~SEC_ASN1_DYNAMIC;
510
511
502k
    if (encode_kind & SEC_ASN1_NO_STREAM) {
512
0
        disallowStreaming = PR_TRUE;
513
0
    }
514
502k
    encode_kind &= ~SEC_ASN1_NO_STREAM;
515
516
502k
    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
502k
    if ((encode_kind & (SEC_ASN1_POINTER | SEC_ASN1_INLINE)) || !universal) {
533
        /* XXX any bits we want to disallow (PORT_Assert against) here? */
534
48.7k
        theTemplate = SEC_ASN1GetSubtemplate(theTemplate, src, PR_TRUE);
535
48.7k
        if (encode_kind & SEC_ASN1_POINTER) {
536
16.2k
            src = *(void **)src;
537
16.2k
            if (src == NULL) {
538
0
                *pHdrException = optional ? hdr_optional : hdr_normal;
539
0
                return 0;
540
0
            }
541
32.5k
        } else if (encode_kind & SEC_ASN1_INLINE) {
542
            /* check that there are no extraneous bits */
543
2.06k
            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
2.06k
        }
559
560
48.7k
        src = (char *)src + theTemplate->offset;
561
562
        /* recurse to find the length of the subtemplate */
563
48.7k
        len = sec_asn1e_contents_length(theTemplate, src, disallowStreaming,
564
48.7k
                                        insideIndefinite, pHdrException);
565
48.7k
        if (len == 0 && optional) {
566
7.60k
            *pHdrException = hdr_optional;
567
41.1k
        } else if (isExplicit) {
568
22.8k
            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
22.8k
            } 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
22.8k
                len += 1 + SEC_ASN1LengthLength(len);
580
22.8k
            }
581
22.8k
        }
582
48.7k
        return len;
583
48.7k
    }
584
453k
    underlying_kind = encode_kind;
585
586
    /* This is only used in decoding; it plays no part in encoding.  */
587
453k
    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
453k
#define UNEXPECTED_FLAGS                                                          \
595
453k
    (SEC_ASN1_EXPLICIT | SEC_ASN1_OPTIONAL | SEC_ASN1_INLINE | SEC_ASN1_POINTER | \
596
453k
     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
453k
    PORT_Assert((underlying_kind & UNEXPECTED_FLAGS) == 0);
600
453k
    underlying_kind &= ~UNEXPECTED_FLAGS;
601
453k
#undef UNEXPECTED_FLAGS
602
603
453k
    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
453k
    } else {
617
453k
        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
56.1k
            case SEC_ASN1_SEQUENCE:
650
56.1k
            case SEC_ASN1_SET: {
651
56.1k
                const SEC_ASN1Template *tmpt;
652
56.1k
                void *sub_src;
653
56.1k
                unsigned long sub_len;
654
655
56.1k
                len = 0;
656
178k
                for (tmpt = theTemplate + 1; tmpt->kind; tmpt++) {
657
122k
                    sub_src = (char *)src + tmpt->offset;
658
122k
                    sub_len = sec_asn1e_contents_length(tmpt, sub_src,
659
122k
                                                        disallowStreaming,
660
122k
                                                        insideIndefinite,
661
122k
                                                        pHdrException);
662
122k
                    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
122k
                    if (*pHdrException == hdr_normal)
668
85.4k
                        len += 1 + SEC_ASN1LengthLength(sub_len);
669
122k
                }
670
56.1k
            } 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
120k
            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
120k
                {
686
120k
                    unsigned char *buf = ((SECItem *)src)->data;
687
120k
                    SECItemType integerType = ((SECItem *)src)->type;
688
120k
                    len = ((SECItem *)src)->len;
689
125k
                    while (len > 0) {
690
118k
                        if (*buf != 0) {
691
43.6k
                            if (*buf & 0x80 && integerType == siUnsignedInteger) {
692
0
                                len++; /* leading zero needed to make number signed */
693
0
                            }
694
43.6k
                            break; /* reached beginning of number */
695
43.6k
                        }
696
74.5k
                        if (len == 1) {
697
47.9k
                            break; /* the number 0 */
698
47.9k
                        }
699
26.5k
                        if (buf[1] & 0x80) {
700
21.3k
                            break; /* leading zero already present */
701
21.3k
                        }
702
                        /* extraneous leading zero, keep going */
703
5.21k
                        buf++;
704
5.21k
                        len--;
705
5.21k
                    }
706
120k
                }
707
120k
                break;
708
709
38.8k
            case SEC_ASN1_NULL:
710
38.8k
                len = 0;
711
38.8k
                break;
712
713
237k
            default:
714
237k
                len = ((SECItem *)src)->len;
715
237k
                break;
716
453k
        } /* end switch */
717
718
453k
#ifndef WHAT_PROBLEM_DOES_THIS_SOLVE
719
        /* if we're streaming, we may have a secitem w/len 0 as placeholder */
720
453k
        if (!len && insideIndefinite && may_stream && !disallowStreaming) {
721
0
            len = 1;
722
0
        }
723
453k
#endif
724
453k
    } /* end else */
725
726
453k
    if (len == 0 && optional)
727
2.06k
        *pHdrException = hdr_optional;
728
451k
    else if (underlying_kind == SEC_ASN1_ANY)
729
30.7k
        *pHdrException = hdr_any;
730
420k
    else
731
420k
        *pHdrException = hdr_normal;
732
733
453k
    return len;
734
453k
}
735
736
static void
737
sec_asn1e_write_header(sec_asn1e_state *state)
738
345k
{
739
345k
    unsigned long contents_length;
740
345k
    unsigned char tag_number, tag_modifiers;
741
345k
    sec_asn1e_hdr_encoding hdrException = hdr_normal;
742
345k
    PRBool indefinite = PR_FALSE;
743
744
345k
    PORT_Assert(state->place == beforeHeader);
745
746
345k
    tag_number = state->tag_number;
747
345k
    tag_modifiers = state->tag_modifiers;
748
749
345k
    if (state->underlying_kind == SEC_ASN1_ANY) {
750
14.5k
        state->place = duringContents;
751
14.5k
        return;
752
14.5k
    }
753
754
331k
    if (state->underlying_kind & SEC_ASN1_CHOICE) {
755
0
        int indx = sec_asn1e_which_choice(state->src, state->theTemplate);
756
0
        if (0 == indx) {
757
            /* XXX set an error? "choice not found" */
758
0
            state->top->status = encodeError;
759
0
            return;
760
0
        }
761
0
        state->place = afterChoice;
762
0
        state = sec_asn1e_push_state(state->top, &state->theTemplate[indx],
763
0
                                     (char *)state->src - state->theTemplate->offset,
764
0
                                     PR_TRUE);
765
0
        if (state) {
766
            /*
767
             * Do the "before" field notification.
768
             */
769
0
            sec_asn1e_notify_before(state->top, state->src, state->depth);
770
0
            (void)sec_asn1e_init_state_based_on_template(state);
771
0
        }
772
0
        return;
773
0
    }
774
775
    /* The !isString test below is apparently intended to ensure that all
776
    ** constructed types receive indefinite length encoding.
777
    */
778
331k
    indefinite = (PRBool)(state->top->streaming && state->may_stream &&
779
0
                          (state->top->from_buf || !state->is_string));
780
781
    /*
782
     * If we are doing a definite-length encoding, first we have to
783
     * walk the data structure to calculate the entire contents length.
784
     * If we are doing an indefinite-length encoding, we still need to
785
     * know if the contents is:
786
     *    optional and to be omitted, or
787
     *    an ANY (header is pre-encoded), or
788
     *    a SAVE or some other kind of template used only by the decoder.
789
     * So, we call this function either way.
790
     */
791
331k
    contents_length = sec_asn1e_contents_length(state->theTemplate,
792
331k
                                                state->src,
793
331k
                                                state->disallowStreaming,
794
331k
                                                indefinite,
795
331k
                                                &hdrException);
796
    /*
797
     * We might be told explicitly not to put out a header.
798
     * But it can also be the case, via a pushed subtemplate, that
799
     * sec_asn1e_contents_length could not know that this field is
800
     * really optional.  So check for that explicitly, too.
801
     */
802
331k
    if (hdrException != hdr_normal ||
803
327k
        (contents_length == 0 && state->optional)) {
804
3.80k
        state->place = afterContents;
805
3.80k
        if (state->top->streaming &&
806
0
            state->may_stream &&
807
0
            state->top->from_buf) {
808
            /* we did not find an optional indefinite string, so we
809
             * don't encode it.  However, if TakeFromBuf is on, we stop
810
             * here anyway to give our caller a chance to intercept at the
811
             * same point where we would stop if the field were present.
812
             */
813
0
            state->top->status = needBytes;
814
0
        }
815
3.80k
        return;
816
3.80k
    }
817
818
327k
    if (indefinite) {
819
        /*
820
         * We need to put out an indefinite-length encoding.
821
         * The only universal types that can be constructed are SETs,
822
         * SEQUENCEs, and strings; so check that it is one of those,
823
         * or that it is not universal (e.g. context-specific).
824
         */
825
0
        state->indefinite = PR_TRUE;
826
0
        PORT_Assert((tag_number == SEC_ASN1_SET) || (tag_number == SEC_ASN1_SEQUENCE) || ((tag_modifiers & SEC_ASN1_CLASS_MASK) != 0) || state->is_string);
827
0
        tag_modifiers |= SEC_ASN1_CONSTRUCTED;
828
0
        contents_length = 0;
829
0
    }
830
831
327k
    sec_asn1e_write_identifier_bytes(state,
832
327k
                                     (unsigned char)(tag_number | tag_modifiers));
833
327k
    sec_asn1e_write_length_bytes(state, contents_length, state->indefinite);
834
835
327k
    if (contents_length == 0 && !state->indefinite) {
836
        /*
837
         * If no real contents to encode, then we are done with this field.
838
         */
839
38.8k
        state->place = afterContents;
840
38.8k
        return;
841
38.8k
    }
842
843
    /*
844
     * An EXPLICIT is nothing but an outer header, which we have already
845
     * written.  Now we need to do the inner header and contents.
846
     */
847
288k
    if (state->isExplicit) {
848
11.4k
        const SEC_ASN1Template *subt =
849
11.4k
            SEC_ASN1GetSubtemplate(state->theTemplate, state->src, PR_TRUE);
850
11.4k
        state->place = afterContents;
851
11.4k
        state = sec_asn1e_push_state(state->top, subt, state->src, PR_TRUE);
852
11.4k
        if (state != NULL) {
853
11.4k
            (void)sec_asn1e_init_state_based_on_template(state);
854
11.4k
        }
855
11.4k
        return;
856
11.4k
    }
857
858
277k
    switch (state->underlying_kind) {
859
0
        case SEC_ASN1_SET_OF:
860
0
        case SEC_ASN1_SEQUENCE_OF:
861
            /*
862
             * We need to push a child to handle each member.
863
             */
864
0
            {
865
0
                void **group;
866
0
                const SEC_ASN1Template *subt;
867
868
0
                group = *(void ***)state->src;
869
0
                if (group == NULL || *group == NULL) {
870
                    /*
871
                     * Group is empty; we are done.
872
                     */
873
0
                    state->place = afterContents;
874
0
                    return;
875
0
                }
876
0
                state->place = duringGroup;
877
0
                subt = SEC_ASN1GetSubtemplate(state->theTemplate, state->src,
878
0
                                              PR_TRUE);
879
0
                state = sec_asn1e_push_state(state->top, subt, *group, PR_TRUE);
880
0
                if (state != NULL) {
881
0
                    (void)sec_asn1e_init_state_based_on_template(state);
882
0
                }
883
0
            }
884
0
            break;
885
886
37.8k
        case SEC_ASN1_SEQUENCE:
887
37.8k
        case SEC_ASN1_SET:
888
            /*
889
             * We need to push a child to handle the individual fields.
890
             */
891
37.8k
            state->place = duringSequence;
892
37.8k
            state = sec_asn1e_push_state(state->top, state->theTemplate + 1,
893
37.8k
                                         state->src, PR_TRUE);
894
37.8k
            if (state != NULL) {
895
                /*
896
                 * Do the "before" field notification.
897
                 */
898
37.8k
                sec_asn1e_notify_before(state->top, state->src, state->depth);
899
37.8k
                (void)sec_asn1e_init_state_based_on_template(state);
900
37.8k
            }
901
37.8k
            break;
902
903
239k
        default:
904
            /*
905
             * I think we do not need to do anything else.
906
             * XXX Correct?
907
             */
908
239k
            state->place = duringContents;
909
239k
            break;
910
277k
    }
911
277k
}
912
913
static void
914
sec_asn1e_write_contents_from_buf(sec_asn1e_state *state,
915
                                  const char *buf, unsigned long len)
916
0
{
917
0
    PORT_Assert(state->place == duringContents);
918
0
    PORT_Assert(state->top->from_buf);
919
0
    PORT_Assert(state->may_stream && !state->disallowStreaming);
920
921
    /*
922
     * Probably they just turned on "take from buf", but have not
923
     * yet given us any bytes.  If there is nothing in the buffer
924
     * then we have nothing to do but return and wait.
925
     */
926
0
    if (buf == NULL || len == 0) {
927
0
        state->top->status = needBytes;
928
0
        return;
929
0
    }
930
    /*
931
     * We are streaming, reading from a passed-in buffer.
932
     * This means we are encoding a simple string or an ANY.
933
     * For the former, we need to put out a substring, with its
934
     * own identifier and length.  For an ANY, we just write it
935
     * out as is (our caller is required to ensure that it
936
     * is a properly encoded entity).
937
     */
938
0
    PORT_Assert(state->is_string); /* includes ANY */
939
0
    if (state->underlying_kind != SEC_ASN1_ANY) {
940
0
        unsigned char identifier;
941
942
        /*
943
         * Create the identifier based on underlying_kind.  We cannot
944
         * use tag_number and tag_modifiers because this can be an
945
         * implicitly encoded field.  In that case, the underlying
946
         * substrings *are* encoded with their real tag.
947
         */
948
0
        identifier = (unsigned char)(state->underlying_kind & SEC_ASN1_TAG_MASK);
949
        /*
950
         * The underlying kind should just be a simple string; there
951
         * should be no bits like CONTEXT_SPECIFIC or CONSTRUCTED set.
952
         */
953
0
        PORT_Assert((identifier & SEC_ASN1_TAGNUM_MASK) == identifier);
954
        /*
955
         * Write out the tag and length for the substring.
956
         */
957
0
        sec_asn1e_write_identifier_bytes(state, identifier);
958
0
        if (state->underlying_kind == SEC_ASN1_BIT_STRING) {
959
0
            char byte;
960
            /*
961
             * Assume we have a length in bytes but we need to output
962
             * a proper bit string.  This interface only works for bit
963
             * strings that are full multiples of 8.  If support for
964
             * real, variable length bit strings is needed then the
965
             * caller will have to know to pass in a bit length instead
966
             * of a byte length and then this code will have to
967
             * perform the encoding necessary (length written is length
968
             * in bytes plus 1, and the first octet of string is the
969
             * number of bits remaining between the end of the bit
970
             * string and the next byte boundary).
971
             */
972
0
            sec_asn1e_write_length_bytes(state, len + 1, PR_FALSE);
973
0
            byte = 0;
974
0
            sec_asn1e_write_contents_bytes(state, &byte, 1);
975
0
        } else {
976
0
            sec_asn1e_write_length_bytes(state, len, PR_FALSE);
977
0
        }
978
0
    }
979
0
    sec_asn1e_write_contents_bytes(state, buf, len);
980
0
    state->top->status = needBytes;
981
0
}
982
983
static void
984
sec_asn1e_write_contents(sec_asn1e_state *state)
985
253k
{
986
253k
    unsigned long len = 0;
987
988
253k
    PORT_Assert(state->place == duringContents);
989
990
253k
    switch (state->underlying_kind) {
991
0
        case SEC_ASN1_SET:
992
0
        case SEC_ASN1_SEQUENCE:
993
0
            PORT_Assert(0);
994
0
            break;
995
996
0
        case SEC_ASN1_BIT_STRING: {
997
0
            SECItem *item;
998
0
            char rem;
999
1000
0
            item = (SECItem *)state->src;
1001
0
            len = (item->len + 7) >> 3;
1002
0
            rem = (unsigned char)((len << 3) - item->len); /* remaining bits */
1003
0
            sec_asn1e_write_contents_bytes(state, &rem, 1);
1004
0
            sec_asn1e_write_contents_bytes(state, (char *)item->data, len);
1005
0
        } break;
1006
1007
0
        case SEC_ASN1_BMP_STRING:
1008
            /* The number of bytes must be divisable by 2 */
1009
0
            if ((((SECItem *)state->src)->len) % 2) {
1010
0
                SEC_ASN1EncoderContext *cx;
1011
1012
0
                cx = state->top;
1013
0
                cx->status = encodeError;
1014
0
                break;
1015
0
            }
1016
            /* otherwise, fall through to write the content */
1017
0
            goto process_string;
1018
1019
0
        case SEC_ASN1_UNIVERSAL_STRING:
1020
            /* The number of bytes must be divisable by 4 */
1021
0
            if ((((SECItem *)state->src)->len) % 4) {
1022
0
                SEC_ASN1EncoderContext *cx;
1023
1024
0
                cx = state->top;
1025
0
                cx->status = encodeError;
1026
0
                break;
1027
0
            }
1028
            /* otherwise, fall through to write the content */
1029
0
            goto process_string;
1030
1031
68.2k
        case SEC_ASN1_INTEGER:
1032
            /* ASN.1 INTEGERs are signed.  If the source is an unsigned
1033
             * integer, the encoder will need to handle the conversion here.
1034
             */
1035
68.2k
            {
1036
68.2k
                unsigned int blen;
1037
68.2k
                unsigned char *buf;
1038
68.2k
                SECItemType integerType;
1039
68.2k
                blen = ((SECItem *)state->src)->len;
1040
68.2k
                buf = ((SECItem *)state->src)->data;
1041
68.2k
                integerType = ((SECItem *)state->src)->type;
1042
83.5k
                while (blen > 0) {
1043
83.5k
                    if (*buf & 0x80 && integerType == siUnsignedInteger) {
1044
10.0k
                        char zero = 0; /* write a leading 0 */
1045
10.0k
                        sec_asn1e_write_contents_bytes(state, &zero, 1);
1046
                        /* and then the remaining buffer */
1047
10.0k
                        sec_asn1e_write_contents_bytes(state,
1048
10.0k
                                                       (char *)buf, blen);
1049
10.0k
                        break;
1050
10.0k
                    }
1051
                    /* Check three possibilities:
1052
                     * 1.  No leading zeros, msb of MSB is not 1;
1053
                     * 2.  The number is zero itself;
1054
                     * 3.  Encoding a signed integer with a leading zero,
1055
                     *     keep the zero so that the number is positive.
1056
                     */
1057
73.4k
                    if (*buf != 0 ||
1058
50.6k
                        blen == 1 ||
1059
58.1k
                        (buf[1] & 0x80 && integerType != siUnsignedInteger)) {
1060
58.1k
                        sec_asn1e_write_contents_bytes(state,
1061
58.1k
                                                       (char *)buf, blen);
1062
58.1k
                        break;
1063
58.1k
                    }
1064
                    /* byte is 0, continue */
1065
15.2k
                    buf++;
1066
15.2k
                    blen--;
1067
15.2k
                }
1068
68.2k
            }
1069
            /* done with this content */
1070
68.2k
            break;
1071
1072
0
        process_string:
1073
185k
        default: {
1074
185k
            SECItem *item;
1075
1076
185k
            item = (SECItem *)state->src;
1077
185k
            sec_asn1e_write_contents_bytes(state, (char *)item->data,
1078
185k
                                           item->len);
1079
185k
        } break;
1080
253k
    }
1081
253k
    state->place = afterContents;
1082
253k
}
1083
1084
/*
1085
 * We are doing a SET OF or SEQUENCE OF, and have just finished an item.
1086
 */
1087
static void
1088
sec_asn1e_next_in_group(sec_asn1e_state *state)
1089
0
{
1090
0
    sec_asn1e_state *child;
1091
0
    void **group;
1092
0
    void *member;
1093
1094
0
    PORT_Assert(state->place == duringGroup);
1095
0
    PORT_Assert(state->child != NULL);
1096
1097
0
    child = state->child;
1098
1099
0
    group = *(void ***)state->src;
1100
1101
    /*
1102
     * Find placement of current item.
1103
     */
1104
0
    member = (char *)(state->child->src) - child->theTemplate->offset;
1105
0
    while (*group != member)
1106
0
        group++;
1107
1108
    /*
1109
     * Move forward to next item.
1110
     */
1111
0
    group++;
1112
0
    if (*group == NULL) {
1113
        /*
1114
         * That was our last one; we are done now.
1115
         */
1116
0
        child->place = notInUse;
1117
0
        state->place = afterContents;
1118
0
        return;
1119
0
    }
1120
0
    child->src = (char *)(*group) + child->theTemplate->offset;
1121
1122
    /*
1123
     * Re-"push" child.
1124
     */
1125
0
    sec_asn1e_scrub_state(child);
1126
0
    state->top->current = child;
1127
0
}
1128
1129
/*
1130
 * We are moving along through a sequence; move forward by one,
1131
 * (detecting end-of-sequence when it happens).
1132
 */
1133
static void
1134
sec_asn1e_next_in_sequence(sec_asn1e_state *state)
1135
85.4k
{
1136
85.4k
    sec_asn1e_state *child;
1137
1138
85.4k
    PORT_Assert(state->place == duringSequence);
1139
85.4k
    PORT_Assert(state->child != NULL);
1140
1141
85.4k
    child = state->child;
1142
1143
    /*
1144
     * Do the "after" field notification.
1145
     */
1146
85.4k
    sec_asn1e_notify_after(state->top, child->src, child->depth);
1147
1148
    /*
1149
     * Move forward.
1150
     */
1151
85.4k
    child->theTemplate++;
1152
85.4k
    if (child->theTemplate->kind == 0) {
1153
        /*
1154
         * We are done with this sequence.
1155
         */
1156
37.8k
        child->place = notInUse;
1157
37.8k
        state->place = afterContents;
1158
37.8k
        return;
1159
37.8k
    }
1160
1161
    /*
1162
     * Reset state and push.
1163
     */
1164
1165
47.5k
    child->src = (char *)state->src + child->theTemplate->offset;
1166
1167
    /*
1168
     * Do the "before" field notification.
1169
     */
1170
47.5k
    sec_asn1e_notify_before(state->top, child->src, child->depth);
1171
1172
47.5k
    state->top->current = child;
1173
47.5k
    (void)sec_asn1e_init_state_based_on_template(child);
1174
47.5k
}
1175
1176
static void
1177
sec_asn1e_after_contents(sec_asn1e_state *state)
1178
356k
{
1179
356k
    PORT_Assert(state->place == afterContents);
1180
1181
356k
    if (state->indefinite)
1182
0
        sec_asn1e_write_end_of_contents_bytes(state);
1183
1184
    /*
1185
     * Just make my parent be the current state.  It will then clean
1186
     * up after me and free me (or reuse me).
1187
     */
1188
356k
    state->top->current = state->parent;
1189
356k
}
1190
1191
/*
1192
 * This function is called whether or not we are streaming; if we
1193
 * *are* streaming, our caller can also instruct us to take bytes
1194
 * from the passed-in buffer (at buf, for length len, which is likely
1195
 * bytes but could even mean bits if the current field is a bit string).
1196
 * If we have been so instructed, we will gobble up bytes from there
1197
 * (rather than from our src structure) and output them, and then
1198
 * we will just return, expecting to be called again -- either with
1199
 * more bytes or after our caller has instructed us that we are done
1200
 * (for now) with the buffer.
1201
 */
1202
SECStatus
1203
SEC_ASN1EncoderUpdate(SEC_ASN1EncoderContext *cx,
1204
                      const char *buf, unsigned long len)
1205
249k
{
1206
249k
    sec_asn1e_state *state;
1207
1208
249k
    if (cx->status == needBytes) {
1209
0
        cx->status = keepGoing;
1210
0
    }
1211
1212
1.05M
    while (cx->status == keepGoing) {
1213
1.05M
        state = cx->current;
1214
1.05M
        switch (state->place) {
1215
345k
            case beforeHeader:
1216
345k
                sec_asn1e_write_header(state);
1217
345k
                break;
1218
253k
            case duringContents:
1219
253k
                if (cx->from_buf)
1220
0
                    sec_asn1e_write_contents_from_buf(state, buf, len);
1221
253k
                else
1222
253k
                    sec_asn1e_write_contents(state);
1223
253k
                break;
1224
0
            case duringGroup:
1225
0
                sec_asn1e_next_in_group(state);
1226
0
                break;
1227
85.4k
            case duringSequence:
1228
85.4k
                sec_asn1e_next_in_sequence(state);
1229
85.4k
                break;
1230
356k
            case afterContents:
1231
356k
                sec_asn1e_after_contents(state);
1232
356k
                break;
1233
0
            case afterImplicit:
1234
2.06k
            case afterInline:
1235
10.7k
            case afterPointer:
1236
10.7k
            case afterChoice:
1237
                /*
1238
                 * These states are more documentation than anything.
1239
                 * They just need to force a pop.
1240
                 */
1241
10.7k
                PORT_Assert(!state->indefinite);
1242
10.7k
                state->place = afterContents;
1243
10.7k
                break;
1244
0
            case notInUse:
1245
0
            default:
1246
                /* This is not an error, but rather a plain old BUG! */
1247
0
                PORT_Assert(0);
1248
0
                cx->status = encodeError;
1249
0
                break;
1250
1.05M
        }
1251
1252
1.05M
        if (cx->status == encodeError)
1253
0
            break;
1254
1255
        /* It might have changed, so we have to update our local copy.  */
1256
1.05M
        state = cx->current;
1257
1258
        /* If it is NULL, we have popped all the way to the top.  */
1259
1.05M
        if (state == NULL) {
1260
249k
            cx->status = allDone;
1261
249k
            break;
1262
249k
        }
1263
1.05M
    }
1264
1265
249k
    if (cx->status == encodeError) {
1266
0
        return SECFailure;
1267
0
    }
1268
1269
249k
    return SECSuccess;
1270
249k
}
1271
1272
void
1273
SEC_ASN1EncoderFinish(SEC_ASN1EncoderContext *cx)
1274
249k
{
1275
    /*
1276
     * XXX anything else that needs to be finished?
1277
     */
1278
1279
249k
    PORT_FreeArena(cx->our_pool, PR_FALSE);
1280
249k
}
1281
1282
SEC_ASN1EncoderContext *
1283
SEC_ASN1EncoderStart(const void *src, const SEC_ASN1Template *theTemplate,
1284
                     SEC_ASN1WriteProc output_proc, void *output_arg)
1285
249k
{
1286
249k
    PLArenaPool *our_pool;
1287
249k
    SEC_ASN1EncoderContext *cx;
1288
1289
249k
    our_pool = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
1290
249k
    if (our_pool == NULL)
1291
0
        return NULL;
1292
1293
249k
    cx = (SEC_ASN1EncoderContext *)PORT_ArenaZAlloc(our_pool, sizeof(*cx));
1294
249k
    if (cx == NULL) {
1295
0
        PORT_FreeArena(our_pool, PR_FALSE);
1296
0
        return NULL;
1297
0
    }
1298
1299
249k
    cx->our_pool = our_pool;
1300
249k
    cx->output_proc = output_proc;
1301
249k
    cx->output_arg = output_arg;
1302
1303
249k
    cx->status = keepGoing;
1304
1305
249k
    if (sec_asn1e_push_state(cx, theTemplate, src, PR_FALSE) == NULL ||
1306
249k
        sec_asn1e_init_state_based_on_template(cx->current) == NULL) {
1307
        /*
1308
         * Trouble initializing (probably due to failed allocations)
1309
         * requires that we just give up.
1310
         */
1311
0
        PORT_FreeArena(our_pool, PR_FALSE);
1312
0
        return NULL;
1313
0
    }
1314
1315
249k
    return cx;
1316
249k
}
1317
1318
/*
1319
 * XXX Do we need a FilterProc, too?
1320
 */
1321
1322
void
1323
SEC_ASN1EncoderSetNotifyProc(SEC_ASN1EncoderContext *cx,
1324
                             SEC_ASN1NotifyProc fn, void *arg)
1325
0
{
1326
0
    cx->notify_proc = fn;
1327
0
    cx->notify_arg = arg;
1328
0
}
1329
1330
void
1331
SEC_ASN1EncoderClearNotifyProc(SEC_ASN1EncoderContext *cx)
1332
0
{
1333
0
    cx->notify_proc = NULL;
1334
0
    cx->notify_arg = NULL; /* not necessary; just being clean */
1335
0
}
1336
1337
void
1338
SEC_ASN1EncoderAbort(SEC_ASN1EncoderContext *cx, int error)
1339
0
{
1340
0
    PORT_Assert(cx);
1341
0
    PORT_SetError(error);
1342
0
    cx->status = encodeError;
1343
0
}
1344
1345
void
1346
SEC_ASN1EncoderSetStreaming(SEC_ASN1EncoderContext *cx)
1347
0
{
1348
    /* XXX is there a way to check that we are "between" fields here? */
1349
1350
0
    cx->streaming = PR_TRUE;
1351
0
}
1352
1353
void
1354
SEC_ASN1EncoderClearStreaming(SEC_ASN1EncoderContext *cx)
1355
0
{
1356
    /* XXX is there a way to check that we are "between" fields here? */
1357
1358
0
    cx->streaming = PR_FALSE;
1359
0
}
1360
1361
void
1362
SEC_ASN1EncoderSetTakeFromBuf(SEC_ASN1EncoderContext *cx)
1363
0
{
1364
    /*
1365
     * XXX is there a way to check that we are "between" fields here?  this
1366
     * needs to include a check for being in between groups of items in
1367
     * a SET_OF or SEQUENCE_OF.
1368
     */
1369
0
    PORT_Assert(cx->streaming);
1370
1371
0
    cx->from_buf = PR_TRUE;
1372
0
}
1373
1374
void
1375
SEC_ASN1EncoderClearTakeFromBuf(SEC_ASN1EncoderContext *cx)
1376
0
{
1377
    /* we should actually be taking from buf *now* */
1378
0
    PORT_Assert(cx->from_buf);
1379
0
    if (!cx->from_buf) /* if not, just do nothing */
1380
0
        return;
1381
1382
0
    cx->from_buf = PR_FALSE;
1383
1384
0
    if (cx->status == needBytes) {
1385
0
        cx->status = keepGoing;
1386
0
        cx->current->place = afterContents;
1387
0
    }
1388
0
}
1389
1390
SECStatus
1391
SEC_ASN1Encode(const void *src, const SEC_ASN1Template *theTemplate,
1392
               SEC_ASN1WriteProc output_proc, void *output_arg)
1393
249k
{
1394
249k
    SEC_ASN1EncoderContext *ecx;
1395
249k
    SECStatus rv;
1396
1397
249k
    ecx = SEC_ASN1EncoderStart(src, theTemplate, output_proc, output_arg);
1398
249k
    if (ecx == NULL)
1399
0
        return SECFailure;
1400
1401
249k
    rv = SEC_ASN1EncoderUpdate(ecx, NULL, 0);
1402
1403
249k
    SEC_ASN1EncoderFinish(ecx);
1404
249k
    return rv;
1405
249k
}
1406
1407
/*
1408
 * XXX depth and data_kind are unused; is there a PC way to silence warnings?
1409
 * (I mean "politically correct", not anything to do with intel/win platform)
1410
 */
1411
static void
1412
sec_asn1e_encode_item_count(void *arg, const char *buf, unsigned long len,
1413
                            int depth, SEC_ASN1EncodingPart data_kind)
1414
459k
{
1415
459k
    unsigned long *count;
1416
1417
459k
    count = (unsigned long *)arg;
1418
459k
    PORT_Assert(count != NULL);
1419
1420
459k
    *count += len;
1421
459k
}
1422
1423
/* XXX depth and data_kind are unused; is there a PC way to silence warnings? */
1424
static void
1425
sec_asn1e_encode_item_store(void *arg, const char *buf, unsigned long len,
1426
                            int depth, SEC_ASN1EncodingPart data_kind)
1427
459k
{
1428
459k
    SECItem *dest;
1429
1430
459k
    dest = (SECItem *)arg;
1431
459k
    PORT_Assert(dest != NULL);
1432
1433
459k
    if (len > 0) {
1434
459k
        PORT_Memcpy(dest->data + dest->len, buf, len);
1435
459k
        dest->len += len;
1436
459k
    }
1437
459k
}
1438
1439
/*
1440
 * Allocate an entire SECItem, or just the data part of it, to hold
1441
 * "len" bytes of stuff.  Allocate from the given pool, if specified,
1442
 * otherwise just do a vanilla PORT_Alloc.
1443
 *
1444
 * XXX This seems like a reasonable general-purpose function (for SECITEM_)?
1445
 */
1446
static SECItem *
1447
sec_asn1e_allocate_item(PLArenaPool *poolp, SECItem *dest, unsigned long len)
1448
127k
{
1449
127k
    if (poolp != NULL) {
1450
7.77k
        void *release;
1451
1452
7.77k
        release = PORT_ArenaMark(poolp);
1453
7.77k
        if (dest == NULL)
1454
3.80k
            dest = (SECItem *)PORT_ArenaAlloc(poolp, sizeof(SECItem));
1455
7.77k
        if (dest != NULL) {
1456
7.77k
            dest->data = (unsigned char *)PORT_ArenaAlloc(poolp, len);
1457
7.77k
            if (dest->data == NULL) {
1458
0
                dest = NULL;
1459
0
            }
1460
7.77k
        }
1461
7.77k
        if (dest == NULL) {
1462
            /* one or both allocations failed; release everything */
1463
0
            PORT_ArenaRelease(poolp, release);
1464
7.77k
        } else {
1465
            /* everything okay; unmark the arena */
1466
7.77k
            PORT_ArenaUnmark(poolp, release);
1467
7.77k
        }
1468
119k
    } else {
1469
119k
        SECItem *indest;
1470
1471
119k
        indest = dest;
1472
119k
        if (dest == NULL)
1473
110k
            dest = (SECItem *)PORT_Alloc(sizeof(SECItem));
1474
119k
        if (dest != NULL) {
1475
119k
            dest->type = siBuffer;
1476
119k
            dest->data = (unsigned char *)PORT_Alloc(len);
1477
119k
            if (dest->data == NULL) {
1478
0
                if (indest == NULL)
1479
0
                    PORT_Free(dest);
1480
0
                dest = NULL;
1481
0
            }
1482
119k
        }
1483
119k
    }
1484
1485
127k
    return dest;
1486
127k
}
1487
1488
SECItem *
1489
SEC_ASN1EncodeItem(PLArenaPool *poolp, SECItem *dest, const void *src,
1490
                   const SEC_ASN1Template *theTemplate)
1491
124k
{
1492
124k
    unsigned long encoding_length;
1493
124k
    SECStatus rv;
1494
1495
124k
    PORT_Assert(dest == NULL || dest->data == NULL);
1496
1497
124k
    encoding_length = 0;
1498
124k
    rv = SEC_ASN1Encode(src, theTemplate,
1499
124k
                        sec_asn1e_encode_item_count, &encoding_length);
1500
124k
    if (rv != SECSuccess)
1501
0
        return NULL;
1502
1503
124k
    dest = sec_asn1e_allocate_item(poolp, dest, encoding_length);
1504
124k
    if (dest == NULL)
1505
0
        return NULL;
1506
1507
    /* XXX necessary?  This really just checks for a bug in the allocate fn */
1508
124k
    PORT_Assert(dest->data != NULL);
1509
124k
    if (dest->data == NULL)
1510
0
        return NULL;
1511
1512
124k
    dest->len = 0;
1513
124k
    (void)SEC_ASN1Encode(src, theTemplate, sec_asn1e_encode_item_store, dest);
1514
1515
124k
    PORT_Assert(encoding_length == dest->len);
1516
124k
    return dest;
1517
124k
}
1518
1519
static SECItem *
1520
sec_asn1e_integer(PLArenaPool *poolp, SECItem *dest, unsigned long value,
1521
                  PRBool is_unsigned)
1522
2.93k
{
1523
2.93k
    unsigned long copy;
1524
2.93k
    unsigned char sign;
1525
2.93k
    int len = 0;
1526
1527
    /*
1528
     * Determine the length of the encoded value (minimum of 1).
1529
     */
1530
2.93k
    copy = value;
1531
3.14k
    do {
1532
3.14k
        len++;
1533
3.14k
        sign = (unsigned char)(copy & 0x80);
1534
3.14k
        copy >>= 8;
1535
3.14k
    } while (copy);
1536
1537
    /*
1538
     * If 'value' is non-negative, and the high bit of the last
1539
     * byte we counted was set, we need to add one to the length so
1540
     * we put a high-order zero byte in the encoding.
1541
     */
1542
2.93k
    if (sign && (is_unsigned || (long)value >= 0))
1543
205
        len++;
1544
1545
    /*
1546
     * Allocate the item (if necessary) and the data pointer within.
1547
     */
1548
2.93k
    dest = sec_asn1e_allocate_item(poolp, dest, len);
1549
2.93k
    if (dest == NULL)
1550
0
        return NULL;
1551
1552
    /*
1553
     * Store the value, byte by byte, in the item.
1554
     */
1555
2.93k
    dest->len = len;
1556
6.28k
    while (len) {
1557
3.35k
        dest->data[--len] = (unsigned char)value;
1558
3.35k
        value >>= 8;
1559
3.35k
    }
1560
2.93k
    PORT_Assert(value == 0);
1561
1562
2.93k
    return dest;
1563
2.93k
}
1564
1565
SECItem *
1566
SEC_ASN1EncodeInteger(PLArenaPool *poolp, SECItem *dest, long value)
1567
2.93k
{
1568
2.93k
    return sec_asn1e_integer(poolp, dest, (unsigned long)value, PR_FALSE);
1569
2.93k
}
1570
1571
SECItem *
1572
SEC_ASN1EncodeUnsignedInteger(PLArenaPool *poolp,
1573
                              SECItem *dest, unsigned long value)
1574
0
{
1575
0
    return sec_asn1e_integer(poolp, dest, value, PR_TRUE);
1576
0
}