Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl36/crypto/cms/cms_env.c
Line
Count
Source
1
/*
2
 * Copyright 2008-2025 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
/*
11
 * Low level key APIs (DH etc) are deprecated for public use, but still ok for
12
 * internal use.
13
 */
14
#include "internal/deprecated.h"
15
16
#include "internal/cryptlib.h"
17
#include <openssl/asn1t.h>
18
#include <openssl/pem.h>
19
#include <openssl/x509v3.h>
20
#include <openssl/err.h>
21
#include <openssl/cms.h>
22
#include <openssl/evp.h>
23
#include <openssl/core_names.h>
24
#include "internal/sizes.h"
25
#include "crypto/asn1.h"
26
#include "crypto/evp.h"
27
#include "crypto/x509.h"
28
#include "cms_local.h"
29
30
/* CMS EnvelopedData Utilities */
31
static void cms_env_set_version(CMS_EnvelopedData *env);
32
33
5.04k
#define CMS_ENVELOPED_STANDARD 1
34
0
#define CMS_ENVELOPED_AUTH 2
35
36
static int cms_get_enveloped_type_simple(const CMS_ContentInfo *cms)
37
6.85k
{
38
6.85k
    int nid = OBJ_obj2nid(cms->contentType);
39
40
6.85k
    switch (nid) {
41
2.52k
    case NID_pkcs7_enveloped:
42
2.52k
        return CMS_ENVELOPED_STANDARD;
43
44
0
    case NID_id_smime_ct_authEnvelopedData:
45
0
        return CMS_ENVELOPED_AUTH;
46
47
4.33k
    default:
48
4.33k
        return 0;
49
6.85k
    }
50
6.85k
}
51
52
static int cms_get_enveloped_type(const CMS_ContentInfo *cms)
53
6.85k
{
54
6.85k
    int ret = cms_get_enveloped_type_simple(cms);
55
56
6.85k
    if (ret == 0)
57
6.85k
        ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA);
58
6.85k
    return ret;
59
6.85k
}
60
61
CMS_EnvelopedData *ossl_cms_get0_enveloped(CMS_ContentInfo *cms)
62
0
{
63
0
    if (OBJ_obj2nid(cms->contentType) != NID_pkcs7_enveloped) {
64
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA);
65
0
        return NULL;
66
0
    }
67
0
    return cms->d.envelopedData;
68
0
}
69
70
CMS_AuthEnvelopedData *ossl_cms_get0_auth_enveloped(CMS_ContentInfo *cms)
71
0
{
72
0
    if (OBJ_obj2nid(cms->contentType) != NID_id_smime_ct_authEnvelopedData) {
73
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA);
74
0
        return NULL;
75
0
    }
76
0
    return cms->d.authEnvelopedData;
77
0
}
78
79
static CMS_EnvelopedData *cms_enveloped_data_init(CMS_ContentInfo *cms)
80
0
{
81
0
    if (cms->d.other == NULL) {
82
0
        cms->d.envelopedData = M_ASN1_new_of(CMS_EnvelopedData);
83
0
        if (cms->d.envelopedData == NULL) {
84
0
            ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
85
0
            return NULL;
86
0
        }
87
0
        cms->d.envelopedData->version = 0;
88
0
        cms->d.envelopedData->encryptedContentInfo->contentType = OBJ_nid2obj(NID_pkcs7_data);
89
0
        ASN1_OBJECT_free(cms->contentType);
90
0
        cms->contentType = OBJ_nid2obj(NID_pkcs7_enveloped);
91
0
        return cms->d.envelopedData;
92
0
    }
93
0
    return ossl_cms_get0_enveloped(cms);
94
0
}
95
96
static CMS_AuthEnvelopedData *
97
cms_auth_enveloped_data_init(CMS_ContentInfo *cms)
98
0
{
99
0
    if (cms->d.other == NULL) {
100
0
        cms->d.authEnvelopedData = M_ASN1_new_of(CMS_AuthEnvelopedData);
101
0
        if (cms->d.authEnvelopedData == NULL) {
102
0
            ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
103
0
            return NULL;
104
0
        }
105
        /* Defined in RFC 5083 - Section 2.1. "AuthEnvelopedData Type" */
106
0
        cms->d.authEnvelopedData->version = 0;
107
0
        cms->d.authEnvelopedData->authEncryptedContentInfo->contentType = OBJ_nid2obj(NID_pkcs7_data);
108
0
        ASN1_OBJECT_free(cms->contentType);
109
0
        cms->contentType = OBJ_nid2obj(NID_id_smime_ct_authEnvelopedData);
110
0
        return cms->d.authEnvelopedData;
111
0
    }
112
0
    return ossl_cms_get0_auth_enveloped(cms);
113
0
}
114
115
int ossl_cms_env_asn1_ctrl(CMS_RecipientInfo *ri, int cmd)
116
0
{
117
0
    EVP_PKEY *pkey;
118
0
    int i;
119
120
0
    switch (ri->type) {
121
0
    case CMS_RECIPINFO_TRANS:
122
0
        pkey = ri->d.ktri->pkey;
123
0
        break;
124
0
    case CMS_RECIPINFO_AGREE: {
125
0
        EVP_PKEY_CTX *pctx = ri->d.kari->pctx;
126
127
0
        if (pctx == NULL)
128
0
            return 0;
129
0
        pkey = EVP_PKEY_CTX_get0_pkey(pctx);
130
0
        if (pkey == NULL)
131
0
            return 0;
132
0
        break;
133
0
    }
134
0
    case CMS_RECIPINFO_KEM:
135
0
        return ossl_cms_kem_envelope(ri, cmd);
136
0
    default:
137
0
        return 0;
138
0
    }
139
140
0
    if (EVP_PKEY_is_a(pkey, "DHX") || EVP_PKEY_is_a(pkey, "DH"))
141
0
        return ossl_cms_dh_envelope(ri, cmd);
142
0
    else if (EVP_PKEY_is_a(pkey, "EC"))
143
0
        return ossl_cms_ecdh_envelope(ri, cmd);
144
0
    else if (EVP_PKEY_is_a(pkey, "RSA"))
145
0
        return ossl_cms_rsa_envelope(ri, cmd);
146
147
    /* Something else? We'll give engines etc a chance to handle this */
148
0
    if (pkey->ameth == NULL || pkey->ameth->pkey_ctrl == NULL)
149
0
        return 1;
150
0
    i = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_CMS_ENVELOPE, cmd, ri);
151
0
    if (i == -2) {
152
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
153
0
        return 0;
154
0
    }
155
0
    if (i <= 0) {
156
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE);
157
0
        return 0;
158
0
    }
159
0
    return 1;
