Coverage Report

Created: 2025-12-10 06:24

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-2025 The OpenSSL Project Authors. All Rights Reserved.
3
 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4
 *
5
 * Licensed under the Apache License 2.0 (the "License").  You may not use
6
 * this file except in compliance with the License.  You can obtain a copy
7
 * in the file LICENSE in the source distribution or at
8
 * https://www.openssl.org/source/license.html
9
 */
10
11
/*
12
 * 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
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
0
    if (!BN_copy(k, scalar)) {
217
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
218
0
        goto err;
219
0
    }
220
221
0
    BN_set_flags(k, BN_FLG_CONSTTIME);
222
223
0
    if ((BN_num_bits(k) > cardinality_bits) || (BN_is_negative(k))) {
224
        /*-
225
         * this is an unusual input, and we don't guarantee
226
         * constant-timeness
227
         */
228
0
        if (!BN_nnmod(k, k, cardinality, ctx)) {
229
0
            ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
230
0
            goto err;
231
0
        }
232
0
    }
233
234
0
    if (!BN_add(lambda, k, cardinality)) {
235
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
236
0
        goto err;
237
0
    }
238
0
    BN_set_flags(lambda, BN_FLG_CONSTTIME);
239
0
    if (!BN_add(k, lambda, cardinality)) {
240
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
241
0
        goto err;
242
0
    }
243
    /*
244
     * lambda := scalar + cardinality
245
     * k := scalar + 2*cardinality
246
     */
247
0
    kbit = BN_is_bit_set(lambda, cardinality_bits);
248
0
    BN_consttime_swap(kbit, k, lambda, group_top + 2);
249
250
0
    group_top = bn_get_top(group->field);
251
0
    if ((bn_wexpand(s->X, group_top) == NULL)
252
0
        || (bn_wexpand(s->Y, group_top) == NULL)
253
0
        || (bn_wexpand(s->Z, group_top) == NULL)
254
0
        || (bn_wexpand(r->X, group_top) == NULL)
255
0
        || (bn_wexpand(r->Y, group_top) == NULL)
256
0
        || (bn_wexpand(r->Z, group_top) == NULL)
257
0
        || (bn_wexpand(p->X, group_top) == NULL)
258
0
        || (bn_wexpand(p->Y, group_top) == NULL)
259
0
        || (bn_wexpand(p->Z, group_top) == NULL)) {
260
0
        ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
261
0
        goto err;
262
0
    }
263
264
    /* ensure input point is in affine coords for ladder step efficiency */
265
0
    if (!p->Z_is_one && (group->meth->make_affine == NULL || !group->meth->make_affine(group, p, ctx))) {
266
0
        ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
267
0
        goto err;
268
0
    }
269
270
    /* Initialize the Montgomery ladder */
271
0
    if (!ec_point_ladder_pre(group, r, s, p, ctx)) {
272
0
        ERR_raise(ERR_LIB_EC, EC_R_LADDER_PRE_FAILURE);
273
0
        goto err;
274
0
    }
275
276
    /* top bit is a 1, in a fixed pos */
277
0
    pbit = 1;
278
279
0
#define EC_POINT_CSWAP(c, a, b, w, t)              \
280
0
    do {                                           \
281
0
        BN_consttime_swap(c, (a)->X, (b)->X, w);   \
282
0
        BN_consttime_swap(c, (a)->Y, (b)->Y, w);   \
283
0
        BN_consttime_swap(c, (a)->Z, (b)->Z, w);   \
284
0
        t = ((a)->Z_is_one ^ (b)->Z_is_one) & (c); \
285
0
        (a)->Z_is_one ^= (t);                      \
286
0
        (b)->Z_is_one ^= (t);                      \
287
0
    } while (0)
