Coverage Report

Created: 2026-09-12 06:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl41/crypto/cms/cms_env.c
Line
Count
Source
1
/*
2
 * Copyright 2008-2026 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
4.23k
#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
5.50k
{
38
5.50k
    int nid = OBJ_obj2nid(cms->contentType);
39
40
5.50k
    switch (nid) {
41
2.11k
    case NID_pkcs7_enveloped:
42
2.11k
        return CMS_ENVELOPED_STANDARD;
43
44
0
    case NID_id_smime_ct_authEnvelopedData:
45
0
        return CMS_ENVELOPED_AUTH;
46
47
3.38k
    default:
48
3.38k
        return 0;
49
5.50k
    }
50
5.50k
}
51
52
static int cms_get_enveloped_type(const CMS_ContentInfo *cms)
53
5.50k
{
54
5.50k
    int ret = cms_get_enveloped_type_simple(cms);
55
56
5.50k
    if (ret == 0)
57
5.50k
        ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA);
58
5.50k
    return ret;
59
5.50k
}
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
5.50k
{
180
5.50k
    switch (cms_get_enveloped_type(cms)) {
181
2.11k
    case CMS_ENVELOPED_STANDARD:
182
2.11k
        return cms->d.envelopedData->recipientInfos;
183
184
0
    case CMS_ENVELOPED_AUTH:
185
0
        return cms->d.authEnvelopedData->recipientInfos;
186
187
3.38k
    default:
188
3.38k
        return NULL;
189
5.50k
    }
190
5.50k
}
191
192
void ossl_cms_RecipientInfos_set_cmsctx(CMS_ContentInfo *cms)
193
3.29k
{
194
3.29k
    int i;
195
3.29k
    CMS_RecipientInfo *ri;
196
3.29k
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
197
3.29k
    STACK_OF(CMS_RecipientInfo) *rinfos = CMS_get0_RecipientInfos(cms);
198
199
8.71k
    for (i = 0; i < sk_CMS_RecipientInfo_num(rinfos); i++) {
200
5.42k
        ri = sk_CMS_RecipientInfo_value(rinfos, i);
201
5.42k
        if (ri != NULL) {
202
5.42k
            switch (ri->type) {
203
1.69k
            case CMS_RECIPINFO_AGREE:
204
1.69k
                ri->d.kari->cms_ctx = ctx;
205
1.69k
                break;
206
971
            case CMS_RECIPINFO_TRANS:
207
971
                ri->d.ktri->cms_ctx = ctx;
208
971
                ossl_x509_set0_libctx(ri->d.ktri->recip,
209
971
                    ossl_cms_ctx_get0_libctx(ctx),
210
971
                    ossl_cms_ctx_get0_propq(ctx));
211
971
                break;
212
186
            case CMS_RECIPINFO_KEK:
213
186
                ri->d.kekri->cms_ctx = ctx;
214
186
                break;
215
2.03k
            case CMS_RECIPINFO_PASS:
216
2.03k
                ri->d.pwri->cms_ctx = ctx;
217
2.03k
                break;
218
0
            case CMS_RECIPINFO_KEM:
219
0
                ri->d.ori->d.kemri->cms_ctx = ctx;
220
0
                break;
221
532
            default:
222
532
                break;
223
5.42k
            }
224
5.42k
        }
225
5.42k
    }
226
3.29k
}
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
0
    size_t secret_len = 0;
282
283
0
    if (env == NULL) {
284
0
        ERR_raise(ERR_LIB_CMS, ERR_R_PASSED_NULL_PARAMETER);
285
0
        return NULL;
286
0
    }
287
288
0
    if (secret != NULL
289
0
        && (secret_len = ASN1_STRING_get_length(secret)) > INT_MAX)
290
0
        return NULL;
291
292
0
    if ((ci = CMS_ContentInfo_new_ex(libctx, propq)) == NULL
293
0
        || (bio = BIO_new(BIO_s_mem())) == NULL)
294
0
        goto end;
295
0
    ci->contentType = OBJ_nid2obj(NID_pkcs7_enveloped);
296
0
    ci->d.envelopedData = env;
297
0
    if (secret != NULL
298
0
        && CMS_decrypt_set1_password(ci, (unsigned char *)ASN1_STRING_get0_data(secret),
299
0
               (int)secret_len)
300
0
            != 1)
301
0
        goto end;
302
0
    res = CMS_decrypt(ci, secret == NULL ? pkey : NULL,
303
0
        secret == NULL ? cert : NULL, detached_data, bio, flags);
304
305
0
end:
306
0
    if (ci != NULL) {
307
0
        ci->d.envelopedData = NULL; /* do not indirectly free |env| */
308
0
        ci->contentType = NULL;
309
0
    }
310
0
    CMS_ContentInfo_free(ci);
311
0
    if (!res) {
312
0
        BIO_free(bio);
313
0
        bio = NULL;
314
0
    }
315
0
    return bio;
316
0
}
317
318
CMS_ContentInfo *
319
CMS_AuthEnvelopedData_create_ex(const EVP_CIPHER *cipher, OSSL_LIB_CTX *libctx,
320
    const char *propq)