160
0
}
161
162
CMS_EncryptedContentInfo *ossl_cms_get0_env_enc_content(const CMS_ContentInfo *cms)
163
0
{
164
0
    switch (cms_get_enveloped_type(cms)) {
165
0
    case CMS_ENVELOPED_STANDARD:
166
0
        return cms->d.envelopedData == NULL ? NULL
167
0
                                            : cms->d.envelopedData->encryptedContentInfo;
168
169
0
    case CMS_ENVELOPED_AUTH:
170
0
        return cms->d.authEnvelopedData == NULL ? NULL
171
0
                                                : cms->d.authEnvelopedData->authEncryptedContentInfo;
172
173
0
    default:
174
0
        return NULL;
175
0
    }
176
0
}
177
178
STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms)
179
6.85k
{
180
6.85k
    switch (cms_get_enveloped_type(cms)) {
181
2.52k
    case CMS_ENVELOPED_STANDARD:
182
2.52k
        return cms->d.envelopedData->recipientInfos;
183
184
0
    case CMS_ENVELOPED_AUTH:
185
0
        return cms->d.authEnvelopedData->recipientInfos;
186
187
4.33k
    default:
188
4.33k
        return NULL;
189
6.85k
    }
190
6.85k
}
191
192
void ossl_cms_RecipientInfos_set_cmsctx(CMS_ContentInfo *cms)
193
2.23k
{
194
2.23k
    int i;
195
2.23k
    CMS_RecipientInfo *ri;
196
2.23k
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
197
2.23k
    STACK_OF(CMS_RecipientInfo) *rinfos = CMS_get0_RecipientInfos(cms);
198
199
6.77k
    for (i = 0; i < sk_CMS_RecipientInfo_num(rinfos); i++) {
200
4.53k
        ri = sk_CMS_RecipientInfo_value(rinfos, i);
201
4.53k
        if (ri != NULL) {
202
4.53k
            switch (ri->type) {
203
1.45k
            case CMS_RECIPINFO_AGREE:
204
1.45k
                ri->d.kari->cms_ctx = ctx;
205
1.45k
                break;
206
1.06k
            case CMS_RECIPINFO_TRANS:
207
1.06k
                ri->d.ktri->cms_ctx = ctx;
208
1.06k
                ossl_x509_set0_libctx(ri->d.ktri->recip,
209
1.06k
                    ossl_cms_ctx_get0_libctx(ctx),
210
1.06k
                    ossl_cms_ctx_get0_propq(ctx));
211
1.06k
                break;
212
118
            case CMS_RECIPINFO_KEK:
213
118
                ri->d.kekri->cms_ctx = ctx;
214
118
                break;
215
1.60k
            case CMS_RECIPINFO_PASS:
216
1.60k
                ri->d.pwri->cms_ctx = ctx;
217
1.60k
                break;
218
0
            case CMS_RECIPINFO_KEM:
219
0
                ri->d.ori->d.kemri->cms_ctx = ctx;
220
0
                break;
221
300
            default:
222
300
                break;
223
4.53k
            }
224
4.53k
        }
225
4.53k
    }
226
2.23k
}
227
228
int CMS_RecipientInfo_type(CMS_RecipientInfo *ri)
229
0
{
230
0
    return ri->type;
231
0
}
232
233
EVP_PKEY_CTX *CMS_RecipientInfo_get0_pkey_ctx(CMS_RecipientInfo *ri)
234
0
{
235
0
    if (ri->type == CMS_RECIPINFO_TRANS)
236
0
        return ri->d.ktri->pctx;
237
0
    else if (ri->type == CMS_RECIPINFO_AGREE)
238
0
        return ri->d.kari->pctx;
239
0
    else if (ri->type == CMS_RECIPINFO_KEM)
240
0
        return ri->d.ori->d.kemri->pctx;
241
0
    return NULL;
242
0
}
243
244
CMS_ContentInfo *CMS_EnvelopedData_create_ex(const EVP_CIPHER *cipher,
245
    OSSL_LIB_CTX *libctx,
246
    const char *propq)
247
0
{
248
0
    CMS_ContentInfo *cms;
249
0
    CMS_EnvelopedData *env;
250
251
0
    cms = CMS_ContentInfo_new_ex(libctx, propq);
252
0
    if (cms == NULL)
253
0
        goto err;
254
0
    env = cms_enveloped_data_init(cms);
255
0
    if (env == NULL)
256
0
        goto err;
257
258
0
    if (!ossl_cms_EncryptedContent_init(env->encryptedContentInfo, cipher, NULL,
259
0
            0, ossl_cms_get0_cmsctx(cms)))
260
0
        goto err;
261
0
    return cms;
262
0
err:
263
0
    CMS_ContentInfo_free(cms);
264
0
    ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
265
0
    return NULL;
266
0
}
267
268
CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher)
269
0
{
270
0
    return CMS_EnvelopedData_create_ex(cipher, NULL, NULL);
271
0
}
272
273
BIO *CMS_EnvelopedData_decrypt(CMS_EnvelopedData *env, BIO *detached_data,
274
    EVP_PKEY *pkey, X509 *cert,
275
    ASN1_OCTET_STRING *secret, unsigned int flags,
276
    OSSL_LIB_CTX *libctx, const char *propq)
277
0
{
278
0
    CMS_ContentInfo *ci;
279
0
    BIO *bio = NULL;
280
0
    int res = 0;
281
282
0
    if (env == NULL) {
283
0
        ERR_raise(ERR_LIB_CMS, ERR_R_PASSED_NULL_PARAMETER);
284
0
        return NULL;
285
0
    }
286
287
0
    if ((ci = CMS_ContentInfo_new_ex(libctx, propq)) == NULL
288
0
        || (bio = BIO_new(BIO_s_mem())) == NULL)
289
0
        goto end;
290
0
    ci->contentType = OBJ_nid2obj(NID_pkcs7_enveloped);
291
0
    ci->d.envelopedData = env;
292
0
    if (secret != NULL
293
0
        && CMS_decrypt_set1_password(ci, (unsigned char *)ASN1_STRING_get0_data(secret),
294
0
               ASN1_STRING_length(secret))
295
0
            != 1)
296
0
        goto end;
297
0
    res = CMS_decrypt(ci, secret == NULL ? pkey : NULL,
298
0
        secret == NULL ? cert : NULL, detached_data, bio, flags);
299
300
0
end:
301
0
    if (ci != NULL) {
302
0
        ci->d.envelopedData = NULL; /* do not indirectly free |env| */
303
0
        ci->contentType = NULL;
304
0
    }
305
0
    CMS_ContentInfo_free(ci);
306
0
    if (!res) {
307
0
        BIO_free(bio);
308
0
        bio = NULL;
309
0
    }
310
0
    return bio;
311
0
}
312
313
CMS_ContentInfo *
314
CMS_AuthEnvelopedData_create_ex(const EVP_CIPHER *cipher, OSSL_LIB_CTX *libctx,
315
    const char *propq)
316
0
{
317
0
    CMS_ContentInfo *cms;
318
0
    CMS_AuthEnvelopedData *aenv;
319
320
0
    cms = CMS_ContentInfo_new_ex(libctx, propq);
321
0
    if (cms == NULL)
322
0
        goto merr;
323
0
    aenv = cms_auth_enveloped_data_init(cms);
324
0
    if (aenv == NULL)
325
0
        goto merr;
326
0
    if (!ossl_cms_EncryptedContent_init(aenv->authEncryptedContentInfo,
327
0
            cipher, NULL, 0,
328
0
            ossl_cms_get0_cmsctx(cms)))
329
0
        goto merr;
330
0
    return cms;
331
0
merr:
332
0
    CMS_ContentInfo_free(cms);
333
0
    ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
334
0
    return NULL;
335
0
}
336
337
CMS_ContentInfo *CMS_AuthEnvelopedData_create(const EVP_CIPHER *cipher)
338
0
{
339
0
    return CMS_AuthEnvelopedData_create_ex(cipher, NULL, NULL);
340
0
}
341
342
/* Key Transport Recipient Info (KTRI) routines */
343
344
/* Initialise a ktri based on passed certificate and key */
345
346
static int cms_RecipientInfo_ktri_init(CMS_RecipientInfo *ri, X509 *recip,
347
    EVP_PKEY *pk, unsigned int flags,
348
    const CMS_CTX *ctx)
