Fix export of provided EC keys
[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 && (params = OSSL_PARAM_BLD_to_param(tmpl)) != NULL)
356         ok = param_cb(params, cbarg);
357
358     OSSL_PARAM_BLD_free_params(params);
359     OSSL_PARAM_BLD_free(tmpl);
360     OPENSSL_free(pub_key);
361     return ok;
362 }
363
364 /* IMEXPORT = IMPORT + EXPORT */
365
366 # define EC_IMEXPORTABLE_DOM_PARAMETERS                          \
367     OSSL_PARAM_utf8_string(OSSL_PKEY_PARAM_EC_NAME, NULL, 0)
368 # define EC_IMEXPORTABLE_PUBLIC_KEY                              \
369     OSSL_PARAM_octet_string(OSSL_PKEY_PARAM_PUB_KEY, NULL, 0)
370 # define EC_IMEXPORTABLE_PRIVATE_KEY                             \
371     OSSL_PARAM_BN(OSSL_PKEY_PARAM_PRIV_KEY, NULL, 0)
372 # define EC_IMEXPORTABLE_OTHER_PARAMETERS                        \
373     OSSL_PARAM_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, NULL)
374
375 /*
376  * Include all the possible combinations of OSSL_PARAM arrays for
377  * ec_imexport_types().
378  *
379  * They are in a separate file as it is ~100 lines of unreadable and
380  * uninteresting machine generated stuff.
381  *
382  * TODO(3.0): the generated list looks quite ugly, as to cover all possible
383  * combinations of the bits in `selection`, it also includes combinations that
384  * are not really useful: we might want to consider alternatives to this
385  * solution.
386  */
387 #include "ec_kmgmt_imexport.inc"
388
389 static ossl_inline
390 const OSSL_PARAM *ec_imexport_types(int selection)
391 {
392     int type_select = 0;
393
394     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
395         type_select += 1;
396     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
397         type_select += 2;
398     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
399         type_select += 4;
400     if ((selection & OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS) != 0)
401         type_select += 8;
402     return ec_types[type_select];
403 }
404
405 static
406 const OSSL_PARAM *ec_import_types(int selection)
407 {
408     return ec_imexport_types(selection);
409 }
410
411 static
412 const OSSL_PARAM *ec_export_types(int selection)
413 {
414     return ec_imexport_types(selection);
415 }
416
417 static
418 int ec_get_params(void *key, OSSL_PARAM params[])
419 {
420     int ret;
421     EC_KEY *eck = key;
422     const EC_GROUP *ecg = NULL;
423     OSSL_PARAM *p;
424     unsigned char *pub_key = NULL;
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     ret = domparams_to_params(eck, NULL, params)
485           && key_to_params(eck, NULL, params, 1, &pub_key)
486           && otherparams_to_params(eck, NULL, params);
487     OPENSSL_free(pub_key);
488     return ret;
489 }
490
491 static const OSSL_PARAM ec_known_gettable_params[] = {
492     OSSL_PARAM_int(OSSL_PKEY_PARAM_BITS, NULL),
493     OSSL_PARAM_int(OSSL_PKEY_PARAM_SECURITY_BITS, NULL),
494     OSSL_PARAM_int(OSSL_PKEY_PARAM_MAX_SIZE, NULL),
495     EC_IMEXPORTABLE_DOM_PARAMETERS,
496     EC_IMEXPORTABLE_PUBLIC_KEY,
497     EC_IMEXPORTABLE_PRIVATE_KEY,
498     EC_IMEXPORTABLE_OTHER_PARAMETERS,
499     OSSL_PARAM_END
500 };
501
502 static
503 const OSSL_PARAM *ec_gettable_params(void)
504 {
505     return ec_known_gettable_params;
506 }
507
508 static const OSSL_PARAM ec_known_settable_params[] = {
509     OSSL_PARAM_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, NULL),
510     OSSL_PARAM_END
511 };
512
513 static
514 const OSSL_PARAM *ec_settable_params(void)
515 {
516     return ec_known_settable_params;
517 }
518
519 static
520 int ec_set_params(void *key, const OSSL_PARAM params[])
521 {
522     EC_KEY *eck = key;
523     const OSSL_PARAM *p;
524
525     p = OSSL_PARAM_locate_const(params, OSSL_PKEY_PARAM_USE_COFACTOR_ECDH);
526     if (p != NULL && !ec_set_param_ecdh_cofactor_mode(eck, p))
527         return 0;
528
529     return 1;
530 }
531
532 static
533 int ec_validate(void *keydata, int selection)
534 {
535     EC_KEY *eck = keydata;
536     int ok = 0;
537     BN_CTX *ctx = BN_CTX_new_ex(ec_key_get_libctx(eck));
538
539     if (ctx == NULL)
540         return 0;
541
542     if ((selection & EC_POSSIBLE_SELECTIONS) != 0)
543         ok = 1;
544
545     if ((selection & OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS) != 0)
546         ok = ok && EC_GROUP_check(EC_KEY_get0_group(eck), ctx);
547
548     if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)
549         ok = ok && ec_key_public_check(eck, ctx);
550
551     if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)
552         ok = ok && ec_key_private_check(eck);
553
554     if ((selection & OSSL_KEYMGMT_SELECT_KEYPAIR) == OSSL_KEYMGMT_SELECT_KEYPAIR)
555         ok = ok && ec_key_pairwise_check(eck, ctx);
556
557     BN_CTX_free(ctx);
558     return ok;
559 }
560
561 const OSSL_DISPATCH ec_keymgmt_functions[] = {
562     { OSSL_FUNC_KEYMGMT_NEW, (void (*)(void))ec_newdata },
563     { OSSL_FUNC_KEYMGMT_FREE, (void (*)(void))ec_freedata },
564     { OSSL_FUNC_KEYMGMT_GET_PARAMS, (void (*) (void))ec_get_params },
565     { OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS, (void (*) (void))ec_gettable_params },
566     { OSSL_FUNC_KEYMGMT_SET_PARAMS, (void (*) (void))ec_set_params },
567     { OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS, (void (*) (void))ec_settable_params },
568     { OSSL_FUNC_KEYMGMT_HAS, (void (*)(void))ec_has },
569     { OSSL_FUNC_KEYMGMT_MATCH, (void (*)(void))ec_match },
570     { OSSL_FUNC_KEYMGMT_VALIDATE, (void (*)(void))ec_validate },
571     { OSSL_FUNC_KEYMGMT_IMPORT, (void (*)(void))ec_import },
572     { OSSL_FUNC_KEYMGMT_IMPORT_TYPES, (void (*)(void))ec_import_types },
573     { OSSL_FUNC_KEYMGMT_EXPORT, (void (*)(void))ec_export },
574     { OSSL_FUNC_KEYMGMT_EXPORT_TYPES, (void (*)(void))ec_export_types },
575     { OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME,
576         (void (*)(void))ec_query_operation_name },
577     { 0, NULL }
578 };