Coverage Report

Created: 2026-09-12 06:55

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