Coverage Report

Created: 2026-09-12 06:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl41/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, n = 0, 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
        /* Reset verification results */
382
0
        si->verify_result = 1; /* so far, fine */
383
0
        si->cert_verified = 0;
384
0
        si->attr_verified = 0;
385
0
        si->content_verified = 0;
386
0
    }
387
388
0
    if (scount != sk_CMS_SignerInfo_num(sinfos))
389
0
        scount += CMS_set1_signers_certs(cms, certs, flags);
390
391
0
    if (scount != sk_CMS_SignerInfo_num(sinfos)) {
392
0
        ERR_raise(ERR_LIB_CMS, CMS_R_SIGNER_CERTIFICATE_NOT_FOUND);
393
0
        goto err;
394
0
    }
395
396
    /* Attempt to verify all signers certs */
397
    /* at this point scount == sk_CMS_SignerInfo_num(sinfos) */
398
399
0
    if ((flags & CMS_NO_SIGNER_CERT_VERIFY) == 0 || cadesVerify) {
400
0
        if (cadesVerify) {
401
            /* Certificate trust chain is required to check CAdES signature */
402
0
            si_chains = OPENSSL_calloc(scount, sizeof(si_chains[0]));
403
0
            if (si_chains == NULL)
404
0
                goto err;
405
0
        }
406
0
        if (!ossl_cms_get1_certs_ex(cms, &untrusted))
407
0
            goto err;
408
0
        if (sk_X509_num(certs) > 0
409
0
            && !ossl_x509_add_certs_new(&untrusted, certs,
410
0
                X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP))
411
0
            goto err;
412
413
0
        if ((flags & CMS_NOCRL) == 0
414
0
            && !ossl_cms_get1_crls_ex(cms, &crls))
415
0
            goto err;
416
0
        for (i = 0; i < scount; i++) {
417
0
            si = sk_CMS_SignerInfo_value(sinfos, i);
418
419
0
            if (!cms_signerinfo_verify_cert(si, store, untrusted, crls,
420
0
                    si_chains ? &si_chains[i] : NULL,
421
0
                    ctx)) {
422
0
                si->verify_result = 0;
423
0
                continue;
424
0
            }
425
0
            si->cert_verified = 1;
426
0
        }
427
0
    }
428
429
    /* Attempt to verify all SignerInfo signed attribute signatures */
430
431
0
    if ((flags & CMS_NO_ATTR_VERIFY) == 0 || cadesVerify) {
432
0
        for (i = 0; i < scount; i++) {
433
0
            si = sk_CMS_SignerInfo_value(sinfos, i);
434
0
            if (!si->verify_result)
435
0
                continue;
436
0
            if (CMS_signed_get_attr_count(si) < 0) {
437
0
                si->attr_verified = 1;
438
0
                continue;
439
0
            }
440
0
            if (CMS_SignerInfo_verify(si) <= 0) {
441
0
                si->verify_result = 0;
442
0
                continue;
443
0
            }
444
0
            if (cadesVerify) {
445
0
                STACK_OF(X509) *si_chain = si_chains ? si_chains[i] : NULL;
446
447
0
                if (ossl_cms_check_signing_certs(si, si_chain) <= 0) {
448
0
                    si->verify_result = 0;
449
0
                    continue;
450
0
                }
451
0
            }
452
0
            si->attr_verified = 1;
453
0
        }
454
0
    }
455
456
    /*
457
     * Performance optimization: if the content is a memory BIO then store
458
     * its contents in a temporary read only memory BIO. This avoids
459
     * potentially large numbers of slow copies of data which will occur when
460
     * reading from a read write memory BIO when signatures are calculated.
461
     */
462
463
0
    if (dcont != NULL && (BIO_method_type(dcont) == BIO_TYPE_MEM)) {
464
0
        char *ptr;
465
0
        long len;
466
467
0
        len = BIO_get_mem_data(dcont, &ptr);
468
0
        tmpin = (len == 0) ? dcont : BIO_new_mem_buf(ptr, len);
469
0
        if (tmpin == NULL) {
470
0
            ERR_raise(ERR_LIB_CMS, ERR_R_BIO_LIB);
471
0
            goto err2;
472
0
        }
473
0
    } else {
474
0
        tmpin = dcont;
475
0
    }