288
289
    /*-
290
     * The ladder step, with branches, is
291
     *
292
     * k[i] == 0: S = add(R, S), R = dbl(R)
293
     * k[i] == 1: R = add(S, R), S = dbl(S)
294
     *
295
     * Swapping R, S conditionally on k[i] leaves you with state
296
     *
297
     * k[i] == 0: T, U = R, S
298
     * k[i] == 1: T, U = S, R
299
     *
300
     * Then perform the ECC ops.
301
     *
302
     * U = add(T, U)
303
     * T = dbl(T)
304
     *
305
     * Which leaves you with state
306
     *
307
     * k[i] == 0: U = add(R, S), T = dbl(R)
308
     * k[i] == 1: U = add(S, R), T = dbl(S)
309
     *
310
     * Swapping T, U conditionally on k[i] leaves you with state
311
     *
312
     * k[i] == 0: R, S = T, U
313
     * k[i] == 1: R, S = U, T
314
     *
315
     * Which leaves you with state
316
     *
317
     * k[i] == 0: S = add(R, S), R = dbl(R)
318
     * k[i] == 1: R = add(S, R), S = dbl(S)
319
     *
320
     * So we get the same logic, but instead of a branch it's a
321
     * conditional swap, followed by ECC ops, then another conditional swap.
322
     *
323
     * Optimization: The end of iteration i and start of i-1 looks like
324
     *
325
     * ...
326
     * CSWAP(k[i], R, S)
327
     * ECC
328
     * CSWAP(k[i], R, S)
329
     * (next iteration)
330
     * CSWAP(k[i-1], R, S)
331
     * ECC
332
     * CSWAP(k[i-1], R, S)
333
     * ...
334
     *
335
     * So instead of two contiguous swaps, you can merge the condition
336
     * bits and do a single swap.
337
     *
338
     * k[i]   k[i-1]    Outcome
339
     * 0      0         No Swap
340
     * 0      1         Swap
341
     * 1      0         Swap
342
     * 1      1         No Swap
343
     *
344
     * This is XOR. pbit tracks the previous bit of k.
345
     */
346
347
0
    for (i = cardinality_bits - 1; i >= 0; i--) {
348
0
        kbit = BN_is_bit_set(k, i) ^ pbit;
349
0
        EC_POINT_CSWAP(kbit, r, s, group_top, Z_is_one);
350
351
        /* Perform a single step of the Montgomery ladder */
352
0
        if (!ec_point_ladder_step(group, r, s, p, ctx)) {
353
0
            ERR_raise(ERR_LIB_EC, EC_R_LADDER_STEP_FAILURE);
354
0
            goto err;
355
0
        }
356
        /*
357
         * pbit logic merges this cswap with that of the
358
         * next iteration
359
         */
360
0
        pbit ^= kbit;
361
0
    }
362
    /* one final cswap to move the right value into r */
363
0
    EC_POINT_CSWAP(pbit, r, s, group_top, Z_is_one);
364
0
#undef EC_POINT_CSWAP
365
366
    /* Finalize ladder (and recover full point coordinates) */
367
0
    if (!ec_point_ladder_post(group, r, s, p, ctx)) {
368
0
        ERR_raise(ERR_LIB_EC, EC_R_LADDER_POST_FAILURE);
369
0
        goto err;
370
0
    }
371
372
0
    ret = 1;
373
374
0
err:
375
0
    EC_POINT_free(p);
376
0
    EC_POINT_clear_free(s);
377
0
    BN_CTX_end(ctx);
378
379
0
    return ret;
380
0
}
381
382
#undef EC_POINT_BN_set_flags
383
384
/*
385
 * Table could be optimised for the wNAF-based implementation,
386
 * sometimes smaller windows will give better performance (thus the
387
 * boundaries should be increased)
388
 */
389
#define EC_window_bits_for_scalar_size(b)      \
390
0
    ((size_t)((b) >= 2000 ? 6 : (b) >= 800 ? 5 \
391
0
            : (b) >= 300                   ? 4 \
392
0
            : (b) >= 70                    ? 3 \
393
0
            : (b) >= 20                    ? 2 \
394
0
                                           : 1))
