Coverage Report

Created: 2025-08-25 06:30

/src/openssl/providers/implementations/kem/rsa_kem.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2020-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
/*
12
 * RSA low level APIs are deprecated for public use, but still ok for
13
 * internal use.
14
 */
15
#include "internal/deprecated.h"
16
#include "internal/nelem.h"
17
#include <openssl/crypto.h>
18
#include <openssl/evp.h>
19
#include <openssl/core_dispatch.h>
20
#include <openssl/core_names.h>
21
#include <openssl/rsa.h>
22
#include <openssl/params.h>
23
#include <openssl/err.h>
24
#include <openssl/proverr.h>
25
#include "crypto/rsa.h"
26
#include "internal/cryptlib.h"
27
#include "prov/provider_ctx.h"
28
#include "prov/providercommon.h"
29
#include "prov/implementations.h"
30
#include "prov/securitycheck.h"
31
32
static OSSL_FUNC_kem_newctx_fn rsakem_newctx;
33
static OSSL_FUNC_kem_encapsulate_init_fn rsakem_encapsulate_init;
34
static OSSL_FUNC_kem_encapsulate_fn rsakem_generate;
35
static OSSL_FUNC_kem_decapsulate_init_fn rsakem_decapsulate_init;
36
static OSSL_FUNC_kem_decapsulate_fn rsakem_recover;
37
static OSSL_FUNC_kem_freectx_fn rsakem_freectx;
38
static OSSL_FUNC_kem_dupctx_fn rsakem_dupctx;
39
static OSSL_FUNC_kem_get_ctx_params_fn rsakem_get_ctx_params;
40
static OSSL_FUNC_kem_gettable_ctx_params_fn rsakem_gettable_ctx_params;
41
static OSSL_FUNC_kem_set_ctx_params_fn rsakem_set_ctx_params;
42
static OSSL_FUNC_kem_settable_ctx_params_fn rsakem_settable_ctx_params;
43
44
/*
45
 * Only the KEM for RSASVE as defined in SP800-56b r2 is implemented
46
 * currently.
47
 */
48
#define KEM_OP_UNDEFINED   -1
49
0
#define KEM_OP_RSASVE       0
50
51
/*
52
 * What's passed as an actual key is defined by the KEYMGMT interface.
53
 * We happen to know that our KEYMGMT simply passes RSA structures, so
54
 * we use that here too.
55
 */
56
typedef struct {
57
    OSSL_LIB_CTX *libctx;
58
    RSA *rsa;
59
    int op;
60
    OSSL_FIPS_IND_DECLARE
61
} PROV_RSA_CTX;
62
63
static const OSSL_ITEM rsakem_opname_id_map[] = {
64
    { KEM_OP_RSASVE, OSSL_KEM_PARAM_OPERATION_RSASVE },
65
};
66
67
static int name2id(const char *name, const OSSL_ITEM *map, size_t sz)
68
0
{
69
0
    size_t i;
70
71
0
    if (name == NULL)
72
0
        return -1;
73
74
0
    for (i = 0; i < sz; ++i) {
75
0
        if (OPENSSL_strcasecmp(map[i].ptr, name) == 0)
76
0
            return map[i].id;
77
0
    }
78
0
    return -1;
79
0
}
80
81
static int rsakem_opname2id(const char *name)
82
0
{
83
0
    return name2id(name, rsakem_opname_id_map, OSSL_NELEM(rsakem_opname_id_map));
84
0
}
85
86
static void *rsakem_newctx(void *provctx)
87
0
{
88
0
    PROV_RSA_CTX *prsactx;
89
90
0
    if (!ossl_prov_is_running())
91
0
        return NULL;
92
93
0
    prsactx =  OPENSSL_zalloc(sizeof(PROV_RSA_CTX));
94
0
    if (prsactx == NULL)
95
0
        return NULL;
96
0
    prsactx->libctx = PROV_LIBCTX_OF(provctx);
97
0
    prsactx->op = KEM_OP_RSASVE;
98
0
    OSSL_FIPS_IND_INIT(prsactx)
99
100
0
    return prsactx;
101
0
}
102
103
static void rsakem_freectx(void *vprsactx)
104
0
{
105
0
    PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx;
106
107
0
    RSA_free(prsactx->rsa);
108
0
    OPENSSL_free(prsactx);
109
0
}
110
111
static void *rsakem_dupctx(void *vprsactx)
112
0
{
113
0
    PROV_RSA_CTX *srcctx = (PROV_RSA_CTX *)vprsactx;
114
0
    PROV_RSA_CTX *dstctx;
115
116
0
    if (!ossl_prov_is_running())
117
0
        return NULL;
118
119
0
    dstctx = OPENSSL_zalloc(sizeof(*srcctx));
120
0
    if (dstctx == NULL)
121
0
        return NULL;
122
123
0
    *dstctx = *srcctx;
124
0
    if (dstctx->rsa != NULL && !RSA_up_ref(dstctx->rsa)) {
125
0
        OPENSSL_free(dstctx);
126
0
        return NULL;
127
0
    }
128
0
    return dstctx;
129
0
}
130
131
static int rsakem_init(void *vprsactx, void *vrsa,
132
                       const OSSL_PARAM params[], int operation,
133
                       const char *desc)
