Coverage Report

Created: 2026-07-16 06:59

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/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
#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
0
{
33
0
    return ossl_ec_key_new_method_int(NULL, NULL);
34
0
}
35
#endif
36
37
EC_KEY *EC_KEY_new_ex(OSSL_LIB_CTX *ctx, const char *propq)
38
0
{
39
0
    return ossl_ec_key_new_method_int(ctx, propq);
40
0
}
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
0
{
70
0
    int i;
71
72
0
    if (r == NULL)
73
0
        return;
74
75
0
    CRYPTO_DOWN_REF(&r->references, &i);
76
0
    REF_PRINT_COUNT("EC_KEY", i, r);
77
0
    if (i > 0)
78
0
        return;
79
0
    REF_ASSERT_ISNT(i < 0);
80
81
0
    if (r->meth != NULL && r->meth->finish != NULL)
82
0
        r->meth->finish(r);
83
84
0
    if (r->group && r->group->meth->keyfinish)
85
0
        r->group->meth->keyfinish(r);
86
87
0
#ifndef FIPS_MODULE
88
0
    CRYPTO_free_ex_data(CRYPTO_EX_INDEX_EC_KEY, r, &r->ex_data);
89
0
#endif
90
0
    CRYPTO_FREE_REF(&r->references);
91
0
    EC_GROUP_free(r->group);
92
0
    EC_POINT_free(r->pub_key);
93
0
    BN_clear_free(r->priv_key);
94
0
    OPENSSL_free(r->propq);
95
96
0
    OPENSSL_clear_free((void *)r, sizeof(EC_KEY));
97
0
}
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
0
{
176
0
    int i;
177
178
0
    if (CRYPTO_UP_REF(&r->references, &i) <= 0)
179
0
        return 0;
180
181
0
    REF_PRINT_COUNT("EC_KEY", i, r);
182
0
    REF_ASSERT_ISNT(i < 2);
183
0
    return ((i > 1) ? 1 : 0);
184
0
}
185
186
int EC_KEY_generate_key(EC_KEY *eckey)
187
0
{
188
0
    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
0
    if (eckey->meth->keygen != NULL) {
193
0
        int ret;
194
195
0
        ret = eckey->meth->keygen(eckey);
196
0
        if (ret == 1)
197
0
            eckey->dirty_cnt++;
198
199
0
        return ret;
200
0
    }
201
0
    ERR_raise(ERR_LIB_EC, EC_R_OPERATION_NOT_SUPPORTED);
202
0
    return 0;
203
0
}
204
205
int ossl_ec_key_gen(EC_KEY *eckey)
206
0
{
207
0
    int ret;
208
209
0
    ret = eckey->group->meth->keygen(eckey);
210
211
0
    if (ret == 1)
212
0
        eckey->dirty_cnt++;
213
0
    return ret;
214
0
}
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
0
{
230
0
    int ok = 0;
231
0
    BIGNUM *priv_key = NULL;
232
0
    const BIGNUM *tmp = NULL;
233
0
    BIGNUM *order = NULL;
234
0
    EC_POINT *pub_key = NULL;
235
0
    const EC_GROUP *group = eckey->group;
236
0
    BN_CTX *ctx = BN_CTX_secure_new_ex(eckey->libctx);
237
0
    int sm2 = EC_KEY_get_flags(eckey) & EC_FLAG_SM2_RANGE ? 1 : 0;
238
239
0
    if (ctx == NULL)
240
0
        goto err;
241
242
0
    if (eckey->priv_key == NULL) {
243
0
        priv_key = BN_secure_new();
244
0
        if (priv_key == NULL)
245
0
            goto err;
246
0
    } 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
0
    tmp = EC_GROUP_get0_order(group);
256
0
    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
0
    if (sm2) {
270
0
        order = BN_new();
271
0
        if (order == NULL || !BN_sub(order, tmp, BN_value_one()))
272
0
            goto err;
273
0
    } else {
274
0
        order = BN_dup(tmp);
275
0
        if (order == NULL)
276
0
            goto err;
277
0
    }
278
279
0
    do
280
0
        if (!BN_priv_rand_range_ex(priv_key, order, 0, ctx))
281
0
            goto err;
282
0
    while (BN_is_zero(priv_key));
283
284
0
    if (eckey->pub_key == NULL) {
285
0
        pub_key = EC_POINT_new(group);
286
0
        if (pub_key == NULL)
287
0
            goto err;
288
0
    } 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
0
    if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
293
0
        goto err;
294
295
0
    eckey->priv_key = priv_key;
296
0
    eckey->pub_key = pub_key;
297
0
    priv_key = NULL;
298
0
    pub_key = NULL;
299
300
0
    eckey->dirty_cnt++;
301
302
#ifdef FIPS_MODULE
303
    pairwise_test = 1;
304
#endif /* FIPS_MODULE */
305
306
0
    ok = 1;
307
0
    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
0
err:
315
    /* Step (9): If there is an error return an invalid keypair. */
316
0
    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
0
    EC_POINT_free(pub_key);
323
0
    BN_clear_free(priv_key);
324
0
    BN_CTX_free(ctx);
325
0
    BN_free(order);
326
0
    return ok;
327
0
}
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
0
{
368
0
    return ec_generate_key(eckey, 0);
369
0
}
370
371
int ossl_ec_key_simple_generate_public_key(EC_KEY *eckey)
372
0
{
373
0
    int ret;
374
0
    BN_CTX *ctx = BN_CTX_new_ex(eckey->libctx);
375
376
0
    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
0
    ret = EC_POINT_mul(eckey->group, eckey->pub_key, eckey->priv_key, NULL,
384
0
        NULL, ctx);
385
386
0
    BN_CTX_free(ctx);
387
0
    if (ret == 1)
388
0
        eckey->dirty_cnt++;
389
390
0
    return ret;
391
0
}
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
0
{
419
0
    int ret = 0;
420
0
    BIGNUM *x, *y;
421
422
0
    BN_CTX_start(ctx);
423
0
    x = BN_CTX_get(ctx);
424
0
    y = BN_CTX_get(ctx);
425
0
    if (y == NULL)
426
0
        goto err;
427
428
0
    if (!EC_POINT_get_affine_coordinates(key->group, key->pub_key, x, y, ctx))
429
0
        goto err;
430
431
0
    if (EC_GROUP_get_field_type(key->group) == NID_X9_62_prime_field) {
432
0
        if (BN_is_negative(x)
433
0
            || BN_cmp(x, key->group->field) >= 0
434
0
            || BN_is_negative(y)
435
0
            || BN_cmp(y, key->group->field) >= 0) {
436
0
            goto err;
437
0
        }
438
0
    } else {
439
0
        int m = EC_GROUP_get_degree(key->group);
440
0
        if (BN_num_bits(x) > m || BN_num_bits(y) > m) {
441
0
            goto err;
442
0
        }
443
0
    }
444
0
    ret = 1;
445
0
err:
446
0
    BN_CTX_end(ctx);
447
0
    return ret;
448
0
}
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
0
{
456
0
    if (eckey == NULL || eckey->group == NULL || eckey->pub_key == NULL) {
457
0
        ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
458
0
        return 0;
459
0
    }
460
461
    /* 5.6.2.3.3 (Step 1): Q != infinity */
462
0
    if (EC_POINT_is_at_infinity(eckey->group, eckey->pub_key)) {
463
0
        ERR_raise(ERR_LIB_EC, EC_R_POINT_AT_INFINITY);
464
0
        return 0;
465
0
    }
466
467
    /* 5.6.2.3.3 (Step 2) Test if the public key is in range */
468
0
    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
0
    if (EC_POINT_is_on_curve(eckey->group, eckey->pub_key, ctx) <= 0) {
475
0
        ERR_raise(ERR_LIB_EC, EC_R_POINT_IS_NOT_ON_CURVE);
476
0
        return 0;
477
0
    }
478
0
    return 1;
479
0
}
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
0
{
487
0
    int ret = 0;
488
0
    EC_POINT *point = NULL;
489
0
    const BIGNUM *order = NULL;
490
0
    const BIGNUM *cofactor = EC_GROUP_get0_cofactor(eckey->group);
491
492
0
    if (!ossl_ec_key_public_check_quick(eckey, ctx))
493
0
        return 0;
494
495
0
    if (cofactor != NULL && BN_is_one(cofactor)) {
496
        /* Skip the unnecessary expensive computation for curves with cofactor of 1. */
497
0
        return 1;
498
0
    }
499
500
0
    point = EC_POINT_new(eckey->group);
501
0
    if (point == NULL)
502
0
        return 0;
503
504
0
    order = eckey->group->order;
505
0
    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
0
    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
0
    if (!EC_POINT_is_at_infinity(eckey->group, point)) {
515
0
        ERR_raise(ERR_LIB_EC, EC_R_WRONG_ORDER);
516
0
        goto err;
517
0
    }
518
0
    ret = 1;
519
0
err:
520
0
    EC_POINT_free(point);
521
0
    return ret;
522
0
}
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
0
{
531
0
    if (eckey == NULL || eckey->group == NULL || eckey->priv_key == NULL) {
532
0
        ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
533
0
        return 0;
534
0
    }
535
0
    if (BN_cmp(eckey->priv_key, BN_value_one()) < 0
536
0
        || BN_cmp(eckey->priv_key, eckey->group->order) >= 0) {
537
0
        ERR_raise(ERR_LIB_EC, EC_R_INVALID_PRIVATE_KEY);
538
0
        return 0;
539
0
    }
540
0
    return 1;
541
0
}
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
0
{
550
0
    int ret = 0;
551
0
    EC_POINT *point = NULL;
552
553
0
    if (eckey == NULL
554
0
        || eckey->group == NULL
555
0
        || eckey->pub_key == NULL
556
0
        || eckey->priv_key == NULL) {
557
0
        ERR_raise(ERR_LIB_EC, ERR_R_PASSED_NULL_PARAMETER);
558
0
        return 0;
559
0
    }
560
561
0
    point = EC_POINT_new(eckey->group);
562
0
    if (point == NULL)
563
0
        goto err;
564
565
0
    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
0
    if (EC_POINT_cmp(eckey->group, point, eckey->pub_key, ctx) != 0) {
570
0
        ERR_raise(ERR_LIB_EC, EC_R_INVALID_PRIVATE_KEY);
571
0
        goto err;
572
0
    }
573
0
    ret = 1;
574
0
err:
575
0
    EC_POINT_free(point);
576
0
    return ret;
577
0
}
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
0
{
674
0
    return key->libctx;
675
0
}
676
677
const char *ossl_ec_key_get0_propq(const EC_KEY *key)
678
0
{
679
0
    return key->propq;
680
0
}
681
682
void ossl_ec_key_set0_libctx(EC_KEY *key, OSSL_LIB_CTX *libctx)
683
0
{
684
0
    key->libctx = libctx;
685
    /* Do we need to propagate this to the group? */
686
0
}
687
688
const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key)
689
0
{
690
0
    return key->group;
691
0
}
692
693
int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group)
694
0
{
695
0
    if (key->meth->set_group != NULL && key->meth->set_group(key, group) == 0)
696
0
        return 0;
697
0
    EC_GROUP_free(key->group);
698
0
    key->group = EC_GROUP_dup(group);
699
0
    if (key->group != NULL && EC_GROUP_get_curve_name(key->group) == NID_sm2)
700
0
        EC_KEY_set_flags(key, EC_FLAG_SM2_RANGE);
701
702
0
    key->dirty_cnt++;
703
0
    return (key->group == NULL) ? 0 : 1;
704
0
}
705
706
const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key)
707
0
{
708
0
    return key->priv_key;
709
0
}
710
711
int EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *priv_key)
712
0
{
713
0
    int fixed_top;
714
0
    const BIGNUM *order = NULL;
715
0
    BIGNUM *tmp_key = NULL;
716
717
0
    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
0
    order = EC_GROUP_get0_order(key->group);
729
0
    if (order == NULL || BN_is_zero(order))
730
0
        return 0; /* This should never happen */
731
732
0
    if (key->group->meth->set_private != NULL
733
0
        && key->group->meth->set_private(key, priv_key) == 0)
734
0
        return 0;
735
0
    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
0
    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
0
    tmp_key = BN_dup(priv_key);
788
0
    if (tmp_key == NULL)
789
0
        return 0;
790
791
0
    BN_set_flags(tmp_key, BN_FLG_CONSTTIME);
792
793
0
    fixed_top = bn_get_top(order) + 2;
794
0
    if (bn_wexpand(tmp_key, fixed_top) == NULL) {
795
0
        BN_clear_free(tmp_key);
796
0
        return 0;
797
0
    }
798
799
0
    BN_clear_free(key->priv_key);
800
0
    key->priv_key = tmp_key;
801
0
    key->dirty_cnt++;
802
803
0
    return 1;
804
0
}
805
806
const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key)
807
0
{
808
0
    return key->pub_key;
809
0
}
810
811
int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub_key)
812
0
{
813
0
    if (key->meth->set_public != NULL
814
0
        && key->meth->set_public(key, pub_key) == 0)
815
0
        return 0;
816
0
    EC_POINT_free(key->pub_key);
817
0
    key->pub_key = EC_POINT_dup(pub_key, key->group);
818
0
    key->dirty_cnt++;
819
0
    return (key->pub_key == NULL) ? 0 : 1;
820
0
}
821
822
unsigned int EC_KEY_get_enc_flags(const EC_KEY *key)
823
0
{
824
0
    return key->enc_flag;
825
0
}
826
827
void EC_KEY_set_enc_flags(EC_KEY *key, unsigned int flags)
828
0
{
829
0
    key->enc_flag = flags;
830
0
}
831
832
point_conversion_form_t EC_KEY_get_conv_form(const EC_KEY *key)
833
0
{
834
0
    return key->group != NULL
835
0
        ? EC_GROUP_get_point_conversion_form(key->group)
836
0
        : POINT_CONVERSION_UNCOMPRESSED;
837
0
}
838
839
void EC_KEY_set_conv_form(EC_KEY *key, point_conversion_form_t cform)
840
0
{
841
0
    if (key->group != NULL)
842
0
        EC_GROUP_set_point_conversion_form(key->group, cform);
843
0
}
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
0
{
862
0
    return key->flags;
863
0
}
864
865
void EC_KEY_set_flags(EC_KEY *key, int flags)
866
0
{
867
0
    key->flags |= flags;
868
0
    key->dirty_cnt++;
869
0
}
870
871
void EC_KEY_clear_flags(EC_KEY *key, int flags)
872
0
{
873
0
    key->flags &= ~flags;
874
0
    key->dirty_cnt++;
875
0
}
876
877
int EC_KEY_decoded_from_explicit_params(const EC_KEY *key)
878
0
{
879
0
    if (key == NULL || key->group == NULL)
880
0
        return -1;
881
0
    return key->group->decoded_from_explicit_params;
882
0
}
883
884
size_t EC_KEY_key2buf(const EC_KEY *key, point_conversion_form_t form,
885
    unsigned char **pbuf, BN_CTX *ctx)
