e2cc9ca7ede81564517756bfe8b3729d777fa772
[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_numbers.h>
17 #include <openssl/core_names.h>
18 #include <openssl/bn.h>
19 #include <openssl/objects.h>
20 #include <openssl/params.h>
21 #include "crypto/bn.h"
22 #include "crypto/ec.h"
23 #include "internal/param_build.h"
24 #include "prov/implementations.h"
25 #include "prov/providercommon.h"
26 #include "prov/provider_ctx.h"
27
28 static OSSL_OP_keymgmt_new_fn ec_newdata;
29 static OSSL_OP_keymgmt_free_fn ec_freedata;
30 static OSSL_OP_keymgmt_get_params_fn ec_get_params;
31 static OSSL_OP_keymgmt_gettable_params_fn ec_gettable_params;
32 static OSSL_OP_keymgmt_set_params_fn ec_set_params;
33 static OSSL_OP_keymgmt_settable_params_fn ec_settable_params;
34 static OSSL_OP_keymgmt_has_fn ec_has;
35 static OSSL_OP_keymgmt_match_fn ec_match;
36 static OSSL_OP_keymgmt_validate_fn ec_validate;
37 static OSSL_OP_keymgmt_import_fn ec_import;
38 static OSSL_OP_keymgmt_import_types_fn ec_import_types;
39 static OSSL_OP_keymgmt_export_fn ec_export;
40 static OSSL_OP_keymgmt_export_types_fn ec_export_types;
41 static OSSL_OP_keymgmt_query_operation_name_fn ec_query_operation_name;
42
43 #define EC_POSSIBLE_SELECTIONS                 \
44     (OSSL_KEYMGMT_SELECT_KEYPAIR | OSSL_KEYMGMT_SELECT_ALL_PARAMETERS )
45
46 static
47 const char *ec_query_operation_name(int operation_id)
48 {
49     switch (operation_id) {
50     case OSSL_OP_KEYEXCH:
51         return "ECDH";
52     case OSSL_OP_SIGNATURE:
53         return "ECDSA";
54     }
55     return NULL;
56 }
57
58 static ossl_inline
59 int domparams_to_params(const EC_KEY *ec, OSSL_PARAM_BLD *tmpl)
60 {
61     const EC_GROUP *ecg;
62     int curve_nid;
63
64     if (ec == NULL)
65         return 0;
66
67     ecg = EC_KEY_get0_group(ec);
68     if (ecg == NULL)
69         return 0;
70
71     curve_nid = EC_GROUP_get_curve_name(ecg);
72
73     if (curve_nid == NID_undef) {
74         /* explicit parameters */
75
76         /*
77          * TODO(3.0): should we support explicit parameters curves?
78          */
79         return 0;
80     } else {
81         /* named curve */
82         const char *curve_name = NULL;
83
84         if ((curve_name = ec_curve_nid2name(curve_nid)) == NULL)
85             return 0;
86
87         if (!ossl_param_bld_push_utf8_string(tmpl, OSSL_PKEY_PARAM_EC_NAME,
88                                              curve_name, 0))
89             return 0;
90     }
91
92     return 1;
93 }
94
95 /*
96  * Callers of key_to_params MUST make sure that domparams_to_params is also
97  * called!
98  *
99  * This function only exports the bare keypair, domain parameters and other
100  * parameters are exported separately.
101  */
102 static ossl_inline
103 int key_to_params(const EC_KEY *eckey, OSSL_PARAM_BLD *tmpl, int include_private)
104 {
105     const BIGNUM *priv_key = NULL;
106     const EC_POINT *pub_point = NULL;
107     const EC_GROUP *ecg = NULL;
108     unsigned char *pub_key = NULL;
109     size_t pub_key_len = 0;
110     int ret = 0;
111
112     if (eckey == NULL
113         || (ecg = EC_KEY_get0_group(eckey)) == NULL)
114         return 0;
115
116     priv_key = EC_KEY_get0_private_key(eckey);
117     pub_point = EC_KEY_get0_public_key(eckey);
118
119     if (pub_point != NULL) {
120         /* convert pub_point to a octet string according to the SECG standard */
121         if ((pub_key_len = EC_POINT_point2buf(ecg, pub_point,
122                                               POINT_CONVERSION_COMPRESSED,
123                                               &pub_key, NULL)) == 0
124             || !ossl_param_bld_push_octet_string(tmpl,
125                                                  OSSL_PKEY_PARAM_PUB_KEY,
126                                                  pub_key, pub_key_len))
127             goto err;
128     }
129
130     if (priv_key != NULL && include_private) {
131         size_t sz;
132         int ecbits;
133
134         /*
135          * Key import/export should never leak the bit length of the secret
136          * scalar in the key.
137          *
138          * For this reason, on export we use padded BIGNUMs with fixed length.
139          *
140          * When importing we also should make sure that, even if short lived,
141          * the newly created BIGNUM is marked with the BN_FLG_CONSTTIME flag as
142          * soon as possible, so that any processing of this BIGNUM might opt for
143          * constant time implementations in the backend.
144          *
145          * Setting the BN_FLG_CONSTTIME flag alone is never enough, we also have
146          * to preallocate the BIGNUM internal buffer to a fixed public size big
147          * enough that operations performed during the processing never trigger
148          * a realloc which would leak the size of the scalar through memory
149          * accesses.
150          *
151          * Fixed Length
152          * ------------
153          *
154          * The order of the large prime subgroup of the curve is our choice for
155          * a fixed public size, as that is generally the upper bound for
156          * generating a private key in EC cryptosystems and should fit all valid
157          * secret scalars.
158          *
159          * For padding on export we just use the bit length of the order
160          * converted to bytes (rounding up).
161          *
162          * For preallocating the BIGNUM storage we look at the number of "words"
163          * required for the internal representation of the order, and we
164          * preallocate 2 extra "words" in case any of the subsequent processing
165          * might temporarily overflow the order length.
166          */
167         ecbits = EC_GROUP_order_bits(ecg);
168         if (ecbits <= 0)
169             goto err;
170         sz = (ecbits + 7 ) / 8;
171         if (!ossl_param_bld_push_BN_pad(tmpl,
172                                         OSSL_PKEY_PARAM_PRIV_KEY,
173                                         priv_key, sz))
174             goto err;
175     }
176
177     ret = 1;
178
179  err:
180     OPENSSL_free(pub_key);
181     return ret;
182 }
183
184 static ossl_inline
185 int otherparams_to_params(const EC_KEY *ec, OSSL_PARAM_BLD *tmpl)
186 {
187     int ecdh_cofactor_mode = 0;
188
189     if (ec == NULL)
190         return 0;
191
192     ecdh_cofactor_mode =
193         (EC_KEY_get_flags(ec) & EC_FLAG_COFACTOR_ECDH) ? 1 : 0;
194     if (!ossl_param_bld_push_int(tmpl,
195                 OSSL_PKEY_PARAM_USE_COFACTOR_ECDH,
196                 ecdh_cofactor_mode))
197         return 0;
198
199     return 1;
200 }
201
202 static
203 void *ec_newdata(void *provctx)
204 {
205     return EC_KEY_new_ex(PROV_LIBRARY_CONTEXT_OF(provctx));
206 }
207
208 static
209 void ec_freedata(void *keydata)
210 {
211     EC_KEY_free(keydata);
212 }
213
214 static
215 int ec_has(void *keydata, int selection)
216 {
217     EC_KEY *ec = keydata;
218     int ok = 0;
219
220     if (ec != NULL) {
221         if ((selection & EC_POSSIBLE_SELECTIONS) != 0)
222             ok = 1;
223
224         if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
225             ok = ok && (EC_KEY_get0_public_key(ec) != NULL);
226         if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
227             ok = ok && (EC_KEY_get0_private_key(ec) != NULL);
228         if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
229             ok = ok && (EC_KEY_get0_group(ec) != NULL);
230         /*
231          * We consider OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS to always be
232          * available, so no extra check is needed other than the previous one
233          * against EC_POSSIBLE_SELECTIONS.
234          */
235     }
236     return ok;
237 }
238
239 static int ec_match(const void *keydata1, const void *keydata2, int selection)
240 {
241     const EC_KEY *ec1 = keydata1;
242     const EC_KEY *ec2 = keydata2;
243     const EC_GROUP *group_a = EC_KEY_get0_group(ec1);
244     const EC_GROUP *group_b = EC_KEY_get0_group(ec2);
245     int ok = 1;
246
247     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
248         ok = ok && group_a != NULL && group_b != NULL
249             && EC_GROUP_cmp(group_a, group_b, NULL) == 0;
250     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) {
251         const BIGNUM *pa = EC_KEY_get0_private_key(ec1);
252         const BIGNUM *pb = EC_KEY_get0_private_key(ec2);
253
254         ok = ok && BN_cmp(pa, pb) == 0;
255     }
256     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) {
257         const EC_POINT *pa = EC_KEY_get0_public_key(ec1);
258         const EC_POINT *pb = EC_KEY_get0_public_key(ec2);
259
260         ok = ok && EC_POINT_cmp(group_b, pa, pb, NULL);
261     }
262     return ok;
263 }
264
265 static
266 int ec_import(void *keydata, int selection, const OSSL_PARAM params[])
267 {
268     EC_KEY *ec = keydata;
269     int ok = 1;
270
271     if (ec == NULL)
272         return 0;
273
274     /*
275      * In this implementation, we can export/import only keydata in the
276      * following combinations:
277      *   - domain parameters only
278      *   - public key with associated domain parameters (+optional other params)
279      *   - private key with associated public key and domain parameters
280      *         (+optional other params)
281      *
282      * This means:
283      *   - domain parameters must always be requested
284      *   - private key must be requested alongside public key
285      *   - other parameters must be requested only alongside a key
286      */
287     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0)
288         return 0;
289     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0
290             && (selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) == 0)
291         return 0;
292     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0
293             && (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
294         return 0;
295
296     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
297         ok = ok && ec_key_domparams_fromdata(ec, params);
298     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
299         int include_private =
300             selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0;
301
302         ok = ok && ec_key_fromdata(ec, params, include_private);
303     }
304     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0)
305         ok = ok && ec_key_otherparams_fromdata(ec, params);
306
307     return ok;
308 }
309
310 static
311 int ec_export(void *keydata, int selection, OSSL_CALLBACK *param_cb,
312               void *cbarg)
313 {
314     EC_KEY *ec = keydata;
315     OSSL_PARAM_BLD tmpl;
316     OSSL_PARAM *params = NULL;
317     int ok = 1;
318
319     if (ec == NULL)
320         return 0;
321
322     /*
323      * In this implementation, we can export/import only keydata in the
324      * following combinations:
325      *   - domain parameters only
326      *   - public key with associated domain parameters (+optional other params)
327      *   - private key with associated public key and domain parameters
328      *         (+optional other params)
329      *
330      * This means:
331      *   - domain parameters must always be requested
332      *   - private key must be requested alongside public key
333      *   - other parameters must be requested only alongside a key
334      */
335     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) == 0)
336         return 0;
337     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0
338             && (selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) == 0)
339         return 0;
340     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0
341             && (selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == 0)
342         return 0;
343
344     ossl_param_bld_init(&tmpl);
345
346     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
347         ok = ok && domparams_to_params(ec, &tmpl);
348     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) != 0) {
349         int include_private =
350             selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY ? 1 : 0;
351
352         ok = ok && key_to_params(ec, &tmpl, include_private);
353     }
354     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0)
355         ok = ok && otherparams_to_params(ec, &tmpl);
356
357     if (!ok
358         || (params = ossl_param_bld_to_param(&tmpl)) == NULL)
359         return 0;
360
361     ok = param_cb(params, cbarg);
362     ossl_param_bld_free(params);
363     return ok;
364 }
365
366 /* IMEXPORT = IMPORT + EXPORT */
367
368 # define EC_IMEXPORTABLE_DOM_PARAMETERS                          \
369     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_NAME, NULL, 0)
370 # define EC_IMEXPORTABLE_PUBLIC_KEY                              \
371     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY, NULL, 0)
372 # define EC_IMEXPORTABLE_PRIVATE_KEY                             \
373     OSSL_PARAM_BN(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0)
374 # define EC_IMEXPORTABLE_OTHER_PARAMETERS                        \
375     OSSL_PARAM_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, NULL)
376
377 /*
378  * Include all the possible combinations of OSSL_PARAM arrays for
379  * ec_imexport_types().
380  *
381  * They are in a separate file as it is ~100 lines of unreadable and
382  * uninteresting machine generated stuff.
383  *
384  * TODO(3.0): the generated list looks quite ugly, as to cover all possible
385  * combinations of the bits in `selection`, it also includes combinations that
386  * are not really useful: we might want to consider alternatives to this
387  * solution.
388  */
389 #include "ec_kmgmt_imexport.inc"
390
391 static ossl_inline
392 const OSSL_PARAM *ec_imexport_types(int selection)
393 {
394     int type_select = 0;
395
396     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
397         type_select += 1;
398     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
399         type_select += 2;
400     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
401         type_select += 4;
402     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0)
403         type_select += 8;
404     return ec_types[type_select];
405 }
406
407 static
408 const OSSL_PARAM *ec_import_types(int selection)
409 {
410     return ec_imexport_types(selection);
411 }
412
413 static
414 const OSSL_PARAM *ec_export_types(int selection)
415 {
416     return ec_imexport_types(selection);
417 }
418
419 static
420 int ec_get_params(void *key, OSSL_PARAM params[])
421 {
422     EC_KEY *eck = key;
423     const EC_GROUP *ecg = NULL;
424     OSSL_PARAM *p;
425
426     ecg = EC_KEY_get0_group(eck);
427     if (ecg == NULL)
428         return 0;
429
430     if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_MAX_SIZE)) != NULL
431         && !OSSL_PARAM_set_int(p, ECDSA_size(eck)))
432         return 0;
433     if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_BITS)) != NULL
434         && !OSSL_PARAM_set_int(p, EC_GROUP_order_bits(ecg)))
435         return 0;
436     if ((p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_SECURITY_BITS)) != NULL) {
437         int ecbits, sec_bits;
438
439         ecbits = EC_GROUP_order_bits(ecg);
440
441         /*
442          * The following estimates are based on the values published
443          * in Table 2 of "NIST Special Publication 800-57 Part 1 Revision 4"
444          * at http://dx.doi.org/10.6028/NIST.SP.800-57pt1r4 .
445          *
446          * Note that the above reference explicitly categorizes algorithms in a
447          * discrete set of values {80, 112, 128, 192, 256}, and that it is
448          * relevant only for NIST approved Elliptic Curves, while OpenSSL
449          * applies the same logic also to other curves.
450          *
451          * Classifications produced by other standardazing bodies might differ,
452          * so the results provided for "bits of security" by this provider are
453          * to be considered merely indicative, and it is the users'
454          * responsibility to compare these values against the normative
455          * references that may be relevant for their intent and purposes.
456          */
457         if (ecbits >= 512)
458             sec_bits = 256;
459         else if (ecbits >= 384)
460             sec_bits = 192;
461         else if (ecbits >= 256)
462             sec_bits = 128;
463         else if (ecbits >= 224)
464             sec_bits = 112;
465         else if (ecbits >= 160)
466             sec_bits = 80;
467         else
468             sec_bits = ecbits / 2;
469
470         if (!OSSL_PARAM_set_int(p, sec_bits))
471             return 0;
472     }
473
474     p = OSSL_PARAM_locate(params, OSSL_PKEY_PARAM_USE_COFACTOR_ECDH);
475     if (p != NULL) {
476         int ecdh_cofactor_mode = 0;
477
478         ecdh_cofactor_mode =
479             (EC_KEY_get_flags(eck) & EC_FLAG_COFACTOR_ECDH) ? 1 : 0;
480
481         if (!OSSL_PARAM_set_int(p, ecdh_cofactor_mode))
482             return 0;
483     }
484
485     return 1;
486 }
487
488 static const OSSL_PARAM ec_known_gettable_params[] = {
489     OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL),
490     OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL),
491     OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL),
492     OSSL_PARAM_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, NULL),
493     OSSL_PARAM_END
494 };
495
496 static
497 const OSSL_PARAM *ec_gettable_params(void)
498 {
499     return ec_known_gettable_params;
500 }
501
502 static const OSSL_PARAM ec_known_settable_params[] = {
503     OSSL_PARAM_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, NULL),
504     OSSL_PARAM_END
505 };
506
507 static
508 const OSSL_PARAM *ec_settable_params(void)
509 {
510     return ec_known_settable_params;
511 }
512
513 static
514 int ec_set_params(void *key, const OSSL_PARAM params[])
515 {
516     EC_KEY *eck = key;
517     const OSSL_PARAM *p;
518
519     p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_USE_COFACTOR_ECDH);
520     if (p != NULL && !ec_set_param_ecdh_cofactor_mode(eck, p))
521         return 0;
522
523     return 1;
524 }
525
526 static
527 int ec_validate(void *keydata, int selection)
528 {
529     EC_KEY *eck = keydata;
530     int ok = 0;
531     BN_CTX *ctx = BN_CTX_new_ex(ec_key_get_libctx(eck));
532
533     if (ctx == NULL)
534         return 0;
535
536     if ((selection & EC_POSSIBLE_SELECTIONS) != 0)
537         ok = 1;
538
539     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
540         ok = ok && EC_GROUP_check(EC_KEY_get0_group(eck), ctx);
541
542     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
543         ok = ok && ec_key_public_check(eck, ctx);
544
545     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
546         ok = ok && ec_key_private_check(eck);
547
548     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == OSSL_KEYMGMT_SELECT_KEYPAIR)
549         ok = ok && ec_key_pairwise_check(eck, ctx);
550
551     BN_CTX_free(ctx);
552     return ok;
553 }
554
555 const OSSL_DISPATCH ec_keymgmt_functions[] = {
556     { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))ec_newdata },
557     { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))ec_freedata },
558     { OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*) (void))ec_get_params },
559     { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*) (void))ec_gettable_params },
560     { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*) (void))ec_set_params },
561     { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*) (void))ec_settable_params },
562     { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))ec_has },
563     { OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))ec_match },
564     { OSSL_FUNC_KEYMGMT_VALIDATE, (void (*)(void))ec_validate },
565     { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ec_import },
566     { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))ec_import_types },
567     { OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))ec_export },
568     { OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))ec_export_types },
569     { OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME,
570         (void (*)(void))ec_query_operation_name },
571     { 0, NULL }
572 };