476
    /*
477
     * If not binary mode and detached generate digests by *writing* through
478
     * the BIO. That makes it possible to canonicalise the input.
479
     */
480
0
    if (!(flags & SMIME_BINARY) && dcont) {
481
        /*
482
         * Create output BIO so we can either handle text or to ensure
483
         * included content doesn't override detached content.
484
         */
485
0
        tmpout = cms_get_text_bio(out, flags);
486
0
        if (tmpout == NULL) {
487
0
            ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
488
0
            goto err;
489
0
        }
490
0
        cmsbio = CMS_dataInit(cms, tmpout);
491
0
        if (cmsbio == NULL)
492
0
            goto err;
493
        /*
494
         * Don't use SMIME_TEXT for verify: it adds headers and we want to
495
         * remove them.
496
         */
497
0
        if (!SMIME_crlf_copy(dcont, cmsbio, flags & ~SMIME_TEXT))
498
0
            goto err;
499
500
0
        if (flags & CMS_TEXT) {
501
0
            if (!SMIME_text(tmpout, out)) {
502
0
                ERR_raise(ERR_LIB_CMS, CMS_R_SMIME_TEXT_ERROR);
503
0
                goto err;
504
0
            }
505
0
        }
506
0
    } else {
507
0
        cmsbio = CMS_dataInit(cms, tmpin);
508
0
        if (cmsbio == NULL)
509
0
            goto err;
510
511
0
        if (!cms_copy_content(out, cmsbio, flags))
512
0
            goto err;
513
0
    }
514
0
    if (!(flags & CMS_NO_CONTENT_VERIFY)) {
515
0
        for (i = 0; i < sk_CMS_SignerInfo_num(sinfos); i++) {
516
0
            si = sk_CMS_SignerInfo_value(sinfos, i);
517
0
            if (!si->verify_result)
518
0
                continue;
519
0
            if (CMS_SignerInfo_verify_ex(si, cmsbio, tmpin) <= 0) {
520
0
                ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_VERIFY_ERROR);
521
0
                si->verify_result = 0;
522
0
                continue;
523
0
            }
524
0
            si->content_verified = 1;
525
0
        }
526
0
    }
527
528
    /* Determine overall result */
529
0
    for (i = 0; i < scount; i++) {
530
0
        if (sk_CMS_SignerInfo_value(sinfos, i)->verify_result)
531
0
            n++;
532
0
    }
533
0
    if ((flags & CMS_VERIFY_PARTIAL) != 0)
534
0
        ret = n > 0; /* One success is enough */
535
0
    else
536
0
        ret = n == scount; /* All must be successful */
537
0
err:
538
0
    if (!ret)
539
0
        for (i = 0; i < scount; i++)
540
0
            sk_CMS_SignerInfo_value(sinfos, i)->verify_result = 0;
541
0
    if (!(flags & SMIME_BINARY) && dcont) {
542
0
        do_free_upto(cmsbio, tmpout);
543
0
        if (tmpin != dcont)
544
0
            BIO_free(tmpin);
545
0
    } else {
546
0
        if (dcont && (tmpin == dcont))
547
0
            do_free_upto(cmsbio, dcont);
548
0
        else if (cmsbio != NULL)
549
0
            BIO_free_all(cmsbio);
550
0
        else
551
0
            BIO_free(tmpin);
552
0
    }
553
554
0
    if (out != tmpout)
555
0
        BIO_free_all(tmpout);
556
557
0
err2:
558
0
    if (si_chains != NULL) {
559
0
        for (i = 0; i < scount; ++i)
560
0
            OSSL_STACK_OF_X509_free(si_chains[i]);
561
0
        OPENSSL_free(si_chains);
562
0
    }
563
0
    sk_X509_pop_free(untrusted, X509_free);
564
0
    sk_X509_CRL_pop_free(crls, X509_CRL_free);
565
566
0
    return ret;
567
0
}
568
569
int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms,
570
    const STACK_OF(X509) *certs,
571
    X509_STORE *store, unsigned int flags)