134
0
{
135
0
    PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx;
136
0
    int protect = 0;
137
138
0
    if (!ossl_prov_is_running())
139
0
        return 0;
140
141
0
    if (prsactx == NULL || vrsa == NULL)
142
0
        return 0;
143
144
0
    if (!ossl_rsa_key_op_get_protect(vrsa, operation, &protect))
145
0
        return 0;
146
0
    if (!RSA_up_ref(vrsa))
147
0
        return 0;
148
0
    RSA_free(prsactx->rsa);
149
0
    prsactx->rsa = vrsa;
150
151
0
    OSSL_FIPS_IND_SET_APPROVED(prsactx)
152
0
    if (!rsakem_set_ctx_params(prsactx, params))
153
0
        return 0;
154
#ifdef FIPS_MODULE
155
    if (!ossl_fips_ind_rsa_key_check(OSSL_FIPS_IND_GET(prsactx),
156
                                     OSSL_FIPS_IND_SETTABLE0, prsactx->libctx,
157
                                     prsactx->rsa, desc, protect))
158
        return 0;
159
#endif
160
0
    return 1;
161
0
}
162
163
static int rsakem_encapsulate_init(void *vprsactx, void *vrsa,
164
                                   const OSSL_PARAM params[])
165
0
{
166
0
    return rsakem_init(vprsactx, vrsa, params, EVP_PKEY_OP_ENCAPSULATE,
167
0
                       "RSA Encapsulate Init");
168
0
}
169
170
static int rsakem_decapsulate_init(void *vprsactx, void *vrsa,
171
                                   const OSSL_PARAM params[])
172
0
{
173
0
    return rsakem_init(vprsactx, vrsa, params, EVP_PKEY_OP_DECAPSULATE,
174
0
                       "RSA Decapsulate Init");
175
0
}
176
177
/* Machine generated by util/perl/OpenSSL/paramnames.pm */
178
#ifndef rsakem_get_ctx_params_list
179
static const OSSL_PARAM rsakem_get_ctx_params_list[] = {
180
# if defined(FIPS_MODULE)
181
    OSSL_PARAM_int(OSSL_KEM_PARAM_FIPS_APPROVED_INDICATOR, NULL),
182
# endif
183
    OSSL_PARAM_END
184
};
185
#endif
186
187
#ifndef rsakem_get_ctx_params_st
188
struct rsakem_get_ctx_params_st {
189
# if defined(FIPS_MODULE)
190
    OSSL_PARAM *ind;
191
# else
192
    int dummy; /* unused */
193
# endif
194
};
195
#endif
196
197
#ifndef rsakem_get_ctx_params_decoder
198
static int rsakem_get_ctx_params_decoder
199
    (const OSSL_PARAM *p, struct rsakem_get_ctx_params_st *r)
200
0
{
201
0
    const char *s;
202
203
0
    memset(r, 0, sizeof(*r));
204
0
    if (p != NULL)
205
0
        for (; (s = p->key) != NULL; p++)
206
# if defined(FIPS_MODULE)
207
            if (ossl_likely(strcmp("fips-indicator", s + 0) == 0)) {
208
                /* KEM_PARAM_FIPS_APPROVED_INDICATOR */
209
                if (ossl_unlikely(r->ind != NULL)) {
210
                    ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
211
                                   "param %s is repeated", s);
212
                    return 0;
213
                }
214
                r->ind = (OSSL_PARAM *)p;
215
            }
216
# else
217
0
            ;
218
0
# endif
219
0
    return 1;
