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