Coverage Report

Created: 2025-12-20 07:02

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/nss/lib/pkcs7/p7decode.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
 * PKCS7 decoding, verification.
7
 */
8
9
#include "p7local.h"
10
11
#include "cert.h"
12
/* XXX do not want to have to include */
13
#include "certdb.h" /* certdb.h -- the trust stuff needed by */
14
                    /* the add certificate code needs to get */
15
                    /* rewritten/abstracted and then this */
16
                    /* include should be removed! */
17
/*#include "cdbhdl.h" */
18
#include "cryptohi.h"
19
#include "keyhi.h"
20
#include "secasn1.h"
21
#include "secitem.h"
22
#include "secoid.h"
23
#include "pk11func.h"
24
#include "prtime.h"
25
#include "secerr.h"
26
#include "sechash.h" /* for HASH_GetHashObject() */
27
#include "secder.h"
28
#include "secpkcs5.h"
29
30
struct sec_pkcs7_decoder_worker {
31
    int depth;
32
    int digcnt;
33
    void **digcxs;
34
    const SECHashObject **digobjs;
35
    sec_PKCS7CipherObject *decryptobj;
36
    PRBool saw_contents;
37
};
38
39
struct SEC_PKCS7DecoderContextStr {
40
    SEC_ASN1DecoderContext *dcx;
41
    SEC_PKCS7ContentInfo *cinfo;
42
    SEC_PKCS7DecoderContentCallback cb;
43
    void *cb_arg;
44
    SECKEYGetPasswordKey pwfn;
45
    void *pwfn_arg;
46
    struct sec_pkcs7_decoder_worker worker;
47
    PLArenaPool *tmp_poolp;
48
    int error;
49
    SEC_PKCS7GetDecryptKeyCallback dkcb;
50
    void *dkcb_arg;
51
    SEC_PKCS7DecryptionAllowedCallback decrypt_allowed_cb;
52
};
53
54
/*
55
 * Handle one worker, decrypting and digesting the data as necessary.
56
 *
57
 * XXX If/when we support nested contents, this probably needs to be
58
 * revised somewhat to get passed the content-info (which unfortunately
59
 * can be two different types depending on whether it is encrypted or not)
60
 * corresponding to the given worker.
61
 */
62
static void
63
sec_pkcs7_decoder_work_data(SEC_PKCS7DecoderContext *p7dcx,
64
                            struct sec_pkcs7_decoder_worker *worker,
65
                            const unsigned char *data, unsigned long len,
66
                            PRBool final)
67
245k
{
68
245k
    unsigned char *buf = NULL;
69
245k
    PRBool freeBuf = PR_FALSE;
70
245k
    SECStatus rv;
71
245k
    int i;
72
73
    /*
74
     * We should really have data to process, or we should be trying
75
     * to finish/flush the last block.  (This is an overly paranoid
76
     * check since all callers are in this file and simple inspection
77
     * proves they do it right.  But it could find a bug in future
78
     * modifications/development, that is why it is here.)
79
     */
80
245k
    PORT_Assert((data != NULL && len) || final);
81
82
    /*
83
     * Decrypt this chunk.
84
     *
85
     * XXX If we get an error, we do not want to do the digest or callback,
86
     * but we want to keep decoding.  Or maybe we want to stop decoding
87
     * altogether if there is a callback, because obviously we are not
88
     * sending the data back and they want to know that.
89
     */
90
245k
    if (worker->decryptobj != NULL) {
91
        /* XXX the following lengths should all be longs? */
92
74
        unsigned int inlen;  /* length of data being decrypted */
93
74
        unsigned int outlen; /* length of decrypted data */
94
74
        unsigned int buflen; /* length available for decrypted data */
95
74
        SECItem *plain;
96
97
74
        inlen = len;
98
74
        buflen = sec_PKCS7DecryptLength(worker->decryptobj, inlen, final);
99
74
        if (buflen == 0) {
100
19
            if (inlen == 0) /* no input and no output */
101
1
                return;
102
            /*
103
             * No output is expected, but the input data may be buffered
104
             * so we still have to call Decrypt.
105
             */
106
18
            rv = sec_PKCS7Decrypt(worker->decryptobj, NULL, NULL, 0,
107
18
                                  data, inlen, final);
108
18
            if (rv != SECSuccess) {
109
0
                p7dcx->error = PORT_GetError();
110
0
                return; /* XXX indicate error? */
111
0
            }
112
18
            return;
113
18
        }
114
115
55
        if (p7dcx->cb != NULL) {
116
55
            buf = (unsigned char *)PORT_Alloc(buflen);
117
55
            freeBuf = PR_TRUE;
118
55
            plain = NULL;
119
55
        } else {
120
0
            unsigned long oldlen;
121
122
            /*
123
             * XXX This assumes one level of content only.
124
             * See comment above about nested content types.
125
             * XXX Also, it should work for signedAndEnvelopedData, too!
126
             */
127
0
            plain = &(p7dcx->cinfo->content.envelopedData->encContentInfo.plainContent);
128
129
0
            oldlen = plain->len;
130
0
            if (oldlen == 0) {
131
0
                buf = (unsigned char *)PORT_ArenaAlloc(p7dcx->cinfo->poolp,
132
0
                                                       buflen);
133
0
            } else {
134
0
                buf = (unsigned char *)PORT_ArenaGrow(p7dcx->cinfo->poolp,
135
0
                                                      plain->data,
136
0
                                                      oldlen, oldlen + buflen);
137
0
                if (buf != NULL)
138
0
                    buf += oldlen;
139
0
            }
140
0
            plain->data = buf;
141
0
        }
142
55
        if (buf == NULL) {
143
0
            p7dcx->error = SEC_ERROR_NO_MEMORY;
144
0
            return; /* XXX indicate error? */
145
0
        }
146
55
        rv = sec_PKCS7Decrypt(worker->decryptobj, buf, &outlen, buflen,
147
55
                              data, inlen, final);
148
55
        if (rv != SECSuccess) {
149
0
            p7dcx->error = PORT_GetError();
150
0
            goto cleanup; /* XXX indicate error? */
151
0
        }
152
55
        if (plain != NULL) {
153
0
            PORT_Assert(final || outlen == buflen);
154
0
            plain->len += outlen;
155
0
        }
156
55
        data = buf;
157
55
        len = outlen;
158
55
    }
159
160
    /*
161
     * Update the running digests.
162
     */
163
245k
    if (len) {
164
245k
        for (i = 0; i < worker->digcnt; i++) {
165
339
            (*worker->digobjs[i]->update)(worker->digcxs[i], data, len);
166
339
        }
167
245k
    }
168
169
    /*
170
     * Pass back the contents bytes, and free the temporary buffer.
171
     */
172
245k
    if (p7dcx->cb != NULL) {
173
245k
        if (len)
174
245k
            (*p7dcx->cb)(p7dcx->cb_arg, (const char *)data, len);
175
245k
    }
176
177
245k
cleanup:
178
245k
    if (freeBuf && buf != NULL) {
179
55
        PORT_Free(buf);
180
55
    }
181
245k
}
182
183
static void
184
sec_pkcs7_decoder_filter(void *arg, const char *data, unsigned long len,
185
                         int depth, SEC_ASN1EncodingPart data_kind)
186
740k
{
187
740k
    SEC_PKCS7DecoderContext *p7dcx;
188
740k
    struct sec_pkcs7_decoder_worker *worker;
189
190
    /*
191
     * Since we do not handle any nested contents, the only bytes we
192
     * are really interested in are the actual contents bytes (not
193
     * the identifier, length, or end-of-contents bytes).  If we were
194
     * handling nested types we would probably need to do something
195
     * smarter based on depth and data_kind.
196
     */
197
740k
    if (data_kind != SEC_ASN1_Contents)
198
494k
        return;
199
200
    /*
201
     * The ASN.1 decoder should not even call us with a length of 0.
202
     * Just being paranoid.
203
     */
204
245k
    PORT_Assert(len);
205
245k
    if (len == 0)
206
0
        return;
207
208
245k
    p7dcx = (SEC_PKCS7DecoderContext *)arg;
209
210
    /*
211
     * Handling nested contents would mean that there is a chain
212
     * of workers -- one per each level of content.  The following
213
     * would start with the first worker and loop over them.
214
     */
215
245k
    worker = &(p7dcx->worker);
216
217
245k
    worker->saw_contents = PR_TRUE;
218
219
245k
    sec_pkcs7_decoder_work_data(p7dcx, worker,
220
245k
                                (const unsigned char *)data, len, PR_FALSE);
221
245k
}
222
223
/*
224
 * Create digest contexts for each algorithm in "digestalgs".
225
 * No algorithms is not an error, we just do not do anything.
226
 * An error (like trouble allocating memory), marks the error
227
 * in "p7dcx" and returns SECFailure, which means that our caller
228
 * should just give up altogether.
229
 */
230
static SECStatus
231
sec_pkcs7_decoder_start_digests(SEC_PKCS7DecoderContext *p7dcx, int depth,
232
                                SECAlgorithmID **digestalgs)