220
0
}
221
#endif
222
/* End of machine generated */
223
224
static int rsakem_get_ctx_params(void *vprsactx, OSSL_PARAM *params)
225
0
{
226
0
    PROV_RSA_CTX *ctx = (PROV_RSA_CTX *)vprsactx;
227
0
    struct rsakem_get_ctx_params_st p;
228
229
0
    if (ctx == NULL || !rsakem_get_ctx_params_decoder(params, &p))
230
0
        return 0;
231
232
0
    if (!OSSL_FIPS_IND_GET_CTX_FROM_PARAM(ctx, p.ind))
233
0
        return 0;
234
0
    return 1;
235
0
}
236
237
static const OSSL_PARAM *rsakem_gettable_ctx_params(ossl_unused void *vprsactx,
238
                                                    ossl_unused void *provctx)
239
0
{
240
0
    return rsakem_get_ctx_params_list;
241
0
}
242
243
/* Machine generated by util/perl/OpenSSL/paramnames.pm */
244
#ifndef rsakem_set_ctx_params_list
245
static const OSSL_PARAM rsakem_set_ctx_params_list[] = {
246
    OSSL_PARAM_utf8_string(OSSL_KEM_PARAM_OPERATION, NULL, 0),
247
# if defined(FIPS_MODULE)
248
    OSSL_PARAM_int(OSSL_KEM_PARAM_FIPS_KEY_CHECK, NULL),
249
# endif
250
    OSSL_PARAM_END
251
};
252
#endif
253
254
#ifndef rsakem_set_ctx_params_st
255
struct rsakem_set_ctx_params_st {
256
# if defined(FIPS_MODULE)
257
    OSSL_PARAM *ind_k;
258
# endif
259
    OSSL_PARAM *op;
260
};
261
#endif
262
263
#ifndef rsakem_set_ctx_params_decoder
264
static int rsakem_set_ctx_params_decoder
265
    (const OSSL_PARAM *p, struct rsakem_set_ctx_params_st *r)
266
0
{
267
0
    const char *s;
268
269
0
    memset(r, 0, sizeof(*r));
270
0
    if (p != NULL)
271
0
        for (; (s = p->key) != NULL; p++)
272
0
            switch(s[0]) {
273
0
            default:
274
0
                break;
275
0
            case 'k':
276
# if defined(FIPS_MODULE)
277
                if (ossl_likely(strcmp("ey-check", s + 1) == 0)) {
278
                    /* KEM_PARAM_FIPS_KEY_CHECK */
279
                    if (ossl_unlikely(r->ind_k != NULL)) {
280
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
281
                                       "param %s is repeated", s);
282
                        return 0;
283
                    }
284
                    r->ind_k = (OSSL_PARAM *)p;
285
                }
286
# endif
287
0
                break;
288
0
            case 'o':
289
0
                if (ossl_likely(strcmp("peration", s + 1) == 0)) {
290
                    /* KEM_PARAM_OPERATION */
291
0
                    if (ossl_unlikely(r->op != NULL)) {
292
0
                        ERR_raise_data(ERR_LIB_PROV, PROV_R_REPEATED_PARAMETER,
293
0
                                       "param %s is repeated", s);
294
0
                        return 0;
295
0
                    }
296
0
                    r->op = (OSSL_PARAM *)p;
297
0
                }
298
0
            }
299
0
    return 1;
300
0
}
301
#endif
302
/* End of machine generated */
303
304
static int rsakem_set_ctx_params(void *vprsactx, const OSSL_PARAM params[])
305
0
{
306
0
    PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx;
307
0
    struct rsakem_set_ctx_params_st p;
308
0
    int op;
309
310
0
    if (prsactx == NULL || !rsakem_set_ctx_params_decoder(params, &p))
311
0
        return 0;
312
313
0
    if (!OSSL_FIPS_IND_SET_CTX_FROM_PARAM(prsactx, OSSL_FIPS_IND_SETTABLE0,
314
0
                                          p.ind_k))
315
0
        return 0;
316
317
0
    if (p.op != NULL) {
318
0
        if (p.op->data_type != OSSL_PARAM_UTF8_STRING)
319
0
            return 0;
320
0
        op = rsakem_opname2id(p.op->data);
321
0
        if (op < 0)
322
0
            return 0;
323
0
        prsactx->op = op;
324
0
    }
325
0
    return 1;
326
0
}
327
328
static const OSSL_PARAM *rsakem_settable_ctx_params(ossl_unused void *vprsactx,
329
                                                    ossl_unused void *provctx)
330
0
{
331
0
    return rsakem_set_ctx_params_list;
332
0
}
333
334
/*
335
 * NIST.SP.800-56Br2
336
 * 7.2.1.2 RSASVE Generate Operation (RSASVE.GENERATE).
337
 *
338
 * Generate a random in the range 1 < z < (n – 1)
339
 */
340
static int rsasve_gen_rand_bytes(RSA *rsa_pub,
341
                                 unsigned char *out, int outlen)