886
0
{
887
0
    if (key == NULL || key->pub_key == NULL || key->group == NULL)
888
0
        return 0;
889
0
    return EC_POINT_point2buf(key->group, key->pub_key, form, pbuf, ctx);
890
0
}
891
892
int EC_KEY_oct2key(EC_KEY *key, const unsigned char *buf, size_t len,
893
    BN_CTX *ctx)
894
0
{
895
0
    if (key == NULL || key->group == NULL)
896
0
        return 0;
897
0
    if (key->pub_key == NULL)
898
0
        key->pub_key = EC_POINT_new(key->group);
899
0
    if (key->pub_key == NULL)
900
0
        return 0;
901
0
    if (EC_POINT_oct2point(key->group, key->pub_key, buf, len, ctx) == 0)
902
0
        return 0;
903
0
    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
0
    if ((key->group->meth->flags & EC_FLAGS_CUSTOM_CURVE) == 0) {
912
0
        EC_GROUP_set_point_conversion_form(key->group,
913
0
            (point_conversion_form_t)(buf[0] & ~0x01));
914
0
    }
915
0
    return 1;
916
0
}
917
918
size_t EC_KEY_priv2oct(const EC_KEY *eckey,
919
    unsigned char *buf, size_t len)
920
0
{
921
0
    if (eckey->group == NULL || eckey->group->meth == NULL)
922
0
        return 0;
923
0
    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
0
    return eckey->group->meth->priv2oct(eckey, buf, len);
929
0
}
930
931
size_t ossl_ec_key_simple_priv2oct(const EC_KEY *eckey,
932
    unsigned char *buf, size_t len)