572
0
{
573
0
    int r;
574
575
0
    flags &= ~(CMS_DETACHED | CMS_TEXT);
576
0
    r = CMS_verify(rcms, certs, store, NULL, NULL, flags);
577
0
    if (r <= 0)
578
0
        return r;
579
0
    return ossl_cms_Receipt_verify(rcms, ocms);
580
0
}
581
582
CMS_ContentInfo *CMS_sign_ex(X509 *signcert, EVP_PKEY *pkey,
583
    const STACK_OF(X509) *certs, BIO *data,
584
    unsigned int flags, OSSL_LIB_CTX *libctx,
585
    const char *propq)
586
0
{
587
0
    CMS_ContentInfo *cms;
588
0
    int i;
589
590
0
    cms = CMS_ContentInfo_new_ex(libctx, propq);
591
0
    if (cms == NULL || !CMS_SignedData_init(cms)) {
592
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
593
0
        goto err;
594
0
    }
595
0
    if (flags & CMS_ASCIICRLF
596
0
        && !CMS_set1_eContentType(cms,
597
0
            OBJ_nid2obj(NID_id_ct_asciiTextWithCRLF))) {
598
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
599
0
        goto err;
600
0
    }
601
602
0
    if (pkey != NULL && !CMS_add1_signer(cms, signcert, pkey, NULL, flags)) {
603
0
        ERR_raise(ERR_LIB_CMS, CMS_R_ADD_SIGNER_ERROR);
604
0
        goto err;
605
0
    }
606
607
0
    for (i = 0; i < sk_X509_num(certs); i++) {
608
0
        X509 *x = sk_X509_value(certs, i);
609
610
0
        if (!CMS_add1_cert(cms, x)) {
611
0
            ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
612
0
            goto err;
613
0
        }
614
0
    }
615
616
0
    if (!(flags & CMS_DETACHED))
617
0
        CMS_set_detached(cms, 0);
618
619
0
    if ((flags & (CMS_STREAM | CMS_PARTIAL))
620
0
        || CMS_final(cms, data, NULL, flags))
621
0
        return cms;
622
0
    else
623
0
        goto err;
624
625
0
err:
626
0
    CMS_ContentInfo_free(cms);
627
0
    return NULL;
628
0
}
629
630
CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey,
631
    const STACK_OF(X509) *certs, BIO *data, unsigned int flags)
632
0
{
633
0
    return CMS_sign_ex(signcert, pkey, certs, data, flags, NULL, NULL);
634
0
}
635
636
CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si,
637
    X509 *signcert, EVP_PKEY *pkey,
638
    const STACK_OF(X509) *certs, unsigned int flags)
639
0
{
640
0
    CMS_SignerInfo *rct_si;
641
0
    CMS_ContentInfo *cms = NULL;
642
0
    ASN1_OCTET_STRING **pos, *os = NULL;
643
0
    BIO *rct_cont = NULL;
644
0
    int r = 0;
645
0
    const CMS_CTX *ctx = si->cms_ctx;
646
647
0
    flags &= ~(CMS_STREAM | CMS_TEXT);
648
    /* Not really detached but avoids content being allocated */
649
0
    flags |= CMS_PARTIAL | CMS_BINARY | CMS_DETACHED;
650
0
    if (pkey == NULL || signcert == NULL) {
651
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY_OR_CERT);
652
0
        return NULL;
653
0
    }
654
655
    /* Initialize signed data */
656
657
0
    cms = CMS_sign_ex(NULL, NULL, certs, NULL, flags,
658
0
        ossl_cms_ctx_get0_libctx(ctx),
659
0
        ossl_cms_ctx_get0_propq(ctx));
660
0
    if (cms == NULL)
661
0
        goto err;
662
663
    /* Set inner content type to signed receipt */
664
0
    if (!CMS_set1_eContentType(cms, OBJ_nid2obj(NID_id_smime_ct_receipt)))
665
0
        goto err;
666
667
0
    rct_si = CMS_add1_signer(cms, signcert, pkey, NULL, flags);
668
0
    if (!rct_si) {
669
0
        ERR_raise(ERR_LIB_CMS, CMS_R_ADD_SIGNER_ERROR);
670
0
        goto err;
671
0
    }
672
673
0
    os = ossl_cms_encode_Receipt(si);
