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