Coverage Report

Created: 2025-12-10 06:24

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