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