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