233
20
{
234
20
    int i, digcnt;
235
236
20
    p7dcx->worker.digcnt = 0;
237
238
20
    if (digestalgs == NULL)
239
0
        return SECSuccess;
240
241
    /*
242
     * Count the algorithms.
243
     */
244
20
    digcnt = 0;
245
50
    while (digestalgs[digcnt] != NULL)
246
30
        digcnt++;
247
248
    /*
249
     * No algorithms means no work to do.
250
     * Just act as if there were no algorithms specified.
251
     */
252
20
    if (digcnt == 0)
253
0
        return SECSuccess;
254
255
20
    p7dcx->worker.digcxs = (void **)PORT_ArenaAlloc(p7dcx->tmp_poolp,
256
20
                                                    digcnt * sizeof(void *));
257
20
    p7dcx->worker.digobjs = (const SECHashObject **)PORT_ArenaAlloc(p7dcx->tmp_poolp,
258
20
                                                                    digcnt * sizeof(SECHashObject *));
259
20
    if (p7dcx->worker.digcxs == NULL || p7dcx->worker.digobjs == NULL) {
260
0
        p7dcx->error = SEC_ERROR_NO_MEMORY;
261
0
        return SECFailure;
262
0
    }
263
264
20
    p7dcx->worker.depth = depth;
265
266
    /*
267
     * Create a digest context for each algorithm.
268
     */
269
50
    for (i = 0; i < digcnt; i++) {
270
30
        SECAlgorithmID *algid = digestalgs[i];
271
30
        SECOidTag oidTag = SECOID_FindOIDTag(&(algid->algorithm));
272
30
        const SECHashObject *digobj = HASH_GetHashObjectByOidTag(oidTag);
273
30
        void *digcx;
274
275
        /*
276
         * Skip any algorithm we do not even recognize; obviously,
277
         * this could be a problem, but if it is critical then the
278
         * result will just be that the signature does not verify.
279
         * We do not necessarily want to error out here, because
280
         * the particular algorithm may not actually be important,
281
         * but we cannot know that until later.
282
         */
283
30
        if (digobj == NULL) {
284
1
            continue;
285
1
        }
286
287
29
        digcx = (*digobj->create)();
288
29
        if (digcx != NULL) {
289
29
            (*digobj->begin)(digcx);
290
29
            p7dcx->worker.digobjs[p7dcx->worker.digcnt] = digobj;
291
29
            p7dcx->worker.digcxs[p7dcx->worker.digcnt] = digcx;
292
29
            p7dcx->worker.digcnt++;
293
29
        }
294
29
    }
295
296
20
    if (p7dcx->worker.digcnt != 0)
297
20
        SEC_ASN1DecoderSetFilterProc(p7dcx->dcx,
298
20
                                     sec_pkcs7_decoder_filter,
299
20
                                     p7dcx,
300
20
                                     (PRBool)(p7dcx->cb != NULL));
301
20
    return SECSuccess;
302
20
}
303
304
/* destroy any active digest contexts without harvesting results */
305
static void
306
sec_pkcs7_decoder_abort_digests(struct sec_pkcs7_decoder_worker *worker)
307
464k
{
308
464k
    int i;
309
310
464k
    if (!worker || worker->digcnt <= 0 || !worker->digcxs || !worker->digobjs) {
311
464k
        worker->digcnt = 0;
312
464k
        return;
313
464k
    }
314
315
25
    for (i = 0; i < worker->digcnt; i++) {
316
14
        if (worker->digcxs[i] && worker->digobjs[i]) {
317
14
            (*worker->digobjs[i]->destroy)(worker->digcxs[i], PR_TRUE);
318
14
        }
319
14
        worker->digcxs[i] = NULL;
320
14
    }
321
322
11
    worker->digcnt = 0;
323
11
}
324
325
/*
326
 * Close out all of the digest contexts, storing the results in "digestsp".
327
 */
328
static SECStatus
329
sec_pkcs7_decoder_finish_digests(SEC_PKCS7DecoderContext *p7dcx,
330
                                 PLArenaPool *poolp,
331
                                 SECItem ***digestsp)
332
9
{
333
    /*
334
     * XXX Handling nested contents would mean that there is a chain
335
     * of workers -- one per each level of content.  The following
336
     * would want to find the last worker in the chain.
337
     */
338
9
    struct sec_pkcs7_decoder_worker *worker = &(p7dcx->worker);
339
340
    /*
341
     * If no digests, then we have nothing to do.
342
     */
343
9
    if (worker->digcnt == 0) {
344
0
        return SECSuccess;
345
0
    }
346
347
    /*
348
     * No matter what happens after this, we want to stop filtering.
349
     * XXX If we handle nested contents, we only want to stop filtering
350
     * if we are finishing off the *last* worker.
351
     */
352
9
    SEC_ASN1DecoderClearFilterProc(p7dcx->dcx);
353
354
    /*
355
     * If we ended up with no contents, just destroy each
356
     * digest context -- they are meaningless and potentially
357
     * confusing, because their presence would imply some content
358
     * was digested.
359
     */
360
9
    if (!worker->saw_contents) {
361
0
        sec_pkcs7_decoder_abort_digests(worker);
362
0
        return SECSuccess;
363
0
    }
364
365
9
    void *mark = PORT_ArenaMark(poolp);
366
367
    /*
368
     * Close out each digest context, saving digest away.
369
     */
370
9
    SECItem **digests =
371
9
        (SECItem **)PORT_ArenaZAlloc(poolp, (worker->digcnt + 1) * sizeof(SECItem *));
372
9
    if (digests == NULL) {
373
0
        p7dcx->error = PORT_GetError();
374
0
        sec_pkcs7_decoder_abort_digests(worker);
375
0
        PORT_ArenaRelease(poolp, mark);
376
0
        return SECFailure;
377
0
    }
378
379
24
    for (int i = 0; i < worker->digcnt; i++) {
380
15
        const SECHashObject *digobj = worker->digobjs[i];
381
15
        digests[i] = SECITEM_AllocItem(poolp, NULL, digobj->length);
382
15
        if (!digests[i]) {
383
0
            p7dcx->error = PORT_GetError();
384
0
            sec_pkcs7_decoder_abort_digests(worker);
385
0
            PORT_ArenaRelease(poolp, mark);
386
0
            return SECFailure;
387
0
        }
388
15
    }
389
390
24
    for (int i = 0; i < worker->digcnt; i++) {
391
15
        void *digcx = worker->digcxs[i];
392
15
        const SECHashObject *digobj = worker->digobjs[i];
393
394
15
        (*digobj->end)(digcx, digests[i]->data, &(digests[i]->len), digests[i]->len);
395
15
        (*digobj->destroy)(digcx, PR_TRUE);
396
15
        worker->digcxs[i] = NULL;
397
15
    }
398
9
    worker->digcnt = 0;
399
9
    *digestsp = digests;
400
401
9
    PORT_ArenaUnmark(poolp, mark);
402
9
    return SECSuccess;
403
9
}
404
405
/*
406
 * XXX Need comment explaining following helper function (which is used
407
 * by sec_pkcs7_decoder_start_decrypt).
408
 */
409
410
static PK11SymKey *
411
sec_pkcs7_decoder_get_recipient_key(SEC_PKCS7DecoderContext *p7dcx,
412
                                    SEC_PKCS7RecipientInfo **recipientinfos,
413
                                    SEC_PKCS7EncryptedContentInfo *enccinfo)
414
0
{
415
0
    SEC_PKCS7RecipientInfo *ri;
416
0
    CERTCertificate *cert = NULL;
417
0
    SECKEYPrivateKey *privkey = NULL;
418
0
    PK11SymKey *bulkkey = NULL;
419
0
    SECOidTag keyalgtag, bulkalgtag, encalgtag;
420
0
    PK11SlotInfo *slot = NULL;
421
422
0
    if (recipientinfos == NULL || recipientinfos[0] == NULL) {
423
0
        p7dcx->error = SEC_ERROR_NOT_A_RECIPIENT;
424
0
        goto no_key_found;
425
0
    }
426
427
0
    cert = PK11_FindCertAndKeyByRecipientList(&slot, recipientinfos, &ri,
428
0
                                              &privkey, p7dcx->pwfn_arg);
429
0
    if (cert == NULL) {
430
0
        p7dcx->error = SEC_ERROR_NOT_A_RECIPIENT;
431
0
        goto no_key_found;
432
0
    }
433
434
0
    ri->cert = cert; /* so we can find it later */
435
0
    PORT_Assert(privkey != NULL);
436
437
0
    keyalgtag = SECOID_GetAlgorithmTag(&(cert->subjectPublicKeyInfo.algorithm));
438
0
    encalgtag = SECOID_GetAlgorithmTag(&(ri->keyEncAlg));
439
0
    if (keyalgtag != encalgtag) {
440
0
        p7dcx->error = SEC_ERROR_PKCS7_KEYALG_MISMATCH;
441
0
        goto no_key_found;
442
0
    }
443
0
    bulkalgtag = SECOID_GetAlgorithmTag(&(enccinfo->contentEncAlg));
444
445
0
    switch (encalgtag) {
446
0
        case SEC_OID_PKCS1_RSA_ENCRYPTION:
447
0
            bulkkey = PK11_PubUnwrapSymKey(privkey, &ri->encKey,
448
0
                                           PK11_AlgtagToMechanism(bulkalgtag),
449
0
                                           CKA_DECRYPT, 0);
450
0
            if (bulkkey == NULL) {
451
0
                p7dcx->error = PORT_GetError();
452
0
                PORT_SetError(0);
453
0
                goto no_key_found;
454
0
            }
455
0
            break;
456
0
        default:
457
0
            p7dcx->error = SEC_ERROR_UNSUPPORTED_KEYALG;
458
0
            break;
459
0
    }
460
461
0
no_key_found:
462
0
    if (privkey != NULL)
463
0
        SECKEY_DestroyPrivateKey(privkey);
464
0
    if (slot != NULL)
465
0
        PK11_FreeSlot(slot);
466
467
0
    return bulkkey;
468
0
}
469
470
/*
471
 * XXX The following comment is old -- the function used to only handle
472
 * EnvelopedData or SignedAndEnvelopedData but now handles EncryptedData
473
 * as well (and it had all of the code of the helper function above
474
 * built into it), though the comment was left as is.  Fix it...
475
 *
476
 * We are just about to decode the content of an EnvelopedData.
477
 * Set up a decryption context so we can decrypt as we go.
478
 * Presumably we are one of the recipients listed in "recipientinfos".
479
 * (XXX And if we are not, or if we have trouble, what should we do?
480
 *  It would be nice to let the decoding still work.  Maybe it should
481
 *  be an error if there is a content callback, but not an error otherwise?)
482
 * The encryption key and related information can be found in "enccinfo".
483
 */
484
static SECStatus
485
sec_pkcs7_decoder_start_decrypt(SEC_PKCS7DecoderContext *p7dcx, int depth,
486
                                SEC_PKCS7RecipientInfo **recipientinfos,
487
                                SEC_PKCS7EncryptedContentInfo *enccinfo,
488
                                PK11SymKey **copy_key_for_signature)
