1/*
2 * Copyright 2002-2022 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
29static int ecdsa_keygen_pairwise_test(EC_KEY *eckey, OSSL_CALLBACK *cb,
30                                      void *cbarg);
31
32#ifndef FIPS_MODULE
33EC_KEY *EC_KEY_new(void)
34{
35    return ossl_ec_key_new_method_int(NULL, NULL, NULL);
36}
37#endif
38
39EC_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
44EC_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
64EC_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
70void 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
105EC_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
187EC_KEY *EC_KEY_dup(const EC_KEY *ec_key)
188{
189    return ossl_ec_key_dup(ec_key, OSSL_KEYMGMT_SELECT_ALL);
190}
191
192int 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
204ENGINE *EC_KEY_get0_engine(const EC_KEY *eckey)
205{
206    return eckey->engine;
207}
208
209int 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
228int 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 */
251static 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    }
337err:
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
353int ossl_ec_key_simple_generate_key(EC_KEY *eckey)
354{
355    return ec_generate_key(eckey, 0);
356}
357
358int 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
380int 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 */
404static 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;
432err:
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 */
441int 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 */
472int 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;
500err:
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 */
510int 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 */
529int 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;
556err:
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 */
572int 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;
593err:
594    BN_CTX_free(ctx);
595    return ok;
596}
597
598int 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
656OSSL_LIB_CTX *ossl_ec_key_get_libctx(const EC_KEY *key)
657{
658    return key->libctx;
659}
660
661const char *ossl_ec_key_get0_propq(const EC_KEY *key)
662{
663    return key->propq;
664}
665
666void 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
672const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key)
673{
674    return key->group;
675}
676
677int 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
690const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key)
691{
692    return key->priv_key;
693}
694
695int 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     * Return `0` to comply with legacy behavior for this function, see
725     * https://github.com/openssl/openssl/issues/18744#issuecomment-1195175696
726     */
727    if (priv_key == NULL) {
728        BN_clear_free(key->priv_key);
729        key->priv_key = NULL;
730        return 0; /* intentional for legacy compatibility */
731    }
732
733    /*
734     * We should never leak the bit length of the secret scalar in the key,
735     * so we always set the `BN_FLG_CONSTTIME` flag on the internal `BIGNUM`
736     * holding the secret scalar.
737     *
738     * This is important also because `BN_dup()` (and `BN_copy()`) do not
739     * propagate the `BN_FLG_CONSTTIME` flag from the source `BIGNUM`, and
740     * this brings an extra risk of inadvertently losing the flag, even when
741     * the caller specifically set it.
742     *
743     * The propagation has been turned on and off a few times in the past
744     * years because in some conditions has shown unintended consequences in
745     * some code paths, so at the moment we can't fix this in the BN layer.
746     *
747     * In `EC_KEY_set_private_key()` we can work around the propagation by
748     * manually setting the flag after `BN_dup()` as we know for sure that
749     * inside the EC module the `BN_FLG_CONSTTIME` is always treated
750     * correctly and should not generate unintended consequences.
751     *
752     * Setting the BN_FLG_CONSTTIME flag alone is never enough, we also have
753     * to preallocate the BIGNUM internal buffer to a fixed public size big
754     * enough that operations performed during the processing never trigger
755     * a realloc which would leak the size of the scalar through memory
756     * accesses.
757     *
758     * Fixed Length
759     * ------------
760     *
761     * The order of the large prime subgroup of the curve is our choice for
762     * a fixed public size, as that is generally the upper bound for
763     * generating a private key in EC cryptosystems and should fit all valid
764     * secret scalars.
765     *
766     * For preallocating the BIGNUM storage we look at the number of "words"
767     * required for the internal representation of the order, and we
768     * preallocate 2 extra "words" in case any of the subsequent processing
769     * might temporarily overflow the order length.
770     */
771    tmp_key = BN_dup(priv_key);
772    if (tmp_key == NULL)
773        return 0;
774
775    BN_set_flags(tmp_key, BN_FLG_CONSTTIME);
776
777    fixed_top = bn_get_top(order) + 2;
778    if (bn_wexpand(tmp_key, fixed_top) == NULL) {
779        BN_clear_free(tmp_key);
780        return 0;
781    }
782
783    BN_clear_free(key->priv_key);
784    key->priv_key = tmp_key;
785    key->dirty_cnt++;
786
787    return 1;
788}
789
790const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key)
791{
792    return key->pub_key;
793}
794
795int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub_key)
796{
797    if (key->meth->set_public != NULL
798        && key->meth->set_public(key, pub_key) == 0)
799        return 0;
800    EC_POINT_free(key->pub_key);
801    key->pub_key = EC_POINT_dup(pub_key, key->group);
802    key->dirty_cnt++;
803    return (key->pub_key == NULL) ? 0 : 1;
804}
805
806unsigned int EC_KEY_get_enc_flags(const EC_KEY *key)
807{
808    return key->enc_flag;
809}
810
811void EC_KEY_set_enc_flags(EC_KEY *key, unsigned int flags)
812{
813    key->enc_flag = flags;
814}
815
816point_conversion_form_t EC_KEY_get_conv_form(const EC_KEY *key)
817{
818    return key->conv_form;
819}
820
821void EC_KEY_set_conv_form(EC_KEY *key, point_conversion_form_t cform)
822{
823    key->conv_form = cform;
824    if (key->group != NULL)
825        EC_GROUP_set_point_conversion_form(key->group, cform);
826}
827
828void EC_KEY_set_asn1_flag(EC_KEY *key, int flag)
829{
830    if (key->group != NULL)
831        EC_GROUP_set_asn1_flag(key->group, flag);
832}
833
834#ifndef OPENSSL_NO_DEPRECATED_3_0
835int EC_KEY_precompute_mult(EC_KEY *key, BN_CTX *ctx)
836{
837    if (key->group == NULL)
838        return 0;
839    return EC_GROUP_precompute_mult(key->group, ctx);
840}
841#endif
842
843int EC_KEY_get_flags(const EC_KEY *key)
844{
845    return key->flags;
846}
847
848void EC_KEY_set_flags(EC_KEY *key, int flags)
849{
850    key->flags |= flags;
851    key->dirty_cnt++;
852}
853
854void EC_KEY_clear_flags(EC_KEY *key, int flags)
855{
856    key->flags &= ~flags;
857    key->dirty_cnt++;
858}
859
860int EC_KEY_decoded_from_explicit_params(const EC_KEY *key)
861{
862    if (key == NULL || key->group == NULL)
863        return -1;
864    return key->group->decoded_from_explicit_params;
865}
866
867size_t EC_KEY_key2buf(const EC_KEY *key, point_conversion_form_t form,
868                        unsigned char **pbuf, BN_CTX *ctx)
869{
870    if (key == NULL || key->pub_key == NULL || key->group == NULL)
871        return 0;
872    return EC_POINT_point2buf(key->group, key->pub_key, form, pbuf, ctx);
873}
874
875int EC_KEY_oct2key(EC_KEY *key, const unsigned char *buf, size_t len,
876                   BN_CTX *ctx)
877{
878    if (key == NULL || key->group == NULL)
879        return 0;
880    if (key->pub_key == NULL)
881        key->pub_key = EC_POINT_new(key->group);
882    if (key->pub_key == NULL)
883        return 0;
884    if (EC_POINT_oct2point(key->group, key->pub_key, buf, len, ctx) == 0)
885        return 0;
886    key->dirty_cnt++;
887    /*
888     * Save the point conversion form.
889     * For non-custom curves the first octet of the buffer (excluding
890     * the last significant bit) contains the point conversion form.
891     * EC_POINT_oct2point() has already performed sanity checking of
892     * the buffer so we know it is valid.
893     */
894    if ((key->group->meth->flags & EC_FLAGS_CUSTOM_CURVE) == 0)
895        key->conv_form = (point_conversion_form_t)(buf[0] & ~0x01);
896    return 1;
897}
898
899size_t EC_KEY_priv2oct(const EC_KEY *eckey,
900                       unsigned char *buf, size_t len)
901{
902    if (eckey->group == NULL || eckey->group->meth == NULL)
903        return 0;
904    if (eckey->group->meth->priv2oct == NULL) {
905        ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
906        return 0;
907    }
908
909    return eckey->group->meth->priv2oct(eckey, buf, len);
910}
911
912size_t ossl_ec_key_simple_priv2oct(const EC_KEY *eckey,
913                                   unsigned char *buf, size_t len)
914{
915    size_t buf_len;
916
917    buf_len = (EC_GROUP_order_bits(eckey->group) + 7) / 8;
918    if (eckey->priv_key == NULL)
919        return 0;
920    if (buf == NULL)
921        return buf_len;
922    else if (len < buf_len)
923        return 0;
924
925    /* Octetstring may need leading zeros if BN is to short */
926
927    if (BN_bn2binpad(eckey->priv_key, buf, buf_len) == -1) {
928        ERR_raise(ERR_LIB_EC, EC_R_BUFFER_TOO_SMALL);
929        return 0;
930    }
931
932    return buf_len;
933}
934
935int EC_KEY_oct2priv(EC_KEY *eckey, const unsigned char *buf, size_t len)
936{
937    int ret;
938
939    if (eckey->group == NULL || eckey->group->meth == NULL)
940        return 0;
941    if (eckey->group->meth->oct2priv == NULL) {
942        ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
943        return 0;
944    }
945    ret = eckey->group->meth->oct2priv(eckey, buf, len);
946    if (ret == 1)
947        eckey->dirty_cnt++;
948    return ret;
949}
950
951int ossl_ec_key_simple_oct2priv(EC_KEY *eckey, const unsigned char *buf,
952                                size_t len)
953{
954    if (eckey->priv_key == NULL)
955        eckey->priv_key = BN_secure_new();
956    if (eckey->priv_key == NULL) {
957        ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
958        return 0;
959    }
960    if (BN_bin2bn(buf, len, eckey->priv_key) == NULL) {
961        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
962        return 0;
963    }
964    eckey->dirty_cnt++;
965    return 1;
966}
967
968size_t EC_KEY_priv2buf(const EC_KEY *eckey, unsigned char **pbuf)
969{
970    size_t len;
971    unsigned char *buf;
972
973    len = EC_KEY_priv2oct(eckey, NULL, 0);
974    if (len == 0)
975        return 0;
976    if ((buf = OPENSSL_malloc(len)) == NULL) {
977        ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
978        return 0;
979    }
980    len = EC_KEY_priv2oct(eckey, buf, len);
981    if (len == 0) {
982        OPENSSL_free(buf);
983        return 0;
984    }
985    *pbuf = buf;
986    return len;
987}
988
989int EC_KEY_can_sign(const EC_KEY *eckey)
990{
991    if (eckey->group == NULL || eckey->group->meth == NULL
992        || (eckey->group->meth->flags & EC_FLAGS_NO_SIGN))
993        return 0;
994    return 1;
995}
996
997/*
998 * FIPS 140-2 IG 9.9 AS09.33
999 * Perform a sign/verify operation.
1000 *
1001 * NOTE: When generating keys for key-agreement schemes - FIPS 140-2 IG 9.9
1002 * states that no additional pairwise tests are required (apart from the tests
1003 * specified in SP800-56A) when generating keys. Hence pairwise ECDH tests are
1004 * omitted here.
1005 */
1006static int ecdsa_keygen_pairwise_test(EC_KEY *eckey, OSSL_CALLBACK *cb,
1007                                      void *cbarg)
1008{
1009    int ret = 0;
1010    unsigned char dgst[16] = {0};
1011    int dgst_len = (int)sizeof(dgst);
1012    ECDSA_SIG *sig = NULL;
1013    OSSL_SELF_TEST *st = NULL;
1014
1015    st = OSSL_SELF_TEST_new(cb, cbarg);
1016    if (st == NULL)
1017        return 0;
1018
1019    OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
1020                           OSSL_SELF_TEST_DESC_PCT_ECDSA);
1021
1022    sig = ECDSA_do_sign(dgst, dgst_len, eckey);
1023    if (sig == NULL)
1024        goto err;
1025
1026    OSSL_SELF_TEST_oncorrupt_byte(st, dgst);
1027
1028    if (ECDSA_do_verify(dgst, dgst_len, sig, eckey) != 1)
1029        goto err;
1030
1031    ret = 1;
1032err:
1033    OSSL_SELF_TEST_onend(st, ret);
1034    OSSL_SELF_TEST_free(st);
1035    ECDSA_SIG_free(sig);
1036    return ret;
1037}
1038