Coverage Report

Created: 2026-10-28 06:28

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