Coverage Report

Created: 2026-09-12 06:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl40/crypto/cms/cms_smime.c
Line
Count
Source
1
/*
2
 * Copyright 2008-2026 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#include "internal/cryptlib.h"
11
#include <openssl/asn1t.h>
12
#include <openssl/x509.h>
13
#include <openssl/x509v3.h>
14
#include <openssl/err.h>
15
#include <openssl/cms.h>
16
#include "cms_local.h"
17
#include "crypto/asn1.h"
18
#include "crypto/x509.h"
19
20
static BIO *cms_get_text_bio(BIO *out, unsigned int flags)
21
0
{
22
0
    BIO *rbio;
23
24
0
    if (out == NULL)
25
0
        rbio = BIO_new(BIO_s_null());
26
0
    else if (flags & CMS_TEXT) {
27
0
        rbio = BIO_new(BIO_s_mem());
28
0
        BIO_set_mem_eof_return(rbio, 0);
29
0
    } else
30
0
        rbio = out;
31
0
    return rbio;
32
0
}
33
34
static int cms_copy_content(BIO *out, BIO *in, unsigned int flags)
35
0
{
36
0
    unsigned char buf[4096];
37
0
    int r = 0, i;
38
0
    BIO *tmpout;
39
0
    BIO *aeadbuf = NULL;
40
41
0
    tmpout = cms_get_text_bio(out, flags);
42
43
0
    if (tmpout == NULL) {
44
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
45
0
        goto err;
46
0
    }
47
48
    /*
49
     * For AEAD content (AuthEnvelopedData) the integrity tag is only verified
50
     * once all the ciphertext has been processed, by the
51
     * BIO_get_cipher_status() call below. RFC 5083 requires that the plaintext
52
     * is not released to the caller until that verification succeeds, so
53
     * buffer it in memory and only forward it to the output BIO once the tag
54
     * has been checked. When CMS_TEXT is set tmpout is already a memory BIO
55
     * that is flushed only on success, so the extra buffering is not needed.
56
     */
57
0
    if (tmpout == out && BIO_method_type(in) == BIO_TYPE_CIPHER) {
58
0
        EVP_CIPHER_CTX *ctx = NULL;
59
60
0
        if (BIO_get_cipher_ctx(in, &ctx) > 0 && ctx != NULL
61
0
            && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))
62
0
                   & EVP_CIPH_FLAG_AEAD_CIPHER)
63
0
                != 0) {
64
0
            aeadbuf = BIO_new(BIO_s_mem());
65
0
            if (aeadbuf == NULL) {
66
0
                ERR_raise(ERR_LIB_CMS, ERR_R_BIO_LIB);
67
0
                goto err;
68
0
            }
69
            /* Return 0 (EOF) rather than a retryable -1 once drained. */
70
0
            BIO_set_mem_eof_return(aeadbuf, 0);
71
0
            tmpout = aeadbuf;
72
0
        }
73
0
    }
74
75
    /* Read all content through chain to process digest, decrypt etc */
76
0
    for (;;) {
77
0
        i = BIO_read(in, buf, sizeof(buf));
78
0
        if (i <= 0) {
79
0
            if (BIO_method_type(in) == BIO_TYPE_CIPHER) {
80
0
                if (BIO_get_cipher_status(in) <= 0)
81
0
                    goto err;
82
0
            }
83
0
            if (i < 0)
84
0
                goto err;
85
0
            break;
86
0
        }
87
88
0
        if (tmpout != NULL && (BIO_write(tmpout, buf, i) != i))
89
0
            goto err;
90
0
    }
91
92
0
    if (flags & CMS_TEXT) {
93
0
        if (!SMIME_text(tmpout, out)) {
94
0
            ERR_raise(ERR_LIB_CMS, CMS_R_SMIME_TEXT_ERROR);
95
0
            goto err;
96
0
        }
97
0
    } else if (aeadbuf != NULL) {
98
        /* Forward the AEAD BIO to out BIO as the tag has been verified. */
99
0
        for (;;) {
100
0
            i = BIO_read(aeadbuf, buf, sizeof(buf));
101
0
            if (i < 0)
102
0
                goto err;
103
0
            if (i == 0)
104
0
                break;
105
0
            if (BIO_write(out, buf, i) != i)
106
0
                goto err;
107
0
        }
108
0
    }
109
110
0
    r = 1;
111
0
err:
112
0
    if (tmpout != out)
113
0
        BIO_free(tmpout);
114
0
    return r;
115
0
}
116
117
static int check_content(CMS_ContentInfo *cms)
118
0
{
119
0
    ASN1_OCTET_STRING **pos = CMS_get0_content(cms);
120
121
0
    if (pos == NULL || *pos == NULL) {
122
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_CONTENT);
123
0
        return 0;
124
0
    }
125
0
    return 1;
126
0
}
127
128
static void do_free_upto(BIO *f, BIO *upto)
129
0
{
130
0
    if (upto != NULL) {
131
0
        BIO *tbio;
132
133
0
        do {
134
0
            tbio = BIO_pop(f);
135
0
            BIO_free(f);
136
0
            f = tbio;
137
0
        } while (f != NULL && f != upto);
138
0
    } else {
139
0
        BIO_free_all(f);
140
0
    }
141
0
}
142
143
int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags)
144
0
{
145
0
    BIO *cont;
146
0
    int r;
147
148
0
    if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_data) {
149
0
        ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_DATA);
