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