489
12.6k
{
490
12.6k
    PK11SymKey *bulkkey = NULL;
491
12.6k
    sec_PKCS7CipherObject *decryptobj;
492
493
    /*
494
     * If a callback is supplied to retrieve the encryption key,
495
     * for instance, for Encrypted Content infos, then retrieve
496
     * the bulkkey from the callback.  Otherwise, assume that
497
     * we are processing Enveloped or SignedAndEnveloped data
498
     * content infos.
499
     *
500
     * XXX Put an assert here?
501
     */
502
12.6k
    if (SEC_PKCS7ContentType(p7dcx->cinfo) == SEC_OID_PKCS7_ENCRYPTED_DATA) {
503
12.6k
        if (p7dcx->dkcb != NULL) {
504
12.6k
            bulkkey = (*p7dcx->dkcb)(p7dcx->dkcb_arg,
505
12.6k
                                     &(enccinfo->contentEncAlg));
506
12.6k
        }
507
12.6k
        enccinfo->keysize = 0;
508
12.6k
    } else {
509
0
        bulkkey = sec_pkcs7_decoder_get_recipient_key(p7dcx, recipientinfos,
510
0
                                                      enccinfo);
511
0
        if (bulkkey == NULL)
512
0
            goto no_decryption;
513
0
        enccinfo->keysize = PK11_GetKeyStrength(bulkkey,
514
0
                                                &(enccinfo->contentEncAlg));
515
0
    }
516
517
    /*
518
     * XXX I think following should set error in p7dcx and clear set error
519
     * (as used to be done here, or as is done in get_receipient_key above.
520
     */
521
12.6k
    if (bulkkey == NULL) {
522
12.6k
        goto no_decryption;
523
12.6k
    }
524
525
    /*
526
     * We want to make sure decryption is allowed.  This is done via
527
     * a callback specified in SEC_PKCS7DecoderStart().
528
     */
529
56
    if (p7dcx->decrypt_allowed_cb) {
530
56
        if ((*p7dcx->decrypt_allowed_cb)(&(enccinfo->contentEncAlg),
531
56
                                         bulkkey) == PR_FALSE) {
532
7
            p7dcx->error = SEC_ERROR_DECRYPTION_DISALLOWED;
533
7
            goto no_decryption;
534
7
        }
535
56
    } else {
536
0
        p7dcx->error = SEC_ERROR_DECRYPTION_DISALLOWED;
537
0
        goto no_decryption;
538
0
    }
539
540
    /*
541
     * When decrypting a signedAndEnvelopedData, the signature also has
542
     * to be decrypted with the bulk encryption key; to avoid having to
543
     * get it all over again later (and do another potentially expensive
544
     * RSA operation), copy it for later signature verification to use.
545
     */
546
49
    if (copy_key_for_signature != NULL)
547
0
        *copy_key_for_signature = PK11_ReferenceSymKey(bulkkey);
548
549
    /*
550
     * Now we have the bulk encryption key (in bulkkey) and the
551
     * the algorithm (in enccinfo->contentEncAlg).  Using those,
552
     * create a decryption context.
553
     */
554
49
    decryptobj = sec_PKCS7CreateDecryptObject(bulkkey,
555
49
                                              &(enccinfo->contentEncAlg));
556
557
    /*
558
     * We are done with (this) bulkkey now.
559
     */
560
49
    PK11_FreeSymKey(bulkkey);
561
49
    bulkkey = NULL;
562
563
49
    if (decryptobj == NULL) {
564
43
        p7dcx->error = PORT_GetError();
565
43
        PORT_SetError(0);
566
43
        goto no_decryption;
567
43
    }
568
569
6
    SEC_ASN1DecoderSetFilterProc(p7dcx->dcx,
570
6
                                 sec_pkcs7_decoder_filter,
571
6
                                 p7dcx,
572
6
                                 (PRBool)(p7dcx->cb != NULL));
573
574
6
    p7dcx->worker.depth = depth;
575
6
    p7dcx->worker.decryptobj = decryptobj;
576
577
6
    return SECSuccess;
578
579
12.6k
no_decryption:
580
12.6k
    PK11_FreeSymKey(bulkkey);
581
    /*
582
     * For some reason (error set already, if appropriate), we cannot
583
     * decrypt the content.  I am not sure what exactly is the right
584
     * thing to do here; in some cases we want to just stop, and in
585
     * others we want to let the decoding finish even though we cannot
586
     * decrypt the content.  My current thinking is that if the caller
587
     * set up a content callback, then they are really interested in
588
     * getting (decrypted) content, and if they cannot they will want
589
     * to know about it.  However, if no callback was specified, then
590
     * maybe it is not important that the decryption failed.
591
     */
592
12.6k
    if (p7dcx->cb != NULL)
593
12.6k
        return SECFailure;
594
0
    else
595
0
        return SECSuccess; /* Let the decoding continue. */
596
12.6k
}
597
598
static SECStatus
599
sec_pkcs7_decoder_finish_decrypt(SEC_PKCS7DecoderContext *p7dcx,
600
                                 PLArenaPool *poolp,
601
                                 SEC_PKCS7EncryptedContentInfo *enccinfo)
