Coverage Report

Created: 2026-08-12 06:14

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