349
0
{
350
0
    CMS_KeyTransRecipientInfo *ktri;
351
0
    int idtype;
352
353
0
    ri->d.ktri = M_ASN1_new_of(CMS_KeyTransRecipientInfo);
354
0
    if (!ri->d.ktri)
355
0
        return 0;
356
0
    ri->encoded_type = ri->type = CMS_RECIPINFO_TRANS;
357
358
0
    ktri = ri->d.ktri;
359
0
    ktri->cms_ctx = ctx;
360
361
0
    if (flags & CMS_USE_KEYID) {
362
0
        ktri->version = 2;
363
0
        idtype = CMS_RECIPINFO_KEYIDENTIFIER;
364
0
    } else {
365
0
        ktri->version = 0;
366
0
        idtype = CMS_RECIPINFO_ISSUER_SERIAL;
367
0
    }
368
369
    /*
370
     * Not a typo: RecipientIdentifier and SignerIdentifier are the same
371
     * structure.
372
     */
373
374
0
    if (!ossl_cms_set1_SignerIdentifier(ktri->rid, recip, idtype, ctx))
375
0
        return 0;
376
377
0
    if (!X509_up_ref(recip))
378
0
        return 0;
379
0
    if (!EVP_PKEY_up_ref(pk)) {
380
0
        X509_free(recip);
381
0
        return 0;
382
0
    }
383
384
0
    ktri->pkey = pk;
385
0
    ktri->recip = recip;
386
387
0
    if (flags & CMS_KEY_PARAM) {
388
0
        ktri->pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
389
0
            ktri->pkey,
390
0
            ossl_cms_ctx_get0_propq(ctx));
391
0
        if (ktri->pctx == NULL)
392
0
            return 0;
393
0
        if (EVP_PKEY_encrypt_init(ktri->pctx) <= 0)
394
0
            return 0;
395
0
    } else if (!ossl_cms_env_asn1_ctrl(ri, 0))
396
0
        return 0;
397
0
    return 1;
398
0
}
399
400
/*
401
 * Add a recipient certificate using appropriate type of RecipientInfo
402
 */
403
404
CMS_RecipientInfo *CMS_add1_recipient(CMS_ContentInfo *cms, X509 *recip,
405
    EVP_PKEY *originatorPrivKey,
406
    X509 *originator, unsigned int flags)
407
0
{
408
0
    CMS_RecipientInfo *ri = NULL;
409
0
    STACK_OF(CMS_RecipientInfo) *ris;
410
0
    EVP_PKEY *pk = NULL;
411
0
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
412
413
0
    ris = CMS_get0_RecipientInfos(cms);
414
0
    if (ris == NULL)
415
0
        goto err;
416
417
    /* Initialize recipient info */
418
0
    ri = M_ASN1_new_of(CMS_RecipientInfo);
419
0
    if (ri == NULL) {
420
0
        ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
421
0
        goto err;
422
0
    }
423
424
0
    pk = X509_get0_pubkey(recip);
425
0
    if (pk == NULL) {
426
0
        ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_GETTING_PUBLIC_KEY);
427
0
        goto err;
428
0
    }
429
430
0
    switch (ossl_cms_pkey_get_ri_type(pk)) {
431
432
0
    case CMS_RECIPINFO_TRANS:
433
0
        if (!cms_RecipientInfo_ktri_init(ri, recip, pk, flags, ctx))
434
0
            goto err;
435
0
        break;
436
437
0
    case CMS_RECIPINFO_AGREE:
438
0
        if (!ossl_cms_RecipientInfo_kari_init(ri, recip, pk, originator,
439
0
                originatorPrivKey, flags, ctx))
440
0
            goto err;
441
0
        break;
442
443
0
    case CMS_RECIPINFO_KEM:
444
0
        if (!ossl_cms_RecipientInfo_kemri_init(ri, recip, pk, flags, ctx))
445
0
            goto err;
446
0
        break;
447
448
0
    default:
449
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
450
0
        goto err;
451
0
    }
452
453
0
    if (!sk_CMS_RecipientInfo_push(ris, ri)) {
454
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
455
0
        goto err;
456
0
    }
457
458
0
    return ri;
459
460
0
err:
461
0
    M_ASN1_free_of(ri, CMS_RecipientInfo);
462
0
    return NULL;
463
0
}
464
465
CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, X509 *recip,
466
    unsigned int flags)
467
0
{
468
0
    return CMS_add1_recipient(cms, recip, NULL, NULL, flags);
469
0
}
470
471
int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri,
472
    EVP_PKEY **pk, X509 **recip,
473
    X509_ALGOR **palg)
474
0
{
475
0
    CMS_KeyTransRecipientInfo *ktri;
476
0
    if (ri->type != CMS_RECIPINFO_TRANS) {
477
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
478
0
        return 0;
479
0
    }
480
481
0
    ktri = ri->d.ktri;
482
483
0
    if (pk)
484
0
        *pk = ktri->pkey;
485
0
    if (recip)
486
0
        *recip = ktri->recip;
487
0
    if (palg)
488
0
        *palg = ktri->keyEncryptionAlgorithm;
489
0
    return 1;
490
0
}
491
492
int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri,
493
    ASN1_OCTET_STRING **keyid,
494
    X509_NAME **issuer,
495
    ASN1_INTEGER **sno)
496
0
{
497
0
    CMS_KeyTransRecipientInfo *ktri;
498
0
    if (ri->type != CMS_RECIPINFO_TRANS) {
499
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
500
0
        return 0;
501
0
    }
502
0
    ktri = ri->d.ktri;
503
504
0
    return ossl_cms_SignerIdentifier_get0_signer_id(ktri->rid, keyid, issuer,
505
0
        sno);
506
0
}
507
508
int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert)
509
0
{
510
0
    if (ri->type != CMS_RECIPINFO_TRANS) {
511
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
512
0
        return -2;
513
0
    }
514
0
    return ossl_cms_SignerIdentifier_cert_cmp(ri->d.ktri->rid, cert);
515
0
}
516
517
int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey)
518
0
{
519
0
    if (ri->type != CMS_RECIPINFO_TRANS) {
520
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
521
0
        return 0;
522
0
    }
523
0
    EVP_PKEY_free(ri->d.ktri->pkey);
524
0
    ri->d.ktri->pkey = pkey;
525
0
    return 1;
526
0
}
527
528
/* Encrypt content key in key transport recipient info */
529
530
static int cms_RecipientInfo_ktri_encrypt(const CMS_ContentInfo *cms,
531
    CMS_RecipientInfo *ri)
532
0
{
533
0
    CMS_KeyTransRecipientInfo *ktri;
534
0
    CMS_EncryptedContentInfo *ec;
535
0
    EVP_PKEY_CTX *pctx;
536
0
    unsigned char *ek = NULL;
537
0
    size_t eklen;
538
0
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
539
540
0
    int ret = 0;
541
542
0
    if (ri->type != CMS_RECIPINFO_TRANS) {
543
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
544
0
        return 0;
545
0
    }
546
0
    ktri = ri->d.ktri;
547
0
    ec = ossl_cms_get0_env_enc_content(cms);
548
549
0
    pctx = ktri->pctx;
550
551
0
    if (pctx) {
552
0
        if (!ossl_cms_env_asn1_ctrl(ri, 0))
553
0
            goto err;
554
0
    } else {
555
0
        pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
556
0
            ktri->pkey,
557
0
            ossl_cms_ctx_get0_propq(ctx));
558
0
        if (pctx == NULL)
559
0
            return 0;
560
561
0
        if (EVP_PKEY_encrypt_init(pctx) <= 0)
562
0
            goto err;
563
0
    }
564
565
0
    if (EVP_PKEY_encrypt(pctx, NULL, &eklen, ec->key, ec->keylen) <= 0)
566
0
        goto err;
567
568
0
    ek = OPENSSL_malloc(eklen);
569
0
    if (ek == NULL)
570
0
        goto err;
571
572
0
    if (EVP_PKEY_encrypt(pctx, ek, &eklen, ec->key, ec->keylen) <= 0)