674
0
    if (os == NULL)
675
0
        goto err;
676
677
    /* Set content to digest */
678
0
    rct_cont = BIO_new_mem_buf(os->data, os->length);
679
0
    if (rct_cont == NULL)
680
0
        goto err;
681
682
    /* Add msgSigDigest attribute */
683
684
0
    if (!ossl_cms_msgSigDigest_add1(rct_si, si))
685
0
        goto err;
686
687
    /* Finalize structure */
688
0
    if (!CMS_final(cms, rct_cont, NULL, flags))
689
0
        goto err;
690
691
    /* Set embedded content */
692
0
    pos = CMS_get0_content(cms);
693
0
    if (pos == NULL)
694
0
        goto err;
695
0
    *pos = os;
696
697
0
    r = 1;
698
699
0
err:
700
0
    BIO_free(rct_cont);
701
0
    if (r)
702
0
        return cms;
703
0
    CMS_ContentInfo_free(cms);
704
0
    ASN1_OCTET_STRING_free(os);
705
0
    return NULL;
706
0
}
707
708
CMS_ContentInfo *CMS_encrypt_ex(const STACK_OF(X509) *certs, BIO *data,
709
    const EVP_CIPHER *cipher, unsigned int flags,
710
    OSSL_LIB_CTX *libctx, const char *propq)
711
0
{
712
0
    CMS_ContentInfo *cms;
713
0
    int i;
714
0
    X509 *recip;
715
716
0
    cms = (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)
717
0
        ? CMS_AuthEnvelopedData_create_ex(cipher, libctx, propq)
718
0
        : CMS_EnvelopedData_create_ex(cipher, libctx, propq);
719
0
    if (cms == NULL) {
720
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
721
0
        goto err;
722
0
    }
723
0
    for (i = 0; i < sk_X509_num(certs); i++) {
724
0
        recip = sk_X509_value(certs, i);
725
0
        if (!CMS_add1_recipient_cert(cms, recip, flags)) {
726
0
            ERR_raise(ERR_LIB_CMS, CMS_R_RECIPIENT_ERROR);
727
0
            goto err;
728
0
        }
729
0
    }
730
731
0
    if (!(flags & CMS_DETACHED))
732
0
        CMS_set_detached(cms, 0);
733
734
0
    if ((flags & (CMS_STREAM | CMS_PARTIAL))
735
0
        || CMS_final(cms, data, NULL, flags))
736
0
        return cms;
737
0
    else
738
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
739
740
0
err:
741
0
    CMS_ContentInfo_free(cms);
742
0
    return NULL;
743
0
}
744
745
CMS_ContentInfo *CMS_encrypt(const STACK_OF(X509) *certs, BIO *data,
746
    const EVP_CIPHER *cipher, unsigned int flags)
747
0
{
748
0
    return CMS_encrypt_ex(certs, data, cipher, flags, NULL, NULL);
749
0
}
750
751
static int cms_kari_set1_pkey_and_peer(CMS_ContentInfo *cms,
752
    CMS_RecipientInfo *ri,
753
    EVP_PKEY *pk, X509 *cert, X509 *peer)
754
0
{
755
0
    int i;
756
0
    STACK_OF(CMS_RecipientEncryptedKey) *reks;
757
0
    CMS_RecipientEncryptedKey *rek;
758
759
0
    reks = CMS_RecipientInfo_kari_get0_reks(ri);
760
0
    for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++) {
761
0
        int rv;
762
763
0
        rek = sk_CMS_RecipientEncryptedKey_value(reks, i);
764
0
        if (cert != NULL && CMS_RecipientEncryptedKey_cert_cmp(rek, cert))
765
0
            continue;
766
0
        CMS_RecipientInfo_kari_set0_pkey_and_peer(ri, pk, peer);
767
0
        rv = CMS_RecipientInfo_kari_decrypt(cms, ri, rek);
768
0
        CMS_RecipientInfo_kari_set0_pkey(ri, NULL);
769
0
        if (rv > 0)
770
0
            return 1;
771
0
        return cert == NULL ? 0 : -1;
772
0
    }
773
0
    return 0;
