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