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