150
0
        return 0;
151
0
    }
152
0
    cont = CMS_dataInit(cms, NULL);
153
0
    if (cont == NULL)
154
0
        return 0;
155
0
    r = cms_copy_content(out, cont, flags);
156
0
    BIO_free_all(cont);
157
0
    return r;
158
0
}
159
160
CMS_ContentInfo *CMS_data_create_ex(BIO *in, unsigned int flags,
161
    OSSL_LIB_CTX *libctx, const char *propq)
162
0
{
163
0
    CMS_ContentInfo *cms = ossl_cms_Data_create(libctx, propq);
164
165
0
    if (cms == NULL)
166
0
        return NULL;
167
168
0
    if ((flags & CMS_STREAM) || CMS_final(cms, in, NULL, flags))
169
0
        return cms;
170
171
0
    CMS_ContentInfo_free(cms);
172
0
    return NULL;
173
0
}
174
175
CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags)
176
0
{
177
0
    return CMS_data_create_ex(in, flags, NULL, NULL);
178
0
}
179
180
int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
181
    unsigned int flags)
182
0
{
183
0
    BIO *cont;
184
0
    int r;
185
186
0
    if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_digest) {
187
0
        ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_DIGESTED_DATA);
188
0
        return 0;
189
0
    }
190
191
0
    if (dcont == NULL && !check_content(cms))
192
0
        return 0;
193
194
0
    cont = CMS_dataInit(cms, dcont);
195
0
    if (cont == NULL)
196
0
        return 0;
197
198
0
    r = cms_copy_content(out, cont, flags);
199
0
    if (r)
200
0
        r = ossl_cms_DigestedData_do_final(cms, cont, 1);
201
0
    do_free_upto(cont, dcont);
202
0
    return r;
203
0
}
204
205
CMS_ContentInfo *CMS_digest_create_ex(BIO *in, const EVP_MD *md,
206
    unsigned int flags, OSSL_LIB_CTX *ctx,
207
    const char *propq)
208
0
{
209
0
    CMS_ContentInfo *cms;
210
211
    /*
212
     * Because the EVP_MD is cached and can be a legacy algorithm, we
213
     * cannot fetch the algorithm if it isn't supplied.
214
     */
215
0
    if (md == NULL)
216
0
        md = EVP_sha1();
217
0
    cms = ossl_cms_DigestedData_create(md, ctx, propq);
218
0
    if (cms == NULL)
219
0
        return NULL;
220
221
0
    if (!(flags & CMS_DETACHED))
222
0
        CMS_set_detached(cms, 0);
223
224
0
    if ((flags & CMS_STREAM) || CMS_final(cms, in, NULL, flags))
225
0
        return cms;
226
227
0
    CMS_ContentInfo_free(cms);
228
0
    return NULL;
229
0
}
230
231
CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md,
232
    unsigned int flags)
233
0
{
234
0
    return CMS_digest_create_ex(in, md, flags, NULL, NULL);
235
0
}
236
237
int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms,
238
    const unsigned char *key, size_t keylen,
239
    BIO *dcont, BIO *out, unsigned int flags)
240
0
{
241
0
    BIO *cont;
242
0
    int r;
243
244
0
    if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_pkcs7_encrypted) {
245
0
        ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_ENCRYPTED_DATA);
246
0
        return 0;
247
0
    }
248
249
0
    if (dcont == NULL && !check_content(cms))
250
0
        return 0;
251
252
0
    if (CMS_EncryptedData_set1_key(cms, NULL, key, keylen) <= 0)
253
0
        return 0;
254
0
    cont = CMS_dataInit(cms, dcont);
255
0
    if (cont == NULL)
256
0
        return 0;
257
0
    r = cms_copy_content(out, cont, flags);
258
0
    do_free_upto(cont, dcont);
259
0
    return r;
260
0
}
261
262
CMS_ContentInfo *CMS_EncryptedData_encrypt_ex(BIO *in, const EVP_CIPHER *cipher,
263
    const unsigned char *key,
264
    size_t keylen, unsigned int flags,
265
    OSSL_LIB_CTX *libctx,
266
    const char *propq)
267
0
{
268
0
    CMS_ContentInfo *cms;
269
270
0
    if (cipher == NULL) {
271
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_CIPHER);
272
0
        return NULL;
273
0
    }
274
0
    cms = CMS_ContentInfo_new_ex(libctx, propq);
275
0
    if (cms == NULL)
276
0
        return NULL;
277
0
    if (!CMS_EncryptedData_set1_key(cms, cipher, key, keylen))
278
0
        goto err;
279
280
0
    if (!(flags & CMS_DETACHED))
281
0
        CMS_set_detached(cms, 0);
282
283
0
    if ((flags & (CMS_STREAM | CMS_PARTIAL))
284
0
        || CMS_final(cms, in, NULL, flags))
285
0
        return cms;
286
287
0
err:
288
0
    CMS_ContentInfo_free(cms);
289
0
    return NULL;
290
0
}
291
292
CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher,
293
    const unsigned char *key,
294
    size_t keylen, unsigned int flags)
