Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl36/crypto/ec/ec_key.c
Line
Count
Source
1
/*
2
 * Copyright 2002-2025 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
215k
{
36
215k
    return ossl_ec_key_new_method_int(NULL, NULL, NULL);
37
215k
}
38
#endif
39
40
EC_KEY *EC_KEY_new_ex(OSSL_LIB_CTX *ctx, const char *propq)
41
756k
{
42
756k
    return ossl_ec_key_new_method_int(ctx, propq, NULL);
43
756k
}
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
3.11M
{
73
3.11M
    int i;
74
75
3.11M
    if (r == NULL)
76
1.74M
        return;
77
78
1.37M
    CRYPTO_DOWN_REF(&r->references, &i);
79
1.37M
    REF_PRINT_COUNT("EC_KEY", i, r);
80
1.37M
    if (i > 0)
81
391k
        return;
82
980k
    REF_ASSERT_ISNT(i < 0);
83
84
980k
    if (r->meth != NULL && r->meth->finish != NULL)
85
0
        r->meth->finish(r);
86
87
980k
#if !defined(OPENSSL_NO_ENGINE) && !defined(FIPS_MODULE)
88
980k
    ENGINE_finish(r->engine);
89
980k
#endif
90
91
980k
    if (r->group && r->group->meth->keyfinish)
92
0
        r->group->meth->keyfinish(r);
93
94
980k
#ifndef FIPS_MODULE
95
980k
    CRYPTO_free_ex_data(CRYPTO_EX_INDEX_EC_KEY, r, &r->ex_data);
96
980k
#endif
97
980k
    CRYPTO_FREE_REF(&r->references);
98
980k
    EC_GROUP_free(r->group);
99
980k
    EC_POINT_free(r->pub_key);
100
980k
    BN_clear_free(r->priv_key);
101
980k
    OPENSSL_free(r->propq);
102
103
980k
    OPENSSL_clear_free((void *)r, sizeof(EC_KEY));
104
980k
}
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
391k
{
194
391k
    int i;
195
196
391k
    if (CRYPTO_UP_REF(&r->references, &i) <= 0)
197
0
        return 0;
198
199
391k
    REF_PRINT_COUNT("EC_KEY", i, r);
200
391k
    REF_ASSERT_ISNT(i < 2);
201
391k
    return ((i > 1) ? 1 : 0);
202
391k
}
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
9.41k
{
211
9.41k
    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
9.41k
    if (eckey->meth->keygen != NULL) {
216
9.41k
        int ret;
217
218
9.41k
        ret = eckey->meth->keygen(eckey);
219
9.41k
        if (ret == 1)
220
9.41k
            eckey->dirty_cnt++;
221
222
9.41k
        return ret;
223
9.41k
    }
224
9.41k
    ERR_raise(ERR_LIB_EC, EC_R_OPERATION_NOT_SUPPORTED);
225
0
    return 0;
226
9.41k
}
227
228
int ossl_ec_key_gen(EC_KEY *eckey)
229
9.41k
{
230
9.41k
    int ret;
231
232
9.41k
    ret = eckey->group->meth->keygen(eckey);
233
234
9.41k
    if (ret == 1)
235
9.41k
        eckey->dirty_cnt++;
236
9.41k
    return ret;
237
9.41k
}
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
8.33k
{
303
8.33k
    int ok = 0;
304
8.33k
    BIGNUM *priv_key = NULL;
305
8.33k
    const BIGNUM *tmp = NULL;
306
8.33k
    BIGNUM *order = NULL;
307
8.33k
    EC_POINT *pub_key = NULL;
308
8.33k
    const EC_GROUP *group = eckey->group;
309
8.33k
    BN_CTX *ctx = BN_CTX_secure_new_ex(eckey->libctx);
310
8.33k
    int sm2 = EC_KEY_get_flags(eckey) & EC_FLAG_SM2_RANGE ? 1 : 0;
311
312
8.33k
    if (ctx == NULL)
313
0
        goto err;
314
315
8.33k
    if (eckey->priv_key == NULL) {
316
8.33k
        priv_key = BN_secure_new();
317
8.33k
        if (priv_key == NULL)
318
0
            goto err;
319
8.33k
    } 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
8.33k
    tmp = EC_GROUP_get0_order(group);
329
8.33k
    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
8.33k
    if (sm2) {
343
0
        order = BN_new();
344
0
        if (order == NULL || !BN_sub(order, tmp, BN_value_one()))
345
0
            goto err;
346
8.33k
    } else {
347
8.33k
        order = BN_dup(tmp);
348
8.33k
        if (order == NULL)
349
0
            goto err;
350
8.33k
    }
351
352
8.33k
    do
353
8.33k
        if (!BN_priv_rand_range_ex(priv_key, order, 0, ctx))
354
0
            goto err;
355
8.33k
    while (BN_is_zero(priv_key));
356
357
8.33k
    if (eckey->pub_key == NULL) {
358
8.33k
        pub_key = EC_POINT_new(group);
359
8.33k
        if (pub_key == NULL)
360
0
            goto err;
361
8.33k
    } 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
8.33k
    if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
366
0
        goto err;
367
368
8.33k
    eckey->priv_key = priv_key;
369
8.33k
    eckey->pub_key = pub_key;
370
8.33k
    priv_key = NULL;
371
8.33k
    pub_key = NULL;
372
373
8.33k
    eckey->dirty_cnt++;
374
375
#ifdef FIPS_MODULE
376
    pairwise_test = 1;
377
#endif /* FIPS_MODULE */
378
379
8.33k
    ok = 1;