321
0
{
322
0
    CMS_ContentInfo *cms;
323
0
    CMS_AuthEnvelopedData *aenv;
324
325
0
    cms = CMS_ContentInfo_new_ex(libctx, propq);
326
0
    if (cms == NULL)
327
0
        goto merr;
328
0
    aenv = cms_auth_enveloped_data_init(cms);
329
0
    if (aenv == NULL)
330
0
        goto merr;
331
0
    if (!ossl_cms_EncryptedContent_init(aenv->authEncryptedContentInfo,
332
0
            cipher, NULL, 0,
333
0
            ossl_cms_get0_cmsctx(cms)))
334
0
        goto merr;
335
0
    return cms;
336
0
merr:
337
0
    CMS_ContentInfo_free(cms);
338
0
    ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB);
339
0
    return NULL;
340
0
}
341
342
CMS_ContentInfo *CMS_AuthEnvelopedData_create(const EVP_CIPHER *cipher)
343
0
{
344
0
    return CMS_AuthEnvelopedData_create_ex(cipher, NULL, NULL);
345
0
}
346
347
/* Key Transport Recipient Info (KTRI) routines */
348
349
/* Initialise a ktri based on passed certificate and key */
350
351
static int cms_RecipientInfo_ktri_init(CMS_RecipientInfo *ri, X509 *recip,
352
    EVP_PKEY *pk, unsigned int flags,
353
    const CMS_CTX *ctx)
354
0
{
355
0
    CMS_KeyTransRecipientInfo *ktri;
356
0
    int idtype;
357
358
0
    ri->d.ktri = M_ASN1_new_of(CMS_KeyTransRecipientInfo);
359
0
    if (!ri->d.ktri)
360
0
        return 0;
361
0
    ri->encoded_type = ri->type = CMS_RECIPINFO_TRANS;
362
363
0
    ktri = ri->d.ktri;
364
0
    ktri->cms_ctx = ctx;
365
366
0
    if (flags & CMS_USE_KEYID) {
367
0
        ktri->version = 2;
368
0
        idtype = CMS_RECIPINFO_KEYIDENTIFIER;
369
0
    } else {
370
0
        ktri->version = 0;
371
0
        idtype = CMS_RECIPINFO_ISSUER_SERIAL;
372
0
    }
373
374
    /*
375
     * Not a typo: RecipientIdentifier and SignerIdentifier are the same
376
     * structure.
377
     */
378
379
0
    if (!ossl_cms_set1_SignerIdentifier(ktri->rid, recip, idtype, ctx))
380
0
        return 0;
381
382
0
    if (!X509_up_ref(recip))
383
0
        return 0;
384
0
    if (!EVP_PKEY_up_ref(pk)) {
385
0
        X509_free(recip);
386
0
        return 0;
387
0
    }
388
389
0
    ktri->pkey = pk;
390
0
    ktri->recip = recip;
391
392
0
    if (flags & CMS_KEY_PARAM) {
393
0
        ktri->pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
394
0
            ktri->pkey,
395
0
            ossl_cms_ctx_get0_propq(ctx));
396
0
        if (ktri->pctx == NULL)
397
0
            return 0;
398
0
        if (EVP_PKEY_encrypt_init(ktri->pctx) <= 0)
399
0
            return 0;
400
0
    } else if (!ossl_cms_env_asn1_ctrl(ri, 0))
401
0
        return 0;
402
0
    return 1;
403
0
}
404
405
/*
406
 * Add a recipient certificate using appropriate type of RecipientInfo
407
 */
408
409
CMS_RecipientInfo *CMS_add1_recipient(CMS_ContentInfo *cms, X509 *recip,
410
    EVP_PKEY *originatorPrivKey,
411
    X509 *originator, unsigned int flags)
412
0
{
413
0
    CMS_RecipientInfo *ri = NULL;
414
0
    STACK_OF(CMS_RecipientInfo) *ris;
415
0
    EVP_PKEY *pk = NULL;
416
0
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
417
418
0
    ris = CMS_get0_RecipientInfos(cms);
419
0
    if (ris == NULL)
420
0
        goto err;
421
422
    /* Initialize recipient info */
423
0
    ri = M_ASN1_new_of(CMS_RecipientInfo);
424
0
    if (ri == NULL) {
425
0
        ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
426
0
        goto err;
427
0
    }
428
429
0
    pk = X509_get0_pubkey(recip);
430
0
    if (pk == NULL) {
431
0
        ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_GETTING_PUBLIC_KEY);
432
0
        goto err;
433
0
    }
434
435
0
    switch (ossl_cms_pkey_get_ri_type(pk)) {
436
437
0
    case CMS_RECIPINFO_TRANS:
438
0
        if (!cms_RecipientInfo_ktri_init(ri, recip, pk, flags, ctx))
439
0
            goto err;
440
0
        break;
441
442
0
    case CMS_RECIPINFO_AGREE:
443
0
        if (!ossl_cms_RecipientInfo_kari_init(ri, recip, pk, originator,
444
0
                originatorPrivKey, flags, ctx))
445
0
            goto err;
446
0
        break;
447
448
0
    case CMS_RECIPINFO_KEM:
449
0
        if (!ossl_cms_RecipientInfo_kemri_init(ri, recip, pk, flags, ctx))
450
0
            goto err;
451
0
        break;
452
453
0
    default:
454
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE);
455
0
        goto err;
456
0
    }
457
458
0
    if (!sk_CMS_RecipientInfo_push(ris, ri)) {
459
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
460
0
        goto err;
461
0
    }
462
463
0
    return ri;
464
465
0
err:
466
0
    M_ASN1_free_of(ri, CMS_RecipientInfo);
467
0
    return NULL;
468
0
}
469
470
CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms, X509 *recip,
471
    unsigned int flags)