395
396
/*-
397
 * Compute
398
 *      \sum scalars[i]*points[i],
399
 * also including
400
 *      scalar*generator
401
 * in the addition if scalar != NULL
402
 */
403
int ossl_ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
404
    size_t num, const EC_POINT *points[],
405
    const BIGNUM *scalars[], BN_CTX *ctx)
406
0
{
407
0
    const EC_POINT *generator = NULL;
408
0
    EC_POINT *tmp = NULL;
409
0
    size_t totalnum;
410
0
    size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */
411
0
    size_t pre_points_per_block = 0;
412
0
    size_t i, j;
413
0
    int k;
414
0
    int r_is_inverted = 0;
415
0
    int r_is_at_infinity = 1;
416
0
    size_t *wsize = NULL; /* individual window sizes */
417
0
    signed char **wNAF = NULL; /* individual wNAFs */
418
0
    size_t *wNAF_len = NULL;
419
0
    size_t max_len = 0;
420
0
    size_t num_val;
421
0
    EC_POINT **val = NULL; /* precomputation */
422
0
    EC_POINT **v;
423
0
    EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' or
424
                                 * 'pre_comp->points' */
425
0
    const EC_PRE_COMP *pre_comp = NULL;
426
0
    int num_scalar = 0; /* flag: will be set to 1 if 'scalar' must be
427
                         * treated like other scalars, i.e.
428
                         * precomputation is not available */
429
0
    int ret = 0;
430
431
0
    if (!BN_is_zero(group->order) && !BN_is_zero(group->cofactor)) {
432
        /*-
433
         * Handle the common cases where the scalar is secret, enforcing a
434
         * scalar multiplication implementation based on a Montgomery ladder,
435
         * with various timing attack defenses.
436
         */
437
0
        if ((scalar != group->order) && (scalar != NULL) && (num == 0)) {
438
            /*-
439
             * In this case we want to compute scalar * GeneratorPoint: this
440
             * codepath is reached most prominently by (ephemeral) key
441
             * generation of EC cryptosystems (i.e. ECDSA keygen and sign setup,
442
             * ECDH keygen/first half), where the scalar is always secret. This
443
             * is why we ignore if BN_FLG_CONSTTIME is actually set and we
444
             * always call the ladder version.
445
             */
446
0
            return ossl_ec_scalar_mul_ladder(group, r, scalar, NULL, ctx);
447
0
        }
448
0
        if ((scalar == NULL) && (num == 1) && (scalars[0] != group->order)) {
449
            /*-
450
             * In this case we want to compute scalar * VariablePoint: this
451
             * codepath is reached most prominently by the second half of ECDH,
452
             * where the secret scalar is multiplied by the peer's public point.
453
             * To protect the secret scalar, we ignore if BN_FLG_CONSTTIME is
454
             * actually set and we always call the ladder version.
455
             */
456
0
            return ossl_ec_scalar_mul_ladder(group, r, scalars[0], points[0],
457
0
                ctx);
458
0
        }
459
0
    }
460
461
0
    if (scalar != NULL) {
462
0
        generator = EC_GROUP_get0_generator(group);
463
0
        if (generator == NULL) {
464
0
            ERR_raise(ERR_LIB_EC, EC_R_UNDEFINED_GENERATOR);
465
0
            goto err;
466
0
        }
467
468
        /* look if we can use precomputed multiples of generator */
469
470
0
        pre_comp = group->pre_comp.ec;
471
0
        if (pre_comp && pre_comp->numblocks
472
0
            && (EC_POINT_cmp(group, generator, pre_comp->points[0], ctx) == 0)) {
473
0
            blocksize = pre_comp->blocksize;
474
475
            /*
476
             * determine maximum number of blocks that wNAF splitting may
477
             * yield (NB: maximum wNAF length is bit length plus one)
478
             */
479
0
            numblocks = (BN_num_bits(scalar) / blocksize) + 1;
480
481
            /*
482
             * we cannot use more blocks than we have precomputation for
483
             */
484
0
            if (numblocks > pre_comp->numblocks)
485
0
                numblocks = pre_comp->numblocks;
486
487
0
            pre_points_per_block = (size_t)1 << (pre_comp->w - 1);
488
489
            /* check that pre_comp looks sane */
490
0
            if (pre_comp->num != (pre_comp->numblocks * pre_points_per_block)) {
491
0
                ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
492
0
                goto err;
493
0
            }
494
0
        } else {
495
            /* can't use precomputation */
496
0
            pre_comp = NULL;
497
0
            numblocks = 1;
498
0
            num_scalar = 1; /* treat 'scalar' like 'num'-th element of
499
                             * 'scalars' */
500
0
        }
501
0
    }
502
503
0
    totalnum = num + numblocks;
504
505
0
    wsize = OPENSSL_malloc_array(totalnum, sizeof(wsize[0]));
506
0
    wNAF_len = OPENSSL_malloc_array(totalnum, sizeof(wNAF_len[0]));
507
    /* include space for pivot */
508
0
    wNAF = OPENSSL_malloc_array(totalnum + 1, sizeof(wNAF[0]));
509
0
    val_sub = OPENSSL_malloc_array(totalnum, sizeof(val_sub[0]));
510
511
    /* Ensure wNAF is initialised in case we end up going to err */
512
0
    if (wNAF != NULL)
513
0
        wNAF[0] = NULL; /* preliminary pivot */
514
515
0
    if (wsize == NULL || wNAF_len == NULL || wNAF == NULL || val_sub == NULL)
516
0
        goto err;
517
518
    /*
519
     * num_val will be the total number of temporarily precomputed points
520
     */
521
0
    num_val = 0;
522
523
0
    for (i = 0; i < num + num_scalar; i++) {
524
0
        size_t bits;
525
526
0
        bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
527
0
        wsize[i] = EC_window_bits_for_scalar_size(bits);
528
0
        num_val += (size_t)1 << (wsize[i] - 1);
529
0
        wNAF[i + 1] = NULL; /* make sure we always have a pivot */
530
0
        wNAF[i] = bn_compute_wNAF((i < num ? scalars[i] : scalar), (int)wsize[i],
531
0
            &wNAF_len[i]);
532
0
        if (wNAF[i] == NULL)
533
0
            goto err;
534
0
        if (wNAF_len[i] > max_len)
535
0
            max_len = wNAF_len[i];
536
0
    }
537
538
0
    if (numblocks) {
539
        /* we go here iff scalar != NULL */
540
541
0
        if (pre_comp == NULL) {
542
0
            if (num_scalar != 1) {
543
0
                ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
544
0
                goto err;
545
0
            }
546
            /* we have already generated a wNAF for 'scalar' */
547
0
        } else {
548
0
            signed char *tmp_wNAF = NULL;
549
0
            size_t tmp_len = 0;
550
551
0
            if (num_scalar != 0) {
552
0
                ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
553
0
                goto err;
554
0
            }
555
556
            /*
557
             * use the window size for which we have precomputation
558
             */
559
0
            wsize[num] = pre_comp->w;
560
0
            tmp_wNAF = bn_compute_wNAF(scalar, (int)wsize[num], &tmp_len);
561
0
            if (!tmp_wNAF)
562
0
                goto err;
563
564
0
            if (tmp_len <= max_len) {
565
                /*
566
                 * One of the other wNAFs is at least as long as the wNAF
567
                 * belonging to the generator, so wNAF splitting will not buy
568
                 * us anything.
569
                 */
570
571
0
                numblocks = 1;
572
0
                totalnum = num + 1; /* don't use wNAF splitting */
573
0
                wNAF[num] = tmp_wNAF;
574
0
                wNAF[num + 1] = NULL;
575
0
                wNAF_len[num] = tmp_len;
576
                /*
577
                 * pre_comp->points starts with the points that we need here:
578
                 */
579
0
                val_sub[num] = pre_comp->points;
580
0
            } else {
581
                /*
582
                 * don't include tmp_wNAF directly into wNAF array - use wNAF
583
                 * splitting and include the blocks
584
                 */
585
586
0
                signed char *pp;
587
0
                EC_POINT **tmp_points;
588
589
0
                if (tmp_len < numblocks * blocksize) {
590
                    /*
591
                     * possibly we can do with fewer blocks than estimated
592
                     */
593
0
                    numblocks = (tmp_len + blocksize - 1) / blocksize;
594
0
                    if (numblocks > pre_comp->numblocks) {
595
0
                        ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
596
0
                        OPENSSL_free(tmp_wNAF);
597
0
                        goto err;
598
0
                    }
599
0
                    totalnum = num + numblocks;
600
0
                }
601
602
                /* split wNAF in 'numblocks' parts */
603
0
                pp = tmp_wNAF;
604
0
                tmp_points = pre_comp->points;
605
606
0
                for (i = num; i < totalnum; i++) {
607
0
                    if (i < totalnum - 1) {
608
0
                        wNAF_len[i] = blocksize;
609
0
                        if (tmp_len < blocksize) {
610
0
                            ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
611
0
                            OPENSSL_free(tmp_wNAF);
612
0
                            goto err;
613
0
                        }
614
0
                        tmp_len -= blocksize;
615
0
                    } else
616
                        /*
617
                         * last block gets whatever is left (this could be
618
                         * more or less than 'blocksize'!)
619
                         */
620
0
                        wNAF_len[i] = tmp_len;
621
622
0
                    wNAF[i + 1] = NULL;
623
0
                    wNAF[i] = OPENSSL_malloc(wNAF_len[i]);
624
0
                    if (wNAF[i] == NULL) {
625
0
                        OPENSSL_free(tmp_wNAF);
626
0
                        goto err;
627
0
                    }
628
0
                    memcpy(wNAF[i], pp, wNAF_len[i]);
629
0
                    if (wNAF_len[i] > max_len)
630
0
                        max_len = wNAF_len[i];
631
632
0
                    if (*tmp_points == NULL) {
633
0
                        ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
634
0
                        OPENSSL_free(tmp_wNAF);
635
0
                        goto err;
636
0
                    }
637
0
                    val_sub[i] = tmp_points;
638
0
                    tmp_points += pre_points_per_block;
639
0
                    pp += blocksize;
640
0
                }
641
0
                OPENSSL_free(tmp_wNAF);
642
0
            }
643
0
        }
644
0
    }
645
646
    /*
647
     * All points we precompute now go into a single array 'val'.
648
     * 'val_sub[i]' is a pointer to the subarray for the i-th point, or to a
649
     * subarray of 'pre_comp->points' if we already have precomputation.
650
     */
651
0
    val = OPENSSL_malloc_array(num_val + 1, sizeof(val[0]));
652
0
    if (val == NULL)
653
0
        goto err;
654
0
    val[num_val] = NULL; /* pivot element */
655
656
    /* allocate points for precomputation */
657
0
    v = val;
658
0
    for (i = 0; i < num + num_scalar; i++) {
659
0
        val_sub[i] = v;
660
0
        for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) {
661
0
            *v = EC_POINT_new(group);
662
0
            if (*v == NULL)
663
0
                goto err;
664
0
            v++;
665
0
        }
666
0
    }
