Coverage Report

Created: 2026-09-12 06:55

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