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