573
0
        goto err;
574
575
0
    ASN1_STRING_set0(ktri->encryptedKey, ek, (int)eklen);
576
0
    ek = NULL;
577
578
0
    ret = 1;
579
580
0
err:
581
0
    EVP_PKEY_CTX_free(pctx);
582
0
    ktri->pctx = NULL;
583
0
    OPENSSL_free(ek);
584
0
    return ret;
585
0
}
586
587
/* Decrypt content key from KTRI */
588
589
static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
590
    CMS_RecipientInfo *ri)
591
0
{
592
0
    CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
593
0
    EVP_PKEY *pkey = ktri->pkey;
594
0
    unsigned char *ek = NULL;
595
0
    size_t eklen;
596
0
    int ret = 0;
597
0
    size_t fixlen = 0;
598
0
    const EVP_CIPHER *cipher = NULL;
599
0
    EVP_CIPHER *fetched_cipher = NULL;
600
0
    CMS_EncryptedContentInfo *ec;
601
0
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
602
0
    OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx);
603
0
    const char *propq = ossl_cms_ctx_get0_propq(ctx);
604
605
0
    ec = ossl_cms_get0_env_enc_content(cms);
606
607
0
    if (ktri->pkey == NULL) {
608
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_PRIVATE_KEY);
609
0
        return 0;
610
0
    }
611
612
0
    if (cms->d.envelopedData->encryptedContentInfo->havenocert
613
0
        && !cms->d.envelopedData->encryptedContentInfo->debug) {
614
0
        X509_ALGOR *calg = ec->contentEncryptionAlgorithm;
615
0
        char name[OSSL_MAX_NAME_SIZE];
616
617
0
        OBJ_obj2txt(name, sizeof(name), calg->algorithm, 0);
618
619
0
        (void)ERR_set_mark();
620
0
        fetched_cipher = EVP_CIPHER_fetch(libctx, name, propq);
621
622
0
        if (fetched_cipher != NULL)
623
0
            cipher = fetched_cipher;
624
0
        else
625
0
            cipher = EVP_get_cipherbyobj(calg->algorithm);
626
0
        if (cipher == NULL) {
627
0
            (void)ERR_clear_last_mark();
628
0
            ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_CIPHER);
629
0
            return 0;
630
0
        }
631
0
        (void)ERR_pop_to_mark();
632
633
0
        fixlen = EVP_CIPHER_get_key_length(cipher);
634
0
        EVP_CIPHER_free(fetched_cipher);
635
0
    }
636
637
0
    ktri->pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq);
638
0
    if (ktri->pctx == NULL)
639
0
        goto err;
640
641
0
    if (EVP_PKEY_decrypt_init(ktri->pctx) <= 0)
642
0
        goto err;
643
644
0
    if (!ossl_cms_env_asn1_ctrl(ri, 1))
645
0
        goto err;
646
647
0
    if (EVP_PKEY_is_a(pkey, "RSA"))
648
        /* upper layer CMS code incorrectly assumes that a successful RSA
649
         * decryption means that the key matches ciphertext (which never
650
         * was the case, implicit rejection or not), so to make it work
651
         * disable implicit rejection for RSA keys */
652
0
        EVP_PKEY_CTX_ctrl_str(ktri->pctx, "rsa_pkcs1_implicit_rejection", "0");
653
654
0
    if (evp_pkey_decrypt_alloc(ktri->pctx, &ek, &eklen, fixlen,
655
0
            ktri->encryptedKey->data,
656
0
            ktri->encryptedKey->length)
657
0
        <= 0)
658
0
        goto err;
659
660
0
    ret = 1;
661
662
0
    OPENSSL_clear_free(ec->key, ec->keylen);
663
0
    ec->key = ek;
664
0
    ec->keylen = eklen;
665
666
0
err:
667
0
    EVP_PKEY_CTX_free(ktri->pctx);
668
0
    ktri->pctx = NULL;
669
0
    if (!ret)
670
0
        OPENSSL_free(ek);
671
672
0
    return ret;
673
0
}
674
675
/* Key Encrypted Key (KEK) RecipientInfo routines */
676
677
int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri,
678
    const unsigned char *id, size_t idlen)
679
0
{
680
0
    ASN1_OCTET_STRING tmp_os;
681
0
    CMS_KEKRecipientInfo *kekri;
682
0
    if (ri->type != CMS_RECIPINFO_KEK) {
683
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
684
0
        return -2;
685
0
    }
686
0
    kekri = ri->d.kekri;
687
0
    tmp_os.type = V_ASN1_OCTET_STRING;
688
0
    tmp_os.flags = 0;
689
0
    tmp_os.data = (unsigned char *)id;
690
0
    tmp_os.length = (int)idlen;
691
0
    return ASN1_OCTET_STRING_cmp(&tmp_os, kekri->kekid->keyIdentifier);
692
0
}
693
694
/* For now hard code AES key wrap info */
695
696
static size_t aes_wrap_keylen(int nid)
697
0
{
698
0
    switch (nid) {
699
0
    case NID_id_aes128_wrap:
700
0
        return 16;
701
702
0
    case NID_id_aes192_wrap:
703
0
        return 24;
704
705
0
    case NID_id_aes256_wrap:
706
0
        return 32;
707
708
0
    default:
709
0
        return 0;
710
0
    }
711
0
}
712
713
CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid,
714
    unsigned char *key, size_t keylen,
715
    unsigned char *id, size_t idlen,
716
    ASN1_GENERALIZEDTIME *date,
717
    ASN1_OBJECT *otherTypeId,
718
    ASN1_TYPE *otherType)
719
0
{
720
0
    CMS_RecipientInfo *ri = NULL;
721
0
    CMS_KEKRecipientInfo *kekri;
722
0
    STACK_OF(CMS_RecipientInfo) *ris = CMS_get0_RecipientInfos(cms);
723
724
0
    if (ris == NULL || idlen > INT_MAX)
725
0
        goto err;
726
727
0
    if (nid == NID_undef) {
728
0
        switch (keylen) {
729
0
        case 16:
730
0
            nid = NID_id_aes128_wrap;
731
0
            break;
732
733
0
        case 24:
734
0
            nid = NID_id_aes192_wrap;
735
0
            break;
736
737
0
        case 32:
738
0
            nid = NID_id_aes256_wrap;
739
0
            break;
740
741
0
        default:
742
0
            ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
743
0
            goto err;
744
0
        }
745
746
0
    } else {
747
748
0
        size_t exp_keylen = aes_wrap_keylen(nid);
749
750
0
        if (!exp_keylen) {
751
0
            ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEK_ALGORITHM);
752
0
            goto err;
753
0
        }
754
755
0
        if (keylen != exp_keylen) {
756
0
            ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
757
0
            goto err;
758
0
        }
759
0
    }
760
761
    /* Initialize recipient info */
762
0
    ri = M_ASN1_new_of(CMS_RecipientInfo);
763
0
    if (!ri) {
764
0
        ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
765
0
        goto err;
766
0
    }
767
768
0
    ri->d.kekri = M_ASN1_new_of(CMS_KEKRecipientInfo);
769
0
    if (!ri->d.kekri) {
770
0
        ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
771
0
        goto err;
772
0
    }
773
0
    ri->encoded_type = ri->type = CMS_RECIPINFO_KEK;
774
775
0
    kekri = ri->d.kekri;
776
777
0
    if (otherTypeId) {
778
0
        kekri->kekid->other = M_ASN1_new_of(CMS_OtherKeyAttribute);
779
0
        if (kekri->kekid->other == NULL) {
780
0
            ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
781
0
            goto err;
782
0
        }
783
0
    }