602
1
{
603
1
    struct sec_pkcs7_decoder_worker *worker;
604
605
    /*
606
     * XXX Handling nested contents would mean that there is a chain
607
     * of workers -- one per each level of content.  The following
608
     * would want to find the last worker in the chain.
609
     */
610
1
    worker = &(p7dcx->worker);
611
612
    /*
613
     * If no decryption context, then we have nothing to do.
614
     */
615
1
    if (worker->decryptobj == NULL)
616
0
        return SECSuccess;
617
618
    /*
619
     * No matter what happens after this, we want to stop filtering.
620
     * XXX If we handle nested contents, we only want to stop filtering
621
     * if we are finishing off the *last* worker.
622
     */
623
1
    SEC_ASN1DecoderClearFilterProc(p7dcx->dcx);
624
625
    /*
626
     * Handle the last block.
627
     */
628
1
    sec_pkcs7_decoder_work_data(p7dcx, worker, NULL, 0, PR_TRUE);
629
630
    /*
631
     * The callback invoked from work_data may have aborted and already
632
     * torn down the decrypt context, so only destroy if it is still set.
633
     */
634
1
    if (worker->decryptobj) {
635
1
        sec_PKCS7DestroyDecryptObject(worker->decryptobj);
636
1
        worker->decryptobj = NULL;
637
1
    }
638
639
1
    return SECSuccess;
640
1
}
641
642
static void
643
sec_pkcs7_decoder_notify(void *arg, PRBool before, void *dest, int depth)
644
269k
{
645
269k
    SEC_PKCS7DecoderContext *p7dcx;
646
269k
    SEC_PKCS7ContentInfo *cinfo;
647
269k
    SEC_PKCS7SignedData *sigd;
648
269k
    SEC_PKCS7EnvelopedData *envd;
649
269k
    SEC_PKCS7SignedAndEnvelopedData *saed;
650
269k
    SEC_PKCS7EncryptedData *encd;
651
269k
    SEC_PKCS7DigestedData *digd;
652
269k
    PRBool after;
653
269k
    SECStatus rv;
654
655
    /*
656
     * Just to make the code easier to read, create an "after" variable
657
     * that is equivalent to "not before".
658
     * (This used to be just the statement "after = !before", but that
659
     * causes a warning on the mac; to avoid that, we do it the long way.)
660
     */
661
269k
    if (before)
662
154k
        after = PR_FALSE;
663
114k
    else
664
114k
        after = PR_TRUE;
665
666
269k
    p7dcx = (SEC_PKCS7DecoderContext *)arg;
667
269k
    if (!p7dcx) {
668
0
        return;
669
0
    }
670
671
269k
    cinfo = p7dcx->cinfo;
672
673
269k
    if (!cinfo) {
674
0
        return;
675
0
    }
676
677
269k
    if (cinfo->contentTypeTag == NULL) {
678
60.9k
        if (after && dest == &(cinfo->contentType))
679
24.8k
            cinfo->contentTypeTag = SECOID_FindOID(&(cinfo->contentType));
680
60.9k
        return;
681
60.9k
    }
682
683
208k
    switch (cinfo->contentTypeTag->offset) {
684
29.3k
        case SEC_OID_PKCS7_SIGNED_DATA:
685
29.3k
            sigd = cinfo->content.signedData;
686
29.3k
            if (sigd == NULL)
687
124
                break;
688
689
29.1k
            if (sigd->contentInfo.contentTypeTag == NULL) {
690
29.1k
                if (after && dest == &(sigd->contentInfo.contentType))
691
56
                    sigd->contentInfo.contentTypeTag =
692
56
                        SECOID_FindOID(&(sigd->contentInfo.contentType));
693
29.1k
                break;
694
29.1k
            }
695
696
            /*
697
             * We only set up a filtering digest if the content is
698
             * plain DATA; anything else needs more work because a
699
             * second pass is required to produce a DER encoding from
700
             * an input that can be BER encoded.  (This is a requirement
701
             * of PKCS7 that is unfortunate, but there you have it.)
702
             *
703
             * XXX Also, since we stop here if this is not DATA, the
704
             * inner content is not getting processed at all.  Someday
705
             * we may want to fix that.
706
             */
707
31
            if (sigd->contentInfo.contentTypeTag->offset != SEC_OID_PKCS7_DATA) {
708
                /* XXX Set an error in p7dcx->error */
709
2
                SEC_ASN1DecoderClearNotifyProc(p7dcx->dcx);
710
2
                break;
711
2
            }
712
713
            /*
714
             * Just before the content, we want to set up a digest context
715
             * for each digest algorithm listed, and start a filter which
716
             * will run all of the contents bytes through that digest.
717
             */
718
29
            if (before && dest == &(sigd->contentInfo.content)) {
719
20
                rv = sec_pkcs7_decoder_start_digests(p7dcx, depth,
720
20
                                                     sigd->digestAlgorithms);
721
20
                if (rv != SECSuccess)
722
0
                    SEC_ASN1DecoderClearNotifyProc(p7dcx->dcx);
723
724
20
                break;
725
20
            }
726
727
            /*
728
             * XXX To handle nested types, here is where we would want
729
             * to check for inner boundaries that need handling.
730
             */
731
732
            /*
733
             * Are we done?
734
             */
735
9
            if (after && dest == &(sigd->contentInfo.content)) {
736
                /*
737
                 * Close out the digest contexts.  We ignore any error
738
                 * because we are stopping anyway; the error status left
739
                 * behind in p7dcx will be seen by outer functions.
740
                 */
741
9
                (void)sec_pkcs7_decoder_finish_digests(p7dcx, cinfo->poolp,
742
9
                                                       &(sigd->digests));
743
744
                /*
745
                 * XXX To handle nested contents, we would need to remove
746
                 * the worker from the chain (and free it).
747
                 */
748
749
                /*
750
                 * Stop notify.
751
                 */
752
9
                SEC_ASN1DecoderClearNotifyProc(p7dcx->dcx);
753
9
            }
754
9
            break;
755
756
1.73k
        case SEC_OID_PKCS7_ENVELOPED_DATA:
757
1.73k
            envd = cinfo->content.envelopedData;
758
1.73k
            if (envd == NULL)
759
1.73k
                break;
760
761
0
            if (envd->encContentInfo.contentTypeTag == NULL) {
762
0
                if (after && dest == &(envd->encContentInfo.contentType))
763
0
                    envd->encContentInfo.contentTypeTag =
764
0
                        SECOID_FindOID(&(envd->encContentInfo.contentType));
765
0
                break;
766
0
            }
767
768
            /*
769
             * Just before the content, we want to set up a decryption
770
             * context, and start a filter which will run all of the
771
             * contents bytes through it to determine the plain content.
772
             */
773
0
            if (before && dest == &(envd->encContentInfo.encContent)) {
774
0
                rv = sec_pkcs7_decoder_start_decrypt(p7dcx, depth,
775
0
                                                     envd->recipientInfos,
776
0
                                                     &(envd->encContentInfo),
777
0
                                                     NULL);
778
0
                if (rv != SECSuccess)
779
0
                    SEC_ASN1DecoderClearNotifyProc(p7dcx->dcx);
780
781
0
                break;
782
0
            }
783
784
            /*
785
             * Are we done?
786
             */
787
0
            if (after && dest == &(envd->encContentInfo.encContent)) {
788
                /*
789
                 * Close out the decryption context.  We ignore any error
790
                 * because we are stopping anyway; the error status left
791
                 * behind in p7dcx will be seen by outer functions.
792
                 */
793
0
                (void)sec_pkcs7_decoder_finish_decrypt(p7dcx, cinfo->poolp,
794
0
                                                       &(envd->encContentInfo));
795
796
                /*
797
                 * XXX To handle nested contents, we would need to remove
798
                 * the worker from the chain (and free it).
799
                 */
800
801
                /*
802
                 * Stop notify.
803
                 */
804
0
                SEC_ASN1DecoderClearNotifyProc(p7dcx->dcx);
805
0
            }
806
0
            break;
807
808
2.20k
        case SEC_OID_PKCS7_SIGNED_ENVELOPED_DATA:
809
2.20k
            saed = cinfo->content.signedAndEnvelopedData;
810
2.20k
            if (saed == NULL)
811
2.20k
                break;
812
813
0
            if (saed->encContentInfo.contentTypeTag == NULL) {
814
0
                if (after && dest == &(saed->encContentInfo.contentType))
815
0
                    saed->encContentInfo.contentTypeTag =
816
0
                        SECOID_FindOID(&(saed->encContentInfo.contentType));
817
0
                break;
818
0
            }
819
820
            /*
821
             * Just before the content, we want to set up a decryption
822
             * context *and* digest contexts, and start a filter which
823
             * will run all of the contents bytes through both.
824
             */
825
0
            if (before && dest == &(saed->encContentInfo.encContent)) {
826
0
                rv = sec_pkcs7_decoder_start_decrypt(p7dcx, depth,
827
0
                                                     saed->recipientInfos,
828
0
                                                     &(saed->encContentInfo),
829
0
                                                     &(saed->sigKey));
830
0
                if (rv == SECSuccess)
831
0
                    rv = sec_pkcs7_decoder_start_digests(p7dcx, depth,
832
0
                                                         saed->digestAlgorithms);
833
0
                if (rv != SECSuccess)
834
0
                    SEC_ASN1DecoderClearNotifyProc(p7dcx->dcx);
835
836
0
                break;
837
0
            }
838
839
            /*
840
             * Are we done?
841
             */
842
0
            if (after && dest == &(saed->encContentInfo.encContent)) {
843
                /*
844
                 * Close out the decryption and digests contexts.
845
                 * We ignore any errors because we are stopping anyway;
846
                 * the error status left behind in p7dcx will be seen by
847
                 * outer functions.
848
                 *
849
                 * Note that the decrypt stuff must be called first;
850
                 * it may have a last buffer to do which in turn has
851
                 * to be added to the digest.
852
                 */
853
0
                (void)sec_pkcs7_decoder_finish_decrypt(p7dcx, cinfo->poolp,
854
0
                                                       &(saed->encContentInfo));
855
0
                (void)sec_pkcs7_decoder_finish_digests(p7dcx, cinfo->poolp,
856
0
                                                       &(saed->digests));
857
858
                /*
859
                 * XXX To handle nested contents, we would need to remove
860
                 * the worker from the chain (and free it).
861
                 */
862
863
                /*
864
                 * Stop notify.
865
                 */
866
0
                SEC_ASN1DecoderClearNotifyProc(p7dcx->dcx);
867
0
            }
868
0
            break;
869
870
8.95k
        case SEC_OID_PKCS7_DIGESTED_DATA:
871
8.95k
            digd = cinfo->content.digestedData;
872
8.95k
            if (digd == NULL)
873
5.93k
                break;
874
875
            /*
876
             * XXX Want to do the digest or not?  Maybe future enhancement...
877
             */
878
3.01k
            if (before && dest == &(digd->contentInfo.content.data)) {
879
5
                SEC_ASN1DecoderSetFilterProc(p7dcx->dcx, sec_pkcs7_decoder_filter,
880
5
                                             p7dcx,
881
5
                                             (PRBool)(p7dcx->cb != NULL));
882
5
                break;
883
5
            }
884
885
            /*
886
             * Are we done?
887
             */
888
3.01k
            if (after && dest == &(digd->contentInfo.content.data)) {
889
0
                SEC_ASN1DecoderClearFilterProc(p7dcx->dcx);
890
0
            }
891
3.01k
            break;
892
893
164k
        case SEC_OID_PKCS7_ENCRYPTED_DATA:
894
164k
            encd = cinfo->content.encryptedData;
895
896
164k
            if (!encd) {
897
12.7k
                break;
898
12.7k
            }
899
900
            /*
901
             * XXX If the decryption key callback is set, we want to start
902
             * the decryption.  If the callback is not set, we will treat the
903
             * content as plain data, since we do not have the key.
904
             *
905
             * Is this the proper thing to do?
906
             */
907
152k
            if (before && dest == &(encd->encContentInfo.encContent)) {
908
                /*
909
                 * Start the encryption process if the decryption key callback
910
                 * is present.  Otherwise, treat the content like plain data.
911
                 */
912
12.6k
                rv = SECSuccess;
913
12.6k
                if (p7dcx->dkcb != NULL) {
914
12.6k
                    rv = sec_pkcs7_decoder_start_decrypt(p7dcx, depth, NULL,
915
12.6k
                                                         &(encd->encContentInfo),
916
12.6k
                                                         NULL);
917
12.6k
                }
918
919
12.6k
                if (rv != SECSuccess)
920
12.6k
                    SEC_ASN1DecoderClearNotifyProc(p7dcx->dcx);
921
922
12.6k
                break;
923
12.6k
            }
924
925
            /*
926
             * Are we done?
927
             */
928
139k
            if (after && dest == &(encd->encContentInfo.encContent)) {
929
                /*
930
                 * Close out the decryption context.  We ignore any error
931
                 * because we are stopping anyway; the error status left
932
                 * behind in p7dcx will be seen by outer functions.
933
                 */
934
1
                (void)sec_pkcs7_decoder_finish_decrypt(p7dcx, cinfo->poolp,
935
1
                                                       &(encd->encContentInfo));
936
937
                /*
938
                 * Stop notify.
939
                 */
940
1
                SEC_ASN1DecoderClearNotifyProc(p7dcx->dcx);
941
1
            }
942
139k
            break;
943
944
469
        case SEC_OID_PKCS7_DATA:
945
            /*
946
             * If a output callback has been specified, we want to set the filter
947
             * to call the callback.  This is taken care of in
948
             * sec_pkcs7_decoder_start_decrypt() or
949
             * sec_pkcs7_decoder_start_digests() for the other content types.
950
             */
951
952
469
            if (before && dest == &(cinfo->content.data)) {
953
954
                /*
955
                 * Set the filter proc up.
956
                 */
957
418
                SEC_ASN1DecoderSetFilterProc(p7dcx->dcx,
958
418
                                             sec_pkcs7_decoder_filter,
959
418
                                             p7dcx,
960
418
                                             (PRBool)(p7dcx->cb != NULL));
961
418
                break;
962
418
            }
963
964
51
            if (after && dest == &(cinfo->content.data)) {
965
                /*
966
                 * Time to clean up after ourself, stop the Notify and Filter
967
                 * procedures.
968
                 */
969
51
                SEC_ASN1DecoderClearNotifyProc(p7dcx->dcx);
970
51
                SEC_ASN1DecoderClearFilterProc(p7dcx->dcx);
971
51
            }
972
51
            break;
973
974
1.05k
        default:
975
1.05k
            SEC_ASN1DecoderClearNotifyProc(p7dcx->dcx);
976
1.05k
            break;
977
208k
    }
978
208k
}
979
980
SEC_PKCS7DecoderContext *
981
SEC_PKCS7DecoderStart(SEC_PKCS7DecoderContentCallback cb, void *cb_arg,
982
                      SECKEYGetPasswordKey pwfn, void *pwfn_arg,
983
                      SEC_PKCS7GetDecryptKeyCallback decrypt_key_cb,
984
                      void *decrypt_key_cb_arg,
985
                      SEC_PKCS7DecryptionAllowedCallback decrypt_allowed_cb)
