Coverage Report

Created: 2026-09-12 06:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl40/providers/implementations/keymgmt/ml_kem_kmgmt.c
Line
Count
Source
1
/*
2
 * Copyright 2024-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 <openssl/core_dispatch.h>
11
#include <openssl/core_names.h>
12
#include <openssl/params.h>
13
#include <openssl/err.h>
14
#include <openssl/proverr.h>
15
#include <openssl/provider.h>
16
#include <openssl/rand.h>
17
#include <openssl/self_test.h>
18
#include <openssl/param_build.h>
19
#include <openssl/cms.h>
20
#include "crypto/ml_kem.h"
21
#include "internal/fips.h"
22
#include "internal/param_build_set.h"
23
#include "internal/sizes.h"
24
#include "prov/der_hkdf.h"
25
#include "prov/der_wrap.h"
26
#include "prov/implementations.h"
27
#include "prov/providercommon.h"
28
#include "prov/provider_ctx.h"
29
#include "prov/securitycheck.h"
30
#include "prov/ml_kem.h"
31
#include "providers/implementations/keymgmt/ml_kem_kmgmt.inc"
32
33
static OSSL_FUNC_keymgmt_new_fn ml_kem_512_new;
34
static OSSL_FUNC_keymgmt_new_fn ml_kem_768_new;
35
static OSSL_FUNC_keymgmt_new_fn ml_kem_1024_new;
36
static OSSL_FUNC_keymgmt_free_fn ml_kem_free_key;
37
static OSSL_FUNC_keymgmt_gen_fn ml_kem_gen;
38
static OSSL_FUNC_keymgmt_gen_init_fn ml_kem_512_gen_init;
39
static OSSL_FUNC_keymgmt_gen_init_fn ml_kem_768_gen_init;
40
static OSSL_FUNC_keymgmt_gen_init_fn ml_kem_1024_gen_init;
41
static OSSL_FUNC_keymgmt_gen_cleanup_fn ml_kem_gen_cleanup;
42
static OSSL_FUNC_keymgmt_gen_set_params_fn ml_kem_gen_set_params;
43
static OSSL_FUNC_keymgmt_gen_settable_params_fn ml_kem_gen_settable_params;
44
#ifndef FIPS_MODULE
45
static OSSL_FUNC_keymgmt_load_fn ml_kem_load;
46
#endif
47
static OSSL_FUNC_keymgmt_get_params_fn ml_kem_get_params;
48
static OSSL_FUNC_keymgmt_gettable_params_fn ml_kem_gettable_params;
49
static OSSL_FUNC_keymgmt_set_params_fn ml_kem_set_params;
50
static OSSL_FUNC_keymgmt_settable_params_fn ml_kem_settable_params;
51
static OSSL_FUNC_keymgmt_has_fn ml_kem_has;
52
static OSSL_FUNC_keymgmt_match_fn ml_kem_match;
53
static OSSL_FUNC_keymgmt_validate_fn ml_kem_validate;
54
static OSSL_FUNC_keymgmt_import_fn ml_kem_import;
55
static OSSL_FUNC_keymgmt_export_fn ml_kem_export;
56
static OSSL_FUNC_keymgmt_import_types_fn ml_kem_imexport_types;
57
static OSSL_FUNC_keymgmt_export_types_fn ml_kem_imexport_types;
58
static OSSL_FUNC_keymgmt_dup_fn ml_kem_dup;
59
60
static const int minimal_selection = OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS
61
    | OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
62
63
typedef struct ml_kem_gen_ctx_st {
64
    PROV_CTX *provctx;
65
    char *propq;
66
    int selection;
67
    int evp_type;
68
    uint8_t seedbuf[ML_KEM_SEED_BYTES];
69
    uint8_t *seed;
70
} PROV_ML_KEM_GEN_CTX;
71
72
static int ml_kem_pairwise_test(const ML_KEM_KEY *key, int key_flags)
73
30
{
74
#ifdef FIPS_MODULE
75
    OSSL_SELF_TEST *st = NULL;
76
    OSSL_CALLBACK *cb = NULL;
77
    void *cbarg = NULL;
78
#endif
79
30
    unsigned char entropy[ML_KEM_RANDOM_BYTES];
80
30
    unsigned char secret[ML_KEM_SHARED_SECRET_BYTES];
81
30
    unsigned char out[ML_KEM_SHARED_SECRET_BYTES];
82
30
    unsigned char *ctext = NULL;
83
30
    const ML_KEM_VINFO *v = ossl_ml_kem_key_vinfo(key);
84
30
    int operation_result = 0;
85
30
    int ret = 0;
86
87
    /* Unless we have both a public and private key, we can't do the test */
88
30
    if (!ossl_ml_kem_have_prvkey(key)
89
30
        || !ossl_ml_kem_have_pubkey(key)
90
30
        || (key_flags & ML_KEM_KEY_PCT_TYPE) == 0)
91
0
        return 1;
92
#ifdef FIPS_MODULE
93
    /* During self test, it is a waste to do this test */
94
    if (ossl_fips_self_testing()
95
        || ossl_self_test_in_progress(ST_ID_ASYM_KEYGEN_ML_KEM)
96
        || ossl_self_test_in_progress(ST_ID_KEM_ML_KEM))
97
        return 1;
98
99
    /*
100
     * The functions `OSSL_SELF_TEST_*` will return directly if parameter `st`
101
     * is NULL.
102
     */