784
785
0
    if (!sk_CMS_RecipientInfo_push(ris, ri)) {
786
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
787
0
        goto err;
788
0
    }
789
790
    /* After this point no calls can fail */
791
792
0
    kekri->version = 4;
793
794
0
    kekri->key = key;
795
0
    kekri->keylen = keylen;
796
797
0
    ASN1_STRING_set0(kekri->kekid->keyIdentifier, id, (int)idlen);
798
799
0
    kekri->kekid->date = date;
800
801
0
    if (kekri->kekid->other) {
802
0
        kekri->kekid->other->keyAttrId = otherTypeId;
803
0
        kekri->kekid->other->keyAttr = otherType;
804
0
    }
805
806
0
    (void)X509_ALGOR_set0(kekri->keyEncryptionAlgorithm, OBJ_nid2obj(nid),
807
0
        V_ASN1_UNDEF, NULL); /* cannot fail */
808
809
0
    return ri;
810
811
0
err:
812
0
    M_ASN1_free_of(ri, CMS_RecipientInfo);
813
0
    return NULL;
814
0
}
815
816
int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri,
817
    X509_ALGOR **palg,
818
    ASN1_OCTET_STRING **pid,
819
    ASN1_GENERALIZEDTIME **pdate,
820
    ASN1_OBJECT **potherid,
821
    ASN1_TYPE **pothertype)
822
0
{
823
0
    CMS_KEKIdentifier *rkid;
824
0
    if (ri->type != CMS_RECIPINFO_KEK) {
825
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
826
0
        return 0;
827
0
    }
828
0
    rkid = ri->d.kekri->kekid;
829
0
    if (palg)
830
0
        *palg = ri->d.kekri->keyEncryptionAlgorithm;
831
0
    if (pid)
832
0
        *pid = rkid->keyIdentifier;
833
0
    if (pdate)
834
0
        *pdate = rkid->date;
835
0
    if (potherid) {
836
0
        if (rkid->other)
837
0
            *potherid = rkid->other->keyAttrId;
838
0
        else
839
0
            *potherid = NULL;
840
0
    }
841
0
    if (pothertype) {
842
0
        if (rkid->other)
843
0
            *pothertype = rkid->other->keyAttr;
844
0
        else
845
0
            *pothertype = NULL;
846
0
    }
847
0
    return 1;
848
0
}
849
850
int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri,
851
    unsigned char *key, size_t keylen)
852
0
{
853
0
    CMS_KEKRecipientInfo *kekri;
854
0
    if (ri->type != CMS_RECIPINFO_KEK) {
855
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
856
0
        return 0;
857
0
    }
858
859
0
    kekri = ri->d.kekri;
860
0
    kekri->key = key;
861
0
    kekri->keylen = keylen;
862
0
    return 1;
863
0
}
864
865
static EVP_CIPHER *cms_get_key_wrap_cipher(size_t keylen, const CMS_CTX *ctx)
866
0
{
867
0
    const char *alg = NULL;
868
869
0
    switch (keylen) {
870
0
    case 16:
871
0
        alg = "AES-128-WRAP";
872
0
        break;
873
0
    case 24:
874
0
        alg = "AES-192-WRAP";
875
0
        break;
876
0
    case 32:
877
0
        alg = "AES-256-WRAP";
878
0
        break;
879
0
    default:
880
0
        return NULL;
881
0
    }
882
0
    return EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(ctx), alg,
883
0
        ossl_cms_ctx_get0_propq(ctx));
884
0
}
885
886
/* Encrypt content key in KEK recipient info */
887
888
static int cms_RecipientInfo_kekri_encrypt(const CMS_ContentInfo *cms,
889
    CMS_RecipientInfo *ri)
890
0
{
891
0
    CMS_EncryptedContentInfo *ec;
892
0
    CMS_KEKRecipientInfo *kekri;
893
0
    unsigned char *wkey = NULL;
894
0
    int wkeylen;
895
0
    int r = 0;
896
0
    EVP_CIPHER *cipher = NULL;
897
0
    int outlen = 0;
898
0
    EVP_CIPHER_CTX *ctx = NULL;
899
0
    const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
900
901
0
    ec = ossl_cms_get0_env_enc_content(cms);
902
0
    if (ec == NULL)
903
0
        return 0;
904
905
0
    kekri = ri->d.kekri;
906
907
0
    if (kekri->key == NULL) {
908
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY);
909
0
        return 0;
910
0
    }
911
912
0
    cipher = cms_get_key_wrap_cipher(kekri->keylen, cms_ctx);
913
0
    if (cipher == NULL) {
914
0
        ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
915
0
        goto err;
916
0
    }
917
918
    /* 8 byte prefix for AES wrap ciphers */
919
0
    wkey = OPENSSL_malloc(ec->keylen + 8);
920
0
    if (wkey == NULL)
921
0
        goto err;
922
923
0
    ctx = EVP_CIPHER_CTX_new();
924
0
    if (ctx == NULL) {
925
0
        ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
926
0
        goto err;
927
0
    }
928
929
0
    EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
930
0
    if (!EVP_EncryptInit_ex(ctx, cipher, NULL, kekri->key, NULL)
931
0
        || !EVP_EncryptUpdate(ctx, wkey, &wkeylen, ec->key, (int)ec->keylen)
932
0
        || !EVP_EncryptFinal_ex(ctx, wkey + wkeylen, &outlen)) {
933
0
        ERR_raise(ERR_LIB_CMS, CMS_R_WRAP_ERROR);
934
0
        goto err;
935
0
    }
936
0
    wkeylen += outlen;
937
0
    if (!ossl_assert((size_t)wkeylen == ec->keylen + 8)) {
938
0
        ERR_raise(ERR_LIB_CMS, CMS_R_WRAP_ERROR);
939
0
        goto err;
940
0
    }
941
942
0
    ASN1_STRING_set0(kekri->encryptedKey, wkey, wkeylen);
943
944
0
    r = 1;
945
946
0
err:
947
0
    EVP_CIPHER_free(cipher);
948
0
    if (!r)
949
0
        OPENSSL_free(wkey);
950
0
    EVP_CIPHER_CTX_free(ctx);
951
952
0
    return r;
953
0
}
954
955
/* Decrypt content key in KEK recipient info */
956
957
static int cms_RecipientInfo_kekri_decrypt(CMS_ContentInfo *cms,
958
    CMS_RecipientInfo *ri)
959
0
{
960
0
    CMS_EncryptedContentInfo *ec;
961
0
    CMS_KEKRecipientInfo *kekri;
962
0
    unsigned char *ukey = NULL;
963
0
    int ukeylen;
964
0
    int r = 0, wrap_nid;
965
0
    EVP_CIPHER *cipher = NULL;
966
0
    int outlen = 0;
967
0
    EVP_CIPHER_CTX *ctx = NULL;
968
0
    const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
969
970
0
    ec = ossl_cms_get0_env_enc_content(cms);
971
0
    if (ec == NULL)
972
0
        return 0;
973
974
0
    kekri = ri->d.kekri;
975
976
0
    if (!kekri->key) {
977
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY);
978
0
        return 0;
979
0
    }
980
981
0
    wrap_nid = OBJ_obj2nid(kekri->keyEncryptionAlgorithm->algorithm);
982
0
    if (aes_wrap_keylen(wrap_nid) != kekri->keylen) {
983
0
        ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
984
0
        return 0;
985
0
    }
986
987
    /* If encrypted key length is invalid don't bother */
988
989
0
    if (kekri->encryptedKey->length < 16) {
990
0
        ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_ENCRYPTED_KEY_LENGTH);
991
0
        goto err;
992
0
    }