774
0
}
775
776
int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert)
777
0
{
778
0
    return CMS_decrypt_set1_pkey_and_peer(cms, pk, cert, NULL);
779
0
}
780
781
int CMS_decrypt_set1_pkey_and_peer(CMS_ContentInfo *cms, EVP_PKEY *pk,
782
    X509 *cert, X509 *peer)
783
0
{
784
0
    STACK_OF(CMS_RecipientInfo) *ris = CMS_get0_RecipientInfos(cms);
785
0
    CMS_RecipientInfo *ri;
786
0
    int i, r, cms_pkey_ri_type;
787
0
    int debug = 0, match_ri = 0;
788
0
    CMS_EncryptedContentInfo *ec = ossl_cms_get0_env_enc_content(cms);
789
790
    /* Prevent mem leak on earlier CMS_decrypt_set1_{pkey_and_peer,password} */
791
0
    if (ec != NULL) {
792
0
        OPENSSL_clear_free(ec->key, ec->keylen);
793
0
        ec->key = NULL;
794
0
        ec->keylen = 0;
795
0
    }
796
797
0
    if (ris != NULL && ec != NULL)
798
0
        debug = ec->debug;
799
800
0
    cms_pkey_ri_type = ossl_cms_pkey_get_ri_type(pk);
801
0
    if (cms_pkey_ri_type == CMS_RECIPINFO_NONE) {
802
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
803
0
        return 0;
804
0
    }
805
806
0
    for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) {
807
0
        int ri_type;
808
809
0
        ri = sk_CMS_RecipientInfo_value(ris, i);
810
0
        ri_type = CMS_RecipientInfo_type(ri);
811
0
        if (!ossl_cms_pkey_is_ri_type_supported(pk, ri_type))
812
0
            continue;
813
0
        match_ri = 1;
814
0
        if (ri_type == CMS_RECIPINFO_AGREE) {
815
0
            r = cms_kari_set1_pkey_and_peer(cms, ri, pk, cert, peer);
816
0
            if (r > 0)
817
0
                return 1;
818
0
            if (r < 0)
819
0
                return 0;
820
0
        } else if (ri_type == CMS_RECIPINFO_KEM) {
821
0
            if (cert == NULL || !CMS_RecipientInfo_kemri_cert_cmp(ri, cert)) {
822
0
                CMS_RecipientInfo_kemri_set0_pkey(ri, pk);
823
0
                r = CMS_RecipientInfo_decrypt(cms, ri);
824
0
                CMS_RecipientInfo_kemri_set0_pkey(ri, NULL);
825
0
                if (cert != NULL || r > 0)
826
0
                    return r;
827
0
            }
828
0
        }
829
        /* If we have a cert, try matching RecipientInfo, else try them all */
830
0
        else if (cert == NULL || !CMS_RecipientInfo_ktri_cert_cmp(ri, cert)) {
831
0
            if (!EVP_PKEY_up_ref(pk))
832
0
                return 0;
833
0
            CMS_RecipientInfo_set0_pkey(ri, pk);
834
0
            r = CMS_RecipientInfo_decrypt(cms, ri);
835
0
            CMS_RecipientInfo_set0_pkey(ri, NULL);
836
0
            if (cert != NULL) {
837
                /*
838
                 * If not debugging clear any error and return success to
839
                 * avoid leaking of information useful to MMA
840
                 */
841
0
                if (!debug) {
842
0
                    ERR_clear_error();
843
0
                    return 1;
844
0
                }
845
0
                if (r > 0)
846
0
                    return 1;
847
0
                ERR_raise(ERR_LIB_CMS, CMS_R_DECRYPT_ERROR);
848
0
                return 0;
849
0
            }
850
            /*
851
             * If no cert and not debugging don't leave loop after first
852
             * successful decrypt. Always attempt to decrypt all recipients
853
             * to avoid leaking timing of a successful decrypt.
854
             */
855
0
            else if (r > 0 && (debug || cms_pkey_ri_type != CMS_RECIPINFO_TRANS))
856
0
                return 1;
857
0
        }
858
0
    }
859
    /* If no cert, key transport and not debugging always return success */
860
0
    if (cert == NULL
861
0
        && cms_pkey_ri_type == CMS_RECIPINFO_TRANS
862
0
        && match_ri
863
0
        && !debug) {
864
0
        ERR_clear_error();
865
0
        return 1;
866
0
    }
