1 /* Originally written by Bodo Moeller for the OpenSSL project.
2  * ====================================================================
3  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  *
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in
14  *    the documentation and/or other materials provided with the
15  *    distribution.
16  *
17  * 3. All advertising materials mentioning features or use of this
18  *    software must display the following acknowledgment:
19  *    "This product includes software developed by the OpenSSL Project
20  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
21  *
22  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
23  *    endorse or promote products derived from this software without
24  *    prior written permission. For written permission, please contact
25  *    openssl-core@openssl.org.
26  *
27  * 5. Products derived from this software may not be called "OpenSSL"
28  *    nor may "OpenSSL" appear in their names without prior written
29  *    permission of the OpenSSL Project.
30  *
31  * 6. Redistributions of any form whatsoever must retain the following
32  *    acknowledgment:
33  *    "This product includes software developed by the OpenSSL Project
34  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
37  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
38  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
39  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
42  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
43  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
44  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
45  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
46  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
47  * OF THE POSSIBILITY OF SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This product includes cryptographic software written by Eric Young
51  * (eay@cryptsoft.com).  This product includes software written by Tim
52  * Hudson (tjh@cryptsoft.com).
53  *
54  */
55 /* ====================================================================
56  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
57  *
58  * Portions of the attached software ("Contribution") are developed by
59  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
60  *
61  * The Contribution is licensed pursuant to the OpenSSL open source
62  * license provided above.
63  *
64  * The elliptic curve binary polynomial software is originally written by
65  * Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems
66  * Laboratories. */
67 
68 #include <openssl/ec.h>
69 
70 #include <string.h>
71 
72 #include <openssl/bn.h>
73 #include <openssl/err.h>
74 #include <openssl/mem.h>
75 #include <openssl/thread.h>
76 
77 #include "internal.h"
78 #include "../internal.h"
79 
80 
81 /* This file implements the wNAF-based interleaving multi-exponentation method
82  * (<URL:http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#multiexp>);
83  * for multiplication with precomputation, we use wNAF splitting
84  * (<URL:http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#fastexp>).
85  * */
86 
87 /* structure for precomputed multiples of the generator */
88 typedef struct ec_pre_comp_st {
89   size_t blocksize;      /* block size for wNAF splitting */
90   size_t numblocks; /* max. number of blocks for which we have precomputation */
91   size_t w;         /* window size */
92   EC_POINT **points; /* array with pre-calculated multiples of generator:
93                       * 'num' pointers to EC_POINT objects followed by a NULL */
94   size_t num; /* numblocks * 2^(w-1) */
95   CRYPTO_refcount_t references;
96 } EC_PRE_COMP;
97 
ec_pre_comp_new(void)98 static EC_PRE_COMP *ec_pre_comp_new(void) {
99   EC_PRE_COMP *ret = NULL;
100 
101   ret = (EC_PRE_COMP *)OPENSSL_malloc(sizeof(EC_PRE_COMP));
102   if (!ret) {
103     OPENSSL_PUT_ERROR(EC, ec_pre_comp_new, ERR_R_MALLOC_FAILURE);
104     return ret;
105   }
106   ret->blocksize = 8; /* default */
107   ret->numblocks = 0;
108   ret->w = 4; /* default */
109   ret->points = NULL;
110   ret->num = 0;
111   ret->references = 1;
112   return ret;
113 }
114 
ec_pre_comp_dup(EC_PRE_COMP * pre_comp)115 void *ec_pre_comp_dup(EC_PRE_COMP *pre_comp) {
116   if (pre_comp == NULL) {
117     return NULL;
118   }
119 
120   CRYPTO_refcount_inc(&pre_comp->references);
121   return pre_comp;
122 }
123 
ec_pre_comp_free(EC_PRE_COMP * pre_comp)124 void ec_pre_comp_free(EC_PRE_COMP *pre_comp) {
125   if (pre_comp == NULL ||
126       !CRYPTO_refcount_dec_and_test_zero(&pre_comp->references)) {
127     return;
128   }
129 
130   if (pre_comp->points) {
131     EC_POINT **p;
132 
133     for (p = pre_comp->points; *p != NULL; p++) {
134       EC_POINT_free(*p);
135     }
136     OPENSSL_free(pre_comp->points);
137   }
138   OPENSSL_free(pre_comp);
139 }
140 
141 
142 /* Determine the modified width-(w+1) Non-Adjacent Form (wNAF) of 'scalar'.
143  * This is an array  r[]  of values that are either zero or odd with an
144  * absolute value less than  2^w  satisfying
145  *     scalar = \sum_j r[j]*2^j
146  * where at most one of any  w+1  consecutive digits is non-zero
147  * with the exception that the most significant digit may be only
148  * w-1 zeros away from that next non-zero digit.
149  */
compute_wNAF(const BIGNUM * scalar,int w,size_t * ret_len)150 static signed char *compute_wNAF(const BIGNUM *scalar, int w, size_t *ret_len) {
151   int window_val;
152   int ok = 0;
153   signed char *r = NULL;
154   int sign = 1;
155   int bit, next_bit, mask;
156   size_t len = 0, j;
157 
158   if (BN_is_zero(scalar)) {
159     r = OPENSSL_malloc(1);
160     if (!r) {
161       OPENSSL_PUT_ERROR(EC, compute_wNAF, ERR_R_MALLOC_FAILURE);
162       goto err;
163     }
164     r[0] = 0;
165     *ret_len = 1;
166     return r;
167   }
168 
169   if (w <= 0 || w > 7) /* 'signed char' can represent integers with absolute
170                           values less than 2^7 */
171   {
172     OPENSSL_PUT_ERROR(EC, compute_wNAF, ERR_R_INTERNAL_ERROR);
173     goto err;
174   }
175   bit = 1 << w;        /* at most 128 */
176   next_bit = bit << 1; /* at most 256 */
177   mask = next_bit - 1; /* at most 255 */
178 
179   if (BN_is_negative(scalar)) {
180     sign = -1;
181   }
182 
183   if (scalar->d == NULL || scalar->top == 0) {
184     OPENSSL_PUT_ERROR(EC, compute_wNAF, ERR_R_INTERNAL_ERROR);
185     goto err;
186   }
187 
188   len = BN_num_bits(scalar);
189   r = OPENSSL_malloc(
190       len +
191       1); /* modified wNAF may be one digit longer than binary representation
192            * (*ret_len will be set to the actual length, i.e. at most
193            * BN_num_bits(scalar) + 1) */
194   if (r == NULL) {
195     OPENSSL_PUT_ERROR(EC, compute_wNAF, ERR_R_MALLOC_FAILURE);
196     goto err;
197   }
198   window_val = scalar->d[0] & mask;
199   j = 0;
200   while ((window_val != 0) ||
201          (j + w + 1 < len)) /* if j+w+1 >= len, window_val will not increase */
202   {
203     int digit = 0;
204 
205     /* 0 <= window_val <= 2^(w+1) */
206 
207     if (window_val & 1) {
208       /* 0 < window_val < 2^(w+1) */
209 
210       if (window_val & bit) {
211         digit = window_val - next_bit; /* -2^w < digit < 0 */
212 
213 #if 1 /* modified wNAF */
214         if (j + w + 1 >= len) {
215           /* special case for generating modified wNAFs:
216            * no new bits will be added into window_val,
217            * so using a positive digit here will decrease
218            * the total length of the representation */
219 
220           digit = window_val & (mask >> 1); /* 0 < digit < 2^w */
221         }
222 #endif
223       } else {
224         digit = window_val; /* 0 < digit < 2^w */
225       }
226 
227       if (digit <= -bit || digit >= bit || !(digit & 1)) {
228         OPENSSL_PUT_ERROR(EC, compute_wNAF, ERR_R_INTERNAL_ERROR);
229         goto err;
230       }
231 
232       window_val -= digit;
233 
234       /* now window_val is 0 or 2^(w+1) in standard wNAF generation;
235        * for modified window NAFs, it may also be 2^w
236        */
237       if (window_val != 0 && window_val != next_bit && window_val != bit) {
238         OPENSSL_PUT_ERROR(EC, compute_wNAF, ERR_R_INTERNAL_ERROR);
239         goto err;
240       }
241     }
242 
243     r[j++] = sign * digit;
244 
245     window_val >>= 1;
246     window_val += bit * BN_is_bit_set(scalar, j + w);
247 
248     if (window_val > next_bit) {
249       OPENSSL_PUT_ERROR(EC, compute_wNAF, ERR_R_INTERNAL_ERROR);
250       goto err;
251     }
252   }
253 
254   if (j > len + 1) {
255     OPENSSL_PUT_ERROR(EC, compute_wNAF, ERR_R_INTERNAL_ERROR);
256     goto err;
257   }
258   len = j;
259   ok = 1;
260 
261 err:
262   if (!ok) {
263     OPENSSL_free(r);
264     r = NULL;
265   }
266   if (ok) {
267     *ret_len = len;
268   }
269   return r;
270 }
271 
272 
273 /* TODO: table should be optimised for the wNAF-based implementation,
274  *       sometimes smaller windows will give better performance
275  *       (thus the boundaries should be increased)
276  */
277 #define EC_window_bits_for_scalar_size(b)                                      \
278   ((size_t)((b) >= 2000 ? 6 : (b) >= 800 ? 5 : (b) >= 300                      \
279                                                    ? 4                         \
280                                                    : (b) >= 70 ? 3 : (b) >= 20 \
281                                                                          ? 2   \
282                                                                          : 1))
283 
284 /* Compute
285  *      \sum scalars[i]*points[i],
286  * also including
287  *      scalar*generator
288  * in the addition if scalar != NULL
289  */
ec_wNAF_mul(const EC_GROUP * group,EC_POINT * r,const BIGNUM * scalar,size_t num,const EC_POINT * points[],const BIGNUM * scalars[],BN_CTX * ctx)290 int ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
291                 size_t num, const EC_POINT *points[], const BIGNUM *scalars[],
292                 BN_CTX *ctx) {
293   BN_CTX *new_ctx = NULL;
294   const EC_POINT *generator = NULL;
295   EC_POINT *tmp = NULL;
296   size_t totalnum;
297   size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */
298   size_t pre_points_per_block = 0;
299   size_t i, j;
300   int k;
301   int r_is_inverted = 0;
302   int r_is_at_infinity = 1;
303   size_t *wsize = NULL;      /* individual window sizes */
304   signed char **wNAF = NULL; /* individual wNAFs */
305   size_t *wNAF_len = NULL;
306   size_t max_len = 0;
307   size_t num_val;
308   EC_POINT **val = NULL; /* precomputation */
309   EC_POINT **v;
310   EC_POINT ***val_sub =
311       NULL; /* pointers to sub-arrays of 'val' or 'pre_comp->points' */
312   const EC_PRE_COMP *pre_comp = NULL;
313   int num_scalar = 0; /* flag: will be set to 1 if 'scalar' must be treated like
314                        * other scalars,
315                        * i.e. precomputation is not available */
316   int ret = 0;
317 
318   if (group->meth != r->meth) {
319     OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, EC_R_INCOMPATIBLE_OBJECTS);
320     return 0;
321   }
322 
323   if ((scalar == NULL) && (num == 0)) {
324     return EC_POINT_set_to_infinity(group, r);
325   }
326 
327   for (i = 0; i < num; i++) {
328     if (group->meth != points[i]->meth) {
329       OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, EC_R_INCOMPATIBLE_OBJECTS);
330       return 0;
331     }
332   }
333 
334   if (ctx == NULL) {
335     ctx = new_ctx = BN_CTX_new();
336     if (ctx == NULL) {
337       goto err;
338     }
339   }
340 
341   if (scalar != NULL) {
342     generator = EC_GROUP_get0_generator(group);
343     if (generator == NULL) {
344       OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, EC_R_UNDEFINED_GENERATOR);
345       goto err;
346     }
347 
348     /* look if we can use precomputed multiples of generator */
349 
350     pre_comp = group->pre_comp;
351 
352     if (pre_comp && pre_comp->numblocks &&
353         (EC_POINT_cmp(group, generator, pre_comp->points[0], ctx) == 0)) {
354       blocksize = pre_comp->blocksize;
355 
356       /* determine maximum number of blocks that wNAF splitting may yield
357        * (NB: maximum wNAF length is bit length plus one) */
358       numblocks = (BN_num_bits(scalar) / blocksize) + 1;
359 
360       /* we cannot use more blocks than we have precomputation for */
361       if (numblocks > pre_comp->numblocks) {
362         numblocks = pre_comp->numblocks;
363       }
364 
365       pre_points_per_block = (size_t)1 << (pre_comp->w - 1);
366 
367       /* check that pre_comp looks sane */
368       if (pre_comp->num != (pre_comp->numblocks * pre_points_per_block)) {
369         OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, ERR_R_INTERNAL_ERROR);
370         goto err;
371       }
372     } else {
373       /* can't use precomputation */
374       pre_comp = NULL;
375       numblocks = 1;
376       num_scalar = 1; /* treat 'scalar' like 'num'-th element of 'scalars' */
377     }
378   }
379 
380   totalnum = num + numblocks;
381 
382   wsize = OPENSSL_malloc(totalnum * sizeof wsize[0]);
383   wNAF_len = OPENSSL_malloc(totalnum * sizeof wNAF_len[0]);
384   wNAF = OPENSSL_malloc((totalnum + 1) *
385                         sizeof wNAF[0]); /* includes space for pivot */
386   val_sub = OPENSSL_malloc(totalnum * sizeof val_sub[0]);
387 
388   /* Ensure wNAF is initialised in case we end up going to err. */
389   if (wNAF) {
390     wNAF[0] = NULL; /* preliminary pivot */
391   }
392 
393   if (!wsize || !wNAF_len || !wNAF || !val_sub) {
394     OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, ERR_R_MALLOC_FAILURE);
395     goto err;
396   }
397 
398   /* num_val will be the total number of temporarily precomputed points */
399   num_val = 0;
400 
401   for (i = 0; i < num + num_scalar; i++) {
402     size_t bits;
403 
404     bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
405     wsize[i] = EC_window_bits_for_scalar_size(bits);
406     num_val += (size_t)1 << (wsize[i] - 1);
407     wNAF[i + 1] = NULL; /* make sure we always have a pivot */
408     wNAF[i] =
409         compute_wNAF((i < num ? scalars[i] : scalar), wsize[i], &wNAF_len[i]);
410     if (wNAF[i] == NULL) {
411       goto err;
412     }
413     if (wNAF_len[i] > max_len) {
414       max_len = wNAF_len[i];
415     }
416   }
417 
418   if (numblocks) {
419     /* we go here iff scalar != NULL */
420 
421     if (pre_comp == NULL) {
422       if (num_scalar != 1) {
423         OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, ERR_R_INTERNAL_ERROR);
424         goto err;
425       }
426       /* we have already generated a wNAF for 'scalar' */
427     } else {
428       signed char *tmp_wNAF = NULL;
429       size_t tmp_len = 0;
430 
431       if (num_scalar != 0) {
432         OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, ERR_R_INTERNAL_ERROR);
433         goto err;
434       }
435 
436       /* use the window size for which we have precomputation */
437       wsize[num] = pre_comp->w;
438       tmp_wNAF = compute_wNAF(scalar, wsize[num], &tmp_len);
439       if (!tmp_wNAF) {
440         goto err;
441       }
442 
443       if (tmp_len <= max_len) {
444         /* One of the other wNAFs is at least as long
445          * as the wNAF belonging to the generator,
446          * so wNAF splitting will not buy us anything. */
447 
448         numblocks = 1; /* don't use wNAF splitting */
449         totalnum = num + numblocks;
450         wNAF[num] = tmp_wNAF;
451         wNAF[num + 1] = NULL;
452         wNAF_len[num] = tmp_len;
453         /* pre_comp->points starts with the points that we need here: */
454         val_sub[num] = pre_comp->points;
455       } else {
456         /* don't include tmp_wNAF directly into wNAF array
457          * - use wNAF splitting and include the blocks */
458 
459         signed char *pp;
460         EC_POINT **tmp_points;
461 
462         if (tmp_len < numblocks * blocksize) {
463           /* possibly we can do with fewer blocks than estimated */
464           numblocks = (tmp_len + blocksize - 1) / blocksize;
465           if (numblocks > pre_comp->numblocks) {
466             OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, ERR_R_INTERNAL_ERROR);
467             goto err;
468           }
469           totalnum = num + numblocks;
470         }
471 
472         /* split wNAF in 'numblocks' parts */
473         pp = tmp_wNAF;
474         tmp_points = pre_comp->points;
475 
476         for (i = num; i < totalnum; i++) {
477           if (i < totalnum - 1) {
478             wNAF_len[i] = blocksize;
479             if (tmp_len < blocksize) {
480               OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, ERR_R_INTERNAL_ERROR);
481               goto err;
482             }
483             tmp_len -= blocksize;
484           } else {
485             /* last block gets whatever is left
486              * (this could be more or less than 'blocksize'!) */
487             wNAF_len[i] = tmp_len;
488           }
489 
490           wNAF[i + 1] = NULL;
491           wNAF[i] = OPENSSL_malloc(wNAF_len[i]);
492           if (wNAF[i] == NULL) {
493             OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, ERR_R_MALLOC_FAILURE);
494             OPENSSL_free(tmp_wNAF);
495             goto err;
496           }
497           memcpy(wNAF[i], pp, wNAF_len[i]);
498           if (wNAF_len[i] > max_len) {
499             max_len = wNAF_len[i];
500           }
501 
502           if (*tmp_points == NULL) {
503             OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, ERR_R_INTERNAL_ERROR);
504             OPENSSL_free(tmp_wNAF);
505             goto err;
506           }
507           val_sub[i] = tmp_points;
508           tmp_points += pre_points_per_block;
509           pp += blocksize;
510         }
511         OPENSSL_free(tmp_wNAF);
512       }
513     }
514   }
515 
516   /* All points we precompute now go into a single array 'val'.
517    * 'val_sub[i]' is a pointer to the subarray for the i-th point,
518    * or to a subarray of 'pre_comp->points' if we already have precomputation.
519    */
520   val = OPENSSL_malloc((num_val + 1) * sizeof val[0]);
521   if (val == NULL) {
522     OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, ERR_R_MALLOC_FAILURE);
523     goto err;
524   }
525   val[num_val] = NULL; /* pivot element */
526 
527   /* allocate points for precomputation */
528   v = val;
529   for (i = 0; i < num + num_scalar; i++) {
530     val_sub[i] = v;
531     for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) {
532       *v = EC_POINT_new(group);
533       if (*v == NULL) {
534         goto err;
535       }
536       v++;
537     }
538   }
539   if (!(v == val + num_val)) {
540     OPENSSL_PUT_ERROR(EC, ec_wNAF_mul, ERR_R_INTERNAL_ERROR);
541     goto err;
542   }
543 
544   if (!(tmp = EC_POINT_new(group))) {
545     goto err;
546   }
547 
548   /* prepare precomputed values:
549    *    val_sub[i][0] :=     points[i]
550    *    val_sub[i][1] := 3 * points[i]
551    *    val_sub[i][2] := 5 * points[i]
552    *    ...
553    */
554   for (i = 0; i < num + num_scalar; i++) {
555     if (i < num) {
556       if (!EC_POINT_copy(val_sub[i][0], points[i])) {
557         goto err;
558       }
559     } else if (!EC_POINT_copy(val_sub[i][0], generator)) {
560       goto err;
561     }
562 
563     if (wsize[i] > 1) {
564       if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx)) {
565         goto err;
566       }
567       for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) {
568         if (!EC_POINT_add(group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx)) {
569           goto err;
570         }
571       }
572     }
573   }
574 
575 #if 1 /* optional; EC_window_bits_for_scalar_size assumes we do this step */
576   if (!EC_POINTs_make_affine(group, num_val, val, ctx)) {
577     goto err;
578   }
579 #endif
580 
581   r_is_at_infinity = 1;
582 
583   for (k = max_len - 1; k >= 0; k--) {
584     if (!r_is_at_infinity && !EC_POINT_dbl(group, r, r, ctx)) {
585       goto err;
586     }
587 
588     for (i = 0; i < totalnum; i++) {
589       if (wNAF_len[i] > (size_t)k) {
590         int digit = wNAF[i][k];
591         int is_neg;
592 
593         if (digit) {
594           is_neg = digit < 0;
595 
596           if (is_neg) {
597             digit = -digit;
598           }
599 
600           if (is_neg != r_is_inverted) {
601             if (!r_is_at_infinity && !EC_POINT_invert(group, r, ctx)) {
602               goto err;
603             }
604             r_is_inverted = !r_is_inverted;
605           }
606 
607           /* digit > 0 */
608 
609           if (r_is_at_infinity) {
610             if (!EC_POINT_copy(r, val_sub[i][digit >> 1])) {
611               goto err;
612             }
613             r_is_at_infinity = 0;
614           } else {
615             if (!EC_POINT_add(group, r, r, val_sub[i][digit >> 1], ctx)) {
616               goto err;
617             }
618           }
619         }
620       }
621     }
622   }
623 
624   if (r_is_at_infinity) {
625     if (!EC_POINT_set_to_infinity(group, r)) {
626       goto err;
627     }
628   } else if (r_is_inverted && !EC_POINT_invert(group, r, ctx)) {
629     goto err;
630   }
631 
632   ret = 1;
633 
634 err:
635   BN_CTX_free(new_ctx);
636   EC_POINT_free(tmp);
637   OPENSSL_free(wsize);
638   OPENSSL_free(wNAF_len);
639   if (wNAF != NULL) {
640     signed char **w;
641 
642     for (w = wNAF; *w != NULL; w++) {
643       OPENSSL_free(*w);
644     }
645 
646     OPENSSL_free(wNAF);
647   }
648   if (val != NULL) {
649     for (v = val; *v != NULL; v++) {
650       EC_POINT_clear_free(*v);
651     }
652 
653     OPENSSL_free(val);
654   }
655   OPENSSL_free(val_sub);
656   return ret;
657 }
658 
659 
660 /* ec_wNAF_precompute_mult()
661  * creates an EC_PRE_COMP object with preprecomputed multiples of the generator
662  * for use with wNAF splitting as implemented in ec_wNAF_mul().
663  *
664  * 'pre_comp->points' is an array of multiples of the generator
665  * of the following form:
666  * points[0] =     generator;
667  * points[1] = 3 * generator;
668  * ...
669  * points[2^(w-1)-1] =     (2^(w-1)-1) * generator;
670  * points[2^(w-1)]   =     2^blocksize * generator;
671  * points[2^(w-1)+1] = 3 * 2^blocksize * generator;
672  * ...
673  * points[2^(w-1)*(numblocks-1)-1] = (2^(w-1)) *  2^(blocksize*(numblocks-2)) *
674  *generator
675  * points[2^(w-1)*(numblocks-1)]   =              2^(blocksize*(numblocks-1)) *
676  *generator
677  * ...
678  * points[2^(w-1)*numblocks-1]     = (2^(w-1)) *  2^(blocksize*(numblocks-1)) *
679  *generator
680  * points[2^(w-1)*numblocks]       = NULL
681  */
ec_wNAF_precompute_mult(EC_GROUP * group,BN_CTX * ctx)682 int ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *ctx) {
683   const EC_POINT *generator;
684   EC_POINT *tmp_point = NULL, *base = NULL, **var;
685   BN_CTX *new_ctx = NULL;
686   BIGNUM *order;
687   size_t i, bits, w, pre_points_per_block, blocksize, numblocks, num;
688   EC_POINT **points = NULL;
689   EC_PRE_COMP *pre_comp;
690   int ret = 0;
691 
692   /* if there is an old EC_PRE_COMP object, throw it away */
693   ec_pre_comp_free(group->pre_comp);
694   group->pre_comp = NULL;
695 
696   generator = EC_GROUP_get0_generator(group);
697   if (generator == NULL) {
698     OPENSSL_PUT_ERROR(EC, ec_wNAF_precompute_mult, EC_R_UNDEFINED_GENERATOR);
699     return 0;
700   }
701 
702   pre_comp = ec_pre_comp_new();
703   if (pre_comp == NULL) {
704     return 0;
705   }
706 
707   if (ctx == NULL) {
708     ctx = new_ctx = BN_CTX_new();
709     if (ctx == NULL) {
710       goto err;
711     }
712   }
713 
714   BN_CTX_start(ctx);
715   order = BN_CTX_get(ctx);
716   if (order == NULL) {
717     goto err;
718   }
719 
720   if (!EC_GROUP_get_order(group, order, ctx)) {
721     goto err;
722   }
723   if (BN_is_zero(order)) {
724     OPENSSL_PUT_ERROR(EC, ec_wNAF_precompute_mult, EC_R_UNKNOWN_ORDER);
725     goto err;
726   }
727 
728   bits = BN_num_bits(order);
729   /* The following parameters mean we precompute (approximately)
730    * one point per bit.
731    *
732    * TBD: The combination  8, 4  is perfect for 160 bits; for other
733    * bit lengths, other parameter combinations might provide better
734    * efficiency.
735    */
736   blocksize = 8;
737   w = 4;
738   if (EC_window_bits_for_scalar_size(bits) > w) {
739     /* let's not make the window too small ... */
740     w = EC_window_bits_for_scalar_size(bits);
741   }
742 
743   numblocks = (bits + blocksize - 1) /
744               blocksize; /* max. number of blocks to use for wNAF splitting */
745 
746   pre_points_per_block = (size_t)1 << (w - 1);
747   num = pre_points_per_block *
748         numblocks; /* number of points to compute and store */
749 
750   points = OPENSSL_malloc(sizeof(EC_POINT *) * (num + 1));
751   if (!points) {
752     OPENSSL_PUT_ERROR(EC, ec_wNAF_precompute_mult, ERR_R_MALLOC_FAILURE);
753     goto err;
754   }
755 
756   var = points;
757   var[num] = NULL; /* pivot */
758   for (i = 0; i < num; i++) {
759     if ((var[i] = EC_POINT_new(group)) == NULL) {
760       OPENSSL_PUT_ERROR(EC, ec_wNAF_precompute_mult, ERR_R_MALLOC_FAILURE);
761       goto err;
762     }
763   }
764 
765   if (!(tmp_point = EC_POINT_new(group)) || !(base = EC_POINT_new(group))) {
766     OPENSSL_PUT_ERROR(EC, ec_wNAF_precompute_mult, ERR_R_MALLOC_FAILURE);
767     goto err;
768   }
769 
770   if (!EC_POINT_copy(base, generator)) {
771     goto err;
772   }
773 
774   /* do the precomputation */
775   for (i = 0; i < numblocks; i++) {
776     size_t j;
777 
778     if (!EC_POINT_dbl(group, tmp_point, base, ctx)) {
779       goto err;
780     }
781 
782     if (!EC_POINT_copy(*var++, base)) {
783       goto err;
784     }
785 
786     for (j = 1; j < pre_points_per_block; j++, var++) {
787       /* calculate odd multiples of the current base point */
788       if (!EC_POINT_add(group, *var, tmp_point, *(var - 1), ctx)) {
789         goto err;
790       }
791     }
792 
793     if (i < numblocks - 1) {
794       /* get the next base (multiply current one by 2^blocksize) */
795       size_t k;
796 
797       if (blocksize <= 2) {
798         OPENSSL_PUT_ERROR(EC, ec_wNAF_precompute_mult, ERR_R_INTERNAL_ERROR);
799         goto err;
800       }
801 
802       if (!EC_POINT_dbl(group, base, tmp_point, ctx)) {
803         goto err;
804       }
805       for (k = 2; k < blocksize; k++) {
806         if (!EC_POINT_dbl(group, base, base, ctx)) {
807           goto err;
808         }
809       }
810     }
811   }
812 
813   if (!EC_POINTs_make_affine(group, num, points, ctx)) {
814     goto err;
815   }
816 
817   pre_comp->blocksize = blocksize;
818   pre_comp->numblocks = numblocks;
819   pre_comp->w = w;
820   pre_comp->points = points;
821   points = NULL;
822   pre_comp->num = num;
823 
824   group->pre_comp = pre_comp;
825   pre_comp = NULL;
826 
827   ret = 1;
828 
829 err:
830   if (ctx != NULL) {
831     BN_CTX_end(ctx);
832   }
833   BN_CTX_free(new_ctx);
834   ec_pre_comp_free(pre_comp);
835   if (points) {
836     EC_POINT **p;
837 
838     for (p = points; *p != NULL; p++) {
839       EC_POINT_free(*p);
840     }
841     OPENSSL_free(points);
842   }
843   EC_POINT_free(tmp_point);
844   EC_POINT_free(base);
845   return ret;
846 }
847 
848 
ec_wNAF_have_precompute_mult(const EC_GROUP * group)849 int ec_wNAF_have_precompute_mult(const EC_GROUP *group) {
850   return group->pre_comp != NULL;
851 }
852