295
0
{
296
0
    return CMS_EncryptedData_encrypt_ex(in, cipher, key, keylen, flags, NULL,
297
0
        NULL);
298
0
}
299
300
static int cms_signerinfo_verify_cert(CMS_SignerInfo *si,
301
    X509_STORE *store,
302
    STACK_OF(X509) *untrusted,
303
    STACK_OF(X509_CRL) *crls,
304
    STACK_OF(X509) **chain,
305
    const CMS_CTX *cms_ctx)
306
0
{
307
0
    X509_STORE_CTX *ctx;
308
0
    X509 *signer;
309
0
    int i, j, r = 0;
310
311
0
    ctx = X509_STORE_CTX_new_ex(ossl_cms_ctx_get0_libctx(cms_ctx),
312
0
        ossl_cms_ctx_get0_propq(cms_ctx));
313
0
    if (ctx == NULL) {
314
0
        ERR_raise(ERR_LIB_CMS, ERR_R_X509_LIB);
315
0
        goto err;
316
0
    }
317
0
    CMS_SignerInfo_get0_algs(si, NULL, &signer, NULL, NULL);
318
0
    if (!X509_STORE_CTX_init(ctx, store, signer, untrusted)) {
319
0
        ERR_raise(ERR_LIB_CMS, CMS_R_STORE_INIT_ERROR);
320
0
        goto err;
321
0
    }
322
0
    X509_STORE_CTX_set_default(ctx, "smime_sign");
323
0
    if (crls != NULL)
324
0
        X509_STORE_CTX_set0_crls(ctx, crls);
325
326
0
    i = X509_verify_cert(ctx);
327
0
    if (i <= 0) {
328
0
        j = X509_STORE_CTX_get_error(ctx);
329
0
        ERR_raise_data(ERR_LIB_CMS, CMS_R_CERTIFICATE_VERIFY_ERROR,
330
0
            "Verify error: %s", X509_verify_cert_error_string(j));
331
0
        goto err;
332
0
    }
333
0
    r = 1;
334
335
    /* also send back the trust chain when required */
336
0
    if (chain != NULL)
337
0
        *chain = X509_STORE_CTX_get1_chain(ctx);
338
0
err:
339
0
    X509_STORE_CTX_free(ctx);
340
0
    return r;
341
0
}
342
343
/* This strongly overlaps with PKCS7_verify() */
344
int CMS_verify(CMS_ContentInfo *cms, const STACK_OF(X509) *certs,
345
    X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags)
346
0
{
347
0
    CMS_SignerInfo *si;
348
0
    STACK_OF(CMS_SignerInfo) *sinfos;
349
0
    STACK_OF(X509) *untrusted = NULL;
350
0
    STACK_OF(X509_CRL) *crls = NULL;
351
0
    STACK_OF(X509) **si_chains = NULL;
352
0
    X509 *signer;
353
0
    int i, scount = 0, ret = 0;
354
0
    BIO *cmsbio = NULL, *tmpin = NULL, *tmpout = NULL;
355
0
    int cadesVerify = (flags & CMS_CADES) != 0;
356
0
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
357
358
0
    if (dcont == NULL && !check_content(cms))
359
0
        return 0;
360
0
    if (dcont != NULL && !(flags & CMS_BINARY)) {
361
0
        const ASN1_OBJECT *coid = CMS_get0_eContentType(cms);
362
363
0
        if (OBJ_obj2nid(coid) == NID_id_ct_asciiTextWithCRLF)
364
0
            flags |= CMS_ASCIICRLF;
365
0
    }
366
367
    /* Attempt to find all signer certificates */
368
369
0
    sinfos = CMS_get0_SignerInfos(cms);
370
371
0
    if (sk_CMS_SignerInfo_num(sinfos) <= 0) {
372
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_SIGNERS);
373
0
        goto err;
374
0
    }
375
376
0
    for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
377
0
        si = sk_CMS_SignerInfo_value(sinfos, i);
378
0
        CMS_SignerInfo_get0_algs(si, NULL, &signer, NULL, NULL);
379
0
        if (signer != NULL)
380
0
            scount++;
381
0
    }
382
383
0
    if (scount != sk_CMS_SignerInfo_num(sinfos))
384
0
        scount += CMS_set1_signers_certs(cms, certs, flags);
385
386
0
    if (scount != sk_CMS_SignerInfo_num(sinfos)) {
387
0
        ERR_raise(ERR_LIB_CMS, CMS_R_SIGNER_CERTIFICATE_NOT_FOUND);
388
0
        goto err;
389
0
    }
390
391
    /* Attempt to verify all signers certs */
392
    /* at this point scount == sk_CMS_SignerInfo_num(sinfos) */
