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