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