380
8.33k
    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
8.33k
err:
389
    /* Step (9): If there is an error return an invalid keypair. */
390
8.33k
    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
8.33k
    EC_POINT_free(pub_key);
398
8.33k
    BN_clear_free(priv_key);
399
8.33k
    BN_CTX_free(ctx);
400
8.33k
    BN_free(order);
401
8.33k
    return ok;
402
8.33k
}
403
404
#ifndef FIPS_MODULE
405
/*
406
 * This is similar to ec_generate_key(), except it uses an ikm to
407
 * derive the private key.
408
 */
409
int ossl_ec_generate_key_dhkem(EC_KEY *eckey,
410
    const unsigned char *ikm, size_t ikmlen)
411
0
{
412
0
    int ok = 0;
413
414
0
    if (eckey->priv_key == NULL) {
415
0
        eckey->priv_key = BN_secure_new();
416
0
        if (eckey->priv_key == NULL)
417
0
            goto err;
418
0
    }
419
0
    if (ossl_ec_dhkem_derive_private(eckey, eckey->priv_key, ikm, ikmlen) <= 0)
420
0
        goto err;
421
0
    if (eckey->pub_key == NULL) {
422
0
        eckey->pub_key = EC_POINT_new(eckey->group);
423
0
        if (eckey->pub_key == NULL)
424
0
            goto err;
425
0
    }
426
0
    if (!ossl_ec_key_simple_generate_public_key(eckey))
427
0
        goto err;
428
429
0
    ok = 1;
430
0
err:
431
0
    if (!ok) {
432
0
        BN_clear_free(eckey->priv_key);
433
0
        eckey->priv_key = NULL;
434
0
        if (eckey->pub_key != NULL)
435
0
            EC_POINT_set_to_infinity(eckey->group, eckey->pub_key);
436
0
    }
437
0
    return ok;
438
0
}
439
#endif
440
441
int ossl_ec_key_simple_generate_key(EC_KEY *eckey)
442
9.41k
{
443
9.41k
    return ec_generate_key(eckey, 0);
444
9.41k
}
445
446
int ossl_ec_key_simple_generate_public_key(EC_KEY *eckey)
447
17.5k
{
448
17.5k
    int ret;
449
17.5k
    BN_CTX *ctx = BN_CTX_new_ex(eckey->libctx);
450
451
17.5k
    if (ctx == NULL)
452
0
        return 0;
453
454
    /*
455
     * See SP800-56AR3 5.6.1.2.2: Step (8)
456
     * pub_key = priv_key * G (where G is a point on the curve)
457
     */
458
17.5k
    ret = EC_POINT_mul(eckey->group, eckey->pub_key, eckey->priv_key, NULL,
459
17.5k
        NULL, ctx);
460
461
17.5k
    BN_CTX_free(ctx);
462
17.5k
    if (ret == 1)
463
17.5k
        eckey->dirty_cnt++;
464
465
17.5k
    return ret;
466
17.5k
}
467
468
int EC_KEY_check_key(const EC_KEY *eckey)
469
0
{
470
0
    if (eckey == NULL || eckey->group == NULL || eckey->pub_key == NULL) {
471
0
        ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
472
0
        return 0;
473
0
    }
474
475
0
    if (eckey->group->meth->keycheck == NULL) {
476
0
        ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
477
0
        return 0;
478
0
    }
479
480
0
    return eckey->group->meth->keycheck(eckey);
481
0
}
482
483
/*
484
 * Check the range of the EC public key.
485
 * See SP800-56A R3 Section 5.6.2.3.3 (Part 2)
486
 * i.e.
487
 *  - If q = odd prime p: Verify that xQ and yQ are integers in the
488
 *    interval[0, p - 1], OR
489
 *  - If q = 2m: Verify that xQ and yQ are bit strings of length m bits.
490
 * Returns 1 if the public key has a valid range, otherwise it returns 0.
491
 */