667
0
    if (!(v == val + num_val)) {
668
0
        ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
669
0
        goto err;
670
0
    }
671
672
0
    if ((tmp = EC_POINT_new(group)) == NULL)
673
0
        goto err;
674
675
    /*-
676
     * prepare precomputed values:
677
     *    val_sub[i][0] :=     points[i]
678
     *    val_sub[i][1] := 3 * points[i]
679
     *    val_sub[i][2] := 5 * points[i]
680
     *    ...
681
     */
682
0
    for (i = 0; i < num + num_scalar; i++) {
683
0
        if (i < num) {
684
0
            if (!EC_POINT_copy(val_sub[i][0], points[i]))
685
0
                goto err;
686
0
        } else {
687
0
            if (!EC_POINT_copy(val_sub[i][0], generator))
688
0
                goto err;
689
0
        }
690
691
0
        if (wsize[i] > 1) {
692
0
            if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx))
693
0
                goto err;
694
0
            for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) {
695
0
                if (!EC_POINT_add(group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx))
696
0
                    goto err;
697
0
            }
698
0
        }
699
0
    }
700
701
0
    if (group->meth->points_make_affine == NULL
702
0
        || !group->meth->points_make_affine(group, num_val, val, ctx))
703
0
        goto err;
704
705
0
    r_is_at_infinity = 1;
