Coverage Report

Created: 2025-06-13 06:58

/src/openssl30/crypto/cms/cms_kari.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2013-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/aes.h>
23
#include "cms_local.h"
24
#include "crypto/asn1.h"
25
26
/* Key Agreement Recipient Info (KARI) routines */
27
28
int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri,
29
                                    X509_ALGOR **palg,
30
                                    ASN1_OCTET_STRING **pukm)
31
0
{
32
0
    if (ri->type != CMS_RECIPINFO_AGREE) {
33
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT);
34
0
        return 0;
35
0
    }
36
0
    if (palg)
37
0
        *palg = ri->d.kari->keyEncryptionAlgorithm;
38
0
    if (pukm)
39
0
        *pukm = ri->d.kari->ukm;
40
0
    return 1;
41
0
}
42
43
/* Retrieve recipient encrypted keys from a kari */
44
45
STACK_OF(CMS_RecipientEncryptedKey)
46
*CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri)
47
0
{
48
0
    if (ri->type != CMS_RECIPINFO_AGREE) {
49
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT);
50
0
        return NULL;
51
0
    }
52
0
    return ri->d.kari->recipientEncryptedKeys;
53
0
}
54
55
int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri,
56
                                        X509_ALGOR **pubalg,
57
                                        ASN1_BIT_STRING **pubkey,
58
                                        ASN1_OCTET_STRING **keyid,
59
                                        X509_NAME **issuer,
60
                                        ASN1_INTEGER **sno)
61
0
{
62
0
    CMS_OriginatorIdentifierOrKey *oik;
63
64
0
    if (ri->type != CMS_RECIPINFO_AGREE) {
65
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT);
66
0
        return 0;
67
0
    }
68
0
    oik = ri->d.kari->originator;
69
0
    if (issuer)
70
0
        *issuer = NULL;
71
0
    if (sno)
72
0
        *sno = NULL;
73
0
    if (keyid)
74
0
        *keyid = NULL;
75
0
    if (pubalg)
76
0
        *pubalg = NULL;
77
0
    if (pubkey)
78
0
        *pubkey = NULL;
79
0
    if (oik->type == CMS_OIK_ISSUER_SERIAL) {
80
0
        if (issuer)
81
0
            *issuer = oik->d.issuerAndSerialNumber->issuer;
82
0
        if (sno)
83
0
            *sno = oik->d.issuerAndSerialNumber->serialNumber;
84
0
    } else if (oik->type == CMS_OIK_KEYIDENTIFIER) {
85
0
        if (keyid)
86
0
            *keyid = oik->d.subjectKeyIdentifier;
87
0
    } else if (oik->type == CMS_OIK_PUBKEY) {
88
0
        if (pubalg)
89
0
            *pubalg = oik->d.originatorKey->algorithm;
90
0
        if (pubkey)
91
0
            *pubkey = oik->d.originatorKey->publicKey;
92
0
    } else
93
0
        return 0;
94
0
    return 1;
95
0
}
96
97
int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert)
98
0
{
99
0
    CMS_OriginatorIdentifierOrKey *oik;
100
101
0
    if (ri->type != CMS_RECIPINFO_AGREE) {
102
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT);
103
0
        return -2;
104
0
    }
105
0
    oik = ri->d.kari->originator;
106
0
    if (oik->type == CMS_OIK_ISSUER_SERIAL)
107
0
        return ossl_cms_ias_cert_cmp(oik->d.issuerAndSerialNumber, cert);
108
0
    else if (oik->type == CMS_OIK_KEYIDENTIFIER)
109
0
        return ossl_cms_keyid_cert_cmp(oik->d.subjectKeyIdentifier, cert);
110
0
    return -1;
111
0
}
112
113
int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek,
114
                                      ASN1_OCTET_STRING **keyid,
115
                                      ASN1_GENERALIZEDTIME **tm,
116
                                      CMS_OtherKeyAttribute **other,
117
                                      X509_NAME **issuer, ASN1_INTEGER **sno)