342
0
{
343
0
    int ret = 0;
344
0
    BN_CTX *bnctx;
345
0
    BIGNUM *z, *nminus3;
346
347
0
    bnctx = BN_CTX_secure_new_ex(ossl_rsa_get0_libctx(rsa_pub));
348
0
    if (bnctx == NULL)
349
0
        return 0;
350
351
    /*
352
     * Generate a random in the range 1 < z < (n – 1).
353
     * Since BN_priv_rand_range_ex() returns a value in range 0 <= r < max
354
     * We can achieve this by adding 2.. but then we need to subtract 3 from
355
     * the upper bound i.e: 2 + (0 <= r < (n - 3))
356
     */
357
0
    BN_CTX_start(bnctx);
358
0
    nminus3 = BN_CTX_get(bnctx);
359
0
    z = BN_CTX_get(bnctx);
360
0
    ret = (z != NULL
361
0
           && (BN_copy(nminus3, RSA_get0_n(rsa_pub)) != NULL)
362
0
           && BN_sub_word(nminus3, 3)
363
0
           && BN_priv_rand_range_ex(z, nminus3, 0, bnctx)
364
0
           && BN_add_word(z, 2)
365
0
           && (BN_bn2binpad(z, out, outlen) == outlen));
366
0
    BN_CTX_end(bnctx);
367
0
    BN_CTX_free(bnctx);
368
0
    return ret;
369
0
}
370
371
/*
372
 * NIST.SP.800-56Br2
373
 * 7.2.1.2 RSASVE Generate Operation (RSASVE.GENERATE).
374
 */
375
static int rsasve_generate(PROV_RSA_CTX *prsactx,
376
                           unsigned char *out, size_t *outlen,
377
                           unsigned char *secret, size_t *secretlen)
378
0
{
379
0
    int ret;
380
0
    size_t nlen;
381
382
    /* Step (1): nlen = Ceil(len(n)/8) */
383
0
    nlen = RSA_size(prsactx->rsa);
384
385
0
    if (out == NULL) {
386
0
        if (nlen == 0) {
387
0
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY);
388
0
            return 0;
389
0
        }
390
0
        if (outlen == NULL && secretlen == NULL)
391
0
            return 0;
392
0
        if (outlen != NULL)
393
0
            *outlen = nlen;
394
0
        if (secretlen != NULL)
395
0
            *secretlen = nlen;
396
0
        return 1;
397
0
    }
398
399
    /*
400
     * If outlen is specified, then it must report the length
401
     * of the out buffer on input so that we can confirm
402
     * its size is sufficent for encapsulation
403
     */
404
0
    if (outlen != NULL && *outlen < nlen) {
405
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_OUTPUT_LENGTH);
406
0
        return 0;
407
0
    }
408
409
    /*
410
     * Step (2): Generate a random byte string z of nlen bytes where
411
     *            1 < z < n - 1
412
     */
413
0
    if (!rsasve_gen_rand_bytes(prsactx->rsa, secret, (int)nlen))
414
0
        return 0;
415
416
    /* Step(3): out = RSAEP((n,e), z) */
417
0
    ret = RSA_public_encrypt((int)nlen, secret, out, prsactx->rsa,
418
0
                             RSA_NO_PADDING);
419
0
    if (ret) {
420
0
        ret = 1;
421
0
        if (outlen != NULL)
422
0
            *outlen = nlen;
423
0
        if (secretlen != NULL)
424
0
            *secretlen = nlen;
425
0
    } else {
426
0
        OPENSSL_cleanse(secret, nlen);
427
0
    }
428
0
    return ret;
429
0
}
430
431
/**
432
 * rsasve_recover - Recovers a secret value from ciphertext using an RSA
433
 * private key.  Once, recovered, the secret value is considered to be a
434
 * shared secret.  Algorithm is preformed as per
435
 * NIST SP 800-56B Rev 2
436
 * 7.2.1.3 RSASVE Recovery Operation (RSASVE.RECOVER).
437
 *
438
 * This function performs RSA decryption using the private key from the
439
 * provided RSA context (`prsactx`). It takes the input ciphertext, decrypts
440
 * it, and writes the decrypted message to the output buffer.
441
 *
442
 * @prsactx:      The RSA context containing the private key.
443
 * @out:          The output buffer to store the decrypted message.
444
 * @outlen:       On input, the size of the output buffer. On successful
445
 *                completion, the actual length of the decrypted message.
446
 * @in:           The input buffer containing the ciphertext to be decrypted.
447
 * @inlen:        The length of the input ciphertext in bytes.
448
 *
449
 * Returns 1 on success, or 0 on error. In case of error, appropriate
450
 * error messages are raised using the ERR_raise function.
451
 */