492
static int ec_key_public_range_check(BN_CTX *ctx, const EC_KEY *key)
493
12.4k
{
494
12.4k
    int ret = 0;
495
12.4k
    BIGNUM *x, *y;
496
497
12.4k
    BN_CTX_start(ctx);
498
12.4k
    x = BN_CTX_get(ctx);
499
12.4k
    y = BN_CTX_get(ctx);
500
12.4k
    if (y == NULL)
501
0
        goto err;
502
503
12.4k
    if (!EC_POINT_get_affine_coordinates(key->group, key->pub_key, x, y, ctx))
504
0
        goto err;
505
506
12.4k
    if (EC_GROUP_get_field_type(key->group) == NID_X9_62_prime_field) {
507
9.84k
        if (BN_is_negative(x)
508
9.84k
            || BN_cmp(x, key->group->field) >= 0
509
9.84k
            || BN_is_negative(y)
510
9.84k
            || BN_cmp(y, key->group->field) >= 0) {
511
0
            goto err;
512
0
        }
513
9.84k
    } else {
514
2.57k
        int m = EC_GROUP_get_degree(key->group);
515
2.57k
        if (BN_num_bits(x) > m || BN_num_bits(y) > m) {
516
0
            goto err;
517
0
        }
518
2.57k
    }
519
12.4k
    ret = 1;
520
12.4k
err:
521
12.4k
    BN_CTX_end(ctx);
522
12.4k
    return ret;
523
12.4k
}
524
525
/*
526
 * ECC Partial Public-Key Validation as specified in SP800-56A R3
527
 * Section 5.6.2.3.4 ECC Partial Public-Key Validation Routine.
528
 */
529
int ossl_ec_key_public_check_quick(const EC_KEY *eckey, BN_CTX *ctx)
530
14.2k
{
531
14.2k
    if (eckey == NULL || eckey->group == NULL || eckey->pub_key == NULL) {
532
1.22k
        ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
533
1.22k
        return 0;
534
1.22k
    }
535
536
    /* 5.6.2.3.3 (Step 1): Q != infinity */
537
13.0k
    if (EC_POINT_is_at_infinity(eckey->group, eckey->pub_key)) {
538
622
        ERR_raise(ERR_LIB_EC, EC_R_POINT_AT_INFINITY);
539
622
        return 0;
540
622
    }
541
542
    /* 5.6.2.3.3 (Step 2) Test if the public key is in range */
543
12.4k
    if (!ec_key_public_range_check(ctx, eckey)) {
544
0
        ERR_raise(ERR_LIB_EC, EC_R_COORDINATES_OUT_OF_RANGE);
545
0
        return 0;
546
0
    }
547
548
    /* 5.6.2.3.3 (Step 3) is the pub_key on the elliptic curve */
549
12.4k
    if (EC_POINT_is_on_curve(eckey->group, eckey->pub_key, ctx) <= 0) {
550
20
        ERR_raise(ERR_LIB_EC, EC_R_POINT_IS_NOT_ON_CURVE);
551
20
        return 0;
552
20
    }
553
12.4k
    return 1;
554
12.4k
}
555
556
/*
557
 * ECC Key validation as specified in SP800-56A R3.
558
 * Section 5.6.2.3.3 ECC Full Public-Key Validation Routine.
559
 */
560
int ossl_ec_key_public_check(const EC_KEY *eckey, BN_CTX *ctx)
561
10.8k
{
562
10.8k
    int ret = 0;
563
10.8k
    EC_POINT *point = NULL;
564
10.8k
    const BIGNUM *order = NULL;
565
10.8k
    const BIGNUM *cofactor = EC_GROUP_get0_cofactor(eckey->group);
566
567
10.8k
    if (!ossl_ec_key_public_check_quick(eckey, ctx))
568
1.47k
        return 0;
569
570
9.36k
    if (cofactor != NULL && BN_is_one(cofactor)) {
571
        /* Skip the unnecessary expensive computation for curves with cofactor of 1. */
572
6.44k
        return 1;
573
6.44k
    }
574
575
2.92k
    point = EC_POINT_new(eckey->group);
576
2.92k
    if (point == NULL)
577
0
        return 0;
578
579
2.92k
    order = eckey->group->order;
580
2.92k
    if (BN_is_zero(order)) {
581
0
        ERR_raise(ERR_LIB_EC, EC_R_INVALID_GROUP_ORDER);
582
0
        goto err;
583
0
    }
584
    /* 5.6.2.3.3 (Step 4) : pub_key * order is the point at infinity. */
585
2.92k
    if (!EC_POINT_mul(eckey->group, point, NULL, eckey->pub_key, order, ctx)) {
586
0
        ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
587
0
        goto err;
588
0
    }
589
2.92k
    if (!EC_POINT_is_at_infinity(eckey->group, point)) {
590
904
        ERR_raise(ERR_LIB_EC, EC_R_WRONG_ORDER);
591
904
        goto err;
592
904
    }
593
2.02k
    ret = 1;
594
2.92k
err:
595
2.92k
    EC_POINT_free(point);
596
2.92k
    return ret;
597
2.02k
}
598
599
/*
600
 * ECC Key validation as specified in SP800-56A R3.
601
 * Section 5.6.2.1.2 Owner Assurance of Private-Key Validity
602
 * The private key is in the range [1, order-1]
603
 */
