Reorganize private crypto header files
[openssl.git] / crypto / cms / cms_env.c
1 /*
2  * Copyright 2008-2018 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/aes.h>
17 #include "cms_lcl.h"
18 #include "crypto/asn1.h"
19 #include "crypto/evp.h"
20
21 /* CMS EnvelopedData Utilities */
22
23 CMS_EnvelopedData *cms_get0_enveloped(CMS_ContentInfo *cms)
24 {
25     if (OBJ_obj2nid(cms->contentType) != NID_pkcs7_enveloped) {
26         CMSerr(CMS_F_CMS_GET0_ENVELOPED,
27                CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA);
28         return NULL;
29     }
30     return cms->d.envelopedData;
31 }
32
33 static CMS_EnvelopedData *cms_enveloped_data_init(CMS_ContentInfo *cms)
34 {
35     if (cms->d.other == NULL) {
36         cms->d.envelopedData = M_ASN1_new_of(CMS_EnvelopedData);
37         if (!cms->d.envelopedData) {
38             CMSerr(CMS_F_CMS_ENVELOPED_DATA_INIT, ERR_R_MALLOC_FAILURE);
39             return NULL;
40         }
41         cms->d.envelopedData->version = 0;
42         cms->d.envelopedData->encryptedContentInfo->contentType =
43             OBJ_nid2obj(NID_pkcs7_data);
44         ASN1_OBJECT_free(cms->contentType);
45         cms->contentType = OBJ_nid2obj(NID_pkcs7_enveloped);
46         return cms->d.envelopedData;
47     }
48     return cms_get0_enveloped(cms);
49 }
50
51 int cms_env_asn1_ctrl(CMS_RecipientInfo *ri, int cmd)
52 {
53     EVP_PKEY *pkey;
54     int i;
55     if (ri->type == CMS_RECIPINFO_TRANS)
56         pkey = ri->d.ktri->pkey;
57     else if (ri->type == CMS_RECIPINFO_AGREE) {
58         EVP_PKEY_CTX *pctx = ri->d.kari->pctx;
59         if (!pctx)
60             return 0;
61         pkey = EVP_PKEY_CTX_get0_pkey(pctx);
62         if (!pkey)
63             return 0;
64     } else
65         return 0;
66     if (!pkey->ameth || !pkey->ameth->pkey_ctrl)
67         return 1;
68     i = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_CMS_ENVELOPE, cmd, ri);
69     if (i == -2) {
70         CMSerr(CMS_F_CMS_ENV_ASN1_CTRL,
71                CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
72         return 0;
73     }
74     if (i <= 0) {
75         CMSerr(CMS_F_CMS_ENV_ASN1_CTRL, CMS_R_CTRL_FAILURE);
76         return 0;
77     }
78     return 1;
79 }
80
81 STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms)
82 {
83     CMS_EnvelopedData *env;
84     env = cms_get0_enveloped(cms);
85     if (!env)
86         return NULL;
87     return env->recipientInfos;
88 }
89
90 int CMS_RecipientInfo_type(CMS_RecipientInfo *ri)
91 {
92     return ri->type;
93 }
94
95 EVP_PKEY_CTX *CMS_RecipientInfo_get0_pkey_ctx(CMS_RecipientInfo *ri)
96 {
97     if (ri->type == CMS_RECIPINFO_TRANS)
98         return ri->d.ktri->pctx;
99     else if (ri->type == CMS_RECIPINFO_AGREE)
100         return ri->d.kari->pctx;
101     return NULL;
102 }
103
104 CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher)
105 {
106     CMS_ContentInfo *cms;
107     CMS_EnvelopedData *env;
108     cms = CMS_ContentInfo_new();
109     if (cms == NULL)
110         goto merr;
111     env = cms_enveloped_data_init(cms);
112     if (env == NULL)
113         goto merr;
114     if (!cms_EncryptedContent_init(env->encryptedContentInfo,
115                                    cipher, NULL, 0))
116         goto merr;
117     return cms;
118  merr:
119     CMS_ContentInfo_free(cms);
120     CMSerr(CMS_F_CMS_ENVELOPEDDATA_CREATE, ERR_R_MALLOC_FAILURE);
121     return NULL;
122 }
123
124 /* Key Transport Recipient Info (KTRI) routines */
125
126 /* Initialise a ktri based on passed certificate and key */
127
128 static int cms_RecipientInfo_ktri_init(CMS_RecipientInfo *ri, X509 *recip,
129                                        EVP_PKEY *pk, unsigned int flags)
130 {
131     CMS_KeyTransRecipientInfo *ktri;
132     int idtype;
133
134     ri->d.ktri = M_ASN1_new_of(CMS_KeyTransRecipientInfo);
135     if (!ri->d.ktri)
136         return 0;
137     ri->type = CMS_RECIPINFO_TRANS;
138
139     ktri = ri->d.ktri;
140
141     if (flags & CMS_USE_KEYID) {
142         ktri->version = 2;
143         idtype = CMS_RECIPINFO_KEYIDENTIFIER;
144     } else {
145         ktri->version = 0;
146         idtype = CMS_RECIPINFO_ISSUER_SERIAL;
147     }
148
149     /*
150      * Not a typo: RecipientIdentifier and SignerIdentifier are the same
151      * structure.
152      */
153
154     if (!cms_set1_SignerIdentifier(ktri->rid, recip, idtype))
155         return 0;
156
157     X509_up_ref(recip);
158     EVP_PKEY_up_ref(pk);
159
160     ktri->pkey = pk;
161     ktri->recip = recip;
162
163     if (flags & CMS_KEY_PARAM) {
164         ktri->pctx = EVP_PKEY_CTX_new(ktri->pkey, NULL);
165         if (ktri->pctx == NULL)
166             return 0;
167         if (EVP_PKEY_encrypt_init(ktri->pctx) <= 0)
168             return 0;
169     } else if (!cms_env_asn1_ctrl(ri, 0))
170         return 0;
171     return 1;
172 }
173
174 /*
175  * Add a recipient certificate using appropriate type of RecipientInfo
176  */
177
178 CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms,
179                                            X509 *recip, unsigned int flags)
180 {
181     CMS_RecipientInfo *ri = NULL;
182     CMS_EnvelopedData *env;
183     EVP_PKEY *pk = NULL;
184     env = cms_get0_enveloped(cms);
185     if (!env)
186         goto err;
187
188     /* Initialize recipient info */
189     ri = M_ASN1_new_of(CMS_RecipientInfo);
190     if (!ri)
191         goto merr;
192
193     pk = X509_get0_pubkey(recip);
194     if (!pk) {
195         CMSerr(CMS_F_CMS_ADD1_RECIPIENT_CERT, CMS_R_ERROR_GETTING_PUBLIC_KEY);
196         goto err;
197     }
198
199     switch (cms_pkey_get_ri_type(pk)) {
200
201     case CMS_RECIPINFO_TRANS:
202         if (!cms_RecipientInfo_ktri_init(ri, recip, pk, flags))
203             goto err;
204         break;
205
206     case CMS_RECIPINFO_AGREE:
207         if (!cms_RecipientInfo_kari_init(ri, recip, pk, flags))
208             goto err;
209         break;
210
211     default:
212         CMSerr(CMS_F_CMS_ADD1_RECIPIENT_CERT,
213                CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
214         goto err;
215
216     }
217
218     if (!sk_CMS_RecipientInfo_push(env->recipientInfos, ri))
219         goto merr;
220
221     return ri;
222
223  merr:
224     CMSerr(CMS_F_CMS_ADD1_RECIPIENT_CERT, ERR_R_MALLOC_FAILURE);
225  err:
226     M_ASN1_free_of(ri, CMS_RecipientInfo);
227     return NULL;
228
229 }
230
231 int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri,
232                                      EVP_PKEY **pk, X509 **recip,
233                                      X509_ALGOR **palg)
234 {
235     CMS_KeyTransRecipientInfo *ktri;
236     if (ri->type != CMS_RECIPINFO_TRANS) {
237         CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS,
238                CMS_R_NOT_KEY_TRANSPORT);
239         return 0;
240     }
241
242     ktri = ri->d.ktri;
243
244     if (pk)
245         *pk = ktri->pkey;
246     if (recip)
247         *recip = ktri->recip;
248     if (palg)
249         *palg = ktri->keyEncryptionAlgorithm;
250     return 1;
251 }
252
253 int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri,
254                                           ASN1_OCTET_STRING **keyid,
255                                           X509_NAME **issuer,
256                                           ASN1_INTEGER **sno)
257 {
258     CMS_KeyTransRecipientInfo *ktri;
259     if (ri->type != CMS_RECIPINFO_TRANS) {
260         CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID,
261                CMS_R_NOT_KEY_TRANSPORT);
262         return 0;
263     }
264     ktri = ri->d.ktri;
265
266     return cms_SignerIdentifier_get0_signer_id(ktri->rid, keyid, issuer, sno);
267 }
268
269 int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert)
270 {
271     if (ri->type != CMS_RECIPINFO_TRANS) {
272         CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP,
273                CMS_R_NOT_KEY_TRANSPORT);
274         return -2;
275     }
276     return cms_SignerIdentifier_cert_cmp(ri->d.ktri->rid, cert);
277 }
278
279 int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey)
280 {
281     if (ri->type != CMS_RECIPINFO_TRANS) {
282         CMSerr(CMS_F_CMS_RECIPIENTINFO_SET0_PKEY, CMS_R_NOT_KEY_TRANSPORT);
283         return 0;
284     }
285     EVP_PKEY_free(ri->d.ktri->pkey);
286     ri->d.ktri->pkey = pkey;
287     return 1;
288 }
289
290 /* Encrypt content key in key transport recipient info */
291
292 static int cms_RecipientInfo_ktri_encrypt(const CMS_ContentInfo *cms,
293                                           CMS_RecipientInfo *ri)
294 {
295     CMS_KeyTransRecipientInfo *ktri;
296     CMS_EncryptedContentInfo *ec;
297     EVP_PKEY_CTX *pctx;
298     unsigned char *ek = NULL;
299     size_t eklen;
300
301     int ret = 0;
302
303     if (ri->type != CMS_RECIPINFO_TRANS) {
304         CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT, CMS_R_NOT_KEY_TRANSPORT);
305         return 0;
306     }
307     ktri = ri->d.ktri;
308     ec = cms->d.envelopedData->encryptedContentInfo;
309
310     pctx = ktri->pctx;
311
312     if (pctx) {
313         if (!cms_env_asn1_ctrl(ri, 0))
314             goto err;
315     } else {
316         pctx = EVP_PKEY_CTX_new(ktri->pkey, NULL);
317         if (pctx == NULL)
318             return 0;
319
320         if (EVP_PKEY_encrypt_init(pctx) <= 0)
321             goto err;
322     }
323
324     if (EVP_PKEY_CTX_ctrl(pctx, -1, EVP_PKEY_OP_ENCRYPT,
325                           EVP_PKEY_CTRL_CMS_ENCRYPT, 0, ri) <= 0) {
326         CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT, CMS_R_CTRL_ERROR);
327         goto err;
328     }
329
330     if (EVP_PKEY_encrypt(pctx, NULL, &eklen, ec->key, ec->keylen) <= 0)
331         goto err;
332
333     ek = OPENSSL_malloc(eklen);
334
335     if (ek == NULL) {
336         CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT, ERR_R_MALLOC_FAILURE);
337         goto err;
338     }
339
340     if (EVP_PKEY_encrypt(pctx, ek, &eklen, ec->key, ec->keylen) <= 0)
341         goto err;
342
343     ASN1_STRING_set0(ktri->encryptedKey, ek, eklen);
344     ek = NULL;
345
346     ret = 1;
347
348  err:
349     EVP_PKEY_CTX_free(pctx);
350     ktri->pctx = NULL;
351     OPENSSL_free(ek);
352     return ret;
353
354 }
355
356 /* Decrypt content key from KTRI */
357
358 static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
359                                           CMS_RecipientInfo *ri)
360 {
361     CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
362     EVP_PKEY *pkey = ktri->pkey;
363     unsigned char *ek = NULL;
364     size_t eklen;
365     int ret = 0;
366     size_t fixlen = 0;
367     CMS_EncryptedContentInfo *ec;
368     ec = cms->d.envelopedData->encryptedContentInfo;
369
370     if (ktri->pkey == NULL) {
371         CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_NO_PRIVATE_KEY);
372         return 0;
373     }
374
375     if (cms->d.envelopedData->encryptedContentInfo->havenocert
376             && !cms->d.envelopedData->encryptedContentInfo->debug) {
377         X509_ALGOR *calg = ec->contentEncryptionAlgorithm;
378         const EVP_CIPHER *ciph = EVP_get_cipherbyobj(calg->algorithm);
379
380         if (ciph == NULL) {
381             CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_UNKNOWN_CIPHER);
382             return 0;
383         }
384
385         fixlen = EVP_CIPHER_key_length(ciph);
386     }
387
388     ktri->pctx = EVP_PKEY_CTX_new(pkey, NULL);
389     if (ktri->pctx == NULL)
390         return 0;
391
392     if (EVP_PKEY_decrypt_init(ktri->pctx) <= 0)
393         goto err;
394
395     if (!cms_env_asn1_ctrl(ri, 1))
396         goto err;
397
398     if (EVP_PKEY_CTX_ctrl(ktri->pctx, -1, EVP_PKEY_OP_DECRYPT,
399                           EVP_PKEY_CTRL_CMS_DECRYPT, 0, ri) <= 0) {
400         CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_CTRL_ERROR);
401         goto err;
402     }
403
404     if (EVP_PKEY_decrypt(ktri->pctx, NULL, &eklen,
405                          ktri->encryptedKey->data,
406                          ktri->encryptedKey->length) <= 0)
407         goto err;
408
409     ek = OPENSSL_malloc(eklen);
410
411     if (ek == NULL) {
412         CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, ERR_R_MALLOC_FAILURE);
413         goto err;
414     }
415
416     if (EVP_PKEY_decrypt(ktri->pctx, ek, &eklen,
417                          ktri->encryptedKey->data,
418                          ktri->encryptedKey->length) <= 0
419             || eklen == 0
420             || (fixlen != 0 && eklen != fixlen)) {
421         CMSerr(CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT, CMS_R_CMS_LIB);
422         goto err;
423     }
424
425     ret = 1;
426
427     OPENSSL_clear_free(ec->key, ec->keylen);
428     ec->key = ek;
429     ec->keylen = eklen;
430
431  err:
432     EVP_PKEY_CTX_free(ktri->pctx);
433     ktri->pctx = NULL;
434     if (!ret)
435         OPENSSL_free(ek);
436
437     return ret;
438 }
439
440 /* Key Encrypted Key (KEK) RecipientInfo routines */
441
442 int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri,
443                                    const unsigned char *id, size_t idlen)
444 {
445     ASN1_OCTET_STRING tmp_os;
446     CMS_KEKRecipientInfo *kekri;
447     if (ri->type != CMS_RECIPINFO_KEK) {
448         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP, CMS_R_NOT_KEK);
449         return -2;
450     }
451     kekri = ri->d.kekri;
452     tmp_os.type = V_ASN1_OCTET_STRING;
453     tmp_os.flags = 0;
454     tmp_os.data = (unsigned char *)id;
455     tmp_os.length = (int)idlen;
456     return ASN1_OCTET_STRING_cmp(&tmp_os, kekri->kekid->keyIdentifier);
457 }
458
459 /* For now hard code AES key wrap info */
460
461 static size_t aes_wrap_keylen(int nid)
462 {
463     switch (nid) {
464     case NID_id_aes128_wrap:
465         return 16;
466
467     case NID_id_aes192_wrap:
468         return 24;
469
470     case NID_id_aes256_wrap:
471         return 32;
472
473     default:
474         return 0;
475     }
476 }
477
478 CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid,
479                                           unsigned char *key, size_t keylen,
480                                           unsigned char *id, size_t idlen,
481                                           ASN1_GENERALIZEDTIME *date,
482                                           ASN1_OBJECT *otherTypeId,
483                                           ASN1_TYPE *otherType)
484 {
485     CMS_RecipientInfo *ri = NULL;
486     CMS_EnvelopedData *env;
487     CMS_KEKRecipientInfo *kekri;
488     env = cms_get0_enveloped(cms);
489     if (!env)
490         goto err;
491
492     if (nid == NID_undef) {
493         switch (keylen) {
494         case 16:
495             nid = NID_id_aes128_wrap;
496             break;
497
498         case 24:
499             nid = NID_id_aes192_wrap;
500             break;
501
502         case 32:
503             nid = NID_id_aes256_wrap;
504             break;
505
506         default:
507             CMSerr(CMS_F_CMS_ADD0_RECIPIENT_KEY, CMS_R_INVALID_KEY_LENGTH);
508             goto err;
509         }
510
511     } else {
512
513         size_t exp_keylen = aes_wrap_keylen(nid);
514
515         if (!exp_keylen) {
516             CMSerr(CMS_F_CMS_ADD0_RECIPIENT_KEY,
517                    CMS_R_UNSUPPORTED_KEK_ALGORITHM);
518             goto err;
519         }
520
521         if (keylen != exp_keylen) {
522             CMSerr(CMS_F_CMS_ADD0_RECIPIENT_KEY, CMS_R_INVALID_KEY_LENGTH);
523             goto err;
524         }
525
526     }
527
528     /* Initialize recipient info */
529     ri = M_ASN1_new_of(CMS_RecipientInfo);
530     if (!ri)
531         goto merr;
532
533     ri->d.kekri = M_ASN1_new_of(CMS_KEKRecipientInfo);
534     if (!ri->d.kekri)
535         goto merr;
536     ri->type = CMS_RECIPINFO_KEK;
537
538     kekri = ri->d.kekri;
539
540     if (otherTypeId) {
541         kekri->kekid->other = M_ASN1_new_of(CMS_OtherKeyAttribute);
542         if (kekri->kekid->other == NULL)
543             goto merr;
544     }
545
546     if (!sk_CMS_RecipientInfo_push(env->recipientInfos, ri))
547         goto merr;
548
549     /* After this point no calls can fail */
550
551     kekri->version = 4;
552
553     kekri->key = key;
554     kekri->keylen = keylen;
555
556     ASN1_STRING_set0(kekri->kekid->keyIdentifier, id, idlen);
557
558     kekri->kekid->date = date;
559
560     if (kekri->kekid->other) {
561         kekri->kekid->other->keyAttrId = otherTypeId;
562         kekri->kekid->other->keyAttr = otherType;
563     }
564
565     X509_ALGOR_set0(kekri->keyEncryptionAlgorithm,
566                     OBJ_nid2obj(nid), V_ASN1_UNDEF, NULL);
567
568     return ri;
569
570  merr:
571     CMSerr(CMS_F_CMS_ADD0_RECIPIENT_KEY, ERR_R_MALLOC_FAILURE);
572  err:
573     M_ASN1_free_of(ri, CMS_RecipientInfo);
574     return NULL;
575
576 }
577
578 int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri,
579                                     X509_ALGOR **palg,
580                                     ASN1_OCTET_STRING **pid,
581                                     ASN1_GENERALIZEDTIME **pdate,
582                                     ASN1_OBJECT **potherid,
583                                     ASN1_TYPE **pothertype)
584 {
585     CMS_KEKIdentifier *rkid;
586     if (ri->type != CMS_RECIPINFO_KEK) {
587         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID, CMS_R_NOT_KEK);
588         return 0;
589     }
590     rkid = ri->d.kekri->kekid;
591     if (palg)
592         *palg = ri->d.kekri->keyEncryptionAlgorithm;
593     if (pid)
594         *pid = rkid->keyIdentifier;
595     if (pdate)
596         *pdate = rkid->date;
597     if (potherid) {
598         if (rkid->other)
599             *potherid = rkid->other->keyAttrId;
600         else
601             *potherid = NULL;
602     }
603     if (pothertype) {
604         if (rkid->other)
605             *pothertype = rkid->other->keyAttr;
606         else
607             *pothertype = NULL;
608     }
609     return 1;
610 }
611
612 int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri,
613                                unsigned char *key, size_t keylen)
614 {
615     CMS_KEKRecipientInfo *kekri;
616     if (ri->type != CMS_RECIPINFO_KEK) {
617         CMSerr(CMS_F_CMS_RECIPIENTINFO_SET0_KEY, CMS_R_NOT_KEK);
618         return 0;
619     }
620
621     kekri = ri->d.kekri;
622     kekri->key = key;
623     kekri->keylen = keylen;
624     return 1;
625 }
626
627 /* Encrypt content key in KEK recipient info */
628
629 static int cms_RecipientInfo_kekri_encrypt(const CMS_ContentInfo *cms,
630                                            CMS_RecipientInfo *ri)
631 {
632     CMS_EncryptedContentInfo *ec;
633     CMS_KEKRecipientInfo *kekri;
634     AES_KEY actx;
635     unsigned char *wkey = NULL;
636     int wkeylen;
637     int r = 0;
638
639     ec = cms->d.envelopedData->encryptedContentInfo;
640
641     kekri = ri->d.kekri;
642
643     if (!kekri->key) {
644         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT, CMS_R_NO_KEY);
645         return 0;
646     }
647
648     if (AES_set_encrypt_key(kekri->key, kekri->keylen << 3, &actx)) {
649         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT,
650                CMS_R_ERROR_SETTING_KEY);
651         goto err;
652     }
653
654     wkey = OPENSSL_malloc(ec->keylen + 8);
655
656     if (wkey == NULL) {
657         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT, ERR_R_MALLOC_FAILURE);
658         goto err;
659     }
660
661     wkeylen = AES_wrap_key(&actx, NULL, wkey, ec->key, ec->keylen);
662
663     if (wkeylen <= 0) {
664         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT, CMS_R_WRAP_ERROR);
665         goto err;
666     }
667
668     ASN1_STRING_set0(kekri->encryptedKey, wkey, wkeylen);
669
670     r = 1;
671
672  err:
673
674     if (!r)
675         OPENSSL_free(wkey);
676     OPENSSL_cleanse(&actx, sizeof(actx));
677
678     return r;
679
680 }
681
682 /* Decrypt content key in KEK recipient info */
683
684 static int cms_RecipientInfo_kekri_decrypt(CMS_ContentInfo *cms,
685                                            CMS_RecipientInfo *ri)
686 {
687     CMS_EncryptedContentInfo *ec;
688     CMS_KEKRecipientInfo *kekri;
689     AES_KEY actx;
690     unsigned char *ukey = NULL;
691     int ukeylen;
692     int r = 0, wrap_nid;
693
694     ec = cms->d.envelopedData->encryptedContentInfo;
695
696     kekri = ri->d.kekri;
697
698     if (!kekri->key) {
699         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT, CMS_R_NO_KEY);
700         return 0;
701     }
702
703     wrap_nid = OBJ_obj2nid(kekri->keyEncryptionAlgorithm->algorithm);
704     if (aes_wrap_keylen(wrap_nid) != kekri->keylen) {
705         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT,
706                CMS_R_INVALID_KEY_LENGTH);
707         return 0;
708     }
709
710     /* If encrypted key length is invalid don't bother */
711
712     if (kekri->encryptedKey->length < 16) {
713         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT,
714                CMS_R_INVALID_ENCRYPTED_KEY_LENGTH);
715         goto err;
716     }
717
718     if (AES_set_decrypt_key(kekri->key, kekri->keylen << 3, &actx)) {
719         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT,
720                CMS_R_ERROR_SETTING_KEY);
721         goto err;
722     }
723
724     ukey = OPENSSL_malloc(kekri->encryptedKey->length - 8);
725
726     if (ukey == NULL) {
727         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT, ERR_R_MALLOC_FAILURE);
728         goto err;
729     }
730
731     ukeylen = AES_unwrap_key(&actx, NULL, ukey,
732                              kekri->encryptedKey->data,
733                              kekri->encryptedKey->length);
734
735     if (ukeylen <= 0) {
736         CMSerr(CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT, CMS_R_UNWRAP_ERROR);
737         goto err;
738     }
739
740     ec->key = ukey;
741     ec->keylen = ukeylen;
742
743     r = 1;
744
745  err:
746
747     if (!r)
748         OPENSSL_free(ukey);
749     OPENSSL_cleanse(&actx, sizeof(actx));
750
751     return r;
752
753 }
754
755 int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri)
756 {
757     switch (ri->type) {
758     case CMS_RECIPINFO_TRANS:
759         return cms_RecipientInfo_ktri_decrypt(cms, ri);
760
761     case CMS_RECIPINFO_KEK:
762         return cms_RecipientInfo_kekri_decrypt(cms, ri);
763
764     case CMS_RECIPINFO_PASS:
765         return cms_RecipientInfo_pwri_crypt(cms, ri, 0);
766
767     default:
768         CMSerr(CMS_F_CMS_RECIPIENTINFO_DECRYPT,
769                CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE);
770         return 0;
771     }
772 }
773
774 int CMS_RecipientInfo_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri)
775 {
776     switch (ri->type) {
777     case CMS_RECIPINFO_TRANS:
778         return cms_RecipientInfo_ktri_encrypt(cms, ri);
779
780     case CMS_RECIPINFO_AGREE:
781         return cms_RecipientInfo_kari_encrypt(cms, ri);
782
783     case CMS_RECIPINFO_KEK:
784         return cms_RecipientInfo_kekri_encrypt(cms, ri);
785
786     case CMS_RECIPINFO_PASS:
787         return cms_RecipientInfo_pwri_crypt(cms, ri, 1);
788
789     default:
790         CMSerr(CMS_F_CMS_RECIPIENTINFO_ENCRYPT,
791                CMS_R_UNSUPPORTED_RECIPIENT_TYPE);
792         return 0;
793     }
794 }
795
796 /* Check structures and fixup version numbers (if necessary) */
797
798 static void cms_env_set_originfo_version(CMS_EnvelopedData *env)
799 {
800     CMS_OriginatorInfo *org = env->originatorInfo;
801     int i;
802     if (org == NULL)
803         return;
804     for (i = 0; i < sk_CMS_CertificateChoices_num(org->certificates); i++) {
805         CMS_CertificateChoices *cch;
806         cch = sk_CMS_CertificateChoices_value(org->certificates, i);
807         if (cch->type == CMS_CERTCHOICE_OTHER) {
808             env->version = 4;
809             return;
810         } else if (cch->type == CMS_CERTCHOICE_V2ACERT) {
811             if (env->version < 3)
812                 env->version = 3;
813         }
814     }
815
816     for (i = 0; i < sk_CMS_RevocationInfoChoice_num(org->crls); i++) {
817         CMS_RevocationInfoChoice *rch;
818         rch = sk_CMS_RevocationInfoChoice_value(org->crls, i);
819         if (rch->type == CMS_REVCHOICE_OTHER) {
820             env->version = 4;
821             return;
822         }
823     }
824 }
825
826 static void cms_env_set_version(CMS_EnvelopedData *env)
827 {
828     int i;
829     CMS_RecipientInfo *ri;
830
831     /*
832      * Can't set version higher than 4 so if 4 or more already nothing to do.
833      */
834     if (env->version >= 4)
835         return;
836
837     cms_env_set_originfo_version(env);
838
839     if (env->version >= 3)
840         return;
841
842     for (i = 0; i < sk_CMS_RecipientInfo_num(env->recipientInfos); i++) {
843         ri = sk_CMS_RecipientInfo_value(env->recipientInfos, i);
844         if (ri->type == CMS_RECIPINFO_PASS || ri->type == CMS_RECIPINFO_OTHER) {
845             env->version = 3;
846             return;
847         } else if (ri->type != CMS_RECIPINFO_TRANS
848                    || ri->d.ktri->version != 0) {
849             env->version = 2;
850         }
851     }
852     if (env->originatorInfo || env->unprotectedAttrs)
853         env->version = 2;
854     if (env->version == 2)
855         return;
856     env->version = 0;
857 }
858
859 BIO *cms_EnvelopedData_init_bio(const CMS_ContentInfo *cms)
860 {
861     CMS_EncryptedContentInfo *ec;
862     STACK_OF(CMS_RecipientInfo) *rinfos;
863     CMS_RecipientInfo *ri;
864     int i, ok = 0;
865     BIO *ret;
866
867     /* Get BIO first to set up key */
868
869     ec = cms->d.envelopedData->encryptedContentInfo;
870     ret = cms_EncryptedContent_init_bio(ec);
871
872     /* If error or no cipher end of processing */
873
874     if (!ret || !ec->cipher)
875         return ret;
876
877     /* Now encrypt content key according to each RecipientInfo type */
878
879     rinfos = cms->d.envelopedData->recipientInfos;
880
881     for (i = 0; i < sk_CMS_RecipientInfo_num(rinfos); i++) {
882         ri = sk_CMS_RecipientInfo_value(rinfos, i);
883         if (CMS_RecipientInfo_encrypt(cms, ri) <= 0) {
884             CMSerr(CMS_F_CMS_ENVELOPEDDATA_INIT_BIO,
885                    CMS_R_ERROR_SETTING_RECIPIENTINFO);
886             goto err;
887         }
888     }
889     cms_env_set_version(cms->d.envelopedData);
890
891     ok = 1;
892
893  err:
894     ec->cipher = NULL;
895     OPENSSL_clear_free(ec->key, ec->keylen);
896     ec->key = NULL;
897     ec->keylen = 0;
898     if (ok)
899         return ret;
900     BIO_free(ret);
901     return NULL;
902
903 }
904
905 /*
906  * Get RecipientInfo type (if any) supported by a key (public or private). To
907  * retain compatibility with previous behaviour if the ctrl value isn't
908  * supported we assume key transport.
909  */
910 int cms_pkey_get_ri_type(EVP_PKEY *pk)
911 {
912     if (pk->ameth && pk->ameth->pkey_ctrl) {
913         int i, r;
914         i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_RI_TYPE, 0, &r);
915         if (i > 0)
916             return r;
917     }
918     return CMS_RECIPINFO_TRANS;
919 }