Standardize syntax of sizeof(foo)
[openssl.git] / crypto / ec / ec_mult.c
1 /*
2  * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 /* ====================================================================
11  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
12  * Portions of this software developed by SUN MICROSYSTEMS, INC.,
13  * and contributed to the OpenSSL project.
14  */
15
16 #include <string.h>
17 #include <openssl/err.h>
18
19 #include "internal/cryptlib.h"
20 #include "internal/bn_int.h"
21 #include "ec_lcl.h"
22
23 /*
24  * This file implements the wNAF-based interleaving multi-exponentiation method
25  * Formerly at:
26  *   http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#multiexp
27  * You might now find it here:
28  *   http://link.springer.com/chapter/10.1007%2F3-540-45537-X_13
29  *   http://www.bmoeller.de/pdf/TI-01-08.multiexp.pdf
30  * For multiplication with precomputation, we use wNAF splitting, formerly at:
31  *   http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#fastexp
32  */
33
34 /* structure for precomputed multiples of the generator */
35 struct ec_pre_comp_st {
36     const EC_GROUP *group;      /* parent EC_GROUP object */
37     size_t blocksize;           /* block size for wNAF splitting */
38     size_t numblocks;           /* max. number of blocks for which we have
39                                  * precomputation */
40     size_t w;                   /* window size */
41     EC_POINT **points;          /* array with pre-calculated multiples of
42                                  * generator: 'num' pointers to EC_POINT
43                                  * objects followed by a NULL */
44     size_t num;                 /* numblocks * 2^(w-1) */
45     int references;
46     CRYPTO_RWLOCK *lock;
47 };
48
49 static EC_PRE_COMP *ec_pre_comp_new(const EC_GROUP *group)
50 {
51     EC_PRE_COMP *ret = NULL;
52
53     if (!group)
54         return NULL;
55
56     ret = OPENSSL_zalloc(sizeof(*ret));
57     if (ret == NULL) {
58         ECerr(EC_F_EC_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
59         return ret;
60     }
61
62     ret->group = group;
63     ret->blocksize = 8;         /* default */
64     ret->w = 4;                 /* default */
65     ret->references = 1;
66
67     ret->lock = CRYPTO_THREAD_lock_new();
68     if (ret->lock == NULL) {
69         ECerr(EC_F_EC_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
70         OPENSSL_free(ret);
71         return NULL;
72     }
73     return ret;
74 }
75
76 EC_PRE_COMP *EC_ec_pre_comp_dup(EC_PRE_COMP *pre)
77 {
78     int i;
79     if (pre != NULL)
80         CRYPTO_atomic_add(&pre->references, 1, &i, pre->lock);
81     return pre;
82 }
83
84 void EC_ec_pre_comp_free(EC_PRE_COMP *pre)
85 {
86     int i;
87
88     if (pre == NULL)
89         return;
90
91     CRYPTO_atomic_add(&pre->references, -1, &i, pre->lock);
92     REF_PRINT_COUNT("EC_ec", pre);
93     if (i > 0)
94         return;
95     REF_ASSERT_ISNT(i < 0);
96
97     if (pre->points != NULL) {
98         EC_POINT **pts;
99
100         for (pts = pre->points; *pts != NULL; pts++)
101             EC_POINT_free(*pts);
102         OPENSSL_free(pre->points);
103     }
104     CRYPTO_THREAD_lock_free(pre->lock);
105     OPENSSL_free(pre);
106 }
107
108 /*
109  * TODO: table should be optimised for the wNAF-based implementation,
110  * sometimes smaller windows will give better performance (thus the
111  * boundaries should be increased)
112  */
113 #define EC_window_bits_for_scalar_size(b) \
114                 ((size_t) \
115                  ((b) >= 2000 ? 6 : \
116                   (b) >=  800 ? 5 : \
117                   (b) >=  300 ? 4 : \
118                   (b) >=   70 ? 3 : \
119                   (b) >=   20 ? 2 : \
120                   1))
121
122 /*-
123  * Compute
124  *      \sum scalars[i]*points[i],
125  * also including
126  *      scalar*generator
127  * in the addition if scalar != NULL
128  */
129 int ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
130                 size_t num, const EC_POINT *points[], const BIGNUM *scalars[],
131                 BN_CTX *ctx)
132 {
133     BN_CTX *new_ctx = NULL;
134     const EC_POINT *generator = NULL;
135     EC_POINT *tmp = NULL;
136     size_t totalnum;
137     size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */
138     size_t pre_points_per_block = 0;
139     size_t i, j;
140     int k;
141     int r_is_inverted = 0;
142     int r_is_at_infinity = 1;
143     size_t *wsize = NULL;       /* individual window sizes */
144     signed char **wNAF = NULL;  /* individual wNAFs */
145     size_t *wNAF_len = NULL;
146     size_t max_len = 0;
147     size_t num_val;
148     EC_POINT **val = NULL;      /* precomputation */
149     EC_POINT **v;
150     EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' or
151                                  * 'pre_comp->points' */
152     const EC_PRE_COMP *pre_comp = NULL;
153     int num_scalar = 0;         /* flag: will be set to 1 if 'scalar' must be
154                                  * treated like other scalars, i.e.
155                                  * precomputation is not available */
156     int ret = 0;
157
158     if (group->meth != r->meth) {
159         ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
160         return 0;
161     }
162
163     if ((scalar == NULL) && (num == 0)) {
164         return EC_POINT_set_to_infinity(group, r);
165     }
166
167     for (i = 0; i < num; i++) {
168         if (group->meth != points[i]->meth) {
169             ECerr(EC_F_EC_WNAF_MUL, EC_R_INCOMPATIBLE_OBJECTS);
170             return 0;
171         }
172     }
173
174     if (ctx == NULL) {
175         ctx = new_ctx = BN_CTX_new();
176         if (ctx == NULL)
177             goto err;
178     }
179
180     if (scalar != NULL) {
181         generator = EC_GROUP_get0_generator(group);
182         if (generator == NULL) {
183             ECerr(EC_F_EC_WNAF_MUL, EC_R_UNDEFINED_GENERATOR);
184             goto err;
185         }
186
187         /* look if we can use precomputed multiples of generator */
188
189         pre_comp = group->pre_comp.ec;
190         if (pre_comp && pre_comp->numblocks
191             && (EC_POINT_cmp(group, generator, pre_comp->points[0], ctx) ==
192                 0)) {
193             blocksize = pre_comp->blocksize;
194
195             /*
196              * determine maximum number of blocks that wNAF splitting may
197              * yield (NB: maximum wNAF length is bit length plus one)
198              */
199             numblocks = (BN_num_bits(scalar) / blocksize) + 1;
200
201             /*
202              * we cannot use more blocks than we have precomputation for
203              */
204             if (numblocks > pre_comp->numblocks)
205                 numblocks = pre_comp->numblocks;
206
207             pre_points_per_block = (size_t)1 << (pre_comp->w - 1);
208
209             /* check that pre_comp looks sane */
210             if (pre_comp->num != (pre_comp->numblocks * pre_points_per_block)) {
211                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
212                 goto err;
213             }
214         } else {
215             /* can't use precomputation */
216             pre_comp = NULL;
217             numblocks = 1;
218             num_scalar = 1;     /* treat 'scalar' like 'num'-th element of
219                                  * 'scalars' */
220         }
221     }
222
223     totalnum = num + numblocks;
224
225     wsize = OPENSSL_malloc(totalnum * sizeof(wsize[0]));
226     wNAF_len = OPENSSL_malloc(totalnum * sizeof(wNAF_len[0]));
227     /* include space for pivot */
228     wNAF = OPENSSL_malloc((totalnum + 1) * sizeof(wNAF[0]));
229     val_sub = OPENSSL_malloc(totalnum * sizeof(val_sub[0]));
230
231     /* Ensure wNAF is initialised in case we end up going to err */
232     if (wNAF != NULL)
233         wNAF[0] = NULL;         /* preliminary pivot */
234
235     if (wsize == NULL || wNAF_len == NULL || wNAF == NULL || val_sub == NULL) {
236         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
237         goto err;
238     }
239
240     /*
241      * num_val will be the total number of temporarily precomputed points
242      */
243     num_val = 0;
244
245     for (i = 0; i < num + num_scalar; i++) {
246         size_t bits;
247
248         bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
249         wsize[i] = EC_window_bits_for_scalar_size(bits);
250         num_val += (size_t)1 << (wsize[i] - 1);
251         wNAF[i + 1] = NULL;     /* make sure we always have a pivot */
252         wNAF[i] =
253             bn_compute_wNAF((i < num ? scalars[i] : scalar), wsize[i],
254                             &wNAF_len[i]);
255         if (wNAF[i] == NULL)
256             goto err;
257         if (wNAF_len[i] > max_len)
258             max_len = wNAF_len[i];
259     }
260
261     if (numblocks) {
262         /* we go here iff scalar != NULL */
263
264         if (pre_comp == NULL) {
265             if (num_scalar != 1) {
266                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
267                 goto err;
268             }
269             /* we have already generated a wNAF for 'scalar' */
270         } else {
271             signed char *tmp_wNAF = NULL;
272             size_t tmp_len = 0;
273
274             if (num_scalar != 0) {
275                 ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
276                 goto err;
277             }
278
279             /*
280              * use the window size for which we have precomputation
281              */
282             wsize[num] = pre_comp->w;
283             tmp_wNAF = bn_compute_wNAF(scalar, wsize[num], &tmp_len);
284             if (!tmp_wNAF)
285                 goto err;
286
287             if (tmp_len <= max_len) {
288                 /*
289                  * One of the other wNAFs is at least as long as the wNAF
290                  * belonging to the generator, so wNAF splitting will not buy
291                  * us anything.
292                  */
293
294                 numblocks = 1;
295                 totalnum = num + 1; /* don't use wNAF splitting */
296                 wNAF[num] = tmp_wNAF;
297                 wNAF[num + 1] = NULL;
298                 wNAF_len[num] = tmp_len;
299                 /*
300                  * pre_comp->points starts with the points that we need here:
301                  */
302                 val_sub[num] = pre_comp->points;
303             } else {
304                 /*
305                  * don't include tmp_wNAF directly into wNAF array - use wNAF
306                  * splitting and include the blocks
307                  */
308
309                 signed char *pp;
310                 EC_POINT **tmp_points;
311
312                 if (tmp_len < numblocks * blocksize) {
313                     /*
314                      * possibly we can do with fewer blocks than estimated
315                      */
316                     numblocks = (tmp_len + blocksize - 1) / blocksize;
317                     if (numblocks > pre_comp->numblocks) {
318                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
319                         OPENSSL_free(tmp_wNAF);
320                         goto err;
321                     }
322                     totalnum = num + numblocks;
323                 }
324
325                 /* split wNAF in 'numblocks' parts */
326                 pp = tmp_wNAF;
327                 tmp_points = pre_comp->points;
328
329                 for (i = num; i < totalnum; i++) {
330                     if (i < totalnum - 1) {
331                         wNAF_len[i] = blocksize;
332                         if (tmp_len < blocksize) {
333                             ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
334                             OPENSSL_free(tmp_wNAF);
335                             goto err;
336                         }
337                         tmp_len -= blocksize;
338                     } else
339                         /*
340                          * last block gets whatever is left (this could be
341                          * more or less than 'blocksize'!)
342                          */
343                         wNAF_len[i] = tmp_len;
344
345                     wNAF[i + 1] = NULL;
346                     wNAF[i] = OPENSSL_malloc(wNAF_len[i]);
347                     if (wNAF[i] == NULL) {
348                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
349                         OPENSSL_free(tmp_wNAF);
350                         goto err;
351                     }
352                     memcpy(wNAF[i], pp, wNAF_len[i]);
353                     if (wNAF_len[i] > max_len)
354                         max_len = wNAF_len[i];
355
356                     if (*tmp_points == NULL) {
357                         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
358                         OPENSSL_free(tmp_wNAF);
359                         goto err;
360                     }
361                     val_sub[i] = tmp_points;
362                     tmp_points += pre_points_per_block;
363                     pp += blocksize;
364                 }
365                 OPENSSL_free(tmp_wNAF);
366             }
367         }
368     }
369
370     /*
371      * All points we precompute now go into a single array 'val'.
372      * 'val_sub[i]' is a pointer to the subarray for the i-th point, or to a
373      * subarray of 'pre_comp->points' if we already have precomputation.
374      */
375     val = OPENSSL_malloc((num_val + 1) * sizeof(val[0]));
376     if (val == NULL) {
377         ECerr(EC_F_EC_WNAF_MUL, ERR_R_MALLOC_FAILURE);
378         goto err;
379     }
380     val[num_val] = NULL;        /* pivot element */
381
382     /* allocate points for precomputation */
383     v = val;
384     for (i = 0; i < num + num_scalar; i++) {
385         val_sub[i] = v;
386         for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) {
387             *v = EC_POINT_new(group);
388             if (*v == NULL)
389                 goto err;
390             v++;
391         }
392     }
393     if (!(v == val + num_val)) {
394         ECerr(EC_F_EC_WNAF_MUL, ERR_R_INTERNAL_ERROR);
395         goto err;
396     }
397
398     if ((tmp = EC_POINT_new(group)) == NULL)
399         goto err;
400
401     /*-
402      * prepare precomputed values:
403      *    val_sub[i][0] :=     points[i]
404      *    val_sub[i][1] := 3 * points[i]
405      *    val_sub[i][2] := 5 * points[i]
406      *    ...
407      */
408     for (i = 0; i < num + num_scalar; i++) {
409         if (i < num) {
410             if (!EC_POINT_copy(val_sub[i][0], points[i]))
411                 goto err;
412         } else {
413             if (!EC_POINT_copy(val_sub[i][0], generator))
414                 goto err;
415         }
416
417         if (wsize[i] > 1) {
418             if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx))
419                 goto err;
420             for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) {
421                 if (!EC_POINT_add
422                     (group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx))
423                     goto err;
424             }
425         }
426     }
427
428     if (!EC_POINTs_make_affine(group, num_val, val, ctx))
429         goto err;
430
431     r_is_at_infinity = 1;
432
433     for (k = max_len - 1; k >= 0; k--) {
434         if (!r_is_at_infinity) {
435             if (!EC_POINT_dbl(group, r, r, ctx))
436                 goto err;
437         }
438
439         for (i = 0; i < totalnum; i++) {
440             if (wNAF_len[i] > (size_t)k) {
441                 int digit = wNAF[i][k];
442                 int is_neg;
443
444                 if (digit) {
445                     is_neg = digit < 0;
446
447                     if (is_neg)
448                         digit = -digit;
449
450                     if (is_neg != r_is_inverted) {
451                         if (!r_is_at_infinity) {
452                             if (!EC_POINT_invert(group, r, ctx))
453                                 goto err;
454                         }
455                         r_is_inverted = !r_is_inverted;
456                     }
457
458                     /* digit > 0 */
459
460                     if (r_is_at_infinity) {
461                         if (!EC_POINT_copy(r, val_sub[i][digit >> 1]))
462                             goto err;
463                         r_is_at_infinity = 0;
464                     } else {
465                         if (!EC_POINT_add
466                             (group, r, r, val_sub[i][digit >> 1], ctx))
467                             goto err;
468                     }
469                 }
470             }
471         }
472     }
473
474     if (r_is_at_infinity) {
475         if (!EC_POINT_set_to_infinity(group, r))
476             goto err;
477     } else {
478         if (r_is_inverted)
479             if (!EC_POINT_invert(group, r, ctx))
480                 goto err;
481     }
482
483     ret = 1;
484
485  err:
486     BN_CTX_free(new_ctx);
487     EC_POINT_free(tmp);
488     OPENSSL_free(wsize);
489     OPENSSL_free(wNAF_len);
490     if (wNAF != NULL) {
491         signed char **w;
492
493         for (w = wNAF; *w != NULL; w++)
494             OPENSSL_free(*w);
495
496         OPENSSL_free(wNAF);
497     }
498     if (val != NULL) {
499         for (v = val; *v != NULL; v++)
500             EC_POINT_clear_free(*v);
501
502         OPENSSL_free(val);
503     }
504     OPENSSL_free(val_sub);
505     return ret;
506 }
507
508 /*-
509  * ec_wNAF_precompute_mult()
510  * creates an EC_PRE_COMP object with preprecomputed multiples of the generator
511  * for use with wNAF splitting as implemented in ec_wNAF_mul().
512  *
513  * 'pre_comp->points' is an array of multiples of the generator
514  * of the following form:
515  * points[0] =     generator;
516  * points[1] = 3 * generator;
517  * ...
518  * points[2^(w-1)-1] =     (2^(w-1)-1) * generator;
519  * points[2^(w-1)]   =     2^blocksize * generator;
520  * points[2^(w-1)+1] = 3 * 2^blocksize * generator;
521  * ...
522  * points[2^(w-1)*(numblocks-1)-1] = (2^(w-1)) *  2^(blocksize*(numblocks-2)) * generator
523  * points[2^(w-1)*(numblocks-1)]   =              2^(blocksize*(numblocks-1)) * generator
524  * ...
525  * points[2^(w-1)*numblocks-1]     = (2^(w-1)) *  2^(blocksize*(numblocks-1)) * generator
526  * points[2^(w-1)*numblocks]       = NULL
527  */
528 int ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
529 {
530     const EC_POINT *generator;
531     EC_POINT *tmp_point = NULL, *base = NULL, **var;
532     BN_CTX *new_ctx = NULL;
533     const BIGNUM *order;
534     size_t i, bits, w, pre_points_per_block, blocksize, numblocks, num;
535     EC_POINT **points = NULL;
536     EC_PRE_COMP *pre_comp;
537     int ret = 0;
538
539     /* if there is an old EC_PRE_COMP object, throw it away */
540     EC_pre_comp_free(group);
541     if ((pre_comp = ec_pre_comp_new(group)) == NULL)
542         return 0;
543
544     generator = EC_GROUP_get0_generator(group);
545     if (generator == NULL) {
546         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNDEFINED_GENERATOR);
547         goto err;
548     }
549
550     if (ctx == NULL) {
551         ctx = new_ctx = BN_CTX_new();
552         if (ctx == NULL)
553             goto err;
554     }
555
556     BN_CTX_start(ctx);
557
558     order = EC_GROUP_get0_order(group);
559     if (order == NULL)
560         goto err;
561     if (BN_is_zero(order)) {
562         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, EC_R_UNKNOWN_ORDER);
563         goto err;
564     }
565
566     bits = BN_num_bits(order);
567     /*
568      * The following parameters mean we precompute (approximately) one point
569      * per bit. TBD: The combination 8, 4 is perfect for 160 bits; for other
570      * bit lengths, other parameter combinations might provide better
571      * efficiency.
572      */
573     blocksize = 8;
574     w = 4;
575     if (EC_window_bits_for_scalar_size(bits) > w) {
576         /* let's not make the window too small ... */
577         w = EC_window_bits_for_scalar_size(bits);
578     }
579
580     numblocks = (bits + blocksize - 1) / blocksize; /* max. number of blocks
581                                                      * to use for wNAF
582                                                      * splitting */
583
584     pre_points_per_block = (size_t)1 << (w - 1);
585     num = pre_points_per_block * numblocks; /* number of points to compute
586                                              * and store */
587
588     points = OPENSSL_malloc(sizeof(*points) * (num + 1));
589     if (points == NULL) {
590         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
591         goto err;
592     }
593
594     var = points;
595     var[num] = NULL;            /* pivot */
596     for (i = 0; i < num; i++) {
597         if ((var[i] = EC_POINT_new(group)) == NULL) {
598             ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
599             goto err;
600         }
601     }
602
603     if ((tmp_point = EC_POINT_new(group)) == NULL
604         || (base = EC_POINT_new(group)) == NULL) {
605         ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_MALLOC_FAILURE);
606         goto err;
607     }
608
609     if (!EC_POINT_copy(base, generator))
610         goto err;
611
612     /* do the precomputation */
613     for (i = 0; i < numblocks; i++) {
614         size_t j;
615
616         if (!EC_POINT_dbl(group, tmp_point, base, ctx))
617             goto err;
618
619         if (!EC_POINT_copy(*var++, base))
620             goto err;
621
622         for (j = 1; j < pre_points_per_block; j++, var++) {
623             /*
624              * calculate odd multiples of the current base point
625              */
626             if (!EC_POINT_add(group, *var, tmp_point, *(var - 1), ctx))
627                 goto err;
628         }
629
630         if (i < numblocks - 1) {
631             /*
632              * get the next base (multiply current one by 2^blocksize)
633              */
634             size_t k;
635
636             if (blocksize <= 2) {
637                 ECerr(EC_F_EC_WNAF_PRECOMPUTE_MULT, ERR_R_INTERNAL_ERROR);
638                 goto err;
639             }
640
641             if (!EC_POINT_dbl(group, base, tmp_point, ctx))
642                 goto err;
643             for (k = 2; k < blocksize; k++) {
644                 if (!EC_POINT_dbl(group, base, base, ctx))
645                     goto err;
646             }
647         }
648     }
649
650     if (!EC_POINTs_make_affine(group, num, points, ctx))
651         goto err;
652
653     pre_comp->group = group;
654     pre_comp->blocksize = blocksize;
655     pre_comp->numblocks = numblocks;
656     pre_comp->w = w;
657     pre_comp->points = points;
658     points = NULL;
659     pre_comp->num = num;
660     SETPRECOMP(group, ec, pre_comp);
661     pre_comp = NULL;
662     ret = 1;
663
664  err:
665     if (ctx != NULL)
666         BN_CTX_end(ctx);
667     BN_CTX_free(new_ctx);
668     EC_ec_pre_comp_free(pre_comp);
669     if (points) {
670         EC_POINT **p;
671
672         for (p = points; *p != NULL; p++)
673             EC_POINT_free(*p);
674         OPENSSL_free(points);
675     }
676     EC_POINT_free(tmp_point);
677     EC_POINT_free(base);
678     return ret;
679 }
680
681 int ec_wNAF_have_precompute_mult(const EC_GROUP *group)
682 {
683     return HAVEPRECOMP(group, ec);
684 }