393
394
0
    if ((flags & CMS_NO_SIGNER_CERT_VERIFY) == 0 || cadesVerify) {
395
0
        if (cadesVerify) {
396
            /* Certificate trust chain is required to check CAdES signature */
397
0
            si_chains = OPENSSL_calloc(scount, sizeof(si_chains[0]));
398
0
            if (si_chains == NULL)
399
0
                goto err;
400
0
        }
401
0
        if (!ossl_cms_get1_certs_ex(cms, &untrusted))
402
0
            goto err;
403
0
        if (sk_X509_num(certs) > 0
404
0
            && !ossl_x509_add_certs_new(&untrusted, certs,
405
0
                X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
406
0
            goto err;
407
408
0
        if ((flags & CMS_NOCRL) == 0
409
0
            && !ossl_cms_get1_crls_ex(cms, &crls))
410
0
            goto err;
411
0
        for (i = 0; i < scount; i++) {
412
0
            si = sk_CMS_SignerInfo_value(sinfos, i);
413
414
0
            if (!cms_signerinfo_verify_cert(si, store, untrusted, crls,
415
0
                    si_chains ? &si_chains[i] : NULL,
416
0
                    ctx))
417
0
                goto err;
418
0
        }
419
0
    }
420
421
    /* Attempt to verify all SignerInfo signed attribute signatures */
422
423
0
    if ((flags & CMS_NO_ATTR_VERIFY) == 0 || cadesVerify) {
424
0
        for (i = 0; i < scount; i++) {
425
0
            si = sk_CMS_SignerInfo_value(sinfos, i);
426
0
            if (CMS_signed_get_attr_count(si) < 0)
427
0
                continue;
428
0
            if (CMS_SignerInfo_verify(si) <= 0)
429
0
                goto err;
430
0
            if (cadesVerify) {
431
0
                STACK_OF(X509) *si_chain = si_chains ? si_chains[i] : NULL;
432
433
0
                if (ossl_cms_check_signing_certs(si, si_chain) <= 0)
434
0
                    goto err;
435
0
            }
436
0
        }
437
0
    }
438
439
    /*
440
     * Performance optimization: if the content is a memory BIO then store
441
     * its contents in a temporary read only memory BIO. This avoids
442
     * potentially large numbers of slow copies of data which will occur when
443
     * reading from a read write memory BIO when signatures are calculated.
444
     */
445
446
0
    if (dcont != NULL && (BIO_method_type(dcont) == BIO_TYPE_MEM)) {
447
0
        char *ptr;
448
0
        long len;
449
450
0
        len = BIO_get_mem_data(dcont, &ptr);
451
0
        tmpin = (len == 0) ? dcont : BIO_new_mem_buf(ptr, len);
452
0
        if (tmpin == NULL) {
453
0
            ERR_raise(ERR_LIB_CMS, ERR_R_BIO_LIB);
454
0
            goto err2;
455
0
        }
456
0
    } else {
457
0
        tmpin = dcont;
458
0
    }
459
    /*
460
     * If not binary mode and detached generate digests by *writing* through
461
     * the BIO. That makes it possible to canonicalise the input.
462
     */
463
0
    if (!(flags & SMIME_BINARY) && dcont) {
464
        /*
465
         * Create output BIO so we can either handle text or to ensure
466
         * included content doesn't override detached content.
467
         */
468
0
        tmpout = cms_get_text_bio(out, flags);
469
0
        if (tmpout == NULL) {
470
0
            ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
471
0
            goto err;
472
0
        }
473
0
        cmsbio = CMS_dataInit(cms, tmpout);
474
0
        if (cmsbio == NULL)
475
0
            goto err;
476
        /*
477
         * Don't use SMIME_TEXT for verify: it adds headers and we want to
478
         * remove them.
479
         */
480
0
        if (!SMIME_crlf_copy(dcont, cmsbio, flags & ~SMIME_TEXT))
481
0
            goto err;
482
483
0
        if (flags & CMS_TEXT) {
484
0
            if (!SMIME_text(tmpout, out)) {
485
0
                ERR_raise(ERR_LIB_CMS, CMS_R_SMIME_TEXT_ERROR);
486
0
                goto err;
487
0
            }
488
0
        }
489
0
    } else {
490
0
        cmsbio = CMS_dataInit(cms, tmpin);
491
0
        if (cmsbio == NULL)
492
0
            goto err;
493
494
0
        if (!cms_copy_content(out, cmsbio, flags))
495
0
            goto err;
496
0
    }
497
0
    if (!(flags & CMS_NO_CONTENT_VERIFY)) {
498
0
        for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
499
0
            si = sk_CMS_SignerInfo_value(sinfos, i);
500
0
            if (CMS_SignerInfo_verify_ex(si, cmsbio, tmpin) <= 0) {
501
0
                ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_VERIFY_ERROR);
502
0
                goto err;
503
0
            }
504
0
        }
505
0
    }
506
507
0
    ret = 1;
508
0
err:
509
0
    if (!(flags & SMIME_BINARY) && dcont) {
510
0
        do_free_upto(cmsbio, tmpout);
511
0
        if (tmpin != dcont)
512
0
            BIO_free(tmpin);
513
0
    } else {
514
0
        if (dcont && (tmpin == dcont))
515
0
            do_free_upto(cmsbio, dcont);
516
0
        else if (cmsbio != NULL)
517
0
            BIO_free_all(cmsbio);
518
0
        else
519
0
            BIO_free(tmpin);
520
0
    }
521
522
0
    if (out != tmpout)
523
0
        BIO_free_all(tmpout);
524
525
0
err2:
526
0
    if (si_chains != NULL) {
527
0
        for (i = 0; i < scount; ++i)
528
0
            OSSL_STACK_OF_X509_free(si_chains[i]);
529
0
        OPENSSL_free(si_chains);
530
0
    }
