Coverage Report

Created: 2026-10-16 07:07

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