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