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