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