Coverage Report

Created: 2025-12-10 06:24

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