993
994
0
    cipher = cms_get_key_wrap_cipher(kekri->keylen, cms_ctx);
995
0
    if (cipher == NULL) {
996
0
        ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
997
0
        goto err;
998
0
    }
999
1000
0
    ukey = OPENSSL_malloc(kekri->encryptedKey->length - 8);
1001
0
    if (ukey == NULL)
1002
0
        goto err;
1003
1004
0
    ctx = EVP_CIPHER_CTX_new();
1005
0
    if (ctx == NULL) {
1006
0
        ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
1007
0
        goto err;
1008
0
    }
1009
1010
0
    if (!EVP_DecryptInit_ex(ctx, cipher, NULL, kekri->key, NULL)
1011
0
        || !EVP_DecryptUpdate(ctx, ukey, &ukeylen,
1012
0
            kekri->encryptedKey->data,
1013
0
            kekri->encryptedKey->length)
1014
0
        || !EVP_DecryptFinal_ex(ctx, ukey + ukeylen, &outlen)) {
1015
0
        ERR_raise(ERR_LIB_CMS, CMS_R_UNWRAP_ERROR);
1016
0
        goto err;
1017
0
    }
1018
0
    ukeylen += outlen;
1019
1020
0
    OPENSSL_clear_free(ec->key, ec->keylen);
1021
0
    ec->key = ukey;
1022
0
    ec->keylen = ukeylen;
1023
1024
0
    r = 1;
1025
1026
0
err:
1027
0
    EVP_CIPHER_free(cipher);
1028
0
    if (!r)
1029
0
        OPENSSL_free(ukey);
1030
0
    EVP_CIPHER_CTX_free(ctx);
1031
1032
0
    return r;
1033
0
}
1034
1035
int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri)
1036
0
{
1037
0
    switch (ri->type) {
1038
0
    case CMS_RECIPINFO_TRANS:
1039
0
        return cms_RecipientInfo_ktri_decrypt(cms, ri);
1040
1041
0
    case CMS_RECIPINFO_KEK:
1042
0
        return cms_RecipientInfo_kekri_decrypt(cms, ri);
1043
1044
0
    case CMS_RECIPINFO_PASS:
1045
0
        return ossl_cms_RecipientInfo_pwri_crypt(cms, ri, 0);
1046
1047
0
    case CMS_RECIPINFO_KEM:
1048
0
        return ossl_cms_RecipientInfo_kemri_decrypt(cms, ri);
1049
1050
0
    default:
1051
0
        ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE);
1052
0
        return 0;
1053
0
    }
1054
0
}
1055
1056
int CMS_RecipientInfo_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri)
1057
0
{
1058
0
    switch (ri->type) {
1059
0
    case CMS_RECIPINFO_TRANS:
1060
0
        return cms_RecipientInfo_ktri_encrypt(cms, ri);
1061
1062
0
    case CMS_RECIPINFO_AGREE:
1063
0
        return ossl_cms_RecipientInfo_kari_encrypt(cms, ri);
1064
1065
0
    case CMS_RECIPINFO_KEK:
1066
0
        return cms_RecipientInfo_kekri_encrypt(cms, ri);
1067
1068
0
    case CMS_RECIPINFO_PASS:
1069
0
        return ossl_cms_RecipientInfo_pwri_crypt(cms, ri, 1);
1070
1071
0
    case CMS_RECIPINFO_KEM:
1072
0
        return ossl_cms_RecipientInfo_kemri_encrypt(cms, ri);
1073
1074
0
    default:
1075
0
        ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_RECIPIENT_TYPE);
1076
0
        return 0;
1077
0
    }
1078
0
}
1079
1080
/* Check structures and fixup version numbers (if necessary) */
1081
1082
static void cms_env_set_originfo_version(CMS_EnvelopedData *env)
1083
0
{
1084
0
    CMS_OriginatorInfo *org = env->originatorInfo;
1085
0
    int i;
1086
0
    if (org == NULL)
1087
0
        return;
1088
0
    for (i = 0; i < sk_CMS_CertificateChoices_num(org->certificates); i++) {
1089
0
        CMS_CertificateChoices *cch;
1090
0
        cch = sk_CMS_CertificateChoices_value(org->certificates, i);
1091
0
        if (cch->type == CMS_CERTCHOICE_OTHER) {
1092
0
            env->version = 4;
1093
0
            return;
1094
0
        } else if (cch->type == CMS_CERTCHOICE_V2ACERT) {
1095
0
            if (env->version < 3)
1096
0
                env->version = 3;
1097
0
        }
1098
0
    }
1099
1100
0
    for (i = 0; i < sk_CMS_RevocationInfoChoice_num(org->crls); i++) {
1101
0
        CMS_RevocationInfoChoice *rch;
1102
0
        rch = sk_CMS_RevocationInfoChoice_value(org->crls, i);
1103
0
        if (rch->type == CMS_REVCHOICE_OTHER) {
1104
0
            env->version = 4;
1105
0
            return;
1106
0
        }
1107
0
    }
1108
0
}
1109
1110
static void cms_env_set_version(CMS_EnvelopedData *env)
1111
0
{
1112
0
    int i;
1113
0
    CMS_RecipientInfo *ri;
1114
1115
    /*
1116
     * Can't set version higher than 4 so if 4 or more already nothing to do.
1117
     */
1118
0
    if (env->version >= 4)
1119
0
        return;
1120
1121
0
    cms_env_set_originfo_version(env);
1122
1123
0
    if (env->version >= 3)
1124
0
        return;
1125
1126
0
    for (i = 0; i < sk_CMS_RecipientInfo_num(env->recipientInfos); i++) {
1127
0
        ri = sk_CMS_RecipientInfo_value(env->recipientInfos, i);
1128
0
        if (ri->type == CMS_RECIPINFO_PASS || ri->type == CMS_RECIPINFO_OTHER
1129
0
            || ri->type == CMS_RECIPINFO_KEM) {
1130
0
            env->version = 3;
1131
0
            return;
1132
0
        } else if (ri->type != CMS_RECIPINFO_TRANS
1133
0
            || ri->d.ktri->version != 0) {
1134
0
            env->version = 2;
1135
0
        }
1136
0
    }
1137
0
    if (env->originatorInfo || env->unprotectedAttrs)
1138
0
        env->version = 2;
1139
0
    if (env->version == 2)
1140
0
        return;
1141
0
    env->version = 0;
1142
0
}
1143
1144
static int cms_env_encrypt_content_key(const CMS_ContentInfo *cms,
1145
    STACK_OF(CMS_RecipientInfo) *ris)
1146
0
{
1147
0
    int i;
1148
0
    CMS_RecipientInfo *ri;
1149
1150
0
    for (i = 0; i < sk_CMS_RecipientInfo_num(ris); i++) {
1151
0
        ri = sk_CMS_RecipientInfo_value(ris, i);
1152
0
        if (CMS_RecipientInfo_encrypt(cms, ri) <= 0)
1153
0
            return -1;
1154
0
    }
1155
0
    return 1;
1156
0
}
1157
1158
static void cms_env_clear_ec(CMS_EncryptedContentInfo *ec)
1159
0
{
1160
0
    ec->cipher = NULL;
1161
0
    OPENSSL_clear_free(ec->key, ec->keylen);
1162
0
    ec->key = NULL;
1163
0
    ec->keylen = 0;
1164
0
}
1165
1166
static BIO *cms_EnvelopedData_Decryption_init_bio(CMS_ContentInfo *cms)
1167
0
{
1168
0
    CMS_EncryptedContentInfo *ec = cms->d.envelopedData->encryptedContentInfo;
1169
0
    BIO *contentBio = ossl_cms_EncryptedContent_init_bio(ec,
1170
0
        ossl_cms_get0_cmsctx(cms),
1171
0
        0);
1172
0
    EVP_CIPHER_CTX *ctx = NULL;
1173
1174
0
    if (contentBio == NULL)
1175
0
        return NULL;
1176
1177
0
    BIO_get_cipher_ctx(contentBio, &ctx);
1178
0
    if (ctx == NULL) {
1179
0
        BIO_free(contentBio);
1180
0
        return NULL;
1181
0
    }
1182
    /*
1183
     * If the selected cipher supports unprotected attributes,
1184
     * deal with it using special ctrl function
1185
     */
1186
0
    if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))