867
868
0
    if (!match_ri)
869
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_RECIPIENT);
870
0
    return 0;
871
0
}
872
873
int CMS_decrypt_set1_key(CMS_ContentInfo *cms,
874
    unsigned char *key, size_t keylen,
875
    const unsigned char *id, size_t idlen)
876
0
{
877
0
    STACK_OF(CMS_RecipientInfo) *ris;
878
0
    CMS_RecipientInfo *ri;
879
0
    int i, r, match_ri = 0;
880
881
0
    ris = CMS_get0_RecipientInfos(cms);
882
0
    for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) {
883
0
        ri = sk_CMS_RecipientInfo_value(ris, i);
884
0
        if (CMS_RecipientInfo_type(ri) != CMS_RECIPINFO_KEK)
885
0
            continue;
886
887
        /* If we have an id, try matching RecipientInfo, else try them all */
888
0
        if (id == NULL
889
0
            || (CMS_RecipientInfo_kekri_id_cmp(ri, id, idlen) == 0)) {
890
0
            match_ri = 1;
891
0
            CMS_RecipientInfo_set0_key(ri, key, keylen);
892
0
            r = CMS_RecipientInfo_decrypt(cms, ri);
893
0
            CMS_RecipientInfo_set0_key(ri, NULL, 0);
894
0
            if (r > 0)
895
0
                return 1;
896
0
            if (id != NULL) {
897
0
                ERR_raise(ERR_LIB_CMS, CMS_R_DECRYPT_ERROR);
898
0
                return 0;
899
0
            }
900
0
            ERR_clear_error();
901
0
        }
902
0
    }
903
904
0
    if (!match_ri)
905
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_RECIPIENT);
906
0
    return 0;
907
0
}
908
909
int CMS_decrypt_set1_password(CMS_ContentInfo *cms,
910
    unsigned char *pass, ossl_ssize_t passlen)
911
0
{
912
0
    STACK_OF(CMS_RecipientInfo) *ris = CMS_get0_RecipientInfos(cms);
913
0
    CMS_RecipientInfo *ri;
914
0
    int i, r, match_ri = 0;
915
0
    CMS_EncryptedContentInfo *ec = ossl_cms_get0_env_enc_content(cms);
916
917
    /* Prevent mem leak on earlier CMS_decrypt_set1_{pkey_and_peer,password} */
918
0
    if (ec != NULL) {
919
0
        OPENSSL_clear_free(ec->key, ec->keylen);
920
0
        ec->key = NULL;
921
0
        ec->keylen = 0;
922
0
    }
923
924
0
    for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) {
925
0
        ri = sk_CMS_RecipientInfo_value(ris, i);
926
0
        if (CMS_RecipientInfo_type(ri) != CMS_RECIPINFO_PASS)
927
0
            continue;
928
929
        /* Must try each PasswordRecipientInfo */
930
0
        match_ri = 1;
931
0
        CMS_RecipientInfo_set0_password(ri, pass, passlen);
932
0
        r = CMS_RecipientInfo_decrypt(cms, ri);
933
0
        CMS_RecipientInfo_set0_password(ri, NULL, 0);
934
0
        if (r > 0)
935
0
            return 1;
936
0
    }
937
938
0
    if (!match_ri)
939
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_RECIPIENT);
940
0
    return 0;
941
0
}
942
943
int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert,
944
    BIO *dcont, BIO *out, unsigned int flags)
945
0
{
946
0
    int r;
947
0
    BIO *cont;
948
0
    CMS_EncryptedContentInfo *ec;
949
0
    int nid = OBJ_obj2nid(CMS_get0_type(cms));
950
951
0
    if (nid != NID_pkcs7_enveloped
952
0
        && nid != NID_id_smime_ct_authEnvelopedData) {
953
0
        ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_ENVELOPED_DATA);
954
0
        return 0;
955
0
    }
956
0
    if (dcont == NULL && !check_content(cms))
957
0
        return 0;
958
0
    ec = ossl_cms_get0_env_enc_content(cms);
959
0
    ec->debug = (flags & CMS_DEBUG_DECRYPT) != 0;
