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