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