531
0
    sk_X509_pop_free(untrusted, X509_free);
532
0
    sk_X509_CRL_pop_free(crls, X509_CRL_free);
533
534
0
    return ret;
535
0
}
536
537
int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms,
538
    const STACK_OF(X509) *certs,
539
    X509_STORE *store, unsigned int flags)
540
0
{
541
0
    int r;
542
543
0
    flags &= ~(CMS_DETACHED | CMS_TEXT);
544
0
    r = CMS_verify(rcms, certs, store, NULL, NULL, flags);
545
0
    if (r <= 0)
546
0
        return r;
547
0
    return ossl_cms_Receipt_verify(rcms, ocms);
548
0
}
549
550
CMS_ContentInfo *CMS_sign_ex(X509 *signcert, EVP_PKEY *pkey,
551
    const STACK_OF(X509) *certs, BIO *data,
552
    unsigned int flags, OSSL_LIB_CTX *libctx,
553
    const char *propq)
554
0
{
555
0
    CMS_ContentInfo *cms;
556
0
    int i;
557
558
0
    cms = CMS_ContentInfo_new_ex(libctx, propq);
559
0
    if (cms == NULL || !CMS_SignedData_init(cms)) {
560
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
561
0
        goto err;
562
0
    }
563
0
    if (flags & CMS_ASCIICRLF
564
0
        && !CMS_set1_eContentType(cms,
565
0
            OBJ_nid2obj(NID_id_ct_asciiTextWithCRLF))) {
566
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
567
0
        goto err;
568
0
    }
569
570
0
    if (pkey != NULL && !CMS_add1_signer(cms, signcert, pkey, NULL, flags)) {
571
0
        ERR_raise(ERR_LIB_CMS, CMS_R_ADD_SIGNER_ERROR);
572
0
        goto err;
573
0
    }
574
575
0
    for (i = 0; i < sk_X509_num(certs); i++) {
576
0
        X509 *x = sk_X509_value(certs, i);
577
578
0
        if (!CMS_add1_cert(cms, x)) {
579
0
            ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
580
0
            goto err;
581
0
        }
582
0
    }
583
584
0
    if (!(flags & CMS_DETACHED))
585
0
        CMS_set_detached(cms, 0);
586
587
0
    if ((flags & (CMS_STREAM | CMS_PARTIAL))
588
0
        || CMS_final(cms, data, NULL, flags))
589
0
        return cms;
590
0
    else
591
0
        goto err;
592
593
0
err:
594
0
    CMS_ContentInfo_free(cms);
595
0
    return NULL;
596
0
}
597
598
CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey,
599
    const STACK_OF(X509) *certs, BIO *data, unsigned int flags)
600
0
{
601
0
    return CMS_sign_ex(signcert, pkey, certs, data, flags, NULL, NULL);
602
0
}
603
604
CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si,
605
    X509 *signcert, EVP_PKEY *pkey,
606
    const STACK_OF(X509) *certs, unsigned int flags)
607
0
{
608
0
    CMS_SignerInfo *rct_si;
609
0
    CMS_ContentInfo *cms = NULL;
610
0
    ASN1_OCTET_STRING **pos, *os = NULL;
611
0
    BIO *rct_cont = NULL;
612
0
    int r = 0;
613
0
    const CMS_CTX *ctx = si->cms_ctx;
614
615
0
    flags &= ~(CMS_STREAM | CMS_TEXT);
616
    /* Not really detached but avoids content being allocated */
617
0
    flags |= CMS_PARTIAL | CMS_BINARY | CMS_DETACHED;
618
0
    if (pkey == NULL || signcert == NULL) {
619
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY_OR_CERT);
620
0
        return NULL;
621
0
    }
622
623
    /* Initialize signed data */
624
625
0
    cms = CMS_sign_ex(NULL, NULL, certs, NULL, flags,
626
0
        ossl_cms_ctx_get0_libctx(ctx),
627
0
        ossl_cms_ctx_get0_propq(ctx));
628
0
    if (cms == NULL)
629
0
        goto err;
630
631
    /* Set inner content type to signed receipt */
632
0
    if (!CMS_set1_eContentType(cms, OBJ_nid2obj(NID_id_smime_ct_receipt)))
633
0
        goto err;
634
635
0
    rct_si = CMS_add1_signer(cms, signcert, pkey, NULL, flags);
636
0
    if (!rct_si) {
637
0
        ERR_raise(ERR_LIB_CMS, CMS_R_ADD_SIGNER_ERROR);
638
0
        goto err;
639
0
    }
640
641
0
    os = ossl_cms_encode_Receipt(si);
642
0
    if (os == NULL)
643
0
        goto err;
644
645
    /* Set content to digest */
646
0
    rct_cont = BIO_new_mem_buf(os->data, os->length);
647
0
    if (rct_cont == NULL)
648
0
        goto err;
649
650
    /* Add msgSigDigest attribute */
651
652
0
    if (!ossl_cms_msgSigDigest_add1(rct_si, si))
653
0
        goto err;
654
655
    /* Finalize structure */
656
0
    if (!CMS_final(cms, rct_cont, NULL, flags))
657
0
        goto err;
658
659
    /* Set embedded content */
660
0
    pos = CMS_get0_content(cms);
661
0
    if (pos == NULL)
