84ce09569301d0f70f0913799e5a0b6a488b4051
[openssl.git] / crypto / ec / ec_key.c
1 /*
2  * Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 /*
12  * ECDSA low level APIs are deprecated for public use, but still ok for
13  * internal use.
14  */
15 #include "internal/deprecated.h"
16
17 #include "internal/cryptlib.h"
18 #include <string.h>
19 #include "ec_local.h"
20 #include "internal/refcount.h"
21 #include <openssl/err.h>
22 #include <openssl/engine.h>
23 #include <openssl/self_test.h>
24 #include "crypto/bn.h"
25
26 static int ecdsa_keygen_pairwise_test(EC_KEY *eckey, OSSL_CALLBACK *cb,
27                                       void *cbarg);
28
29 #ifndef FIPS_MODULE
30 EC_KEY *EC_KEY_new(void)
31 {
32     return ec_key_new_method_int(NULL, NULL, NULL);
33 }
34 #endif
35
36 EC_KEY *EC_KEY_new_with_libctx(OPENSSL_CTX *ctx, const char *propq)
37 {
38     return ec_key_new_method_int(ctx, propq, NULL);
39 }
40
41 EC_KEY *EC_KEY_new_by_curve_name_with_libctx(OPENSSL_CTX *ctx,
42                                              const char *propq, int nid)
43 {
44     EC_KEY *ret = EC_KEY_new_with_libctx(ctx, propq);
45     if (ret == NULL)
46         return NULL;
47     ret->group = EC_GROUP_new_by_curve_name_with_libctx(ctx, propq, nid);
48     if (ret->group == NULL) {
49         EC_KEY_free(ret);
50         return NULL;
51     }
52     if (ret->meth->set_group != NULL
53         && ret->meth->set_group(ret, ret->group) == 0) {
54         EC_KEY_free(ret);
55         return NULL;
56     }
57     return ret;
58 }
59
60 #ifndef FIPS_MODULE
61 EC_KEY *EC_KEY_new_by_curve_name(int nid)
62 {
63     return EC_KEY_new_by_curve_name_with_libctx(NULL, NULL, nid);
64 }
65 #endif
66
67 void EC_KEY_free(EC_KEY *r)
68 {
69     int i;
70
71     if (r == NULL)
72         return;
73
74     CRYPTO_DOWN_REF(&r->references, &i, r->lock);
75     REF_PRINT_COUNT("EC_KEY", r);
76     if (i > 0)
77         return;
78     REF_ASSERT_ISNT(i < 0);
79
80     if (r->meth != NULL && r->meth->finish != NULL)
81         r->meth->finish(r);
82
83 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
84     ENGINE_finish(r->engine);
85 #endif
86
87     if (r->group && r->group->meth->keyfinish)
88         r->group->meth->keyfinish(r);
89
90 #ifndef FIPS_MODULE
91     CRYPTO_free_ex_data(CRYPTO_EX_INDEX_EC_KEY, r, &r->ex_data);
92 #endif
93     CRYPTO_THREAD_lock_free(r->lock);
94     EC_GROUP_free(r->group);
95     EC_POINT_free(r->pub_key);
96     BN_clear_free(r->priv_key);
97     OPENSSL_free(r->propq);
98
99     OPENSSL_clear_free((void *)r, sizeof(EC_KEY));
100 }
101
102 EC_KEY *EC_KEY_copy(EC_KEY *dest, const EC_KEY *src)
103 {
104     if (dest == NULL || src == NULL) {
105         ECerr(EC_F_EC_KEY_COPY, ERR_R_PASSED_NULL_PARAMETER);
106         return NULL;
107     }
108     if (src->meth != dest->meth) {
109         if (dest->meth->finish != NULL)
110             dest->meth->finish(dest);
111         if (dest->group && dest->group->meth->keyfinish)
112             dest->group->meth->keyfinish(dest);
113 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
114         if (ENGINE_finish(dest->engine) == 0)
115             return 0;
116         dest->engine = NULL;
117 #endif
118     }
119     dest->libctx = src->libctx;
120     /* copy the parameters */
121     if (src->group != NULL) {
122         /* clear the old group */
123         EC_GROUP_free(dest->group);
124         dest->group = ec_group_new_with_libctx(src->libctx, src->propq,
125                                                src->group->meth);
126         if (dest->group == NULL)
127             return NULL;
128         if (!EC_GROUP_copy(dest->group, src->group))
129             return NULL;
130
131         /*  copy the public key */
132         if (src->pub_key != NULL) {
133             EC_POINT_free(dest->pub_key);
134             dest->pub_key = EC_POINT_new(src->group);
135             if (dest->pub_key == NULL)
136                 return NULL;
137             if (!EC_POINT_copy(dest->pub_key, src->pub_key))
138                 return NULL;
139         }
140         /* copy the private key */
141         if (src->priv_key != NULL) {
142             if (dest->priv_key == NULL) {
143                 dest->priv_key = BN_new();
144                 if (dest->priv_key == NULL)
145                     return NULL;
146             }
147             if (!BN_copy(dest->priv_key, src->priv_key))
148                 return NULL;
149             if (src->group->meth->keycopy
150                 && src->group->meth->keycopy(dest, src) == 0)
151                 return NULL;
152         }
153     }
154
155
156     /* copy the rest */
157     dest->enc_flag = src->enc_flag;
158     dest->conv_form = src->conv_form;
159     dest->version = src->version;
160     dest->flags = src->flags;
161 #ifndef FIPS_MODULE
162     if (!CRYPTO_dup_ex_data(CRYPTO_EX_INDEX_EC_KEY,
163                             &dest->ex_data, &src->ex_data))
164         return NULL;
165 #endif
166
167     if (src->meth != dest->meth) {
168 #if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
169         if (src->engine != NULL && ENGINE_init(src->engine) == 0)
170             return NULL;
171         dest->engine = src->engine;
172 #endif
173         dest->meth = src->meth;
174     }
175
176     if (src->meth->copy != NULL && src->meth->copy(dest, src) == 0)
177         return NULL;
178
179     dest->dirty_cnt++;
180
181     return dest;
182 }
183
184 EC_KEY *EC_KEY_dup(const EC_KEY *ec_key)
185 {
186     EC_KEY *ret = ec_key_new_method_int(ec_key->libctx, ec_key->propq,
187                                         ec_key->engine);
188
189     if (ret == NULL)
190         return NULL;
191
192     if (EC_KEY_copy(ret, ec_key) == NULL) {
193         EC_KEY_free(ret);
194         return NULL;
195     }
196     return ret;
197 }
198
199 int EC_KEY_up_ref(EC_KEY *r)
200 {
201     int i;
202
203     if (CRYPTO_UP_REF(&r->references, &i, r->lock) <= 0)
204         return 0;
205
206     REF_PRINT_COUNT("EC_KEY", r);
207     REF_ASSERT_ISNT(i < 2);
208     return ((i > 1) ? 1 : 0);
209 }
210
211 ENGINE *EC_KEY_get0_engine(const EC_KEY *eckey)
212 {
213     return eckey->engine;
214 }
215
216 int EC_KEY_generate_key(EC_KEY *eckey)
217 {
218     if (eckey == NULL || eckey->group == NULL) {
219         ECerr(EC_F_EC_KEY_GENERATE_KEY, ERR_R_PASSED_NULL_PARAMETER);
220         return 0;
221     }
222     if (eckey->meth->keygen != NULL) {
223         int ret;
224
225         ret = eckey->meth->keygen(eckey);
226         if (ret == 1)
227             eckey->dirty_cnt++;
228
229         return ret;
230     }
231     ECerr(EC_F_EC_KEY_GENERATE_KEY, EC_R_OPERATION_NOT_SUPPORTED);
232     return 0;
233 }
234
235 int ossl_ec_key_gen(EC_KEY *eckey)
236 {
237     int ret;
238
239     ret = eckey->group->meth->keygen(eckey);
240
241     if (ret == 1)
242         eckey->dirty_cnt++;
243     return ret;
244 }
245
246 /*
247  * ECC Key generation.
248  * See SP800-56AR3 5.6.1.2.2 "Key Pair Generation by Testing Candidates"
249  *
250  * Params:
251  *     libctx A context containing an optional self test callback.
252  *     eckey An EC key object that contains domain params. The generated keypair
253  *           is stored in this object.
254  *     pairwise_test Set to non zero to perform a pairwise test. If the test
255  *                   fails then the keypair is not generated,
256  * Returns 1 if the keypair was generated or 0 otherwise.
257  */
258 int ec_generate_key(OPENSSL_CTX *libctx, EC_KEY *eckey, int pairwise_test)
259 {
260     int ok = 0;
261     BIGNUM *priv_key = NULL;
262     const BIGNUM *order = NULL;
263     EC_POINT *pub_key = NULL;
264     const EC_GROUP *group = eckey->group;
265     BN_CTX *ctx = BN_CTX_secure_new_ex(eckey->libctx);
266
267     if (ctx == NULL)
268         goto err;
269
270     if (eckey->priv_key == NULL) {
271         priv_key = BN_secure_new();
272         if (priv_key == NULL)
273             goto err;
274     } else
275         priv_key = eckey->priv_key;
276
277     /*
278      * Steps (1-2): Check domain parameters and security strength.
279      * These steps must be done by the user. This would need to be
280      * stated in the security policy.
281      */
282
283     order = EC_GROUP_get0_order(group);
284     if (order == NULL)
285         goto err;
286
287     /*
288      * Steps (3-7): priv_key = DRBG_RAND(order_n_bits) (range [1, n-1]).
289      * Although this is slightly different from the standard, it is effectively
290      * equivalent as it gives an unbiased result ranging from 1..n-1. It is also
291      * faster as the standard needs to retry more often. Also doing
292      * 1 + rand[0..n-2] would effect the way that tests feed dummy entropy into
293      * rand so the simpler backward compatible method has been used here.
294      */
295     do
296         if (!BN_priv_rand_range_ex(priv_key, order, ctx))
297             goto err;
298     while (BN_is_zero(priv_key)) ;
299
300     if (eckey->pub_key == NULL) {
301         pub_key = EC_POINT_new(group);
302         if (pub_key == NULL)
303             goto err;
304     } else
305         pub_key = eckey->pub_key;
306
307     /* Step (8) : pub_key = priv_key * G (where G is a point on the curve) */
308     if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
309         goto err;
310
311     eckey->priv_key = priv_key;
312     eckey->pub_key = pub_key;
313     priv_key = NULL;
314     pub_key = NULL;
315
316     eckey->dirty_cnt++;
317
318 #ifdef FIPS_MODULE
319     pairwise_test = 1;
320 #endif /* FIPS_MODULE */
321
322     ok = 1;
323     if (pairwise_test) {
324         OSSL_CALLBACK *cb = NULL;
325         void *cbarg = NULL;
326
327         OSSL_SELF_TEST_get_callback(libctx, &cb, &cbarg);
328         ok = ecdsa_keygen_pairwise_test(eckey, cb, cbarg);
329     }
330 err:
331     /* Step (9): If there is an error return an invalid keypair. */
332     if (!ok) {
333         BN_clear(eckey->priv_key);
334         if (eckey->pub_key != NULL)
335             EC_POINT_set_to_infinity(group, eckey->pub_key);
336     }
337
338     EC_POINT_free(pub_key);
339     BN_clear_free(priv_key);
340     BN_CTX_free(ctx);
341     return ok;
342 }
343
344 int ec_key_simple_generate_key(EC_KEY *eckey)
345 {
346     return ec_generate_key(NULL, eckey, 0);
347 }
348
349 int ec_key_simple_generate_public_key(EC_KEY *eckey)
350 {
351     int ret;
352     BN_CTX *ctx = BN_CTX_new_ex(eckey->libctx);
353
354     if (ctx == NULL)
355         return 0;
356
357     /*
358      * See SP800-56AR3 5.6.1.2.2: Step (8)
359      * pub_key = priv_key * G (where G is a point on the curve)
360      */
361     ret = EC_POINT_mul(eckey->group, eckey->pub_key, eckey->priv_key, NULL,
362                        NULL, ctx);
363
364     BN_CTX_free(ctx);
365     if (ret == 1)
366         eckey->dirty_cnt++;
367
368     return ret;
369 }
370
371 int EC_KEY_check_key(const EC_KEY *eckey)
372 {
373     if (eckey == NULL || eckey->group == NULL || eckey->pub_key == NULL) {
374         ECerr(EC_F_EC_KEY_CHECK_KEY, ERR_R_PASSED_NULL_PARAMETER);
375         return 0;
376     }
377
378     if (eckey->group->meth->keycheck == NULL) {
379         ECerr(EC_F_EC_KEY_CHECK_KEY, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
380         return 0;
381     }
382
383     return eckey->group->meth->keycheck(eckey);
384 }
385
386 /*
387  * Check the range of the EC public key.
388  * See SP800-56A R3 Section 5.6.2.3.3 (Part 2)
389  * i.e.
390  *  - If q = odd prime p: Verify that xQ and yQ are integers in the
391  *    interval[0, p - 1], OR
392  *  - If q = 2m: Verify that xQ and yQ are bit strings of length m bits.
393  * Returns 1 if the public key has a valid range, otherwise it returns 0.
394  */
395 static int ec_key_public_range_check(BN_CTX *ctx, const EC_KEY *key)
396 {
397     int ret = 0;
398     BIGNUM *x, *y;
399
400     BN_CTX_start(ctx);
401     x = BN_CTX_get(ctx);
402     y = BN_CTX_get(ctx);
403     if (y == NULL)
404         goto err;
405
406     if (!EC_POINT_get_affine_coordinates(key->group, key->pub_key, x, y, ctx))
407         goto err;
408
409     if (EC_GROUP_get_field_type(key->group) == NID_X9_62_prime_field) {
410         if (BN_is_negative(x)
411             || BN_cmp(x, key->group->field) >= 0
412             || BN_is_negative(y)
413             || BN_cmp(y, key->group->field) >= 0) {
414             goto err;
415         }
416     } else {
417         int m = EC_GROUP_get_degree(key->group);
418         if (BN_num_bits(x) > m || BN_num_bits(y) > m) {
419             goto err;
420         }
421     }
422     ret = 1;
423 err:
424     BN_CTX_end(ctx);
425     return ret;
426 }
427
428 /*
429  * ECC Key validation as specified in SP800-56A R3.
430  * Section 5.6.2.3.3 ECC Full Public-Key Validation.
431  */
432 int ec_key_public_check(const EC_KEY *eckey, BN_CTX *ctx)
433 {
434     int ret = 0;
435     EC_POINT *point = NULL;
436     const BIGNUM *order = NULL;
437
438     if (eckey == NULL || eckey->group == NULL || eckey->pub_key == NULL) {
439         ECerr(0, ERR_R_PASSED_NULL_PARAMETER);
440         return 0;
441     }
442
443     /* 5.6.2.3.3 (Step 1): Q != infinity */
444     if (EC_POINT_is_at_infinity(eckey->group, eckey->pub_key)) {
445         ECerr(0, EC_R_POINT_AT_INFINITY);
446         return 0;
447     }
448
449     point = EC_POINT_new(eckey->group);
450     if (point == NULL)
451         return 0;
452
453     /* 5.6.2.3.3 (Step 2) Test if the public key is in range */
454     if (!ec_key_public_range_check(ctx, eckey)) {
455         ECerr(0, EC_R_COORDINATES_OUT_OF_RANGE);
456         goto err;
457     }
458
459     /* 5.6.2.3.3 (Step 3) is the pub_key on the elliptic curve */
460     if (EC_POINT_is_on_curve(eckey->group, eckey->pub_key, ctx) <= 0) {
461         ECerr(0, EC_R_POINT_IS_NOT_ON_CURVE);
462         goto err;
463     }
464
465     order = eckey->group->order;
466     if (BN_is_zero(order)) {
467         ECerr(0, EC_R_INVALID_GROUP_ORDER);
468         goto err;
469     }
470     /* 5.6.2.3.3 (Step 4) : pub_key * order is the point at infinity. */
471     if (!EC_POINT_mul(eckey->group, point, NULL, eckey->pub_key, order, ctx)) {
472         ECerr(0, ERR_R_EC_LIB);
473         goto err;
474     }
475     if (!EC_POINT_is_at_infinity(eckey->group, point)) {
476         ECerr(0, EC_R_WRONG_ORDER);
477         goto err;
478     }
479     ret = 1;
480 err:
481     EC_POINT_free(point);
482     return ret;
483 }
484
485 /*
486  * ECC Key validation as specified in SP800-56A R3.
487  * Section 5.6.2.1.2 Owner Assurance of Private-Key Validity
488  * The private key is in the range [1, order-1]
489  */
490 int ec_key_private_check(const EC_KEY *eckey)
491 {
492     if (eckey == NULL || eckey->group == NULL || eckey->priv_key == NULL) {
493         ECerr(0, ERR_R_PASSED_NULL_PARAMETER);
494         return 0;
495     }
496     if (BN_cmp(eckey->priv_key, BN_value_one()) < 0
497         || BN_cmp(eckey->priv_key, eckey->group->order) >= 0) {
498         ECerr(0, EC_R_INVALID_PRIVATE_KEY);
499         return 0;
500     }
501     return 1;
502 }
503
504 /*
505  * ECC Key validation as specified in SP800-56A R3.
506  * Section 5.6.2.1.4 Owner Assurance of Pair-wise Consistency (b)
507  * Check if generator * priv_key = pub_key
508  */
509 int ec_key_pairwise_check(const EC_KEY *eckey, BN_CTX *ctx)
510 {
511     int ret = 0;
512     EC_POINT *point = NULL;
513
514     if (eckey == NULL
515        || eckey->group == NULL
516        || eckey->pub_key == NULL
517        || eckey->priv_key == NULL) {
518         ECerr(0, ERR_R_PASSED_NULL_PARAMETER);
519         return 0;
520     }
521
522     point = EC_POINT_new(eckey->group);
523     if (point == NULL)
524         goto err;
525
526
527     if (!EC_POINT_mul(eckey->group, point, eckey->priv_key, NULL, NULL, ctx)) {
528         ECerr(0, ERR_R_EC_LIB);
529         goto err;
530     }
531     if (EC_POINT_cmp(eckey->group, point, eckey->pub_key, ctx) != 0) {
532         ECerr(0, EC_R_INVALID_PRIVATE_KEY);
533         goto err;
534     }
535     ret = 1;
536 err:
537     EC_POINT_free(point);
538     return ret;
539 }
540
541
542 /*
543  * ECC Key validation as specified in SP800-56A R3.
544  *    Section 5.6.2.3.3 ECC Full Public-Key Validation
545  *    Section 5.6.2.1.2 Owner Assurance of Private-Key Validity
546  *    Section 5.6.2.1.4 Owner Assurance of Pair-wise Consistency
547  * NOTES:
548  *    Before calling this method in fips mode, there should be an assurance that
549  *    an approved elliptic-curve group is used.
550  * Returns 1 if the key is valid, otherwise it returns 0.
551  */
552 int ec_key_simple_check_key(const EC_KEY *eckey)
553 {
554     int ok = 0;
555     BN_CTX *ctx = NULL;
556
557     if (eckey == NULL) {
558         ECerr(0, ERR_R_PASSED_NULL_PARAMETER);
559         return 0;
560     }
561     if ((ctx = BN_CTX_new_ex(eckey->libctx)) == NULL)
562         return 0;
563
564     if (!ec_key_public_check(eckey, ctx))
565         goto err;
566
567     if (eckey->priv_key != NULL) {
568         if (!ec_key_private_check(eckey)
569             || !ec_key_pairwise_check(eckey, ctx))
570             goto err;
571     }
572     ok = 1;
573 err:
574     BN_CTX_free(ctx);
575     return ok;
576 }
577
578 int EC_KEY_set_public_key_affine_coordinates(EC_KEY *key, BIGNUM *x,
579                                              BIGNUM *y)
580 {
581     BN_CTX *ctx = NULL;
582     BIGNUM *tx, *ty;
583     EC_POINT *point = NULL;
584     int ok = 0;
585
586     if (key == NULL || key->group == NULL || x == NULL || y == NULL) {
587         ECerr(EC_F_EC_KEY_SET_PUBLIC_KEY_AFFINE_COORDINATES,
588               ERR_R_PASSED_NULL_PARAMETER);
589         return 0;
590     }
591     ctx = BN_CTX_new_ex(key->libctx);
592     if (ctx == NULL)
593         return 0;
594
595     BN_CTX_start(ctx);
596     point = EC_POINT_new(key->group);
597
598     if (point == NULL)
599         goto err;
600
601     tx = BN_CTX_get(ctx);
602     ty = BN_CTX_get(ctx);
603     if (ty == NULL)
604         goto err;
605
606     if (!EC_POINT_set_affine_coordinates(key->group, point, x, y, ctx))
607         goto err;
608     if (!EC_POINT_get_affine_coordinates(key->group, point, tx, ty, ctx))
609         goto err;
610
611     /*
612      * Check if retrieved coordinates match originals. The range check is done
613      * inside EC_KEY_check_key().
614      */
615     if (BN_cmp(x, tx) || BN_cmp(y, ty)) {
616         ECerr(EC_F_EC_KEY_SET_PUBLIC_KEY_AFFINE_COORDINATES,
617               EC_R_COORDINATES_OUT_OF_RANGE);
618         goto err;
619     }
620
621     /* EC_KEY_set_public_key updates dirty_cnt */
622     if (!EC_KEY_set_public_key(key, point))
623         goto err;
624
625     if (EC_KEY_check_key(key) == 0)
626         goto err;
627
628     ok = 1;
629
630  err:
631     BN_CTX_end(ctx);
632     BN_CTX_free(ctx);
633     EC_POINT_free(point);
634     return ok;
635
636 }
637
638 OPENSSL_CTX *ec_key_get_libctx(const EC_KEY *key)
639 {
640     return key->libctx;
641 }
642
643 const char *ec_key_get0_propq(const EC_KEY *key)
644 {
645     return key->propq;
646 }
647
648 const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key)
649 {
650     return key->group;
651 }
652
653 int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group)
654 {
655     if (key->meth->set_group != NULL && key->meth->set_group(key, group) == 0)
656         return 0;
657     EC_GROUP_free(key->group);
658     key->group = EC_GROUP_dup(group);
659     key->dirty_cnt++;
660     return (key->group == NULL) ? 0 : 1;
661 }
662
663 const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key)
664 {
665     return key->priv_key;
666 }
667
668 int EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *priv_key)
669 {
670     int fixed_top;
671     const BIGNUM *order = NULL;
672     BIGNUM *tmp_key = NULL;
673
674     if (key->group == NULL || key->group->meth == NULL)
675         return 0;
676
677     /*
678      * Not only should key->group be set, but it should also be in a valid
679      * fully initialized state.
680      *
681      * Specifically, to operate in constant time, we need that the group order
682      * is set, as we use its length as the fixed public size of any scalar used
683      * as an EC private key.
684      */
685     order = EC_GROUP_get0_order(key->group);
686     if (order == NULL || BN_is_zero(order))
687         return 0; /* This should never happen */
688
689     if (key->group->meth->set_private != NULL
690         && key->group->meth->set_private(key, priv_key) == 0)
691         return 0;
692     if (key->meth->set_private != NULL
693         && key->meth->set_private(key, priv_key) == 0)
694         return 0;
695
696     /*
697      * We should never leak the bit length of the secret scalar in the key,
698      * so we always set the `BN_FLG_CONSTTIME` flag on the internal `BIGNUM`
699      * holding the secret scalar.
700      *
701      * This is important also because `BN_dup()` (and `BN_copy()`) do not
702      * propagate the `BN_FLG_CONSTTIME` flag from the source `BIGNUM`, and
703      * this brings an extra risk of inadvertently losing the flag, even when
704      * the caller specifically set it.
705      *
706      * The propagation has been turned on and off a few times in the past
707      * years because in some conditions has shown unintended consequences in
708      * some code paths, so at the moment we can't fix this in the BN layer.
709      *
710      * In `EC_KEY_set_private_key()` we can work around the propagation by
711      * manually setting the flag after `BN_dup()` as we know for sure that
712      * inside the EC module the `BN_FLG_CONSTTIME` is always treated
713      * correctly and should not generate unintended consequences.
714      *
715      * Setting the BN_FLG_CONSTTIME flag alone is never enough, we also have
716      * to preallocate the BIGNUM internal buffer to a fixed public size big
717      * enough that operations performed during the processing never trigger
718      * a realloc which would leak the size of the scalar through memory
719      * accesses.
720      *
721      * Fixed Length
722      * ------------
723      *
724      * The order of the large prime subgroup of the curve is our choice for
725      * a fixed public size, as that is generally the upper bound for
726      * generating a private key in EC cryptosystems and should fit all valid
727      * secret scalars.
728      *
729      * For preallocating the BIGNUM storage we look at the number of "words"
730      * required for the internal representation of the order, and we
731      * preallocate 2 extra "words" in case any of the subsequent processing
732      * might temporarily overflow the order length.
733      */
734     tmp_key = BN_dup(priv_key);
735     if (tmp_key == NULL)
736         return 0;
737
738     BN_set_flags(tmp_key, BN_FLG_CONSTTIME);
739
740     fixed_top = bn_get_top(order) + 2;
741     if (bn_wexpand(tmp_key, fixed_top) == NULL) {
742         BN_clear_free(tmp_key);
743         return 0;
744     }
745
746     BN_clear_free(key->priv_key);
747     key->priv_key = tmp_key;
748     key->dirty_cnt++;
749
750     return 1;
751 }
752
753 const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key)
754 {
755     return key->pub_key;
756 }
757
758 int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub_key)
759 {
760     if (key->meth->set_public != NULL
761         && key->meth->set_public(key, pub_key) == 0)
762         return 0;
763     EC_POINT_free(key->pub_key);
764     key->pub_key = EC_POINT_dup(pub_key, key->group);
765     key->dirty_cnt++;
766     return (key->pub_key == NULL) ? 0 : 1;
767 }
768
769 unsigned int EC_KEY_get_enc_flags(const EC_KEY *key)
770 {
771     return key->enc_flag;
772 }
773
774 void EC_KEY_set_enc_flags(EC_KEY *key, unsigned int flags)
775 {
776     key->enc_flag = flags;
777 }
778
779 point_conversion_form_t EC_KEY_get_conv_form(const EC_KEY *key)
780 {
781     return key->conv_form;
782 }
783
784 void EC_KEY_set_conv_form(EC_KEY *key, point_conversion_form_t cform)
785 {
786     key->conv_form = cform;
787     if (key->group != NULL)
788         EC_GROUP_set_point_conversion_form(key->group, cform);
789 }
790
791 void EC_KEY_set_asn1_flag(EC_KEY *key, int flag)
792 {
793     if (key->group != NULL)
794         EC_GROUP_set_asn1_flag(key->group, flag);
795 }
796
797 #ifndef OPENSSL_NO_DEPRECATED_3_0
798 int EC_KEY_precompute_mult(EC_KEY *key, BN_CTX *ctx)
799 {
800     if (key->group == NULL)
801         return 0;
802     return EC_GROUP_precompute_mult(key->group, ctx);
803 }
804 #endif
805
806 int EC_KEY_get_flags(const EC_KEY *key)
807 {
808     return key->flags;
809 }
810
811 void EC_KEY_set_flags(EC_KEY *key, int flags)
812 {
813     key->flags |= flags;
814     key->dirty_cnt++;
815 }
816
817 void EC_KEY_clear_flags(EC_KEY *key, int flags)
818 {
819     key->flags &= ~flags;
820     key->dirty_cnt++;
821 }
822
823 size_t EC_KEY_key2buf(const EC_KEY *key, point_conversion_form_t form,
824                         unsigned char **pbuf, BN_CTX *ctx)
825 {
826     if (key == NULL || key->pub_key == NULL || key->group == NULL)
827         return 0;
828     return EC_POINT_point2buf(key->group, key->pub_key, form, pbuf, ctx);
829 }
830
831 int EC_KEY_oct2key(EC_KEY *key, const unsigned char *buf, size_t len,
832                    BN_CTX *ctx)
833 {
834     if (key == NULL || key->group == NULL)
835         return 0;
836     if (key->pub_key == NULL)
837         key->pub_key = EC_POINT_new(key->group);
838     if (key->pub_key == NULL)
839         return 0;
840     if (EC_POINT_oct2point(key->group, key->pub_key, buf, len, ctx) == 0)
841         return 0;
842     key->dirty_cnt++;
843     /*
844      * Save the point conversion form.
845      * For non-custom curves the first octet of the buffer (excluding
846      * the last significant bit) contains the point conversion form.
847      * EC_POINT_oct2point() has already performed sanity checking of
848      * the buffer so we know it is valid.
849      */
850     if ((key->group->meth->flags & EC_FLAGS_CUSTOM_CURVE) == 0)
851         key->conv_form = (point_conversion_form_t)(buf[0] & ~0x01);
852     return 1;
853 }
854
855 size_t EC_KEY_priv2oct(const EC_KEY *eckey,
856                        unsigned char *buf, size_t len)
857 {
858     if (eckey->group == NULL || eckey->group->meth == NULL)
859         return 0;
860     if (eckey->group->meth->priv2oct == NULL) {
861         ECerr(EC_F_EC_KEY_PRIV2OCT, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
862         return 0;
863     }
864
865     return eckey->group->meth->priv2oct(eckey, buf, len);
866 }
867
868 size_t ec_key_simple_priv2oct(const EC_KEY *eckey,
869                               unsigned char *buf, size_t len)
870 {
871     size_t buf_len;
872
873     buf_len = (EC_GROUP_order_bits(eckey->group) + 7) / 8;
874     if (eckey->priv_key == NULL)
875         return 0;
876     if (buf == NULL)
877         return buf_len;
878     else if (len < buf_len)
879         return 0;
880
881     /* Octetstring may need leading zeros if BN is to short */
882
883     if (BN_bn2binpad(eckey->priv_key, buf, buf_len) == -1) {
884         ECerr(EC_F_EC_KEY_SIMPLE_PRIV2OCT, EC_R_BUFFER_TOO_SMALL);
885         return 0;
886     }
887
888     return buf_len;
889 }
890
891 int EC_KEY_oct2priv(EC_KEY *eckey, const unsigned char *buf, size_t len)
892 {
893     int ret;
894
895     if (eckey->group == NULL || eckey->group->meth == NULL)
896         return 0;
897     if (eckey->group->meth->oct2priv == NULL) {
898         ECerr(EC_F_EC_KEY_OCT2PRIV, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
899         return 0;
900     }
901     ret = eckey->group->meth->oct2priv(eckey, buf, len);
902     if (ret == 1)
903         eckey->dirty_cnt++;
904     return ret;
905 }
906
907 int ec_key_simple_oct2priv(EC_KEY *eckey, const unsigned char *buf, size_t len)
908 {
909     if (eckey->priv_key == NULL)
910         eckey->priv_key = BN_secure_new();
911     if (eckey->priv_key == NULL) {
912         ECerr(EC_F_EC_KEY_SIMPLE_OCT2PRIV, ERR_R_MALLOC_FAILURE);
913         return 0;
914     }
915     eckey->priv_key = BN_bin2bn(buf, len, eckey->priv_key);
916     if (eckey->priv_key == NULL) {
917         ECerr(EC_F_EC_KEY_SIMPLE_OCT2PRIV, ERR_R_BN_LIB);
918         return 0;
919     }
920     eckey->dirty_cnt++;
921     return 1;
922 }
923
924 size_t EC_KEY_priv2buf(const EC_KEY *eckey, unsigned char **pbuf)
925 {
926     size_t len;
927     unsigned char *buf;
928
929     len = EC_KEY_priv2oct(eckey, NULL, 0);
930     if (len == 0)
931         return 0;
932     if ((buf = OPENSSL_malloc(len)) == NULL) {
933         ECerr(EC_F_EC_KEY_PRIV2BUF, ERR_R_MALLOC_FAILURE);
934         return 0;
935     }
936     len = EC_KEY_priv2oct(eckey, buf, len);
937     if (len == 0) {
938         OPENSSL_free(buf);
939         return 0;
940     }
941     *pbuf = buf;
942     return len;
943 }
944
945 int EC_KEY_can_sign(const EC_KEY *eckey)
946 {
947     if (eckey->group == NULL || eckey->group->meth == NULL
948         || (eckey->group->meth->flags & EC_FLAGS_NO_SIGN))
949         return 0;
950     return 1;
951 }
952
953 /*
954  * FIPS 140-2 IG 9.9 AS09.33
955  * Perform a sign/verify operation.
956  *
957  * NOTE: When generating keys for key-agreement schemes - FIPS 140-2 IG 9.9
958  * states that no additional pairwise tests are required (apart from the tests
959  * specified in SP800-56A) when generating keys. Hence pairwise ECDH tests are
960  * omitted here.
961  */
962 static int ecdsa_keygen_pairwise_test(EC_KEY *eckey, OSSL_CALLBACK *cb,
963                                       void *cbarg)
964 {
965     int ret = 0;
966     unsigned char dgst[16] = {0};
967     int dgst_len = (int)sizeof(dgst);
968     ECDSA_SIG *sig = NULL;
969     OSSL_SELF_TEST *st = NULL;
970
971     st = OSSL_SELF_TEST_new(cb, cbarg);
972     if (st == NULL)
973         return 0;
974
975     OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
976                            OSSL_SELF_TEST_DESC_PCT_ECDSA);
977
978     sig = ECDSA_do_sign(dgst, dgst_len, eckey);
979     if (sig == NULL)
980         goto err;
981
982     OSSL_SELF_TEST_oncorrupt_byte(st, dgst);
983
984     if (ECDSA_do_verify(dgst, dgst_len, sig, eckey) != 1)
985         goto err;
986
987     ret = 1;
988 err:
989     OSSL_SELF_TEST_onend(st, ret);
990     OSSL_SELF_TEST_free(st);
991     ECDSA_SIG_free(sig);
992     return ret;
993 }