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