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