103
    OSSL_SELF_TEST_get_callback(key->libctx, &cb, &cbarg);
104
105
    st = OSSL_SELF_TEST_new(cb, cbarg);
106
    if (st == NULL)
107
        return 0;
108
109
    OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
110
        OSSL_SELF_TEST_DESC_PCT_ML_KEM);
111
#endif /* FIPS_MODULE */
112
113
30
    ctext = OPENSSL_malloc(v->ctext_bytes);
114
30
    if (ctext == NULL)
115
0
        goto err;
116
117
30
    memset(out, 0, sizeof(out));
118
119
30
    if (key_flags & ML_KEM_KEY_RANDOM_PCT) {
120
30
        operation_result = ossl_ml_kem_encap_rand(ctext, v->ctext_bytes,
121
30
            secret, sizeof(secret), key);
122
30
    } else {
123
0
        memset(entropy, 0125, sizeof(entropy));
124
0
        operation_result = ossl_ml_kem_encap_seed(ctext, v->ctext_bytes,
125
0
            secret, sizeof(secret),
126
0
            entropy, sizeof(entropy),
127
0
            key);
128
0
    }
129
30
    if (operation_result != 1)
130
0
        goto err;
131
132
#ifdef FIPS_MODULE
133
    OSSL_SELF_TEST_oncorrupt_byte(st, ctext);
134
#endif
135
136
30
    operation_result = ossl_ml_kem_decap(out, sizeof(out), ctext, v->ctext_bytes,
137
30
        key);
138
30
    if (operation_result != 1 || memcmp(out, secret, sizeof(out)) != 0)
139
0
        goto err;
140
141
30
    ret = 1;
142
30
err:
143
#ifdef FIPS_MODULE
144
    OSSL_SELF_TEST_onend(st, ret);
145
    OSSL_SELF_TEST_free(st);
146
#else
147
30
    if (ret == 0) {
148
0
        ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY,
149
0
            "public part of %s private key fails to match private",
150
0
            v->algorithm_name);
151
0
    }
152
30
#endif
153
30
    OPENSSL_cleanse((void *)entropy, sizeof(entropy));
154
30
    OPENSSL_cleanse((void *)secret, sizeof(secret));
155
30
    OPENSSL_cleanse((void *)out, sizeof(out));
156
30
    OPENSSL_clear_free(ctext, v->ctext_bytes);
157
30
    return ret;
158
30
}
159
160
ML_KEM_KEY *ossl_prov_ml_kem_new(PROV_CTX *ctx, const char *propq, int evp_type)
161
63.9k
{
162
63.9k
    ML_KEM_KEY *key;
163
164
63.9k
    if (!ossl_prov_is_running())
165
0
        return NULL;
166
167
#ifdef FIPS_MODULE
168
    if (!ossl_deferred_self_test(PROV_LIBCTX_OF(ctx),
169
            ST_ID_ASYM_KEYGEN_ML_KEM))
170
        return NULL;
171
#endif
172
173
    /*
174
     * When decoding, if the key ends up "loaded" into the same provider, these
175
     * are the correct config settings, otherwise, new values will be assigned
176
     * on import into a different provider.  The "load" API does not pass along
177
     * the provider context.
178
     */
179
63.9k
    if ((key = ossl_ml_kem_key_new(PROV_LIBCTX_OF(ctx), propq, evp_type)) != NULL) {
180
63.9k
        const char *pct_type = ossl_prov_ctx_get_param(
181
63.9k
            ctx, OSSL_PKEY_PARAM_ML_KEM_IMPORT_PCT_TYPE, "random");
182
183
63.9k
        if (ossl_prov_ctx_get_bool_param(
184
63.9k
                ctx, OSSL_PKEY_PARAM_ML_KEM_RETAIN_SEED, 1))
185
63.9k
            key->prov_flags |= ML_KEM_KEY_RETAIN_SEED;
186
0
        else
187
0
            key->prov_flags &= ~ML_KEM_KEY_RETAIN_SEED;
188
63.9k
        if (ossl_prov_ctx_get_bool_param(
189
63.9k
                ctx, OSSL_PKEY_PARAM_ML_KEM_PREFER_SEED, 1))
190
63.9k
            key->prov_flags |= ML_KEM_KEY_PREFER_SEED;
191
0
        else
192
0
            key->prov_flags &= ~ML_KEM_KEY_PREFER_SEED;
193
63.9k
        if (OPENSSL_strcasecmp(pct_type, "random") == 0)
194
63.9k
            key->prov_flags |= ML_KEM_KEY_RANDOM_PCT;
195
0
        else if (OPENSSL_strcasecmp(pct_type, "fixed") == 0)
196
0
            key->prov_flags |= ML_KEM_KEY_FIXED_PCT;
197
0
        else
198
0
            key->prov_flags &= ~ML_KEM_KEY_PCT_TYPE;
199
63.9k
    }
200
63.9k
    return key;
201
63.9k
}
202
203
static int ml_kem_has(const void *vkey, int selection)
204
706
{
205
706
    const ML_KEM_KEY *key = vkey;
206
207
    /* A NULL key MUST fail to have anything */
208
706
    if (!ossl_prov_is_running() || key == NULL)
209
0
        return 0;
210
211
706
    switch (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) {
212
87
    case 0:
213
87
        return 1;
214
403
    case OSSL_KEYMGMT_SELECT_PUBLIC_KEY:
215
403
        return ossl_ml_kem_have_pubkey(key);
216
216
    default:
217
216
        return ossl_ml_kem_have_prvkey(key);
218
706
    }
219
706
}
220
221
static int ml_kem_match(const void *vkey1, const void *vkey2, int selection)
222
150
{
223
150
    const ML_KEM_KEY *key1 = vkey1;
224
150
    const ML_KEM_KEY *key2 = vkey2;
225
226
150
    if (!ossl_prov_is_running())
227
0
        return 0;
228
229
    /* All we have that can be compared is key material */
230
150
    if (!(selection & OSSL_KEYMGMT_SELECT_KEYPAIR))
231
0
        return 1;
232
233
150
    return ossl_ml_kem_pubkey_cmp(key1, key2);
234
150
}
235
236
static int ml_kem_validate(const void *vkey, int selection, int check_type)
237
340
{
238
340
    const ML_KEM_KEY *key = vkey;
239
240
340
    if (!ml_kem_has(key, selection))
241
110
        return 0;
242
243
230
    if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == OSSL_KEYMGMT_SELECT_KEYPAIR)