933
0
{
934
0
    int buf_len;
935
936
0
    buf_len = (EC_GROUP_order_bits(eckey->group) + 7) / 8;
937
0
    if (eckey->priv_key == NULL)
938
0
        return 0;
939
0
    if (buf == NULL)
940
0
        return buf_len;
941
0
    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
0
    if (BN_bn2binpad(eckey->priv_key, buf, buf_len) == -1) {
947
0
        ERR_raise(ERR_LIB_EC, EC_R_BUFFER_TOO_SMALL);
948
0
        return 0;
949
0
    }
950
951
0
    return buf_len;
952
0
}
953
954
int EC_KEY_oct2priv(EC_KEY *eckey, const unsigned char *buf, size_t len)
955
0
{
956
0
    int ret;
957
958
0
    if (eckey->group == NULL || eckey->group->meth == NULL)
959
0
        return 0;
960
0
    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
0
    ret = eckey->group->meth->oct2priv(eckey, buf, len);
965
0
    if (ret == 1)
966
0
        eckey->dirty_cnt++;
967
0
    return ret;
968
0
}
969
970
int ossl_ec_key_simple_oct2priv(EC_KEY *eckey, const unsigned char *buf,
971
    size_t len)
972
0
{
973
0
    if (len > INT_MAX) {
974
0
        ERR_raise(ERR_LIB_EC, ERR_R_PASSED_INVALID_ARGUMENT);
975
0
        return 0;
976
0
    }
977
0
    if (eckey->priv_key == NULL)
978
0
        eckey->priv_key = BN_secure_new();
979
0
    if (eckey->priv_key == NULL) {
980
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
981
0
        return 0;
982
0
    }
983
0
    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
0
    eckey->dirty_cnt++;
988
0
    return 1;
989
0
}
990
991
size_t EC_KEY_priv2buf(const EC_KEY *eckey, unsigned char **pbuf)
992
0
{
993
0
    size_t len;
994
0
    unsigned char *buf;
995
996
0
    len = EC_KEY_priv2oct(eckey, NULL, 0);
997
0
    if (len == 0)
998
0
        return 0;
999
0
    if ((buf = OPENSSL_malloc(len)) == NULL)
1000
0
        return 0;
1001
0
    len = EC_KEY_priv2oct(eckey, buf, len);
1002
0
    if (len == 0) {
1003
0
        OPENSSL_free(buf);
1004
0
        return 0;
1005
0
    }
1006
0
    *pbuf = buf;
1007
0
    return len;
1008
0
}
1009
1010
int EC_KEY_can_sign(const EC_KEY *eckey)
1011
0
{
1012
0
    if (eckey->group == NULL || eckey->group->meth == NULL
1013
0
        || (eckey->group->meth->flags & EC_FLAGS_NO_SIGN))
1014
0
        return 0;
1015
0
    return 1;
1016
0
}
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
}