604
int ossl_ec_key_private_check(const EC_KEY *eckey)
605
8.38k
{
606
8.38k
    if (eckey == NULL || eckey->group == NULL || eckey->priv_key == NULL) {
607
1.60k
        ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
608
1.60k
        return 0;
609
1.60k
    }
610
6.77k
    if (BN_cmp(eckey->priv_key, BN_value_one()) < 0
611
6.08k
        || BN_cmp(eckey->priv_key, eckey->group->order) >= 0) {
612
2.91k
        ERR_raise(ERR_LIB_EC, EC_R_INVALID_PRIVATE_KEY);
613
2.91k
        return 0;
614
2.91k
    }
615
3.85k
    return 1;
616
6.77k
}
617
618
/*
619
 * ECC Key validation as specified in SP800-56A R3.
620
 * Section 5.6.2.1.4 Owner Assurance of Pair-wise Consistency (b)
621
 * Check if generator * priv_key = pub_key
622
 */
623
int ossl_ec_key_pairwise_check(const EC_KEY *eckey, BN_CTX *ctx)
624
1.88k
{
625
1.88k
    int ret = 0;
626
1.88k
    EC_POINT *point = NULL;
627
628
1.88k
    if (eckey == NULL
629
1.88k
        || eckey->group == NULL
630
1.88k
        || eckey->pub_key == NULL
631
1.88k
        || eckey->priv_key == NULL) {
632
0
        ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
633
0
        return 0;
634
0
    }
635
636
1.88k
    point = EC_POINT_new(eckey->group);
637
1.88k
    if (point == NULL)
638
0
        goto err;
639
640
1.88k
    if (!EC_POINT_mul(eckey->group, point, eckey->priv_key, NULL, NULL, ctx)) {
641
0
        ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
642
0
        goto err;
643
0
    }
644
1.88k
    if (EC_POINT_cmp(eckey->group, point, eckey->pub_key, ctx) != 0) {
645
346
        ERR_raise(ERR_LIB_EC, EC_R_INVALID_PRIVATE_KEY);
646
346
        goto err;
647
346
    }
648
1.54k
    ret = 1;
649
1.88k
err:
650
1.88k
    EC_POINT_free(point);
651
1.88k
    return ret;
652
1.54k
}
653
654
/*
655
 * ECC Key validation as specified in SP800-56A R3.
656
 *    Section 5.6.2.3.3 ECC Full Public-Key Validation
657
 *    Section 5.6.2.1.2 Owner Assurance of Private-Key Validity
658
 *    Section 5.6.2.1.4 Owner Assurance of Pair-wise Consistency
659
 * NOTES:
660
 *    Before calling this method in fips mode, there should be an assurance that
661
 *    an approved elliptic-curve group is used.
662
 * Returns 1 if the key is valid, otherwise it returns 0.
663
 */
664
int ossl_ec_key_simple_check_key(const EC_KEY *eckey)
665
0
{
666
0
    int ok = 0;
667
0
    BN_CTX *ctx = NULL;
668
669
0
    if (eckey == NULL) {
670
0
        ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
671
0
        return 0;
672
0
    }
673
0
    if ((ctx = BN_CTX_new_ex(eckey->libctx)) == NULL)
674
0
        return 0;
675
676
0
    if (!ossl_ec_key_public_check(eckey, ctx))
677
0
        goto err;
678
679
0
    if (eckey->priv_key != NULL) {
680
0
        if (!ossl_ec_key_private_check(eckey)
681
0
            || !ossl_ec_key_pairwise_check(eckey, ctx))
682
0
            goto err;
683
0
    }
684
0
    ok = 1;
685
0
err:
686
0
    BN_CTX_free(ctx);
687
0
    return ok;
688
0
}
689
690
int EC_KEY_set_public_key_affine_coordinates(EC_KEY *key, BIGNUM *x,
691
    BIGNUM *y)