472
0
{
473
0
    return CMS_add1_recipient(cms, recip, NULL, NULL, flags);
474
0
}
475
476
int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri,
477
    EVP_PKEY **pk, X509 **recip,
478
    X509_ALGOR **palg)
479
0
{
480
0
    CMS_KeyTransRecipientInfo *ktri;
481
0
    if (ri->type != CMS_RECIPINFO_TRANS) {
482
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
483
0
        return 0;
484
0
    }
485
486
0
    ktri = ri->d.ktri;
487
488
0
    if (pk)
489
0
        *pk = ktri->pkey;
490
0
    if (recip)
491
0
        *recip = ktri->recip;
492
0
    if (palg)
493
0
        *palg = ktri->keyEncryptionAlgorithm;
494
0
    return 1;
495
0
}
496
497
int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri,
498
    ASN1_OCTET_STRING **keyid,
499
    X509_NAME **issuer,
500
    ASN1_INTEGER **sno)
501
0
{
502
0
    CMS_KeyTransRecipientInfo *ktri;
503
0
    if (ri->type != CMS_RECIPINFO_TRANS) {
504
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
505
0
        return 0;
506
0
    }
507
0
    ktri = ri->d.ktri;
508
509
0
    return ossl_cms_SignerIdentifier_get0_signer_id(ktri->rid, keyid, issuer,
510
0
        sno);
511
0
}
512
513
int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert)
514
0
{
515
0
    if (ri->type != CMS_RECIPINFO_TRANS) {
516
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
517
0
        return -2;
518
0
    }
519
0
    return ossl_cms_SignerIdentifier_cert_cmp(ri->d.ktri->rid, cert);
520
0
}
521
522
int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey)
523
0
{
524
0
    if (ri->type != CMS_RECIPINFO_TRANS) {
525
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
526
0
        return 0;
527
0
    }
528
0
    EVP_PKEY_free(ri->d.ktri->pkey);
529
0
    ri->d.ktri->pkey = pkey;
530
0
    return 1;
531
0
}
532
533
/* Encrypt content key in key transport recipient info */
534
535
static int cms_RecipientInfo_ktri_encrypt(const CMS_ContentInfo *cms,
536
    CMS_RecipientInfo *ri)
537
0
{
538
0
    CMS_KeyTransRecipientInfo *ktri;
539
0
    CMS_EncryptedContentInfo *ec;
540
0
    EVP_PKEY_CTX *pctx;
541
0
    unsigned char *ek = NULL;
542
0
    size_t eklen;
543
0
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
544
545
0
    int ret = 0;
546
547
0
    if (ri->type != CMS_RECIPINFO_TRANS) {
548
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_TRANSPORT);
549
0
        return 0;
550
0
    }
551
0
    ktri = ri->d.ktri;
552
0
    ec = ossl_cms_get0_env_enc_content(cms);
553
554
0
    pctx = ktri->pctx;
555
556
0
    if (pctx) {
557
0
        if (!ossl_cms_env_asn1_ctrl(ri, 0))
558
0
            goto err;
559
0
    } else {
560
0
        pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
561
0
            ktri->pkey,
562
0
            ossl_cms_ctx_get0_propq(ctx));
563
0
        if (pctx == NULL)
564
0
            return 0;
565
566
0
        if (EVP_PKEY_encrypt_init(pctx) <= 0)
567
0
            goto err;
568
0
    }
569
570
0
    if (EVP_PKEY_encrypt(pctx, NULL, &eklen, ec->key, ec->keylen) <= 0)
571
0
        goto err;
572
573
0
    ek = OPENSSL_malloc(eklen);
574
0
    if (ek == NULL)
575
0
        goto err;
576
577
0
    if (EVP_PKEY_encrypt(pctx, ek, &eklen, ec->key, ec->keylen) <= 0)
578
0
        goto err;
579
580
0
    ASN1_STRING_set0(ktri->encryptedKey, ek, (int)eklen);
581
0
    ek = NULL;
582
583
0
    ret = 1;
584
585
0
err:
586
0
    EVP_PKEY_CTX_free(pctx);
587
0
    ktri->pctx = NULL;
588
0
    OPENSSL_free(ek);
589
0
    return ret;
590
0
}
591
592
/* Decrypt content key from KTRI */
593
594
static int cms_RecipientInfo_ktri_decrypt(CMS_ContentInfo *cms,
595
    CMS_RecipientInfo *ri)
596
0
{
597
0
    CMS_KeyTransRecipientInfo *ktri = ri->d.ktri;
598
0
    EVP_PKEY *pkey = ktri->pkey;
599
0
    unsigned char *ek = NULL;
600
0
    size_t eklen;
601
0
    int ret = 0;
602
0
    size_t fixlen = 0;
603
0
    const EVP_CIPHER *cipher = NULL;
604
0
    EVP_CIPHER *fetched_cipher = NULL;
605
0
    CMS_EncryptedContentInfo *ec;
606
0
    const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms);
607
0
    OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx);
608
0
    const char *propq = ossl_cms_ctx_get0_propq(ctx);
609
610
0
    ec = ossl_cms_get0_env_enc_content(cms);
611
612
0
    if (ktri->pkey == NULL) {
613
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_PRIVATE_KEY);
614
0
        return 0;
615
0
    }