986
24.9k
{
987
24.9k
    SEC_PKCS7DecoderContext *p7dcx;
988
24.9k
    SEC_ASN1DecoderContext *dcx;
989
24.9k
    SEC_PKCS7ContentInfo *cinfo;
990
24.9k
    PLArenaPool *poolp;
991
992
24.9k
    poolp = PORT_NewArena(1024); /* XXX what is right value? */
993
24.9k
    if (poolp == NULL)
994
0
        return NULL;
995
996
24.9k
    cinfo = (SEC_PKCS7ContentInfo *)PORT_ArenaZAlloc(poolp, sizeof(*cinfo));
997
24.9k
    if (cinfo == NULL) {
998
0
        PORT_FreeArena(poolp, PR_FALSE);
999
0
        return NULL;
1000
0
    }
1001
1002
24.9k
    cinfo->poolp = poolp;
1003
24.9k
    cinfo->pwfn = pwfn;
1004
24.9k
    cinfo->pwfn_arg = pwfn_arg;
1005
24.9k
    cinfo->created = PR_FALSE;
1006
24.9k
    cinfo->refCount = 1;
1007
1008
24.9k
    p7dcx =
1009
24.9k
        (SEC_PKCS7DecoderContext *)PORT_ZAlloc(sizeof(SEC_PKCS7DecoderContext));
1010
24.9k
    if (p7dcx == NULL) {
1011
0
        PORT_FreeArena(poolp, PR_FALSE);
1012
0
        return NULL;
1013
0
    }
1014
1015
24.9k
    p7dcx->tmp_poolp = PORT_NewArena(1024); /* XXX what is right value? */
1016
24.9k
    if (p7dcx->tmp_poolp == NULL) {
1017
0
        PORT_Free(p7dcx);
1018
0
        PORT_FreeArena(poolp, PR_FALSE);
1019
0
        return NULL;
1020
0
    }
1021
1022
24.9k
    dcx = SEC_ASN1DecoderStart(poolp, cinfo, sec_PKCS7ContentInfoTemplate);
1023
24.9k
    if (dcx == NULL) {
1024
0
        PORT_FreeArena(p7dcx->tmp_poolp, PR_FALSE);
1025
0
        PORT_Free(p7dcx);
1026
0
        PORT_FreeArena(poolp, PR_FALSE);
1027
0
        return NULL;
1028
0
    }
1029
1030
24.9k
    SEC_ASN1DecoderSetNotifyProc(dcx, sec_pkcs7_decoder_notify, p7dcx);
1031
1032
24.9k
    p7dcx->dcx = dcx;
1033
24.9k
    p7dcx->cinfo = cinfo;
1034
24.9k
    p7dcx->cb = cb;
1035
24.9k
    p7dcx->cb_arg = cb_arg;
1036
24.9k
    p7dcx->pwfn = pwfn;
1037
24.9k
    p7dcx->pwfn_arg = pwfn_arg;
1038
24.9k
    p7dcx->dkcb = decrypt_key_cb;
1039
24.9k
    p7dcx->dkcb_arg = decrypt_key_cb_arg;
1040
24.9k
    p7dcx->decrypt_allowed_cb = decrypt_allowed_cb;
1041
1042
24.9k
    return p7dcx;
1043
24.9k
}
1044
1045
/*
1046
 * Do the next chunk of PKCS7 decoding.  If there is a problem, set
1047
 * an error and return a failure status.  Note that in the case of
1048
 * an error, this routine is still prepared to be called again and
1049
 * again in case that is the easiest route for our caller to take.
1050
 * We simply detect it and do not do anything except keep setting
1051
 * that error in case our caller has not noticed it yet...
1052
 */
1053
SECStatus
1054
SEC_PKCS7DecoderUpdate(SEC_PKCS7DecoderContext *p7dcx,
1055
                       const char *buf, unsigned long len)
1056
1.65M
{
1057
1.65M
    if (!p7dcx) {
1058
0
        PORT_SetError(SEC_ERROR_INVALID_ARGS);
1059
0
        return SECFailure;
1060
0
    }
1061
1062
1.65M
    if (p7dcx->cinfo != NULL && p7dcx->dcx != NULL) {
1063
1.21M
        PORT_Assert(p7dcx->error == 0);
1064
1.21M
        if (p7dcx->error == 0) {
1065
1.21M
            if (SEC_ASN1DecoderUpdate(p7dcx->dcx, buf, len) != SECSuccess) {
1066
272
                p7dcx->error = PORT_GetError();
1067
272
                PORT_Assert(p7dcx->error);
1068
272
                if (p7dcx->error == 0)
1069
0
                    p7dcx->error = -1;
1070
272
            }
1071
1.21M
        }
1072
1.21M
    }
1073
1074
1.65M
    if (p7dcx->error) {
1075
439k
        sec_pkcs7_decoder_abort_digests(&p7dcx->worker);
1076
439k
        if (p7dcx->worker.decryptobj) {
1077
1
            sec_PKCS7DestroyDecryptObject(p7dcx->worker.decryptobj);
1078
1
            p7dcx->worker.decryptobj = NULL;
1079
1
        }
1080
439k
        if (p7dcx->dcx != NULL) {
1081
322
            (void)SEC_ASN1DecoderFinish(p7dcx->dcx);
1082
322
            p7dcx->dcx = NULL;
1083
322
        }
1084
439k
        if (p7dcx->cinfo != NULL) {
1085
322
            SEC_PKCS7DestroyContentInfo(p7dcx->cinfo);
1086
322
            p7dcx->cinfo = NULL;
1087
322
        }
1088
439k
        PORT_SetError(p7dcx->error);
1089
439k
        return SECFailure;
1090
439k
    }
1091
1092
1.21M
    return SECSuccess;
1093
1.65M
}
1094
1095
SEC_PKCS7ContentInfo *
1096
SEC_PKCS7DecoderFinish(SEC_PKCS7DecoderContext *p7dcx)
1097
24.9k
{
1098
24.9k
    SEC_PKCS7ContentInfo *cinfo;
1099
1100
24.9k
    sec_pkcs7_decoder_abort_digests(&p7dcx->worker);
1101
24.9k
    cinfo = p7dcx->cinfo;
1102
24.9k
    if (p7dcx->dcx != NULL) {
1103
24.6k
        if (SEC_ASN1DecoderFinish(p7dcx->dcx) != SECSuccess) {
1104
449
            SEC_PKCS7DestroyContentInfo(cinfo);
1105
449
            cinfo = NULL;
1106
449
        }
1107
24.6k
    }
1108
    /* free any NSS data structures */
1109
24.9k
    if (p7dcx->worker.decryptobj) {
1110
0
        sec_PKCS7DestroyDecryptObject(p7dcx->worker.decryptobj);
1111
0
        p7dcx->worker.decryptobj = NULL;
1112
0
    }
1113
1114
24.9k
    PORT_FreeArena(p7dcx->tmp_poolp, PR_FALSE);
1115
24.9k
    PORT_Free(p7dcx);
1116
24.9k
    return cinfo;
1117
24.9k
}
1118
1119
SEC_PKCS7ContentInfo *
1120
SEC_PKCS7DecodeItem(SECItem *p7item,
1121
                    SEC_PKCS7DecoderContentCallback cb, void *cb_arg,
1122
                    SECKEYGetPasswordKey pwfn, void *pwfn_arg,
1123
                    SEC_PKCS7GetDecryptKeyCallback decrypt_key_cb,
1124
                    void *decrypt_key_cb_arg,
1125
                    SEC_PKCS7DecryptionAllowedCallback decrypt_allowed_cb)
1126
0
{
1127
0
    SEC_PKCS7DecoderContext *p7dcx;
1128
1129
0
    p7dcx = SEC_PKCS7DecoderStart(cb, cb_arg, pwfn, pwfn_arg, decrypt_key_cb,
1130
0
                                  decrypt_key_cb_arg, decrypt_allowed_cb);
1131
0
    if (!p7dcx) {
1132
        /* error code is set */
1133
0
        return NULL;
1134
0
    }
1135
0
    (void)SEC_PKCS7DecoderUpdate(p7dcx, (char *)p7item->data, p7item->len);
1136
0
    return SEC_PKCS7DecoderFinish(p7dcx);
1137
0
}
1138
1139
/*
1140
 * Abort the ASN.1 stream. Used by pkcs 12
1141
 */
1142
void
1143
SEC_PKCS7DecoderAbort(SEC_PKCS7DecoderContext *p7dcx, int error)
1144
6
{
1145
6
    PORT_Assert(p7dcx);
1146
6
    if (!p7dcx) {
1147
0
        return;
1148
0
    }
1149
1150
    /* ensure any streaming helpers are torn down */
1151
6
    sec_pkcs7_decoder_abort_digests(&p7dcx->worker);
1152
6
    if (p7dcx->worker.decryptobj) {
1153
4
        sec_PKCS7DestroyDecryptObject(p7dcx->worker.decryptobj);
1154
4
        p7dcx->worker.decryptobj = NULL;
1155
4
    }
1156
1157
6
    SEC_ASN1DecoderAbort(p7dcx->dcx, error);
1158
6
}
1159
1160
/*
1161
 * If the thing contains any certs or crls return true; false otherwise.
1162
 */
1163
PRBool
1164
SEC_PKCS7ContainsCertsOrCrls(SEC_PKCS7ContentInfo *cinfo)
1165
0
{
1166
0
    SECOidTag kind;
1167
0
    SECItem **certs;
1168
0
    CERTSignedCrl **crls;
1169
1170
0
    kind = SEC_PKCS7ContentType(cinfo);
1171
0
    switch (kind) {
1172
0
        default:
1173
0
        case SEC_OID_PKCS7_DATA:
1174
0
        case SEC_OID_PKCS7_DIGESTED_DATA:
1175
0
        case SEC_OID_PKCS7_ENVELOPED_DATA:
1176
0
        case SEC_OID_PKCS7_ENCRYPTED_DATA:
1177
0
            return PR_FALSE;
1178
0
        case SEC_OID_PKCS7_SIGNED_DATA:
1179
0
            certs = cinfo->content.signedData->rawCerts;
1180
0
            crls = cinfo->content.signedData->crls;
1181
0
            break;
1182
0
        case SEC_OID_PKCS7_SIGNED_ENVELOPED_DATA:
1183
0
            certs = cinfo->content.signedAndEnvelopedData->rawCerts;
1184
0
            crls = cinfo->content.signedAndEnvelopedData->crls;
1185
0
            break;
1186
0
    }
1187
1188
    /*
1189
     * I know this could be collapsed, but I was in a mood to be explicit.
1190
     */
1191
0
    if (certs != NULL && certs[0] != NULL)
1192
0
        return PR_TRUE;
1193
0
    else if (crls != NULL && crls[0] != NULL)
1194
0
        return PR_TRUE;
1195
0
    else
1196
0
        return PR_FALSE;
1197
0
}
1198
1199
/* return the content length...could use GetContent, however we
1200
 * need the encrypted content length
1201
 */