692
0
{
693
0
    BN_CTX *ctx = NULL;
694
0
    BIGNUM *tx, *ty;
695
0
    EC_POINT *point = NULL;
696
0
    int ok = 0;
697
698
0
    if (key == NULL || key->group == NULL || x == NULL || y == NULL) {
699
0
        ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
700
0
        return 0;
701
0
    }
702
0
    ctx = BN_CTX_new_ex(key->libctx);
703
0
    if (ctx == NULL)
704
0
        return 0;
705
706
0
    BN_CTX_start(ctx);
707
0
    point = EC_POINT_new(key->group);
708
709
0
    if (point == NULL)
710
0
        goto err;
711
712
0
    tx = BN_CTX_get(ctx);
713
0
    ty = BN_CTX_get(ctx);
714
0
    if (ty == NULL)
715
0
        goto err;
716
717
0
    if (!EC_POINT_set_affine_coordinates(key->group, point, x, y, ctx))
718
0
        goto err;
719
0
    if (!EC_POINT_get_affine_coordinates(key->group, point, tx, ty, ctx))
720
0
        goto err;
721
722
    /*
723
     * Check if retrieved coordinates match originals. The range check is done
724
     * inside EC_KEY_check_key().
725
     */
726
0
    if (BN_cmp(x, tx) || BN_cmp(y, ty)) {
727
0
        ERR_raise(ERR_LIB_EC, EC_R_COORDINATES_OUT_OF_RANGE);
728
0
        goto err;
729
0
    }
730
731
    /* EC_KEY_set_public_key updates dirty_cnt */
732
0
    if (!EC_KEY_set_public_key(key, point))
733
0
        goto err;
734
735
0
    if (EC_KEY_check_key(key) == 0)
736
0
        goto err;
737
738
0
    ok = 1;
739
740
0
err:
741
0
    BN_CTX_end(ctx);
742
0
    BN_CTX_free(ctx);
743
0
    EC_POINT_free(point);
744
0
    return ok;
745
0
}
746
747
OSSL_LIB_CTX *ossl_ec_key_get_libctx(const EC_KEY *key)
748
1.43M
{
749
1.43M
    return key->libctx;
750
1.43M
}
751
752
const char *ossl_ec_key_get0_propq(const EC_KEY *key)
753
615k
{
754
615k
    return key->propq;
755
615k
}
756
757
void ossl_ec_key_set0_libctx(EC_KEY *key, OSSL_LIB_CTX *libctx)
758
362k
{
759
362k
    key->libctx = libctx;
760
    /* Do we need to propagate this to the group? */
761
362k
}
762
763
const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key)
764
2.98M
{
765
2.98M
    return key->group;
766
2.98M
}
767
768
int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group)
769
673k
{
770
673k
    if (key->meth->set_group != NULL && key->meth->set_group(key, group) == 0)
771
0
        return 0;
772
673k
    EC_GROUP_free(key->group);
773
673k
    key->group = EC_GROUP_dup(group);
774
673k
    if (key->group != NULL && EC_GROUP_get_curve_name(key->group) == NID_sm2)
775
5.75k
        EC_KEY_set_flags(key, EC_FLAG_SM2_RANGE);
776
777
673k
    key->dirty_cnt++;
778
673k
    return (key->group == NULL) ? 0 : 1;
779
673k
}
780
781
const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key)
782
660k
{
783
660k
    return key->priv_key;
784
660k
}
785
786
int EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *priv_key)
787
102k
{
788
102k
    int fixed_top;
789
102k
    const BIGNUM *order = NULL;
790
102k
    BIGNUM *tmp_key = NULL;
791
792
102k
    if (key->group == NULL || key->group->meth == NULL)
793
0
        return 0;
794
795
    /*
796
     * Not only should key->group be set, but it should also be in a valid
797
     * fully initialized state.
798
     *
799
     * Specifically, to operate in constant time, we need that the group order
800
     * is set, as we use its length as the fixed public size of any scalar used
801
     * as an EC private key.
802
     */
803
102k
    order = EC_GROUP_get0_order(key->group);
804
102k
    if (order == NULL || BN_is_zero(order))
805
0
        return 0; /* This should never happen */
806
807
102k
    if (key->group->meth->set_private != NULL
808
0
        && key->group->meth->set_private(key, priv_key) == 0)
809
0
        return 0;
810
102k
    if (key->meth->set_private != NULL
811
0
        && key->meth->set_private(key, priv_key) == 0)
812
0
        return 0;
813
814
    /*
815
     * Return `0` to comply with legacy behavior for this function, see
816
     * https://github.com/openssl/openssl/issues/18744#issuecomment-1195175696
817
     */
818
102k
    if (priv_key == NULL) {
819
0
        BN_clear_free(key->priv_key);
820
0
        key->priv_key = NULL;
821
0
        return 0; /* intentional for legacy compatibility */
822
0
    }
823
824
    /*
825
     * We should never leak the bit length of the secret scalar in the key,
826
     * so we always set the `BN_FLG_CONSTTIME` flag on the internal `BIGNUM`
827
     * holding the secret scalar.
828
     *
829
     * This is important also because `BN_dup()` (and `BN_copy()`) do not
830
     * propagate the `BN_FLG_CONSTTIME` flag from the source `BIGNUM`, and
831
     * this brings an extra risk of inadvertently losing the flag, even when
832
     * the caller specifically set it.
833
     *
834
     * The propagation has been turned on and off a few times in the past
835
     * years because in some conditions has shown unintended consequences in
836
     * some code paths, so at the moment we can't fix this in the BN layer.
837
     *
838
     * In `EC_KEY_set_private_key()` we can work around the propagation by
839
     * manually setting the flag after `BN_dup()` as we know for sure that
840
     * inside the EC module the `BN_FLG_CONSTTIME` is always treated
841
     * correctly and should not generate unintended consequences.
842
     *
843
     * Setting the BN_FLG_CONSTTIME flag alone is never enough, we also have
844
     * to preallocate the BIGNUM internal buffer to a fixed public size big
845
     * enough that operations performed during the processing never trigger
846
     * a realloc which would leak the size of the scalar through memory
847
     * accesses.
848
     *
849
     * Fixed Length
850
     * ------------
851
     *
852
     * The order of the large prime subgroup of the curve is our choice for
853
     * a fixed public size, as that is generally the upper bound for
854
     * generating a private key in EC cryptosystems and should fit all valid
855
     * secret scalars.
856
     *
857
     * For preallocating the BIGNUM storage we look at the number of "words"
858
     * required for the internal representation of the order, and we
859
     * preallocate 2 extra "words" in case any of the subsequent processing
860
     * might temporarily overflow the order length.
861
     */
862
102k
    tmp_key = BN_dup(priv_key);
863
102k
    if (tmp_key == NULL)
864
0
        return 0;
865
866
102k
    BN_set_flags(tmp_key, BN_FLG_CONSTTIME);
867
868
102k
    fixed_top = bn_get_top(order) + 2;
869
102k
    if (bn_wexpand(tmp_key, fixed_top) == NULL) {
870
0
        BN_clear_free(tmp_key);
871
0
        return 0;
872
0
    }
873
874
102k
    BN_clear_free(key->priv_key);
875
102k
    key->priv_key = tmp_key;
876
102k
    key->dirty_cnt++;
877
878
102k
    return 1;
879
102k
}
880
881
const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key)
882
780k
{
883
780k
    return key->pub_key;
884
780k
}
885
886
int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub_key)
887
102k
{
888
102k
    if (key->meth->set_public != NULL
889
0
        && key->meth->set_public(key, pub_key) == 0)
890
0
        return 0;
891
102k
    EC_POINT_free(key->pub_key);
892
102k
    key->pub_key = EC_POINT_dup(pub_key, key->group);
893
102k
    key->dirty_cnt++;
894
102k
    return (key->pub_key == NULL) ? 0 : 1;
895
102k
}
896
897
unsigned int EC_KEY_get_enc_flags(const EC_KEY *key)
898
514k
{
899
514k
    return key->enc_flag;
900
514k
}
901
902
void EC_KEY_set_enc_flags(EC_KEY *key, unsigned int flags)
903
2.88k
{
904
2.88k
    key->enc_flag = flags;
905
2.88k
}
906
907
point_conversion_form_t EC_KEY_get_conv_form(const EC_KEY *key)
908
633k
{
909
633k
    return key->conv_form;
910
633k
}
911
912
void EC_KEY_set_conv_form(EC_KEY *key, point_conversion_form_t cform)
913
102k
{
914
102k
    key->conv_form = cform;
915
102k
    if (key->group != NULL)
916
102k
        EC_GROUP_set_point_conversion_form(key->group, cform);
917
102k
}
918
919
void EC_KEY_set_asn1_flag(EC_KEY *key, int flag)
920
0
{
921
0
    if (key->group != NULL)
922
0
        EC_GROUP_set_asn1_flag(key->group, flag);
923
0
}
924
925
#ifndef OPENSSL_NO_DEPRECATED_3_0
926
int EC_KEY_precompute_mult(EC_KEY *key, BN_CTX *ctx)
927
0
{
928
0
    if (key->group == NULL)
929
0
        return 0;
930
0
    return EC_GROUP_precompute_mult(key->group, ctx);
931
0
}
932
#endif
933
934
int EC_KEY_get_flags(const EC_KEY *key)
935
1.83M
{
936
1.83M
    return key->flags;
937
1.83M
}
938
939
void EC_KEY_set_flags(EC_KEY *key, int flags)
940
57.3k
{
941
57.3k
    key->flags |= flags;
942
57.3k
    key->dirty_cnt++;
943
57.3k
}
944
945
void EC_KEY_clear_flags(EC_KEY *key, int flags)
946
51.4k
{
947
51.4k
    key->flags &= ~flags;
948
51.4k
    key->dirty_cnt++;
949
51.4k
}
950
951
int EC_KEY_decoded_from_explicit_params(const EC_KEY *key)
952
4
{
953
4
    if (key == NULL || key->group == NULL)
954
0
        return -1;
955
4
    return key->group->decoded_from_explicit_params;
956
4
}
957
958
size_t EC_KEY_key2buf(const EC_KEY *key, point_conversion_form_t form,
959
    unsigned char **pbuf, BN_CTX *ctx)