244
30
        return ml_kem_pairwise_test(key, ML_KEM_KEY_RANDOM_PCT);
245
200
    return 1;
246
230
}
247
248
static int ml_kem_export(void *vkey, int selection, OSSL_CALLBACK *param_cb,
249
    void *cbarg)
250
33.7k
{
251
33.7k
    ML_KEM_KEY *key = vkey;
252
33.7k
    OSSL_PARAM_BLD *tmpl = NULL;
253
33.7k
    OSSL_PARAM *params = NULL;
254
33.7k
    const ML_KEM_VINFO *v;
255
33.7k
    uint8_t *pubenc = NULL, *prvenc = NULL, *seedenc = NULL;
256
33.7k
    size_t prvlen = 0, seedlen = 0;
257
33.7k
    int ret = 0;
258
259
33.7k
    if (!ossl_prov_is_running() || key == NULL)
260
0
        return 0;
261
262
33.7k
    if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
263
0
        return 0;
264
265
33.7k
    v = ossl_ml_kem_key_vinfo(key);
266
33.7k
    if (!ossl_ml_kem_have_pubkey(key)) {
267
        /* Fail when no key material can be returned */
268
0
        if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) == 0
269
0
            || !ossl_ml_kem_decoded_key(key)) {
270
0
            ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
271
0
            return 0;
272
0
        }
273
33.7k
    } else if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
274
33.7k
        pubenc = OPENSSL_malloc(v->pubkey_bytes);
275
33.7k
        if (pubenc == NULL
276
33.7k
            || !ossl_ml_kem_encode_public_key(pubenc, v->pubkey_bytes, key))
277
0
            goto err;
278
33.7k
    }
279
280
33.7k
    if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
281
        /*
282
         * The seed and/or private key material are allocated on the secure
283
         * heap if configured, ossl_param_build_set_octet_string(), will then
284
         * also use the secure heap.
285
         */
286
12
        if (ossl_ml_kem_have_seed(key)) {
287
12
            seedlen = ML_KEM_SEED_BYTES;
288
12
            if ((seedenc = OPENSSL_secure_zalloc(seedlen)) == NULL
289
12
                || !ossl_ml_kem_encode_seed(seedenc, seedlen, key))
290
0
                goto err;
291
12
        }
292
12
        if (ossl_ml_kem_have_prvkey(key)) {
293
12
            prvlen = v->prvkey_bytes;
294
12
            if ((prvenc = OPENSSL_secure_zalloc(prvlen)) == NULL
295
12
                || !ossl_ml_kem_encode_private_key(prvenc, prvlen, key))
296
0
                goto err;
297
12
        } else if (ossl_ml_kem_have_dkenc(key)) {
298
0
            prvlen = v->prvkey_bytes;
299
0
            if ((prvenc = OPENSSL_secure_zalloc(prvlen)) == NULL)
300
0
                goto err;
301
0
            memcpy(prvenc, key->encoded_dk, prvlen);
302
0
        }
303
12
    }
304
305
33.7k
    tmpl = OSSL_PARAM_BLD_new();
306
33.7k
    if (tmpl == NULL)
307
0
        goto err;
308
309
    /* The (d, z) seed, when available and private keys are requested. */
310
33.7k
    if (seedenc != NULL
311
12
        && !ossl_param_build_set_octet_string(
312
12
            tmpl, params, OSSL_PKEY_PARAM_ML_KEM_SEED, seedenc, seedlen))
313
0
        goto err;
314
315
    /* The private key in the FIPS 203 |dk| format, when requested. */
316
33.7k
    if (prvenc != NULL
317
12
        && !ossl_param_build_set_octet_string(
318
12
            tmpl, params, OSSL_PKEY_PARAM_PRIV_KEY, prvenc, prvlen))
319
0
        goto err;
320
321
    /* The public key on request; it is always available when either is */
322
33.7k
    if (pubenc != NULL
323
33.7k
        && !ossl_param_build_set_octet_string(
324
33.7k
            tmpl, params, OSSL_PKEY_PARAM_PUB_KEY, pubenc, v->pubkey_bytes))
325
0
        goto err;
326
327
33.7k
    params = OSSL_PARAM_BLD_to_param(tmpl);
328
33.7k
    if (params == NULL)
329
0
        goto err;
