Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl30/crypto/ec/ec_mult.c
Line
Count
Source
1
/*
2
 * Copyright 2001-2021 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
 * ECDSA low level APIs are deprecated for public use, but still ok for
13
 * internal use.
14
 */
15
#include "internal/deprecated.h"
16
17
#include <string.h>
18
#include <openssl/err.h>
19
20
#include "internal/cryptlib.h"
21
#include "crypto/bn.h"
22
#include "ec_local.h"
23
#include "internal/refcount.h"
24
25
/*
26
 * This file implements the wNAF-based interleaving multi-exponentiation method
27
 * Formerly at:
28
 *   http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#multiexp
29
 * You might now find it here:
30
 *   http://link.springer.com/chapter/10.1007%2F3-540-45537-X_13
31
 *   http://www.bmoeller.de/pdf/TI-01-08.multiexp.pdf
32
 * For multiplication with precomputation, we use wNAF splitting, formerly at:
33
 *   http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#fastexp
34
 */
35
36
/* structure for precomputed multiples of the generator */
37
struct ec_pre_comp_st {
38
    const EC_GROUP *group; /* parent EC_GROUP object */
39
    size_t blocksize; /* block size for wNAF splitting */
40
    size_t numblocks; /* max. number of blocks for which we have
41
                       * precomputation */
42
    size_t w; /* window size */
43
    EC_POINT **points; /* array with pre-calculated multiples of
44
                        * generator: 'num' pointers to EC_POINT
45
                        * objects followed by a NULL */
46
    size_t num; /* numblocks * 2^(w-1) */
47
    CRYPTO_REF_COUNT references;
48
    CRYPTO_RWLOCK *lock;
49
};
50
51
static EC_PRE_COMP *ec_pre_comp_new(const EC_GROUP *group)
52
0
{
53
0
    EC_PRE_COMP *ret = NULL;
54
55
0
    if (!group)
56
0
        return NULL;
57
58
0
    ret = OPENSSL_zalloc(sizeof(*ret));
59
0
    if (ret == NULL) {
60
0
        ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
61
0
        return ret;
62
0
    }
63
64
0
    ret->group = group;
65
0
    ret->blocksize = 8; /* default */
66
0
    ret->w = 4; /* default */
67
0
    ret->references = 1;
68
69
0
    ret->lock = CRYPTO_THREAD_lock_new();
70
0
    if (ret->lock == NULL) {
71
0
        ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
72
0
        OPENSSL_free(ret);
73
0
        return NULL;
74
0
    }
75
0
    return ret;
76
0
}
77
78
EC_PRE_COMP *EC_ec_pre_comp_dup(EC_PRE_COMP *pre)
79
0
{
80
0
    int i;
81
0
    if (pre != NULL)
82
0
        CRYPTO_UP_REF(&pre->references, &i, pre->lock);
83
0
    return pre;
84
0
}
85
86
void EC_ec_pre_comp_free(EC_PRE_COMP *pre)
87
0
{
88
0
    int i;
89
90
0
    if (pre == NULL)
91
0
        return;
92
93
0
    CRYPTO_DOWN_REF(&pre->references, &i, pre->lock);
94
0
    REF_PRINT_COUNT("EC_ec", pre);
95
0
    if (i > 0)
96
0
        return;
97
0
    REF_ASSERT_ISNT(i < 0);
98
99
0
    if (pre->points != NULL) {
100
0
        EC_POINT **pts;
101
102
0
        for (pts = pre->points; *pts != NULL; pts++)
103
0
            EC_POINT_free(*pts);
104
0
        OPENSSL_free(pre->points);
105
0
    }
106
0
    CRYPTO_THREAD_lock_free(pre->lock);
107
0
    OPENSSL_free(pre);
108
0
}
109
110
#define EC_POINT_BN_set_flags(P, flags) \
111
50.3k
    do {                                \
112
50.3k
        BN_set_flags((P)->X, (flags));  \
113
50.3k
        BN_set_flags((P)->Y, (flags));  \
114
50.3k
        BN_set_flags((P)->Z, (flags));  \
115
50.3k
    } while (0)
116
117
/*-
118
 * This functions computes a single point multiplication over the EC group,
119
 * using, at a high level, a Montgomery ladder with conditional swaps, with
120
 * various timing attack defenses.
121
 *
122
 * It performs either a fixed point multiplication
123
 *          (scalar * generator)
124
 * when point is NULL, or a variable point multiplication
125
 *          (scalar * point)
126
 * when point is not NULL.
127
 *
128
 * `scalar` cannot be NULL and should be in the range [0,n) otherwise all
129
 * constant time bets are off (where n is the cardinality of the EC group).
130
 *
131
 * This function expects `group->order` and `group->cardinality` to be well
132
 * defined and non-zero: it fails with an error code otherwise.
133
 *
134
 * NB: This says nothing about the constant-timeness of the ladder step
135
 * implementation (i.e., the default implementation is based on EC_POINT_add and
136
 * EC_POINT_dbl, which of course are not constant time themselves) or the
137
 * underlying multiprecision arithmetic.
138
 *
139
 * The product is stored in `r`.
140
 *
141
 * This is an internal function: callers are in charge of ensuring that the
142
 * input parameters `group`, `r`, `scalar` and `ctx` are not NULL.
143
 *
144
 * Returns 1 on success, 0 otherwise.
145
 */