616
617
0
    if (cms->d.envelopedData->encryptedContentInfo->havenocert
618
0
        && !cms->d.envelopedData->encryptedContentInfo->debug) {
619
0
        X509_ALGOR *calg = ec->contentEncryptionAlgorithm;
620
0
        char name[OSSL_MAX_NAME_SIZE];
621
622
0
        OBJ_obj2txt(name, sizeof(name), calg->algorithm, 0);
623
624
0
        (void)ERR_set_mark();
625
0
        fetched_cipher = EVP_CIPHER_fetch(libctx, name, propq);
626
627
0
        if (fetched_cipher != NULL)
628
0
            cipher = fetched_cipher;
629
0
        else
630
0
            cipher = EVP_get_cipherbyobj(calg->algorithm);
631
0
        if (cipher == NULL) {
632
0
            (void)ERR_clear_last_mark();
633
0
            ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_CIPHER);
634
0
            return 0;
635
0
        }
636
0
        (void)ERR_pop_to_mark();
637
638
0
        fixlen = EVP_CIPHER_get_key_length(cipher);
639
0
        EVP_CIPHER_free(fetched_cipher);
640
0
    }
641
642
0
    ktri->pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq);
643
0
    if (ktri->pctx == NULL)
644
0
        goto err;
645
646
0
    if (EVP_PKEY_decrypt_init(ktri->pctx) <= 0)
647
0
        goto err;
648
649
0
    if (!ossl_cms_env_asn1_ctrl(ri, 1))
650
0
        goto err;
651
652
0
    if (evp_pkey_decrypt_alloc(ktri->pctx, &ek, &eklen, fixlen,
653
0
            ktri->encryptedKey->data,
654
0
            ktri->encryptedKey->length)
655
0
        <= 0)
656
0
        goto err;
657
658
0
    ret = 1;
659
660
0
    OPENSSL_clear_free(ec->key, ec->keylen);
661
0
    ec->key = ek;
662
0
    ec->keylen = eklen;
663
664
0
err:
665
0
    EVP_PKEY_CTX_free(ktri->pctx);
666
0
    ktri->pctx = NULL;
667
0
    if (!ret)
668
0
        OPENSSL_free(ek);
669
670
0
    return ret;
671
0
}
672
673
/* Key Encrypted Key (KEK) RecipientInfo routines */
674
675
int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri,
676
    const unsigned char *id, size_t idlen)
677
0
{
678
0
    ASN1_OCTET_STRING tmp_os;
679
0
    CMS_KEKRecipientInfo *kekri;
680
0
    if (ri->type != CMS_RECIPINFO_KEK) {
681
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
682
0
        return -2;
683
0
    }
684
0
    kekri = ri->d.kekri;
685
0
    tmp_os.type = V_ASN1_OCTET_STRING;
686
0
    tmp_os.flags = 0;
687
0
    tmp_os.data = (unsigned char *)id;
688
0
    tmp_os.length = (int)idlen;
689
0
    return ASN1_OCTET_STRING_cmp(&tmp_os, kekri->kekid->keyIdentifier);
690
0
}
691
692
/* For now hard code AES key wrap info */
693
694
static size_t aes_wrap_keylen(int nid)
695
0
{
696
0
    switch (nid) {
697
0
    case NID_id_aes128_wrap:
698
0
        return 16;
699
700
0
    case NID_id_aes192_wrap:
701
0
        return 24;
702
703
0
    case NID_id_aes256_wrap:
704
0
        return 32;
705
706
0
    default:
707
0
        return 0;
708
0
    }
709
0
}
710
711
CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid,
712
    unsigned char *key, size_t keylen,
713
    unsigned char *id, size_t idlen,
714
    ASN1_GENERALIZEDTIME *date,
715
    ASN1_OBJECT *otherTypeId,
716
    ASN1_TYPE *otherType)
717
0
{
718
0
    CMS_RecipientInfo *ri = NULL;
719
0
    CMS_KEKRecipientInfo *kekri;
720
0
    STACK_OF(CMS_RecipientInfo) *ris = CMS_get0_RecipientInfos(cms);
721
722
0
    if (ris == NULL || idlen > INT_MAX)
723
0
        goto err;
724
725
0
    if (nid == NID_undef) {
726
0
        switch (keylen) {
727
0
        case 16:
728
0
            nid = NID_id_aes128_wrap;
729
0
            break;
730
731
0
        case 24:
732
0
            nid = NID_id_aes192_wrap;
733
0
            break;
734
735
0
        case 32:
736
0
            nid = NID_id_aes256_wrap;
737
0
            break;
738
739
0
        default:
740
0
            ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
741
0
            goto err;
742
0
        }
743
744
0
    } else {
745
746
0
        size_t exp_keylen = aes_wrap_keylen(nid);
747
748
0
        if (!exp_keylen) {
749
0
            ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEK_ALGORITHM);
750
0
            goto err;
751
0
        }
752
753
0
        if (keylen != exp_keylen) {
754
0
            ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
755
0
            goto err;
756
0
        }
757
0
    }
758
759
    /* Initialize recipient info */
760
0
    ri = M_ASN1_new_of(CMS_RecipientInfo);
761
0
    if (!ri) {
762
0
        ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
763
0
        goto err;
764
0
    }
765
766
0
    ri->d.kekri = M_ASN1_new_of(CMS_KEKRecipientInfo);
767
0
    if (!ri->d.kekri) {
768
0
        ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
769
0
        goto err;
770
0
    }
771
0
    ri->encoded_type = ri->type = CMS_RECIPINFO_KEK;
772
773
0
    kekri = ri->d.kekri;
774
775
0
    if (otherTypeId) {
776
0
        kekri->kekid->other = M_ASN1_new_of(CMS_OtherKeyAttribute);
777
0
        if (kekri->kekid->other == NULL) {
778
0
            ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
779
0
            goto err;
780
0
        }
781
0
    }