1202
PRBool
1203
SEC_PKCS7IsContentEmpty(SEC_PKCS7ContentInfo *cinfo, unsigned int minLen)
1204
0
{
1205
0
    SECItem *item = NULL;
1206
1207
0
    if (cinfo == NULL) {
1208
0
        return PR_TRUE;
1209
0
    }
1210
1211
0
    switch (SEC_PKCS7ContentType(cinfo)) {
1212
0
        case SEC_OID_PKCS7_DATA:
1213
0
            item = cinfo->content.data;
1214
0
            break;
1215
0
        case SEC_OID_PKCS7_ENCRYPTED_DATA:
1216
0
            item = &cinfo->content.encryptedData->encContentInfo.encContent;
1217
0
            break;
1218
0
        default:
1219
            /* add other types */
1220
0
            return PR_FALSE;
1221
0
    }
1222
1223
0
    if (!item) {
1224
0
        return PR_TRUE;
1225
0
    } else if (item->len <= minLen) {
1226
0
        return PR_TRUE;
1227
0
    }
1228
1229
0
    return PR_FALSE;
1230
0
}
1231
1232
PRBool
1233
SEC_PKCS7ContentIsEncrypted(SEC_PKCS7ContentInfo *cinfo)
1234
0
{
1235
0
    SECOidTag kind;
1236
1237
0
    kind = SEC_PKCS7ContentType(cinfo);
1238
0
    switch (kind) {
1239
0
        default:
1240
0
        case SEC_OID_PKCS7_DATA:
1241
0
        case SEC_OID_PKCS7_DIGESTED_DATA:
1242
0
        case SEC_OID_PKCS7_SIGNED_DATA:
1243
0
            return PR_FALSE;
1244
0
        case SEC_OID_PKCS7_ENCRYPTED_DATA:
1245
0
        case SEC_OID_PKCS7_ENVELOPED_DATA:
1246
0
        case SEC_OID_PKCS7_SIGNED_ENVELOPED_DATA:
1247
0
            return PR_TRUE;
1248
0
    }
1249
0
}
1250
1251
/*
1252
 * If the PKCS7 content has a signature (not just *could* have a signature)
1253
 * return true; false otherwise.  This can/should be called before calling
1254
 * VerifySignature, which will always indicate failure if no signature is
1255
 * present, but that does not mean there even was a signature!
1256
 * Note that the content itself can be empty (detached content was sent
1257
 * another way); it is the presence of the signature that matters.
1258
 */
1259
PRBool
1260
SEC_PKCS7ContentIsSigned(SEC_PKCS7ContentInfo *cinfo)
1261
0
{
1262
0
    SECOidTag kind;
1263
0
    SEC_PKCS7SignerInfo **signerinfos;
1264
1265
0
    kind = SEC_PKCS7ContentType(cinfo);
1266
0
    switch (kind) {
1267
0
        default:
1268
0
        case SEC_OID_PKCS7_DATA:
1269
0
        case SEC_OID_PKCS7_DIGESTED_DATA:
1270
0
        case SEC_OID_PKCS7_ENVELOPED_DATA:
1271
0
        case SEC_OID_PKCS7_ENCRYPTED_DATA:
1272
0
            return PR_FALSE;
1273
0
        case SEC_OID_PKCS7_SIGNED_DATA:
1274
0
            signerinfos = cinfo->content.signedData->signerInfos;
1275
0
            break;
1276
0
        case SEC_OID_PKCS7_SIGNED_ENVELOPED_DATA:
1277
0
            signerinfos = cinfo->content.signedAndEnvelopedData->signerInfos;
1278
0
            break;
1279
0
    }
1280
1281
    /*
1282
     * I know this could be collapsed; but I kind of think it will get
1283
     * more complicated before I am finished, so...
1284
     */
1285
0
    if (signerinfos != NULL && signerinfos[0] != NULL)
1286
0
        return PR_TRUE;
1287
0
    else
1288
0
        return PR_FALSE;
1289
0
}
1290
1291
/*
1292
 * sec_pkcs7_verify_signature
1293
 *
1294
 *      Look at a PKCS7 contentInfo and check if the signature is good.
1295
 *      The digest was either calculated earlier (and is stored in the
1296
 *      contentInfo itself) or is passed in via "detached_digest".
1297
 *
1298
 *      The verification checks that the signing cert is valid and trusted
1299
 *      for the purpose specified by "certusage" at
1300
 *      - "*atTime" if "atTime" is not null, or
1301
 *      - the signing time if the signing time is available in "cinfo", or
1302
 *      - the current time (as returned by PR_Now).
1303
 *
1304
 *      In addition, if "keepcerts" is true, add any new certificates found
1305
 *      into our local database.
1306
 *
1307
 * XXX Each place which returns PR_FALSE should be sure to have a good
1308
 * error set for inspection by the caller.  Alternatively, we could create
1309
 * an enumeration of success and each type of failure and return that
1310
 * instead of a boolean.  For now, the default in a bad situation is to
1311
 * set the error to SEC_ERROR_PKCS7_BAD_SIGNATURE.  But this should be
1312
 * reviewed; better (more specific) errors should be possible (to distinguish
1313
 * a signature failure from a badly-formed pkcs7 signedData, for example).
1314
 * Some of the errors should probably just be SEC_ERROR_BAD_SIGNATURE,
1315
 * but that has a less helpful error string associated with it right now;
1316
 * if/when that changes, review and change these as needed.
1317
 *
1318
 * XXX This is broken wrt signedAndEnvelopedData.  In that case, the
1319
 * message digest is doubly encrypted -- first encrypted with the signer
1320
 * private key but then again encrypted with the bulk encryption key used
1321
 * to encrypt the content.  So before we can pass the digest to VerifyDigest,
1322
 * we need to decrypt it with the bulk encryption key.  Also, in this case,
1323
 * there should be NO authenticatedAttributes (signerinfo->authAttr should
1324
 * be NULL).
1325
 */
1326
static PRBool
1327
sec_pkcs7_verify_signature(SEC_PKCS7ContentInfo *cinfo,
1328
                           SECCertUsage certusage,
1329
                           const SECItem *detached_digest,
1330
                           HASH_HashType digest_type,
1331
                           PRBool keepcerts,
1332
                           const PRTime *atTime)