146
int ossl_ec_scalar_mul_ladder(const EC_GROUP *group, EC_POINT *r,
147
    const BIGNUM *scalar, const EC_POINT *point,
148
    BN_CTX *ctx)
149
16.7k
{
150
16.7k
    int i, cardinality_bits, group_top, kbit, pbit, Z_is_one;
151
16.7k
    EC_POINT *p = NULL;
152
16.7k
    EC_POINT *s = NULL;
153
16.7k
    BIGNUM *k = NULL;
154
16.7k
    BIGNUM *lambda = NULL;
155
16.7k
    BIGNUM *cardinality = NULL;
156
16.7k
    int ret = 0;
157
158
    /* early exit if the input point is the point at infinity */
159
16.7k
    if (point != NULL && EC_POINT_is_at_infinity(group, point))
160
0
        return EC_POINT_set_to_infinity(group, r);
161
162
16.7k
    if (BN_is_zero(group->order)) {
163
0
        ERR_raise(ERR_LIB_EC, EC_R_UNKNOWN_ORDER);
164
0
        return 0;
165
0
    }
166
16.7k
    if (BN_is_zero(group->cofactor)) {
167
0
        ERR_raise(ERR_LIB_EC, EC_R_UNKNOWN_COFACTOR);
168
0
        return 0;
169
0
    }
170
171
16.7k
    BN_CTX_start(ctx);
172
173
16.7k
    if (((p = EC_POINT_new(group)) == NULL)
174
16.7k
        || ((s = EC_POINT_new(group)) == NULL)) {
175
0
        ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
176
0
        goto err;
177
0
    }
178
179
16.7k
    if (point == NULL) {
180
13.7k
        if (!EC_POINT_copy(p, group->generator)) {
181
0
            ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
182
0
            goto err;
183
0
        }
184
13.7k
    } else {
185
3.06k
        if (!EC_POINT_copy(p, point)) {
186
0
            ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
187
0
            goto err;
188
0
        }
189
3.06k
    }
190
191
16.7k
    EC_POINT_BN_set_flags(p, BN_FLG_CONSTTIME);
192
16.7k
    EC_POINT_BN_set_flags(r, BN_FLG_CONSTTIME);
193
16.7k
    EC_POINT_BN_set_flags(s, BN_FLG_CONSTTIME);
194
195
16.7k
    cardinality = BN_CTX_get(ctx);
196
16.7k
    lambda = BN_CTX_get(ctx);
197
16.7k
    k = BN_CTX_get(ctx);
198
16.7k
    if (k == NULL) {
199
0
        ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
200
0
        goto err;
201
0
    }
202
203
16.7k
    if (!BN_mul(cardinality, group->order, group->cofactor, ctx)) {
204
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
205
0
        goto err;
206
0
    }
207
208
    /*
209
     * Group cardinalities are often on a word boundary.
210
     * So when we pad the scalar, some timing diff might
211
     * pop if it needs to be expanded due to carries.
212
     * So expand ahead of time.
213
     */
214
16.7k
    cardinality_bits = BN_num_bits(cardinality);
215
16.7k
    group_top = bn_get_top(cardinality);
216
16.7k
    if ((bn_wexpand(k, group_top + 2) == NULL)
217
16.7k
        || (bn_wexpand(lambda, group_top + 2) == NULL)) {
218
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
219
0
        goto err;
220
0
    }
221
222
16.7k
    if (!BN_copy(k, scalar)) {
223
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
224
0
        goto err;
225
0
    }
226
227
16.7k
    BN_set_flags(k, BN_FLG_CONSTTIME);
228
229
16.7k
    if ((BN_num_bits(k) > cardinality_bits) || (BN_is_negative(k))) {
230
        /*-
231
         * this is an unusual input, and we don't guarantee
232
         * constant-timeness
233
         */
234
3.28k
        if (!BN_nnmod(k, k, cardinality, ctx)) {
235
0
            ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
236
0
            goto err;
237
0
        }
238
3.28k
    }
239
240
16.7k
    if (!BN_add(lambda, k, cardinality)) {
241
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
242
0
        goto err;
243
0
    }
244
16.7k
    BN_set_flags(lambda, BN_FLG_CONSTTIME);
245
16.7k
    if (!BN_add(k, lambda, cardinality)) {
246
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
247
0
        goto err;
248
0
    }
249
    /*
250
     * lambda := scalar + cardinality
251
     * k := scalar + 2*cardinality
252
     */
253
16.7k
    kbit = BN_is_bit_set(lambda, cardinality_bits);
254
16.7k
    BN_consttime_swap(kbit, k, lambda, group_top + 2);
255
256
16.7k
    group_top = bn_get_top(group->field);
257
16.7k
    if ((bn_wexpand(s->X, group_top) == NULL)
258
16.7k
        || (bn_wexpand(s->Y, group_top) == NULL)
259
16.7k
        || (bn_wexpand(s->Z, group_top) == NULL)
260
16.7k
        || (bn_wexpand(r->X, group_top) == NULL)
261
16.7k
        || (bn_wexpand(r->Y, group_top) == NULL)
262
16.7k
        || (bn_wexpand(r->Z, group_top) == NULL)
263
16.7k
        || (bn_wexpand(p->X, group_top) == NULL)
264
16.7k
        || (bn_wexpand(p->Y, group_top) == NULL)
265
16.7k
        || (bn_wexpand(p->Z, group_top) == NULL)) {
266
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
267
0
        goto err;
268
0
    }
269
270
    /* ensure input point is in affine coords for ladder step efficiency */
271
16.7k
    if (!p->Z_is_one && (group->meth->make_affine == NULL || !group->meth->make_affine(group, p, ctx))) {
272
0
        ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
273
0
        goto err;
274
0
    }
275
276
    /* Initialize the Montgomery ladder */
277
16.7k
    if (!ec_point_ladder_pre(group, r, s, p, ctx)) {
278
0
        ERR_raise(ERR_LIB_EC, EC_R_LADDER_PRE_FAILURE);
279
0
        goto err;
280
0
    }
281
282
    /* top bit is a 1, in a fixed pos */
283
16.7k
    pbit = 1;
284
285
16.7k
#define EC_POINT_CSWAP(c, a, b, w, t)              \
286
4.94M
    do {                                           \
287
4.94M
        BN_consttime_swap(c, (a)->X, (b)->X, w);   \
288
4.94M
        BN_consttime_swap(c, (a)->Y, (b)->Y, w);   \
289
4.94M
        BN_consttime_swap(c, (a)->Z, (b)->Z, w);   \
290
4.94M
        t = ((a)->Z_is_one ^ (b)->Z_is_one) & (c); \
291
4.94M
        (a)->Z_is_one ^= (t);                      \
292
4.94M
        (b)->Z_is_one ^= (t);                      \
293
4.94M
    } while (0)
294
295
    /*-
296
     * The ladder step, with branches, is
297
     *
298
     * k[i] == 0: S = add(R, S), R = dbl(R)
299
     * k[i] == 1: R = add(S, R), S = dbl(S)
300
     *
301
     * Swapping R, S conditionally on k[i] leaves you with state
302
     *
303
     * k[i] == 0: T, U = R, S
304
     * k[i] == 1: T, U = S, R
305
     *
306
     * Then perform the ECC ops.
307
     *
308
     * U = add(T, U)
309
     * T = dbl(T)
310
     *
311
     * Which leaves you with state
312
     *
313
     * k[i] == 0: U = add(R, S), T = dbl(R)
314
     * k[i] == 1: U = add(S, R), T = dbl(S)
315
     *
316
     * Swapping T, U conditionally on k[i] leaves you with state
317
     *
318
     * k[i] == 0: R, S = T, U
319
     * k[i] == 1: R, S = U, T
320
     *
321
     * Which leaves you with state
322
     *
323
     * k[i] == 0: S = add(R, S), R = dbl(R)
324
     * k[i] == 1: R = add(S, R), S = dbl(S)
325
     *
326
     * So we get the same logic, but instead of a branch it's a
327
     * conditional swap, followed by ECC ops, then another conditional swap.
328
     *
329
     * Optimization: The end of iteration i and start of i-1 looks like
330
     *
331
     * ...
332
     * CSWAP(k[i], R, S)
333
     * ECC
334
     * CSWAP(k[i], R, S)
335
     * (next iteration)
336
     * CSWAP(k[i-1], R, S)
337
     * ECC
338
     * CSWAP(k[i-1], R, S)
339
     * ...
340
     *
341
     * So instead of two contiguous swaps, you can merge the condition
342
     * bits and do a single swap.
343
     *
344
     * k[i]   k[i-1]    Outcome
345
     * 0      0         No Swap
346
     * 0      1         Swap
347
     * 1      0         Swap
348
     * 1      1         No Swap
349
     *
350
     * This is XOR. pbit tracks the previous bit of k.
351
     */
352
353
4.94M
    for (i = cardinality_bits - 1; i >= 0; i--) {
354
4.92M
        kbit = BN_is_bit_set(k, i) ^ pbit;
355
4.92M
        EC_POINT_CSWAP(kbit, r, s, group_top, Z_is_one);
356
357
        /* Perform a single step of the Montgomery ladder */
358
4.92M
        if (!ec_point_ladder_step(group, r, s, p, ctx)) {
359
0
            ERR_raise(ERR_LIB_EC, EC_R_LADDER_STEP_FAILURE);
360
0
            goto err;
361
0
        }
362
        /*
363
         * pbit logic merges this cswap with that of the
364
         * next iteration
365
         */
366
4.92M
        pbit ^= kbit;
367
4.92M
    }
368
    /* one final cswap to move the right value into r */
369
16.7k
    EC_POINT_CSWAP(pbit, r, s, group_top, Z_is_one);
370
16.7k
#undef EC_POINT_CSWAP
371
372
    /* Finalize ladder (and recover full point coordinates) */
373
16.7k
    if (!ec_point_ladder_post(group, r, s, p, ctx)) {
374
0
        ERR_raise(ERR_LIB_EC, EC_R_LADDER_POST_FAILURE);
375
0
        goto err;
376
0
    }
377
378
16.7k
    ret = 1;
379
380
16.7k
err:
381
16.7k
    EC_POINT_free(p);
382
16.7k
    EC_POINT_clear_free(s);
383
16.7k
    BN_CTX_end(ctx);
384
385
16.7k
    return ret;
386
16.7k
}
387
388
#undef EC_POINT_BN_set_flags
389
390
/*
391
 * Table could be optimised for the wNAF-based implementation,
392
 * sometimes smaller windows will give better performance (thus the
393
 * boundaries should be increased)
394
 */