662
0
        goto err;
663
0
    *pos = os;
664
665
0
    r = 1;
666
667
0
err:
668
0
    BIO_free(rct_cont);
669
0
    if (r)
670
0
        return cms;
671
0
    CMS_ContentInfo_free(cms);
672
0
    ASN1_OCTET_STRING_free(os);
673
0
    return NULL;
674
0
}
675
676
CMS_ContentInfo *CMS_encrypt_ex(const STACK_OF(X509) *certs, BIO *data,
677
    const EVP_CIPHER *cipher, unsigned int flags,
678
    OSSL_LIB_CTX *libctx, const char *propq)
679
0
{
680
0
    CMS_ContentInfo *cms;
681
0
    int i;
682
0
    X509 *recip;
683
684
0
    cms = (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)
685
0
        ? CMS_AuthEnvelopedData_create_ex(cipher, libctx, propq)
686
0
        : CMS_EnvelopedData_create_ex(cipher, libctx, propq);
687
0
    if (cms == NULL) {
688
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
689
0
        goto err;
690
0
    }
691
0
    for (i = 0; i < sk_X509_num(certs); i++) {
692
0
        recip = sk_X509_value(certs, i);
693
0
        if (!CMS_add1_recipient_cert(cms, recip, flags)) {
694
0
            ERR_raise(ERR_LIB_CMS, CMS_R_RECIPIENT_ERROR);
695
0
            goto err;
696
0
        }
697
0
    }
698
699
0
    if (!(flags & CMS_DETACHED))
700
0
        CMS_set_detached(cms, 0);
701
702
0
    if ((flags & (CMS_STREAM | CMS_PARTIAL))
703
0
        || CMS_final(cms, data, NULL, flags))
704
0
        return cms;
705
0
    else
706
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
707
708
0
err:
709
0
    CMS_ContentInfo_free(cms);
710
0
    return NULL;
711
0
}
712
713
CMS_ContentInfo *CMS_encrypt(const STACK_OF(X509) *certs, BIO *data,
714
    const EVP_CIPHER *cipher, unsigned int flags)
715
0
{
716
0
    return CMS_encrypt_ex(certs, data, cipher, flags, NULL, NULL);
717
0
}
718
719
static int cms_kari_set1_pkey_and_peer(CMS_ContentInfo *cms,
720
    CMS_RecipientInfo *ri,
721
    EVP_PKEY *pk, X509 *cert, X509 *peer)
722
0
{
723
0
    int i;
724
0
    STACK_OF(CMS_RecipientEncryptedKey) *reks;
725
0
    CMS_RecipientEncryptedKey *rek;
726
727
0
    reks = CMS_RecipientInfo_kari_get0_reks(ri);
728
0
    for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++) {
729
0
        int rv;
730
731
0
        rek = sk_CMS_RecipientEncryptedKey_value(reks, i);
732
0
        if (cert != NULL && CMS_RecipientEncryptedKey_cert_cmp(rek, cert))
733
0
            continue;
734
0
        CMS_RecipientInfo_kari_set0_pkey_and_peer(ri, pk, peer);
735
0
        rv = CMS_RecipientInfo_kari_decrypt(cms, ri, rek);
736
0
        CMS_RecipientInfo_kari_set0_pkey(ri, NULL);
737
0
        if (rv > 0)
738
0
            return 1;
739
0
        return cert == NULL ? 0 : -1;
740
0
    }
741
0
    return 0;
742
0
}
743
744
int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert)
745
0
{
746
0
    return CMS_decrypt_set1_pkey_and_peer(cms, pk, cert, NULL);
747
0
}
748
749
int CMS_decrypt_set1_pkey_and_peer(CMS_ContentInfo *cms, EVP_PKEY *pk,
750
    X509 *cert, X509 *peer)
