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