395
#define EC_window_bits_for_scalar_size(b)      \
396
3.73k
    ((size_t)((b) >= 2000 ? 6 : (b) >= 800 ? 5 \
397
3.70k
            : (b) >= 300                   ? 4 \
398
3.61k
            : (b) >= 70                    ? 3 \
399
3.11k
            : (b) >= 20                    ? 2 \
400
1.54k
                                           : 1))
401
402
/*-
403
 * Compute
404
 *      \sum scalars[i]*points[i],
405
 * also including
406
 *      scalar*generator
407
 * in the addition if scalar != NULL
408
 */
409
int ossl_ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
410
    size_t num, const EC_POINT *points[],
411
    const BIGNUM *scalars[], BN_CTX *ctx)
412
7.87k
{
413
7.87k
    const EC_POINT *generator = NULL;
414
7.87k
    EC_POINT *tmp = NULL;
415
7.87k
    size_t totalnum;
416
7.87k
    size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */
417
7.87k
    size_t pre_points_per_block = 0;
418
7.87k
    size_t i, j;
419
7.87k
    int k;
420
7.87k
    int r_is_inverted = 0;
421
7.87k
    int r_is_at_infinity = 1;
422
7.87k
    size_t *wsize = NULL; /* individual window sizes */
423
7.87k
    signed char **wNAF = NULL; /* individual wNAFs */
424
7.87k
    size_t *wNAF_len = NULL;
425
7.87k
    size_t max_len = 0;
426
7.87k
    size_t num_val;
427
7.87k
    EC_POINT **val = NULL; /* precomputation */
428
7.87k
    EC_POINT **v;
429
7.87k
    EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' or
430
                                 * 'pre_comp->points' */
431
7.87k
    const EC_PRE_COMP *pre_comp = NULL;
432
7.87k
    int num_scalar = 0; /* flag: will be set to 1 if 'scalar' must be
433
                         * treated like other scalars, i.e.
434
                         * precomputation is not available */
435
7.87k
    int ret = 0;
436
437
7.87k
    if (!BN_is_zero(group->order) && !BN_is_zero(group->cofactor)) {
438
        /*-
439
         * Handle the common cases where the scalar is secret, enforcing a
440
         * scalar multiplication implementation based on a Montgomery ladder,
441
         * with various timing attack defenses.
442
         */
443
6.03k
        if ((scalar != group->order) && (scalar != NULL) && (num == 0)) {
444
            /*-
445
             * In this case we want to compute scalar * GeneratorPoint: this
446
             * codepath is reached most prominently by (ephemeral) key
447
             * generation of EC cryptosystems (i.e. ECDSA keygen and sign setup,
448
             * ECDH keygen/first half), where the scalar is always secret. This
449
             * is why we ignore if BN_FLG_CONSTTIME is actually set and we
450
             * always call the ladder version.
451
             */
452
3.96k
            return ossl_ec_scalar_mul_ladder(group, r, scalar, NULL, ctx);
453
3.96k
        }
454
2.07k
        if ((scalar == NULL) && (num == 1) && (scalars[0] != group->order)) {
455
            /*-
456
             * In this case we want to compute scalar * VariablePoint: this
457
             * codepath is reached most prominently by the second half of ECDH,
458
             * where the secret scalar is multiplied by the peer's public point.
459
             * To protect the secret scalar, we ignore if BN_FLG_CONSTTIME is
460
             * actually set and we always call the ladder version.
461
             */
462
266
            return ossl_ec_scalar_mul_ladder(group, r, scalars[0], points[0],
463
266
                ctx);
464
266
        }
465
2.07k
    }
466
467
3.64k
    if (scalar != NULL) {
468
2.37k
        generator = EC_GROUP_get0_generator(group);
469
2.37k
        if (generator == NULL) {
470
0
            ERR_raise(ERR_LIB_EC, EC_R_UNDEFINED_GENERATOR);
471
0
            goto err;
472
0
        }
473
474
        /* look if we can use precomputed multiples of generator */
475
476
2.37k
        pre_comp = group->pre_comp.ec;
477
2.37k
        if (pre_comp && pre_comp->numblocks
478
0
            && (EC_POINT_cmp(group, generator, pre_comp->points[0], ctx) == 0)) {
479
0
            blocksize = pre_comp->blocksize;
480
481
            /*
482
             * determine maximum number of blocks that wNAF splitting may
483
             * yield (NB: maximum wNAF length is bit length plus one)
484
             */
485
0
            numblocks = (BN_num_bits(scalar) / blocksize) + 1;
486
487
            /*
488
             * we cannot use more blocks than we have precomputation for
489
             */
490
0
            if (numblocks > pre_comp->numblocks)
491
0
                numblocks = pre_comp->numblocks;
492
493
0
            pre_points_per_block = (size_t)1 << (pre_comp->w - 1);
494
495
            /* check that pre_comp looks sane */
496
0
            if (pre_comp->num != (pre_comp->numblocks * pre_points_per_block)) {
497
0
                ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
498
0
                goto err;
499
0
            }
500
2.37k
        } else {
501
            /* can't use precomputation */
502
2.37k
            pre_comp = NULL;
503
2.37k
            numblocks = 1;
504
2.37k
            num_scalar = 1; /* treat 'scalar' like 'num'-th element of
505
                             * 'scalars' */
506
2.37k
        }
507
2.37k
    }
508
509
3.64k
    totalnum = num + numblocks;
510
511
3.64k
    wsize = OPENSSL_malloc(totalnum * sizeof(wsize[0]));
512
3.64k
    wNAF_len = OPENSSL_malloc(totalnum * sizeof(wNAF_len[0]));
513
    /* include space for pivot */
514
3.64k
    wNAF = OPENSSL_malloc((totalnum + 1) * sizeof(wNAF[0]));
515
3.64k
    val_sub = OPENSSL_malloc(totalnum * sizeof(val_sub[0]));
516
517
    /* Ensure wNAF is initialised in case we end up going to err */
518
3.64k
    if (wNAF != NULL)
519
3.64k
        wNAF[0] = NULL; /* preliminary pivot */
520
521
3.64k
    if (wsize == NULL || wNAF_len == NULL || wNAF == NULL || val_sub == NULL) {
522
0
        ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
523
0
        goto err;
524
0
    }
525
526
    /*
527
     * num_val will be the total number of temporarily precomputed points
528
     */
529
3.64k
    num_val = 0;
530
531
7.38k
    for (i = 0; i < num + num_scalar; i++) {
532
3.73k
        size_t bits;
533
534
3.73k
        bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
535
3.73k
        wsize[i] = EC_window_bits_for_scalar_size(bits);
536
3.73k
        num_val += (size_t)1 << (wsize[i] - 1);
537
3.73k
        wNAF[i + 1] = NULL; /* make sure we always have a pivot */
538
3.73k
        wNAF[i] = bn_compute_wNAF((i < num ? scalars[i] : scalar), wsize[i],
539
3.73k
            &wNAF_len[i]);
540
3.73k
        if (wNAF[i] == NULL)
541
0
            goto err;
542
3.73k
        if (wNAF_len[i] > max_len)
543
3.70k
            max_len = wNAF_len[i];
544
3.73k
    }
545
546
3.64k
    if (numblocks) {
547
        /* we go here iff scalar != NULL */
548
549
2.37k
        if (pre_comp == NULL) {
550
2.37k
            if (num_scalar != 1) {
551
0
                ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
552
0
                goto err;
553
0
            }
554
            /* we have already generated a wNAF for 'scalar' */
555
2.37k
        } else {
556
0
            signed char *tmp_wNAF = NULL;
557
0
            size_t tmp_len = 0;
558
559
0
            if (num_scalar != 0) {
560
0
                ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
561
0
                goto err;
562
0
            }
563
564
            /*
565
             * use the window size for which we have precomputation
566
             */
567
0
            wsize[num] = pre_comp->w;
568
0
            tmp_wNAF = bn_compute_wNAF(scalar, wsize[num], &tmp_len);
569
0
            if (!tmp_wNAF)
570
0
                goto err;
571
572
0
            if (tmp_len <= max_len) {
573
                /*
574
                 * One of the other wNAFs is at least as long as the wNAF
575
                 * belonging to the generator, so wNAF splitting will not buy
576
                 * us anything.
577
                 */
578
579
0
                numblocks = 1;
580
0
                totalnum = num + 1; /* don't use wNAF splitting */
581
0
                wNAF[num] = tmp_wNAF;
582
0
                wNAF[num + 1] = NULL;
583
0
                wNAF_len[num] = tmp_len;
584
                /*
585
                 * pre_comp->points starts with the points that we need here:
586
                 */
587
0
                val_sub[num] = pre_comp->points;
588
0
            } else {
589
                /*
590
                 * don't include tmp_wNAF directly into wNAF array - use wNAF
591
                 * splitting and include the blocks
592
                 */
593
594
0
                signed char *pp;
595
0
                EC_POINT **tmp_points;
596
597
0
                if (tmp_len < numblocks * blocksize) {
598
                    /*
599
                     * possibly we can do with fewer blocks than estimated
600
                     */
601
0
                    numblocks = (tmp_len + blocksize - 1) / blocksize;
602
0
                    if (numblocks > pre_comp->numblocks) {
603
0
                        ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
604
0
                        OPENSSL_free(tmp_wNAF);
605
0
                        goto err;
606
0
                    }
607
0
                    totalnum = num + numblocks;
608
0
                }
609
610
                /* split wNAF in 'numblocks' parts */
611
0
                pp = tmp_wNAF;
612
0
                tmp_points = pre_comp->points;
613
614
0
                for (i = num; i < totalnum; i++) {
615
0
                    if (i < totalnum - 1) {
616
0
                        wNAF_len[i] = blocksize;
617
0
                        if (tmp_len < blocksize) {
618
0
                            ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
619
0
                            OPENSSL_free(tmp_wNAF);
620
0
                            goto err;
621
0
                        }
622
0
                        tmp_len -= blocksize;
623
0
                    } else
624
                        /*
625
                         * last block gets whatever is left (this could be
626
                         * more or less than 'blocksize'!)
627
                         */
628
0
                        wNAF_len[i] = tmp_len;
629
630
0
                    wNAF[i + 1] = NULL;
631
0
                    wNAF[i] = OPENSSL_malloc(wNAF_len[i]);
632
0
                    if (wNAF[i] == NULL) {
633
0
                        ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
634
0
                        OPENSSL_free(tmp_wNAF);
635
0
                        goto err;
636
0
                    }
637
0
                    memcpy(wNAF[i], pp, wNAF_len[i]);
638
0
                    if (wNAF_len[i] > max_len)
639
0
                        max_len = wNAF_len[i];
640
641
0
                    if (*tmp_points == NULL) {
642
0
                        ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
643
0
                        OPENSSL_free(tmp_wNAF);
644
0
                        goto err;
645
0
                    }
646
0
                    val_sub[i] = tmp_points;
647
0
                    tmp_points += pre_points_per_block;
648
0
                    pp += blocksize;
649
0
                }
650
0
                OPENSSL_free(tmp_wNAF);
651
0
            }
652
0
        }
653
2.37k
    }
654
655
    /*
656
     * All points we precompute now go into a single array 'val'.
657
     * 'val_sub[i]' is a pointer to the subarray for the i-th point, or to a
658
     * subarray of 'pre_comp->points' if we already have precomputation.
659
     */
660
3.64k
    val = OPENSSL_malloc((num_val + 1) * sizeof(val[0]));
661
3.64k
    if (val == NULL) {
662
0
        ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
663
0
        goto err;
664
0
    }
665
3.64k
    val[num_val] = NULL; /* pivot element */
666
667
    /* allocate points for precomputation */
668
3.64k
    v = val;
669
7.38k
    for (i = 0; i < num + num_scalar; i++) {
670
3.73k
        val_sub[i] = v;
671
18.5k
        for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) {
672
14.8k
            *v = EC_POINT_new(group);
673
14.8k
            if (*v == NULL)
674
0
                goto err;
675
14.8k
            v++;
676
14.8k
        }
677
3.73k
    }