1333
0
{
1334
0
    SECAlgorithmID **digestalgs, *bulkid;
1335
0
    const SECItem *digest;
1336
0
    SECItem **digests;
1337
0
    SECItem **rawcerts;
1338
0
    SEC_PKCS7SignerInfo **signerinfos, *signerinfo;
1339
0
    CERTCertificate *cert, **certs;
1340
0
    PRBool goodsig;
1341
0
    CERTCertDBHandle *certdb, *defaultdb;
1342
0
    SECOidTag encTag, digestTag;
1343
0
    HASH_HashType found_type;
1344
0
    int i, certcount;
1345
0
    SECKEYPublicKey *publickey;
1346
0
    SECItem *content_type;
1347
0
    PK11SymKey *sigkey;
1348
0
    SECItem *encoded_stime;
1349
0
    PRTime stime;
1350
0
    PRTime verificationTime;
1351
0
    SECStatus rv;
1352
1353
    /*
1354
     * Everything needed in order to "goto done" safely.
1355
     */
1356
0
    goodsig = PR_FALSE;
1357
0
    certcount = 0;
1358
0
    cert = NULL;
1359
0
    certs = NULL;
1360
0
    certdb = NULL;
1361
0
    defaultdb = CERT_GetDefaultCertDB();
1362
0
    publickey = NULL;
1363
1364
0
    if (!SEC_PKCS7ContentIsSigned(cinfo)) {
1365
0
        PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1366
0
        goto done;
1367
0
    }
1368
1369
0
    PORT_Assert(cinfo->contentTypeTag != NULL);
1370
1371
0
    switch (cinfo->contentTypeTag->offset) {
1372
0
        default:
1373
0
        case SEC_OID_PKCS7_DATA:
1374
0
        case SEC_OID_PKCS7_DIGESTED_DATA:
1375
0
        case SEC_OID_PKCS7_ENVELOPED_DATA:
1376
0
        case SEC_OID_PKCS7_ENCRYPTED_DATA:
1377
            /* Could only get here if SEC_PKCS7ContentIsSigned is broken. */
1378
0
            PORT_Assert(0);
1379
0
        case SEC_OID_PKCS7_SIGNED_DATA: {
1380
0
            SEC_PKCS7SignedData *sdp;
1381
1382
0
            sdp = cinfo->content.signedData;
1383
0
            digestalgs = sdp->digestAlgorithms;
1384
0
            digests = sdp->digests;
1385
0
            rawcerts = sdp->rawCerts;
1386
0
            signerinfos = sdp->signerInfos;
1387
0
            content_type = &(sdp->contentInfo.contentType);
1388
0
            sigkey = NULL;
1389
0
            bulkid = NULL;
1390
0
        } break;
1391
0
        case SEC_OID_PKCS7_SIGNED_ENVELOPED_DATA: {
1392
0
            SEC_PKCS7SignedAndEnvelopedData *saedp;
1393
1394
0
            saedp = cinfo->content.signedAndEnvelopedData;
1395
0
            digestalgs = saedp->digestAlgorithms;
1396
0
            digests = saedp->digests;
1397
0
            rawcerts = saedp->rawCerts;
1398
0
            signerinfos = saedp->signerInfos;
1399
0
            content_type = &(saedp->encContentInfo.contentType);
1400
0
            sigkey = saedp->sigKey;
1401
0
            bulkid = &(saedp->encContentInfo.contentEncAlg);
1402
0
        } break;
1403
0
    }
1404
1405
0
    if ((signerinfos == NULL) || (signerinfos[0] == NULL)) {
1406
0
        PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1407
0
        goto done;
1408
0
    }
1409
1410
    /*
1411
     * XXX Need to handle multiple signatures; checking them is easy,
1412
     * but what should be the semantics here (like, return value)?
1413
     */
1414
0
    if (signerinfos[1] != NULL) {
1415
0
        PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1416
0
        goto done;
1417
0
    }
1418
1419
0
    signerinfo = signerinfos[0];
1420
1421
    /*
1422
     * XXX I would like to just pass the issuerAndSN, along with the rawcerts
1423
     * and crls, to some function that did all of this certificate stuff
1424
     * (open/close the database if necessary, verifying the certs, etc.)
1425
     * and gave me back a cert pointer if all was good.
1426
     */
1427
0
    certdb = defaultdb;
1428
0
    if (certdb == NULL) {
1429
0
        goto done;
1430
0
    }
1431
1432
0
    certcount = 0;
1433
0
    if (rawcerts != NULL) {
1434
0
        for (; rawcerts[certcount] != NULL; certcount++) {
1435
            /* just counting */
1436
0
        }
1437
0
    }
1438
1439
    /*
1440
     * Note that the result of this is that each cert in "certs"
1441
     * needs to be destroyed.
1442
     */
1443
0
    rv = CERT_ImportCerts(certdb, certusage, certcount, rawcerts, &certs,
1444
0
                          keepcerts, PR_FALSE, NULL);
1445
0
    if (rv != SECSuccess) {
1446
0
        goto done;
1447
0
    }
1448
1449
    /*
1450
     * This cert will also need to be freed, but since we save it
1451
     * in signerinfo for later, we do not want to destroy it when
1452
     * we leave this function -- we let the clean-up of the entire
1453
     * cinfo structure later do the destroy of this cert.
1454
     */
1455
0
    cert = CERT_FindCertByIssuerAndSN(certdb, signerinfo->issuerAndSN);
1456
0
    if (cert == NULL) {
1457
0
        goto done;
1458
0
    }
1459
1460
0
    signerinfo->cert = cert;
1461
1462
    /*
1463
     * Get and convert the signing time; if available, it will be used
1464
     * both on the cert verification and for importing the sender
1465
     * email profile.
1466
     */
1467
0
    encoded_stime = SEC_PKCS7GetSigningTime(cinfo);
1468
0
    if (encoded_stime != NULL) {
1469
0
        if (DER_DecodeTimeChoice(&stime, encoded_stime) != SECSuccess)
1470
0
            encoded_stime = NULL; /* conversion failed, so pretend none */
1471
0
    }
1472
1473
    /*
1474
     * XXX  This uses the signing time, if available.  Additionally, we
1475
     * might want to, if there is no signing time, get the message time
1476
     * from the mail header itself, and use that.  That would require
1477
     * a change to our interface though, and for S/MIME callers to pass
1478
     * in a time (and for non-S/MIME callers to pass in nothing, or
1479
     * maybe make them pass in the current time, always?).
1480
     */
1481
0
    if (atTime) {
1482
0
        verificationTime = *atTime;
1483
0
    } else if (encoded_stime != NULL) {
1484
0
        verificationTime = stime;
1485
0
    } else {
1486
0
        verificationTime = PR_Now();
1487
0
    }
1488
0
    if (CERT_VerifyCert(certdb, cert, PR_TRUE, certusage, verificationTime,
1489
0
                        cinfo->pwfn_arg, NULL) != SECSuccess) {
1490
        /*
1491
         * XXX Give the user an option to check the signature anyway?
1492
         * If we want to do this, need to give a way to leave and display
1493
         * some dialog and get the answer and come back through (or do
1494
         * the rest of what we do below elsewhere, maybe by putting it
1495
         * in a function that we call below and could call from a dialog
1496
         * finish handler).
1497
         */
1498
0
        goto savecert;
1499
0
    }
1500
1501
0
    publickey = CERT_ExtractPublicKey(cert);
1502
0
    if (publickey == NULL)
1503
0
        goto done;
1504
1505
    /*
1506
     * XXX No!  If digests is empty, see if we can create it now by
1507
     * digesting the contents.  This is necessary if we want to allow
1508
     * somebody to do a simple decode (without filtering, etc.) and
1509
     * then later call us here to do the verification.
1510
     * OR, we can just specify that the interface to this routine
1511
     * *requires* that the digest(s) be done before calling and either
1512
     * stashed in the struct itself or passed in explicitly (as would
1513
     * be done for detached contents).
1514
     */
1515
0
    if ((digests == NULL || digests[0] == NULL) && (detached_digest == NULL || detached_digest->data == NULL))
1516
0
        goto done;
1517
1518
    /*
1519
     * Find and confirm digest algorithm.
1520
     */
1521
0
    digestTag = SECOID_FindOIDTag(&(signerinfo->digestAlg.algorithm));
1522
1523
    /* make sure we understand the digest type first */
1524
0
    found_type = HASH_GetHashTypeByOidTag(digestTag);
1525
0
    if ((digestTag == SEC_OID_UNKNOWN) || (found_type == HASH_AlgNULL)) {
1526
0
        PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1527
0
        goto done;
1528
0
    }
1529
1530
0
    if (detached_digest != NULL) {
1531
0
        unsigned int hashLen = HASH_ResultLen(found_type);
1532
1533
0
        if (digest_type != found_type ||
1534
0
            detached_digest->len != hashLen) {
1535
0
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1536
0
            goto done;
1537
0
        }
1538
0
        digest = detached_digest;
1539
0
    } else {
1540
0
        PORT_Assert(digestalgs != NULL && digestalgs[0] != NULL);
1541
0
        if (digestalgs == NULL || digestalgs[0] == NULL) {
1542
0
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1543
0
            goto done;
1544
0
        }
1545
1546
        /*
1547
         * pick digest matching signerinfo->digestAlg from digests
1548
         */
1549
0
        for (i = 0; digestalgs[i] != NULL; i++) {
1550
0
            if (SECOID_FindOIDTag(&(digestalgs[i]->algorithm)) == digestTag)
1551
0
                break;
1552
0
        }
1553
0
        if (digestalgs[i] == NULL) {
1554
0
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1555
0
            goto done;
1556
0
        }
1557
1558
0
        digest = digests[i];
1559
0
    }
1560
1561
0
    encTag = SECOID_FindOIDTag(&(signerinfo->digestEncAlg.algorithm));
1562
0
    if (encTag == SEC_OID_UNKNOWN) {
1563
0
        PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1564
0
        goto done;
1565
0
    }
1566
1567
0
    if (signerinfo->authAttr != NULL) {
1568
0
        SEC_PKCS7Attribute *attr;
1569
0
        SECItem *value;
1570
0
        SECItem encoded_attrs;
1571
1572
        /*
1573
         * We have a sigkey only for signedAndEnvelopedData, which is
1574
         * not supposed to have any authenticated attributes.
1575
         */
1576
0
        if (sigkey != NULL) {
1577
0
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1578
0
            goto done;
1579
0
        }
1580
1581
        /*
1582
         * PKCS #7 says that if there are any authenticated attributes,
1583
         * then there must be one for content type which matches the
1584
         * content type of the content being signed, and there must
1585
         * be one for message digest which matches our message digest.
1586
         * So check these things first.
1587
         * XXX Might be nice to have a compare-attribute-value function
1588
         * which could collapse the following nicely.
1589
         */
1590
0
        attr = sec_PKCS7FindAttribute(signerinfo->authAttr,
1591
0
                                      SEC_OID_PKCS9_CONTENT_TYPE, PR_TRUE);
1592
0
        value = sec_PKCS7AttributeValue(attr);
1593
0
        if (value == NULL || value->len != content_type->len) {
1594
0
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1595
0
            goto done;
1596
0
        }
1597
0
        if (PORT_Memcmp(value->data, content_type->data, value->len) != 0) {
1598
0
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1599
0
            goto done;
1600
0
        }
1601
1602
0
        attr = sec_PKCS7FindAttribute(signerinfo->authAttr,
1603
0
                                      SEC_OID_PKCS9_MESSAGE_DIGEST, PR_TRUE);
1604
0
        value = sec_PKCS7AttributeValue(attr);
1605
0
        if (value == NULL || value->len != digest->len) {
1606
0
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1607
0
            goto done;
1608
0
        }
1609
0
        if (PORT_Memcmp(value->data, digest->data, value->len) != 0) {
1610
0
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1611
0
            goto done;
1612
0
        }
1613
1614
        /*
1615
         * Okay, we met the constraints of the basic attributes.
1616
         * Now check the signature, which is based on a digest of
1617
         * the DER-encoded authenticated attributes.  So, first we
1618
         * encode and then we digest/verify.
1619
         */
1620
0
        encoded_attrs.data = NULL;
1621
0
        encoded_attrs.len = 0;
1622
0
        if (sec_PKCS7EncodeAttributes(NULL, &encoded_attrs,
1623
0
                                      &(signerinfo->authAttr)) == NULL)
1624
0
            goto done;
1625
1626
0
        if (encoded_attrs.data == NULL || encoded_attrs.len == 0) {
1627
0
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1628
0
            goto done;
1629
0
        }
1630
1631
0
        goodsig = (PRBool)(VFY_VerifyDataDirect(encoded_attrs.data,
1632
0
                                                encoded_attrs.len,
1633
0
                                                publickey, &(signerinfo->encDigest),
1634
0
                                                encTag, digestTag, NULL,
1635
0
                                                cinfo->pwfn_arg) == SECSuccess);
1636
0
        PORT_Free(encoded_attrs.data);
1637
0
    } else {
1638
0
        SECItem *sig;
1639
0
        SECItem holder;
1640
1641
        /*
1642
         * No authenticated attributes.
1643
         * The signature is based on the plain message digest.
1644
         */
1645
1646
0
        sig = &(signerinfo->encDigest);
1647
0
        if (sig->len == 0) { /* bad signature */
1648
0
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1649
0
            goto done;
1650
0
        }
1651
1652
0
        if (sigkey != NULL) {
1653
0
            sec_PKCS7CipherObject *decryptobj;
1654
0
            unsigned int buflen;
1655
1656
            /*
1657
             * For signedAndEnvelopedData, we first must decrypt the encrypted
1658
             * digest with the bulk encryption key.  The result is the normal
1659
             * encrypted digest (aka the signature).
1660
             */
1661
0
            decryptobj = sec_PKCS7CreateDecryptObject(sigkey, bulkid);
1662
0
            if (decryptobj == NULL)
1663
0
                goto done;
1664
1665
0
            buflen = sec_PKCS7DecryptLength(decryptobj, sig->len, PR_TRUE);
1666
0
            PORT_Assert(buflen);
1667
0
            if (buflen == 0) { /* something is wrong */
1668
0
                sec_PKCS7DestroyDecryptObject(decryptobj);
1669
0
                goto done;
1670
0
            }
1671
1672
0
            holder.data = (unsigned char *)PORT_Alloc(buflen);
1673
0
            if (holder.data == NULL) {
1674
0
                sec_PKCS7DestroyDecryptObject(decryptobj);
1675
0
                goto done;
1676
0
            }
1677
1678
0
            rv = sec_PKCS7Decrypt(decryptobj, holder.data, &holder.len, buflen,
1679
0
                                  sig->data, sig->len, PR_TRUE);
1680
0
            sec_PKCS7DestroyDecryptObject(decryptobj);
1681
0
            if (rv != SECSuccess) {
1682
0
                goto done;
1683
0
            }
1684
1685
0
            sig = &holder;
1686
0
        }
1687
1688
0
        goodsig = (PRBool)(VFY_VerifyDigestDirect(digest, publickey, sig,
1689
0
                                                  encTag, digestTag, cinfo->pwfn_arg) == SECSuccess);
1690
1691
0
        if (sigkey != NULL) {
1692
0
            PORT_Assert(sig == &holder);
1693
0
            PORT_ZFree(holder.data, holder.len);
1694
0
        }
1695
0
    }
1696
1697
0
    if (!goodsig) {
1698
        /*
1699
         * XXX Change the generic error into our specific one, because
1700
         * in that case we get a better explanation out of the Security
1701
         * Advisor.  This is really a bug in our error strings (the
1702
         * "generic" error has a lousy/wrong message associated with it
1703
         * which assumes the signature verification was done for the
1704
         * purposes of checking the issuer signature on a certificate)
1705
         * but this is at least an easy workaround and/or in the
1706
         * Security Advisor, which specifically checks for the error
1707
         * SEC_ERROR_PKCS7_BAD_SIGNATURE and gives more explanation
1708
         * in that case but does not similarly check for
1709
         * SEC_ERROR_BAD_SIGNATURE.  It probably should, but then would
1710
         * probably say the wrong thing in the case that it *was* the
1711
         * certificate signature check that failed during the cert
1712
         * verification done above.  Our error handling is really a mess.
1713
         */
1714
0
        if (PORT_GetError() == SEC_ERROR_BAD_SIGNATURE)
1715
0
            PORT_SetError(SEC_ERROR_PKCS7_BAD_SIGNATURE);
1716
0
    }
1717
1718
0
savecert:
1719
    /*
1720
     * Only save the smime profile if we are checking an email message and
1721
     * the cert has an email address in it.
1722
     */
1723
0
    if (cert->emailAddr && cert->emailAddr[0] &&
1724
0
        ((certusage == certUsageEmailSigner) ||
1725
0
         (certusage == certUsageEmailRecipient))) {
1726
0
        SECItem *profile = NULL;
1727
0
        int save_error;
1728
1729
        /*
1730
         * Remember the current error set because we do not care about
1731
         * anything set by the functions we are about to call.
1732
         */
1733
0
        save_error = PORT_GetError();
1734
1735
0
        if (goodsig && (signerinfo->authAttr != NULL)) {
1736
            /*
1737
             * If the signature is good, then we can save the S/MIME profile,
1738
             * if we have one.
1739
             */
1740
0
            SEC_PKCS7Attribute *attr;
1741
1742
0
            attr = sec_PKCS7FindAttribute(signerinfo->authAttr,
1743
0
                                          SEC_OID_PKCS9_SMIME_CAPABILITIES,
1744
0
                                          PR_TRUE);
1745
0
            profile = sec_PKCS7AttributeValue(attr);
1746
0
        }
1747
1748
0
        rv = CERT_SaveSMimeProfile(cert, profile, encoded_stime);
1749
1750
        /*
1751
         * Restore the saved error in case the calls above set a new
1752
         * one that we do not actually care about.
1753
         */
1754
0
        PORT_SetError(save_error);
1755
1756
        /*
1757
         * XXX Failure is not indicated anywhere -- the signature
1758
         * verification itself is unaffected by whether or not the
1759
         * profile was successfully saved.
1760
         */
1761
0
    }
1762
1763
0
done:
1764
1765
    /*
1766
     * See comment above about why we do not want to destroy cert
1767
     * itself here.
1768
     */
1769
1770
0
    if (certs != NULL)
1771
0
        CERT_DestroyCertArray(certs, certcount);
1772
1773
0
    if (publickey != NULL)
1774
0
        SECKEY_DestroyPublicKey(publickey);
1775
1776
0
    return goodsig;
1777
0
}
1778
1779
/*
1780
 * SEC_PKCS7VerifySignature
1781
 *      Look at a PKCS7 contentInfo and check if the signature is good.
1782
 *      The verification checks that the signing cert is valid and trusted
1783
 *      for the purpose specified by "certusage".
1784
 *
1785
 *      In addition, if "keepcerts" is true, add any new certificates found
1786
 *      into our local database.
1787
 */
