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