Coverage Report

Created: 2026-02-22 06:11

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