678
3.64k
    if (!(v == val + num_val)) {
679
0
        ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
680
0
        goto err;
681
0
    }
682
683
3.64k
    if ((tmp = EC_POINT_new(group)) == NULL)
684
0
        goto err;
685
686
    /*-
687
     * prepare precomputed values:
688
     *    val_sub[i][0] :=     points[i]
689
     *    val_sub[i][1] := 3 * points[i]
690
     *    val_sub[i][2] := 5 * points[i]
691
     *    ...
692
     */
693
7.38k
    for (i = 0; i < num + num_scalar; i++) {
694
3.73k
        if (i < num) {
695
1.36k
            if (!EC_POINT_copy(val_sub[i][0], points[i]))
696
0
                goto err;
697
2.37k
        } else {
698
2.37k
            if (!EC_POINT_copy(val_sub[i][0], generator))
699
0
                goto err;
700
2.37k
        }
701
702
3.73k
        if (wsize[i] > 1) {
703
2.76k
            if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx))
704
0
                goto err;
705
13.8k
            for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) {
706
11.0k
                if (!EC_POINT_add(group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx))
707
0
                    goto err;
708
11.0k
            }
709
2.76k
        }
710
3.73k
    }
711
712
3.64k
    if (group->meth->points_make_affine == NULL
713
3.64k
        || !group->meth->points_make_affine(group, num_val, val, ctx))
