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