1788
PRBool
1789
SEC_PKCS7VerifySignature(SEC_PKCS7ContentInfo *cinfo,
1790
                         SECCertUsage certusage,
1791
                         PRBool keepcerts)
1792
0
{
1793
0
    return sec_pkcs7_verify_signature(cinfo, certusage,
1794
0
                                      NULL, HASH_AlgNULL, keepcerts, NULL);
1795
0
}
1796
1797
/*
1798
 * SEC_PKCS7VerifyDetachedSignature
1799
 *      Look at a PKCS7 contentInfo and check if the signature matches
1800
 *      a passed-in digest (calculated, supposedly, from detached contents).
1801
 *      The verification checks that the signing cert is valid and trusted
1802
 *      for the purpose specified by "certusage".
1803
 *
1804
 *      In addition, if "keepcerts" is true, add any new certificates found
1805
 *      into our local database.
1806
 */
1807
PRBool
1808
SEC_PKCS7VerifyDetachedSignature(SEC_PKCS7ContentInfo *cinfo,
1809
                                 SECCertUsage certusage,
1810
                                 const SECItem *detached_digest,
1811
                                 HASH_HashType digest_type,
1812
                                 PRBool keepcerts)
1813
0
{
1814
0
    return sec_pkcs7_verify_signature(cinfo, certusage,
1815
0
                                      detached_digest, digest_type,
1816
0
                                      keepcerts, NULL);
1817
0
}
1818
1819
/*
1820
 * SEC_PKCS7VerifyDetachedSignatureAtTime
1821
 *      Look at a PKCS7 contentInfo and check if the signature matches
1822
 *      a passed-in digest (calculated, supposedly, from detached contents).
1823
 *      The verification checks that the signing cert is valid and trusted
1824
 *      for the purpose specified by "certusage" at time "atTime".
1825
 *
1826
 *      In addition, if "keepcerts" is true, add any new certificates found
1827
 *      into our local database.
1828
 */
1829
PRBool
1830
SEC_PKCS7VerifyDetachedSignatureAtTime(SEC_PKCS7ContentInfo *cinfo,
1831
                                       SECCertUsage certusage,
1832
                                       const SECItem *detached_digest,
1833
                                       HASH_HashType digest_type,
1834
                                       PRBool keepcerts,
1835
                                       PRTime atTime)
1836
0
{
1837
0
    return sec_pkcs7_verify_signature(cinfo, certusage,
1838
0
                                      detached_digest, digest_type,
1839
0
                                      keepcerts, &atTime);
1840
0
}
1841
1842
/*
1843
 * Return the asked-for portion of the name of the signer of a PKCS7
1844
 * signed object.
1845
 *
1846
 * Returns a pointer to allocated memory, which must be freed.
1847
 * A NULL return value is an error.
1848
 */
1849
1850
0
#define sec_common_name 1
1851
0
#define sec_email_address 2
1852
1853
static char *
1854
sec_pkcs7_get_signer_cert_info(SEC_PKCS7ContentInfo *cinfo, int selector)
1855
0
{
1856
0
    SECOidTag kind;
1857
0
    SEC_PKCS7SignerInfo **signerinfos;
1858
0
    CERTCertificate *signercert;
1859
0
    char *container;
1860
1861
0
    kind = SEC_PKCS7ContentType(cinfo);
1862
0
    switch (kind) {
1863
0
        default:
1864
0
        case SEC_OID_PKCS7_DATA:
1865
0
        case SEC_OID_PKCS7_DIGESTED_DATA:
1866
0
        case SEC_OID_PKCS7_ENVELOPED_DATA:
1867
0
        case SEC_OID_PKCS7_ENCRYPTED_DATA:
1868
0
            PORT_Assert(0);
1869
0
            return NULL;
1870
0
        case SEC_OID_PKCS7_SIGNED_DATA: {
1871
0
            SEC_PKCS7SignedData *sdp;
1872
1873
0
            sdp = cinfo->content.signedData;
1874
0
            signerinfos = sdp->signerInfos;
1875
0
        } break;
1876
0
        case SEC_OID_PKCS7_SIGNED_ENVELOPED_DATA: {
1877
0
            SEC_PKCS7SignedAndEnvelopedData *saedp;
1878
1879
0
            saedp = cinfo->content.signedAndEnvelopedData;
1880
0
            signerinfos = saedp->signerInfos;
1881
0
        } break;
1882
0
    }
1883
1884
0
    if (signerinfos == NULL || signerinfos[0] == NULL)
1885
0
        return NULL;
1886
1887
0
    signercert = signerinfos[0]->cert;
1888
1889
    /*
1890
     * No cert there; see if we can find one by calling verify ourselves.
1891
     */
1892
0
    if (signercert == NULL) {
1893
        /*
1894
         * The cert usage does not matter in this case, because we do not
1895
         * actually care about the verification itself, but we have to pick
1896
         * some valid usage to pass in.
1897
         */
1898
0
        (void)sec_pkcs7_verify_signature(cinfo, certUsageEmailSigner,
1899
0
                                         NULL, HASH_AlgNULL, PR_FALSE, NULL);
1900
0
        signercert = signerinfos[0]->cert;
1901
0
        if (signercert == NULL)
1902
0
            return NULL;
1903
0
    }
1904
1905
0
    switch (selector) {
1906
0
        case sec_common_name:
1907
0
            container = CERT_GetCommonName(&signercert->subject);
1908
0
            break;
1909
0
        case sec_email_address:
1910
0
            if (signercert->emailAddr && signercert->emailAddr[0]) {
1911
0
                container = PORT_Strdup(signercert->emailAddr);
1912
0
            } else {
1913
0
                container = NULL;
1914
0
            }
1915
0
            break;
1916
0
        default:
1917
0
            PORT_Assert(0);
1918
0
            container = NULL;
1919
0
            break;
1920
0
    }
1921
1922
0
    return container;
1923
0
}
1924
1925
char *
1926
SEC_PKCS7GetSignerCommonName(SEC_PKCS7ContentInfo *cinfo)
1927
0
{
1928
0
    return sec_pkcs7_get_signer_cert_info(cinfo, sec_common_name);
1929
0
}
1930
1931
char *
1932
SEC_PKCS7GetSignerEmailAddress(SEC_PKCS7ContentInfo *cinfo)
1933
0
{
1934
0
    return sec_pkcs7_get_signer_cert_info(cinfo, sec_email_address);
1935
0
}
1936
1937
/*
1938
 * Return the signing time, in UTCTime format, of a PKCS7 contentInfo.
1939
 */
1940
SECItem *
1941
SEC_PKCS7GetSigningTime(SEC_PKCS7ContentInfo *cinfo)
1942
0
{
1943
0
    SEC_PKCS7SignerInfo **signerinfos;
1944
0
    SEC_PKCS7Attribute *attr;
1945
1946
0
    if (SEC_PKCS7ContentType(cinfo) != SEC_OID_PKCS7_SIGNED_DATA)
1947
0
        return NULL;
1948
1949
0
    signerinfos = cinfo->content.signedData->signerInfos;
1950
1951
    /*
1952
     * No signature, or more than one, means no deal.
1953
     */
1954
0
    if (signerinfos == NULL || signerinfos[0] == NULL || signerinfos[1] != NULL)
1955
0
        return NULL;
1956
1957
0
    attr = sec_PKCS7FindAttribute(signerinfos[0]->authAttr,
1958
0
                                  SEC_OID_PKCS9_SIGNING_TIME, PR_TRUE);
1959
0
    return sec_PKCS7AttributeValue(attr);
1960
0
}