Coverage Report

Created: 2026-09-12 06:55

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