Coverage Report

Created: 2025-06-13 06:58

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