Coverage Report

Created: 2025-12-04 06:33

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