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