330
331
33.7k
    ret = param_cb(params, cbarg);
332
33.7k
    OSSL_PARAM_clear_free(params);
333
334
33.7k
err:
335
33.7k
    OSSL_PARAM_BLD_free(tmpl);
336
33.7k
    OPENSSL_secure_clear_free(seedenc, seedlen);
337
33.7k
    OPENSSL_secure_clear_free(prvenc, prvlen);
338
33.7k
    OPENSSL_clear_free(pubenc, v->pubkey_bytes);
339
33.7k
    return ret;
340
33.7k
}
341
342
static const OSSL_PARAM *ml_kem_imexport_types(int selection)
343
0
{
344
0
    if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0)
345
0
        return ml_kem_key_type_params_list;
346
0
    return NULL;
347
0
}
348
349
static int check_seed(const uint8_t *seed, const uint8_t *prvenc,
350
    ML_KEM_KEY *key)
351
0
{
352
0
    size_t zlen = ML_KEM_RANDOM_BYTES;
353
354
0
    if (memcmp(seed + ML_KEM_SEED_BYTES - zlen,
355
0
            prvenc + key->vinfo->prvkey_bytes - zlen, zlen)
356
0
        == 0)
357
0
        return 1;
358
0
    ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY,
359
0
        "private %s key implicit rejection secret does"
360
0
        " not match seed",
361
0
        key->vinfo->algorithm_name);
362
0
    return 0;
363
0
}
364
365
static int check_prvenc(const uint8_t *prvenc, ML_KEM_KEY *key)
366
0
{
367
0
    size_t len = key->vinfo->prvkey_bytes;
368
0
    uint8_t *buf = OPENSSL_malloc(len);
369
0
    int ret = 0;
370
371
0
    if (buf != NULL
372
0
        && ossl_ml_kem_encode_private_key(buf, len, key))
373
0
        ret = memcmp(buf, prvenc, len) == 0;
374
0
    OPENSSL_clear_free(buf, len);
375
0
    if (ret)
376
0
        return 1;
377
378
0
    if (buf != NULL)
379
0
        ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY,
380
0
            "explicit %s private key does not match seed",
381
0
            key->vinfo->algorithm_name);
382
0
    ossl_ml_kem_key_reset(key);
383
0
    return 0;
384
0
}
385
386
static int ml_kem_key_fromdata(ML_KEM_KEY *key,
387
    const OSSL_PARAM params[],
388
    int include_private)
389
120
{
390
120
    const void *pubenc = NULL, *prvenc = NULL, *seedenc = NULL;
391
120
    size_t publen = 0, prvlen = 0, seedlen = 0, puboff;
392
120
    const ML_KEM_VINFO *v;
393
120
    struct ml_kem_key_type_params_st p;
394
395
    /* Invalid attempt to mutate a key, what is the right error to report? */
396
120
    if (key == NULL
397
120
        || ossl_ml_kem_have_pubkey(key)
398
120
        || !ml_kem_key_type_params_decoder(params, &p))
399
0
        return 0;
400
120
    v = ossl_ml_kem_key_vinfo(key);
401
402
    /*
403
     * When a private key is provided, without a seed, any public key also
404
     * provided will be ignored (apart from length), just as with the seed.
405
     */
406
120
    if (p.seed != NULL && include_private) {
407
        /*
408
         * When a seed is provided, the private and public keys may be ignored,
409
         * after validating just their lengths.  Comparing encodings or hashes
410
         * when applicable is possible, but not currently implemented.
411
         */
412
0
        if (OSSL_PARAM_get_octet_string_ptr(p.seed, &seedenc, &seedlen) != 1)
413
0
            return 0;
414
0
        if (seedlen != 0 && seedlen != ML_KEM_SEED_BYTES) {
415
0
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_SEED_LENGTH);
416
0
            return 0;
417
0
        }
418
0
    }
419
420
120
    if (p.privkey != NULL && include_private) {
421
66
        if (OSSL_PARAM_get_octet_string_ptr(p.privkey, &prvenc, &prvlen) != 1)
422
0
            return 0;
423
66
        if (prvlen != 0 && prvlen != v->prvkey_bytes) {
424
39
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
425
39
            return 0;
426
39
        }
427
66
    }
428
429
    /* Used only when no seed or private key is provided. */
430
81
    if (p.pubkey != NULL) {
431
54
        if (OSSL_PARAM_get_octet_string_ptr(p.pubkey, &pubenc, &publen) != 1)
432
0
            return 0;
433
54
        if (publen != 0 && publen != v->pubkey_bytes) {
434
28
            ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
435
28
            return 0;
436
28
        }
437
54
    }
438
439
    /* The caller MUST specify at least one of seed, private or public keys. */
440
53
    if (seedlen == 0 && publen == 0 && prvlen == 0) {
441
2
        ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
442
2
        return 0;
443
2
    }
444
445
    /* Check any explicit public key against embedded value in private key */
446
51
    if (publen > 0 && prvlen > 0) {
447
        /* point to the ek offset in dk = DKpke||ek||H(ek)||z */
448
0
        puboff = prvlen - ML_KEM_RANDOM_BYTES - ML_KEM_PKHASH_BYTES - publen;
449
0
        if (memcmp(pubenc, (unsigned char *)prvenc + puboff, publen) != 0) {
450
0
            ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY,
451
0
                "explicit %s public key does not match private",
452
0
                v->algorithm_name);
453
0
            return 0;
454
0
        }