714
0
        goto err;
715
716
3.64k
    r_is_at_infinity = 1;
717
718
631k
    for (k = max_len - 1; k >= 0; k--) {
719
627k
        if (!r_is_at_infinity) {
720
624k
            if (!EC_POINT_dbl(group, r, r, ctx))
721
0
                goto err;
722
624k
        }
723
724
1.28M
        for (i = 0; i < totalnum; i++) {
725
656k
            if (wNAF_len[i] > (size_t)k) {
726
646k
                int digit = wNAF[i][k];
727
646k
                int is_neg;
728
729
646k
                if (digit) {
730
82.6k
                    is_neg = digit < 0;
731
732
82.6k
                    if (is_neg)
733
38.0k
                        digit = -digit;
734
735
82.6k
                    if (is_neg != r_is_inverted) {
736
37.7k
                        if (!r_is_at_infinity) {
737
37.7k
                            if (!EC_POINT_invert(group, r, ctx))
738
0
                                goto err;
739
37.7k
                        }
740
37.7k
                        r_is_inverted = !r_is_inverted;
741
37.7k
                    }
742
743
                    /* digit > 0 */
744
745
82.6k
                    if (r_is_at_infinity) {
746
3.59k
                        if (!EC_POINT_copy(r, val_sub[i][digit >> 1]))
747
0
                            goto err;
748
749
                        /*-
750
                         * Apply coordinate blinding for EC_POINT.
751
                         *
752
                         * The underlying EC_METHOD can optionally implement this function:
753
                         * ossl_ec_point_blind_coordinates() returns 0 in case of errors or 1 on
754
                         * success or if coordinate blinding is not implemented for this
755
                         * group.
756
                         */
757
3.59k
                        if (!ossl_ec_point_blind_coordinates(group, r, ctx)) {
758
0
                            ERR_raise(ERR_LIB_EC, EC_R_POINT_COORDINATES_BLIND_FAILURE);
759
0
                            goto err;
760
0
                        }
761
762
3.59k
                        r_is_at_infinity = 0;
763
79.0k
                    } else {
764
79.0k
                        if (!EC_POINT_add(group, r, r, val_sub[i][digit >> 1], ctx))
765
0
                            goto err;
766
79.0k
                    }
767
82.6k
                }
768
646k
            }
769
656k
        }
770
627k
    }
