Coverage Report

Created: 2023-06-08 06:43

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