118
0
{
119
0
    CMS_KeyAgreeRecipientIdentifier *rid = rek->rid;
120
121
0
    if (rid->type == CMS_REK_ISSUER_SERIAL) {
122
0
        if (issuer)
123
0
            *issuer = rid->d.issuerAndSerialNumber->issuer;
124
0
        if (sno)
125
0
            *sno = rid->d.issuerAndSerialNumber->serialNumber;
126
0
        if (keyid)
127
0
            *keyid = NULL;
128
0
        if (tm)
129
0
            *tm = NULL;
130
0
        if (other)
131
0
            *other = NULL;
132
0
    } else if (rid->type == CMS_REK_KEYIDENTIFIER) {
133
0
        if (keyid)
134
0
            *keyid = rid->d.rKeyId->subjectKeyIdentifier;
135
0
        if (tm)
136
0
            *tm = rid->d.rKeyId->date;
137
0
        if (other)
138
0
            *other = rid->d.rKeyId->other;
139
0
        if (issuer)
140
0
            *issuer = NULL;
141
0
        if (sno)
142
0
            *sno = NULL;
143
0
    } else
144
0
        return 0;
145
0
    return 1;
146
0
}
147
148
int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek,
149
                                       X509 *cert)
150
0
{
151
0
    CMS_KeyAgreeRecipientIdentifier *rid = rek->rid;
152
153
0
    if (rid->type == CMS_REK_ISSUER_SERIAL)
154
0
        return ossl_cms_ias_cert_cmp(rid->d.issuerAndSerialNumber, cert);
155
0
    else if (rid->type == CMS_REK_KEYIDENTIFIER)
156
0
        return ossl_cms_keyid_cert_cmp(rid->d.rKeyId->subjectKeyIdentifier,
157
0
                                       cert);
158
0
    else
159
0
        return -1;
160
0
}
161
162
int CMS_RecipientInfo_kari_set0_pkey_and_peer(CMS_RecipientInfo *ri,
163
                                              EVP_PKEY *pk, X509 *peer)
164
0
{
165
0
    EVP_PKEY_CTX *pctx;
166
0
    CMS_KeyAgreeRecipientInfo *kari = ri->d.kari;
167
168
0
    EVP_PKEY_CTX_free(kari->pctx);
169
0
    kari->pctx = NULL;
170
0
    if (pk == NULL)
171
0
        return 1;
172
173
0
    pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(kari->cms_ctx),
174
0
                                      pk,
175
0
                                      ossl_cms_ctx_get0_propq(kari->cms_ctx));
176
0
    if (pctx == NULL || EVP_PKEY_derive_init(pctx) <= 0)
177
0
        goto err;
178
179
0
    if (peer != NULL) {
180
0
        EVP_PKEY *pub_pkey = X509_get0_pubkey(peer);
181
182
0
        if (EVP_PKEY_derive_set_peer(pctx, pub_pkey) <= 0)
183
0
            goto err;
184
0
    }
185
186
0
    kari->pctx = pctx;
187
0
    return 1;
188
0
 err:
189
0
    EVP_PKEY_CTX_free(pctx);
190
0
    return 0;
191
0
}
192
193
int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk)
194
0
{
195
0
    return CMS_RecipientInfo_kari_set0_pkey_and_peer(ri, pk, NULL);
196
0
}
197
198
EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri)
199
0
{
200
0
    if (ri->type == CMS_RECIPINFO_AGREE)
201
0
        return ri->d.kari->ctx;
202
0
    return NULL;
203
0
}
204
205
/*
206
 * Derive KEK and decrypt/encrypt with it to produce either the original CEK
207
 * or the encrypted CEK.
208
 */
209
210
static int cms_kek_cipher(unsigned char **pout, size_t *poutlen,
211
                          const unsigned char *in, size_t inlen,
212
                          CMS_KeyAgreeRecipientInfo *kari, int enc)
213
0
{
214
    /* Key encryption key */
215
0
    unsigned char kek[EVP_MAX_KEY_LENGTH];
216
0
    size_t keklen;
217
0
    int rv = 0;
218
0
    unsigned char *out = NULL;
219
0
    int outlen;
220
221
0
    keklen = EVP_CIPHER_CTX_get_key_length(kari->ctx);
222
0
    if (keklen > EVP_MAX_KEY_LENGTH)
223
0
        return 0;
224
    /* Derive KEK */
225
0
    if (EVP_PKEY_derive(kari->pctx, kek, &keklen) <= 0)
226
0
        goto err;
227
    /* Set KEK in context */
228
0
    if (!EVP_CipherInit_ex(kari->ctx, NULL, NULL, kek, NULL, enc))
229
0
        goto err;
230
    /* obtain output length of ciphered key */
231
0
    if (!EVP_CipherUpdate(kari->ctx, NULL, &outlen, in, inlen))
232
0
        goto err;
233
0
    out = OPENSSL_malloc(outlen);
234
0
    if (out == NULL)
235
0
        goto err;
236
0
    if (!EVP_CipherUpdate(kari->ctx, out, &outlen, in, inlen))
237
0
        goto err;
238
0
    *pout = out;
239
0
    *poutlen = (size_t)outlen;
240
0
    rv = 1;
241
242
0
 err:
243
0
    OPENSSL_cleanse(kek, keklen);
244
0
    if (!rv)
245
0
        OPENSSL_free(out);
246
0
    EVP_CIPHER_CTX_reset(kari->ctx);
247
    /* FIXME: WHY IS kari->pctx freed here?  /RL */
248
0
    EVP_PKEY_CTX_free(kari->pctx);
249
0
    kari->pctx = NULL;
250
0
    return rv;
251
0
}
252
253
int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms,
254
                                   CMS_RecipientInfo *ri,
