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