1187
0
            & EVP_CIPH_FLAG_CIPHER_WITH_MAC)
1188
0
            != 0
1189
0
        && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_PROCESS_UNPROTECTED, 0,
1190
0
               cms->d.envelopedData->unprotectedAttrs)
1191
0
            <= 0) {
1192
0
        BIO_free(contentBio);
1193
0
        return NULL;
1194
0
    }
1195
0
    return contentBio;
1196
0
}
1197
1198
static BIO *cms_EnvelopedData_Encryption_init_bio(CMS_ContentInfo *cms)
1199
0
{
1200
0
    CMS_EncryptedContentInfo *ec;
1201
0
    STACK_OF(CMS_RecipientInfo) *rinfos;
1202
0
    int ok = 0;
1203
0
    BIO *ret;
1204
0
    CMS_EnvelopedData *env = cms->d.envelopedData;
1205
1206
    /* Get BIO first to set up key */
1207
1208
0
    ec = env->encryptedContentInfo;
1209
0
    ret = ossl_cms_EncryptedContent_init_bio(ec, ossl_cms_get0_cmsctx(cms), 0);
1210
1211
    /* If error end of processing */
1212
0
    if (!ret)
1213
0
        return ret;
1214
1215
    /* Now encrypt content key according to each RecipientInfo type */
1216
0
    rinfos = env->recipientInfos;
1217
0
    if (cms_env_encrypt_content_key(cms, rinfos) < 0) {
1218
0
        ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_SETTING_RECIPIENTINFO);
1219
0
        goto err;
1220
0
    }
1221
1222
    /* And finally set the version */
1223
0
    cms_env_set_version(env);
1224
1225
0
    ok = 1;
1226
1227
0
err:
1228
0
    cms_env_clear_ec(ec);
1229
0
    if (ok)
1230
0
        return ret;
1231
0
    BIO_free(ret);
1232
0
    return NULL;
1233
0
}
1234
1235
BIO *ossl_cms_EnvelopedData_init_bio(CMS_ContentInfo *cms)
1236
0
{
1237
0
    if (cms->d.envelopedData->encryptedContentInfo->cipher != NULL) {
1238
        /* If cipher is set it's encryption */
1239
0
        return cms_EnvelopedData_Encryption_init_bio(cms);
1240
0
    }
1241
1242
    /* If cipher is not set it's decryption */
1243
0
    return cms_EnvelopedData_Decryption_init_bio(cms);
1244
0
}
1245
1246
BIO *ossl_cms_AuthEnvelopedData_init_bio(CMS_ContentInfo *cms)
1247
0
{
1248
0
    CMS_EncryptedContentInfo *ec;
1249
0
    STACK_OF(CMS_RecipientInfo) *rinfos;
1250
0
    int ok = 0;
1251
0
    BIO *ret;
1252
0
    CMS_AuthEnvelopedData *aenv = cms->d.authEnvelopedData;
1253
1254
    /* Get BIO first to set up key */
1255
0
    ec = aenv->authEncryptedContentInfo;
1256
    /* Set tag for decryption */
1257
0
    if (ec->cipher == NULL) {
1258
0
        ec->tag = aenv->mac->data;
1259
0
        ec->taglen = aenv->mac->length;
1260
0
    }
1261
0
    ret = ossl_cms_EncryptedContent_init_bio(ec, ossl_cms_get0_cmsctx(cms), 1);
1262
1263
    /* If error or no cipher end of processing */
1264
0
    if (ret == NULL || ec->cipher == NULL)
1265
0
        return ret;
1266
1267
    /* Now encrypt content key according to each RecipientInfo type */
1268
0
    rinfos = aenv->recipientInfos;
1269
0
    if (cms_env_encrypt_content_key(cms, rinfos) < 0) {
1270
0
        ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_SETTING_RECIPIENTINFO);
1271
0
        goto err;
1272
0
    }
1273
1274
    /* And finally set the version */
1275
0
    aenv->version = 0;
1276
1277
0
    ok = 1;
1278
1279
0
err:
1280
0
    cms_env_clear_ec(ec);
1281
0
    if (ok)
1282
0
        return ret;
1283
0
    BIO_free(ret);
1284
0
    return NULL;
1285
0
}
1286
1287
int ossl_cms_EnvelopedData_final(CMS_ContentInfo *cms, BIO *chain)
1288
0
{
1289
0
    CMS_EnvelopedData *env = NULL;
1290
0
    EVP_CIPHER_CTX *ctx = NULL;
1291
0
    BIO *mbio = BIO_find_type(chain, BIO_TYPE_CIPHER);
1292
1293
0
    env = ossl_cms_get0_enveloped(cms);
1294
0
    if (env == NULL)
1295
0
        return 0;
1296
1297
0
    if (mbio == NULL) {
1298
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_NOT_FOUND);
1299
0
        return 0;
1300
0
    }
1301
1302
0
    BIO_get_cipher_ctx(mbio, &ctx);
1303
1304
    /*
1305
     * If the selected cipher supports unprotected attributes,
1306
     * deal with it using special ctrl function
1307
     */
1308
0
    if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))
1309
0
            & EVP_CIPH_FLAG_CIPHER_WITH_MAC)
1310
0
        != 0) {
1311
0
        if (env->unprotectedAttrs == NULL)
1312
0
            env->unprotectedAttrs = sk_X509_ATTRIBUTE_new_null();
1313
1314
0
        if (env->unprotectedAttrs == NULL) {
1315
0
            ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
1316
0
            return 0;
1317
0
        }
1318
1319
0
        if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_PROCESS_UNPROTECTED,
1320
0
                1, env->unprotectedAttrs)
1321
0
            <= 0) {
1322
0
            ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE);
1323
0
            return 0;
1324
0
        }
1325
0
    }
1326
1327
0
    cms_env_set_version(cms->d.envelopedData);
1328
0
    return 1;
1329
0
}
1330
1331
int ossl_cms_AuthEnvelopedData_final(CMS_ContentInfo *cms, BIO *cmsbio)
1332
0
{
1333
0
    EVP_CIPHER_CTX *ctx;
1334
0
    unsigned char *tag = NULL;
1335
0
    int taglen, ok = 0;
1336
1337
0
    BIO_get_cipher_ctx(cmsbio, &ctx);
1338
1339
    /*
1340
     * The tag is set only for encryption. There is nothing to do for
1341
     * decryption.
1342
     */
1343
0
    if (!EVP_CIPHER_CTX_is_encrypting(ctx))
1344
0
        return 1;
1345
1346
0
    taglen = EVP_CIPHER_CTX_get_tag_length(ctx);
1347
0
    if (taglen <= 0
1348
0
        || (tag = OPENSSL_malloc(taglen)) == NULL
1349
0
        || EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen,
1350
0
               tag)
1351
0
            <= 0) {
1352
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_GET_TAG);
1353
0
        goto err;
1354
0
    }
1355
1356
0
    if (!ASN1_OCTET_STRING_set(cms->d.authEnvelopedData->mac, tag, taglen))
1357
0
        goto err;