455
0
    }
456
457
51
    if (seedlen != 0
458
0
        && (prvlen == 0 || (key->prov_flags & ML_KEM_KEY_PREFER_SEED))) {
459
0
        if (prvlen != 0 && !check_seed(seedenc, prvenc, key))
460
0
            return 0;
461
0
        if (!ossl_ml_kem_set_seed(seedenc, seedlen, key)
462
0
            || !ossl_ml_kem_genkey(NULL, 0, key))
463
0
            return 0;
464
0
        return prvlen == 0 || check_prvenc(prvenc, key);
465
51
    } else if (prvlen != 0) {
466
27
        return ossl_ml_kem_parse_private_key(prvenc, prvlen, key);
467
27
    }
468
24
    return ossl_ml_kem_parse_public_key(pubenc, publen, key);
469
51
}
470
471
static int ml_kem_import(void *vkey, int selection, const OSSL_PARAM params[])
472
178
{
473
178
    ML_KEM_KEY *key = vkey;
474
178
    int include_private;
475
178
    int res;
476
477
178
    if (!ossl_prov_is_running() || key == NULL)
478
0
        return 0;
479
480
178
    if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
481
0
        return 0;
482
483
178
    include_private = selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0;
484
178
    res = ml_kem_key_fromdata(key, params, include_private);
485
178
    if (res > 0 && include_private
486
0
        && !ml_kem_pairwise_test(key, key->prov_flags)) {
487
0
        ossl_ml_kem_key_reset(key);
488
0
        res = 0;
489
0
    }
490
178
    return res;
491
178
}
492
493
static const OSSL_PARAM *ml_kem_gettable_params(void *provctx)
494
0
{
495
0
    return ml_kem_get_params_list;
496
0
}
497
498
#ifndef FIPS_MODULE
499
static void *ml_kem_load(const void *reference, size_t reference_sz)
500
447
{
501
447
    ML_KEM_KEY *key = NULL;
502
447
    uint8_t *encoded_dk = NULL;
503
447
    uint8_t seed[ML_KEM_SEED_BYTES];
504
505
447
    if (ossl_prov_is_running() && reference_sz == sizeof(key)) {
506
        /* The contents of the reference is the address to our object */
507
447
        key = *(ML_KEM_KEY **)reference;
508
447
        encoded_dk = key->encoded_dk;
509
447
        key->encoded_dk = NULL;
510
        /* We grabbed, so we detach it */
511
447
        *(ML_KEM_KEY **)reference = NULL;
512
447
        if (encoded_dk != NULL
513
47
            && ossl_ml_kem_encode_seed(seed, sizeof(seed), key)
514
0
            && !check_seed(seed, encoded_dk, key))
515
0
            goto err;
516
        /* Generate the key now, if it holds only a stashed seed. */
517
447
        if (ossl_ml_kem_have_seed(key)
518
76
            && (encoded_dk == NULL
519
76
                || (key->prov_flags & ML_KEM_KEY_PREFER_SEED))) {
520
76
            if (!ossl_ml_kem_genkey(NULL, 0, key)
521
76
                || (encoded_dk != NULL && !check_prvenc(encoded_dk, key)))
522
0
                goto err;
523
371
        } else if (encoded_dk != NULL) {
524
47
            if (!ossl_ml_kem_parse_private_key(encoded_dk,
525
47
                    key->vinfo->prvkey_bytes, key)) {
526
47
                ERR_raise_data(ERR_LIB_PROV, PROV_R_INVALID_KEY,
527
47
                    "error parsing %s private key",
528
47
                    key->vinfo->algorithm_name);
529
47
                goto err;
530
47
            }
531
0
            if (!ml_kem_pairwise_test(key, key->prov_flags))
532
0
                goto err;
533
0
        }
534
400
        OPENSSL_secure_clear_free(encoded_dk, key->vinfo->prvkey_bytes);
535
400
        OPENSSL_cleanse((void *)seed, sizeof(seed));
536
400
        return key;
537
447
    }
538
539
47
err:
540
47
    if (key != NULL && key->vinfo != NULL)
541
47
        OPENSSL_secure_clear_free(encoded_dk, key->vinfo->prvkey_bytes);
542
47
    OPENSSL_cleanse((void *)seed, sizeof(seed));
543
47
    ossl_ml_kem_key_free(key);
544
47
    return NULL;
545
447
}
546
#endif
547
548
static int ml_kem_get_key_param(const ML_KEM_KEY *key, OSSL_PARAM *p,
549
    size_t bytes,
550
    int (*get_f)(uint8_t *out, size_t len,
551
        const ML_KEM_KEY *key))
552
0
{
553
0
    if (p->data_type != OSSL_PARAM_OCTET_STRING)
554
0
        return 0;
555
0
    p->return_size = bytes;
556
0
    if (p->data != NULL)
557
0
        if (p->data_size < p->return_size
558
0
            || !(*get_f)(p->data, p->return_size, key))
559
0
            return 0;
560
0
    return 1;
561
0
}
562
563
/*
564
 * It is assumed the key is guaranteed non-NULL here, and is from this provider
565
 */