706
707
0
    if (max_len > INT_MAX)
708
0
        goto err;
709
0
    for (k = (int)(max_len - 1); k >= 0; k--) {
710
0
        if (!r_is_at_infinity) {
711
0
            if (!EC_POINT_dbl(group, r, r, ctx))
712
0
                goto err;
713
0
        }
714
715
0
        for (i = 0; i < totalnum; i++) {
716
0
            if (wNAF_len[i] > (size_t)k) {
717
0
                int digit = wNAF[i][k];
718
0
                int is_neg;
719
720
0
                if (digit) {
721
0
                    is_neg = digit < 0;
722
723
0
                    if (is_neg)
724
0
                        digit = -digit;
725
726
0
                    if (is_neg != r_is_inverted) {
727
0
                        if (!r_is_at_infinity) {
728
0
                            if (!EC_POINT_invert(group, r, ctx))
729
0
                                goto err;
730
0
                        }
731
0
                        r_is_inverted = !r_is_inverted;
732
0
                    }
733
734
                    /* digit > 0 */
735
736
0
                    if (r_is_at_infinity) {
737
0
                        if (!EC_POINT_copy(r, val_sub[i][digit >> 1]))
738
0
                            goto err;
739
740
                        /*-
741
                         * Apply coordinate blinding for EC_POINT.
742
                         *
743
                         * The underlying EC_METHOD can optionally implement this function:
744
                         * ossl_ec_point_blind_coordinates() returns 0 in case of errors or 1 on
745
                         * success or if coordinate blinding is not implemented for this
746
                         * group.
747
                         */
748
0
                        if (!ossl_ec_point_blind_coordinates(group, r, ctx)) {
749
0
                            ERR_raise(ERR_LIB_EC, EC_R_POINT_COORDINATES_BLIND_FAILURE);
750
0
                            goto err;
751
0
                        }
752
753
0
                        r_is_at_infinity = 0;
754
0
                    } else {
755
0
                        if (!EC_POINT_add(group, r, r, val_sub[i][digit >> 1], ctx))
756
0
                            goto err;
757
0
                    }
758
0
                }
759
0
            }
760
0
        }
761
0
    }