771
772
3.64k
    if (r_is_at_infinity) {
773
56
        if (!EC_POINT_set_to_infinity(group, r))
774
0
            goto err;
775
3.59k
    } else {
776
3.59k
        if (r_is_inverted)
777
1.68k
            if (!EC_POINT_invert(group, r, ctx))
778
0
                goto err;
779
3.59k
    }
780
781
3.64k
    ret = 1;
782
783
3.64k
err:
784
3.64k
    EC_POINT_free(tmp);
785
3.64k
    OPENSSL_free(wsize);
786
3.64k
    OPENSSL_free(wNAF_len);
787
3.64k
    if (wNAF != NULL) {
788
3.64k
        signed char **w;
789
790
7.38k
        for (w = wNAF; *w != NULL; w++)
791
3.73k
            OPENSSL_free(*w);
792
793
3.64k
        OPENSSL_free(wNAF);
794
3.64k
    }
795
3.64k
    if (val != NULL) {
796
18.4k
        for (v = val; *v != NULL; v++)
797
14.8k
            EC_POINT_clear_free(*v);
798
799
3.64k
        OPENSSL_free(val);
800
3.64k
    }
801
3.64k
    OPENSSL_free(val_sub);
802
3.64k
    return ret;
803
3.64k
}
804
805
/*-
806
 * ossl_ec_wNAF_precompute_mult()
807
 * creates an EC_PRE_COMP object with preprecomputed multiples of the generator
808
 * for use with wNAF splitting as implemented in ossl_ec_wNAF_mul().
809
 *
810
 * 'pre_comp->points' is an array of multiples of the generator
811
 * of the following form:
812
 * points[0] =     generator;
813
 * points[1] = 3 * generator;
814
 * ...
815
 * points[2^(w-1)-1] =     (2^(w-1)-1) * generator;
816
 * points[2^(w-1)]   =     2^blocksize * generator;
817
 * points[2^(w-1)+1] = 3 * 2^blocksize * generator;
818
 * ...
819
 * points[2^(w-1)*(numblocks-1)-1] = (2^(w-1)) *  2^(blocksize*(numblocks-2)) * generator
820
 * points[2^(w-1)*(numblocks-1)]   =              2^(blocksize*(numblocks-1)) * generator
821
 * ...
822
 * points[2^(w-1)*numblocks-1]     = (2^(w-1)) *  2^(blocksize*(numblocks-1)) * generator
823
 * points[2^(w-1)*numblocks]       = NULL
824
 */