782
783
0
    if (!sk_CMS_RecipientInfo_push(ris, ri)) {
784
0
        ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
785
0
        goto err;
786
0
    }
787
788
    /* After this point no calls can fail */
789
790
0
    kekri->version = 4;
791
792
0
    kekri->key = key;
793
0
    kekri->keylen = keylen;
794
795
0
    ASN1_STRING_set0(kekri->kekid->keyIdentifier, id, (int)idlen);
796
797
0
    kekri->kekid->date = date;
798
799
0
    if (kekri->kekid->other) {
800
0
        kekri->kekid->other->keyAttrId = otherTypeId;
801
0
        kekri->kekid->other->keyAttr = otherType;
802
0
    }
803
804
0
    (void)X509_ALGOR_set0(kekri->keyEncryptionAlgorithm, OBJ_nid2obj(nid),
805
0
        V_ASN1_UNDEF, NULL); /* cannot fail */
806
807
0
    return ri;
808
809
0
err:
810
0
    M_ASN1_free_of(ri, CMS_RecipientInfo);
811
0
    return NULL;
812
0
}
813
814
int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri,
815
    X509_ALGOR **palg,
816
    ASN1_OCTET_STRING **pid,
817
    ASN1_GENERALIZEDTIME **pdate,
818
    ASN1_OBJECT **potherid,
819
    ASN1_TYPE **pothertype)
820
0
{
821
0
    CMS_KEKIdentifier *rkid;
822
0
    if (ri->type != CMS_RECIPINFO_KEK) {
823
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
824
0
        return 0;
825
0
    }
826
0
    rkid = ri->d.kekri->kekid;
827
0
    if (palg)
828
0
        *palg = ri->d.kekri->keyEncryptionAlgorithm;
829
0
    if (pid)
830
0
        *pid = rkid->keyIdentifier;
831
0
    if (pdate)
832
0
        *pdate = rkid->date;
833
0
    if (potherid) {
834
0
        if (rkid->other)
835
0
            *potherid = rkid->other->keyAttrId;
836
0
        else
837
0
            *potherid = NULL;
838
0
    }
839
0
    if (pothertype) {
840
0
        if (rkid->other)
841
0
            *pothertype = rkid->other->keyAttr;
842
0
        else
843
0
            *pothertype = NULL;
844
0
    }
845
0
    return 1;
846
0
}
847
848
int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri,
849
    unsigned char *key, size_t keylen)
850
0
{
851
0
    CMS_KEKRecipientInfo *kekri;
852
0
    if (ri->type != CMS_RECIPINFO_KEK) {
853
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEK);
854
0
        return 0;
855
0
    }
856
857
0
    kekri = ri->d.kekri;
858
0
    kekri->key = key;
859
0
    kekri->keylen = keylen;
860
0
    return 1;
861
0
}
862
863
static EVP_CIPHER *cms_get_key_wrap_cipher(size_t keylen, const CMS_CTX *ctx)
864
0
{
865
0
    const char *alg = NULL;
866
867
0
    switch (keylen) {
868
0
    case 16:
869
0
        alg = "AES-128-WRAP";
870
0
        break;
871
0
    case 24:
872
0
        alg = "AES-192-WRAP";
873
0
        break;
874
0
    case 32:
875
0
        alg = "AES-256-WRAP";
876
0
        break;
877
0
    default:
878
0
        return NULL;
879
0
    }
880
0
    return EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(ctx), alg,
881
0
        ossl_cms_ctx_get0_propq(ctx));
882
0
}
883
884
/* Encrypt content key in KEK recipient info */
885
886
static int cms_RecipientInfo_kekri_encrypt(const CMS_ContentInfo *cms,
887
    CMS_RecipientInfo *ri)
888
0
{
889
0
    CMS_EncryptedContentInfo *ec;
890
0
    CMS_KEKRecipientInfo *kekri;
891
0
    unsigned char *wkey = NULL;
892
0
    int wkeylen;
893
0
    int r = 0;
894
0
    EVP_CIPHER *cipher = NULL;
895
0
    int outlen = 0;
896
0
    EVP_CIPHER_CTX *ctx = NULL;
897
0
    const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
898
899
0
    ec = ossl_cms_get0_env_enc_content(cms);
900
0
    if (ec == NULL)
901
0
        return 0;
902
903
0
    kekri = ri->d.kekri;
904
905
0
    if (kekri->key == NULL) {
906
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY);
907
0
        return 0;
908
0
    }
909
910
0
    cipher = cms_get_key_wrap_cipher(kekri->keylen, cms_ctx);
911
0
    if (cipher == NULL) {
912
0
        ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
913
0
        goto err;
914
0
    }
915
916
    /* 8 byte prefix for AES wrap ciphers */
917
0
    wkey = OPENSSL_malloc(ec->keylen + 8);
918
0
    if (wkey == NULL)
919
0
        goto err;
920
921
0
    ctx = EVP_CIPHER_CTX_new();
922
0
    if (ctx == NULL) {
923
0
        ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB);
924
0
        goto err;
925
0
    }
926
927
0
    EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
928
0
    if (!EVP_EncryptInit_ex(ctx, cipher, NULL, kekri->key, NULL)
929
0
        || !EVP_EncryptUpdate(ctx, wkey, &wkeylen, ec->key, (int)ec->keylen)
930
0
        || !EVP_EncryptFinal_ex(ctx, wkey + wkeylen, &outlen)) {
931
0
        ERR_raise(ERR_LIB_CMS, CMS_R_WRAP_ERROR);
932
0
        goto err;
933
0
    }