762
763
0
    if (r_is_at_infinity) {
764
0
        if (!EC_POINT_set_to_infinity(group, r))
765
0
            goto err;
766
0
    } else {
767
0
        if (r_is_inverted)
768
0
            if (!EC_POINT_invert(group, r, ctx))
769
0
                goto err;
770
0
    }
771
772
0
    ret = 1;
773
774
0
err:
775
0
    EC_POINT_free(tmp);
776
0
    OPENSSL_free(wsize);
777
0
    OPENSSL_free(wNAF_len);
778
0
    if (wNAF != NULL) {
779
0
        signed char **w;
780
781
0
        for (w = wNAF; *w != NULL; w++)
782
0
            OPENSSL_free(*w);
783
784
0
        OPENSSL_free(wNAF);
785
0
    }
786
0
    if (val != NULL) {
787
0
        for (v = val; *v != NULL; v++)
788
0
            EC_POINT_clear_free(*v);
789
790
0
        OPENSSL_free(val);
791
0
    }
792
0
    OPENSSL_free(val_sub);
793
0
    return ret;
794
0
}
795
796
/*-
797
 * ossl_ec_wNAF_precompute_mult()
798
 * creates an EC_PRE_COMP object with preprecomputed multiples of the generator
799
 * for use with wNAF splitting as implemented in ossl_ec_wNAF_mul().
800
 *
801
 * 'pre_comp->points' is an array of multiples of the generator
802
 * of the following form:
803
 * points[0] =     generator;
804
 * points[1] = 3 * generator;
805
 * ...
806
 * points[2^(w-1)-1] =     (2^(w-1)-1) * generator;
807
 * points[2^(w-1)]   =     2^blocksize * generator;
808
 * points[2^(w-1)+1] = 3 * 2^blocksize * generator;
809
 * ...
810
 * points[2^(w-1)*(numblocks-1)-1] = (2^(w-1)) *  2^(blocksize*(numblocks-2)) * generator
811
 * points[2^(w-1)*(numblocks-1)]   =              2^(blocksize*(numblocks-1)) * generator
812
 * ...
813
 * points[2^(w-1)*numblocks-1]     = (2^(w-1)) *  2^(blocksize*(numblocks-1)) * generator
814
 * points[2^(w-1)*numblocks]       = NULL
815
 */