566
static int ml_kem_get_params(void *vkey, OSSL_PARAM params[])
567
48.8k
{
568
48.8k
    ML_KEM_KEY *key = vkey;
569
48.8k
    const ML_KEM_VINFO *v;
570
48.8k
    struct ml_kem_get_params_st p;
571
572
48.8k
    if (key == NULL || !ml_kem_get_params_decoder(params, &p))
573
0
        return 0;
574
575
48.8k
    v = ossl_ml_kem_key_vinfo(key);
576
577
48.8k
    if (p.bits != NULL && !OSSL_PARAM_set_size_t(p.bits, v->bits))
578
0
        return 0;
579
580
48.8k
    if (p.secbits != NULL && !OSSL_PARAM_set_size_t(p.secbits, v->secbits))
581
0
        return 0;
582
583
48.8k
    if (p.maxsize != NULL && !OSSL_PARAM_set_size_t(p.maxsize, v->ctext_bytes))
584
0
        return 0;
585
586
48.8k
    if (p.seccat != NULL && !OSSL_PARAM_set_int(p.seccat, v->security_category))
587
0
        return 0;
588
589
48.8k
    if (p.pubkey != NULL && ossl_ml_kem_have_pubkey(key)) {
590
        /* Exported to EVP_PKEY_get_raw_public_key() */
591
0
        if (!ml_kem_get_key_param(key, p.pubkey, v->pubkey_bytes,
592
0
                &ossl_ml_kem_encode_public_key))
593
0
            return 0;
594
0
    }
595
596
48.8k
    if (p.encpubkey != NULL && ossl_ml_kem_have_pubkey(key)) {
597
        /* Needed by EVP_PKEY_get1_encoded_public_key() */
598
0
        if (!ml_kem_get_key_param(key, p.encpubkey, v->pubkey_bytes,
599
0
                &ossl_ml_kem_encode_public_key))
600
0
            return 0;
601
0
    }
602
603
48.8k
    if (p.privkey != NULL && ossl_ml_kem_have_prvkey(key)) {
604
        /* Exported to EVP_PKEY_get_raw_private_key() */
605
0
        if (!ml_kem_get_key_param(key, p.privkey, v->prvkey_bytes,
606
0
                &ossl_ml_kem_encode_private_key))
607
0
            return 0;
608
0
    }
609
610
48.8k
    if (p.seed != NULL && ossl_ml_kem_have_seed(key)) {
611
        /* Exported for import */
612
0
        if (!ml_kem_get_key_param(key, p.seed, ML_KEM_SEED_BYTES,
613
0
                &ossl_ml_kem_encode_seed))
614
0
            return 0;
615
0
    }
616
617
48.8k
#ifndef OPENSSL_NO_CMS
618
48.8k
    if (p.ri_type != NULL && !OSSL_PARAM_set_int(p.ri_type, CMS_RECIPINFO_KEM))
619
0
        return 0;
620
621
48.8k
    if (p.kemri_kdf_alg != NULL) {
622
0
        uint8_t aid_buf[OSSL_MAX_ALGORITHM_ID_SIZE];
623
0
        int ret;
624
0
        size_t aid_len = 0;
625
0
        WPACKET pkt;
626
0
        uint8_t *aid = NULL;
627
628
0
        ret = WPACKET_init_der(&pkt, aid_buf, sizeof(aid_buf));
629
0
        ret &= ossl_DER_w_begin_sequence(&pkt, -1)
630
0
            && ossl_DER_w_precompiled(&pkt, -1, ossl_der_oid_id_alg_hkdf_with_sha256,
631
0
                sizeof(ossl_der_oid_id_alg_hkdf_with_sha256))
632
0
            && ossl_DER_w_end_sequence(&pkt, -1);
633
0
        if (ret && WPACKET_finish(&pkt)) {
634
0
            WPACKET_get_total_written(&pkt, &aid_len);
635
0
            aid = WPACKET_get_curr(&pkt);
636
0
        }
637
0
        WPACKET_cleanup(&pkt);
638
0
        if (!ret)
639
0
            return 0;
640
0
        if (aid != NULL && aid_len != 0 && !OSSL_PARAM_set_octet_string(p.kemri_kdf_alg, aid, aid_len))
641
0
            return 0;
642
0
    }
643
48.8k
#endif
644
645
48.8k
    return 1;
646
48.8k
}
647
648
static const OSSL_PARAM *ml_kem_settable_params(void *provctx)
649
0
{
650
0
    return ml_kem_set_params_list;
651
0
}
652
653
static int ml_kem_set_params(void *vkey, const OSSL_PARAM params[])
654
0
{
655
0
    ML_KEM_KEY *key = vkey;
656
0
    const void *pubenc = NULL;
657
0
    size_t publen = 0;
658
0
    struct ml_kem_set_params_st p;
659
660
0
    if (key == NULL || !ml_kem_set_params_decoder(params, &p))
661
0
        return 0;
662
663
    /* Used in TLS via EVP_PKEY_set1_encoded_public_key(). */
664
0
    if (p.pub != NULL
665
0
        && (OSSL_PARAM_get_octet_string_ptr(p.pub, &pubenc, &publen) != 1
666
0
            || publen != key->vinfo->pubkey_bytes)) {
667
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY);
668
0
        return 0;
669
0
    }
670
671
0
    if (publen == 0)
672
0
        return 1;
673
674
    /* Key mutation is reportedly generally not allowed */
675
0
    if (ossl_ml_kem_have_pubkey(key)) {
676
0
        ERR_raise_data(ERR_LIB_PROV,
677
0
            PROV_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE,
678
0
            "ML-KEM keys cannot be mutated");
679
0
        return 0;
680
0
    }
