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