255
                                   CMS_RecipientEncryptedKey *rek)
256
0
{
257
0
    int rv = 0;
258
0
    unsigned char *enckey = NULL, *cek = NULL;
259
0
    size_t enckeylen;
260
0
    size_t ceklen;
261
0
    CMS_EncryptedContentInfo *ec;
262
263
0
    enckeylen = rek->encryptedKey->length;
264
0
    enckey = rek->encryptedKey->data;
265
    /* Setup all parameters to derive KEK */
266
0
    if (!ossl_cms_env_asn1_ctrl(ri, 1))
267
0
        goto err;
268
    /* Attempt to decrypt CEK */
269
0
    if (!cms_kek_cipher(&cek, &ceklen, enckey, enckeylen, ri->d.kari, 0))
270
0
        goto err;
271
0
    ec = ossl_cms_get0_env_enc_content(cms);
272
0
    OPENSSL_clear_free(ec->key, ec->keylen);
273
0
    ec->key = cek;
274
0
    ec->keylen = ceklen;
275
0
    cek = NULL;
276
0
    rv = 1;
277
0
 err:
278
0
    OPENSSL_free(cek);
279
0
    return rv;
280
0
}
281
282
/* Create ephemeral key and initialise context based on it */
283
static int cms_kari_create_ephemeral_key(CMS_KeyAgreeRecipientInfo *kari,
284
                                         EVP_PKEY *pk)
285
0
{
286
0
    EVP_PKEY_CTX *pctx = NULL;
287
0
    EVP_PKEY *ekey = NULL;
288
0
    int rv = 0;
289
0
    const CMS_CTX *ctx = kari->cms_ctx;
290
0
    OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx);
291
0
    const char *propq = ossl_cms_ctx_get0_propq(ctx);
292
293
0
    pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propq);
294
0
    if (pctx == NULL)
295
0
        goto err;
296
0
    if (EVP_PKEY_keygen_init(pctx) <= 0)
297
0
        goto err;
298
0
    if (EVP_PKEY_keygen(pctx, &ekey) <= 0)
299
0
        goto err;
300
0
    EVP_PKEY_CTX_free(pctx);
301
0
    pctx = EVP_PKEY_CTX_new_from_pkey(libctx, ekey, propq);
302
0
    if (pctx == NULL)
303
0
        goto err;
304
0
    if (EVP_PKEY_derive_init(pctx) <= 0)
305
0
        goto err;
306
0
    kari->pctx = pctx;
307
0
    rv = 1;
308
0
 err:
309
0
    if (!rv)
310
0
        EVP_PKEY_CTX_free(pctx);
311
0
    EVP_PKEY_free(ekey);
312
0
    return rv;
313
0
}
314
315
/* Set originator private key and initialise context based on it */
316
static int cms_kari_set_originator_private_key(CMS_KeyAgreeRecipientInfo *kari,
317
                                               EVP_PKEY *originatorPrivKey )
318
0
{
319
0
    EVP_PKEY_CTX *pctx = NULL;
320
0
    int rv = 0;
321
0
    const CMS_CTX *ctx = kari->cms_ctx;
322
323
0
    pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx),
324
0
                                      originatorPrivKey,
325
0
                                      ossl_cms_ctx_get0_propq(ctx));
326
0
    if (pctx == NULL)
327
0
        goto err;
328
0
    if (EVP_PKEY_derive_init(pctx) <= 0)
329
0
         goto err;
330
331
0
    kari->pctx = pctx;
332
0
    rv = 1;
333
0
 err:
334
0
    if (rv == 0)
335
0
        EVP_PKEY_CTX_free(pctx);
336
0
    return rv;
337
0
}
338
339
/* Initialise a kari based on passed certificate and key */
340
341
int ossl_cms_RecipientInfo_kari_init(CMS_RecipientInfo *ri,  X509 *recip,
342
                                     EVP_PKEY *recipPubKey, X509 *originator,
343
                                     EVP_PKEY *originatorPrivKey,
344
                                     unsigned int flags, const CMS_CTX *ctx)
