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