751
0
{
752
0
    STACK_OF(CMS_RecipientInfo) *ris = CMS_get0_RecipientInfos(cms);
753
0
    CMS_RecipientInfo *ri;
754
0
    int i, r, cms_pkey_ri_type;
755
0
    int debug = 0, match_ri = 0;
756
0
    CMS_EncryptedContentInfo *ec = ossl_cms_get0_env_enc_content(cms);
757
758
    /* Prevent mem leak on earlier CMS_decrypt_set1_{pkey_and_peer,password} */
759
0
    if (ec != NULL) {
760
0
        OPENSSL_clear_free(ec->key, ec->keylen);
761
0
        ec->key = NULL;
762
0
        ec->keylen = 0;
763
0
    }
764
765
0
    if (ris != NULL && ec != NULL)
766
0
        debug = ec->debug;
767
768
0
    cms_pkey_ri_type = ossl_cms_pkey_get_ri_type(pk);
769
0
    if (cms_pkey_ri_type == CMS_RECIPINFO_NONE) {
770
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
771
0
        return 0;
772
0
    }
773
774
0
    for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) {
775
0
        int ri_type;
776
777
0
        ri = sk_CMS_RecipientInfo_value(ris, i);
778
0
        ri_type = CMS_RecipientInfo_type(ri);
779
0
        if (!ossl_cms_pkey_is_ri_type_supported(pk, ri_type))
780
0
            continue;
781
0
        match_ri = 1;
782
0
        if (ri_type == CMS_RECIPINFO_AGREE) {
783
0
            r = cms_kari_set1_pkey_and_peer(cms, ri, pk, cert, peer);
784
0
            if (r > 0)
785
0
                return 1;
786
0
            if (r < 0)
787
0
                return 0;
788
0
        } else if (ri_type == CMS_RECIPINFO_KEM) {
789
0
            if (cert == NULL || !CMS_RecipientInfo_kemri_cert_cmp(ri, cert)) {
790
0
                CMS_RecipientInfo_kemri_set0_pkey(ri, pk);
791
0
                r = CMS_RecipientInfo_decrypt(cms, ri);
792
0
                CMS_RecipientInfo_kemri_set0_pkey(ri, NULL);
793
0
                if (cert != NULL || r > 0)
794
0
                    return r;
795
0
            }
796
0
        }
797
        /* If we have a cert, try matching RecipientInfo, else try them all */
798
0
        else if (cert == NULL || !CMS_RecipientInfo_ktri_cert_cmp(ri, cert)) {
799
0
            if (!EVP_PKEY_up_ref(pk))
800
0
                return 0;
801
0
            CMS_RecipientInfo_set0_pkey(ri, pk);
802
0
            r = CMS_RecipientInfo_decrypt(cms, ri);
803
0
            CMS_RecipientInfo_set0_pkey(ri, NULL);
804
0
            if (cert != NULL) {
805
                /*
806
                 * If not debugging clear any error and return success to
807
                 * avoid leaking of information useful to MMA
808
                 */
809
0
                if (!debug) {
810
0
                    ERR_clear_error();
811
0
                    return 1;
812
0
                }
813
0
                if (r > 0)
814
0
                    return 1;
815
0
                ERR_raise(ERR_LIB_CMS, CMS_R_DECRYPT_ERROR);
816
0
                return 0;
817
0
            }
818
            /*
819
             * If no cert and not debugging don't leave loop after first
820
             * successful decrypt. Always attempt to decrypt all recipients
821
             * to avoid leaking timing of a successful decrypt.
822
             */
823
0
            else if (r > 0 && (debug || cms_pkey_ri_type != CMS_RECIPINFO_TRANS))
824
0
                return 1;
825
0
        }
826
0
    }
827
    /* If no cert, key transport and not debugging always return success */
828
0
    if (cert == NULL
829
0
        && cms_pkey_ri_type == CMS_RECIPINFO_TRANS
830
0
        && match_ri
831
0
        && !debug) {
832
0
        ERR_clear_error();
833
0
        return 1;
834
0
    }
835
836
0
    if (!match_ri)
837
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_RECIPIENT);
838
0
    return 0;
839
0
}
840
841
int CMS_decrypt_set1_key(CMS_ContentInfo *cms,
842
    unsigned char *key, size_t keylen,
843
    const unsigned char *id, size_t idlen)
844
0
{
845
0
    STACK_OF(CMS_RecipientInfo) *ris;
846
0
    CMS_RecipientInfo *ri;
847
0
    int i, r, match_ri = 0;
848
849
0
    ris = CMS_get0_RecipientInfos(cms);
850
0
    for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) {
851
0
        ri = sk_CMS_RecipientInfo_value(ris, i);
852
0
        if (CMS_RecipientInfo_type(ri) != CMS_RECIPINFO_KEK)
853
0
            continue;
854
855
        /* If we have an id, try matching RecipientInfo, else try them all */
856
0
        if (id == NULL
857
0
            || (CMS_RecipientInfo_kekri_id_cmp(ri, id, idlen) == 0)) {
858
0
            match_ri = 1;
859
0
            CMS_RecipientInfo_set0_key(ri, key, keylen);
860
0
            r = CMS_RecipientInfo_decrypt(cms, ri);
861
0
            CMS_RecipientInfo_set0_key(ri, NULL, 0);
862
0
            if (r > 0)
863
0
                return 1;
864
0
            if (id != NULL) {
865
0
                ERR_raise(ERR_LIB_CMS, CMS_R_DECRYPT_ERROR);
866
0
                return 0;
867
0
            }
868
0
            ERR_clear_error();
869
0
        }
870
0
    }
871
872
0
    if (!match_ri)
873
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_RECIPIENT);
874
0
    return 0;
875
0
}
876
877
int CMS_decrypt_set1_password(CMS_ContentInfo *cms,
878
    unsigned char *pass, ossl_ssize_t passlen)
879
0
{
880
0
    STACK_OF(CMS_RecipientInfo) *ris = CMS_get0_RecipientInfos(cms);
881
0
    CMS_RecipientInfo *ri;
882
0
    int i, r, match_ri = 0;
883
0
    CMS_EncryptedContentInfo *ec = ossl_cms_get0_env_enc_content(cms);
884
885
    /* Prevent mem leak on earlier CMS_decrypt_set1_{pkey_and_peer,password} */
886
0
    if (ec != NULL) {
887
0
        OPENSSL_clear_free(ec->key, ec->keylen);
888
0
        ec->key = NULL;
889
0
        ec->keylen = 0;
890
0
    }
891
892
0
    for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) {
893
0
        ri = sk_CMS_RecipientInfo_value(ris, i);
894
0
        if (CMS_RecipientInfo_type(ri) != CMS_RECIPINFO_PASS)
895
0
            continue;
896
897
        /* Must try each PasswordRecipientInfo */
898
0
        match_ri = 1;
899
0
        CMS_RecipientInfo_set0_password(ri, pass, passlen);
900
0
        r = CMS_RecipientInfo_decrypt(cms, ri);
901
0
        CMS_RecipientInfo_set0_password(ri, NULL, 0);
902
0
        if (r > 0)
903
0
            return 1;
904
0
    }