1358
1359
0
    ok = 1;
1360
0
err:
1361
0
    OPENSSL_free(tag);
1362
0
    return ok;
1363
0
}
1364
1365
/*
1366
 * Get RecipientInfo type (if any) supported by a key (public or private). To
1367
 * retain compatibility with previous behaviour if the ctrl value isn't
1368
 * supported we assume key transport.
1369
 */
1370
int ossl_cms_pkey_get_ri_type(EVP_PKEY *pk)
1371
0
{
1372
0
    int ri_type;
1373
0
    EVP_PKEY_CTX *ctx = NULL;
1374
1375
    /*
1376
     * First check the provider for RecipientInfo support since a key may support
1377
     * multiple types, e.g. an RSA key and provider may support RSA key transport
1378
     * and/or RSA-KEM.
1379
     */
1380
0
    if (evp_pkey_is_provided(pk)
1381
0
        && EVP_PKEY_get_int_param(pk, OSSL_PKEY_PARAM_CMS_RI_TYPE, &ri_type))
1382
0
        return ri_type;
1383
1384
    /* Check types that we know about */
1385
0
    if (EVP_PKEY_is_a(pk, "DH"))
1386
0
        return CMS_RECIPINFO_AGREE;
1387
0
    else if (EVP_PKEY_is_a(pk, "DHX"))
1388
0
        return CMS_RECIPINFO_AGREE;
1389
0
    else if (EVP_PKEY_is_a(pk, "DSA"))
1390
0
        return CMS_RECIPINFO_NONE;
1391
0
    else if (EVP_PKEY_is_a(pk, "EC"))
1392
0
        return CMS_RECIPINFO_AGREE;
1393
0
    else if (EVP_PKEY_is_a(pk, "RSA"))
1394
0
        return CMS_RECIPINFO_TRANS;
1395
1396
    /*
1397
     * Otherwise this might be an engine implementation, so see if we can get
1398
     * the type from the ameth.
1399
     */
1400
0
    if (pk->ameth && pk->ameth->pkey_ctrl) {
1401
0
        int i, r;
1402
0
        i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_RI_TYPE, 0, &r);
1403
0
        if (i > 0)
1404
0
            return r;
1405
0
    }
1406
1407
    /*
1408
     * Otherwise try very hard to figure out what RecipientInfo the key supports.
1409
     */
1410
0
    ri_type = CMS_RECIPINFO_TRANS;
1411
0
    ctx = EVP_PKEY_CTX_new(pk, NULL);
1412
0
    if (ctx != NULL) {
1413
0
        ERR_set_mark();
1414
0
        if (EVP_PKEY_encrypt_init(ctx) > 0)
1415
0
            ri_type = CMS_RECIPINFO_TRANS;
1416
0
        else if (EVP_PKEY_derive_init(ctx) > 0)
1417
0
            ri_type = CMS_RECIPINFO_AGREE;
1418
0
        else if (EVP_PKEY_encapsulate_init(ctx, NULL) > 0)
1419
0
            ri_type = CMS_RECIPINFO_KEM;
1420
0
        ERR_pop_to_mark();
1421
0
    }
1422
0
    EVP_PKEY_CTX_free(ctx);
1423
1424
0
    return ri_type;
1425
0
}
1426
1427
int ossl_cms_pkey_is_ri_type_supported(EVP_PKEY *pk, int ri_type)
1428
0
{
1429
0
    int supportedRiType;
1430
1431
0
    if (pk->ameth != NULL && pk->ameth->pkey_ctrl != NULL) {
1432
0
        int i, r;
1433
1434
0
        i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_IS_RI_TYPE_SUPPORTED,
1435
0
            ri_type, &r);
1436
0
        if (i > 0)
1437
0
            return r;
1438
0
    }
1439
1440
0
    supportedRiType = ossl_cms_pkey_get_ri_type(pk);
1441
0
    if (supportedRiType < 0)
1442
0
        return 0;
1443
1444
0
    return (supportedRiType == ri_type);
1445
0
}
1446
1447
int ossl_cms_RecipientInfo_wrap_init(CMS_RecipientInfo *ri,
1448
    const EVP_CIPHER *cipher)
1449
0
{
1450
0
    const CMS_CTX *cms_ctx;
1451
0
    EVP_CIPHER_CTX *ctx;
1452
0
    const EVP_CIPHER *kekcipher;
1453
0
    EVP_CIPHER *fetched_kekcipher;
1454
0
    const char *kekcipher_name;
1455
0
    int keylen;
1456
0
    int ret;
1457
1458
0
    if (ri->type == CMS_RECIPINFO_AGREE) {
1459
0
        cms_ctx = ri->d.kari->cms_ctx;
1460
0
        ctx = ri->d.kari->ctx;
1461
0
    } else if (ri->type == CMS_RECIPINFO_KEM) {
1462
0
        cms_ctx = ri->d.ori->d.kemri->cms_ctx;
1463
0
        ctx = ri->d.ori->d.kemri->ctx;
1464
0
    } else {
1465
0
        ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE);
1466
0
        return 0;
1467
0
    }
1468
1469
    /* If a suitable wrap algorithm is already set nothing to do */
1470
0
    kekcipher = EVP_CIPHER_CTX_get0_cipher(ctx);
1471
0
    if (kekcipher != NULL) {
1472
0
        if (EVP_CIPHER_CTX_get_mode(ctx) != EVP_CIPH_WRAP_MODE)
1473
0
            return 0;
1474
0
        return 1;
1475
0
    }
1476
0
    if (cipher == NULL)
1477
0
        return 0;
1478
0
    keylen = EVP_CIPHER_get_key_length(cipher);
1479
0
    if (keylen <= 0) {
1480
0
        ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
1481
0
        return 0;
1482
0
    }
1483
0
    if ((EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_GET_WRAP_CIPHER) != 0) {
1484
0
        ret = EVP_CIPHER_meth_get_ctrl(cipher)(NULL, EVP_CTRL_GET_WRAP_CIPHER,
1485
0
            0, &kekcipher);
1486
0
        if (ret <= 0)
1487
0
            return 0;
1488
1489
0
        if (kekcipher != NULL) {
1490
0
            if (EVP_CIPHER_get_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
1491
0
                return 0;
1492
0
            kekcipher_name = EVP_CIPHER_get0_name(kekcipher);
1493
0
            goto enc;
1494
0
        }
1495
0
    }
1496
1497
    /*
1498
     * Pick a cipher based on content encryption cipher. If it is DES3 use
1499
     * DES3 wrap otherwise use AES wrap similar to key size.
1500
     */
1501
0
#ifndef OPENSSL_NO_DES
1502
0
    if (EVP_CIPHER_get_type(cipher) == NID_des_ede3_cbc)
1503
0
        kekcipher_name = SN_id_smime_alg_CMS3DESwrap;
1504
0
    else
1505
0
#endif
1506
0
        if (keylen <= 16)
1507
0
        kekcipher_name = SN_id_aes128_wrap;
1508
0
    else if (keylen <= 24)
1509
0
        kekcipher_name = SN_id_aes192_wrap;
1510
0
    else
1511
0
        kekcipher_name = SN_id_aes256_wrap;
1512
0
enc:
1513
0
    fetched_kekcipher = EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(cms_ctx),
1514
0
        kekcipher_name,
1515
0
        ossl_cms_ctx_get0_propq(cms_ctx));
1516
0
    if (fetched_kekcipher == NULL)
1517
0
        return 0;
1518
0
    ret = EVP_EncryptInit_ex(ctx, fetched_kekcipher, NULL, NULL, NULL);
1519
0
    EVP_CIPHER_free(fetched_kekcipher);
1520
0
    return ret;
1521
0
}