345
0
{
346
0
    CMS_KeyAgreeRecipientInfo *kari;
347
0
    CMS_RecipientEncryptedKey *rek = NULL;
348
349
0
    ri->d.kari = M_ASN1_new_of(CMS_KeyAgreeRecipientInfo);
350
0
    if (ri->d.kari == NULL)
351
0
        return 0;
352
0
    ri->type = CMS_RECIPINFO_AGREE;
353
354
0
    kari = ri->d.kari;
355
0
    kari->version = 3;
356
0
    kari->cms_ctx = ctx;
357
358
0
    rek = M_ASN1_new_of(CMS_RecipientEncryptedKey);
359
0
    if (rek == NULL)
360
0
        return 0;
361
362
0
    if (!sk_CMS_RecipientEncryptedKey_push(kari->recipientEncryptedKeys, rek)) {
363
0
        M_ASN1_free_of(rek, CMS_RecipientEncryptedKey);
364
0
        return 0;
365
0
    }
366
367
0
    if (flags & CMS_USE_KEYID) {
368
0
        rek->rid->type = CMS_REK_KEYIDENTIFIER;
369
0
        rek->rid->d.rKeyId = M_ASN1_new_of(CMS_RecipientKeyIdentifier);
370
0
        if (rek->rid->d.rKeyId == NULL)
371
0
            return 0;
372
0
        if (!ossl_cms_set1_keyid(&rek->rid->d.rKeyId->subjectKeyIdentifier, recip))
373
0
            return 0;
374
0
    } else {
375
0
        rek->rid->type = CMS_REK_ISSUER_SERIAL;
376
0
        if (!ossl_cms_set1_ias(&rek->rid->d.issuerAndSerialNumber, recip))
377
0
            return 0;
378
0
    }
379
380
0
    if (originatorPrivKey == NULL && originator == NULL) {
381
        /* Create ephemeral key */
382
0
        if (!cms_kari_create_ephemeral_key(kari, recipPubKey))
383
0
            return 0;
384
0
    } else {
385
        /* Use originator key */
386
0
        CMS_OriginatorIdentifierOrKey *oik = ri->d.kari->originator;
387
388
0
        if (originatorPrivKey == NULL || originator == NULL)
389
0
            return 0;
390
391
0
        if (flags & CMS_USE_ORIGINATOR_KEYID) {
392
0
             oik->type = CMS_OIK_KEYIDENTIFIER;
393
0
             oik->d.subjectKeyIdentifier = ASN1_OCTET_STRING_new();
394
0
             if (oik->d.subjectKeyIdentifier == NULL)
395
0
                  return 0;
396
0
             if (!ossl_cms_set1_keyid(&oik->d.subjectKeyIdentifier, originator))
397
0
                  return 0;
398
0
        } else {
399
0
             oik->type = CMS_REK_ISSUER_SERIAL;
400
0
             if (!ossl_cms_set1_ias(&oik->d.issuerAndSerialNumber, originator))
401
0
                  return 0;
402
0
        }
403
404
0
        if (!cms_kari_set_originator_private_key(kari, originatorPrivKey))
405
0
            return 0;
406
0
    }
407
408
0
    EVP_PKEY_up_ref(recipPubKey);
409
0
    rek->pkey = recipPubKey;
410
0
    return 1;
411
0
}
412
413
static int cms_wrap_init(CMS_KeyAgreeRecipientInfo *kari,
414
                         const EVP_CIPHER *cipher)
