Coverage Report

Created: 2026-10-16 07:31

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/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 || !CRYPTO_UP_REF(&pre->references, &i))
76
0
        return NULL;
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
0
    do {                                \
106
0
        BN_set_flags((P)->X, (flags));  \
107
0
        BN_set_flags((P)->Y, (flags));  \
108
0
        BN_set_flags((P)->Z, (flags));  \
109
0
    } 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
0
{
144
0
    int i, cardinality_bits, group_top, kbit, pbit, Z_is_one;
145
0
    EC_POINT *p = NULL;
146
0
    EC_POINT *s = NULL;
147
0
    BIGNUM *k = NULL;
148
0
    BIGNUM *lambda = NULL;
149
0
    BIGNUM *cardinality = NULL;
150
0
    int ret = 0;
151
152
    /* early exit if the input point is the point at infinity */
153
0
    if (point != NULL && EC_POINT_is_at_infinity(group, point))
154
0
        return EC_POINT_set_to_infinity(group, r);
155
156
0
    if (BN_is_zero(group->order)) {
157
0
        ERR_raise(ERR_LIB_EC, EC_R_UNKNOWN_ORDER);
158
0
        return 0;
159
0
    }
160
0
    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
0
    BN_CTX_start(ctx);
166
167
0
    if (((p = EC_POINT_new(group)) == NULL)
168
0
        || ((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
0
    if (point == NULL) {
174
0
        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
0
    } else {
179
0
        if (!EC_POINT_copy(p, point)) {
180
0
            ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
181
0
            goto err;
182
0
        }
183
0
    }
184
185
0
    EC_POINT_BN_set_flags(p, BN_FLG_CONSTTIME);
186
0
    EC_POINT_BN_set_flags(r, BN_FLG_CONSTTIME);
187
0
    EC_POINT_BN_set_flags(s, BN_FLG_CONSTTIME);
188
189
0
    cardinality = BN_CTX_get(ctx);
190
0
    lambda = BN_CTX_get(ctx);
191
0
    k = BN_CTX_get(ctx);
192
0
    if (k == NULL) {
193
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
194
0
        goto err;
195
0
    }
196
197
0
    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
0
    cardinality_bits = BN_num_bits(cardinality);
209
0
    group_top = bn_get_top(cardinality);
210
0
    if ((bn_wexpand(k, group_top + 2) == NULL)
211
0
        || (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
0
    if (BN_copy(k, scalar) == NULL) {
228
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
229
0
        goto err;
230
0
    }
231
232
0
    BN_set_flags(k, BN_FLG_CONSTTIME);
233
234
0
    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
0
        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
0
    }
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
0
    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
0
    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
0
    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
0
    BN_set_flags(lambda, BN_FLG_CONSTTIME);
276
0
    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
0
    kbit = BN_is_bit_set(lambda, cardinality_bits);
285
0
    BN_consttime_swap(kbit, k, lambda, group_top + 2);
286
287
0
    group_top = bn_get_top(group->field);
288
0
    if ((bn_wexpand(s->X, group_top) == NULL)
289
0
        || (bn_wexpand(s->Y, group_top) == NULL)
290
0
        || (bn_wexpand(s->Z, group_top) == NULL)
291
0
        || (bn_wexpand(r->X, group_top) == NULL)
292
0
        || (bn_wexpand(r->Y, group_top) == NULL)
293
0
        || (bn_wexpand(r->Z, group_top) == NULL)
294
0
        || (bn_wexpand(p->X, group_top) == NULL)
295
0
        || (bn_wexpand(p->Y, group_top) == NULL)
296
0
        || (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
0
    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
0
    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
0
    pbit = 1;
315
316
0
#define EC_POINT_CSWAP(c, a, b, w, t)              \
317
0
    do {                                           \
318
0
        BN_consttime_swap(c, (a)->X, (b)->X, w);   \
319
0
        BN_consttime_swap(c, (a)->Y, (b)->Y, w);   \
320
0
        BN_consttime_swap(c, (a)->Z, (b)->Z, w);   \
321
0
        t = ((a)->Z_is_one ^ (b)->Z_is_one) & (c); \
322
0
        (a)->Z_is_one ^= (t);                      \
323
0
        (b)->Z_is_one ^= (t);                      \
324
0
    } 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
0
    for (i = cardinality_bits - 1; i >= 0; i--) {
385
0
        kbit = BN_is_bit_set(k, i) ^ pbit;
386
0
        EC_POINT_CSWAP(kbit, r, s, group_top, Z_is_one);
387
388
        /* Perform a single step of the Montgomery ladder */
389
0
        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
0
        pbit ^= kbit;
398
0
    }
399
    /* one final cswap to move the right value into r */
400
0
    EC_POINT_CSWAP(pbit, r, s, group_top, Z_is_one);
401
0
#undef EC_POINT_CSWAP
402
403
    /* Finalize ladder (and recover full point coordinates) */
404
0
    if (!ec_point_ladder_post(group, r, s, p, ctx)) {
405
0
        ERR_raise(ERR_LIB_EC, EC_R_LADDER_POST_FAILURE);
406
0
        goto err;
407
0
    }
408
409
0
    ret = 1;
410
411
0
err:
412
0
    EC_POINT_free(p);
413
0
    EC_POINT_clear_free(s);
414
0
    BN_CTX_end(ctx);
415
416
0
    return ret;
417
0
}
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
0
    ((size_t)((b) >= 2000 ? 6 : (b) >= 800 ? 5 \
428
0
            : (b) >= 300                   ? 4 \
429
0
            : (b) >= 70                    ? 3 \
430
0
            : (b) >= 20                    ? 2 \
431
0
                                           : 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
0
{
444
0
    const EC_POINT *generator = NULL;
445
0
    EC_POINT *tmp = NULL;
446
0
    size_t totalnum;
447
0
    size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */
448
0
    size_t pre_points_per_block = 0;
449
0
    size_t i, j;
450
0
    int k;
451
0
    int r_is_inverted = 0;
452
0
    int r_is_at_infinity = 1;
453
0
    size_t *wsize = NULL; /* individual window sizes */
454
0
    signed char **wNAF = NULL; /* individual wNAFs */
455
0
    size_t *wNAF_len = NULL;
456
0
    size_t max_len = 0;
457
0
    size_t num_val;
458
0
    EC_POINT **val = NULL; /* precomputation */
459
0
    EC_POINT **v;
460
0
    EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' or
461
                                 * 'pre_comp->points' */
462
0
    const EC_PRE_COMP *pre_comp = NULL;
463
0
    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
0
    int ret = 0;
467
468
0
    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
0
        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
0
            return ossl_ec_scalar_mul_ladder(group, r, scalar, NULL, ctx);
484
0
        }
485
0
        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
0
    }
497
498
0
    if (scalar != NULL) {
499
0
        generator = EC_GROUP_get0_generator(group);
500
0
        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
0
        pre_comp = group->pre_comp.ec;
508
0
        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
0
        } else {
532
            /* can't use precomputation */
533
0
            pre_comp = NULL;
534
0
            numblocks = 1;
535
0
            num_scalar = 1; /* treat 'scalar' like 'num'-th element of
536
                             * 'scalars' */
537
0
        }
538
0
    }
539
540
0
    totalnum = num + numblocks;
541
542
0
    wsize = OPENSSL_malloc_array(totalnum, sizeof(wsize[0]));
543
0
    wNAF_len = OPENSSL_malloc_array(totalnum, sizeof(wNAF_len[0]));
544
    /* include space for pivot */
545
0
    wNAF = OPENSSL_malloc_array(totalnum + 1, sizeof(wNAF[0]));
546
0
    val_sub = OPENSSL_malloc_array(totalnum, sizeof(val_sub[0]));
547
548
    /* Ensure wNAF is initialised in case we end up going to err */
549
0
    if (wNAF != NULL)
550
0
        wNAF[0] = NULL; /* preliminary pivot */
551
552
0
    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
0
    num_val = 0;
559
560
0
    for (i = 0; i < num + num_scalar; i++) {
561
0
        size_t bits;
562
563
0
        bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
564
0
        wsize[i] = EC_window_bits_for_scalar_size(bits);
565
0
        num_val += (size_t)1 << (wsize[i] - 1);
566
0
        wNAF[i + 1] = NULL; /* make sure we always have a pivot */
567
0
        wNAF[i] = bn_compute_wNAF((i < num ? scalars[i] : scalar), (int)wsize[i],
568
0
            &wNAF_len[i]);
569
0
        if (wNAF[i] == NULL)
570
0
            goto err;
571
0
        if (wNAF_len[i] > max_len)
572
0
            max_len = wNAF_len[i];
573
0
    }
574
575
0
    if (numblocks) {
576
        /* we go here iff scalar != NULL */
577
578
0
        if (pre_comp == NULL) {
579
0
            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
0
        } 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, (int)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
0
    }
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
0
    val = OPENSSL_malloc_array(num_val + 1, sizeof(val[0]));
689
0
    if (val == NULL)
690
0
        goto err;
691
0
    val[num_val] = NULL; /* pivot element */
692
693
    /* allocate points for precomputation */
694
0
    v = val;
695
0
    for (i = 0; i < num + num_scalar; i++) {
696
0
        val_sub[i] = v;
697
0
        for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) {
698
0
            *v = EC_POINT_new(group);
699
0
            if (*v == NULL)
700
0
                goto err;
701
0
            v++;
702
0
        }
703
0
    }
704
0
    if (!(v == val + num_val)) {
705
0
        ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
706
0
        goto err;
707
0
    }
708
709
0
    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
0
    for (i = 0; i < num + num_scalar; i++) {
720
0
        if (i < num) {
721
0
            if (!EC_POINT_copy(val_sub[i][0], points[i]))
722
0
                goto err;
723
0
        } else {
724
0
            if (!EC_POINT_copy(val_sub[i][0], generator))
725
0
                goto err;
726
0
        }
727
728
0
        if (wsize[i] > 1) {
729
0
            if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx))
730
0
                goto err;
731
0
            for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) {
732
0
                if (!EC_POINT_add(group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx))
733
0
                    goto err;
734
0
            }
735
0
        }
736
0
    }
737
738
0
    if (group->meth->points_make_affine == NULL
739
0
        || !group->meth->points_make_affine(group, num_val, val, ctx))
740
0
        goto err;
741
742
0
    r_is_at_infinity = 1;
743
744
0
    if (max_len > INT_MAX)
745
0
        goto err;
746
0
    for (k = (int)(max_len - 1); k >= 0; k--) {
747
0
        if (!r_is_at_infinity) {
748
0
            if (!EC_POINT_dbl(group, r, r, ctx))
749
0
                goto err;
750
0
        }
751
752
0
        for (i = 0; i < totalnum; i++) {
753
0
            if (wNAF_len[i] > (size_t)k) {
754
0
                int digit = wNAF[i][k];
755
0
                int is_neg;
756
757
0
                if (digit) {
758
0
                    is_neg = digit < 0;
759
760
0
                    if (is_neg)
761
0
                        digit = -digit;
762
763
0
                    if (is_neg != r_is_inverted) {
764
0
                        if (!r_is_at_infinity) {
765
0
                            if (!EC_POINT_invert(group, r, ctx))
766
0
                                goto err;
767
0
                        }
768
0
                        r_is_inverted = !r_is_inverted;
769
0
                    }
770
771
                    /* digit > 0 */
772
773
0
                    if (r_is_at_infinity) {
774
0
                        if (!EC_POINT_copy(r, val_sub[i][digit >> 1]))
775
0
                            goto err;
776
777
                        /*-
778
                         * Apply coordinate blinding for EC_POINT.
779
                         *
780
                         * The underlying EC_METHOD can optionally implement this function:
781
                         * ossl_ec_point_blind_coordinates() returns 0 in case of errors or 1 on
782
                         * success or if coordinate blinding is not implemented for this
783
                         * group.
784
                         */
785
0
                        if (!ossl_ec_point_blind_coordinates(group, r, ctx)) {
786
0
                            ERR_raise(ERR_LIB_EC, EC_R_POINT_COORDINATES_BLIND_FAILURE);
787
0
                            goto err;
788
0
                        }
789
790
0
                        r_is_at_infinity = 0;
791
0
                    } else {
792
0
                        if (!EC_POINT_add(group, r, r, val_sub[i][digit >> 1], ctx))
793
0
                            goto err;
794
0
                    }
795
0
                }
796
0
            }
797
0
        }
798
0
    }
799
800
0
    if (r_is_at_infinity) {
801
0
        if (!EC_POINT_set_to_infinity(group, r))
802
0
            goto err;
803
0
    } else {
804
0
        if (r_is_inverted)
805
0
            if (!EC_POINT_invert(group, r, ctx))
806
0
                goto err;
807
0
    }
808
809
0
    ret = 1;
810
811
0
err:
812
0
    EC_POINT_free(tmp);
813
0
    OPENSSL_free(wsize);
814
0
    OPENSSL_free(wNAF_len);
815
0
    if (wNAF != NULL) {
816
0
        signed char **w;
817
818
0
        for (w = wNAF; *w != NULL; w++)
819
0
            OPENSSL_free(*w);
820
821
0
        OPENSSL_free(wNAF);
822
0
    }
823
0
    if (val != NULL) {
824
0
        for (v = val; *v != NULL; v++)
825
0
            EC_POINT_clear_free(*v);
826
827
0
        OPENSSL_free(val);
828
0
    }
829
0
    OPENSSL_free(val_sub);
830
0
    return ret;
831
0
}
832
833
/*-
834
 * ossl_ec_wNAF_precompute_mult()
835
 * creates an EC_PRE_COMP object with preprecomputed multiples of the generator
836
 * for use with wNAF splitting as implemented in ossl_ec_wNAF_mul().
837
 *
838
 * 'pre_comp->points' is an array of multiples of the generator
839
 * of the following form:
840
 * points[0] =     generator;
841
 * points[1] = 3 * generator;
842
 * ...
843
 * points[2^(w-1)-1] =     (2^(w-1)-1) * generator;
844
 * points[2^(w-1)]   =     2^blocksize * generator;
845
 * points[2^(w-1)+1] = 3 * 2^blocksize * generator;
846
 * ...
847
 * points[2^(w-1)*(numblocks-1)-1] = (2^(w-1)) *  2^(blocksize*(numblocks-2)) * generator
848
 * points[2^(w-1)*(numblocks-1)]   =              2^(blocksize*(numblocks-1)) * generator
849
 * ...
850
 * points[2^(w-1)*numblocks-1]     = (2^(w-1)) *  2^(blocksize*(numblocks-1)) * generator
851
 * points[2^(w-1)*numblocks]       = NULL
852
 */
853
int ossl_ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
854
0
{
855
0
    const EC_POINT *generator;
856
0
    EC_POINT *tmp_point = NULL, *base = NULL, **var;
857
0
    const BIGNUM *order;
858
0
    size_t i, bits, w, pre_points_per_block, blocksize, numblocks, num;
859
0
    EC_POINT **points = NULL;
860
0
    EC_PRE_COMP *pre_comp;
861
0
    int ret = 0;
862
0
    int used_ctx = 0;
863
0
#ifndef FIPS_MODULE
864
0
    BN_CTX *new_ctx = NULL;
865
0
#endif
866
867
    /* if there is an old EC_PRE_COMP object, throw it away */
868
0
    EC_pre_comp_free(group);
869
0
    if ((pre_comp = ec_pre_comp_new(group)) == NULL)
870
0
        return 0;
871
872
0
    generator = EC_GROUP_get0_generator(group);
873
0
    if (generator == NULL) {
874
0
        ERR_raise(ERR_LIB_EC, EC_R_UNDEFINED_GENERATOR);
875
0
        goto err;
876
0
    }
877
878
0
#ifndef FIPS_MODULE
879
0
    if (ctx == NULL)
880
0
        ctx = new_ctx = BN_CTX_new();
881
0
#endif
882
0
    if (ctx == NULL)
883
0
        goto err;
884
885
0
    BN_CTX_start(ctx);
886
0
    used_ctx = 1;
887
888
0
    order = EC_GROUP_get0_order(group);
889
0
    if (order == NULL)
890
0
        goto err;
891
0
    if (BN_is_zero(order)) {
892
0
        ERR_raise(ERR_LIB_EC, EC_R_UNKNOWN_ORDER);
893
0
        goto err;
894
0
    }
895
896
0
    bits = BN_num_bits(order);
897
    /*
898
     * The following parameters mean we precompute (approximately) one point
899
     * per bit. TBD: The combination 8, 4 is perfect for 160 bits; for other
900
     * bit lengths, other parameter combinations might provide better
901
     * efficiency.
902
     */
903
0
    blocksize = 8;
904
0
    w = 4;
905
0
    if (EC_window_bits_for_scalar_size(bits) > w) {
906
        /* let's not make the window too small ... */
907
0
        w = EC_window_bits_for_scalar_size(bits);
908
0
    }
909
910
0
    numblocks = (bits + blocksize - 1) / blocksize; /* max. number of blocks
911
                                                     * to use for wNAF
912
                                                     * splitting */
913
914
0
    pre_points_per_block = (size_t)1 << (w - 1);
915
0
    num = pre_points_per_block * numblocks; /* number of points to compute
916
                                             * and store */
917
918
0
    points = OPENSSL_malloc_array(num + 1, sizeof(*points));
919
0
    if (points == NULL)
920
0
        goto err;
921
922
0
    var = points;
923
0
    var[num] = NULL; /* pivot */
924
0
    for (i = 0; i < num; i++) {
925
0
        if ((var[i] = EC_POINT_new(group)) == NULL) {
926
0
            ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
927
0
            goto err;
928
0
        }
929
0
    }
930
931
0
    if ((tmp_point = EC_POINT_new(group)) == NULL
932
0
        || (base = EC_POINT_new(group)) == NULL) {
933
0
        ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
934
0
        goto err;
935
0
    }
936
937
0
    if (!EC_POINT_copy(base, generator))
938
0
        goto err;
939
940
    /* do the precomputation */
941
0
    for (i = 0; i < numblocks; i++) {
942
0
        size_t j;
943
944
0
        if (!EC_POINT_dbl(group, tmp_point, base, ctx))
945
0
            goto err;
946
947
0
        if (!EC_POINT_copy(*var++, base))
948
0
            goto err;
949
950
0
        for (j = 1; j < pre_points_per_block; j++, var++) {
951
            /*
952
             * calculate odd multiples of the current base point
953
             */
954
0
            if (!EC_POINT_add(group, *var, tmp_point, *(var - 1), ctx))
955
0
                goto err;
956
0
        }
957
958
0
        if (i < numblocks - 1) {
959
            /*
960
             * get the next base (multiply current one by 2^blocksize)
961
             */
962
0
            size_t k;
963
964
0
            if (blocksize <= 2) {
965
0
                ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
966
0
                goto err;
967
0
            }
968
969
0
            if (!EC_POINT_dbl(group, base, tmp_point, ctx))
970
0
                goto err;
971
0
            for (k = 2; k < blocksize; k++) {
972
0
                if (!EC_POINT_dbl(group, base, base, ctx))
973
0
                    goto err;
974
0
            }
975
0
        }
976
0
    }
977
978
0
    if (group->meth->points_make_affine == NULL
979
0
        || !group->meth->points_make_affine(group, num, points, ctx))
980
0
        goto err;
981
982
0
    pre_comp->group = group;
983
0
    pre_comp->blocksize = blocksize;
984
0
    pre_comp->numblocks = numblocks;
985
0
    pre_comp->w = w;
986
0
    pre_comp->points = points;
987
0
    points = NULL;
988
0
    pre_comp->num = num;
989
0
    SETPRECOMP(group, ec, pre_comp);
990
0
    pre_comp = NULL;
991
0
    ret = 1;
992
993
0
err:
994
0
    if (used_ctx)
995
0
        BN_CTX_end(ctx);
996
0
#ifndef FIPS_MODULE
997
0
    BN_CTX_free(new_ctx);
998
0
#endif
999
0
    EC_ec_pre_comp_free(pre_comp);
1000
0
    if (points) {
1001
0
        EC_POINT **p;
1002
1003
0
        for (p = points; *p != NULL; p++)
1004
0
            EC_POINT_free(*p);
1005
0
        OPENSSL_free(points);
1006
0
    }
1007
0
    EC_POINT_free(tmp_point);
1008
0
    EC_POINT_free(base);
1009
0
    return ret;
1010
0
}
1011
1012
int ossl_ec_wNAF_have_precompute_mult(const EC_GROUP *group)
1013
0
{
1014
    return HAVEPRECOMP(group, ec);
1015
0
}