93909353942fd38306aa864e156318d375c3b1f6
[openssl.git] / providers / implementations / keymgmt / ec_kmgmt.c
1 /*
2  * Copyright 2020-2023 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 /*
11  * ECDH/ECDSA low level APIs are deprecated for public use, but still ok for
12  * internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <string.h>
17 #include <openssl/core_dispatch.h>
18 #include <openssl/core_names.h>
19 #include <openssl/bn.h>
20 #include <openssl/err.h>
21 #include <openssl/objects.h>
22 #include <openssl/proverr.h>
23 #include "crypto/bn.h"
24 #include "crypto/ec.h"
25 #include "prov/implementations.h"
26 #include "prov/providercommon.h"
27 #include "prov/provider_ctx.h"
28 #include "internal/param_build_set.h"
29
30 #ifndef FIPS_MODULE
31 # ifndef OPENSSL_NO_SM2
32 #  include "crypto/sm2.h"
33 # endif
34 #endif
35
36 static OSSL_FUNC_keymgmt_new_fn ec_newdata;
37 static OSSL_FUNC_keymgmt_gen_init_fn ec_gen_init;
38 static OSSL_FUNC_keymgmt_gen_set_template_fn ec_gen_set_template;
39 static OSSL_FUNC_keymgmt_gen_set_params_fn ec_gen_set_params;
40 static OSSL_FUNC_keymgmt_gen_settable_params_fn ec_gen_settable_params;
41 static OSSL_FUNC_keymgmt_gen_fn ec_gen;
42 static OSSL_FUNC_keymgmt_gen_cleanup_fn ec_gen_cleanup;
43 static OSSL_FUNC_keymgmt_load_fn ec_load;
44 static OSSL_FUNC_keymgmt_free_fn ec_freedata;
45 static OSSL_FUNC_keymgmt_get_params_fn ec_get_params;
46 static OSSL_FUNC_keymgmt_gettable_params_fn ec_gettable_params;
47 static OSSL_FUNC_keymgmt_set_params_fn ec_set_params;
48 static OSSL_FUNC_keymgmt_settable_params_fn ec_settable_params;
49 static OSSL_FUNC_keymgmt_has_fn ec_has;
50 static OSSL_FUNC_keymgmt_match_fn ec_match;
51 static OSSL_FUNC_keymgmt_validate_fn ec_validate;
52 static OSSL_FUNC_keymgmt_import_fn ec_import;
53 static OSSL_FUNC_keymgmt_import_types_fn ec_import_types;
54 static OSSL_FUNC_keymgmt_export_fn ec_export;
55 static OSSL_FUNC_keymgmt_export_types_fn ec_export_types;
56 static OSSL_FUNC_keymgmt_query_operation_name_fn ec_query_operation_name;
57 static OSSL_FUNC_keymgmt_dup_fn ec_dup;
58 #ifndef FIPS_MODULE
59 # ifndef OPENSSL_NO_SM2
60 static OSSL_FUNC_keymgmt_new_fn sm2_newdata;
61 static OSSL_FUNC_keymgmt_gen_init_fn sm2_gen_init;
62 static OSSL_FUNC_keymgmt_gen_fn sm2_gen;
63 static OSSL_FUNC_keymgmt_get_params_fn sm2_get_params;
64 static OSSL_FUNC_keymgmt_gettable_params_fn sm2_gettable_params;
65 static OSSL_FUNC_keymgmt_settable_params_fn sm2_settable_params;
66 static OSSL_FUNC_keymgmt_import_fn sm2_import;
67 static OSSL_FUNC_keymgmt_query_operation_name_fn sm2_query_operation_name;
68 static OSSL_FUNC_keymgmt_validate_fn sm2_validate;
69 # endif
70 #endif
71
72 #define EC_DEFAULT_MD "SHA256"
73 #define EC_POSSIBLE_SELECTIONS                                                 \
74     (OSSL_KEYMGMT_SELECT_KEYPAIR | OSSL_KEYMGMT_SELECT_ALL_PARAMETERS)
75 #define SM2_DEFAULT_MD "SM3"
76
77 static
78 const char *ec_query_operation_name(int operation_id)
79 {
80     switch (operation_id) {
81     case OSSL_OP_KEYEXCH:
82         return "ECDH";
83     case OSSL_OP_SIGNATURE:
84         return "ECDSA";
85     }
86     return NULL;
87 }
88
89 #ifndef FIPS_MODULE
90 # ifndef OPENSSL_NO_SM2
91 static
92 const char *sm2_query_operation_name(int operation_id)
93 {
94     switch (operation_id) {
95     case OSSL_OP_SIGNATURE:
96         return "SM2";
97     }
98     return NULL;
99 }
100 # endif
101 #endif
102
103 /*
104  * Callers of key_to_params MUST make sure that domparams_to_params is also
105  * called!
106  *
107  * This function only exports the bare keypair, domain parameters and other
108  * parameters are exported separately.
109  */
110 static ossl_inline
111 int key_to_params(const EC_KEY *eckey, OSSL_PARAM_BLD *tmpl,
112                   OSSL_PARAM params[], int include_private,
113                   unsigned char **pub_key)
114 {
115     BIGNUM *x = NULL, *y = NULL;
116     const BIGNUM *priv_key = NULL;
117     const EC_POINT *pub_point = NULL;
118     const EC_GROUP *ecg = NULL;
119     size_t pub_key_len = 0;
120     int ret = 0;
121     BN_CTX *bnctx = NULL;
122
123     if (eckey == NULL
124         || (ecg = EC_KEY_get0_group(eckey)) == NULL)
125         return 0;
126
127     priv_key = EC_KEY_get0_private_key(eckey);
128     pub_point = EC_KEY_get0_public_key(eckey);
129
130     if (pub_point != NULL) {
131         OSSL_PARAM *p = NULL, *px = NULL, *py = NULL;
132         /*
133          * EC_POINT_point2buf() can generate random numbers in some
134          * implementations so we need to ensure we use the correct libctx.
135          */
136         bnctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(eckey));
137         if (bnctx == NULL)
138             goto err;
139
140
141         /* If we are doing a get then check first before decoding the point */
142         if (tmpl == NULL) {
143             p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_PUB_KEY);
144             px = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_EC_PUB_X);
145             py = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_EC_PUB_Y);
146         }
147
148         if (p != NULL || tmpl != NULL) {
149             /* convert pub_point to a octet string according to the SECG standard */
150             point_conversion_form_t format = EC_KEY_get_conv_form(eckey);
151
152             if ((pub_key_len = EC_POINT_point2buf(ecg, pub_point,
153                                                   format,
154                                                   pub_key, bnctx)) == 0
155                 || !ossl_param_build_set_octet_string(tmpl, p,
156                                                       OSSL_PKEY_PARAM_PUB_KEY,
157                                                       *pub_key, pub_key_len))
158                 goto err;
159         }
160         if (px != NULL || py != NULL) {
161             if (px != NULL) {
162                 x = BN_CTX_get(bnctx);
163                 if (x == NULL)
164                     goto err;
165             }
166             if (py != NULL) {
167                 y = BN_CTX_get(bnctx);
168                 if (y == NULL)
169                     goto err;
170             }
171
172             if (!EC_POINT_get_affine_coordinates(ecg, pub_point, x, y, bnctx))
173                 goto err;
174             if (px != NULL
175                 && !ossl_param_build_set_bn(tmpl, px,
176                                             OSSL_PKEY_PARAM_EC_PUB_X, x))
177                 goto err;
178             if (py != NULL
179                 && !ossl_param_build_set_bn(tmpl, py,
180                                             OSSL_PKEY_PARAM_EC_PUB_Y, y))
181                 goto err;
182         }
183     }
184
185     if (priv_key != NULL && include_private) {
186         size_t sz;
187         int ecbits;
188
189         /*
190          * Key import/export should never leak the bit length of the secret
191          * scalar in the key.
192          *
193          * For this reason, on export we use padded BIGNUMs with fixed length.
194          *
195          * When importing we also should make sure that, even if short lived,
196          * the newly created BIGNUM is marked with the BN_FLG_CONSTTIME flag as
197          * soon as possible, so that any processing of this BIGNUM might opt for
198          * constant time implementations in the backend.
199          *
200          * Setting the BN_FLG_CONSTTIME flag alone is never enough, we also have
201          * to preallocate the BIGNUM internal buffer to a fixed public size big
202          * enough that operations performed during the processing never trigger
203          * a realloc which would leak the size of the scalar through memory
204          * accesses.
205          *
206          * Fixed Length
207          * ------------
208          *
209          * The order of the large prime subgroup of the curve is our choice for
210          * a fixed public size, as that is generally the upper bound for
211          * generating a private key in EC cryptosystems and should fit all valid
212          * secret scalars.
213          *
214          * For padding on export we just use the bit length of the order
215          * converted to bytes (rounding up).
216          *
217          * For preallocating the BIGNUM storage we look at the number of "words"
218          * required for the internal representation of the order, and we
219          * preallocate 2 extra "words" in case any of the subsequent processing
220          * might temporarily overflow the order length.
221          */
222         ecbits = EC_GROUP_order_bits(ecg);
223         if (ecbits <= 0)
224             goto err;
225         sz = (ecbits + 7) / 8;
226
227         if (!ossl_param_build_set_bn_pad(tmpl, params,
228                                          OSSL_PKEY_PARAM_PRIV_KEY,
229                                          priv_key, sz))
230             goto err;
231     }
232     ret = 1;
233  err:
234     BN_CTX_free(bnctx);
235     return ret;
236 }
237
238 static ossl_inline
239 int otherparams_to_params(const EC_KEY *ec, OSSL_PARAM_BLD *tmpl,
240                           OSSL_PARAM params[])
241 {
242     int ecdh_cofactor_mode = 0, group_check = 0;
243     const char *name = NULL;
244     point_conversion_form_t format;
245
246     if (ec == NULL)
247         return 0;
248
249     format = EC_KEY_get_conv_form(ec);
250     name = ossl_ec_pt_format_id2name((int)format);
251     if (name != NULL
252         && !ossl_param_build_set_utf8_string(tmpl, params,
253                                              OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT,
254                                              name))
255         return 0;
256
257     group_check = EC_KEY_get_flags(ec) & EC_FLAG_CHECK_NAMED_GROUP_MASK;
258     name = ossl_ec_check_group_type_id2name(group_check);
259     if (name != NULL
260         && !ossl_param_build_set_utf8_string(tmpl, params,
261                                              OSSL_PKEY_PARAM_EC_GROUP_CHECK_TYPE,
262                                              name))
263         return 0;
264
265     if ((EC_KEY_get_enc_flags(ec) & EC_PKEY_NO_PUBKEY) != 0
266             && !ossl_param_build_set_int(tmpl, params,
267                                          OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC, 0))
268         return 0;
269
270     ecdh_cofactor_mode =
271         (EC_KEY_get_flags(ec) & EC_FLAG_COFACTOR_ECDH) ? 1 : 0;
272     return ossl_param_build_set_int(tmpl, params,
273                                     OSSL_PKEY_PARAM_USE_COFACTOR_ECDH,
274                                     ecdh_cofactor_mode);
275 }
276
277 static
278 void *ec_newdata(void *provctx)
279 {
280     if (!ossl_prov_is_running())
281         return NULL;
282     return EC_KEY_new_ex(PROV_LIBCTX_OF(provctx), NULL);
283 }
284
285 #ifndef FIPS_MODULE
286 # ifndef OPENSSL_NO_SM2
287 static
288 void *sm2_newdata(void *provctx)
289 {
290     if (!ossl_prov_is_running())
291         return NULL;
292     return EC_KEY_new_by_curve_name_ex(PROV_LIBCTX_OF(provctx), NULL, NID_sm2);
293 }
294 # endif
295 #endif
296
297 static
298 void ec_freedata(void *keydata)
299 {
300     EC_KEY_free(keydata);
301 }
302
303 static
304 int ec_has(const void *keydata, int selection)
305 {
306     const EC_KEY *ec = keydata;
307     int ok = 1;
308
309     if (!ossl_prov_is_running() || ec == NULL)
310         return 0;
311     if ((selection & EC_POSSIBLE_SELECTIONS) == 0)
312         return 1; /* the selection is not missing */
313
314     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
315         ok = ok && (EC_KEY_get0_public_key(ec) != NULL);
316     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
317         ok = ok && (EC_KEY_get0_private_key(ec) != NULL);
318     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
319         ok = ok && (EC_KEY_get0_group(ec) != NULL);
320     /*
321      * We consider OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS to always be
322      * available, so no extra check is needed other than the previous one
323      * against EC_POSSIBLE_SELECTIONS.
324      */
325     return ok;
326 }
327
328 static int ec_match(const void *keydata1, const void *keydata2, int selection)
329 {
330     const EC_KEY *ec1 = keydata1;
331     const EC_KEY *ec2 = keydata2;
332     const EC_GROUP *group_a = EC_KEY_get0_group(ec1);
333     const EC_GROUP *group_b = EC_KEY_get0_group(ec2);
334     BN_CTX *ctx = NULL;
335     int ok = 1;
336
337     if (!ossl_prov_is_running())
338         return 0;
339
340     ctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(ec1));
341     if (ctx == NULL)
342         return 0;
343
344     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
345         ok = ok && group_a != NULL && group_b != NULL
346             && EC_GROUP_cmp(group_a, group_b, ctx) == 0;
347     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
348         int key_checked = 0;
349
350         if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
351             const EC_POINT *pa = EC_KEY_get0_public_key(ec1);
352             const EC_POINT *pb = EC_KEY_get0_public_key(ec2);
353
354             if (pa != NULL && pb != NULL) {
355                 ok = ok && EC_POINT_cmp(group_b, pa, pb, ctx) == 0;
356                 key_checked = 1;
357             }
358         }
359         if (!key_checked
360             && (selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
361             const BIGNUM *pa = EC_KEY_get0_private_key(ec1);
362             const BIGNUM *pb = EC_KEY_get0_private_key(ec2);
363
364             if (pa != NULL && pb != NULL) {
365                 ok = ok && BN_cmp(pa, pb) == 0;
366                 key_checked = 1;
367             }
368         }
369         ok = ok && key_checked;
370     }
371     BN_CTX_free(ctx);
372     return ok;
373 }
374
375 static int common_check_sm2(const EC_KEY *ec, int sm2_wanted)
376 {
377     const EC_GROUP *ecg = NULL;
378
379     /*
380      * sm2_wanted: import the keys or domparams only on SM2 Curve
381      * !sm2_wanted: import the keys or domparams only not on SM2 Curve
382      */
383     if ((ecg = EC_KEY_get0_group(ec)) == NULL
384         || (sm2_wanted ^ (EC_GROUP_get_curve_name(ecg) == NID_sm2)))
385         return 0;
386     return 1;
387 }
388
389 static
390 int common_import(void *keydata, int selection, const OSSL_PARAM params[],
391                   int sm2_wanted)
392 {
393     EC_KEY *ec = keydata;
394     int ok = 1;
395
396     if (!ossl_prov_is_running() || ec == NULL)
397         return 0;
398
399     /*
400      * In this implementation, we can export/import only keydata in the
401      * following combinations:
402      *   - domain parameters (+optional other params)
403      *   - public key with associated domain parameters (+optional other params)
404      *   - private key with associated domain parameters and optional public key
405      *         (+optional other params)
406      *
407      * This means:
408      *   - domain parameters must always be requested
409      *   - private key must be requested alongside public key
410      *   - other parameters are always optional
411      */
412     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0)
413         return 0;
414
415     ok = ok && ossl_ec_group_fromdata(ec, params);
416
417     if (!common_check_sm2(ec, sm2_wanted))
418         return 0;
419
420     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
421         int include_private =
422             selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0;
423
424         ok = ok && ossl_ec_key_fromdata(ec, params, include_private);
425     }
426     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0)
427         ok = ok && ossl_ec_key_otherparams_fromdata(ec, params);
428
429     return ok;
430 }
431
432 static
433 int ec_import(void *keydata, int selection, const OSSL_PARAM params[])
434 {
435     return common_import(keydata, selection, params, 0);
436 }
437
438 #ifndef FIPS_MODULE
439 # ifndef OPENSSL_NO_SM2
440 static
441 int sm2_import(void *keydata, int selection, const OSSL_PARAM params[])
442 {
443     return common_import(keydata, selection, params, 1);
444 }
445 # endif
446 #endif
447
448 static
449 int ec_export(void *keydata, int selection, OSSL_CALLBACK *param_cb,
450               void *cbarg)
451 {
452     EC_KEY *ec = keydata;
453     OSSL_PARAM_BLD *tmpl = NULL;
454     OSSL_PARAM *params = NULL;
455     unsigned char *pub_key = NULL, *genbuf = NULL;
456     BN_CTX *bnctx = NULL;
457     int ok = 1;
458
459     if (!ossl_prov_is_running() || ec == NULL)
460         return 0;
461
462     /*
463      * In this implementation, we can export/import only keydata in the
464      * following combinations:
465      *   - domain parameters (+optional other params)
466      *   - public key with associated domain parameters (+optional other params)
467      *   - private key with associated public key and domain parameters
468      *         (+optional other params)
469      *
470      * This means:
471      *   - domain parameters must always be requested
472      *   - private key must be requested alongside public key
473      *   - other parameters are always optional
474      */
475     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0)
476         return 0;
477     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0
478             && (selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) == 0)
479         return 0;
480
481     tmpl = OSSL_PARAM_BLD_new();
482     if (tmpl == NULL)
483         return 0;
484
485     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0) {
486         bnctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(ec));
487         if (bnctx == NULL) {
488             ok = 0;
489             goto end;
490         }
491         BN_CTX_start(bnctx);
492         ok = ok && ossl_ec_group_todata(EC_KEY_get0_group(ec), tmpl, NULL,
493                                         ossl_ec_key_get_libctx(ec),
494                                         ossl_ec_key_get0_propq(ec),
495                                         bnctx, &genbuf);
496     }
497
498     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
499         int include_private =
500             selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0;
501
502         ok = ok && key_to_params(ec, tmpl, NULL, include_private, &pub_key);
503     }
504     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0)
505         ok = ok && otherparams_to_params(ec, tmpl, NULL);
506
507     if (!ok || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
508         ok = 0;
509         goto end;
510     }
511
512     ok = param_cb(params, cbarg);
513     OSSL_PARAM_free(params);
514 end:
515     OSSL_PARAM_BLD_free(tmpl);
516     OPENSSL_free(pub_key);
517     OPENSSL_free(genbuf);
518     BN_CTX_end(bnctx);
519     BN_CTX_free(bnctx);
520     return ok;
521 }
522
523 /* IMEXPORT = IMPORT + EXPORT */
524
525 # define EC_IMEXPORTABLE_DOM_PARAMETERS                                        \
526     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, NULL, 0),               \
527     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_ENCODING, NULL, 0),              \
528     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, NULL, 0),\
529     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_FIELD_TYPE, NULL, 0),            \
530     OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_P, NULL, 0),                              \
531     OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_A, NULL, 0),                              \
532     OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_B, NULL, 0),                              \
533     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_EC_GENERATOR, NULL, 0),            \
534     OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_ORDER, NULL, 0),                          \
535     OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_COFACTOR, NULL, 0),                       \
536     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_EC_SEED, NULL, 0),                 \
537     OSSL_PARAM_int(OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS, NULL)
538
539 # define EC_IMEXPORTABLE_PUBLIC_KEY                                            \
540     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY, NULL, 0)
541 # define EC_IMEXPORTABLE_PRIVATE_KEY                                           \
542     OSSL_PARAM_BN(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0)
543 # define EC_IMEXPORTABLE_OTHER_PARAMETERS                                      \
544     OSSL_PARAM_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, NULL),                   \
545     OSSL_PARAM_int(OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC, NULL)
546
547 /*
548  * Include all the possible combinations of OSSL_PARAM arrays for
549  * ec_imexport_types().
550  *
551  * They are in a separate file as it is ~100 lines of unreadable and
552  * uninteresting machine generated stuff.
553  */
554 #include "ec_kmgmt_imexport.inc"
555
556 static ossl_inline
557 const OSSL_PARAM *ec_imexport_types(int selection)
558 {
559     int type_select = 0;
560
561     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
562         type_select += 1;
563     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
564         type_select += 2;
565     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
566         type_select += 4;
567     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0)
568         type_select += 8;
569     return ec_types[type_select];
570 }
571
572 static
573 const OSSL_PARAM *ec_import_types(int selection)
574 {
575     return ec_imexport_types(selection);
576 }
577
578 static
579 const OSSL_PARAM *ec_export_types(int selection)
580 {
581     return ec_imexport_types(selection);
582 }
583
584 static int ec_get_ecm_params(const EC_GROUP *group, OSSL_PARAM params[])
585 {
586 #ifdef OPENSSL_NO_EC2M
587     return 1;
588 #else
589     int ret = 0, m;
590     unsigned int k1 = 0, k2 = 0, k3 = 0;
591     int basis_nid;
592     const char *basis_name = NULL;
593     int fid = EC_GROUP_get_field_type(group);
594
595     if (fid != NID_X9_62_characteristic_two_field)
596         return 1;
597
598     basis_nid = EC_GROUP_get_basis_type(group);
599     if (basis_nid == NID_X9_62_tpBasis)
600         basis_name = SN_X9_62_tpBasis;
601     else if (basis_nid == NID_X9_62_ppBasis)
602         basis_name = SN_X9_62_ppBasis;
603     else
604         goto err;
605
606     m = EC_GROUP_get_degree(group);
607     if (!ossl_param_build_set_int(NULL, params, OSSL_PKEY_PARAM_EC_CHAR2_M, m)
608         || !ossl_param_build_set_utf8_string(NULL, params,
609                                              OSSL_PKEY_PARAM_EC_CHAR2_TYPE,
610                                              basis_name))
611         goto err;
612
613     if (basis_nid == NID_X9_62_tpBasis) {
614         if (!EC_GROUP_get_trinomial_basis(group, &k1)
615             || !ossl_param_build_set_int(NULL, params,
616                                          OSSL_PKEY_PARAM_EC_CHAR2_TP_BASIS,
617                                          (int)k1))
618             goto err;
619     } else {
620         if (!EC_GROUP_get_pentanomial_basis(group, &k1, &k2, &k3)
621             || !ossl_param_build_set_int(NULL, params,
622                                          OSSL_PKEY_PARAM_EC_CHAR2_PP_K1, (int)k1)
623             || !ossl_param_build_set_int(NULL, params,
624                                          OSSL_PKEY_PARAM_EC_CHAR2_PP_K2, (int)k2)
625             || !ossl_param_build_set_int(NULL, params,
626                                          OSSL_PKEY_PARAM_EC_CHAR2_PP_K3, (int)k3))
627             goto err;
628     }
629     ret = 1;
630 err:
631     return ret;
632 #endif /* OPENSSL_NO_EC2M */
633 }
634
635 static
636 int common_get_params(void *key, OSSL_PARAM params[], int sm2)
637 {
638     int ret = 0;
639     EC_KEY *eck = key;
640     const EC_GROUP *ecg = NULL;
641     OSSL_PARAM *p;
642     unsigned char *pub_key = NULL, *genbuf = NULL;
643     OSSL_LIB_CTX *libctx;
644     const char *propq;
645     BN_CTX *bnctx = NULL;
646
647     ecg = EC_KEY_get0_group(eck);
648     if (ecg == NULL) {
649         ERR_raise(ERR_LIB_PROV, PROV_R_NO_PARAMETERS_SET);
650         return 0;
651     }
652
653     libctx = ossl_ec_key_get_libctx(eck);
654     propq = ossl_ec_key_get0_propq(eck);
655
656     bnctx = BN_CTX_new_ex(libctx);
657     if (bnctx == NULL)
658         return 0;
659     BN_CTX_start(bnctx);
660
661     if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_MAX_SIZE)) != NULL
662         && !OSSL_PARAM_set_int(p, ECDSA_size(eck)))
663         goto err;
664     if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_BITS)) != NULL
665         && !OSSL_PARAM_set_int(p, EC_GROUP_order_bits(ecg)))
666         goto err;
667     if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_SECURITY_BITS)) != NULL) {
668         int ecbits, sec_bits;
669
670         ecbits = EC_GROUP_order_bits(ecg);
671
672         /*
673          * The following estimates are based on the values published
674          * in Table 2 of "NIST Special Publication 800-57 Part 1 Revision 4"
675          * at http://dx.doi.org/10.6028/NIST.SP.800-57pt1r4 .
676          *
677          * Note that the above reference explicitly categorizes algorithms in a
678          * discrete set of values {80, 112, 128, 192, 256}, and that it is
679          * relevant only for NIST approved Elliptic Curves, while OpenSSL
680          * applies the same logic also to other curves.
681          *
682          * Classifications produced by other standardazing bodies might differ,
683          * so the results provided for "bits of security" by this provider are
684          * to be considered merely indicative, and it is the users'
685          * responsibility to compare these values against the normative
686          * references that may be relevant for their intent and purposes.
687          */
688         if (ecbits >= 512)
689             sec_bits = 256;
690         else if (ecbits >= 384)
691             sec_bits = 192;
692         else if (ecbits >= 256)
693             sec_bits = 128;
694         else if (ecbits >= 224)
695             sec_bits = 112;
696         else if (ecbits >= 160)
697             sec_bits = 80;
698         else
699             sec_bits = ecbits / 2;
700
701         if (!OSSL_PARAM_set_int(p, sec_bits))
702             goto err;
703     }
704
705     if ((p = OSSL_PARAM_locate(params,
706                                OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS))
707             != NULL) {
708         int explicitparams = EC_KEY_decoded_from_explicit_params(eck);
709
710         if (explicitparams < 0
711              || !OSSL_PARAM_set_int(p, explicitparams))
712             goto err;
713     }
714
715     if (!sm2) {
716         if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_DEFAULT_DIGEST)) != NULL
717                 && !OSSL_PARAM_set_utf8_string(p, EC_DEFAULT_MD))
718             goto err;
719     } else {
720         if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_DEFAULT_DIGEST)) != NULL
721                 && !OSSL_PARAM_set_utf8_string(p, SM2_DEFAULT_MD))
722             goto err;
723     }
724
725     /* SM2 doesn't support this PARAM */
726     if (!sm2) {
727         p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_USE_COFACTOR_ECDH);
728         if (p != NULL) {
729             int ecdh_cofactor_mode = 0;
730
731             ecdh_cofactor_mode =
732                 (EC_KEY_get_flags(eck) & EC_FLAG_COFACTOR_ECDH) ? 1 : 0;
733
734             if (!OSSL_PARAM_set_int(p, ecdh_cofactor_mode))
735                 goto err;
736         }
737     }
738     if ((p = OSSL_PARAM_locate(params,
739                                OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY)) != NULL) {
740         const EC_POINT *ecp = EC_KEY_get0_public_key(key);
741
742         if (ecp == NULL) {
743             ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY);
744             goto err;
745         }
746         p->return_size = EC_POINT_point2oct(ecg, ecp,
747                                             POINT_CONVERSION_UNCOMPRESSED,
748                                             p->data, p->data_size, bnctx);
749         if (p->return_size == 0)
750             goto err;
751     }
752
753     ret = ec_get_ecm_params(ecg, params)
754           && ossl_ec_group_todata(ecg, NULL, params, libctx, propq, bnctx,
755                                   &genbuf)
756           && key_to_params(eck, NULL, params, 1, &pub_key)
757           && otherparams_to_params(eck, NULL, params);
758 err:
759     OPENSSL_free(genbuf);
760     OPENSSL_free(pub_key);
761     BN_CTX_end(bnctx);
762     BN_CTX_free(bnctx);
763     return ret;
764 }
765
766 static
767 int ec_get_params(void *key, OSSL_PARAM params[])
768 {
769     return common_get_params(key, params, 0);
770 }
771
772 #ifndef OPENSSL_NO_EC2M
773 # define EC2M_GETTABLE_DOM_PARAMS                                              \
774         OSSL_PARAM_int(OSSL_PKEY_PARAM_EC_CHAR2_M, NULL),                      \
775         OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_CHAR2_TYPE, NULL, 0),        \
776         OSSL_PARAM_int(OSSL_PKEY_PARAM_EC_CHAR2_TP_BASIS, NULL),               \
777         OSSL_PARAM_int(OSSL_PKEY_PARAM_EC_CHAR2_PP_K1, NULL),                  \
778         OSSL_PARAM_int(OSSL_PKEY_PARAM_EC_CHAR2_PP_K2, NULL),                  \
779         OSSL_PARAM_int(OSSL_PKEY_PARAM_EC_CHAR2_PP_K3, NULL),
780 #else
781 # define EC2M_GETTABLE_DOM_PARAMS
782 #endif
783
784 static const OSSL_PARAM ec_known_gettable_params[] = {
785     OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL),
786     OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL),
787     OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL),
788     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_DEFAULT_DIGEST, NULL, 0),
789     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0),
790     OSSL_PARAM_int(OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS, NULL),
791     EC_IMEXPORTABLE_DOM_PARAMETERS,
792     EC2M_GETTABLE_DOM_PARAMS
793     EC_IMEXPORTABLE_PUBLIC_KEY,
794     OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_PUB_X, NULL, 0),
795     OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_PUB_Y, NULL, 0),
796     EC_IMEXPORTABLE_PRIVATE_KEY,
797     EC_IMEXPORTABLE_OTHER_PARAMETERS,
798     OSSL_PARAM_END
799 };
800
801 static
802 const OSSL_PARAM *ec_gettable_params(void *provctx)
803 {
804     return ec_known_gettable_params;
805 }
806
807 static const OSSL_PARAM ec_known_settable_params[] = {
808     OSSL_PARAM_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, NULL),
809     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0),
810     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_ENCODING, NULL, 0),
811     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, NULL, 0),
812     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_EC_SEED, NULL, 0),
813     OSSL_PARAM_int(OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC, NULL),
814     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_GROUP_CHECK_TYPE, NULL, 0),
815     OSSL_PARAM_END
816 };
817
818 static
819 const OSSL_PARAM *ec_settable_params(void *provctx)
820 {
821     return ec_known_settable_params;
822 }
823
824 static
825 int ec_set_params(void *key, const OSSL_PARAM params[])
826 {
827     EC_KEY *eck = key;
828     const OSSL_PARAM *p;
829
830     if (key == NULL)
831         return 0;
832     if (params == NULL)
833         return 1;
834
835
836     if (!ossl_ec_group_set_params((EC_GROUP *)EC_KEY_get0_group(key), params))
837         return 0;
838
839     p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY);
840     if (p != NULL) {
841         BN_CTX *ctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(key));
842         int ret = 1;
843
844         if (ctx == NULL
845                 || p->data_type != OSSL_PARAM_OCTET_STRING
846                 || !EC_KEY_oct2key(key, p->data, p->data_size, ctx))
847             ret = 0;
848         BN_CTX_free(ctx);
849         if (!ret)
850             return 0;
851     }
852
853     return ossl_ec_key_otherparams_fromdata(eck, params);
854 }
855
856 #ifndef FIPS_MODULE
857 # ifndef OPENSSL_NO_SM2
858 static
859 int sm2_get_params(void *key, OSSL_PARAM params[])
860 {
861     return common_get_params(key, params, 1);
862 }
863
864 static const OSSL_PARAM sm2_known_gettable_params[] = {
865     OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL),
866     OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL),
867     OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL),
868     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_DEFAULT_DIGEST, NULL, 0),
869     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0),
870     OSSL_PARAM_int(OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS, NULL),
871     EC_IMEXPORTABLE_DOM_PARAMETERS,
872     EC_IMEXPORTABLE_PUBLIC_KEY,
873     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_EC_PUB_X, NULL, 0),
874     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_EC_PUB_Y, NULL, 0),
875     EC_IMEXPORTABLE_PRIVATE_KEY,
876     OSSL_PARAM_END
877 };
878
879 static
880 const OSSL_PARAM *sm2_gettable_params(ossl_unused void *provctx)
881 {
882     return sm2_known_gettable_params;
883 }
884
885 static const OSSL_PARAM sm2_known_settable_params[] = {
886     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY, NULL, 0),
887     OSSL_PARAM_END
888 };
889
890 static
891 const OSSL_PARAM *sm2_settable_params(ossl_unused void *provctx)
892 {
893     return sm2_known_settable_params;
894 }
895
896 static
897 int sm2_validate(const void *keydata, int selection, int checktype)
898 {
899     const EC_KEY *eck = keydata;
900     int ok = 1;
901     BN_CTX *ctx = NULL;
902
903     if (!ossl_prov_is_running())
904         return 0;
905
906     if ((selection & EC_POSSIBLE_SELECTIONS) == 0)
907         return 1; /* nothing to validate */
908
909     ctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(eck));
910     if  (ctx == NULL)
911         return 0;
912
913     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
914         ok = ok && EC_GROUP_check(EC_KEY_get0_group(eck), ctx);
915
916     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
917         if (checktype == OSSL_KEYMGMT_VALIDATE_QUICK_CHECK)
918             ok = ok && ossl_ec_key_public_check_quick(eck, ctx);
919         else
920             ok = ok && ossl_ec_key_public_check(eck, ctx);
921     }
922
923     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
924         ok = ok && ossl_sm2_key_private_check(eck);
925
926     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == OSSL_KEYMGMT_SELECT_KEYPAIR)
927         ok = ok && ossl_ec_key_pairwise_check(eck, ctx);
928
929     BN_CTX_free(ctx);
930     return ok;
931 }
932 # endif
933 #endif
934
935 static
936 int ec_validate(const void *keydata, int selection, int checktype)
937 {
938     const EC_KEY *eck = keydata;
939     int ok = 1;
940     BN_CTX *ctx = NULL;
941
942     if (!ossl_prov_is_running())
943         return 0;
944
945     if ((selection & EC_POSSIBLE_SELECTIONS) == 0)
946         return 1; /* nothing to validate */
947
948     ctx = BN_CTX_new_ex(ossl_ec_key_get_libctx(eck));
949     if  (ctx == NULL)
950         return 0;
951
952     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0) {
953         int flags = EC_KEY_get_flags(eck);
954
955         if ((flags & EC_FLAG_CHECK_NAMED_GROUP) != 0)
956             ok = ok && EC_GROUP_check_named_curve(EC_KEY_get0_group(eck),
957                            (flags & EC_FLAG_CHECK_NAMED_GROUP_NIST) != 0, ctx) > 0;
958         else
959             ok = ok && EC_GROUP_check(EC_KEY_get0_group(eck), ctx);
960     }
961
962     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
963         if (checktype == OSSL_KEYMGMT_VALIDATE_QUICK_CHECK)
964             ok = ok && ossl_ec_key_public_check_quick(eck, ctx);
965         else
966             ok = ok && ossl_ec_key_public_check(eck, ctx);
967     }
968
969     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
970         ok = ok && ossl_ec_key_private_check(eck);
971
972     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == OSSL_KEYMGMT_SELECT_KEYPAIR)
973         ok = ok && ossl_ec_key_pairwise_check(eck, ctx);
974
975     BN_CTX_free(ctx);
976     return ok;
977 }
978
979 struct ec_gen_ctx {
980     OSSL_LIB_CTX *libctx;
981     char *group_name;
982     char *encoding;
983     char *pt_format;
984     char *group_check;
985     char *field_type;
986     BIGNUM *p, *a, *b, *order, *cofactor;
987     unsigned char *gen, *seed;
988     size_t gen_len, seed_len;
989     int selection;
990     int ecdh_mode;
991     EC_GROUP *gen_group;
992     unsigned char *dhkem_ikm;
993     size_t dhkem_ikmlen;
994 };
995
996 static void *ec_gen_init(void *provctx, int selection,
997                          const OSSL_PARAM params[])
998 {
999     OSSL_LIB_CTX *libctx = PROV_LIBCTX_OF(provctx);
1000     struct ec_gen_ctx *gctx = NULL;
1001
1002     if (!ossl_prov_is_running() || (selection & (EC_POSSIBLE_SELECTIONS)) == 0)
1003         return NULL;
1004
1005     if ((gctx = OPENSSL_zalloc(sizeof(*gctx))) != NULL) {
1006         gctx->libctx = libctx;
1007         gctx->selection = selection;
1008         gctx->ecdh_mode = 0;
1009         if (!ec_gen_set_params(gctx, params)) {
1010             OPENSSL_free(gctx);
1011             gctx = NULL;
1012         }
1013     }
1014     return gctx;
1015 }
1016
1017 #ifndef FIPS_MODULE
1018 # ifndef OPENSSL_NO_SM2
1019 static void *sm2_gen_init(void *provctx, int selection,
1020                          const OSSL_PARAM params[])
1021 {
1022     struct ec_gen_ctx *gctx = ec_gen_init(provctx, selection, params);
1023
1024     if (gctx != NULL) {
1025         if (gctx->group_name != NULL)
1026             return gctx;
1027         if ((gctx->group_name = OPENSSL_strdup("sm2")) != NULL)
1028             return gctx;
1029         ec_gen_cleanup(gctx);
1030     }
1031     return NULL;
1032 }
1033 # endif
1034 #endif
1035
1036 static int ec_gen_set_group(void *genctx, const EC_GROUP *src)
1037 {
1038     struct ec_gen_ctx *gctx = genctx;
1039     EC_GROUP *group;
1040
1041     group = EC_GROUP_dup(src);
1042     if (group == NULL) {
1043         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CURVE);
1044         return 0;
1045     }
1046     EC_GROUP_free(gctx->gen_group);
1047     gctx->gen_group = group;
1048     return 1;
1049 }
1050
1051 static int ec_gen_set_template(void *genctx, void *templ)
1052 {
1053     struct ec_gen_ctx *gctx = genctx;
1054     EC_KEY *ec = templ;
1055     const EC_GROUP *ec_group;
1056
1057     if (!ossl_prov_is_running() || gctx == NULL || ec == NULL)
1058         return 0;
1059     if ((ec_group = EC_KEY_get0_group(ec)) == NULL)
1060         return 0;
1061     return ec_gen_set_group(gctx, ec_group);
1062 }
1063
1064 #define COPY_INT_PARAM(params, key, val)                                       \
1065 p = OSSL_PARAM_locate_const(params, key);                                      \
1066 if (p != NULL && !OSSL_PARAM_get_int(p, &val))                                 \
1067     goto err;
1068
1069 #define COPY_UTF8_PARAM(params, key, val)                                      \
1070 p = OSSL_PARAM_locate_const(params, key);                                      \
1071 if (p != NULL) {                                                               \
1072     if (p->data_type != OSSL_PARAM_UTF8_STRING)                                \
1073         goto err;                                                              \
1074     OPENSSL_free(val);                                                         \
1075     val = OPENSSL_strdup(p->data);                                             \
1076     if (val == NULL)                                                           \
1077         goto err;                                                              \
1078 }
1079
1080 #define COPY_OCTET_PARAM(params, key, val, len)                                \
1081 p = OSSL_PARAM_locate_const(params, key);                                      \
1082 if (p != NULL) {                                                               \
1083     if (p->data_type != OSSL_PARAM_OCTET_STRING)                               \
1084         goto err;                                                              \
1085     OPENSSL_free(val);                                                         \
1086     len = p->data_size;                                                        \
1087     val = OPENSSL_memdup(p->data, p->data_size);                               \
1088     if (val == NULL)                                                           \
1089         goto err;                                                              \
1090 }
1091
1092 #define COPY_BN_PARAM(params, key, bn)                                         \
1093 p = OSSL_PARAM_locate_const(params, key);                                      \
1094 if (p != NULL) {                                                               \
1095     if (bn == NULL)                                                            \
1096         bn = BN_new();                                                         \
1097     if (bn == NULL || !OSSL_PARAM_get_BN(p, &bn))                              \
1098         goto err;                                                              \
1099 }
1100
1101 static int ec_gen_set_params(void *genctx, const OSSL_PARAM params[])
1102 {
1103     int ret = 0;
1104     struct ec_gen_ctx *gctx = genctx;
1105     const OSSL_PARAM *p;
1106     EC_GROUP *group = NULL;
1107
1108     COPY_INT_PARAM(params, OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, gctx->ecdh_mode);
1109
1110     COPY_UTF8_PARAM(params, OSSL_PKEY_PARAM_GROUP_NAME, gctx->group_name);
1111     COPY_UTF8_PARAM(params, OSSL_PKEY_PARAM_EC_FIELD_TYPE, gctx->field_type);
1112     COPY_UTF8_PARAM(params, OSSL_PKEY_PARAM_EC_ENCODING, gctx->encoding);
1113     COPY_UTF8_PARAM(params, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, gctx->pt_format);
1114     COPY_UTF8_PARAM(params, OSSL_PKEY_PARAM_EC_GROUP_CHECK_TYPE, gctx->group_check);
1115
1116     COPY_BN_PARAM(params, OSSL_PKEY_PARAM_EC_P, gctx->p);
1117     COPY_BN_PARAM(params, OSSL_PKEY_PARAM_EC_A, gctx->a);
1118     COPY_BN_PARAM(params, OSSL_PKEY_PARAM_EC_B, gctx->b);
1119     COPY_BN_PARAM(params, OSSL_PKEY_PARAM_EC_ORDER, gctx->order);
1120     COPY_BN_PARAM(params, OSSL_PKEY_PARAM_EC_COFACTOR, gctx->cofactor);
1121
1122     COPY_OCTET_PARAM(params, OSSL_PKEY_PARAM_EC_SEED, gctx->seed, gctx->seed_len);
1123     COPY_OCTET_PARAM(params, OSSL_PKEY_PARAM_EC_GENERATOR, gctx->gen,
1124                      gctx->gen_len);
1125
1126     COPY_OCTET_PARAM(params, OSSL_PKEY_PARAM_DHKEM_IKM, gctx->dhkem_ikm,
1127                      gctx->dhkem_ikmlen);
1128
1129     ret = 1;
1130 err:
1131     EC_GROUP_free(group);
1132     return ret;
1133 }
1134
1135 static int ec_gen_set_group_from_params(struct ec_gen_ctx *gctx)
1136 {
1137     int ret = 0;
1138     OSSL_PARAM_BLD *bld;
1139     OSSL_PARAM *params = NULL;
1140     EC_GROUP *group = NULL;
1141
1142     bld = OSSL_PARAM_BLD_new();
1143     if (bld == NULL)
1144         return 0;
1145
1146     if (gctx->encoding != NULL
1147         && !OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_EC_ENCODING,
1148                                             gctx->encoding, 0))
1149         goto err;
1150
1151     if (gctx->pt_format != NULL
1152         && !OSSL_PARAM_BLD_push_utf8_string(bld,
1153                                             OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT,
1154                                             gctx->pt_format, 0))
1155         goto err;
1156
1157     if (gctx->group_name != NULL) {
1158         if (!OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_GROUP_NAME,
1159                                              gctx->group_name, 0))
1160             goto err;
1161         /* Ignore any other parameters if there is a group name */
1162         goto build;
1163     } else if (gctx->field_type != NULL) {
1164         if (!OSSL_PARAM_BLD_push_utf8_string(bld, OSSL_PKEY_PARAM_EC_FIELD_TYPE,
1165                                              gctx->field_type, 0))
1166             goto err;
1167     } else {
1168         goto err;
1169     }
1170     if (gctx->p == NULL
1171         || gctx->a == NULL
1172         || gctx->b == NULL
1173         || gctx->order == NULL
1174         || !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_P, gctx->p)
1175         || !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_A, gctx->a)
1176         || !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_B, gctx->b)
1177         || !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_ORDER, gctx->order))
1178         goto err;
1179
1180     if (gctx->cofactor != NULL
1181         && !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_EC_COFACTOR,
1182                                    gctx->cofactor))
1183         goto err;
1184
1185     if (gctx->seed != NULL
1186         && !OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_EC_SEED,
1187                                              gctx->seed, gctx->seed_len))
1188         goto err;
1189
1190     if (gctx->gen == NULL
1191         || !OSSL_PARAM_BLD_push_octet_string(bld, OSSL_PKEY_PARAM_EC_GENERATOR,
1192                                              gctx->gen, gctx->gen_len))
1193         goto err;
1194 build:
1195     params = OSSL_PARAM_BLD_to_param(bld);
1196     if (params == NULL)
1197         goto err;
1198     group = EC_GROUP_new_from_params(params, gctx->libctx, NULL);
1199     if (group == NULL)
1200         goto err;
1201
1202     EC_GROUP_free(gctx->gen_group);
1203     gctx->gen_group = group;
1204
1205     ret = 1;
1206 err:
1207     OSSL_PARAM_free(params);
1208     OSSL_PARAM_BLD_free(bld);
1209     return ret;
1210 }
1211
1212 static const OSSL_PARAM *ec_gen_settable_params(ossl_unused void *genctx,
1213                                                 ossl_unused void *provctx)
1214 {
1215     static OSSL_PARAM settable[] = {
1216         OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, NULL, 0),
1217         OSSL_PARAM_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, NULL),
1218         OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_ENCODING, NULL, 0),
1219         OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, NULL, 0),
1220         OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_FIELD_TYPE, NULL, 0),
1221         OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_P, NULL, 0),
1222         OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_A, NULL, 0),
1223         OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_B, NULL, 0),
1224         OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_EC_GENERATOR, NULL, 0),
1225         OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_ORDER, NULL, 0),
1226         OSSL_PARAM_BN(OSSL_PKEY_PARAM_EC_COFACTOR, NULL, 0),
1227         OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_EC_SEED, NULL, 0),
1228         OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_DHKEM_IKM, NULL, 0),
1229         OSSL_PARAM_END
1230     };
1231
1232     return settable;
1233 }
1234
1235 static int ec_gen_assign_group(EC_KEY *ec, EC_GROUP *group)
1236 {
1237     if (group == NULL) {
1238         ERR_raise(ERR_LIB_PROV, PROV_R_NO_PARAMETERS_SET);
1239         return 0;
1240     }
1241     return EC_KEY_set_group(ec, group) > 0;
1242 }
1243
1244 /*
1245  * The callback arguments (osslcb & cbarg) are not used by EC_KEY generation
1246  */
1247 static void *ec_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg)
1248 {
1249     struct ec_gen_ctx *gctx = genctx;
1250     EC_KEY *ec = NULL;
1251     int ret = 0;
1252
1253     if (!ossl_prov_is_running()
1254         || gctx == NULL
1255         || (ec = EC_KEY_new_ex(gctx->libctx, NULL)) == NULL)
1256         return NULL;
1257
1258     if (gctx->gen_group == NULL) {
1259         if (!ec_gen_set_group_from_params(gctx))
1260             goto err;
1261     } else {
1262         if (gctx->encoding != NULL) {
1263             int flags = ossl_ec_encoding_name2id(gctx->encoding);
1264
1265             if (flags < 0)
1266                 goto err;
1267             EC_GROUP_set_asn1_flag(gctx->gen_group, flags);
1268         }
1269         if (gctx->pt_format != NULL) {
1270             int format = ossl_ec_pt_format_name2id(gctx->pt_format);
1271
1272             if (format < 0)
1273                 goto err;
1274             EC_GROUP_set_point_conversion_form(gctx->gen_group, format);
1275         }
1276     }
1277
1278     /* We must always assign a group, no matter what */
1279     ret = ec_gen_assign_group(ec, gctx->gen_group);
1280
1281     /* Whether you want it or not, you get a keypair, not just one half */
1282     if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
1283 #ifndef FIPS_MODULE
1284         if (gctx->dhkem_ikm != NULL && gctx->dhkem_ikmlen != 0)
1285             ret = ret && ossl_ec_generate_key_dhkem(ec, gctx->dhkem_ikm,
1286                                                     gctx->dhkem_ikmlen);
1287         else
1288 #endif
1289             ret = ret && EC_KEY_generate_key(ec);
1290     }
1291
1292     if (gctx->ecdh_mode != -1)
1293         ret = ret && ossl_ec_set_ecdh_cofactor_mode(ec, gctx->ecdh_mode);
1294
1295     if (gctx->group_check != NULL)
1296         ret = ret && ossl_ec_set_check_group_type_from_name(ec,
1297                                                             gctx->group_check);
1298     if (ret)
1299         return ec;
1300 err:
1301     /* Something went wrong, throw the key away */
1302     EC_KEY_free(ec);
1303     return NULL;
1304 }
1305
1306 #ifndef FIPS_MODULE
1307 # ifndef OPENSSL_NO_SM2
1308 /*
1309  * The callback arguments (osslcb & cbarg) are not used by EC_KEY generation
1310  */
1311 static void *sm2_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg)
1312 {
1313     struct ec_gen_ctx *gctx = genctx;
1314     EC_KEY *ec = NULL;
1315     int ret = 1;
1316
1317     if (gctx == NULL
1318         || (ec = EC_KEY_new_ex(gctx->libctx, NULL)) == NULL)
1319         return NULL;
1320
1321     if (gctx->gen_group == NULL) {
1322         if (!ec_gen_set_group_from_params(gctx))
1323             goto err;
1324     } else {
1325         if (gctx->encoding) {
1326             int flags = ossl_ec_encoding_name2id(gctx->encoding);
1327
1328             if (flags < 0)
1329                 goto err;
1330             EC_GROUP_set_asn1_flag(gctx->gen_group, flags);
1331         }
1332         if (gctx->pt_format != NULL) {
1333             int format = ossl_ec_pt_format_name2id(gctx->pt_format);
1334
1335             if (format < 0)
1336                 goto err;
1337             EC_GROUP_set_point_conversion_form(gctx->gen_group, format);
1338         }
1339     }
1340
1341     /* We must always assign a group, no matter what */
1342     ret = ec_gen_assign_group(ec, gctx->gen_group);
1343
1344     /* Whether you want it or not, you get a keypair, not just one half */
1345     if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0)
1346         ret = ret && EC_KEY_generate_key(ec);
1347
1348     if (ret)
1349         return ec;
1350 err:
1351     /* Something went wrong, throw the key away */
1352     EC_KEY_free(ec);
1353     return NULL;
1354 }
1355 # endif
1356 #endif
1357
1358 static void ec_gen_cleanup(void *genctx)
1359 {
1360     struct ec_gen_ctx *gctx = genctx;
1361
1362     if (gctx == NULL)
1363         return;
1364
1365     OPENSSL_clear_free(gctx->dhkem_ikm, gctx->dhkem_ikmlen);
1366     EC_GROUP_free(gctx->gen_group);
1367     BN_free(gctx->p);
1368     BN_free(gctx->a);
1369     BN_free(gctx->b);
1370     BN_free(gctx->order);
1371     BN_free(gctx->cofactor);
1372     OPENSSL_free(gctx->group_name);
1373     OPENSSL_free(gctx->field_type);
1374     OPENSSL_free(gctx->pt_format);
1375     OPENSSL_free(gctx->encoding);
1376     OPENSSL_free(gctx->seed);
1377     OPENSSL_free(gctx->gen);
1378     OPENSSL_free(gctx);
1379 }
1380
1381 static void *common_load(const void *reference, size_t reference_sz,
1382                          int sm2_wanted)
1383 {
1384     EC_KEY *ec = NULL;
1385
1386     if (ossl_prov_is_running() && reference_sz == sizeof(ec)) {
1387         /* The contents of the reference is the address to our object */
1388         ec = *(EC_KEY **)reference;
1389
1390         if (!common_check_sm2(ec, sm2_wanted))
1391             return NULL;
1392
1393         /* We grabbed, so we detach it */
1394         *(EC_KEY **)reference = NULL;
1395         return ec;
1396     }
1397     return NULL;
1398 }
1399
1400 static void *ec_load(const void *reference, size_t reference_sz)
1401 {
1402     return common_load(reference, reference_sz, 0);
1403 }
1404
1405 #ifndef FIPS_MODULE
1406 # ifndef OPENSSL_NO_SM2
1407 static void *sm2_load(const void *reference, size_t reference_sz)
1408 {
1409     return common_load(reference, reference_sz, 1);
1410 }
1411 # endif
1412 #endif
1413
1414 static void *ec_dup(const void *keydata_from, int selection)
1415 {
1416     if (ossl_prov_is_running())
1417         return ossl_ec_key_dup(keydata_from, selection);
1418     return NULL;
1419 }
1420
1421 const OSSL_DISPATCH ossl_ec_keymgmt_functions[] = {
1422     { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))ec_newdata },
1423     { OSSL_FUNC_KEYMGMT_GEN_INIT, (void (*)(void))ec_gen_init },
1424     { OSSL_FUNC_KEYMGMT_GEN_SET_TEMPLATE,
1425       (void (*)(void))ec_gen_set_template },
1426     { OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS, (void (*)(void))ec_gen_set_params },
1427     { OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS,
1428       (void (*)(void))ec_gen_settable_params },
1429     { OSSL_FUNC_KEYMGMT_GEN, (void (*)(void))ec_gen },
1430     { OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (void (*)(void))ec_gen_cleanup },
1431     { OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))ec_load },
1432     { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))ec_freedata },
1433     { OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*) (void))ec_get_params },
1434     { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*) (void))ec_gettable_params },
1435     { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*) (void))ec_set_params },
1436     { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*) (void))ec_settable_params },
1437     { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))ec_has },
1438     { OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))ec_match },
1439     { OSSL_FUNC_KEYMGMT_VALIDATE, (void (*)(void))ec_validate },
1440     { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ec_import },
1441     { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))ec_import_types },
1442     { OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))ec_export },
1443     { OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))ec_export_types },
1444     { OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME,
1445       (void (*)(void))ec_query_operation_name },
1446     { OSSL_FUNC_KEYMGMT_DUP, (void (*)(void))ec_dup },
1447     OSSL_DISPATCH_END
1448 };
1449
1450 #ifndef FIPS_MODULE
1451 # ifndef OPENSSL_NO_SM2
1452 const OSSL_DISPATCH ossl_sm2_keymgmt_functions[] = {
1453     { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))sm2_newdata },
1454     { OSSL_FUNC_KEYMGMT_GEN_INIT, (void (*)(void))sm2_gen_init },
1455     { OSSL_FUNC_KEYMGMT_GEN_SET_TEMPLATE,
1456       (void (*)(void))ec_gen_set_template },
1457     { OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS, (void (*)(void))ec_gen_set_params },
1458     { OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS,
1459       (void (*)(void))ec_gen_settable_params },
1460     { OSSL_FUNC_KEYMGMT_GEN, (void (*)(void))sm2_gen },
1461     { OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (void (*)(void))ec_gen_cleanup },
1462     { OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))sm2_load },
1463     { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))ec_freedata },
1464     { OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*) (void))sm2_get_params },
1465     { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*) (void))sm2_gettable_params },
1466     { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*) (void))ec_set_params },
1467     { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*) (void))sm2_settable_params },
1468     { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))ec_has },
1469     { OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))ec_match },
1470     { OSSL_FUNC_KEYMGMT_VALIDATE, (void (*)(void))sm2_validate },
1471     { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))sm2_import },
1472     { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))ec_import_types },
1473     { OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))ec_export },
1474     { OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))ec_export_types },
1475     { OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME,
1476       (void (*)(void))sm2_query_operation_name },
1477     { OSSL_FUNC_KEYMGMT_DUP, (void (*)(void))ec_dup },
1478     OSSL_DISPATCH_END
1479 };
1480 # endif
1481 #endif