452
static int rsasve_recover(PROV_RSA_CTX *prsactx,
453
                          unsigned char *out, size_t *outlen,
454
                          const unsigned char *in, size_t inlen)
455
0
{
456
0
    size_t nlen;
457
0
    int ret;
458
459
    /* Step (1): get the byte length of n */
460
0
    nlen = RSA_size(prsactx->rsa);
461
462
0
    if (out == NULL) {
463
0
        if (nlen == 0) {
464
0
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY);
465
0
            return 0;
466
0
        }
467
0
        *outlen = nlen;
468
0
        return 1;
469
0
    }
470
471
    /*
472
     * Step (2): check the input ciphertext 'inlen' matches the nlen
473
     * and that outlen is at least nlen bytes
474
     */
475
0
    if (inlen != nlen) {
476
0
        ERR_raise(ERR_LIB_PROV, PROV_R_BAD_LENGTH);
477
0
        return 0;
478
0
    }
479
480
    /*
481
     * If outlen is specified, then it must report the length
482
     * of the out buffer, so that we can confirm that it is of
483
     * sufficient size to hold the output of decapsulation
484
     */
485
0
    if (outlen != NULL && *outlen < nlen) {
486
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_OUTPUT_LENGTH);
487
0
        return 0;
488
0
    }
489
490
    /* Step (3): out = RSADP((n,d), in) */
491
0
    ret = RSA_private_decrypt((int)inlen, in, out, prsactx->rsa, RSA_NO_PADDING);
492
0
    if (ret > 0 && outlen != NULL)
493
0
        *outlen = ret;
494
0
    return ret > 0;
495
0
}
496
497
static int rsakem_generate(void *vprsactx, unsigned char *out, size_t *outlen,
498
                           unsigned char *secret, size_t *secretlen)
499
0
{
500
0
    PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx;
501
502
0
    if (!ossl_prov_is_running())
503
0
        return 0;
504
505
0
    switch (prsactx->op) {
506
0
        case KEM_OP_RSASVE:
507
0
            return rsasve_generate(prsactx, out, outlen, secret, secretlen);
508
0
        default:
509
0
            return -2;
510
0
    }
511
0
}
512
513
static int rsakem_recover(void *vprsactx, unsigned char *out, size_t *outlen,
514
                          const unsigned char *in, size_t inlen)
515
0
{
516
0
    PROV_RSA_CTX *prsactx = (PROV_RSA_CTX *)vprsactx;
517
518
0
    if (!ossl_prov_is_running())
519
0
        return 0;
520
521
0
    switch (prsactx->op) {
522
0
        case KEM_OP_RSASVE:
523
0
            return rsasve_recover(prsactx, out, outlen, in, inlen);
524
0
        default:
525
0
            return -2;
526
0
    }
527
0
}
528
529
const OSSL_DISPATCH ossl_rsa_asym_kem_functions[] = {
530
    { OSSL_FUNC_KEM_NEWCTX, (void (*)(void))rsakem_newctx },
531
    { OSSL_FUNC_KEM_ENCAPSULATE_INIT,
532
      (void (*)(void))rsakem_encapsulate_init },
533
    { OSSL_FUNC_KEM_ENCAPSULATE, (void (*)(void))rsakem_generate },
534
    { OSSL_FUNC_KEM_DECAPSULATE_INIT,
535
      (void (*)(void))rsakem_decapsulate_init },
536
    { OSSL_FUNC_KEM_DECAPSULATE, (void (*)(void))rsakem_recover },
537
    { OSSL_FUNC_KEM_FREECTX, (void (*)(void))rsakem_freectx },
538
    { OSSL_FUNC_KEM_DUPCTX, (void (*)(void))rsakem_dupctx },
539
    { OSSL_FUNC_KEM_GET_CTX_PARAMS,
540
      (void (*)(void))rsakem_get_ctx_params },
541
    { OSSL_FUNC_KEM_GETTABLE_CTX_PARAMS,
542
      (void (*)(void))rsakem_gettable_ctx_params },
543
    { OSSL_FUNC_KEM_SET_CTX_PARAMS,
544
      (void (*)(void))rsakem_set_ctx_params },
545
    { OSSL_FUNC_KEM_SETTABLE_CTX_PARAMS,
546
      (void (*)(void))rsakem_settable_ctx_params },
547
    OSSL_DISPATCH_END
548
};