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