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