825
int ossl_ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
826
0
{
827
0
    const EC_POINT *generator;
828
0
    EC_POINT *tmp_point = NULL, *base = NULL, **var;
829
0
    const BIGNUM *order;
830
0
    size_t i, bits, w, pre_points_per_block, blocksize, numblocks, num;
831
0
    EC_POINT **points = NULL;
832
0
    EC_PRE_COMP *pre_comp;
833
0
    int ret = 0;
834
0
    int used_ctx = 0;
835
0
#ifndef FIPS_MODULE
836
0
    BN_CTX *new_ctx = NULL;
837
0
#endif
838
839
    /* if there is an old EC_PRE_COMP object, throw it away */
840
0
    EC_pre_comp_free(group);
841
0
    if ((pre_comp = ec_pre_comp_new(group)) == NULL)
842
0
        return 0;
843
844
0
    generator = EC_GROUP_get0_generator(group);
845
0
    if (generator == NULL) {
846
0
        ERR_raise(ERR_LIB_EC, EC_R_UNDEFINED_GENERATOR);
847
0
        goto err;
848
0
    }
849
850
0
#ifndef FIPS_MODULE
851
0
    if (ctx == NULL)
852
0
        ctx = new_ctx = BN_CTX_new();
853
0
#endif
854
0
    if (ctx == NULL)
855
0
        goto err;
856
857
0
    BN_CTX_start(ctx);
858
0
    used_ctx = 1;
859
860
0
    order = EC_GROUP_get0_order(group);
861
0
    if (order == NULL)
862
0
        goto err;
863
0
    if (BN_is_zero(order)) {
864
0
        ERR_raise(ERR_LIB_EC, EC_R_UNKNOWN_ORDER);
865
0
        goto err;
866
0
    }
867
868
0
    bits = BN_num_bits(order);
869
    /*
870
     * The following parameters mean we precompute (approximately) one point
871
     * per bit. TBD: The combination 8, 4 is perfect for 160 bits; for other
872
     * bit lengths, other parameter combinations might provide better
873
     * efficiency.
874
     */
875
0
    blocksize = 8;
876
0
    w = 4;
877
0
    if (EC_window_bits_for_scalar_size(bits) > w) {
878
        /* let's not make the window too small ... */
879
0
        w = EC_window_bits_for_scalar_size(bits);
880
0
    }
881
882
0
    numblocks = (bits + blocksize - 1) / blocksize; /* max. number of blocks
883
                                                     * to use for wNAF
884
                                                     * splitting */
885
886
0
    pre_points_per_block = (size_t)1 << (w - 1);
887
0
    num = pre_points_per_block * numblocks; /* number of points to compute
888
                                             * and store */
889
890
0
    points = OPENSSL_malloc(sizeof(*points) * (num + 1));
891
0
    if (points == NULL) {
892
0
        ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
893
0
        goto err;
894
0
    }
895
896
0
    var = points;
897
0
    var[num] = NULL; /* pivot */
898
0
    for (i = 0; i < num; i++) {
899
0
        if ((var[i] = EC_POINT_new(group)) == NULL) {
900
0
            ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
901
0
            goto err;
902
0
        }
903
0
    }
904
905
0
    if ((tmp_point = EC_POINT_new(group)) == NULL
906
0
        || (base = EC_POINT_new(group)) == NULL) {
907
0
        ERR_raise(ERR_LIB_EC, ERR_R_MALLOC_FAILURE);
908
0
        goto err;
909
0
    }
910
911
0
    if (!EC_POINT_copy(base, generator))
912
0
        goto err;
913
914
    /* do the precomputation */
915
0
    for (i = 0; i < numblocks; i++) {
916
0
        size_t j;
917
918
0
        if (!EC_POINT_dbl(group, tmp_point, base, ctx))
919
0
            goto err;
920
921
0
        if (!EC_POINT_copy(*var++, base))
922
0
            goto err;
923
924
0
        for (j = 1; j < pre_points_per_block; j++, var++) {
925
            /*
926
             * calculate odd multiples of the current base point
927
             */
928
0
            if (!EC_POINT_add(group, *var, tmp_point, *(var - 1), ctx))
929
0
                goto err;
930
0
        }
931
932
0
        if (i < numblocks - 1) {
933
            /*
934
             * get the next base (multiply current one by 2^blocksize)
935
             */
936
0
            size_t k;
937
938
0
            if (blocksize <= 2) {
939
0
                ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
940
0
                goto err;
941
0
            }
942
943
0
            if (!EC_POINT_dbl(group, base, tmp_point, ctx))
944
0
                goto err;
945
0
            for (k = 2; k < blocksize; k++) {
946
0
                if (!EC_POINT_dbl(group, base, base, ctx))
947
0
                    goto err;
948
0
            }
949
0
        }
950
0
    }
951
952
0
    if (group->meth->points_make_affine == NULL
953
0
        || !group->meth->points_make_affine(group, num, points, ctx))
954
0
        goto err;
955
956
0
    pre_comp->group = group;
957
0
    pre_comp->blocksize = blocksize;
958
0
    pre_comp->numblocks = numblocks;
959
0
    pre_comp->w = w;
960
0
    pre_comp->points = points;
961
0
    points = NULL;
962
0
    pre_comp->num = num;
963
0
    SETPRECOMP(group, ec, pre_comp);
964
0
    pre_comp = NULL;
965
0
    ret = 1;
966
967
0
err:
968
0
    if (used_ctx)
969
0
        BN_CTX_end(ctx);
970
0
#ifndef FIPS_MODULE
971
0
    BN_CTX_free(new_ctx);
972
0
#endif
973
0
    EC_ec_pre_comp_free(pre_comp);
974
0
    if (points) {
975
0
        EC_POINT **p;
976
977
0
        for (p = points; *p != NULL; p++)
978
0
            EC_POINT_free(*p);
979
0
        OPENSSL_free(points);
980
0
    }
981
0
    EC_POINT_free(tmp_point);
982
0
    EC_POINT_free(base);
983
0
    return ret;
984
0
}
985
986
int ossl_ec_wNAF_have_precompute_mult(const EC_GROUP *group)
987
0
{
988
    return HAVEPRECOMP(group, ec);
989
0
}