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