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