960
20.2k
{
961
20.2k
    if (key == NULL || key->pub_key == NULL || key->group == NULL)
962
0
        return 0;
963
20.2k
    return EC_POINT_point2buf(key->group, key->pub_key, form, pbuf, ctx);
964
20.2k
}
965
966
int EC_KEY_oct2key(EC_KEY *key, const unsigned char *buf, size_t len,
967
    BN_CTX *ctx)
968
628k
{
969
628k
    if (key == NULL || key->group == NULL)
970
0
        return 0;
971
628k
    if (key->pub_key == NULL)
972
566k
        key->pub_key = EC_POINT_new(key->group);
973
628k
    if (key->pub_key == NULL)
974
0
        return 0;
975
628k
    if (EC_POINT_oct2point(key->group, key->pub_key, buf, len, ctx) == 0)
976
264k
        return 0;
977
363k
    key->dirty_cnt++;
978
    /*
979
     * Save the point conversion form.
980
     * For non-custom curves the first octet of the buffer (excluding
981
     * the last significant bit) contains the point conversion form.
982
     * EC_POINT_oct2point() has already performed sanity checking of
983
     * the buffer so we know it is valid.
984
     */
985
363k
    if ((key->group->meth->flags & EC_FLAGS_CUSTOM_CURVE) == 0)
986
363k
        key->conv_form = (point_conversion_form_t)(buf[0] & ~0x01);
987
363k
    return 1;
988
628k
}
989
990
size_t EC_KEY_priv2oct(const EC_KEY *eckey,
991
    unsigned char *buf, size_t len)
