Coverage Report

Created: 2026-11-16 07:12

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