xref: /openssl/crypto/cms/cms_env.c (revision 7ed6de99)
1 /*
2  * Copyright 2008-2024 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/pem.h>
13 #include <openssl/x509v3.h>
14 #include <openssl/err.h>
15 #include <openssl/cms.h>
16 #include <openssl/evp.h>
17 #include "internal/sizes.h"
18 #include "crypto/asn1.h"
19 #include "crypto/evp.h"
20 #include "crypto/x509.h"
21 #include "cms_local.h"
22 
23 /* CMS EnvelopedData Utilities */
24 static void cms_env_set_version(CMS_EnvelopedData *env);
25 
26 #define CMS_ENVELOPED_STANDARD 1
27 #define CMS_ENVELOPED_AUTH     2
28 
cms_get_enveloped_type_simple(const CMS_ContentInfo * cms)29 static int cms_get_enveloped_type_simple(const CMS_ContentInfo *cms)
30 {
31     int nid = OBJ_obj2nid(cms->contentType);
32 
33     switch (nid) {
34     case NID_pkcs7_enveloped:
35         return CMS_ENVELOPED_STANDARD;
36 
37     case NID_id_smime_ct_authEnvelopedData:
38         return CMS_ENVELOPED_AUTH;
39 
40     default:
41         return 0;
42     }
43 }
44 
cms_get_enveloped_type(const CMS_ContentInfo * cms)45 static int cms_get_enveloped_type(const CMS_ContentInfo *cms)
46 {
47     int ret = cms_get_enveloped_type_simple(cms);
48 
49     if (ret == 0)
50         ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA);
51     return ret;
52 }
53 
ossl_cms_get0_enveloped(CMS_ContentInfo * cms)54 CMS_EnvelopedData *ossl_cms_get0_enveloped(CMS_ContentInfo *cms)
55 {
56     if (OBJ_obj2nid(cms->contentType) != NID_pkcs7_enveloped) {
57         ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA);
58         return NULL;
59     }
60     return cms->d.envelopedData;
61 }
62 
ossl_cms_get0_auth_enveloped(CMS_ContentInfo * cms)63 CMS_AuthEnvelopedData *ossl_cms_get0_auth_enveloped(CMS_ContentInfo *cms)
64 {
65     if (OBJ_obj2nid(cms->contentType) != NID_id_smime_ct_authEnvelopedData) {
66         ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA);
67         return NULL;
68     }
69     return cms->d.authEnvelopedData;
70 }
71 
cms_enveloped_data_init(CMS_ContentInfo * cms)72 static CMS_EnvelopedData *cms_enveloped_data_init(CMS_ContentInfo *cms)
73 {
74     if (cms->d.other == NULL) {
75         cms->d.envelopedData = M_ASN1_new_of(CMS_EnvelopedData);
76         if (cms->d.envelopedData == NULL) {
77             ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
78             return NULL;
79         }
80         cms->d.envelopedData->version = 0;
81         cms->d.envelopedData->encryptedContentInfo->contentType =
82             OBJ_nid2obj(NID_pkcs7_data);
83         ASN1_OBJECT_free(cms->contentType);
84         cms->contentType = OBJ_nid2obj(NID_pkcs7_enveloped);
85         return cms->d.envelopedData;
86     }
87     return ossl_cms_get0_enveloped(cms);
88 }
89 
90 static CMS_AuthEnvelopedData *
cms_auth_enveloped_data_init(CMS_ContentInfo * cms)91 cms_auth_enveloped_data_init(CMS_ContentInfo *cms)
92 {
93     if (cms->d.other == NULL) {
94         cms->d.authEnvelopedData = M_ASN1_new_of(CMS_AuthEnvelopedData);
95         if (cms->d.authEnvelopedData == NULL) {
96             ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
97             return NULL;
98         }
99         /* Defined in RFC 5083 - Section 2.1. "AuthEnvelopedData Type" */
100         cms->d.authEnvelopedData->version = 0;
101         cms->d.authEnvelopedData->authEncryptedContentInfo->contentType =
102             OBJ_nid2obj(NID_pkcs7_data);
103         ASN1_OBJECT_free(cms->contentType);
104         cms->contentType = OBJ_nid2obj(NID_id_smime_ct_authEnvelopedData);
105         return cms->d.authEnvelopedData;
106     }
107     return ossl_cms_get0_auth_enveloped(cms);
108 }
109 
ossl_cms_env_asn1_ctrl(CMS_RecipientInfo * ri,int cmd)110 int ossl_cms_env_asn1_ctrl(CMS_RecipientInfo *ri, int cmd)
111 {
112     EVP_PKEY *pkey;
113     int i;
114     if (ri->type == CMS_RECIPINFO_TRANS)
115         pkey = ri->d.ktri->pkey;
116     else if (ri->type == CMS_RECIPINFO_AGREE) {
117         EVP_PKEY_CTX *pctx = ri->d.kari->pctx;
118 
119         if (pctx == NULL)
120             return 0;
121         pkey = EVP_PKEY_CTX_get0_pkey(pctx);
122         if (pkey == NULL)
123             return 0;
124     } else
125         return 0;
126 
127     if (EVP_PKEY_is_a(pkey, "DHX") || EVP_PKEY_is_a(pkey, "DH"))
128         return ossl_cms_dh_envelope(ri, cmd);
129     else if (EVP_PKEY_is_a(pkey, "EC"))
130         return ossl_cms_ecdh_envelope(ri, cmd);
131     else if (EVP_PKEY_is_a(pkey, "RSA"))
132         return ossl_cms_rsa_envelope(ri, cmd);
133 
134     /* Something else? We'll give engines etc a chance to handle this */
135     if (pkey->ameth == NULL || pkey->ameth->pkey_ctrl == NULL)
136         return 1;
137     i = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_CMS_ENVELOPE, cmd, ri);
138     if (i == -2) {
139         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
140         return 0;
141     }
142     if (i <= 0) {
143         ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE);
144         return 0;
145     }
146     return 1;
147 }
148 
ossl_cms_get0_env_enc_content(const CMS_ContentInfo * cms)149 CMS_EncryptedContentInfo *ossl_cms_get0_env_enc_content(const CMS_ContentInfo *cms)
150 {
151     switch (cms_get_enveloped_type(cms)) {
152     case CMS_ENVELOPED_STANDARD:
153         return cms->d.envelopedData == NULL ? NULL
154             : cms->d.envelopedData->encryptedContentInfo;
155 
156     case CMS_ENVELOPED_AUTH:
157         return cms->d.authEnvelopedData == NULL ? NULL
158             : cms->d.authEnvelopedData->authEncryptedContentInfo;
159 
160     default:
161         return NULL;
162     }
163 }
164 
STACK_OF(CMS_RecipientInfo)165 STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms)
166 {
167     switch (cms_get_enveloped_type(cms)) {
168     case CMS_ENVELOPED_STANDARD:
169         return cms->d.envelopedData->recipientInfos;
170 
171     case CMS_ENVELOPED_AUTH:
172         return cms->d.authEnvelopedData->recipientInfos;
173 
174     default:
175         return NULL;
176     }
177 }
178 
ossl_cms_RecipientInfos_set_cmsctx(CMS_ContentInfo * cms)179 void ossl_cms_RecipientInfos_set_cmsctx(CMS_ContentInfo *cms)
180 {
181     int i;
182     CMS_RecipientInfo *ri;
183     const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
184     STACK_OF(CMS_RecipientInfo) *rinfos = CMS_get0_RecipientInfos(cms);
185 
186     for (i = 0; i < sk_CMS_RecipientInfo_num(rinfos); i++) {
187         ri = sk_CMS_RecipientInfo_value(rinfos, i);
188         if (ri != NULL) {
189             switch (ri->type) {
190             case CMS_RECIPINFO_AGREE:
191                 ri->d.kari->cms_ctx = ctx;
192                 break;
193             case CMS_RECIPINFO_TRANS:
194                 ri->d.ktri->cms_ctx = ctx;
195                 ossl_x509_set0_libctx(ri->d.ktri->recip,
196                                       ossl_cms_ctx_get0_libctx(ctx),
197                                       ossl_cms_ctx_get0_propq(ctx));
198                 break;
199             case CMS_RECIPINFO_KEK:
200                 ri->d.kekri->cms_ctx = ctx;
201                 break;
202             case CMS_RECIPINFO_PASS:
203                 ri->d.pwri->cms_ctx = ctx;
204                 break;
205             default:
206                 break;
207             }
208         }
209     }
210 }
211 
CMS_RecipientInfo_type(CMS_RecipientInfo * ri)212 int CMS_RecipientInfo_type(CMS_RecipientInfo *ri)
213 {
214     return ri->type;
215 }
216 
CMS_RecipientInfo_get0_pkey_ctx(CMS_RecipientInfo * ri)217 EVP_PKEY_CTX *CMS_RecipientInfo_get0_pkey_ctx(CMS_RecipientInfo *ri)
218 {
219     if (ri->type == CMS_RECIPINFO_TRANS)
220         return ri->d.ktri->pctx;
221     else if (ri->type == CMS_RECIPINFO_AGREE)
222         return ri->d.kari->pctx;
223     return NULL;
224 }
225 
CMS_EnvelopedData_create_ex(const EVP_CIPHER * cipher,OSSL_LIB_CTX * libctx,const char * propq)226 CMS_ContentInfo *CMS_EnvelopedData_create_ex(const EVP_CIPHER *cipher,
227                                              OSSL_LIB_CTX *libctx,
228                                              const char *propq)
229 {
230     CMS_ContentInfo *cms;
231     CMS_EnvelopedData *env;
232 
233     cms = CMS_ContentInfo_new_ex(libctx, propq);
234     if (cms == NULL)
235         goto err;
236     env = cms_enveloped_data_init(cms);
237     if (env == NULL)
238         goto err;
239 
240     if (!ossl_cms_EncryptedContent_init(env->encryptedContentInfo, cipher, NULL,
241                                         0, ossl_cms_get0_cmsctx(cms)))
242         goto err;
243     return cms;
244  err:
245     CMS_ContentInfo_free(cms);
246     ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
247     return NULL;
248 }
249 
CMS_EnvelopedData_create(const EVP_CIPHER * cipher)250 CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher)
251 {
252     return CMS_EnvelopedData_create_ex(cipher, NULL, NULL);
253 }
254 
CMS_EnvelopedData_decrypt(CMS_EnvelopedData * env,BIO * detached_data,EVP_PKEY * pkey,X509 * cert,ASN1_OCTET_STRING * secret,unsigned int flags,OSSL_LIB_CTX * libctx,const char * propq)255 BIO *CMS_EnvelopedData_decrypt(CMS_EnvelopedData *env, BIO *detached_data,
256                                EVP_PKEY *pkey, X509 *cert,
257                                ASN1_OCTET_STRING *secret, unsigned int flags,
258                                OSSL_LIB_CTX *libctx, const char *propq)
259 {
260     CMS_ContentInfo *ci;
261     BIO *bio = NULL;
262     int res = 0;
263 
264     if (env == NULL) {
265         ERR_raise(ERR_LIB_CMS, ERR_R_PASSED_NULL_PARAMETER);
266         return NULL;
267     }
268 
269     if ((ci = CMS_ContentInfo_new_ex(libctx, propq)) == NULL
270             || (bio = BIO_new(BIO_s_mem())) == NULL)
271         goto end;
272     ci->contentType = OBJ_nid2obj(NID_pkcs7_enveloped);
273     ci->d.envelopedData = env;
274     if (secret != NULL
275         && CMS_decrypt_set1_password(ci, (unsigned char *)
276                                      ASN1_STRING_get0_data(secret),
277                                      ASN1_STRING_length(secret)) != 1)
278         goto end;
279     res = CMS_decrypt(ci, secret == NULL ? pkey : NULL,
280                       secret == NULL ? cert : NULL, detached_data, bio, flags);
281 
282  end:
283     if (ci != NULL) {
284         ci->d.envelopedData = NULL; /* do not indirectly free |env| */
285         ci->contentType = NULL;
286     }
287     CMS_ContentInfo_free(ci);
288     if (!res) {
289         BIO_free(bio);
290         bio = NULL;
291     }
292     return bio;
293 }
294 
295 CMS_ContentInfo *
CMS_AuthEnvelopedData_create_ex(const EVP_CIPHER * cipher,OSSL_LIB_CTX * libctx,const char * propq)296 CMS_AuthEnvelopedData_create_ex(const EVP_CIPHER *cipher, OSSL_LIB_CTX *libctx,
297                                 const char *propq)
298 {
299     CMS_ContentInfo *cms;
300     CMS_AuthEnvelopedData *aenv;
301 
302     cms = CMS_ContentInfo_new_ex(libctx, propq);
303     if (cms == NULL)
304         goto merr;
305     aenv = cms_auth_enveloped_data_init(cms);
306     if (aenv == NULL)
307         goto merr;
308     if (!ossl_cms_EncryptedContent_init(aenv->authEncryptedContentInfo,
309                                         cipher, NULL, 0,
310                                         ossl_cms_get0_cmsctx(cms)))
311         goto merr;
312     return cms;
313  merr:
314     CMS_ContentInfo_free(cms);
315     ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
316     return NULL;
317 }
318 
319 
CMS_AuthEnvelopedData_create(const EVP_CIPHER * cipher)320 CMS_ContentInfo *CMS_AuthEnvelopedData_create(const EVP_CIPHER *cipher)
321 {
322     return CMS_AuthEnvelopedData_create_ex(cipher, NULL, NULL);
323 }
324 
325 /* Key Transport Recipient Info (KTRI) routines */
326 
327 /* Initialise a ktri based on passed certificate and key */
328 
cms_RecipientInfo_ktri_init(CMS_RecipientInfo * ri,X509 * recip,EVP_PKEY * pk,unsigned int flags,const CMS_CTX * ctx)329 static int cms_RecipientInfo_ktri_init(CMS_RecipientInfo *ri, X509 *recip,
330                                        EVP_PKEY *pk, unsigned int flags,
331                                        const CMS_CTX *ctx)
332 {
333     CMS_KeyTransRecipientInfo *ktri;
334     int idtype;
335 
336     ri->d.ktri = M_ASN1_new_of(CMS_KeyTransRecipientInfo);
337     if (!ri->d.ktri)
338         return 0;
339     ri->type = CMS_RECIPINFO_TRANS;
340 
341     ktri = ri->d.ktri;
342     ktri->cms_ctx = ctx;
343 
344     if (flags & CMS_USE_KEYID) {
345         ktri->version = 2;
346         idtype = CMS_RECIPINFO_KEYIDENTIFIER;
347     } else {
348         ktri->version = 0;
349         idtype = CMS_RECIPINFO_ISSUER_SERIAL;
350     }
351 
352     /*
353      * Not a typo: RecipientIdentifier and SignerIdentifier are the same
354      * structure.
355      */
356 
357     if (!ossl_cms_set1_SignerIdentifier(ktri->rid, recip, idtype, ctx))
358         return 0;
359 
360     X509_up_ref(recip);
361     EVP_PKEY_up_ref(pk);
362 
363     ktri->pkey = pk;
364     ktri->recip = recip;
365 
366     if (flags & CMS_KEY_PARAM) {
367         ktri->pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
368                                                 ktri->pkey,
369                                                 ossl_cms_ctx_get0_propq(ctx));
370         if (ktri->pctx == NULL)
371             return 0;
372         if (EVP_PKEY_encrypt_init(ktri->pctx) <= 0)
373             return 0;
374     } else if (!ossl_cms_env_asn1_ctrl(ri, 0))
375         return 0;
376     return 1;
377 }
378 
379 /*
380  * Add a recipient certificate using appropriate type of RecipientInfo
381  */
382 
CMS_add1_recipient(CMS_ContentInfo * cms,X509 * recip,EVP_PKEY * originatorPrivKey,X509 * originator,unsigned int flags)383 CMS_RecipientInfo *CMS_add1_recipient(CMS_ContentInfo *cms, X509 *recip,
384                                       EVP_PKEY *originatorPrivKey,
385                                       X509 *originator, unsigned int flags)
386 {
387     CMS_RecipientInfo *ri = NULL;
388     STACK_OF(CMS_RecipientInfo) *ris;
389     EVP_PKEY *pk = NULL;
390     const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
391 
392     ris = CMS_get0_RecipientInfos(cms);
393     if (ris == NULL)
394         goto err;
395 
396     /* Initialize recipient info */
397     ri = M_ASN1_new_of(CMS_RecipientInfo);
398     if (ri == NULL) {
399         ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
400         goto err;
401     }
402 
403     pk = X509_get0_pubkey(recip);
404     if (pk == NULL) {
405         ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_GETTING_PUBLIC_KEY);
406         goto err;
407     }
408 
409     switch (ossl_cms_pkey_get_ri_type(pk)) {
410 
411     case CMS_RECIPINFO_TRANS:
412         if (!cms_RecipientInfo_ktri_init(ri, recip, pk, flags, ctx))
413             goto err;
414         break;
415 
416     case CMS_RECIPINFO_AGREE:
417         if (!ossl_cms_RecipientInfo_kari_init(ri, recip, pk, originator,
418                                               originatorPrivKey, flags, ctx))
419             goto err;
420         break;
421 
422     default:
423         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
424         goto err;
425 
426     }
427 
428     if (!sk_CMS_RecipientInfo_push(ris, ri)) {
429         ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
430         goto err;
431     }
432 
433     return ri;
434 
435  err:
436     M_ASN1_free_of(ri, CMS_RecipientInfo);
437     return NULL;
438 
439 }
440 
CMS_add1_recipient_cert(CMS_ContentInfo * cms,X509 * recip,unsigned int flags)441 CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, X509 *recip,
442                                            unsigned int flags)
443 {
444      return CMS_add1_recipient(cms, recip, NULL, NULL, flags);
445 }
446 
CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo * ri,EVP_PKEY ** pk,X509 ** recip,X509_ALGOR ** palg)447 int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri,
448                                      EVP_PKEY **pk, X509 **recip,
449                                      X509_ALGOR **palg)
450 {
451     CMS_KeyTransRecipientInfo *ktri;
452     if (ri->type != CMS_RECIPINFO_TRANS) {
453         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
454         return 0;
455     }
456 
457     ktri = ri->d.ktri;
458 
459     if (pk)
460         *pk = ktri->pkey;
461     if (recip)
462         *recip = ktri->recip;
463     if (palg)
464         *palg = ktri->keyEncryptionAlgorithm;
465     return 1;
466 }
467 
CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo * ri,ASN1_OCTET_STRING ** keyid,X509_NAME ** issuer,ASN1_INTEGER ** sno)468 int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri,
469                                           ASN1_OCTET_STRING **keyid,
470                                           X509_NAME **issuer,
471                                           ASN1_INTEGER **sno)
472 {
473     CMS_KeyTransRecipientInfo *ktri;
474     if (ri->type != CMS_RECIPINFO_TRANS) {
475         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
476         return 0;
477     }
478     ktri = ri->d.ktri;
479 
480     return ossl_cms_SignerIdentifier_get0_signer_id(ktri->rid, keyid, issuer,
481                                                     sno);
482 }
483 
CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo * ri,X509 * cert)484 int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert)
485 {
486     if (ri->type != CMS_RECIPINFO_TRANS) {
487         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
488         return -2;
489     }
490     return ossl_cms_SignerIdentifier_cert_cmp(ri->d.ktri->rid, cert);
491 }
492 
CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo * ri,EVP_PKEY * pkey)493 int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey)
494 {
495     if (ri->type != CMS_RECIPINFO_TRANS) {
496         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
497         return 0;
498     }
499     EVP_PKEY_free(ri->d.ktri->pkey);
500     ri->d.ktri->pkey = pkey;
501     return 1;
502 }
503 
504 /* Encrypt content key in key transport recipient info */
505 
cms_RecipientInfo_ktri_encrypt(const CMS_ContentInfo * cms,CMS_RecipientInfo * ri)506 static int cms_RecipientInfo_ktri_encrypt(const CMS_ContentInfo *cms,
507                                           CMS_RecipientInfo *ri)
508 {
509     CMS_KeyTransRecipientInfo *ktri;
510     CMS_EncryptedContentInfo *ec;
511     EVP_PKEY_CTX *pctx;
512     unsigned char *ek = NULL;
513     size_t eklen;
514     const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
515 
516     int ret = 0;
517 
518     if (ri->type != CMS_RECIPINFO_TRANS) {
519         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
520         return 0;
521     }
522     ktri = ri->d.ktri;
523     ec = ossl_cms_get0_env_enc_content(cms);
524 
525     pctx = ktri->pctx;
526 
527     if (pctx) {
528         if (!ossl_cms_env_asn1_ctrl(ri, 0))
529             goto err;
530     } else {
531         pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
532                                           ktri->pkey,
533                                           ossl_cms_ctx_get0_propq(ctx));
534         if (pctx == NULL)
535             return 0;
536 
537         if (EVP_PKEY_encrypt_init(pctx) <= 0)
538             goto err;
539     }
540 
541     if (EVP_PKEY_encrypt(pctx, NULL, &eklen, ec->key, ec->keylen) <= 0)
542         goto err;
543 
544     ek = OPENSSL_malloc(eklen);
545     if (ek == NULL)
546         goto err;
547 
548     if (EVP_PKEY_encrypt(pctx, ek, &eklen, ec->key, ec->keylen) <= 0)
549         goto err;
550 
551     ASN1_STRING_set0(ktri->encryptedKey, ek, eklen);
552     ek = NULL;
553 
554     ret = 1;
555 
556  err:
557     EVP_PKEY_CTX_free(pctx);
558     ktri->pctx = NULL;
559     OPENSSL_free(ek);
560     return ret;
561 }
562 
563 /* Decrypt content key from KTRI */
564 
cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo * cms,CMS_RecipientInfo * ri)565 static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
566                                           CMS_RecipientInfo *ri)
567 {
568     CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
569     EVP_PKEY *pkey = ktri->pkey;
570     unsigned char *ek = NULL;
571     size_t eklen;
572     int ret = 0;
573     size_t fixlen = 0;
574     const EVP_CIPHER *cipher = NULL;
575     EVP_CIPHER *fetched_cipher = NULL;
576     CMS_EncryptedContentInfo *ec;
577     const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
578     OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx);
579     const char *propq = ossl_cms_ctx_get0_propq(ctx);
580 
581     ec = ossl_cms_get0_env_enc_content(cms);
582 
583     if (ktri->pkey == NULL) {
584         ERR_raise(ERR_LIB_CMS, CMS_R_NO_PRIVATE_KEY);
585         return 0;
586     }
587 
588     if (cms->d.envelopedData->encryptedContentInfo->havenocert
589             && !cms->d.envelopedData->encryptedContentInfo->debug) {
590         X509_ALGOR *calg = ec->contentEncryptionAlgorithm;
591         char name[OSSL_MAX_NAME_SIZE];
592 
593         OBJ_obj2txt(name, sizeof(name), calg->algorithm, 0);
594 
595         (void)ERR_set_mark();
596         fetched_cipher = EVP_CIPHER_fetch(libctx, name, propq);
597 
598         if (fetched_cipher != NULL)
599             cipher = fetched_cipher;
600         else
601             cipher = EVP_get_cipherbyobj(calg->algorithm);
602         if (cipher == NULL) {
603             (void)ERR_clear_last_mark();
604             ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_CIPHER);
605             return 0;
606         }
607         (void)ERR_pop_to_mark();
608 
609         fixlen = EVP_CIPHER_get_key_length(cipher);
610         EVP_CIPHER_free(fetched_cipher);
611     }
612 
613     ktri->pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq);
614     if (ktri->pctx == NULL)
615         goto err;
616 
617     if (EVP_PKEY_decrypt_init(ktri->pctx) <= 0)
618         goto err;
619 
620     if (!ossl_cms_env_asn1_ctrl(ri, 1))
621         goto err;
622 
623     if (EVP_PKEY_is_a(pkey, "RSA"))
624         /* upper layer CMS code incorrectly assumes that a successful RSA
625          * decryption means that the key matches ciphertext (which never
626          * was the case, implicit rejection or not), so to make it work
627          * disable implicit rejection for RSA keys */
628         EVP_PKEY_CTX_ctrl_str(ktri->pctx, "rsa_pkcs1_implicit_rejection", "0");
629 
630     if (evp_pkey_decrypt_alloc(ktri->pctx, &ek, &eklen, fixlen,
631                                ktri->encryptedKey->data,
632                                ktri->encryptedKey->length) <= 0)
633         goto err;
634 
635     ret = 1;
636 
637     OPENSSL_clear_free(ec->key, ec->keylen);
638     ec->key = ek;
639     ec->keylen = eklen;
640 
641  err:
642     EVP_PKEY_CTX_free(ktri->pctx);
643     ktri->pctx = NULL;
644     if (!ret)
645         OPENSSL_free(ek);
646 
647     return ret;
648 }
649 
650 /* Key Encrypted Key (KEK) RecipientInfo routines */
651 
CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo * ri,const unsigned char * id,size_t idlen)652 int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri,
653                                    const unsigned char *id, size_t idlen)
654 {
655     ASN1_OCTET_STRING tmp_os;
656     CMS_KEKRecipientInfo *kekri;
657     if (ri->type != CMS_RECIPINFO_KEK) {
658         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
659         return -2;
660     }
661     kekri = ri->d.kekri;
662     tmp_os.type = V_ASN1_OCTET_STRING;
663     tmp_os.flags = 0;
664     tmp_os.data = (unsigned char *)id;
665     tmp_os.length = (int)idlen;
666     return ASN1_OCTET_STRING_cmp(&tmp_os, kekri->kekid->keyIdentifier);
667 }
668 
669 /* For now hard code AES key wrap info */
670 
aes_wrap_keylen(int nid)671 static size_t aes_wrap_keylen(int nid)
672 {
673     switch (nid) {
674     case NID_id_aes128_wrap:
675         return 16;
676 
677     case NID_id_aes192_wrap:
678         return 24;
679 
680     case NID_id_aes256_wrap:
681         return 32;
682 
683     default:
684         return 0;
685     }
686 }
687 
CMS_add0_recipient_key(CMS_ContentInfo * cms,int nid,unsigned char * key,size_t keylen,unsigned char * id,size_t idlen,ASN1_GENERALIZEDTIME * date,ASN1_OBJECT * otherTypeId,ASN1_TYPE * otherType)688 CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid,
689                                           unsigned char *key, size_t keylen,
690                                           unsigned char *id, size_t idlen,
691                                           ASN1_GENERALIZEDTIME *date,
692                                           ASN1_OBJECT *otherTypeId,
693                                           ASN1_TYPE *otherType)
694 {
695     CMS_RecipientInfo *ri = NULL;
696     CMS_KEKRecipientInfo *kekri;
697     STACK_OF(CMS_RecipientInfo) *ris = CMS_get0_RecipientInfos(cms);
698 
699     if (ris == NULL)
700         goto err;
701 
702     if (nid == NID_undef) {
703         switch (keylen) {
704         case 16:
705             nid = NID_id_aes128_wrap;
706             break;
707 
708         case 24:
709             nid = NID_id_aes192_wrap;
710             break;
711 
712         case 32:
713             nid = NID_id_aes256_wrap;
714             break;
715 
716         default:
717             ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
718             goto err;
719         }
720 
721     } else {
722 
723         size_t exp_keylen = aes_wrap_keylen(nid);
724 
725         if (!exp_keylen) {
726             ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEK_ALGORITHM);
727             goto err;
728         }
729 
730         if (keylen != exp_keylen) {
731             ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
732             goto err;
733         }
734 
735     }
736 
737     /* Initialize recipient info */
738     ri = M_ASN1_new_of(CMS_RecipientInfo);
739     if (!ri) {
740         ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
741         goto err;
742     }
743 
744     ri->d.kekri = M_ASN1_new_of(CMS_KEKRecipientInfo);
745     if (!ri->d.kekri) {
746         ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
747         goto err;
748     }
749     ri->type = CMS_RECIPINFO_KEK;
750 
751     kekri = ri->d.kekri;
752 
753     if (otherTypeId) {
754         kekri->kekid->other = M_ASN1_new_of(CMS_OtherKeyAttribute);
755         if (kekri->kekid->other == NULL) {
756             ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
757             goto err;
758         }
759     }
760 
761     if (!sk_CMS_RecipientInfo_push(ris, ri)) {
762         ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
763         goto err;
764     }
765 
766     /* After this point no calls can fail */
767 
768     kekri->version = 4;
769 
770     kekri->key = key;
771     kekri->keylen = keylen;
772 
773     ASN1_STRING_set0(kekri->kekid->keyIdentifier, id, idlen);
774 
775     kekri->kekid->date = date;
776 
777     if (kekri->kekid->other) {
778         kekri->kekid->other->keyAttrId = otherTypeId;
779         kekri->kekid->other->keyAttr = otherType;
780     }
781 
782     (void)X509_ALGOR_set0(kekri->keyEncryptionAlgorithm, OBJ_nid2obj(nid),
783                           V_ASN1_UNDEF, NULL); /* cannot fail */
784 
785     return ri;
786 
787  err:
788     M_ASN1_free_of(ri, CMS_RecipientInfo);
789     return NULL;
790 }
791 
CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo * ri,X509_ALGOR ** palg,ASN1_OCTET_STRING ** pid,ASN1_GENERALIZEDTIME ** pdate,ASN1_OBJECT ** potherid,ASN1_TYPE ** pothertype)792 int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri,
793                                     X509_ALGOR **palg,
794                                     ASN1_OCTET_STRING **pid,
795                                     ASN1_GENERALIZEDTIME **pdate,
796                                     ASN1_OBJECT **potherid,
797                                     ASN1_TYPE **pothertype)
798 {
799     CMS_KEKIdentifier *rkid;
800     if (ri->type != CMS_RECIPINFO_KEK) {
801         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
802         return 0;
803     }
804     rkid = ri->d.kekri->kekid;
805     if (palg)
806         *palg = ri->d.kekri->keyEncryptionAlgorithm;
807     if (pid)
808         *pid = rkid->keyIdentifier;
809     if (pdate)
810         *pdate = rkid->date;
811     if (potherid) {
812         if (rkid->other)
813             *potherid = rkid->other->keyAttrId;
814         else
815             *potherid = NULL;
816     }
817     if (pothertype) {
818         if (rkid->other)
819             *pothertype = rkid->other->keyAttr;
820         else
821             *pothertype = NULL;
822     }
823     return 1;
824 }
825 
CMS_RecipientInfo_set0_key(CMS_RecipientInfo * ri,unsigned char * key,size_t keylen)826 int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri,
827                                unsigned char *key, size_t keylen)
828 {
829     CMS_KEKRecipientInfo *kekri;
830     if (ri->type != CMS_RECIPINFO_KEK) {
831         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
832         return 0;
833     }
834 
835     kekri = ri->d.kekri;
836     kekri->key = key;
837     kekri->keylen = keylen;
838     return 1;
839 }
840 
cms_get_key_wrap_cipher(size_t keylen,const CMS_CTX * ctx)841 static EVP_CIPHER *cms_get_key_wrap_cipher(size_t keylen, const CMS_CTX *ctx)
842 {
843     const char *alg = NULL;
844 
845     switch (keylen) {
846     case 16:
847         alg = "AES-128-WRAP";
848         break;
849     case 24:
850         alg = "AES-192-WRAP";
851         break;
852     case 32:
853         alg = "AES-256-WRAP";
854         break;
855     default:
856         return NULL;
857     }
858     return EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(ctx), alg,
859                             ossl_cms_ctx_get0_propq(ctx));
860 }
861 
862 
863 /* Encrypt content key in KEK recipient info */
864 
cms_RecipientInfo_kekri_encrypt(const CMS_ContentInfo * cms,CMS_RecipientInfo * ri)865 static int cms_RecipientInfo_kekri_encrypt(const CMS_ContentInfo *cms,
866                                            CMS_RecipientInfo *ri)
867 {
868     CMS_EncryptedContentInfo *ec;
869     CMS_KEKRecipientInfo *kekri;
870     unsigned char *wkey = NULL;
871     int wkeylen;
872     int r = 0;
873     EVP_CIPHER *cipher = NULL;
874     int outlen = 0;
875     EVP_CIPHER_CTX *ctx = NULL;
876     const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
877 
878     ec = ossl_cms_get0_env_enc_content(cms);
879     if (ec == NULL)
880         return 0;
881 
882     kekri = ri->d.kekri;
883 
884     if (kekri->key == NULL) {
885         ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY);
886         return 0;
887     }
888 
889     cipher = cms_get_key_wrap_cipher(kekri->keylen, cms_ctx);
890     if (cipher == NULL) {
891         ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
892         goto err;
893     }
894 
895     /* 8 byte prefix for AES wrap ciphers */
896     wkey = OPENSSL_malloc(ec->keylen + 8);
897     if (wkey == NULL)
898         goto err;
899 
900     ctx = EVP_CIPHER_CTX_new();
901     if (ctx == NULL) {
902         ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
903         goto err;
904     }
905 
906     EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
907     if (!EVP_EncryptInit_ex(ctx, cipher, NULL, kekri->key, NULL)
908             || !EVP_EncryptUpdate(ctx, wkey, &wkeylen, ec->key, ec->keylen)
909             || !EVP_EncryptFinal_ex(ctx, wkey + wkeylen, &outlen)) {
910         ERR_raise(ERR_LIB_CMS, CMS_R_WRAP_ERROR);
911         goto err;
912     }
913     wkeylen += outlen;
914     if (!ossl_assert((size_t)wkeylen == ec->keylen + 8)) {
915         ERR_raise(ERR_LIB_CMS, CMS_R_WRAP_ERROR);
916         goto err;
917     }
918 
919     ASN1_STRING_set0(kekri->encryptedKey, wkey, wkeylen);
920 
921     r = 1;
922 
923  err:
924     EVP_CIPHER_free(cipher);
925     if (!r)
926         OPENSSL_free(wkey);
927     EVP_CIPHER_CTX_free(ctx);
928 
929     return r;
930 }
931 
932 /* Decrypt content key in KEK recipient info */
933 
cms_RecipientInfo_kekri_decrypt(CMS_ContentInfo * cms,CMS_RecipientInfo * ri)934 static int cms_RecipientInfo_kekri_decrypt(CMS_ContentInfo *cms,
935                                            CMS_RecipientInfo *ri)
936 {
937     CMS_EncryptedContentInfo *ec;
938     CMS_KEKRecipientInfo *kekri;
939     unsigned char *ukey = NULL;
940     int ukeylen;
941     int r = 0, wrap_nid;
942     EVP_CIPHER *cipher = NULL;
943     int outlen = 0;
944     EVP_CIPHER_CTX *ctx = NULL;
945     const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
946 
947     ec = ossl_cms_get0_env_enc_content(cms);
948     if (ec == NULL)
949         return 0;
950 
951     kekri = ri->d.kekri;
952 
953     if (!kekri->key) {
954         ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY);
955         return 0;
956     }
957 
958     wrap_nid = OBJ_obj2nid(kekri->keyEncryptionAlgorithm->algorithm);
959     if (aes_wrap_keylen(wrap_nid) != kekri->keylen) {
960         ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
961         return 0;
962     }
963 
964     /* If encrypted key length is invalid don't bother */
965 
966     if (kekri->encryptedKey->length < 16) {
967         ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_ENCRYPTED_KEY_LENGTH);
968         goto err;
969     }
970 
971     cipher = cms_get_key_wrap_cipher(kekri->keylen, cms_ctx);
972     if (cipher == NULL) {
973         ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
974         goto err;
975     }
976 
977     ukey = OPENSSL_malloc(kekri->encryptedKey->length - 8);
978     if (ukey == NULL)
979         goto err;
980 
981     ctx = EVP_CIPHER_CTX_new();
982     if (ctx == NULL) {
983         ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
984         goto err;
985     }
986 
987     if (!EVP_DecryptInit_ex(ctx, cipher, NULL, kekri->key, NULL)
988             || !EVP_DecryptUpdate(ctx, ukey, &ukeylen,
989                                   kekri->encryptedKey->data,
990                                   kekri->encryptedKey->length)
991             || !EVP_DecryptFinal_ex(ctx, ukey + ukeylen, &outlen)) {
992         ERR_raise(ERR_LIB_CMS, CMS_R_UNWRAP_ERROR);
993         goto err;
994     }
995     ukeylen += outlen;
996 
997     OPENSSL_clear_free(ec->key, ec->keylen);
998     ec->key = ukey;
999     ec->keylen = ukeylen;
1000 
1001     r = 1;
1002 
1003  err:
1004     EVP_CIPHER_free(cipher);
1005     if (!r)
1006         OPENSSL_free(ukey);
1007     EVP_CIPHER_CTX_free(ctx);
1008 
1009     return r;
1010 }
1011 
CMS_RecipientInfo_decrypt(CMS_ContentInfo * cms,CMS_RecipientInfo * ri)1012 int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri)
1013 {
1014     switch (ri->type) {
1015     case CMS_RECIPINFO_TRANS:
1016         return cms_RecipientInfo_ktri_decrypt(cms, ri);
1017 
1018     case CMS_RECIPINFO_KEK:
1019         return cms_RecipientInfo_kekri_decrypt(cms, ri);
1020 
1021     case CMS_RECIPINFO_PASS:
1022         return ossl_cms_RecipientInfo_pwri_crypt(cms, ri, 0);
1023 
1024     default:
1025         ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE);
1026         return 0;
1027     }
1028 }
1029 
CMS_RecipientInfo_encrypt(const CMS_ContentInfo * cms,CMS_RecipientInfo * ri)1030 int CMS_RecipientInfo_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri)
1031 {
1032     switch (ri->type) {
1033     case CMS_RECIPINFO_TRANS:
1034         return cms_RecipientInfo_ktri_encrypt(cms, ri);
1035 
1036     case CMS_RECIPINFO_AGREE:
1037         return ossl_cms_RecipientInfo_kari_encrypt(cms, ri);
1038 
1039     case CMS_RECIPINFO_KEK:
1040         return cms_RecipientInfo_kekri_encrypt(cms, ri);
1041 
1042     case CMS_RECIPINFO_PASS:
1043         return ossl_cms_RecipientInfo_pwri_crypt(cms, ri, 1);
1044 
1045     default:
1046         ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_RECIPIENT_TYPE);
1047         return 0;
1048     }
1049 }
1050 
1051 /* Check structures and fixup version numbers (if necessary) */
1052 
cms_env_set_originfo_version(CMS_EnvelopedData * env)1053 static void cms_env_set_originfo_version(CMS_EnvelopedData *env)
1054 {
1055     CMS_OriginatorInfo *org = env->originatorInfo;
1056     int i;
1057     if (org == NULL)
1058         return;
1059     for (i = 0; i < sk_CMS_CertificateChoices_num(org->certificates); i++) {
1060         CMS_CertificateChoices *cch;
1061         cch = sk_CMS_CertificateChoices_value(org->certificates, i);
1062         if (cch->type == CMS_CERTCHOICE_OTHER) {
1063             env->version = 4;
1064             return;
1065         } else if (cch->type == CMS_CERTCHOICE_V2ACERT) {
1066             if (env->version < 3)
1067                 env->version = 3;
1068         }
1069     }
1070 
1071     for (i = 0; i < sk_CMS_RevocationInfoChoice_num(org->crls); i++) {
1072         CMS_RevocationInfoChoice *rch;
1073         rch = sk_CMS_RevocationInfoChoice_value(org->crls, i);
1074         if (rch->type == CMS_REVCHOICE_OTHER) {
1075             env->version = 4;
1076             return;
1077         }
1078     }
1079 }
1080 
cms_env_set_version(CMS_EnvelopedData * env)1081 static void cms_env_set_version(CMS_EnvelopedData *env)
1082 {
1083     int i;
1084     CMS_RecipientInfo *ri;
1085 
1086     /*
1087      * Can't set version higher than 4 so if 4 or more already nothing to do.
1088      */
1089     if (env->version >= 4)
1090         return;
1091 
1092     cms_env_set_originfo_version(env);
1093 
1094     if (env->version >= 3)
1095         return;
1096 
1097     for (i = 0; i < sk_CMS_RecipientInfo_num(env->recipientInfos); i++) {
1098         ri = sk_CMS_RecipientInfo_value(env->recipientInfos, i);
1099         if (ri->type == CMS_RECIPINFO_PASS || ri->type == CMS_RECIPINFO_OTHER) {
1100             env->version = 3;
1101             return;
1102         } else if (ri->type != CMS_RECIPINFO_TRANS
1103                    || ri->d.ktri->version != 0) {
1104             env->version = 2;
1105         }
1106     }
1107     if (env->originatorInfo || env->unprotectedAttrs)
1108         env->version = 2;
1109     if (env->version == 2)
1110         return;
1111     env->version = 0;
1112 }
1113 
cms_env_encrypt_content_key(const CMS_ContentInfo * cms,STACK_OF (CMS_RecipientInfo)* ris)1114 static int cms_env_encrypt_content_key(const CMS_ContentInfo *cms,
1115                                        STACK_OF(CMS_RecipientInfo) *ris)
1116 {
1117     int i;
1118     CMS_RecipientInfo *ri;
1119 
1120     for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) {
1121         ri = sk_CMS_RecipientInfo_value(ris, i);
1122         if (CMS_RecipientInfo_encrypt(cms, ri) <= 0)
1123             return -1;
1124     }
1125     return 1;
1126 }
1127 
cms_env_clear_ec(CMS_EncryptedContentInfo * ec)1128 static void cms_env_clear_ec(CMS_EncryptedContentInfo *ec)
1129 {
1130     ec->cipher = NULL;
1131     OPENSSL_clear_free(ec->key, ec->keylen);
1132     ec->key = NULL;
1133     ec->keylen = 0;
1134 }
1135 
cms_EnvelopedData_Decryption_init_bio(CMS_ContentInfo * cms)1136 static BIO *cms_EnvelopedData_Decryption_init_bio(CMS_ContentInfo *cms)
1137 {
1138     CMS_EncryptedContentInfo *ec = cms->d.envelopedData->encryptedContentInfo;
1139     BIO *contentBio = ossl_cms_EncryptedContent_init_bio(ec,
1140                                                          ossl_cms_get0_cmsctx(cms));
1141     EVP_CIPHER_CTX *ctx = NULL;
1142 
1143     if (contentBio == NULL)
1144         return NULL;
1145 
1146     BIO_get_cipher_ctx(contentBio, &ctx);
1147     if (ctx == NULL) {
1148         BIO_free(contentBio);
1149         return NULL;
1150     }
1151     /*
1152      * If the selected cipher supports unprotected attributes,
1153      * deal with it using special ctrl function
1154      */
1155     if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))
1156                 & EVP_CIPH_FLAG_CIPHER_WITH_MAC) != 0
1157          && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_PROCESS_UNPROTECTED, 0,
1158                                 cms->d.envelopedData->unprotectedAttrs) <= 0) {
1159         BIO_free(contentBio);
1160         return NULL;
1161     }
1162     return contentBio;
1163 }
1164 
cms_EnvelopedData_Encryption_init_bio(CMS_ContentInfo * cms)1165 static BIO *cms_EnvelopedData_Encryption_init_bio(CMS_ContentInfo *cms)
1166 {
1167     CMS_EncryptedContentInfo *ec;
1168     STACK_OF(CMS_RecipientInfo) *rinfos;
1169     int ok = 0;
1170     BIO *ret;
1171     CMS_EnvelopedData *env = cms->d.envelopedData;
1172 
1173     /* Get BIO first to set up key */
1174 
1175     ec = env->encryptedContentInfo;
1176     ret = ossl_cms_EncryptedContent_init_bio(ec, ossl_cms_get0_cmsctx(cms));
1177 
1178     /* If error end of processing */
1179     if (!ret)
1180         return ret;
1181 
1182     /* Now encrypt content key according to each RecipientInfo type */
1183     rinfos = env->recipientInfos;
1184     if (cms_env_encrypt_content_key(cms, rinfos) < 0) {
1185         ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_SETTING_RECIPIENTINFO);
1186         goto err;
1187     }
1188 
1189     /* And finally set the version */
1190     cms_env_set_version(env);
1191 
1192     ok = 1;
1193 
1194  err:
1195     cms_env_clear_ec(ec);
1196     if (ok)
1197         return ret;
1198     BIO_free(ret);
1199     return NULL;
1200 }
1201 
ossl_cms_EnvelopedData_init_bio(CMS_ContentInfo * cms)1202 BIO *ossl_cms_EnvelopedData_init_bio(CMS_ContentInfo *cms)
1203 {
1204     if (cms->d.envelopedData->encryptedContentInfo->cipher != NULL) {
1205          /* If cipher is set it's encryption */
1206          return cms_EnvelopedData_Encryption_init_bio(cms);
1207     }
1208 
1209     /* If cipher is not set it's decryption */
1210     return cms_EnvelopedData_Decryption_init_bio(cms);
1211 }
1212 
ossl_cms_AuthEnvelopedData_init_bio(CMS_ContentInfo * cms)1213 BIO *ossl_cms_AuthEnvelopedData_init_bio(CMS_ContentInfo *cms)
1214 {
1215     CMS_EncryptedContentInfo *ec;
1216     STACK_OF(CMS_RecipientInfo) *rinfos;
1217     int ok = 0;
1218     BIO *ret;
1219     CMS_AuthEnvelopedData *aenv = cms->d.authEnvelopedData;
1220 
1221     /* Get BIO first to set up key */
1222     ec = aenv->authEncryptedContentInfo;
1223     /* Set tag for decryption */
1224     if (ec->cipher == NULL) {
1225         ec->tag = aenv->mac->data;
1226         ec->taglen = aenv->mac->length;
1227     }
1228     ret = ossl_cms_EncryptedContent_init_bio(ec, ossl_cms_get0_cmsctx(cms));
1229 
1230     /* If error or no cipher end of processing */
1231     if (ret == NULL || ec->cipher == NULL)
1232         return ret;
1233 
1234     /* Now encrypt content key according to each RecipientInfo type */
1235     rinfos = aenv->recipientInfos;
1236     if (cms_env_encrypt_content_key(cms, rinfos) < 0) {
1237         ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_SETTING_RECIPIENTINFO);
1238         goto err;
1239     }
1240 
1241     /* And finally set the version */
1242     aenv->version = 0;
1243 
1244     ok = 1;
1245 
1246  err:
1247     cms_env_clear_ec(ec);
1248     if (ok)
1249         return ret;
1250     BIO_free(ret);
1251     return NULL;
1252 }
1253 
ossl_cms_EnvelopedData_final(CMS_ContentInfo * cms,BIO * chain)1254 int ossl_cms_EnvelopedData_final(CMS_ContentInfo *cms, BIO *chain)
1255 {
1256     CMS_EnvelopedData *env = NULL;
1257     EVP_CIPHER_CTX *ctx = NULL;
1258     BIO *mbio = BIO_find_type(chain, BIO_TYPE_CIPHER);
1259 
1260     env = ossl_cms_get0_enveloped(cms);
1261     if (env == NULL)
1262         return 0;
1263 
1264     if (mbio == NULL) {
1265         ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_NOT_FOUND);
1266         return 0;
1267     }
1268 
1269     BIO_get_cipher_ctx(mbio, &ctx);
1270 
1271     /*
1272      * If the selected cipher supports unprotected attributes,
1273      * deal with it using special ctrl function
1274      */
1275     if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))
1276             & EVP_CIPH_FLAG_CIPHER_WITH_MAC) != 0) {
1277         if (env->unprotectedAttrs == NULL)
1278             env->unprotectedAttrs = sk_X509_ATTRIBUTE_new_null();
1279 
1280         if (env->unprotectedAttrs == NULL) {
1281             ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
1282             return 0;
1283         }
1284 
1285         if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_PROCESS_UNPROTECTED,
1286                                 1, env->unprotectedAttrs) <= 0) {
1287             ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE);
1288             return 0;
1289         }
1290     }
1291 
1292     cms_env_set_version(cms->d.envelopedData);
1293     return 1;
1294 }
1295 
ossl_cms_AuthEnvelopedData_final(CMS_ContentInfo * cms,BIO * cmsbio)1296 int ossl_cms_AuthEnvelopedData_final(CMS_ContentInfo *cms, BIO *cmsbio)
1297 {
1298     EVP_CIPHER_CTX *ctx;
1299     unsigned char *tag = NULL;
1300     int taglen, ok = 0;
1301 
1302     BIO_get_cipher_ctx(cmsbio, &ctx);
1303 
1304     /*
1305      * The tag is set only for encryption. There is nothing to do for
1306      * decryption.
1307      */
1308     if (!EVP_CIPHER_CTX_is_encrypting(ctx))
1309         return 1;
1310 
1311     taglen = EVP_CIPHER_CTX_get_tag_length(ctx);
1312     if (taglen <= 0
1313             || (tag = OPENSSL_malloc(taglen)) == NULL
1314             || EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen,
1315                                    tag) <= 0) {
1316         ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_GET_TAG);
1317         goto err;
1318     }
1319 
1320     if (!ASN1_OCTET_STRING_set(cms->d.authEnvelopedData->mac, tag, taglen))
1321         goto err;
1322 
1323     ok = 1;
1324 err:
1325     OPENSSL_free(tag);
1326     return ok;
1327 }
1328 
1329 /*
1330  * Get RecipientInfo type (if any) supported by a key (public or private). To
1331  * retain compatibility with previous behaviour if the ctrl value isn't
1332  * supported we assume key transport.
1333  */
ossl_cms_pkey_get_ri_type(EVP_PKEY * pk)1334 int ossl_cms_pkey_get_ri_type(EVP_PKEY *pk)
1335 {
1336     /* Check types that we know about */
1337     if (EVP_PKEY_is_a(pk, "DH"))
1338         return CMS_RECIPINFO_AGREE;
1339     else if (EVP_PKEY_is_a(pk, "DHX"))
1340         return CMS_RECIPINFO_AGREE;
1341     else if (EVP_PKEY_is_a(pk, "DSA"))
1342         return CMS_RECIPINFO_NONE;
1343     else if (EVP_PKEY_is_a(pk, "EC"))
1344         return CMS_RECIPINFO_AGREE;
1345     else if (EVP_PKEY_is_a(pk, "RSA"))
1346         return CMS_RECIPINFO_TRANS;
1347 
1348     /*
1349      * Otherwise this might ben an engine implementation, so see if we can get
1350      * the type from the ameth.
1351      */
1352     if (pk->ameth && pk->ameth->pkey_ctrl) {
1353         int i, r;
1354         i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_RI_TYPE, 0, &r);
1355         if (i > 0)
1356             return r;
1357     }
1358     return CMS_RECIPINFO_TRANS;
1359 }
1360 
ossl_cms_pkey_is_ri_type_supported(EVP_PKEY * pk,int ri_type)1361 int ossl_cms_pkey_is_ri_type_supported(EVP_PKEY *pk, int ri_type)
1362 {
1363     int supportedRiType;
1364 
1365     if (pk->ameth != NULL && pk->ameth->pkey_ctrl != NULL) {
1366         int i, r;
1367 
1368         i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_IS_RI_TYPE_SUPPORTED,
1369                                  ri_type, &r);
1370         if (i > 0)
1371             return r;
1372     }
1373 
1374     supportedRiType = ossl_cms_pkey_get_ri_type(pk);
1375     if (supportedRiType < 0)
1376         return 0;
1377 
1378     return (supportedRiType == ri_type);
1379 }
1380