816
int ossl_ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
817
0
{
818
0
    const EC_POINT *generator;
819
0
    EC_POINT *tmp_point = NULL, *base = NULL, **var;
820
0
    const BIGNUM *order;
821
0
    size_t i, bits, w, pre_points_per_block, blocksize, numblocks, num;
822
0
    EC_POINT **points = NULL;
823
0
    EC_PRE_COMP *pre_comp;
824
0
    int ret = 0;
825
0
    int used_ctx = 0;
826
0
#ifndef FIPS_MODULE
827
0
    BN_CTX *new_ctx = NULL;
828
0
#endif
829
830
    /* if there is an old EC_PRE_COMP object, throw it away */
831
0
    EC_pre_comp_free(group);
832
0
    if ((pre_comp = ec_pre_comp_new(group)) == NULL)
833
0
        return 0;
834
835
0
    generator = EC_GROUP_get0_generator(group);
836
0
    if (generator == NULL) {
837
0
        ERR_raise(ERR_LIB_EC, EC_R_UNDEFINED_GENERATOR);
838
0
        goto err;
839
0
    }
840
841
0
#ifndef FIPS_MODULE
842
0
    if (ctx == NULL)
843
0
        ctx = new_ctx = BN_CTX_new();
844
0
#endif
845
0
    if (ctx == NULL)
846
0
        goto err;
847
848
0
    BN_CTX_start(ctx);
849
0
    used_ctx = 1;
850
851
0
    order = EC_GROUP_get0_order(group);
852
0
    if (order == NULL)
853
0
        goto err;
854
0
    if (BN_is_zero(order)) {
855
0
        ERR_raise(ERR_LIB_EC, EC_R_UNKNOWN_ORDER);
856
0
        goto err;
857
0
    }
858
859
0
    bits = BN_num_bits(order);
860
    /*
861
     * The following parameters mean we precompute (approximately) one point
862
     * per bit. TBD: The combination 8, 4 is perfect for 160 bits; for other
863
     * bit lengths, other parameter combinations might provide better
864
     * efficiency.
865
     */
866
0
    blocksize = 8;
867
0
    w = 4;
868
0
    if (EC_window_bits_for_scalar_size(bits) > w) {
869
        /* let's not make the window too small ... */
870
0
        w = EC_window_bits_for_scalar_size(bits);
871
0
    }
872
873
0
    numblocks = (bits + blocksize - 1) / blocksize; /* max. number of blocks
874
                                                     * to use for wNAF
875
                                                     * splitting */
876
877
0
    pre_points_per_block = (size_t)1 << (w - 1);
878
0
    num = pre_points_per_block * numblocks; /* number of points to compute
879
                                             * and store */
880
881
0
    points = OPENSSL_malloc_array(num + 1, sizeof(*points));
882
0
    if (points == NULL)
883
0
        goto err;
884
885
0
    var = points;
886
0
    var[num] = NULL; /* pivot */
887
0
    for (i = 0; i < num; i++) {
888
0
        if ((var[i] = EC_POINT_new(group)) == NULL) {
889
0
            ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
890
0
            goto err;
891
0
        }
892
0
    }
893
894
0
    if ((tmp_point = EC_POINT_new(group)) == NULL
895
0
        || (base = EC_POINT_new(group)) == NULL) {
896
0
        ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
897
0
        goto err;
898
0
    }
899
900
0
    if (!EC_POINT_copy(base, generator))
901
0
        goto err;
902
903
    /* do the precomputation */
904
0
    for (i = 0; i < numblocks; i++) {
905
0
        size_t j;
906
907
0
        if (!EC_POINT_dbl(group, tmp_point, base, ctx))
908
0
            goto err;
909
910
0
        if (!EC_POINT_copy(*var++, base))
911
0
            goto err;
912
913
0
        for (j = 1; j < pre_points_per_block; j++, var++) {
914
            /*
915
             * calculate odd multiples of the current base point
916
             */
917
0
            if (!EC_POINT_add(group, *var, tmp_point, *(var - 1), ctx))
918
0
                goto err;
919
0
        }
920
921
0
        if (i < numblocks - 1) {
922
            /*
923
             * get the next base (multiply current one by 2^blocksize)
924
             */
925
0
            size_t k;
926
927
0
            if (blocksize <= 2) {
928
0
                ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
929
0
                goto err;
930
0
            }
931
932
0
            if (!EC_POINT_dbl(group, base, tmp_point, ctx))
933
0
                goto err;
934
0
            for (k = 2; k < blocksize; k++) {
935
0
                if (!EC_POINT_dbl(group, base, base, ctx))
936
0
                    goto err;
937
0
            }
938
0
        }
939
0
    }
940
941
0
    if (group->meth->points_make_affine == NULL
942
0
        || !group->meth->points_make_affine(group, num, points, ctx))
943
0
        goto err;
944
945
0
    pre_comp->group = group;
946
0
    pre_comp->blocksize = blocksize;
947
0
    pre_comp->numblocks = numblocks;
948
0
    pre_comp->w = w;
949
0
    pre_comp->points = points;
950
0
    points = NULL;
951
0
    pre_comp->num = num;
952
0
    SETPRECOMP(group, ec, pre_comp);
953
0
    pre_comp = NULL;
954
0
    ret = 1;
955
956
0
err:
957
0
    if (used_ctx)
958
0
        BN_CTX_end(ctx);
959
0
#ifndef FIPS_MODULE
960
0
    BN_CTX_free(new_ctx);
961
0
#endif
962
0
    EC_ec_pre_comp_free(pre_comp);
963
0
    if (points) {
964
0
        EC_POINT **p;
965
966
0
        for (p = points; *p != NULL; p++)
967
0
            EC_POINT_free(*p);
968
0
        OPENSSL_free(points);
969
0
    }
970
0
    EC_POINT_free(tmp_point);
971
0
    EC_POINT_free(base);
972
0
    return ret;
973
0
}
974
975
int ossl_ec_wNAF_have_precompute_mult(const EC_GROUP *group)
976
0
{
977
    return HAVEPRECOMP(group, ec);
978
0
}