960
0
    ec->havenocert = cert == NULL;
961
0
    if (pk == NULL && cert == NULL && dcont == NULL && out == NULL)
962
0
        return 1;
963
0
    if (pk != NULL && !CMS_decrypt_set1_pkey(cms, pk, cert))
964
0
        return 0;
965
0
    cont = CMS_dataInit(cms, dcont);
966
0
    if (cont == NULL)
967
0
        return 0;
968
0
    r = cms_copy_content(out, cont, flags);
969
0
    do_free_upto(cont, dcont);
970
0
    return r;
971
0
}
972
973
int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont, unsigned int flags)
974
0
{
975
0
    BIO *cmsbio;
976
0
    int ret = 0;
977
978
0
    if ((cmsbio = CMS_dataInit(cms, dcont)) == NULL) {
979
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CMS_LIB);
980
0
        return 0;
981
0
    }
982
983
0
    if (!SMIME_crlf_copy(data, cmsbio, flags)) {
984
0
        goto err;
985
0
    }
986
987
0
    (void)BIO_flush(cmsbio);
988
989
0
    if (!CMS_dataFinal_ex(cms, cmsbio, data)) {
990
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CMS_DATAFINAL_ERROR);
991
0
        goto err;
992
0
    }
993
994
0
    ret = 1;
995
996
0
err:
997
0
    do_free_upto(cmsbio, dcont);
998
999
0
    return ret;
1000
0
}
1001
1002
int CMS_final_digest(CMS_ContentInfo *cms,
1003
    const unsigned char *md, unsigned int mdlen,
1004
    BIO *dcont, unsigned int flags)
1005
0
{
1006
0
    BIO *cmsbio;
1007
0
    int ret = 0;
1008
1009
0
    if ((cmsbio = CMS_dataInit(cms, dcont)) == NULL) {
1010
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CMS_LIB);
1011
0
        return 0;
1012
0
    }
1013
1014
0
    (void)BIO_flush(cmsbio);
1015
1016
0
    if (!ossl_cms_DataFinal(cms, cmsbio, NULL, md, mdlen)) {
1017
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CMS_DATAFINAL_ERROR);
1018
0
        goto err;
1019
0
    }
1020
0
    ret = 1;
1021
1022
0
err:
1023
0
    do_free_upto(cmsbio, dcont);
1024
0
    return ret;
1025
0
}
1026
1027
#ifndef OPENSSL_NO_ZLIB
1028
1029
int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
1030
    unsigned int flags)
1031
{
1032
    BIO *cont;
1033
    int r;
1034
1035
    if (OBJ_obj2nid(CMS_get0_type(cms)) != NID_id_smime_ct_compressedData) {
1036
        ERR_raise(ERR_LIB_CMS, CMS_R_TYPE_NOT_COMPRESSED_DATA);
1037
        return 0;
1038
    }
1039
1040
    if (dcont == NULL && !check_content(cms))
1041
        return 0;
1042
1043
    cont = CMS_dataInit(cms, dcont);
1044
    if (cont == NULL)
1045
        return 0;
1046
    r = cms_copy_content(out, cont, flags);
1047
    do_free_upto(cont, dcont);
1048
    return r;
1049
}
1050
1051
CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags)
1052
{
1053
    CMS_ContentInfo *cms;
1054
1055
    if (comp_nid <= 0)
1056
        comp_nid = NID_zlib_compression;
1057
    cms = ossl_cms_CompressedData_create(comp_nid, NULL, NULL);
1058
    if (cms == NULL)
1059
        return NULL;
1060
1061
    if (!(flags & CMS_DETACHED))
1062
        CMS_set_detached(cms, 0);
1063
1064
    if ((flags & CMS_STREAM) || CMS_final(cms, in, NULL, flags))
1065
        return cms;
1066
1067
    CMS_ContentInfo_free(cms);
1068
    return NULL;
1069
}
1070
1071
#else
1072
1073
int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
1074
    unsigned int flags)
1075
0
{
1076
0
    ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1077
0
    return 0;
1078
0
}
1079
1080
CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags)
1081
0
{
1082
0
    ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1083
    return NULL;
1084
0
}
1085
1086
#endif