Coverage Report

Created: 2026-09-12 06:55

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