Coverage Report

Created: 2018-08-29 13:53

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