934
0
    wkeylen += outlen;
935
0
    if (!ossl_assert((size_t)wkeylen == ec->keylen + 8)) {
936
0
        ERR_raise(ERR_LIB_CMS, CMS_R_WRAP_ERROR);
937
0
        goto err;
938
0
    }
939
940
0
    ASN1_STRING_set0(kekri->encryptedKey, wkey, wkeylen);
941
942
0
    r = 1;
943
944
0
err:
945
0
    EVP_CIPHER_free(cipher);
946
0
    if (!r)
947
0
        OPENSSL_free(wkey);
948
0
    EVP_CIPHER_CTX_free(ctx);
949
950
0
    return r;
951
0
}
952
953
/* Decrypt content key in KEK recipient info */
954
955
static int cms_RecipientInfo_kekri_decrypt(CMS_ContentInfo *cms,
956
    CMS_RecipientInfo *ri)
957
0
{
958
0
    CMS_EncryptedContentInfo *ec;
959
0
    CMS_KEKRecipientInfo *kekri;
960
0
    unsigned char *ukey = NULL;
961
0
    size_t ukey_alloc_len = 0;
962
0
    int ukeylen;
963
0
    int r = 0, wrap_nid;
964
0
    EVP_CIPHER *cipher = NULL;
965
0
    int outlen = 0;
966
0
    EVP_CIPHER_CTX *ctx = NULL;
967
0
    const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms);
968
969
0
    ec = ossl_cms_get0_env_enc_content(cms);
970
0
    if (ec == NULL)
971
0
        return 0;
972
973
0
    kekri = ri->d.kekri;
974
975
0
    if (!kekri->key) {
976
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY);
977
0
        return 0;
978
0
    }
979
980
0
    wrap_nid = OBJ_obj2nid(kekri->keyEncryptionAlgorithm->algorithm);
981
0
    if (aes_wrap_keylen(wrap_nid) != kekri->keylen) {
982
0
        ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
983
0
        return 0;
984
0
    }
985
986
    /* If encrypted key length is invalid don't bother */
987
988
0
    if (kekri->encryptedKey->length < 16) {
989
0
        ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_ENCRYPTED_KEY_LENGTH);
990
0
        goto err;
991
0
    }
992
993
0
    cipher = cms_get_key_wrap_cipher(kekri->keylen, cms_ctx);
994
0
    if (cipher == NULL) {
995
0
        ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
996
0
        goto err;
997
0
    }
998
999
0
    ukey_alloc_len = (size_t)kekri->encryptedKey->length - 8;
1000
0
    ukey = OPENSSL_malloc(ukey_alloc_len);
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_clear_free(ukey, ukey_alloc_len);
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
/* The DER encoding of authAttrs, with the universal SET OF tag, is the AAD */
1247
static int cms_AuthEnvelopedData_set_aad(BIO *b,
1248
    STACK_OF(X509_ATTRIBUTE) *authAttrs)
1249
0
{
1250
0
    EVP_CIPHER_CTX *ctx;
1251
0
    unsigned char *aad = NULL;
1252
0
    int aadlen, outl, ok = 0;
1253
0
    const ASN1_ITEM *item;
1254
1255
0
    if (!BIO_get_cipher_ctx(b, &ctx))
1256
0
        return 0;
1257
0
    item = EVP_CIPHER_CTX_is_encrypting(ctx)
1258
0
        ? ASN1_ITEM_rptr(CMS_Attributes_AadEncrypt)
1259
0
        : ASN1_ITEM_rptr(CMS_Attributes_AadDecrypt);
1260
0
    aadlen = ASN1_item_i2d((ASN1_VALUE *)authAttrs, &aad, item);
1261
0
    if (aadlen <= 0 || aad == NULL) {
1262
0
        ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB);
1263
0
        goto err;
1264
0
    }
1265
0
    if (EVP_CipherUpdate(ctx, NULL, &outl, aad, aadlen) <= 0) {
1266
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE);
1267
0
        goto err;
1268
0
    }
1269
0
    ok = 1;
1270
0
err:
1271
0
    OPENSSL_free(aad);
1272
0
    return ok;
1273
0
}
1274
1275
BIO *ossl_cms_AuthEnvelopedData_init_bio(CMS_ContentInfo *cms)
1276
0
{
1277
0
    CMS_EncryptedContentInfo *ec;
1278
0
    STACK_OF(CMS_RecipientInfo) *rinfos;
1279
0
    int ok = 0;
1280
0
    BIO *ret;
1281
0
    CMS_AuthEnvelopedData *aenv = cms->d.authEnvelopedData;
1282
1283
    /* Get BIO first to set up key */
1284
0
    ec = aenv->authEncryptedContentInfo;
1285
    /* Set tag for decryption */
1286
0
    if (ec->cipher == NULL) {
1287
0
        ec->tag = aenv->mac->data;
1288
0
        ec->taglen = aenv->mac->length;
1289
0
    }
1290
0
    ret = ossl_cms_EncryptedContent_init_bio(ec, ossl_cms_get0_cmsctx(cms), 1);
1291
0
    if (ret == NULL)
1292
0
        return NULL;
1293
1294
    /* authAttrs, if present, are the AEAD associated data */
1295
0
    if (aenv->authAttrs != NULL
1296
0
        && !cms_AuthEnvelopedData_set_aad(ret, aenv->authAttrs))
1297
0
        goto err;
1298
1299
    /* If no cipher end of processing */
1300
0
    if (ec->cipher == NULL)
1301
0
        return ret;
1302
1303
    /* Now encrypt content key according to each RecipientInfo type */
1304
0
    rinfos = aenv->recipientInfos;
1305
0
    if (cms_env_encrypt_content_key(cms, rinfos) < 0) {
1306
0
        ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_SETTING_RECIPIENTINFO);
1307
0
        goto err;
1308
0
    }