905
906
0
    if (!match_ri)
907
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_RECIPIENT);
908
0
    return 0;
909
0
}
910
911
int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert,
912
    BIO *dcont, BIO *out, unsigned int flags)
913
0
{
914
0
    int r;
915
0
    BIO *cont;
916
0
    CMS_EncryptedContentInfo *ec;
917
0
    int nid = OBJ_obj2nid(CMS_get0_type(cms));
918
919
0
    if (nid != NID_pkcs7_enveloped
920
0
        && nid != NID_id_smime_ct_authEnvelopedData) {
921
0
        ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_ENVELOPED_DATA);
922
0
        return 0;
923
0
    }
924
0
    if (dcont == NULL && !check_content(cms))
925
0
        return 0;
926
0
    ec = ossl_cms_get0_env_enc_content(cms);
927
0
    ec->debug = (flags & CMS_DEBUG_DECRYPT) != 0;
928
0
    ec->havenocert = cert == NULL;
929
0
    if (pk == NULL && cert == NULL && dcont == NULL && out == NULL)
930
0
        return 1;
931
0
    if (pk != NULL && !CMS_decrypt_set1_pkey(cms, pk, cert))
932
0
        return 0;
933
0
    cont = CMS_dataInit(cms, dcont);
934
0
    if (cont == NULL)
935
0
        return 0;
936
0
    r = cms_copy_content(out, cont, flags);
937
0
    do_free_upto(cont, dcont);
938
0
    return r;
939
0
}
940
941
int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, unsigned int flags)
942
0
{
943
0
    BIO *cmsbio;
944
0
    int ret = 0;
945
946
0
    if ((cmsbio = CMS_dataInit(cms, dcont)) == NULL) {
947
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CMS_LIB);
948
0
        return 0;
949
0
    }
950
951
0
    if (!SMIME_crlf_copy(data, cmsbio, flags)) {
952
0
        goto err;
953
0
    }
954
955
0
    (void)BIO_flush(cmsbio);
956
957
0
    if (!CMS_dataFinal_ex(cms, cmsbio, data)) {
958
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CMS_DATAFINAL_ERROR);
959
0
        goto err;
960
0
    }
961
962
0
    ret = 1;
963
964
0
err:
965
0
    do_free_upto(cmsbio, dcont);
966
967
0
    return ret;
968
0
}
969
970
int CMS_final_digest(CMS_ContentInfo *cms,
971
    const unsigned char *md, unsigned int mdlen,
972
    BIO *dcont, unsigned int flags)
973
0
{
974
0
    BIO *cmsbio;
975
0
    int ret = 0;
976
977
0
    if ((cmsbio = CMS_dataInit(cms, dcont)) == NULL) {
978
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CMS_LIB);
979
0
        return 0;
980
0
    }
981
982
0
    (void)BIO_flush(cmsbio);
983
984
0
    if (!ossl_cms_DataFinal(cms, cmsbio, NULL, md, mdlen)) {
985
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CMS_DATAFINAL_ERROR);
986
0
        goto err;
987
0
    }
988
0
    ret = 1;
989
990
0
err:
991
0
    do_free_upto(cmsbio, dcont);
992
0
    return ret;
993
0
}
994
995
#ifndef OPENSSL_NO_ZLIB
996
997
int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
998
    unsigned int flags)
999
{
1000
    BIO *cont;
1001
    int r;
1002
1003
    if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_id_smime_ct_compressedData) {
1004
        ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_COMPRESSED_DATA);
1005
        return 0;
1006
    }
1007
1008
    if (dcont == NULL && !check_content(cms))
1009
        return 0;
1010
1011
    cont = CMS_dataInit(cms, dcont);
1012
    if (cont == NULL)
1013
        return 0;
1014
    r = cms_copy_content(out, cont, flags);
1015
    do_free_upto(cont, dcont);
1016
    return r;
1017
}
1018
1019
CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags)
1020
{
1021
    CMS_ContentInfo *cms;
1022
1023
    if (comp_nid <= 0)
1024
        comp_nid = NID_zlib_compression;
1025
    cms = ossl_cms_CompressedData_create(comp_nid, NULL, NULL);
1026
    if (cms == NULL)
1027
        return NULL;
1028
1029
    if (!(flags & CMS_DETACHED))
1030
        CMS_set_detached(cms, 0);
1031
1032
    if ((flags & CMS_STREAM) || CMS_final(cms, in, NULL, flags))
1033
        return cms;
1034
1035
    CMS_ContentInfo_free(cms);
1036
    return NULL;
1037
}
1038
1039
#else
1040
1041
int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
1042
    unsigned int flags)
1043
0
{
1044
0
    ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1045
0
    return 0;
1046
0
}
1047
1048
CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags)
1049
0
{
1050
0
    ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1051
    return NULL;
1052
0
}
1053
1054
#endif