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