1309
1310
    /* And finally set the version */
1311
0
    aenv->version = 0;
1312
1313
0
    ok = 1;
1314
1315
0
err:
1316
0
    cms_env_clear_ec(ec);
1317
0
    if (ok)
1318
0
        return ret;
1319
0
    BIO_free(ret);
1320
0
    return NULL;
1321
0
}
1322
1323
int ossl_cms_EnvelopedData_final(CMS_ContentInfo *cms, BIO *chain)
1324
0
{
1325
0
    CMS_EnvelopedData *env = NULL;
1326
0
    EVP_CIPHER_CTX *ctx = NULL;
1327
0
    BIO *mbio = BIO_find_type(chain, BIO_TYPE_CIPHER);
1328
1329
0
    env = ossl_cms_get0_enveloped(cms);
1330
0
    if (env == NULL)
1331
0
        return 0;
1332
1333
0
    if (mbio == NULL) {
1334
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_NOT_FOUND);
1335
0
        return 0;
1336
0
    }
1337
1338
0
    BIO_get_cipher_ctx(mbio, &ctx);
1339
1340
    /*
1341
     * If the selected cipher supports unprotected attributes,
1342
     * deal with it using special ctrl function
1343
     */
1344
0
    if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx))
1345
0
            & EVP_CIPH_FLAG_CIPHER_WITH_MAC)
1346
0
        != 0) {
1347
0
        if (env->unprotectedAttrs == NULL)
1348
0
            env->unprotectedAttrs = sk_X509_ATTRIBUTE_new_null();
1349
1350
0
        if (env->unprotectedAttrs == NULL) {
1351
0
            ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB);
1352
0
            return 0;
1353
0
        }
1354
1355
0
        if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_PROCESS_UNPROTECTED,
1356
0
                1, env->unprotectedAttrs)
1357
0
            <= 0) {
1358
0
            ERR_raise(ERR_LIB_CMS, CMS_R_CTRL_FAILURE);
1359
0
            return 0;
1360
0
        }
1361
0
    }
1362
1363
0
    cms_env_set_version(cms->d.envelopedData);
1364
0
    return 1;
1365
0
}
1366
1367
int ossl_cms_AuthEnvelopedData_final(CMS_ContentInfo *cms, BIO *cmsbio)
1368
0
{
1369
0
    EVP_CIPHER_CTX *ctx;
1370
0
    unsigned char *tag = NULL;
1371
0
    int taglen, ok = 0;
1372
1373
0
    BIO_get_cipher_ctx(cmsbio, &ctx);
1374
1375
    /*
1376
     * The tag is set only for encryption. There is nothing to do for
1377
     * decryption.
1378
     */
1379
0
    if (!EVP_CIPHER_CTX_is_encrypting(ctx))
1380
0
        return 1;
1381
1382
0
    taglen = EVP_CIPHER_CTX_get_tag_length(ctx);
1383
0
    if (taglen <= 0
1384
0
        || (tag = OPENSSL_malloc(taglen)) == NULL
1385
0
        || EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, taglen,
1386
0
               tag)
1387
0
            <= 0) {
1388
0
        ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_GET_TAG);
1389
0
        goto err;
1390
0
    }
1391
1392
0
    if (!ASN1_OCTET_STRING_set(cms->d.authEnvelopedData->mac, tag, taglen))
1393
0
        goto err;
1394
1395
0
    ok = 1;
1396
0
err:
1397
0
    OPENSSL_free(tag);
1398
0
    return ok;
1399
0
}
1400
1401
/*
1402
 * Get RecipientInfo type (if any) supported by a key (public or private). To
1403
 * retain compatibility with previous behaviour if the ctrl value isn't
1404
 * supported we assume key transport.
1405
 */
1406
int ossl_cms_pkey_get_ri_type(EVP_PKEY *pk)
1407
0
{
1408
0
    int ri_type;
1409
0
    EVP_PKEY_CTX *ctx = NULL;
1410
1411
    /*
1412
     * First check the provider for RecipientInfo support since a key may support
1413
     * multiple types, e.g. an RSA key and provider may support RSA key transport
1414
     * and/or RSA-KEM.
1415
     */
1416
0
    if (evp_pkey_is_provided(pk)
1417
0
        && EVP_PKEY_get_int_param(pk, OSSL_PKEY_PARAM_CMS_RI_TYPE, &ri_type))
1418
0
        return ri_type;
1419
1420
    /* Check types that we know about */
1421
0
    if (EVP_PKEY_is_a(pk, "DH"))
1422
0
        return CMS_RECIPINFO_AGREE;
1423
0
    else if (EVP_PKEY_is_a(pk, "DHX"))
1424
0
        return CMS_RECIPINFO_AGREE;
1425
0
    else if (EVP_PKEY_is_a(pk, "DSA"))
1426
0
        return CMS_RECIPINFO_NONE;
1427
0
    else if (EVP_PKEY_is_a(pk, "EC"))
1428
0
        return CMS_RECIPINFO_AGREE;
1429
0
    else if (EVP_PKEY_is_a(pk, "RSA"))
1430
0
        return CMS_RECIPINFO_TRANS;
1431
1432
    /*
1433
     * Otherwise this might be an engine implementation, so see if we can get
1434
     * the type from the ameth.
1435
     */
1436
0
    if (pk->ameth && pk->ameth->pkey_ctrl) {
1437
0
        int i, r;
1438
0
        i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_RI_TYPE, 0, &r);
1439
0
        if (i > 0)
1440
0
            return r;
1441
0
    }
