Coverage Report

Created: 2025-07-11 07:06

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