xref: /src/crypto/openssl/providers/implementations/keymgmt/mlx_kmgmt.c (revision f25b8c9fb4f58cf61adb47d7570abe7caa6d385d)
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/err.h>
13 #include <openssl/param_build.h>
14 #include <openssl/params.h>
15 #include <openssl/proverr.h>
16 #include <openssl/rand.h>
17 #include <openssl/self_test.h>
18 #include "internal/nelem.h"
19 #include "internal/param_build_set.h"
20 #include "prov/implementations.h"
21 #include "prov/mlx_kem.h"
22 #include "prov/provider_ctx.h"
23 #include "prov/providercommon.h"
24 #include "prov/securitycheck.h"
25 
26 static OSSL_FUNC_keymgmt_gen_fn mlx_kem_gen;
27 static OSSL_FUNC_keymgmt_gen_cleanup_fn mlx_kem_gen_cleanup;
28 static OSSL_FUNC_keymgmt_gen_set_params_fn mlx_kem_gen_set_params;
29 static OSSL_FUNC_keymgmt_gen_settable_params_fn mlx_kem_gen_settable_params;
30 static OSSL_FUNC_keymgmt_get_params_fn mlx_kem_get_params;
31 static OSSL_FUNC_keymgmt_gettable_params_fn mlx_kem_gettable_params;
32 static OSSL_FUNC_keymgmt_set_params_fn mlx_kem_set_params;
33 static OSSL_FUNC_keymgmt_settable_params_fn mlx_kem_settable_params;
34 static OSSL_FUNC_keymgmt_has_fn mlx_kem_has;
35 static OSSL_FUNC_keymgmt_match_fn mlx_kem_match;
36 static OSSL_FUNC_keymgmt_import_fn mlx_kem_import;
37 static OSSL_FUNC_keymgmt_export_fn mlx_kem_export;
38 static OSSL_FUNC_keymgmt_import_types_fn mlx_kem_imexport_types;
39 static OSSL_FUNC_keymgmt_export_types_fn mlx_kem_imexport_types;
40 static OSSL_FUNC_keymgmt_dup_fn mlx_kem_dup;
41 
42 static const int minimal_selection = OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS
43     | OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
44 
45 /* Must match DECLARE_DISPATCH invocations at the end of the file */
46 static const ECDH_VINFO hybrid_vtable[] = {
47     { "EC", "P-256", 65, 32, 32, 1, EVP_PKEY_ML_KEM_768 },
48     { "EC", "P-384", 97, 48, 48, 1, EVP_PKEY_ML_KEM_1024 },
49 #if !defined(OPENSSL_NO_ECX)
50     { "X25519", NULL, 32, 32, 32, 0, EVP_PKEY_ML_KEM_768 },
51     { "X448", NULL, 56, 56, 56, 0, EVP_PKEY_ML_KEM_1024 },
52 #endif
53 };
54 
55 typedef struct mlx_kem_gen_ctx_st {
56     OSSL_LIB_CTX *libctx;
57     char *propq;
58     int selection;
59     unsigned int evp_type;
60 } PROV_ML_KEM_GEN_CTX;
61 
mlx_kem_key_free(void * vkey)62 static void mlx_kem_key_free(void *vkey)
63 {
64     MLX_KEY *key = vkey;
65 
66     if (key == NULL)
67         return;
68     OPENSSL_free(key->propq);
69     EVP_PKEY_free(key->mkey);
70     EVP_PKEY_free(key->xkey);
71     OPENSSL_free(key);
72 }
73 
74 /* Takes ownership of propq */
75 static void *
mlx_kem_key_new(unsigned int v,OSSL_LIB_CTX * libctx,char * propq)76 mlx_kem_key_new(unsigned int v, OSSL_LIB_CTX *libctx, char *propq)
77 {
78     MLX_KEY *key = NULL;
79     unsigned int ml_kem_variant;
80 
81     if (!ossl_prov_is_running()
82         || v >= OSSL_NELEM(hybrid_vtable)
83         || (key = OPENSSL_malloc(sizeof(*key))) == NULL)
84         goto err;
85 
86     ml_kem_variant = hybrid_vtable[v].ml_kem_variant;
87     key->libctx = libctx;
88     key->minfo = ossl_ml_kem_get_vinfo(ml_kem_variant);
89     key->xinfo = &hybrid_vtable[v];
90     key->xkey = key->mkey = NULL;
91     key->state = MLX_HAVE_NOKEYS;
92     key->propq = propq;
93     return key;
94 
95 err:
96     OPENSSL_free(propq);
97     return NULL;
98 }
99 
mlx_kem_has(const void * vkey,int selection)100 static int mlx_kem_has(const void *vkey, int selection)
101 {
102     const MLX_KEY *key = vkey;
103 
104     /* A NULL key MUST fail to have anything */
105     if (!ossl_prov_is_running() || key == NULL)
106         return 0;
107 
108     switch (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) {
109     case 0:
110         return 1;
111     case OSSL_KEYMGMT_SELECT_PUBLIC_KEY:
112         return mlx_kem_have_pubkey(key);
113     default:
114         return mlx_kem_have_prvkey(key);
115     }
116 }
117 
mlx_kem_match(const void * vkey1,const void * vkey2,int selection)118 static int mlx_kem_match(const void *vkey1, const void *vkey2, int selection)
119 {
120     const MLX_KEY *key1 = vkey1;
121     const MLX_KEY *key2 = vkey2;
122     int have_pub1 = mlx_kem_have_pubkey(key1);
123     int have_pub2 = mlx_kem_have_pubkey(key2);
124 
125     if (!ossl_prov_is_running())
126         return 0;
127 
128     /* Compare domain parameters */
129     if (key1->xinfo != key2->xinfo)
130         return 0;
131 
132     if (!(selection & OSSL_KEYMGMT_SELECT_KEYPAIR))
133         return 1;
134 
135     if (have_pub1 ^ have_pub2)
136         return 0;
137 
138     /* As in other providers, equal when both have no key material. */
139     if (!have_pub1)
140         return 1;
141 
142     return EVP_PKEY_eq(key1->mkey, key2->mkey)
143         && EVP_PKEY_eq(key1->xkey, key2->xkey);
144 }
145 
146 typedef struct export_cb_arg_st {
147     const char *algorithm_name;
148     uint8_t *pubenc;
149     uint8_t *prvenc;
150     int pubcount;
151     int prvcount;
152     size_t puboff;
153     size_t prvoff;
154     size_t publen;
155     size_t prvlen;
156 } EXPORT_CB_ARG;
157 
158 /* Copy any exported key material into its storage slot */
export_sub_cb(const OSSL_PARAM * params,void * varg)159 static int export_sub_cb(const OSSL_PARAM *params, void *varg)
160 {
161     EXPORT_CB_ARG *sub_arg = varg;
162     const OSSL_PARAM *p = NULL;
163     size_t len;
164 
165     /*
166      * The caller will decide whether anything essential is missing, but, if
167      * some key material was returned, it should have the right (parameter)
168      * data type and length.
169      */
170     if (ossl_param_is_empty(params))
171         return 1;
172     if (sub_arg->pubenc != NULL
173         && (p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY)) != NULL) {
174         void *pub = sub_arg->pubenc + sub_arg->puboff;
175 
176         if (OSSL_PARAM_get_octet_string(p, &pub, sub_arg->publen, &len) != 1)
177             return 0;
178         if (len != sub_arg->publen) {
179             ERR_raise_data(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR,
180                 "Unexpected %s public key length %lu != %lu",
181                 sub_arg->algorithm_name, (unsigned long)len,
182                 sub_arg->publen);
183             return 0;
184         }
185         ++sub_arg->pubcount;
186     }
187     if (sub_arg->prvenc != NULL
188         && (p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PRIV_KEY)) != NULL) {
189         void *prv = sub_arg->prvenc + sub_arg->prvoff;
190 
191         if (OSSL_PARAM_get_octet_string(p, &prv, sub_arg->prvlen, &len) != 1)
192             return 0;
193         if (len != sub_arg->prvlen) {
194             ERR_raise_data(ERR_LIB_PROV, ERR_R_INTERNAL_ERROR,
195                 "Unexpected %s private key length %lu != %lu",
196                 sub_arg->algorithm_name, (unsigned long)len,
197                 (unsigned long)sub_arg->publen);
198             return 0;
199         }
200         ++sub_arg->prvcount;
201     }
202     return 1;
203 }
204 
205 static int
export_sub(EXPORT_CB_ARG * sub_arg,int selection,MLX_KEY * key)206 export_sub(EXPORT_CB_ARG *sub_arg, int selection, MLX_KEY *key)
207 {
208     int slot;
209 
210     /*
211      * The caller is responsible for initialising only the pubenc and prvenc
212      * pointer fields, the rest are set here or in the callback.
213      */
214     sub_arg->pubcount = 0;
215     sub_arg->prvcount = 0;
216 
217     for (slot = 0; slot < 2; ++slot) {
218         int ml_kem_slot = key->xinfo->ml_kem_slot;
219         EVP_PKEY *pkey;
220 
221         /* Export the parts of each component into its storage slot */
222         if (slot == ml_kem_slot) {
223             pkey = key->mkey;
224             sub_arg->algorithm_name = key->minfo->algorithm_name;
225             sub_arg->puboff = slot * key->xinfo->pubkey_bytes;
226             sub_arg->prvoff = slot * key->xinfo->prvkey_bytes;
227             sub_arg->publen = key->minfo->pubkey_bytes;
228             sub_arg->prvlen = key->minfo->prvkey_bytes;
229         } else {
230             pkey = key->xkey;
231             sub_arg->algorithm_name = key->xinfo->algorithm_name;
232             sub_arg->puboff = (1 - ml_kem_slot) * key->minfo->pubkey_bytes;
233             sub_arg->prvoff = (1 - ml_kem_slot) * key->minfo->prvkey_bytes;
234             sub_arg->publen = key->xinfo->pubkey_bytes;
235             sub_arg->prvlen = key->xinfo->prvkey_bytes;
236         }
237         if (!EVP_PKEY_export(pkey, selection, export_sub_cb, (void *)sub_arg))
238             return 0;
239     }
240     return 1;
241 }
242 
mlx_kem_export(void * vkey,int selection,OSSL_CALLBACK * param_cb,void * cbarg)243 static int mlx_kem_export(void *vkey, int selection, OSSL_CALLBACK *param_cb,
244     void *cbarg)
245 {
246     MLX_KEY *key = vkey;
247     OSSL_PARAM_BLD *tmpl = NULL;
248     OSSL_PARAM *params = NULL;
249     size_t publen;
250     size_t prvlen;
251     int ret = 0;
252     EXPORT_CB_ARG sub_arg;
253 
254     if (!ossl_prov_is_running() || key == NULL)
255         return 0;
256 
257     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
258         return 0;
259 
260     /* Fail when no key material has yet been provided */
261     if (!mlx_kem_have_pubkey(key)) {
262         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
263         return 0;
264     }
265     publen = key->minfo->pubkey_bytes + key->xinfo->pubkey_bytes;
266     prvlen = key->minfo->prvkey_bytes + key->xinfo->prvkey_bytes;
267     memset(&sub_arg, 0, sizeof(sub_arg));
268 
269     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
270         sub_arg.pubenc = OPENSSL_malloc(publen);
271         if (sub_arg.pubenc == NULL)
272             goto err;
273     }
274 
275     if (mlx_kem_have_prvkey(key)
276         && (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
277         /*
278          * Allocated on the secure heap if configured, this is detected in
279          * ossl_param_build_set_octet_string(), which will then also use the
280          * secure heap.
281          */
282         sub_arg.prvenc = OPENSSL_secure_zalloc(prvlen);
283         if (sub_arg.prvenc == NULL)
284             goto err;
285     }
286 
287     tmpl = OSSL_PARAM_BLD_new();
288     if (tmpl == NULL)
289         goto err;
290 
291     /* Extract sub-component key material */
292     if (!export_sub(&sub_arg, selection, key))
293         goto err;
294 
295     if (sub_arg.pubenc != NULL && sub_arg.pubcount == 2
296         && !ossl_param_build_set_octet_string(
297             tmpl, NULL, OSSL_PKEY_PARAM_PUB_KEY, sub_arg.pubenc, publen))
298         goto err;
299 
300     if (sub_arg.prvenc != NULL && sub_arg.prvcount == 2
301         && !ossl_param_build_set_octet_string(
302             tmpl, NULL, OSSL_PKEY_PARAM_PRIV_KEY, sub_arg.prvenc, prvlen))
303         goto err;
304 
305     params = OSSL_PARAM_BLD_to_param(tmpl);
306     if (params == NULL)
307         goto err;
308 
309     ret = param_cb(params, cbarg);
310     OSSL_PARAM_free(params);
311 
312 err:
313     OSSL_PARAM_BLD_free(tmpl);
314     OPENSSL_secure_clear_free(sub_arg.prvenc, prvlen);
315     OPENSSL_free(sub_arg.pubenc);
316     return ret;
317 }
318 
mlx_kem_imexport_types(int selection)319 static const OSSL_PARAM *mlx_kem_imexport_types(int selection)
320 {
321     static const OSSL_PARAM key_types[] = {
322         OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY, NULL, 0),
323         OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
324         OSSL_PARAM_END
325     };
326 
327     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0)
328         return key_types;
329     return NULL;
330 }
331 
332 static int
load_slot(OSSL_LIB_CTX * libctx,const char * propq,const char * pname,int selection,MLX_KEY * key,int slot,const uint8_t * in,int mbytes,int xbytes)333 load_slot(OSSL_LIB_CTX *libctx, const char *propq, const char *pname,
334     int selection, MLX_KEY *key, int slot, const uint8_t *in,
335     int mbytes, int xbytes)
336 {
337     EVP_PKEY_CTX *ctx;
338     EVP_PKEY **ppkey;
339     OSSL_PARAM parr[] = { OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END };
340     const char *alg;
341     char *group = NULL;
342     size_t off, len;
343     void *val;
344     int ml_kem_slot = key->xinfo->ml_kem_slot;
345     int ret = 0;
346 
347     if (slot == ml_kem_slot) {
348         alg = key->minfo->algorithm_name;
349         ppkey = &key->mkey;
350         off = slot * xbytes;
351         len = mbytes;
352     } else {
353         alg = key->xinfo->algorithm_name;
354         group = (char *)key->xinfo->group_name;
355         ppkey = &key->xkey;
356         off = (1 - ml_kem_slot) * mbytes;
357         len = xbytes;
358     }
359     val = (void *)(in + off);
360 
361     if ((ctx = EVP_PKEY_CTX_new_from_name(libctx, alg, propq)) == NULL
362         || EVP_PKEY_fromdata_init(ctx) <= 0)
363         goto err;
364     parr[0] = OSSL_PARAM_construct_octet_string(pname, val, len);
365     if (group != NULL)
366         parr[1] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
367             group, 0);
368     if (EVP_PKEY_fromdata(ctx, ppkey, selection, parr) > 0)
369         ret = 1;
370 
371 err:
372     EVP_PKEY_CTX_free(ctx);
373     return ret;
374 }
375 
376 static int
load_keys(MLX_KEY * key,const uint8_t * pubenc,size_t publen,const uint8_t * prvenc,size_t prvlen)377 load_keys(MLX_KEY *key,
378     const uint8_t *pubenc, size_t publen,
379     const uint8_t *prvenc, size_t prvlen)
380 {
381     int slot;
382 
383     for (slot = 0; slot < 2; ++slot) {
384         if (prvlen) {
385             /* Ignore public keys when private provided */
386             if (!load_slot(key->libctx, key->propq, OSSL_PKEY_PARAM_PRIV_KEY,
387                     minimal_selection, key, slot, prvenc,
388                     key->minfo->prvkey_bytes, key->xinfo->prvkey_bytes))
389                 goto err;
390         } else if (publen) {
391             /* Absent private key data, import public keys */
392             if (!load_slot(key->libctx, key->propq, OSSL_PKEY_PARAM_PUB_KEY,
393                     minimal_selection, key, slot, pubenc,
394                     key->minfo->pubkey_bytes, key->xinfo->pubkey_bytes))
395                 goto err;
396         }
397     }
398     key->state = prvlen ? MLX_HAVE_PRVKEY : MLX_HAVE_PUBKEY;
399     return 1;
400 
401 err:
402     EVP_PKEY_free(key->mkey);
403     EVP_PKEY_free(key->xkey);
404     key->xkey = key->mkey = NULL;
405     key->state = MLX_HAVE_NOKEYS;
406     return 0;
407 }
408 
mlx_kem_key_fromdata(MLX_KEY * key,const OSSL_PARAM params[],int include_private)409 static int mlx_kem_key_fromdata(MLX_KEY *key,
410     const OSSL_PARAM params[],
411     int include_private)
412 {
413     const OSSL_PARAM *param_prv_key = NULL, *param_pub_key;
414     const void *pubenc = NULL, *prvenc = NULL;
415     size_t pubkey_bytes, prvkey_bytes;
416     size_t publen = 0, prvlen = 0;
417 
418     /* Invalid attempt to mutate a key, what is the right error to report? */
419     if (key == NULL || mlx_kem_have_pubkey(key))
420         return 0;
421     pubkey_bytes = key->minfo->pubkey_bytes + key->xinfo->pubkey_bytes;
422     prvkey_bytes = key->minfo->prvkey_bytes + key->xinfo->prvkey_bytes;
423 
424     /* What does the caller want to set? */
425     param_pub_key = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PUB_KEY);
426     if (param_pub_key != NULL && OSSL_PARAM_get_octet_string_ptr(param_pub_key, &pubenc, &publen) != 1)
427         return 0;
428     if (include_private)
429         param_prv_key = OSSL_PARAM_locate_const(params,
430             OSSL_PKEY_PARAM_PRIV_KEY);
431     if (param_prv_key != NULL && OSSL_PARAM_get_octet_string_ptr(param_prv_key, &prvenc, &prvlen) != 1)
432         return 0;
433 
434     /* The caller MUST specify at least one of the public or private keys. */
435     if (publen == 0 && prvlen == 0) {
436         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
437         return 0;
438     }
439 
440     /*
441      * When a pubkey is provided, its length MUST be correct, if a private key
442      * is also provided, the public key will be otherwise ignored.  We could
443      * look for a matching encoded block, but unclear this is useful.
444      */
445     if (publen != 0 && publen != pubkey_bytes) {
446         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
447         return 0;
448     }
449     if (prvlen != 0 && prvlen != prvkey_bytes) {
450         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY_LENGTH);
451         return 0;
452     }
453 
454     return load_keys(key, pubenc, publen, prvenc, prvlen);
455 }
456 
mlx_kem_import(void * vkey,int selection,const OSSL_PARAM params[])457 static int mlx_kem_import(void *vkey, int selection, const OSSL_PARAM params[])
458 {
459     MLX_KEY *key = vkey;
460     int include_private;
461 
462     if (!ossl_prov_is_running() || key == NULL)
463         return 0;
464 
465     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
466         return 0;
467 
468     include_private = selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0;
469     return mlx_kem_key_fromdata(key, params, include_private);
470 }
471 
mlx_kem_gettable_params(void * provctx)472 static const OSSL_PARAM *mlx_kem_gettable_params(void *provctx)
473 {
474     static const OSSL_PARAM arr[] = {
475         OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL),
476         OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL),
477         OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL),
478         OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0),
479         OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0),
480         OSSL_PARAM_END
481     };
482 
483     return arr;
484 }
485 
486 /*
487  * It is assumed the key is guaranteed non-NULL here, and is from this provider
488  */
mlx_kem_get_params(void * vkey,OSSL_PARAM params[])489 static int mlx_kem_get_params(void *vkey, OSSL_PARAM params[])
490 {
491     MLX_KEY *key = vkey;
492     OSSL_PARAM *p, *pub, *prv = NULL;
493     EXPORT_CB_ARG sub_arg;
494     int selection;
495     size_t publen = key->minfo->pubkey_bytes + key->xinfo->pubkey_bytes;
496     size_t prvlen = key->minfo->prvkey_bytes + key->xinfo->prvkey_bytes;
497 
498     /* The reported "bit" count is those of the ML-KEM key */
499     p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_BITS);
500     if (p != NULL)
501         if (!OSSL_PARAM_set_int(p, key->minfo->bits))
502             return 0;
503 
504     /* The reported security bits are those of the ML-KEM key */
505     p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_SECURITY_BITS);
506     if (p != NULL)
507         if (!OSSL_PARAM_set_int(p, key->minfo->secbits))
508             return 0;
509 
510     /* The ciphertext sizes are additive */
511     p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_MAX_SIZE);
512     if (p != NULL)
513         if (!OSSL_PARAM_set_int(p, key->minfo->ctext_bytes + key->xinfo->pubkey_bytes))
514             return 0;
515 
516     if (!mlx_kem_have_pubkey(key))
517         return 1;
518 
519     memset(&sub_arg, 0, sizeof(sub_arg));
520     pub = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY);
521     if (pub != NULL) {
522         if (pub->data_type != OSSL_PARAM_OCTET_STRING)
523             return 0;
524         pub->return_size = publen;
525         if (pub->data == NULL) {
526             pub = NULL;
527         } else if (pub->data_size < publen) {
528             ERR_raise_data(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL,
529                 "public key output buffer too short: %lu < %lu",
530                 (unsigned long)pub->data_size,
531                 (unsigned long)publen);
532             return 0;
533         } else {
534             sub_arg.pubenc = pub->data;
535         }
536     }
537     if (mlx_kem_have_prvkey(key)) {
538         prv = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_PRIV_KEY);
539         if (prv != NULL) {
540             if (prv->data_type != OSSL_PARAM_OCTET_STRING)
541                 return 0;
542             prv->return_size = prvlen;
543             if (prv->data == NULL) {
544                 prv = NULL;
545             } else if (prv->data_size < prvlen) {
546                 ERR_raise_data(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL,
547                     "private key output buffer too short: %lu < %lu",
548                     (unsigned long)prv->data_size,
549                     (unsigned long)prvlen);
550                 return 0;
551             } else {
552                 sub_arg.prvenc = prv->data;
553             }
554         }
555     }
556     if (pub == NULL && prv == NULL)
557         return 1;
558 
559     selection = prv == NULL ? 0 : OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
560     selection |= pub == NULL ? 0 : OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
561     if (key->xinfo->group_name != NULL)
562         selection |= OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS;
563 
564     /* Extract sub-component key material */
565     if (!export_sub(&sub_arg, selection, key))
566         return 0;
567 
568     if ((pub != NULL && sub_arg.pubcount != 2)
569         || (prv != NULL && sub_arg.prvcount != 2))
570         return 0;
571 
572     return 1;
573 }
574 
mlx_kem_settable_params(void * provctx)575 static const OSSL_PARAM *mlx_kem_settable_params(void *provctx)
576 {
577     static const OSSL_PARAM arr[] = {
578         OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0),
579         OSSL_PARAM_END
580     };
581 
582     return arr;
583 }
584 
mlx_kem_set_params(void * vkey,const OSSL_PARAM params[])585 static int mlx_kem_set_params(void *vkey, const OSSL_PARAM params[])
586 {
587     MLX_KEY *key = vkey;
588     const OSSL_PARAM *p;
589     const void *pubenc = NULL;
590     size_t publen = 0;
591 
592     if (ossl_param_is_empty(params))
593         return 1;
594 
595     /* Only one settable parameter is supported */
596     p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY);
597     if (p == NULL)
598         return 1;
599 
600     /* Key mutation is reportedly generally not allowed */
601     if (mlx_kem_have_pubkey(key)) {
602         ERR_raise_data(ERR_LIB_PROV,
603             PROV_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE,
604             "keys cannot be mutated");
605         return 0;
606     }
607     /* An unlikely failure mode is the parameter having some unexpected type */
608     if (!OSSL_PARAM_get_octet_string_ptr(p, &pubenc, &publen))
609         return 0;
610 
611     p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PROPERTIES);
612     if (p != NULL) {
613         OPENSSL_free(key->propq);
614         key->propq = NULL;
615         if (!OSSL_PARAM_get_utf8_string(p, &key->propq, 0))
616             return 0;
617     }
618 
619     if (publen != key->minfo->pubkey_bytes + key->xinfo->pubkey_bytes) {
620         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KEY);
621         return 0;
622     }
623 
624     return load_keys(key, pubenc, publen, NULL, 0);
625 }
626 
mlx_kem_gen_set_params(void * vgctx,const OSSL_PARAM params[])627 static int mlx_kem_gen_set_params(void *vgctx, const OSSL_PARAM params[])
628 {
629     PROV_ML_KEM_GEN_CTX *gctx = vgctx;
630     const OSSL_PARAM *p;
631 
632     if (gctx == NULL)
633         return 0;
634     if (ossl_param_is_empty(params))
635         return 1;
636 
637     p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_PROPERTIES);
638     if (p != NULL) {
639         if (p->data_type != OSSL_PARAM_UTF8_STRING)
640             return 0;
641         OPENSSL_free(gctx->propq);
642         if ((gctx->propq = OPENSSL_strdup(p->data)) == NULL)
643             return 0;
644     }
645     return 1;
646 }
647 
mlx_kem_gen_init(int evp_type,OSSL_LIB_CTX * libctx,int selection,const OSSL_PARAM params[])648 static void *mlx_kem_gen_init(int evp_type, OSSL_LIB_CTX *libctx,
649     int selection, const OSSL_PARAM params[])
650 {
651     PROV_ML_KEM_GEN_CTX *gctx = NULL;
652 
653     /*
654      * We can only generate private keys, check that the selection is
655      * appropriate.
656      */
657     if (!ossl_prov_is_running()
658         || (selection & minimal_selection) == 0
659         || (gctx = OPENSSL_zalloc(sizeof(*gctx))) == NULL)
660         return NULL;
661 
662     gctx->evp_type = evp_type;
663     gctx->libctx = libctx;
664     gctx->selection = selection;
665     if (mlx_kem_gen_set_params(gctx, params))
666         return gctx;
667 
668     mlx_kem_gen_cleanup(gctx);
669     return NULL;
670 }
671 
mlx_kem_gen_settable_params(ossl_unused void * vgctx,ossl_unused void * provctx)672 static const OSSL_PARAM *mlx_kem_gen_settable_params(ossl_unused void *vgctx,
673     ossl_unused void *provctx)
674 {
675     static OSSL_PARAM settable[] = {
676         OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PROPERTIES, NULL, 0),
677         OSSL_PARAM_END
678     };
679 
680     return settable;
681 }
682 
mlx_kem_gen(void * vgctx,OSSL_CALLBACK * osslcb,void * cbarg)683 static void *mlx_kem_gen(void *vgctx, OSSL_CALLBACK *osslcb, void *cbarg)
684 {
685     PROV_ML_KEM_GEN_CTX *gctx = vgctx;
686     MLX_KEY *key;
687     char *propq;
688 
689     if (gctx == NULL
690         || (gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == OSSL_KEYMGMT_SELECT_PUBLIC_KEY)
691         return NULL;
692 
693     /* Lose ownership of propq */
694     propq = gctx->propq;
695     gctx->propq = NULL;
696     if ((key = mlx_kem_key_new(gctx->evp_type, gctx->libctx, propq)) == NULL)
697         return NULL;
698 
699     if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
700         return key;
701 
702     /* For now, using the same "propq" for all components */
703     key->mkey = EVP_PKEY_Q_keygen(key->libctx, key->propq,
704         key->minfo->algorithm_name);
705     key->xkey = EVP_PKEY_Q_keygen(key->libctx, key->propq,
706         key->xinfo->algorithm_name,
707         key->xinfo->group_name);
708     if (key->mkey != NULL && key->xkey != NULL) {
709         key->state = MLX_HAVE_PRVKEY;
710         return key;
711     }
712 
713     mlx_kem_key_free(key);
714     return NULL;
715 }
716 
mlx_kem_gen_cleanup(void * vgctx)717 static void mlx_kem_gen_cleanup(void *vgctx)
718 {
719     PROV_ML_KEM_GEN_CTX *gctx = vgctx;
720 
721     if (gctx == NULL)
722         return;
723     OPENSSL_free(gctx->propq);
724     OPENSSL_free(gctx);
725 }
726 
mlx_kem_dup(const void * vkey,int selection)727 static void *mlx_kem_dup(const void *vkey, int selection)
728 {
729     const MLX_KEY *key = vkey;
730     MLX_KEY *ret;
731 
732     if (!ossl_prov_is_running()
733         || (ret = OPENSSL_memdup(key, sizeof(*ret))) == NULL)
734         return NULL;
735 
736     if (ret->propq != NULL
737         && (ret->propq = OPENSSL_strdup(ret->propq)) == NULL) {
738         OPENSSL_free(ret);
739         return NULL;
740     }
741 
742     /* Absent key material, nothing left to do */
743     if (ret->mkey == NULL) {
744         if (ret->xkey == NULL)
745             return ret;
746         /* Fail if the source key is an inconsistent state */
747         OPENSSL_free(ret->propq);
748         OPENSSL_free(ret);
749         return NULL;
750     }
751 
752     switch (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) {
753     case 0:
754         ret->xkey = ret->mkey = NULL;
755         ret->state = MLX_HAVE_NOKEYS;
756         return ret;
757     case OSSL_KEYMGMT_SELECT_KEYPAIR:
758         ret->mkey = EVP_PKEY_dup(key->mkey);
759         ret->xkey = EVP_PKEY_dup(key->xkey);
760         if (ret->xkey != NULL && ret->mkey != NULL)
761             return ret;
762         break;
763     default:
764         ERR_raise_data(ERR_LIB_PROV, PROV_R_UNSUPPORTED_SELECTION,
765             "duplication of partial key material not supported");
766         break;
767     }
768 
769     mlx_kem_key_free(ret);
770     return NULL;
771 }
772 
773 #define DECLARE_DISPATCH(name, variant)                                                    \
774     static OSSL_FUNC_keymgmt_new_fn mlx_##name##_kem_new;                                  \
775     static void *mlx_##name##_kem_new(void *provctx)                                       \
776     {                                                                                      \
777         OSSL_LIB_CTX *libctx;                                                              \
778                                                                                            \
779         libctx = provctx == NULL ? NULL : PROV_LIBCTX_OF(provctx);                         \
780         return mlx_kem_key_new(variant, libctx, NULL);                                     \
781     }                                                                                      \
782     static OSSL_FUNC_keymgmt_gen_init_fn mlx_##name##_kem_gen_init;                        \
783     static void *mlx_##name##_kem_gen_init(void *provctx, int selection,                   \
784         const OSSL_PARAM params[])                                                         \
785     {                                                                                      \
786         OSSL_LIB_CTX *libctx;                                                              \
787                                                                                            \
788         libctx = provctx == NULL ? NULL : PROV_LIBCTX_OF(provctx);                         \
789         return mlx_kem_gen_init(variant, libctx, selection, params);                       \
790     }                                                                                      \
791     const OSSL_DISPATCH ossl_mlx_##name##_kem_kmgmt_functions[] = {                        \
792         { OSSL_FUNC_KEYMGMT_NEW, (OSSL_FUNC)mlx_##name##_kem_new },                        \
793         { OSSL_FUNC_KEYMGMT_FREE, (OSSL_FUNC)mlx_kem_key_free },                           \
794         { OSSL_FUNC_KEYMGMT_GET_PARAMS, (OSSL_FUNC)mlx_kem_get_params },                   \
795         { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (OSSL_FUNC)mlx_kem_gettable_params },         \
796         { OSSL_FUNC_KEYMGMT_SET_PARAMS, (OSSL_FUNC)mlx_kem_set_params },                   \
797         { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (OSSL_FUNC)mlx_kem_settable_params },         \
798         { OSSL_FUNC_KEYMGMT_HAS, (OSSL_FUNC)mlx_kem_has },                                 \
799         { OSSL_FUNC_KEYMGMT_MATCH, (OSSL_FUNC)mlx_kem_match },                             \
800         { OSSL_FUNC_KEYMGMT_GEN_INIT, (OSSL_FUNC)mlx_##name##_kem_gen_init },              \
801         { OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS, (OSSL_FUNC)mlx_kem_gen_set_params },           \
802         { OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS, (OSSL_FUNC)mlx_kem_gen_settable_params }, \
803         { OSSL_FUNC_KEYMGMT_GEN, (OSSL_FUNC)mlx_kem_gen },                                 \
804         { OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (OSSL_FUNC)mlx_kem_gen_cleanup },                 \
805         { OSSL_FUNC_KEYMGMT_DUP, (OSSL_FUNC)mlx_kem_dup },                                 \
806         { OSSL_FUNC_KEYMGMT_IMPORT, (OSSL_FUNC)mlx_kem_import },                           \
807         { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (OSSL_FUNC)mlx_kem_imexport_types },             \
808         { OSSL_FUNC_KEYMGMT_EXPORT, (OSSL_FUNC)mlx_kem_export },                           \
809         { OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (OSSL_FUNC)mlx_kem_imexport_types },             \
810         OSSL_DISPATCH_END                                                                  \
811     }
812 /* See |hybrid_vtable| above */
813 DECLARE_DISPATCH(p256, 0);
814 DECLARE_DISPATCH(p384, 1);
815 #if !defined(OPENSSL_NO_ECX)
816 DECLARE_DISPATCH(x25519, 2);
817 DECLARE_DISPATCH(x448, 3);
818 #endif
819