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