PROV: Fix EC OSSL_FUNC_keymgmt_match() to work in the FIPS provider
[openssl.git] / providers / implementations / keymgmt / ec_kmgmt.c
1 /*
2  * Copyright 2020 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 <openssl/core_dispatch.h>
17 #include <openssl/core_names.h>
18 #include <openssl/bn.h>
19 #include <openssl/err.h>
20 #include <openssl/objects.h>
21 #include "crypto/bn.h"
22 #include "crypto/ec.h"
23 #include "prov/implementations.h"
24 #include "prov/providercommon.h"
25 #include "prov/providercommonerr.h"
26 #include "prov/provider_ctx.h"
27 #include "internal/param_build_set.h"
28
29 static OSSL_FUNC_keymgmt_new_fn ec_newdata;
30 static OSSL_FUNC_keymgmt_gen_init_fn ec_gen_init;
31 static OSSL_FUNC_keymgmt_gen_set_template_fn ec_gen_set_template;
32 static OSSL_FUNC_keymgmt_gen_set_params_fn ec_gen_set_params;
33 static OSSL_FUNC_keymgmt_gen_settable_params_fn ec_gen_settable_params;
34 static OSSL_FUNC_keymgmt_gen_fn ec_gen;
35 static OSSL_FUNC_keymgmt_gen_cleanup_fn ec_gen_cleanup;
36 static OSSL_FUNC_keymgmt_load_fn ec_load;
37 static OSSL_FUNC_keymgmt_free_fn ec_freedata;
38 static OSSL_FUNC_keymgmt_get_params_fn ec_get_params;
39 static OSSL_FUNC_keymgmt_gettable_params_fn ec_gettable_params;
40 static OSSL_FUNC_keymgmt_set_params_fn ec_set_params;
41 static OSSL_FUNC_keymgmt_settable_params_fn ec_settable_params;
42 static OSSL_FUNC_keymgmt_has_fn ec_has;
43 static OSSL_FUNC_keymgmt_match_fn ec_match;
44 static OSSL_FUNC_keymgmt_validate_fn ec_validate;
45 static OSSL_FUNC_keymgmt_import_fn ec_import;
46 static OSSL_FUNC_keymgmt_import_types_fn ec_import_types;
47 static OSSL_FUNC_keymgmt_export_fn ec_export;
48 static OSSL_FUNC_keymgmt_export_types_fn ec_export_types;
49 static OSSL_FUNC_keymgmt_query_operation_name_fn ec_query_operation_name;
50
51 #define EC_DEFAULT_MD "SHA256"
52 #define EC_POSSIBLE_SELECTIONS                                                 \
53     (OSSL_KEYMGMT_SELECT_KEYPAIR | OSSL_KEYMGMT_SELECT_ALL_PARAMETERS)
54
55 static
56 const char *ec_query_operation_name(int operation_id)
57 {
58     switch (operation_id) {
59     case OSSL_OP_KEYEXCH:
60         return "ECDH";
61     case OSSL_OP_SIGNATURE:
62         return "ECDSA";
63     }
64     return NULL;
65 }
66
67 static ossl_inline
68 int domparams_to_params(const EC_KEY *ec, OSSL_PARAM_BLD *tmpl,
69                         OSSL_PARAM params[])
70 {
71     const EC_GROUP *ecg;
72     int curve_nid;
73
74     if (ec == NULL)
75         return 0;
76
77     ecg = EC_KEY_get0_group(ec);
78     if (ecg == NULL)
79         return 0;
80
81     curve_nid = EC_GROUP_get_curve_name(ecg);
82
83     if (curve_nid == NID_undef) {
84         /* TODO(3.0): should we support explicit parameters curves? */
85         return 0;
86     } else {
87         /* named curve */
88         const char *curve_name = NULL;
89
90         if ((curve_name = ec_curve_nid2name(curve_nid)) == NULL)
91             return 0;
92         if (!ossl_param_build_set_utf8_string(tmpl, params,
93                                               OSSL_PKEY_PARAM_GROUP_NAME,
94                                               curve_name))
95
96             return 0;
97     }
98
99     return 1;
100 }
101
102 /*
103  * Callers of key_to_params MUST make sure that domparams_to_params is also
104  * called!
105  *
106  * This function only exports the bare keypair, domain parameters and other
107  * parameters are exported separately.
108  */
109 static ossl_inline
110 int key_to_params(const EC_KEY *eckey, OSSL_PARAM_BLD *tmpl,
111                   OSSL_PARAM params[], int include_private,
112                   unsigned char **pub_key)
113 {
114     BIGNUM *x = NULL, *y = NULL;
115     const BIGNUM *priv_key = NULL;
116     const EC_POINT *pub_point = NULL;
117     const EC_GROUP *ecg = NULL;
118     size_t pub_key_len = 0;
119     int ret = 0;
120     BN_CTX *bnctx = NULL;
121
122     if (eckey == NULL
123         || (ecg = EC_KEY_get0_group(eckey)) == NULL)
124         return 0;
125
126     priv_key = EC_KEY_get0_private_key(eckey);
127     pub_point = EC_KEY_get0_public_key(eckey);
128
129     if (pub_point != NULL) {
130         OSSL_PARAM *p = NULL, *px = NULL, *py = NULL;
131         /*
132          * EC_POINT_point2buf() can generate random numbers in some
133          * implementations so we need to ensure we use the correct libctx.
134          */
135         bnctx = BN_CTX_new_ex(ec_key_get_libctx(eckey));
136         if (bnctx == NULL)
137             goto err;
138
139
140         /* If we are doing a get then check first before decoding the point */
141         if (tmpl == NULL) {
142             p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_PUB_KEY);
143             px = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_EC_PUB_X);
144             py = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_EC_PUB_Y);
145         }
146
147         if (p != NULL || tmpl != NULL) {
148             /* convert pub_point to a octet string according to the SECG standard */
149             if ((pub_key_len = EC_POINT_point2buf(ecg, pub_point,
150                                                   POINT_CONVERSION_COMPRESSED,
151                                                   pub_key, bnctx)) == 0
152                 || !ossl_param_build_set_octet_string(tmpl, p,
153                                                       OSSL_PKEY_PARAM_PUB_KEY,
154                                                       *pub_key, pub_key_len))
155                 goto err;
156         }
157         if (px != NULL || py != NULL) {
158             if (px != NULL)
159                 x = BN_CTX_get(bnctx);
160             if (py != NULL)
161                 y = BN_CTX_get(bnctx);
162
163             if (!EC_POINT_get_affine_coordinates(ecg, pub_point, x, y, bnctx))
164                 goto err;
165             if (px != NULL
166                 && !ossl_param_build_set_bn(tmpl, px,
167                                             OSSL_PKEY_PARAM_EC_PUB_X, x))
168                 goto err;
169             if (py != NULL
170                 && !ossl_param_build_set_bn(tmpl, py,
171                                             OSSL_PKEY_PARAM_EC_PUB_Y, y))
172                 goto err;
173         }
174     }
175
176     if (priv_key != NULL && include_private) {
177         size_t sz;
178         int ecbits;
179
180         /*
181          * Key import/export should never leak the bit length of the secret
182          * scalar in the key.
183          *
184          * For this reason, on export we use padded BIGNUMs with fixed length.
185          *
186          * When importing we also should make sure that, even if short lived,
187          * the newly created BIGNUM is marked with the BN_FLG_CONSTTIME flag as
188          * soon as possible, so that any processing of this BIGNUM might opt for
189          * constant time implementations in the backend.
190          *
191          * Setting the BN_FLG_CONSTTIME flag alone is never enough, we also have
192          * to preallocate the BIGNUM internal buffer to a fixed public size big
193          * enough that operations performed during the processing never trigger
194          * a realloc which would leak the size of the scalar through memory
195          * accesses.
196          *
197          * Fixed Length
198          * ------------
199          *
200          * The order of the large prime subgroup of the curve is our choice for
201          * a fixed public size, as that is generally the upper bound for
202          * generating a private key in EC cryptosystems and should fit all valid
203          * secret scalars.
204          *
205          * For padding on export we just use the bit length of the order
206          * converted to bytes (rounding up).
207          *
208          * For preallocating the BIGNUM storage we look at the number of "words"
209          * required for the internal representation of the order, and we
210          * preallocate 2 extra "words" in case any of the subsequent processing
211          * might temporarily overflow the order length.
212          */
213         ecbits = EC_GROUP_order_bits(ecg);
214         if (ecbits <= 0)
215             goto err;
216         sz = (ecbits + 7 ) / 8;
217
218         if (!ossl_param_build_set_bn_pad(tmpl, params,
219                                          OSSL_PKEY_PARAM_PRIV_KEY,
220                                          priv_key, sz))
221             goto err;
222     }
223     ret = 1;
224  err:
225     BN_CTX_free(bnctx);
226     return ret;
227 }
228
229 static ossl_inline
230 int otherparams_to_params(const EC_KEY *ec, OSSL_PARAM_BLD *tmpl,
231                           OSSL_PARAM params[])
232 {
233     int ecdh_cofactor_mode = 0;
234
235     if (ec == NULL)
236         return 0;
237
238     ecdh_cofactor_mode =
239         (EC_KEY_get_flags(ec) & EC_FLAG_COFACTOR_ECDH) ? 1 : 0;
240     return ossl_param_build_set_int(tmpl, params,
241                                     OSSL_PKEY_PARAM_USE_COFACTOR_ECDH,
242                                     ecdh_cofactor_mode);
243 }
244
245 static
246 void *ec_newdata(void *provctx)
247 {
248     return EC_KEY_new_with_libctx(PROV_LIBRARY_CONTEXT_OF(provctx), NULL);
249 }
250
251 static
252 void ec_freedata(void *keydata)
253 {
254     EC_KEY_free(keydata);
255 }
256
257 static
258 int ec_has(void *keydata, int selection)
259 {
260     EC_KEY *ec = keydata;
261     int ok = 0;
262
263     if (ec != NULL) {
264         if ((selection & EC_POSSIBLE_SELECTIONS) != 0)
265             ok = 1;
266
267         if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
268             ok = ok && (EC_KEY_get0_public_key(ec) != NULL);
269         if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
270             ok = ok && (EC_KEY_get0_private_key(ec) != NULL);
271         if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
272             ok = ok && (EC_KEY_get0_group(ec) != NULL);
273         /*
274          * We consider OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS to always be
275          * available, so no extra check is needed other than the previous one
276          * against EC_POSSIBLE_SELECTIONS.
277          */
278     }
279     return ok;
280 }
281
282 static int ec_match(const void *keydata1, const void *keydata2, int selection)
283 {
284     const EC_KEY *ec1 = keydata1;
285     const EC_KEY *ec2 = keydata2;
286     const EC_GROUP *group_a = EC_KEY_get0_group(ec1);
287     const EC_GROUP *group_b = EC_KEY_get0_group(ec2);
288     BN_CTX *ctx = BN_CTX_new_ex(ec_key_get_libctx(ec1));
289     int ok = 1;
290
291     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
292         ok = ok && group_a != NULL && group_b != NULL
293             && EC_GROUP_cmp(group_a, group_b, ctx) == 0;
294     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
295         const BIGNUM *pa = EC_KEY_get0_private_key(ec1);
296         const BIGNUM *pb = EC_KEY_get0_private_key(ec2);
297
298         ok = ok && BN_cmp(pa, pb) == 0;
299     }
300     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
301         const EC_POINT *pa = EC_KEY_get0_public_key(ec1);
302         const EC_POINT *pb = EC_KEY_get0_public_key(ec2);
303
304         ok = ok && EC_POINT_cmp(group_b, pa, pb, ctx) == 0;
305     }
306     BN_CTX_free(ctx);
307     return ok;
308 }
309
310 static
311 int ec_import(void *keydata, int selection, const OSSL_PARAM params[])
312 {
313     EC_KEY *ec = keydata;
314     int ok = 1;
315
316     if (ec == NULL)
317         return 0;
318
319     /*
320      * In this implementation, we can export/import only keydata in the
321      * following combinations:
322      *   - domain parameters only
323      *   - public key with associated domain parameters (+optional other params)
324      *   - private key with associated public key and domain parameters
325      *         (+optional other params)
326      *
327      * This means:
328      *   - domain parameters must always be requested
329      *   - private key must be requested alongside public key
330      *   - other parameters must be requested only alongside a key
331      */
332     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0)
333         return 0;
334     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0
335             && (selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) == 0)
336         return 0;
337     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0
338             && (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
339         return 0;
340
341     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
342         ok = ok && ec_key_domparams_fromdata(ec, params);
343     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
344         int include_private =
345             selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0;
346
347         ok = ok && ec_key_fromdata(ec, params, include_private);
348     }
349     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0)
350         ok = ok && ec_key_otherparams_fromdata(ec, params);
351
352     return ok;
353 }
354
355 static
356 int ec_export(void *keydata, int selection, OSSL_CALLBACK *param_cb,
357               void *cbarg)
358 {
359     EC_KEY *ec = keydata;
360     OSSL_PARAM_BLD *tmpl;
361     OSSL_PARAM *params = NULL;
362     unsigned char *pub_key = NULL;
363     int ok = 1;
364
365     if (ec == NULL)
366         return 0;
367
368     /*
369      * In this implementation, we can export/import only keydata in the
370      * following combinations:
371      *   - domain parameters only
372      *   - public key with associated domain parameters (+optional other params)
373      *   - private key with associated public key and domain parameters
374      *         (+optional other params)
375      *
376      * This means:
377      *   - domain parameters must always be requested
378      *   - private key must be requested alongside public key
379      *   - other parameters must be requested only alongside a key
380      */
381     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0)
382         return 0;
383     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0
384             && (selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) == 0)
385         return 0;
386     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0
387             && (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
388         return 0;
389
390     tmpl = OSSL_PARAM_BLD_new();
391     if (tmpl == NULL)
392         return 0;
393
394     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
395         ok = ok && domparams_to_params(ec, tmpl, NULL);
396
397     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
398         int include_private =
399             selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0;
400
401         ok = ok && key_to_params(ec, tmpl, NULL, include_private, &pub_key);
402     }
403     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0)
404         ok = ok && otherparams_to_params(ec, tmpl, NULL);
405
406     if (ok && (params = OSSL_PARAM_BLD_to_param(tmpl)) != NULL)
407         ok = param_cb(params, cbarg);
408
409     OSSL_PARAM_BLD_free_params(params);
410     OSSL_PARAM_BLD_free(tmpl);
411     OPENSSL_free(pub_key);
412     return ok;
413 }
414
415 /* IMEXPORT = IMPORT + EXPORT */
416
417 # define EC_IMEXPORTABLE_DOM_PARAMETERS                          \
418     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, NULL, 0)
419 # define EC_IMEXPORTABLE_PUBLIC_KEY                              \
420     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY, NULL, 0)
421 # define EC_IMEXPORTABLE_PRIVATE_KEY                             \
422     OSSL_PARAM_BN(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0)
423 # define EC_IMEXPORTABLE_OTHER_PARAMETERS                        \
424     OSSL_PARAM_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, NULL)
425
426 /*
427  * Include all the possible combinations of OSSL_PARAM arrays for
428  * ec_imexport_types().
429  *
430  * They are in a separate file as it is ~100 lines of unreadable and
431  * uninteresting machine generated stuff.
432  *
433  * TODO(3.0): the generated list looks quite ugly, as to cover all possible
434  * combinations of the bits in `selection`, it also includes combinations that
435  * are not really useful: we might want to consider alternatives to this
436  * solution.
437  */
438 #include "ec_kmgmt_imexport.inc"
439
440 static ossl_inline
441 const OSSL_PARAM *ec_imexport_types(int selection)
442 {
443     int type_select = 0;
444
445     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
446         type_select += 1;
447     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
448         type_select += 2;
449     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
450         type_select += 4;
451     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0)
452         type_select += 8;
453     return ec_types[type_select];
454 }
455
456 static
457 const OSSL_PARAM *ec_import_types(int selection)
458 {
459     return ec_imexport_types(selection);
460 }
461
462 static
463 const OSSL_PARAM *ec_export_types(int selection)
464 {
465     return ec_imexport_types(selection);
466 }
467
468 static
469 int ec_get_params(void *key, OSSL_PARAM params[])
470 {
471     int ret;
472     EC_KEY *eck = key;
473     const EC_GROUP *ecg = NULL;
474     OSSL_PARAM *p;
475     unsigned char *pub_key = NULL;
476
477     ecg = EC_KEY_get0_group(eck);
478     if (ecg == NULL)
479         return 0;
480
481     if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_MAX_SIZE)) != NULL
482         && !OSSL_PARAM_set_int(p, ECDSA_size(eck)))
483         return 0;
484     if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_BITS)) != NULL
485         && !OSSL_PARAM_set_int(p, EC_GROUP_order_bits(ecg)))
486         return 0;
487     if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_SECURITY_BITS)) != NULL) {
488         int ecbits, sec_bits;
489
490         ecbits = EC_GROUP_order_bits(ecg);
491
492         /*
493          * The following estimates are based on the values published
494          * in Table 2 of "NIST Special Publication 800-57 Part 1 Revision 4"
495          * at http://dx.doi.org/10.6028/NIST.SP.800-57pt1r4 .
496          *
497          * Note that the above reference explicitly categorizes algorithms in a
498          * discrete set of values {80, 112, 128, 192, 256}, and that it is
499          * relevant only for NIST approved Elliptic Curves, while OpenSSL
500          * applies the same logic also to other curves.
501          *
502          * Classifications produced by other standardazing bodies might differ,
503          * so the results provided for "bits of security" by this provider are
504          * to be considered merely indicative, and it is the users'
505          * responsibility to compare these values against the normative
506          * references that may be relevant for their intent and purposes.
507          */
508         if (ecbits >= 512)
509             sec_bits = 256;
510         else if (ecbits >= 384)
511             sec_bits = 192;
512         else if (ecbits >= 256)
513             sec_bits = 128;
514         else if (ecbits >= 224)
515             sec_bits = 112;
516         else if (ecbits >= 160)
517             sec_bits = 80;
518         else
519             sec_bits = ecbits / 2;
520
521         if (!OSSL_PARAM_set_int(p, sec_bits))
522             return 0;
523     }
524
525     if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_DEFAULT_DIGEST)) != NULL
526         && !OSSL_PARAM_set_utf8_string(p, EC_DEFAULT_MD))
527         return 0;
528
529     p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_USE_COFACTOR_ECDH);
530     if (p != NULL) {
531         int ecdh_cofactor_mode = 0;
532
533         ecdh_cofactor_mode =
534             (EC_KEY_get_flags(eck) & EC_FLAG_COFACTOR_ECDH) ? 1 : 0;
535
536         if (!OSSL_PARAM_set_int(p, ecdh_cofactor_mode))
537             return 0;
538     }
539     if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_TLS_ENCODED_PT)) != NULL) {
540         BN_CTX *ctx = BN_CTX_new_ex(ec_key_get_libctx(key));
541
542         if (ctx == NULL)
543             return 0;
544         p->return_size = EC_POINT_point2oct(EC_KEY_get0_group(key),
545                                             EC_KEY_get0_public_key(key),
546                                             POINT_CONVERSION_UNCOMPRESSED,
547                                             p->data, p->return_size, ctx);
548         BN_CTX_free(ctx);
549         if (p->return_size == 0)
550             return 0;
551     }
552
553     ret = domparams_to_params(eck, NULL, params)
554           && key_to_params(eck, NULL, params, 1, &pub_key)
555           && otherparams_to_params(eck, NULL, params);
556     OPENSSL_free(pub_key);
557     return ret;
558 }
559
560 static const OSSL_PARAM ec_known_gettable_params[] = {
561     OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL),
562     OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL),
563     OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL),
564     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_TLS_ENCODED_PT, NULL, 0),
565     EC_IMEXPORTABLE_DOM_PARAMETERS,
566     EC_IMEXPORTABLE_PUBLIC_KEY,
567     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_EC_PUB_X, NULL, 0),
568     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_EC_PUB_Y, NULL, 0),
569     EC_IMEXPORTABLE_PRIVATE_KEY,
570     EC_IMEXPORTABLE_OTHER_PARAMETERS,
571     OSSL_PARAM_END
572 };
573
574 static
575 const OSSL_PARAM *ec_gettable_params(void *provctx)
576 {
577     return ec_known_gettable_params;
578 }
579
580 static const OSSL_PARAM ec_known_settable_params[] = {
581     OSSL_PARAM_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, NULL),
582     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_TLS_ENCODED_PT, NULL, 0),
583     OSSL_PARAM_END
584 };
585
586 static
587 const OSSL_PARAM *ec_settable_params(void *provctx)
588 {
589     return ec_known_settable_params;
590 }
591
592 static
593 int ec_set_params(void *key, const OSSL_PARAM params[])
594 {
595     EC_KEY *eck = key;
596     const OSSL_PARAM *p;
597
598     p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_TLS_ENCODED_PT);
599     if (p != NULL) {
600         BN_CTX *ctx = BN_CTX_new_ex(ec_key_get_libctx(key));
601         int ret = 1;
602
603         if (ctx == NULL
604                 || p->data_type != OSSL_PARAM_OCTET_STRING
605                 || !EC_KEY_oct2key(key, p->data, p->data_size, ctx))
606             ret = 0;
607         BN_CTX_free(ctx);
608         if (!ret)
609             return 0;
610     }
611
612     return ec_key_otherparams_fromdata(eck, params);
613 }
614
615 static
616 int ec_validate(void *keydata, int selection)
617 {
618     EC_KEY *eck = keydata;
619     int ok = 0;
620     BN_CTX *ctx = BN_CTX_new_ex(ec_key_get_libctx(eck));
621
622     if (ctx == NULL)
623         return 0;
624
625     if ((selection & EC_POSSIBLE_SELECTIONS) != 0)
626         ok = 1;
627
628     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
629         ok = ok && EC_GROUP_check(EC_KEY_get0_group(eck), ctx);
630
631     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
632         ok = ok && ec_key_public_check(eck, ctx);
633
634     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
635         ok = ok && ec_key_private_check(eck);
636
637     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == OSSL_KEYMGMT_SELECT_KEYPAIR)
638         ok = ok && ec_key_pairwise_check(eck, ctx);
639
640     BN_CTX_free(ctx);
641     return ok;
642 }
643
644 struct ec_gen_ctx {
645     OPENSSL_CTX *libctx;
646     EC_GROUP *gen_group;
647     int selection;
648     int ecdh_mode;
649 };
650
651 static void *ec_gen_init(void *provctx, int selection)
652 {
653     OPENSSL_CTX *libctx = PROV_LIBRARY_CONTEXT_OF(provctx);
654     struct ec_gen_ctx *gctx = NULL;
655
656     if ((selection & (EC_POSSIBLE_SELECTIONS)) == 0)
657         return NULL;
658
659     if ((gctx = OPENSSL_zalloc(sizeof(*gctx))) != NULL) {
660         gctx->libctx = libctx;
661         gctx->gen_group = NULL;
662         gctx->selection = selection;
663         gctx->ecdh_mode = 0;
664     }
665     return gctx;
666 }
667
668 static int ec_gen_set_group(void *genctx, int nid)
669 {
670     struct ec_gen_ctx *gctx = genctx;
671     EC_GROUP *group;
672
673     group = EC_GROUP_new_by_curve_name_with_libctx(gctx->libctx, NULL, nid);
674     if (group == NULL) {
675         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CURVE);
676         return 0;
677     }
678     EC_GROUP_free(gctx->gen_group);
679     gctx->gen_group = group;
680     return 1;
681 }
682 static int ec_gen_set_template(void *genctx, void *templ)
683 {
684     struct ec_gen_ctx *gctx = genctx;
685     EC_KEY *ec = templ;
686     const EC_GROUP *ec_group;
687
688     if (gctx == NULL || ec == NULL)
689         return 0;
690     if ((ec_group = EC_KEY_get0_group(ec)) == NULL)
691         return 0;
692     return ec_gen_set_group(gctx, EC_GROUP_get_curve_name(ec_group));
693 }
694
695 static int ec_gen_set_params(void *genctx, const OSSL_PARAM params[])
696 {
697     struct ec_gen_ctx *gctx = genctx;
698     const OSSL_PARAM *p;
699
700     if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_USE_COFACTOR_ECDH))
701         != NULL) {
702         if (!OSSL_PARAM_get_int(p, &gctx->ecdh_mode))
703             return 0;
704     }
705     if ((p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_GROUP_NAME))
706         != NULL) {
707         const char *curve_name = NULL;
708         int ret = 0;
709
710         switch (p->data_type) {
711         case OSSL_PARAM_UTF8_STRING:
712             /* The OSSL_PARAM functions have no support for this */
713             curve_name = p->data;
714             ret = (curve_name != NULL);
715             break;
716         case OSSL_PARAM_UTF8_PTR:
717             ret = OSSL_PARAM_get_utf8_ptr(p, &curve_name);
718             break;
719         }
720
721         if (ret) {
722             int nid = ec_curve_name2nid(curve_name);
723
724             if (nid == NID_undef) {
725                 ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CURVE);
726                 ret = 0;
727             } else {
728                 ret = ec_gen_set_group(gctx, nid);
729             }
730         }
731         return ret;
732     }
733     return 1;
734 }
735
736 static const OSSL_PARAM *ec_gen_settable_params(void *provctx)
737 {
738     static OSSL_PARAM settable[] = {
739         OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, NULL, 0),
740         OSSL_PARAM_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, NULL),
741         OSSL_PARAM_END
742     };
743
744     return settable;
745 }
746
747 static int ec_gen_assign_group(EC_KEY *ec, EC_GROUP *group)
748 {
749     if (group == NULL) {
750         ERR_raise(ERR_LIB_PROV, PROV_R_NO_PARAMETERS_SET);
751         return 0;
752     }
753     return EC_KEY_set_group(ec, group) > 0;
754 }
755
756 /*
757  * The callback arguments (osslcb & cbarg) are not used by EC_KEY generation
758  */
759 static void *ec_gen(void *genctx, OSSL_CALLBACK *osslcb, void *cbarg)
760 {
761     struct ec_gen_ctx *gctx = genctx;
762     EC_KEY *ec = NULL;
763     int ret = 1;                 /* Start optimistically */
764
765     if (gctx == NULL
766         || (ec = EC_KEY_new_with_libctx(gctx->libctx, NULL)) == NULL)
767         return NULL;
768
769     /* We must always assign a group, no matter what */
770     ret = ec_gen_assign_group(ec, gctx->gen_group);
771     /* Whether you want it or not, you get a keypair, not just one half */
772     if ((gctx->selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0)
773         ret = ret && EC_KEY_generate_key(ec);
774
775     if (gctx->ecdh_mode != -1)
776         ret = ret && ec_set_ecdh_cofactor_mode(ec, gctx->ecdh_mode);
777
778     if (ret)
779         return ec;
780
781     /* Something went wrong, throw the key away */
782     EC_KEY_free(ec);
783     return NULL;
784 }
785
786 static void ec_gen_cleanup(void *genctx)
787 {
788     struct ec_gen_ctx *gctx = genctx;
789
790     if (gctx == NULL)
791         return;
792
793     EC_GROUP_free(gctx->gen_group);
794     OPENSSL_free(gctx);
795 }
796
797 void *ec_load(const void *reference, size_t reference_sz)
798 {
799     EC_KEY *ec = NULL;
800
801     if (reference_sz == sizeof(ec)) {
802         /* The contents of the reference is the address to our object */
803         ec = *(EC_KEY **)reference;
804         /* We grabbed, so we detach it */
805         *(EC_KEY **)reference = NULL;
806         return ec;
807     }
808     return NULL;
809 }
810
811 const OSSL_DISPATCH ec_keymgmt_functions[] = {
812     { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))ec_newdata },
813     { OSSL_FUNC_KEYMGMT_GEN_INIT, (void (*)(void))ec_gen_init },
814     { OSSL_FUNC_KEYMGMT_GEN_SET_TEMPLATE,
815       (void (*)(void))ec_gen_set_template },
816     { OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS, (void (*)(void))ec_gen_set_params },
817     { OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS,
818       (void (*)(void))ec_gen_settable_params },
819     { OSSL_FUNC_KEYMGMT_GEN, (void (*)(void))ec_gen },
820     { OSSL_FUNC_KEYMGMT_GEN_CLEANUP, (void (*)(void))ec_gen_cleanup },
821     { OSSL_FUNC_KEYMGMT_LOAD, (void (*)(void))ec_load },
822     { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))ec_freedata },
823     { OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*) (void))ec_get_params },
824     { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*) (void))ec_gettable_params },
825     { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*) (void))ec_set_params },
826     { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*) (void))ec_settable_params },
827     { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))ec_has },
828     { OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))ec_match },
829     { OSSL_FUNC_KEYMGMT_VALIDATE, (void (*)(void))ec_validate },
830     { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ec_import },
831     { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))ec_import_types },
832     { OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))ec_export },
833     { OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))ec_export_types },
834     { OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME,
835       (void (*)(void))ec_query_operation_name },
836     { 0, NULL }
837 };