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