681
682
0
    return ossl_ml_kem_parse_public_key(pubenc, publen, key);
683
0
}
684
685
static int ml_kem_gen_set_params(void *vgctx, const OSSL_PARAM params[])
686
96.4k
{
687
96.4k
    PROV_ML_KEM_GEN_CTX *gctx = vgctx;
688
96.4k
    struct ml_kem_gen_set_params_st p;
689
690
96.4k
    if (gctx == NULL || !ml_kem_gen_set_params_decoder(params, &p))
691
0
        return 0;
692
693
96.4k
    if (p.propq != NULL) {
694
0
        if (p.propq->data_type != OSSL_PARAM_UTF8_STRING)
695
0
            return 0;
696
0
        OPENSSL_free(gctx->propq);
697
0
        if ((gctx->propq = OPENSSL_strdup(p.propq->data)) == NULL)
698
0
            return 0;
699
0
    }
700
701
96.4k
    if (p.seed != NULL) {
702
0
        size_t len = ML_KEM_SEED_BYTES;
703
704
0
        gctx->seed = gctx->seedbuf;
705
0
        if (OSSL_PARAM_get_octet_string(p.seed, (void **)&gctx->seed, len, &len)
706
0
            && len == ML_KEM_SEED_BYTES)
707
0
            return 1;
708
709
        /* Possibly, but less likely wrong data type */
710
0
        ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_SEED_LENGTH);
711
0
        OPENSSL_cleanse((void *)gctx->seedbuf, sizeof(gctx->seedbuf));
712
0
        gctx->seed = NULL;
713
0
        return 0;
714
0
    }
715
716
96.4k
    return 1;
717
96.4k
}
718
719
static void *ml_kem_gen_init(void *provctx, int selection,
720
    const OSSL_PARAM params[], int evp_type)
721
63.5k
{
722
63.5k
    PROV_ML_KEM_GEN_CTX *gctx = NULL;
723
724
    /*
725
     * We can only generate private keys, check that the selection is
726
     * appropriate.
727
     */
728
63.5k
    if (!ossl_prov_is_running()
729
63.5k
        || (selection & minimal_selection) == 0
730
63.5k
        || (gctx = OPENSSL_zalloc(sizeof(*gctx))) == NULL)
731
0
        return NULL;
732
733
63.5k
    gctx->selection = selection;
734
63.5k
    gctx->evp_type = evp_type;
735
63.5k
    gctx->provctx = provctx;
736
63.5k
    if (ml_kem_gen_set_params(gctx, params))
737
63.5k
        return gctx;
738
739
0
    ml_kem_gen_cleanup(gctx);
740
0
    return NULL;
741
63.5k
}
742
743
static const OSSL_PARAM *ml_kem_gen_settable_params(ossl_unused void *vgctx,
744
    ossl_unused void *provctx)
