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