Coverage Report

Created: 2026-09-12 06:55

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