415
0
{
416
0
    const CMS_CTX *cms_ctx = kari->cms_ctx;
417
0
    EVP_CIPHER_CTX *ctx = kari->ctx;
418
0
    const EVP_CIPHER *kekcipher;
419
0
    EVP_CIPHER *fetched_kekcipher;
420
0
    const char *kekcipher_name;
421
0
    int keylen;
422
0
    int ret;
423
424
    /* If a suitable wrap algorithm is already set nothing to do */
425
0
    kekcipher = EVP_CIPHER_CTX_get0_cipher(ctx);
426
0
    if (kekcipher != NULL) {
427
0
        if (EVP_CIPHER_CTX_get_mode(ctx) != EVP_CIPH_WRAP_MODE)
428
0
            return 0;
429
0
        return 1;
430
0
    }
431
0
    if (cipher == NULL)
432
0
        return 0;
433
0
    keylen = EVP_CIPHER_get_key_length(cipher);
434
0
    if ((EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_GET_WRAP_CIPHER) != 0) {
435
0
        ret = EVP_CIPHER_meth_get_ctrl(cipher)(NULL, EVP_CTRL_GET_WRAP_CIPHER,
436
0
                                               0, &kekcipher);
437
0
        if (ret <= 0)
438
0
             return 0;
439
440
0
        if (kekcipher != NULL) {
441
0
             if (EVP_CIPHER_get_mode(kekcipher) != EVP_CIPH_WRAP_MODE)
442
0
                 return 0;
443
0
             kekcipher_name = EVP_CIPHER_get0_name(kekcipher);
444
0
             goto enc;
445
0
        }
446
0
    }
447
448
    /*
449
     * Pick a cipher based on content encryption cipher. If it is DES3 use
450
     * DES3 wrap otherwise use AES wrap similar to key size.
451
     */
452
0
#ifndef OPENSSL_NO_DES
453
0
    if (EVP_CIPHER_get_type(cipher) == NID_des_ede3_cbc)
454
0
        kekcipher_name = SN_id_smime_alg_CMS3DESwrap;
455
0
    else
456
0
#endif
457
0
    if (keylen <= 16)
458
0
        kekcipher_name = SN_id_aes128_wrap;
459
0
    else if (keylen <= 24)
460
0
        kekcipher_name = SN_id_aes192_wrap;
461
0
    else
462
0
        kekcipher_name = SN_id_aes256_wrap;
463
0
enc:
464
0
    fetched_kekcipher = EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(cms_ctx),
465
0
                                         kekcipher_name,
466
0
                                         ossl_cms_ctx_get0_propq(cms_ctx));
467
0
    if (fetched_kekcipher == NULL)
468
0
        return 0;
469
0
    ret = EVP_EncryptInit_ex(ctx, fetched_kekcipher, NULL, NULL, NULL);
470
0
    EVP_CIPHER_free(fetched_kekcipher);
471
0
    return ret;
472
0
}
473
474
/* Encrypt content key in key agreement recipient info */
475
476
int ossl_cms_RecipientInfo_kari_encrypt(const CMS_ContentInfo *cms,
477
                                        CMS_RecipientInfo *ri)
478
0
{
479
0
    CMS_KeyAgreeRecipientInfo *kari;
480
0
    CMS_EncryptedContentInfo *ec;
481
0
    CMS_RecipientEncryptedKey *rek;
482
0
    STACK_OF(CMS_RecipientEncryptedKey) *reks;
483
0
    int i;
484
485
0
    if (ri->type != CMS_RECIPINFO_AGREE) {
486
0
        ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT);
487
0
        return 0;
488
0
    }
489
0
    kari = ri->d.kari;
490
0
    reks = kari->recipientEncryptedKeys;
491
0
    ec = ossl_cms_get0_env_enc_content(cms);
492
    /* Initialise wrap algorithm parameters */
493
0
    if (!cms_wrap_init(kari, ec->cipher))
494
0
        return 0;
495
    /*
496
     * If no originator key set up initialise for ephemeral key the public key
497
     * ASN1 structure will set the actual public key value.
498
     */
499
0
    if (kari->originator->type == -1) {
500
0
        CMS_OriginatorIdentifierOrKey *oik = kari->originator;
501
0
        oik->type = CMS_OIK_PUBKEY;
502
0
        oik->d.originatorKey = M_ASN1_new_of(CMS_OriginatorPublicKey);
503
0
        if (!oik->d.originatorKey)
504
0
            return 0;
505
0
    } else {
506
        /*
507
         * Currently it is not possible to get public key as it is not stored
508
         * during kari initialization.
509
         */
510
0
        ERR_raise(ERR_LIB_CMS, CMS_R_ERROR_UNSUPPORTED_STATIC_KEY_AGREEMENT);
511
0
        return 0;
512
0
    }
513
    /* Initialise KDF algorithm */
514
0
    if (!ossl_cms_env_asn1_ctrl(ri, 0))
515
0
        return 0;
516
    /* For each rek, derive KEK, encrypt CEK */
517
0
    for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++) {
518
0
        unsigned char *enckey;
519
0
        size_t enckeylen;
520
0
        rek = sk_CMS_RecipientEncryptedKey_value(reks, i);
521
0
        if (EVP_PKEY_derive_set_peer(kari->pctx, rek->pkey) <= 0)
522
0
            return 0;
523
0
        if (!cms_kek_cipher(&enckey, &enckeylen, ec->key, ec->keylen,
524
0
                            kari, 1))
525
0
            return 0;
526
0
        ASN1_STRING_set0(rek->encryptedKey, enckey, enckeylen);
527
0
    }
528
529
0
    return 1;
530
0
}