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