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