Coverage Report

Created: 2025-12-08 06:22

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