Coverage Report

Created: 2023-06-08 06:40

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