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