Coverage Report

Created: 2025-12-31 06:58

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