745
0
{
746
0
    return ml_kem_gen_set_params_list;
747
0
}
748
749
static void *ml_kem_gen(void *vgctx, OSSL_CALLBACK *osslcb, void *cbarg)
750
63.5k
{
751
63.5k
    PROV_ML_KEM_GEN_CTX *gctx = vgctx;
752
63.5k
    ML_KEM_KEY *key;
753
63.5k
    uint8_t *nopub = NULL;
754
63.5k
    uint8_t *seed;
755
63.5k
    int genok = 0;
756
757
63.5k
    if (gctx == NULL
758
63.5k
        || (gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == OSSL_KEYMGMT_SELECT_PUBLIC_KEY)
759
0
        return NULL;
760
63.5k
    seed = gctx->seed;
761
63.5k
    key = ossl_prov_ml_kem_new(gctx->provctx, gctx->propq, gctx->evp_type);
762
63.5k
    if (key == NULL)
763
0
        return NULL;
764
765
63.5k
    if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
766
0
        return key;
767
768
63.5k
    if (seed != NULL && !ossl_ml_kem_set_seed(seed, ML_KEM_SEED_BYTES, key)) {
769
0
        ossl_ml_kem_key_free(key);
770
0
        return NULL;
771
0
    }
772
63.5k
    genok = ossl_ml_kem_genkey(nopub, 0, key);
773
774
    /* Erase the single-use seed */
775
63.5k
    if (seed != NULL)
776
0
        OPENSSL_cleanse(seed, ML_KEM_SEED_BYTES);
777
63.5k
    gctx->seed = NULL;
778
779
63.5k
    if (genok) {
780
#ifdef FIPS_MODULE
781
        if (!ml_kem_pairwise_test(key, ML_KEM_KEY_FIXED_PCT)) {
782
            ossl_ml_kem_key_free(key);
783
            return NULL;
784
        }
785
#endif /* FIPS_MODULE */
786
63.5k
        return key;
787
63.5k
    }
788
789
0
    ossl_ml_kem_key_free(key);
790
0
    return NULL;
791
63.5k
}
792
793
static void ml_kem_gen_cleanup(void *vgctx)
794
63.5k
{
795
63.5k
    PROV_ML_KEM_GEN_CTX *gctx = vgctx;
796
797
63.5k
    if (gctx == NULL)
798
0
        return;
799
800
63.5k
    if (gctx->seed != NULL)
801
0
        OPENSSL_cleanse(gctx->seed, ML_KEM_SEED_BYTES);
802
63.5k
    OPENSSL_free(gctx->propq);
803
63.5k
    OPENSSL_free(gctx);
804
63.5k
}
805
806
static void *ml_kem_dup(const void *vkey, int selection)
807
85
{
808
85
    const ML_KEM_KEY *key = vkey;
809
810
85
    if (!ossl_prov_is_running())
811
0
        return NULL;
812
813
85
    return ossl_ml_kem_key_dup(key, selection);
814
85
}
815
816
static void ml_kem_free_key(void *keydata)
817
64.2k
{
818
64.2k
    ossl_ml_kem_key_free((ML_KEM_KEY *)keydata);
819
64.2k
}
820
821
#ifndef FIPS_MODULE
822
#define DISPATCH_LOAD_FN \
823
    { OSSL_FUNC_KEYMGMT_LOAD, (OSSL_FUNC)ml_kem_load },
824
#else
825
#define DISPATCH_LOAD_FN /* Non-FIPS only */
826
#endif
827
828
#define DECLARE_VARIANT(bits)                                                             \
829
    static OSSL_FUNC_keymgmt_new_fn ml_kem_##bits##_new;                                  \
830
    static OSSL_FUNC_keymgmt_gen_init_fn ml_kem_##bits##_gen_init;                        \
831
    static void *ml_kem_##bits##_new(void *provctx)                                       \
832
279
    {                                                                                     \
833
279
        return ossl_prov_ml_kem_new(provctx, NULL, EVP_PKEY_ML_KEM_##bits);               \
834
279
    }                                                                                     \
835
    static void *ml_kem_##bits##_gen_init(void *provctx, int selection,                   \
836
        const OSSL_PARAM params[])                                                        \
837
63.5k
    {                                                                                     \
838
63.5k
        return ml_kem_gen_init(provctx, selection, params,                                \
839
63.5k
            EVP_PKEY_ML_KEM_##bits);                                                      \
840
63.5k
    }                                                                                     \
ml_kem_kmgmt.c:ml_kem_512_gen_init
Line
Count
Source
837
307
    {                                                                                     \
838
307
        return ml_kem_gen_init(provctx, selection, params,                                \
839
307
            EVP_PKEY_ML_KEM_##bits);                                                      \
840
307
    }                                                                                     \
ml_kem_kmgmt.c:ml_kem_768_gen_init
Line
Count
Source
837
63.0k
    {                                                                                     \
838
63.0k
        return ml_kem_gen_init(provctx, selection, params,                                \
839
63.0k
            EVP_PKEY_ML_KEM_##bits);                                                      \
840
63.0k
    }                                                                                     \
ml_kem_kmgmt.c:ml_kem_1024_gen_init
Line
Count
Source
837
126
    {                                                                                     \
838
126
        return ml_kem_gen_init(provctx, selection, params,                                \
839
126
            EVP_PKEY_ML_KEM_##bits);                                                      \
840
126
    }                                                                                     \
841
    const OSSL_DISPATCH ossl_ml_kem_##bits##_keymgmt_functions[] = {                      \
842
        { OSSL_FUNC_KEYMGMT_NEW, (OSSL_FUNC)ml_kem_##bits##_new },                        \
843
        { OSSL_FUNC_KEYMGMT_FREE, (OSSL_FUNC)ml_kem_free_key },                           \
844
        { OSSL_FUNC_KEYMGMT_GET_PARAMS, (OSSL_FUNC)ml_kem_get_params },                   \
845
        { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (OSSL_FUNC)ml_kem_gettable_params },         \
846
        { OSSL_FUNC_KEYMGMT_SET_PARAMS, (OSSL_FUNC)ml_kem_set_params },                   \
847
        { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (OSSL_FUNC)ml_kem_settable_params },         \
848
        { OSSL_FUNC_KEYMGMT_HAS, (OSSL_FUNC)ml_kem_has },                                 \
849
        { OSSL_FUNC_KEYMGMT_MATCH, (OSSL_FUNC)ml_kem_match },                             \
850
        { OSSL_FUNC_KEYMGMT_VALIDATE, (OSSL_FUNC)ml_kem_validate },                       \
851
        { OSSL_FUNC_KEYMGMT_GEN_INIT, (OSSL_FUNC)ml_kem_##bits##_gen_init },              \
852
        { OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS, (OSSL_FUNC)ml_kem_gen_set_params },           \
853
        { OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS, (OSSL_FUNC)ml_kem_gen_settable_params }, \
854
        { OSSL_FUNC_KEYMGMT_GEN, (OSSL_FUNC)ml_kem_gen },                                 \
855
        { OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (OSSL_FUNC)ml_kem_gen_cleanup },                 \
856
        DISPATCH_LOAD_FN { OSSL_FUNC_KEYMGMT_DUP, (OSSL_FUNC)ml_kem_dup },                \
857
        { OSSL_FUNC_KEYMGMT_IMPORT, (OSSL_FUNC)ml_kem_import },                           \
858
        { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (OSSL_FUNC)ml_kem_imexport_types },             \
859
        { OSSL_FUNC_KEYMGMT_EXPORT, (OSSL_FUNC)ml_kem_export },                           \
860
        { OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (OSSL_FUNC)ml_kem_imexport_types },             \
861
        OSSL_DISPATCH_END                                                                 \
862
    }
863
63
DECLARE_VARIANT(512);
864
53
DECLARE_VARIANT(768);
865
DECLARE_VARIANT(1024);