xref: /freebsd/crypto/openssl/crypto/cms/cms_env.c (revision e7be843b4a162e68651d3911f0357ed464915629)
1 /*
2  * Copyright 2008-2025 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     if (!X509_up_ref(recip))
361         return 0;
362     if (!EVP_PKEY_up_ref(pk)) {
363         X509_free(recip);
364         return 0;
365     }
366 
367     ktri->pkey = pk;
368     ktri->recip = recip;
369 
370     if (flags & CMS_KEY_PARAM) {
371         ktri->pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
372                                                 ktri->pkey,
373                                                 ossl_cms_ctx_get0_propq(ctx));
374         if (ktri->pctx == NULL)
375             return 0;
376         if (EVP_PKEY_encrypt_init(ktri->pctx) <= 0)
377             return 0;
378     } else if (!ossl_cms_env_asn1_ctrl(ri, 0))
379         return 0;
380     return 1;
381 }
382 
383 /*
384  * Add a recipient certificate using appropriate type of RecipientInfo
385  */
386 
CMS_add1_recipient(CMS_ContentInfo * cms,X509 * recip,EVP_PKEY * originatorPrivKey,X509 * originator,unsigned int flags)387 CMS_RecipientInfo *CMS_add1_recipient(CMS_ContentInfo *cms, X509 *recip,
388                                       EVP_PKEY *originatorPrivKey,
389                                       X509 *originator, unsigned int flags)
390 {
391     CMS_RecipientInfo *ri = NULL;
392     STACK_OF(CMS_RecipientInfo) *ris;
393     EVP_PKEY *pk = NULL;
394     const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
395 
396     ris = CMS_get0_RecipientInfos(cms);
397     if (ris == NULL)
398         goto err;
399 
400     /* Initialize recipient info */
401     ri = M_ASN1_new_of(CMS_RecipientInfo);
402     if (ri == NULL) {
403         ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
404         goto err;
405     }
406 
407     pk = X509_get0_pubkey(recip);
408     if (pk == NULL) {
409         ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_GETTING_PUBLIC_KEY);
410         goto err;
411     }
412 
413     switch (ossl_cms_pkey_get_ri_type(pk)) {
414 
415     case CMS_RECIPINFO_TRANS:
416         if (!cms_RecipientInfo_ktri_init(ri, recip, pk, flags, ctx))
417             goto err;
418         break;
419 
420     case CMS_RECIPINFO_AGREE:
421         if (!ossl_cms_RecipientInfo_kari_init(ri, recip, pk, originator,
422                                               originatorPrivKey, flags, ctx))
423             goto err;
424         break;
425 
426     default:
427         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
428         goto err;
429 
430     }
431 
432     if (!sk_CMS_RecipientInfo_push(ris, ri)) {
433         ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
434         goto err;
435     }
436 
437     return ri;
438 
439  err:
440     M_ASN1_free_of(ri, CMS_RecipientInfo);
441     return NULL;
442 
443 }
444 
CMS_add1_recipient_cert(CMS_ContentInfo * cms,X509 * recip,unsigned int flags)445 CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, X509 *recip,
446                                            unsigned int flags)
447 {
448      return CMS_add1_recipient(cms, recip, NULL, NULL, flags);
449 }
450 
CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo * ri,EVP_PKEY ** pk,X509 ** recip,X509_ALGOR ** palg)451 int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri,
452                                      EVP_PKEY **pk, X509 **recip,
453                                      X509_ALGOR **palg)
454 {
455     CMS_KeyTransRecipientInfo *ktri;
456     if (ri->type != CMS_RECIPINFO_TRANS) {
457         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
458         return 0;
459     }
460 
461     ktri = ri->d.ktri;
462 
463     if (pk)
464         *pk = ktri->pkey;
465     if (recip)
466         *recip = ktri->recip;
467     if (palg)
468         *palg = ktri->keyEncryptionAlgorithm;
469     return 1;
470 }
471 
CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo * ri,ASN1_OCTET_STRING ** keyid,X509_NAME ** issuer,ASN1_INTEGER ** sno)472 int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri,
473                                           ASN1_OCTET_STRING **keyid,
474                                           X509_NAME **issuer,
475                                           ASN1_INTEGER **sno)
476 {
477     CMS_KeyTransRecipientInfo *ktri;
478     if (ri->type != CMS_RECIPINFO_TRANS) {
479         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
480         return 0;
481     }
482     ktri = ri->d.ktri;
483 
484     return ossl_cms_SignerIdentifier_get0_signer_id(ktri->rid, keyid, issuer,
485                                                     sno);
486 }
487 
CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo * ri,X509 * cert)488 int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert)
489 {
490     if (ri->type != CMS_RECIPINFO_TRANS) {
491         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
492         return -2;
493     }
494     return ossl_cms_SignerIdentifier_cert_cmp(ri->d.ktri->rid, cert);
495 }
496 
CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo * ri,EVP_PKEY * pkey)497 int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey)
498 {
499     if (ri->type != CMS_RECIPINFO_TRANS) {
500         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
501         return 0;
502     }
503     EVP_PKEY_free(ri->d.ktri->pkey);
504     ri->d.ktri->pkey = pkey;
505     return 1;
506 }
507 
508 /* Encrypt content key in key transport recipient info */
509 
cms_RecipientInfo_ktri_encrypt(const CMS_ContentInfo * cms,CMS_RecipientInfo * ri)510 static int cms_RecipientInfo_ktri_encrypt(const CMS_ContentInfo *cms,
511                                           CMS_RecipientInfo *ri)
512 {
513     CMS_KeyTransRecipientInfo *ktri;
514     CMS_EncryptedContentInfo *ec;
515     EVP_PKEY_CTX *pctx;
516     unsigned char *ek = NULL;
517     size_t eklen;
518     const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
519 
520     int ret = 0;
521 
522     if (ri->type != CMS_RECIPINFO_TRANS) {
523         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
524         return 0;
525     }
526     ktri = ri->d.ktri;
527     ec = ossl_cms_get0_env_enc_content(cms);
528 
529     pctx = ktri->pctx;
530 
531     if (pctx) {
532         if (!ossl_cms_env_asn1_ctrl(ri, 0))
533             goto err;
534     } else {
535         pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
536                                           ktri->pkey,
537                                           ossl_cms_ctx_get0_propq(ctx));
538         if (pctx == NULL)
539             return 0;
540 
541         if (EVP_PKEY_encrypt_init(pctx) <= 0)
542             goto err;
543     }
544 
545     if (EVP_PKEY_encrypt(pctx, NULL, &eklen, ec->key, ec->keylen) <= 0)
546         goto err;
547 
548     ek = OPENSSL_malloc(eklen);
549     if (ek == NULL)
550         goto err;
551 
552     if (EVP_PKEY_encrypt(pctx, ek, &eklen, ec->key, ec->keylen) <= 0)
553         goto err;
554 
555     ASN1_STRING_set0(ktri->encryptedKey, ek, eklen);
556     ek = NULL;
557 
558     ret = 1;
559 
560  err:
561     EVP_PKEY_CTX_free(pctx);
562     ktri->pctx = NULL;
563     OPENSSL_free(ek);
564     return ret;
565 }
566 
567 /* Decrypt content key from KTRI */
568 
cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo * cms,CMS_RecipientInfo * ri)569 static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
570                                           CMS_RecipientInfo *ri)
571 {
572     CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
573     EVP_PKEY *pkey = ktri->pkey;
574     unsigned char *ek = NULL;
575     size_t eklen;
576     int ret = 0;
577     size_t fixlen = 0;
578     const EVP_CIPHER *cipher = NULL;
579     EVP_CIPHER *fetched_cipher = NULL;
580     CMS_EncryptedContentInfo *ec;
581     const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
582     OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx);
583     const char *propq = ossl_cms_ctx_get0_propq(ctx);
584 
585     ec = ossl_cms_get0_env_enc_content(cms);
586 
587     if (ktri->pkey == NULL) {
588         ERR_raise(ERR_LIB_CMS, CMS_R_NO_PRIVATE_KEY);
589         return 0;
590     }
591 
592     if (cms->d.envelopedData->encryptedContentInfo->havenocert
593             && !cms->d.envelopedData->encryptedContentInfo->debug) {
594         X509_ALGOR *calg = ec->contentEncryptionAlgorithm;
595         char name[OSSL_MAX_NAME_SIZE];
596 
597         OBJ_obj2txt(name, sizeof(name), calg->algorithm, 0);
598 
599         (void)ERR_set_mark();
600         fetched_cipher = EVP_CIPHER_fetch(libctx, name, propq);
601 
602         if (fetched_cipher != NULL)
603             cipher = fetched_cipher;
604         else
605             cipher = EVP_get_cipherbyobj(calg->algorithm);
606         if (cipher == NULL) {
607             (void)ERR_clear_last_mark();
608             ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_CIPHER);
609             return 0;
610         }
611         (void)ERR_pop_to_mark();
612 
613         fixlen = EVP_CIPHER_get_key_length(cipher);
614         EVP_CIPHER_free(fetched_cipher);
615     }
616 
617     ktri->pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq);
618     if (ktri->pctx == NULL)
619         goto err;
620 
621     if (EVP_PKEY_decrypt_init(ktri->pctx) <= 0)
622         goto err;
623 
624     if (!ossl_cms_env_asn1_ctrl(ri, 1))
625         goto err;
626 
627     if (EVP_PKEY_is_a(pkey, "RSA"))
628         /* upper layer CMS code incorrectly assumes that a successful RSA
629          * decryption means that the key matches ciphertext (which never
630          * was the case, implicit rejection or not), so to make it work
631          * disable implicit rejection for RSA keys */
632         EVP_PKEY_CTX_ctrl_str(ktri->pctx, "rsa_pkcs1_implicit_rejection", "0");
633 
634     if (evp_pkey_decrypt_alloc(ktri->pctx, &ek, &eklen, fixlen,
635                                ktri->encryptedKey->data,
636                                ktri->encryptedKey->length) <= 0)
637         goto err;
638 
639     ret = 1;
640 
641     OPENSSL_clear_free(ec->key, ec->keylen);
642     ec->key = ek;
643     ec->keylen = eklen;
644 
645  err:
646     EVP_PKEY_CTX_free(ktri->pctx);
647     ktri->pctx = NULL;
648     if (!ret)
649         OPENSSL_free(ek);
650 
651     return ret;
652 }
653 
654 /* Key Encrypted Key (KEK) RecipientInfo routines */
655 
CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo * ri,const unsigned char * id,size_t idlen)656 int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri,
657                                    const unsigned char *id, size_t idlen)
658 {
659     ASN1_OCTET_STRING tmp_os;
660     CMS_KEKRecipientInfo *kekri;
661     if (ri->type != CMS_RECIPINFO_KEK) {
662         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
663         return -2;
664     }
665     kekri = ri->d.kekri;
666     tmp_os.type = V_ASN1_OCTET_STRING;
667     tmp_os.flags = 0;
668     tmp_os.data = (unsigned char *)id;
669     tmp_os.length = (int)idlen;
670     return ASN1_OCTET_STRING_cmp(&tmp_os, kekri->kekid->keyIdentifier);
671 }
672 
673 /* For now hard code AES key wrap info */
674 
aes_wrap_keylen(int nid)675 static size_t aes_wrap_keylen(int nid)
676 {
677     switch (nid) {
678     case NID_id_aes128_wrap:
679         return 16;
680 
681     case NID_id_aes192_wrap:
682         return 24;
683 
684     case NID_id_aes256_wrap:
685         return 32;
686 
687     default:
688         return 0;
689     }
690 }
691 
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)692 CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid,
693                                           unsigned char *key, size_t keylen,
694                                           unsigned char *id, size_t idlen,
695                                           ASN1_GENERALIZEDTIME *date,
696                                           ASN1_OBJECT *otherTypeId,
697                                           ASN1_TYPE *otherType)
698 {
699     CMS_RecipientInfo *ri = NULL;
700     CMS_KEKRecipientInfo *kekri;
701     STACK_OF(CMS_RecipientInfo) *ris = CMS_get0_RecipientInfos(cms);
702 
703     if (ris == NULL)
704         goto err;
705 
706     if (nid == NID_undef) {
707         switch (keylen) {
708         case 16:
709             nid = NID_id_aes128_wrap;
710             break;
711 
712         case 24:
713             nid = NID_id_aes192_wrap;
714             break;
715 
716         case 32:
717             nid = NID_id_aes256_wrap;
718             break;
719 
720         default:
721             ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
722             goto err;
723         }
724 
725     } else {
726 
727         size_t exp_keylen = aes_wrap_keylen(nid);
728 
729         if (!exp_keylen) {
730             ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEK_ALGORITHM);
731             goto err;
732         }
733 
734         if (keylen != exp_keylen) {
735             ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
736             goto err;
737         }
738 
739     }
740 
741     /* Initialize recipient info */
742     ri = M_ASN1_new_of(CMS_RecipientInfo);
743     if (!ri) {
744         ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
745         goto err;
746     }
747 
748     ri->d.kekri = M_ASN1_new_of(CMS_KEKRecipientInfo);
749     if (!ri->d.kekri) {
750         ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
751         goto err;
752     }
753     ri->type = CMS_RECIPINFO_KEK;
754 
755     kekri = ri->d.kekri;
756 
757     if (otherTypeId) {
758         kekri->kekid->other = M_ASN1_new_of(CMS_OtherKeyAttribute);
759         if (kekri->kekid->other == NULL) {
760             ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
761             goto err;
762         }
763     }
764 
765     if (!sk_CMS_RecipientInfo_push(ris, ri)) {
766         ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
767         goto err;
768     }
769 
770     /* After this point no calls can fail */
771 
772     kekri->version = 4;
773 
774     kekri->key = key;
775     kekri->keylen = keylen;
776 
777     ASN1_STRING_set0(kekri->kekid->keyIdentifier, id, idlen);
778 
779     kekri->kekid->date = date;
780 
781     if (kekri->kekid->other) {
782         kekri->kekid->other->keyAttrId = otherTypeId;
783         kekri->kekid->other->keyAttr = otherType;
784     }
785 
786     (void)X509_ALGOR_set0(kekri->keyEncryptionAlgorithm, OBJ_nid2obj(nid),
787                           V_ASN1_UNDEF, NULL); /* cannot fail */
788 
789     return ri;
790 
791  err:
792     M_ASN1_free_of(ri, CMS_RecipientInfo);
793     return NULL;
794 }
795 
CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo * ri,X509_ALGOR ** palg,ASN1_OCTET_STRING ** pid,ASN1_GENERALIZEDTIME ** pdate,ASN1_OBJECT ** potherid,ASN1_TYPE ** pothertype)796 int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri,
797                                     X509_ALGOR **palg,
798                                     ASN1_OCTET_STRING **pid,
799                                     ASN1_GENERALIZEDTIME **pdate,
800                                     ASN1_OBJECT **potherid,
801                                     ASN1_TYPE **pothertype)
802 {
803     CMS_KEKIdentifier *rkid;
804     if (ri->type != CMS_RECIPINFO_KEK) {
805         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
806         return 0;
807     }
808     rkid = ri->d.kekri->kekid;
809     if (palg)
810         *palg = ri->d.kekri->keyEncryptionAlgorithm;
811     if (pid)
812         *pid = rkid->keyIdentifier;
813     if (pdate)
814         *pdate = rkid->date;
815     if (potherid) {
816         if (rkid->other)
817             *potherid = rkid->other->keyAttrId;
818         else
819             *potherid = NULL;
820     }
821     if (pothertype) {
822         if (rkid->other)
823             *pothertype = rkid->other->keyAttr;
824         else
825             *pothertype = NULL;
826     }
827     return 1;
828 }
829 
CMS_RecipientInfo_set0_key(CMS_RecipientInfo * ri,unsigned char * key,size_t keylen)830 int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri,
831                                unsigned char *key, size_t keylen)
832 {
833     CMS_KEKRecipientInfo *kekri;
834     if (ri->type != CMS_RECIPINFO_KEK) {
835         ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
836         return 0;
837     }
838 
839     kekri = ri->d.kekri;
840     kekri->key = key;
841     kekri->keylen = keylen;
842     return 1;
843 }
844 
cms_get_key_wrap_cipher(size_t keylen,const CMS_CTX * ctx)845 static EVP_CIPHER *cms_get_key_wrap_cipher(size_t keylen, const CMS_CTX *ctx)
846 {
847     const char *alg = NULL;
848 
849     switch (keylen) {
850     case 16:
851         alg = "AES-128-WRAP";
852         break;
853     case 24:
854         alg = "AES-192-WRAP";
855         break;
856     case 32:
857         alg = "AES-256-WRAP";
858         break;
859     default:
860         return NULL;
861     }
862     return EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(ctx), alg,
863                             ossl_cms_ctx_get0_propq(ctx));
864 }
865 
866 
867 /* Encrypt content key in KEK recipient info */
868 
cms_RecipientInfo_kekri_encrypt(const CMS_ContentInfo * cms,CMS_RecipientInfo * ri)869 static int cms_RecipientInfo_kekri_encrypt(const CMS_ContentInfo *cms,
870                                            CMS_RecipientInfo *ri)
871 {
872     CMS_EncryptedContentInfo *ec;
873     CMS_KEKRecipientInfo *kekri;
874     unsigned char *wkey = NULL;
875     int wkeylen;
876     int r = 0;
877     EVP_CIPHER *cipher = NULL;
878     int outlen = 0;
879     EVP_CIPHER_CTX *ctx = NULL;
880     const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
881 
882     ec = ossl_cms_get0_env_enc_content(cms);
883     if (ec == NULL)
884         return 0;
885 
886     kekri = ri->d.kekri;
887 
888     if (kekri->key == NULL) {
889         ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY);
890         return 0;
891     }
892 
893     cipher = cms_get_key_wrap_cipher(kekri->keylen, cms_ctx);
894     if (cipher == NULL) {
895         ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
896         goto err;
897     }
898 
899     /* 8 byte prefix for AES wrap ciphers */
900     wkey = OPENSSL_malloc(ec->keylen + 8);
901     if (wkey == NULL)
902         goto err;
903 
904     ctx = EVP_CIPHER_CTX_new();
905     if (ctx == NULL) {
906         ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
907         goto err;
908     }
909 
910     EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
911     if (!EVP_EncryptInit_ex(ctx, cipher, NULL, kekri->key, NULL)
912             || !EVP_EncryptUpdate(ctx, wkey, &wkeylen, ec->key, ec->keylen)
913             || !EVP_EncryptFinal_ex(ctx, wkey + wkeylen, &outlen)) {
914         ERR_raise(ERR_LIB_CMS, CMS_R_WRAP_ERROR);
915         goto err;
916     }
917     wkeylen += outlen;
918     if (!ossl_assert((size_t)wkeylen == ec->keylen + 8)) {
919         ERR_raise(ERR_LIB_CMS, CMS_R_WRAP_ERROR);
920         goto err;
921     }
922 
923     ASN1_STRING_set0(kekri->encryptedKey, wkey, wkeylen);
924 
925     r = 1;
926 
927  err:
928     EVP_CIPHER_free(cipher);
929     if (!r)
930         OPENSSL_free(wkey);
931     EVP_CIPHER_CTX_free(ctx);
932 
933     return r;
934 }
935 
936 /* Decrypt content key in KEK recipient info */
937 
cms_RecipientInfo_kekri_decrypt(CMS_ContentInfo * cms,CMS_RecipientInfo * ri)938 static int cms_RecipientInfo_kekri_decrypt(CMS_ContentInfo *cms,
939                                            CMS_RecipientInfo *ri)
940 {
941     CMS_EncryptedContentInfo *ec;
942     CMS_KEKRecipientInfo *kekri;
943     unsigned char *ukey = NULL;
944     int ukeylen;
945     int r = 0, wrap_nid;
946     EVP_CIPHER *cipher = NULL;
947     int outlen = 0;
948     EVP_CIPHER_CTX *ctx = NULL;
949     const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
950 
951     ec = ossl_cms_get0_env_enc_content(cms);
952     if (ec == NULL)
953         return 0;
954 
955     kekri = ri->d.kekri;
956 
957     if (!kekri->key) {
958         ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY);
959         return 0;
960     }
961 
962     wrap_nid = OBJ_obj2nid(kekri->keyEncryptionAlgorithm->algorithm);
963     if (aes_wrap_keylen(wrap_nid) != kekri->keylen) {
964         ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
965         return 0;
966     }
967 
968     /* If encrypted key length is invalid don't bother */
969 
970     if (kekri->encryptedKey->length < 16) {
971         ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_ENCRYPTED_KEY_LENGTH);
972         goto err;
973     }
974 
975     cipher = cms_get_key_wrap_cipher(kekri->keylen, cms_ctx);
976     if (cipher == NULL) {
977         ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
978         goto err;
979     }
980 
981     ukey = OPENSSL_malloc(kekri->encryptedKey->length - 8);
982     if (ukey == NULL)
983         goto err;
984 
985     ctx = EVP_CIPHER_CTX_new();
986     if (ctx == NULL) {
987         ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
988         goto err;
989     }
990 
991     if (!EVP_DecryptInit_ex(ctx, cipher, NULL, kekri->key, NULL)
992             || !EVP_DecryptUpdate(ctx, ukey, &ukeylen,
993                                   kekri->encryptedKey->data,
994                                   kekri->encryptedKey->length)
995             || !EVP_DecryptFinal_ex(ctx, ukey + ukeylen, &outlen)) {
996         ERR_raise(ERR_LIB_CMS, CMS_R_UNWRAP_ERROR);
997         goto err;
998     }
999     ukeylen += outlen;
1000 
1001     OPENSSL_clear_free(ec->key, ec->keylen);
1002     ec->key = ukey;
1003     ec->keylen = ukeylen;
1004 
1005     r = 1;
1006 
1007  err:
1008     EVP_CIPHER_free(cipher);
1009     if (!r)
1010         OPENSSL_free(ukey);
1011     EVP_CIPHER_CTX_free(ctx);
1012 
1013     return r;
1014 }
1015 
CMS_RecipientInfo_decrypt(CMS_ContentInfo * cms,CMS_RecipientInfo * ri)1016 int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri)
1017 {
1018     switch (ri->type) {
1019     case CMS_RECIPINFO_TRANS:
1020         return cms_RecipientInfo_ktri_decrypt(cms, ri);
1021 
1022     case CMS_RECIPINFO_KEK:
1023         return cms_RecipientInfo_kekri_decrypt(cms, ri);
1024 
1025     case CMS_RECIPINFO_PASS:
1026         return ossl_cms_RecipientInfo_pwri_crypt(cms, ri, 0);
1027 
1028     default:
1029         ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE);
1030         return 0;
1031     }
1032 }
1033 
CMS_RecipientInfo_encrypt(const CMS_ContentInfo * cms,CMS_RecipientInfo * ri)1034 int CMS_RecipientInfo_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri)
1035 {
1036     switch (ri->type) {
1037     case CMS_RECIPINFO_TRANS:
1038         return cms_RecipientInfo_ktri_encrypt(cms, ri);
1039 
1040     case CMS_RECIPINFO_AGREE:
1041         return ossl_cms_RecipientInfo_kari_encrypt(cms, ri);
1042 
1043     case CMS_RECIPINFO_KEK:
1044         return cms_RecipientInfo_kekri_encrypt(cms, ri);
1045 
1046     case CMS_RECIPINFO_PASS:
1047         return ossl_cms_RecipientInfo_pwri_crypt(cms, ri, 1);
1048 
1049     default:
1050         ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_RECIPIENT_TYPE);
1051         return 0;
1052     }
1053 }
1054 
1055 /* Check structures and fixup version numbers (if necessary) */
1056 
cms_env_set_originfo_version(CMS_EnvelopedData * env)1057 static void cms_env_set_originfo_version(CMS_EnvelopedData *env)
1058 {
1059     CMS_OriginatorInfo *org = env->originatorInfo;
1060     int i;
1061     if (org == NULL)
1062         return;
1063     for (i = 0; i < sk_CMS_CertificateChoices_num(org->certificates); i++) {
1064         CMS_CertificateChoices *cch;
1065         cch = sk_CMS_CertificateChoices_value(org->certificates, i);
1066         if (cch->type == CMS_CERTCHOICE_OTHER) {
1067             env->version = 4;
1068             return;
1069         } else if (cch->type == CMS_CERTCHOICE_V2ACERT) {
1070             if (env->version < 3)
1071                 env->version = 3;
1072         }
1073     }
1074 
1075     for (i = 0; i < sk_CMS_RevocationInfoChoice_num(org->crls); i++) {
1076         CMS_RevocationInfoChoice *rch;
1077         rch = sk_CMS_RevocationInfoChoice_value(org->crls, i);
1078         if (rch->type == CMS_REVCHOICE_OTHER) {
1079             env->version = 4;
1080             return;
1081         }
1082     }
1083 }
1084 
cms_env_set_version(CMS_EnvelopedData * env)1085 static void cms_env_set_version(CMS_EnvelopedData *env)
1086 {
1087     int i;
1088     CMS_RecipientInfo *ri;
1089 
1090     /*
1091      * Can't set version higher than 4 so if 4 or more already nothing to do.
1092      */
1093     if (env->version >= 4)
1094         return;
1095 
1096     cms_env_set_originfo_version(env);
1097 
1098     if (env->version >= 3)
1099         return;
1100 
1101     for (i = 0; i < sk_CMS_RecipientInfo_num(env->recipientInfos); i++) {
1102         ri = sk_CMS_RecipientInfo_value(env->recipientInfos, i);
1103         if (ri->type == CMS_RECIPINFO_PASS || ri->type == CMS_RECIPINFO_OTHER) {
1104             env->version = 3;
1105             return;
1106         } else if (ri->type != CMS_RECIPINFO_TRANS
1107                    || ri->d.ktri->version != 0) {
1108             env->version = 2;
1109         }
1110     }
1111     if (env->originatorInfo || env->unprotectedAttrs)
1112         env->version = 2;
1113     if (env->version == 2)
1114         return;
1115     env->version = 0;
1116 }
1117 
cms_env_encrypt_content_key(const CMS_ContentInfo * cms,STACK_OF (CMS_RecipientInfo)* ris)1118 static int cms_env_encrypt_content_key(const CMS_ContentInfo *cms,
1119                                        STACK_OF(CMS_RecipientInfo) *ris)
1120 {
1121     int i;
1122     CMS_RecipientInfo *ri;
1123 
1124     for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) {
1125         ri = sk_CMS_RecipientInfo_value(ris, i);
1126         if (CMS_RecipientInfo_encrypt(cms, ri) <= 0)
1127             return -1;
1128     }
1129     return 1;
1130 }
1131 
cms_env_clear_ec(CMS_EncryptedContentInfo * ec)1132 static void cms_env_clear_ec(CMS_EncryptedContentInfo *ec)
1133 {
1134     ec->cipher = NULL;
1135     OPENSSL_clear_free(ec->key, ec->keylen);
1136     ec->key = NULL;
1137     ec->keylen = 0;
1138 }
1139 
cms_EnvelopedData_Decryption_init_bio(CMS_ContentInfo * cms)1140 static BIO *cms_EnvelopedData_Decryption_init_bio(CMS_ContentInfo *cms)
1141 {
1142     CMS_EncryptedContentInfo *ec = cms->d.envelopedData->encryptedContentInfo;
1143     BIO *contentBio = ossl_cms_EncryptedContent_init_bio(ec,
1144                                                          ossl_cms_get0_cmsctx(cms));
1145     EVP_CIPHER_CTX *ctx = NULL;
1146 
1147     if (contentBio == NULL)
1148         return NULL;
1149 
1150     BIO_get_cipher_ctx(contentBio, &ctx);
1151     if (ctx == NULL) {
1152         BIO_free(contentBio);
1153         return NULL;
1154     }
1155     /*
1156      * If the selected cipher supports unprotected attributes,
1157      * deal with it using special ctrl function
1158      */
1159     if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))
1160                 & EVP_CIPH_FLAG_CIPHER_WITH_MAC) != 0
1161          && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_PROCESS_UNPROTECTED, 0,
1162                                 cms->d.envelopedData->unprotectedAttrs) <= 0) {
1163         BIO_free(contentBio);
1164         return NULL;
1165     }
1166     return contentBio;
1167 }
1168 
cms_EnvelopedData_Encryption_init_bio(CMS_ContentInfo * cms)1169 static BIO *cms_EnvelopedData_Encryption_init_bio(CMS_ContentInfo *cms)
1170 {
1171     CMS_EncryptedContentInfo *ec;
1172     STACK_OF(CMS_RecipientInfo) *rinfos;
1173     int ok = 0;
1174     BIO *ret;
1175     CMS_EnvelopedData *env = cms->d.envelopedData;
1176 
1177     /* Get BIO first to set up key */
1178 
1179     ec = env->encryptedContentInfo;
1180     ret = ossl_cms_EncryptedContent_init_bio(ec, ossl_cms_get0_cmsctx(cms));
1181 
1182     /* If error end of processing */
1183     if (!ret)
1184         return ret;
1185 
1186     /* Now encrypt content key according to each RecipientInfo type */
1187     rinfos = env->recipientInfos;
1188     if (cms_env_encrypt_content_key(cms, rinfos) < 0) {
1189         ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_SETTING_RECIPIENTINFO);
1190         goto err;
1191     }
1192 
1193     /* And finally set the version */
1194     cms_env_set_version(env);
1195 
1196     ok = 1;
1197 
1198  err:
1199     cms_env_clear_ec(ec);
1200     if (ok)
1201         return ret;
1202     BIO_free(ret);
1203     return NULL;
1204 }
1205 
ossl_cms_EnvelopedData_init_bio(CMS_ContentInfo * cms)1206 BIO *ossl_cms_EnvelopedData_init_bio(CMS_ContentInfo *cms)
1207 {
1208     if (cms->d.envelopedData->encryptedContentInfo->cipher != NULL) {
1209          /* If cipher is set it's encryption */
1210          return cms_EnvelopedData_Encryption_init_bio(cms);
1211     }
1212 
1213     /* If cipher is not set it's decryption */
1214     return cms_EnvelopedData_Decryption_init_bio(cms);
1215 }
1216 
ossl_cms_AuthEnvelopedData_init_bio(CMS_ContentInfo * cms)1217 BIO *ossl_cms_AuthEnvelopedData_init_bio(CMS_ContentInfo *cms)
1218 {
1219     CMS_EncryptedContentInfo *ec;
1220     STACK_OF(CMS_RecipientInfo) *rinfos;
1221     int ok = 0;
1222     BIO *ret;
1223     CMS_AuthEnvelopedData *aenv = cms->d.authEnvelopedData;
1224 
1225     /* Get BIO first to set up key */
1226     ec = aenv->authEncryptedContentInfo;
1227     /* Set tag for decryption */
1228     if (ec->cipher == NULL) {
1229         ec->tag = aenv->mac->data;
1230         ec->taglen = aenv->mac->length;
1231     }
1232     ret = ossl_cms_EncryptedContent_init_bio(ec, ossl_cms_get0_cmsctx(cms));
1233 
1234     /* If error or no cipher end of processing */
1235     if (ret == NULL || ec->cipher == NULL)
1236         return ret;
1237 
1238     /* Now encrypt content key according to each RecipientInfo type */
1239     rinfos = aenv->recipientInfos;
1240     if (cms_env_encrypt_content_key(cms, rinfos) < 0) {
1241         ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_SETTING_RECIPIENTINFO);
1242         goto err;
1243     }
1244 
1245     /* And finally set the version */
1246     aenv->version = 0;
1247 
1248     ok = 1;
1249 
1250  err:
1251     cms_env_clear_ec(ec);
1252     if (ok)
1253         return ret;
1254     BIO_free(ret);
1255     return NULL;
1256 }
1257 
ossl_cms_EnvelopedData_final(CMS_ContentInfo * cms,BIO * chain)1258 int ossl_cms_EnvelopedData_final(CMS_ContentInfo *cms, BIO *chain)
1259 {
1260     CMS_EnvelopedData *env = NULL;
1261     EVP_CIPHER_CTX *ctx = NULL;
1262     BIO *mbio = BIO_find_type(chain, BIO_TYPE_CIPHER);
1263 
1264     env = ossl_cms_get0_enveloped(cms);
1265     if (env == NULL)
1266         return 0;
1267 
1268     if (mbio == NULL) {
1269         ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_NOT_FOUND);
1270         return 0;
1271     }
1272 
1273     BIO_get_cipher_ctx(mbio, &ctx);
1274 
1275     /*
1276      * If the selected cipher supports unprotected attributes,
1277      * deal with it using special ctrl function
1278      */
1279     if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))
1280             & EVP_CIPH_FLAG_CIPHER_WITH_MAC) != 0) {
1281         if (env->unprotectedAttrs == NULL)
1282             env->unprotectedAttrs = sk_X509_ATTRIBUTE_new_null();
1283 
1284         if (env->unprotectedAttrs == NULL) {
1285             ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
1286             return 0;
1287         }
1288 
1289         if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_PROCESS_UNPROTECTED,
1290                                 1, env->unprotectedAttrs) <= 0) {
1291             ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE);
1292             return 0;
1293         }
1294     }
1295 
1296     cms_env_set_version(cms->d.envelopedData);
1297     return 1;
1298 }
1299 
ossl_cms_AuthEnvelopedData_final(CMS_ContentInfo * cms,BIO * cmsbio)1300 int ossl_cms_AuthEnvelopedData_final(CMS_ContentInfo *cms, BIO *cmsbio)
1301 {
1302     EVP_CIPHER_CTX *ctx;
1303     unsigned char *tag = NULL;
1304     int taglen, ok = 0;
1305 
1306     BIO_get_cipher_ctx(cmsbio, &ctx);
1307 
1308     /*
1309      * The tag is set only for encryption. There is nothing to do for
1310      * decryption.
1311      */
1312     if (!EVP_CIPHER_CTX_is_encrypting(ctx))
1313         return 1;
1314 
1315     taglen = EVP_CIPHER_CTX_get_tag_length(ctx);
1316     if (taglen <= 0
1317             || (tag = OPENSSL_malloc(taglen)) == NULL
1318             || EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen,
1319                                    tag) <= 0) {
1320         ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_GET_TAG);
1321         goto err;
1322     }
1323 
1324     if (!ASN1_OCTET_STRING_set(cms->d.authEnvelopedData->mac, tag, taglen))
1325         goto err;
1326 
1327     ok = 1;
1328 err:
1329     OPENSSL_free(tag);
1330     return ok;
1331 }
1332 
1333 /*
1334  * Get RecipientInfo type (if any) supported by a key (public or private). To
1335  * retain compatibility with previous behaviour if the ctrl value isn't
1336  * supported we assume key transport.
1337  */
ossl_cms_pkey_get_ri_type(EVP_PKEY * pk)1338 int ossl_cms_pkey_get_ri_type(EVP_PKEY *pk)
1339 {
1340     /* Check types that we know about */
1341     if (EVP_PKEY_is_a(pk, "DH"))
1342         return CMS_RECIPINFO_AGREE;
1343     else if (EVP_PKEY_is_a(pk, "DHX"))
1344         return CMS_RECIPINFO_AGREE;
1345     else if (EVP_PKEY_is_a(pk, "DSA"))
1346         return CMS_RECIPINFO_NONE;
1347     else if (EVP_PKEY_is_a(pk, "EC"))
1348         return CMS_RECIPINFO_AGREE;
1349     else if (EVP_PKEY_is_a(pk, "RSA"))
1350         return CMS_RECIPINFO_TRANS;
1351 
1352     /*
1353      * Otherwise this might ben an engine implementation, so see if we can get
1354      * the type from the ameth.
1355      */
1356     if (pk->ameth && pk->ameth->pkey_ctrl) {
1357         int i, r;
1358         i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_RI_TYPE, 0, &r);
1359         if (i > 0)
1360             return r;
1361     }
1362     return CMS_RECIPINFO_TRANS;
1363 }
1364 
ossl_cms_pkey_is_ri_type_supported(EVP_PKEY * pk,int ri_type)1365 int ossl_cms_pkey_is_ri_type_supported(EVP_PKEY *pk, int ri_type)
1366 {
1367     int supportedRiType;
1368 
1369     if (pk->ameth != NULL && pk->ameth->pkey_ctrl != NULL) {
1370         int i, r;
1371 
1372         i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_IS_RI_TYPE_SUPPORTED,
1373                                  ri_type, &r);
1374         if (i > 0)
1375             return r;
1376     }
1377 
1378     supportedRiType = ossl_cms_pkey_get_ri_type(pk);
1379     if (supportedRiType < 0)
1380         return 0;
1381 
1382     return (supportedRiType == ri_type);
1383 }
1384