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