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