992
51.3k
{
993
51.3k
    if (eckey->group == NULL || eckey->group->meth == NULL)
994
0
        return 0;
995
51.3k
    if (eckey->group->meth->priv2oct == NULL) {
996
0
        ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
997
0
        return 0;
998
0
    }
999
1000
51.3k
    return eckey->group->meth->priv2oct(eckey, buf, len);
1001
51.3k
}
1002
1003
size_t ossl_ec_key_simple_priv2oct(const EC_KEY *eckey,
1004
    unsigned char *buf, size_t len)
1005
51.3k
{
1006
51.3k
    int buf_len;
1007
1008
51.3k
    buf_len = (EC_GROUP_order_bits(eckey->group) + 7) / 8;
1009
51.3k
    if (eckey->priv_key == NULL)
1010
0
        return 0;
1011
51.3k
    if (buf == NULL)
1012
25.6k
        return buf_len;
1013
25.6k
    else if (len < (size_t)buf_len)
1014
0
        return 0;
1015
1016
    /* Octetstring may need leading zeros if BN is to short */
1017
1018
25.6k
    if (BN_bn2binpad(eckey->priv_key, buf, buf_len) == -1) {
1019
8.14k
        ERR_raise(ERR_LIB_EC, EC_R_BUFFER_TOO_SMALL);
1020
8.14k
        return 0;
1021
8.14k
    }
1022
1023
17.5k
    return buf_len;
1024
25.6k
}
1025
1026
int EC_KEY_oct2priv(EC_KEY *eckey, const unsigned char *buf, size_t len)
1027
78.8k
{
1028
78.8k
    int ret;
1029
1030
78.8k
    if (eckey->group == NULL || eckey->group->meth == NULL)
1031
0
        return 0;
1032
78.8k
    if (eckey->group->meth->oct2priv == NULL) {
1033
0
        ERR_raise(ERR_LIB_EC, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1034
0
        return 0;
1035
0
    }
1036
78.8k
    ret = eckey->group->meth->oct2priv(eckey, buf, len);
1037
78.8k
    if (ret == 1)
1038
78.8k
        eckey->dirty_cnt++;
1039
78.8k
    return ret;
1040
78.8k
}
1041
1042
int ossl_ec_key_simple_oct2priv(EC_KEY *eckey, const unsigned char *buf,
1043
    size_t len)
1044
27.7k
{
1045
27.7k
    if (len > INT_MAX) {
1046
0
        ERR_raise(ERR_LIB_EC, ERR_R_PASSED_INVALID_ARGUMENT);
1047
0
        return 0;
1048
0
    }
1049
27.7k
    if (eckey->priv_key == NULL)
1050
27.7k
        eckey->priv_key = BN_secure_new();
1051
27.7k
    if (eckey->priv_key == NULL) {
1052
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
1053
0
        return 0;
1054
0
    }
1055
27.7k
    if (BN_bin2bn(buf, (int)len, eckey->priv_key) == NULL) {
1056
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
1057
0
        return 0;
1058
0
    }
1059
27.7k
    eckey->dirty_cnt++;
1060
27.7k
    return 1;
1061
27.7k
}
1062
1063
size_t EC_KEY_priv2buf(const EC_KEY *eckey, unsigned char **pbuf)
1064
25.6k
{
1065
25.6k
    size_t len;
1066
25.6k
    unsigned char *buf;
1067
1068
25.6k
    len = EC_KEY_priv2oct(eckey, NULL, 0);
1069
25.6k
    if (len == 0)
1070
0
        return 0;
1071
25.6k
    if ((buf = OPENSSL_malloc(len)) == NULL)
1072
0
        return 0;
1073
25.6k
    len = EC_KEY_priv2oct(eckey, buf, len);
1074
25.6k
    if (len == 0) {
1075
8.14k
        OPENSSL_free(buf);
1076
8.14k
        return 0;
1077
8.14k
    }
1078
17.5k
    *pbuf = buf;
1079
17.5k
    return len;
1080
25.6k
}
1081
1082
int EC_KEY_can_sign(const EC_KEY *eckey)
1083
15.0k
{
1084
15.0k
    if (eckey->group == NULL || eckey->group->meth == NULL
1085
15.0k
        || (eckey->group->meth->flags & EC_FLAGS_NO_SIGN))
1086
0
        return 0;
1087
15.0k
    return 1;
1088
15.0k
}
1089
1090
/*
1091
 * FIPS 140-2 IG 9.9 AS09.33
1092
 * Perform a sign/verify operation.
1093
 *
1094
 * NOTE: When generating keys for key-agreement schemes - FIPS 140-2 IG 9.9
1095
 * states that no additional pairwise tests are required (apart from the tests
1096
 * specified in SP800-56A) when generating keys. Hence pairwise ECDH tests are
1097
 * omitted here.
1098
 */
1099
static int ecdsa_keygen_pairwise_test(EC_KEY *eckey, OSSL_CALLBACK *cb,
1100
    void *cbarg)
1101
0
{
1102
0
    int ret = 0;
1103
0
    unsigned char dgst[16] = { 0 };
1104
0
    int dgst_len = (int)sizeof(dgst);
1105
0
    ECDSA_SIG *sig = NULL;
1106
0
    OSSL_SELF_TEST *st = NULL;
1107
1108
0
    st = OSSL_SELF_TEST_new(cb, cbarg);
1109
0
    if (st == NULL)
1110
0
        return 0;
1111
1112
0
    OSSL_SELF_TEST_onbegin(st, OSSL_SELF_TEST_TYPE_PCT,
1113
0
        OSSL_SELF_TEST_DESC_PCT_ECDSA);
1114
1115
0
    sig = ECDSA_do_sign(dgst, dgst_len, eckey);
1116
0
    if (sig == NULL)
1117
0
        goto err;
1118
1119
0
    OSSL_SELF_TEST_oncorrupt_byte(st, dgst);
1120
1121
0
    if (ECDSA_do_verify(dgst, dgst_len, sig, eckey) != 1)
1122
0
        goto err;
1123
1124
0
    ret = 1;
1125
0
err:
1126
0
    OSSL_SELF_TEST_onend(st, ret);
1127
0
    OSSL_SELF_TEST_free(st);
1128
0
    ECDSA_SIG_free(sig);
1129
0
    return ret;
1130
0
}