1442
1443
    /*
1444
     * Otherwise try very hard to figure out what RecipientInfo the key supports.
1445
     */
1446
0
    ri_type = CMS_RECIPINFO_TRANS;
1447
0
    ctx = EVP_PKEY_CTX_new(pk, NULL);
1448
0
    if (ctx != NULL) {
1449
0
        ERR_set_mark();
1450
0
        if (EVP_PKEY_encrypt_init(ctx) > 0)
1451
0
            ri_type = CMS_RECIPINFO_TRANS;
1452
0
        else if (EVP_PKEY_derive_init(ctx) > 0)
1453
0
            ri_type = CMS_RECIPINFO_AGREE;
1454
0
        else if (EVP_PKEY_encapsulate_init(ctx, NULL) > 0)
1455
0
            ri_type = CMS_RECIPINFO_KEM;
1456
0
        ERR_pop_to_mark();
1457
0
    }
1458
0
    EVP_PKEY_CTX_free(ctx);
1459
1460
0
    return ri_type;
1461
0
}
1462
1463
int ossl_cms_pkey_is_ri_type_supported(EVP_PKEY *pk, int ri_type)
1464
0
{
1465
0
    int supportedRiType;
1466
1467
0
    if (pk->ameth != NULL && pk->ameth->pkey_ctrl != NULL) {
1468
0
        int i, r;
1469
1470
0
        i = pk->ameth->pkey_ctrl(pk, ASN1_PKEY_CTRL_CMS_IS_RI_TYPE_SUPPORTED,
1471
0
            ri_type, &r);
1472
0
        if (i > 0)
1473
0
            return r;
1474
0
    }
1475
1476
0
    supportedRiType = ossl_cms_pkey_get_ri_type(pk);
1477
0
    if (supportedRiType < 0)
1478
0
        return 0;
1479
1480
0
    return (supportedRiType == ri_type);
1481
0
}
1482
1483
int ossl_cms_RecipientInfo_wrap_init(CMS_RecipientInfo *ri,
1484
    const EVP_CIPHER *cipher)
1485
0
{
1486
0
    const CMS_CTX *cms_ctx;
1487
0
    EVP_CIPHER_CTX *ctx;
1488
0
    const EVP_CIPHER *kekcipher;
1489
0
    EVP_CIPHER *fetched_kekcipher;
1490
0
    const char *kekcipher_name;
1491
0
    int keylen;
1492
0
    int ret;
1493
1494
0
    if (ri->type == CMS_RECIPINFO_AGREE) {
1495
0
        cms_ctx = ri->d.kari->cms_ctx;
1496
0
        ctx = ri->d.kari->ctx;
1497
0
    } else if (ri->type == CMS_RECIPINFO_KEM) {
1498
0
        cms_ctx = ri->d.ori->d.kemri->cms_ctx;
1499
0
        ctx = ri->d.ori->d.kemri->ctx;
1500
0
    } else {
1501
0
        ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE);
1502
0
        return 0;
1503
0
    }
1504
1505
    /* If a suitable wrap algorithm is already set nothing to do */
1506
0
    kekcipher = EVP_CIPHER_CTX_get0_cipher(ctx);
1507
0
    if (kekcipher != NULL) {
1508
0
        if (EVP_CIPHER_CTX_get_mode(ctx) != EVP_CIPH_WRAP_MODE)
1509
0
            return 0;
1510
0
        return 1;
1511
0
    }
1512
0
    if (cipher == NULL)
1513
0
        return 0;
1514
0
    keylen = EVP_CIPHER_get_key_length(cipher);
1515
0
    if (keylen <= 0) {
1516
0
        ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH);
1517
0
        return 0;
1518
0
    }
1519
1520
    /*
1521
     * Pick a cipher based on content encryption cipher. If it is DES3 use
1522
     * DES3 wrap otherwise use AES wrap similar to key size.
1523
     */
1524
0
#ifndef OPENSSL_NO_DES
1525
0
    if (EVP_CIPHER_get_type(cipher) == NID_des_ede3_cbc)
1526
0
        kekcipher_name = SN_id_smime_alg_CMS3DESwrap;
1527
0
    else
1528
0
#endif
1529
0
        if (keylen <= 16)
1530
0
        kekcipher_name = SN_id_aes128_wrap;
1531
0
    else if (keylen <= 24)
1532
0
        kekcipher_name = SN_id_aes192_wrap;
1533
0
    else
1534
0
        kekcipher_name = SN_id_aes256_wrap;
1535
1536
0
    fetched_kekcipher = EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(cms_ctx),
1537
0
        kekcipher_name,
1538
0
        ossl_cms_ctx_get0_propq(cms_ctx));
1539
0
    if (fetched_kekcipher == NULL)
1540
0
        return 0;
1541
0
    ret = EVP_EncryptInit_ex(ctx, fetched_kekcipher, NULL, NULL, NULL);
1542
0
    EVP_CIPHER_free(fetched_kekcipher);
1543
0
    return ret;
1544
0
}