Coverage Report

Created: 2025-06-13 06:58

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