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