Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc / deps / grpc / third_party / boringssl / crypto / fipsmodule / ec / wnaf.c
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 #include <openssl/type_check.h>
77
78 #include "internal.h"
79 #include "../bn/internal.h"
80 #include "../../internal.h"
81
82
83 // This file implements the wNAF-based interleaving multi-exponentiation method
84 // at:
85 //   http://link.springer.com/chapter/10.1007%2F3-540-45537-X_13
86 //   http://www.bmoeller.de/pdf/TI-01-08.multiexp.pdf
87
88 int ec_compute_wNAF(const EC_GROUP *group, int8_t *out, const EC_SCALAR *scalar,
89                     size_t bits, int w) {
90   // 'int8_t' can represent integers with absolute values less than 2^7.
91   if (w <= 0 || w > 7 || bits == 0) {
92     OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
93     return 0;
94   }
95   int bit = 1 << w;         // at most 128
96   int next_bit = bit << 1;  // at most 256
97   int mask = next_bit - 1;  // at most 255
98
99   int window_val = scalar->words[0] & mask;
100   size_t j = 0;
101   // If j+w+1 >= bits, window_val will not increase.
102   while (window_val != 0 || j + w + 1 < bits) {
103     int digit = 0;
104
105     // 0 <= window_val <= 2^(w+1)
106
107     if (window_val & 1) {
108       // 0 < window_val < 2^(w+1)
109
110       if (window_val & bit) {
111         digit = window_val - next_bit;  // -2^w < digit < 0
112
113 #if 1  // modified wNAF
114         if (j + w + 1 >= bits) {
115           // special case for generating modified wNAFs:
116           // no new bits will be added into window_val,
117           // so using a positive digit here will decrease
118           // the total length of the representation
119
120           digit = window_val & (mask >> 1);  // 0 < digit < 2^w
121         }
122 #endif
123       } else {
124         digit = window_val;  // 0 < digit < 2^w
125       }
126
127       if (digit <= -bit || digit >= bit || !(digit & 1)) {
128         OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
129         return 0;
130       }
131
132       window_val -= digit;
133
134       // Now window_val is 0 or 2^(w+1) in standard wNAF generation;
135       // for modified window NAFs, it may also be 2^w.
136       if (window_val != 0 && window_val != next_bit && window_val != bit) {
137         OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
138         return 0;
139       }
140     }
141
142     out[j++] = digit;
143
144     window_val >>= 1;
145     window_val +=
146         bit * bn_is_bit_set_words(scalar->words, group->order.width, j + w);
147
148     if (window_val > next_bit) {
149       OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
150       return 0;
151     }
152   }
153
154   // Fill the rest of the wNAF with zeros.
155   if (j > bits + 1) {
156     OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
157     return 0;
158   }
159   for (size_t i = j; i < bits + 1; i++) {
160     out[i] = 0;
161   }
162
163   return 1;
164 }
165
166 // TODO: table should be optimised for the wNAF-based implementation,
167 //       sometimes smaller windows will give better performance
168 //       (thus the boundaries should be increased)
169 static size_t window_bits_for_scalar_size(size_t b) {
170   if (b >= 300) {
171     return 4;
172   }
173
174   if (b >= 70) {
175     return 3;
176   }
177
178   if (b >= 20) {
179     return 2;
180   }
181
182   return 1;
183 }
184
185 // EC_WNAF_MAX_WINDOW_BITS is the largest value returned by
186 // |window_bits_for_scalar_size|.
187 #define EC_WNAF_MAX_WINDOW_BITS 4
188
189 // compute_precomp sets |out[i]| to a newly-allocated |EC_POINT| containing
190 // (2*i+1)*p, for i from 0 to |len|. It returns one on success and
191 // zero on error.
192 static int compute_precomp(const EC_GROUP *group, EC_POINT **out,
193                            const EC_POINT *p, size_t len, BN_CTX *ctx) {
194   out[0] = EC_POINT_new(group);
195   if (out[0] == NULL ||
196       !EC_POINT_copy(out[0], p)) {
197     return 0;
198   }
199
200   int ret = 0;
201   EC_POINT *two_p = EC_POINT_new(group);
202   if (two_p == NULL ||
203       !EC_POINT_dbl(group, two_p, p, ctx)) {
204     goto err;
205   }
206
207   for (size_t i = 1; i < len; i++) {
208     out[i] = EC_POINT_new(group);
209     if (out[i] == NULL ||
210         !EC_POINT_add(group, out[i], out[i - 1], two_p, ctx)) {
211       goto err;
212     }
213   }
214
215   ret = 1;
216
217 err:
218   EC_POINT_free(two_p);
219   return ret;
220 }
221
222 static int lookup_precomp(const EC_GROUP *group, EC_POINT *out,
223                           EC_POINT *const *precomp, int digit, BN_CTX *ctx) {
224   if (digit < 0) {
225     digit = -digit;
226     return EC_POINT_copy(out, precomp[digit >> 1]) &&
227            EC_POINT_invert(group, out, ctx);
228   }
229
230   return EC_POINT_copy(out, precomp[digit >> 1]);
231 }
232
233 int ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const EC_SCALAR *g_scalar,
234                 const EC_POINT *p, const EC_SCALAR *p_scalar, BN_CTX *ctx) {
235   BN_CTX *new_ctx = NULL;
236   EC_POINT *precomp_storage[2 * (1 << (EC_WNAF_MAX_WINDOW_BITS - 1))] = {NULL};
237   EC_POINT **g_precomp = NULL, **p_precomp = NULL;
238   int8_t g_wNAF[EC_MAX_SCALAR_BYTES * 8 + 1];
239   int8_t p_wNAF[EC_MAX_SCALAR_BYTES * 8 + 1];
240   EC_POINT *tmp = NULL;
241   int ret = 0;
242
243   if (ctx == NULL) {
244     ctx = new_ctx = BN_CTX_new();
245     if (ctx == NULL) {
246       goto err;
247     }
248   }
249
250   size_t bits = BN_num_bits(&group->order);
251   size_t wsize = window_bits_for_scalar_size(bits);
252   size_t wNAF_len = bits + 1;
253   size_t precomp_len = (size_t)1 << (wsize - 1);
254
255   OPENSSL_COMPILE_ASSERT(
256       OPENSSL_ARRAY_SIZE(g_wNAF) == OPENSSL_ARRAY_SIZE(p_wNAF),
257       g_wNAF_and_p_wNAF_are_different_sizes);
258
259   if (wNAF_len > OPENSSL_ARRAY_SIZE(g_wNAF) ||
260       2 * precomp_len > OPENSSL_ARRAY_SIZE(precomp_storage)) {
261     OPENSSL_PUT_ERROR(EC, ERR_R_INTERNAL_ERROR);
262     goto err;
263   }
264
265   // TODO(davidben): |mul_public| is for ECDSA verification which can assume
266   // non-NULL inputs, but this code is also used for |mul| which cannot. It's
267   // not constant-time, so replace the generic |mul| and remove the NULL checks.
268   size_t total_precomp = 0;
269   if (g_scalar != NULL) {
270     const EC_POINT *g = EC_GROUP_get0_generator(group);
271     if (g == NULL) {
272       OPENSSL_PUT_ERROR(EC, EC_R_UNDEFINED_GENERATOR);
273       goto err;
274     }
275     g_precomp = precomp_storage + total_precomp;
276     total_precomp += precomp_len;
277     if (!ec_compute_wNAF(group, g_wNAF, g_scalar, bits, wsize) ||
278         !compute_precomp(group, g_precomp, g, precomp_len, ctx)) {
279       goto err;
280     }
281   }
282
283   if (p_scalar != NULL) {
284     p_precomp = precomp_storage + total_precomp;
285     total_precomp += precomp_len;
286     if (!ec_compute_wNAF(group, p_wNAF, p_scalar, bits, wsize) ||
287         !compute_precomp(group, p_precomp, p, precomp_len, ctx)) {
288       goto err;
289     }
290   }
291
292   tmp = EC_POINT_new(group);
293   if (tmp == NULL ||
294       // |window_bits_for_scalar_size| assumes we do this step.
295       !EC_POINTs_make_affine(group, total_precomp, precomp_storage, ctx)) {
296     goto err;
297   }
298
299   int r_is_at_infinity = 1;
300   for (size_t k = wNAF_len - 1; k < wNAF_len; k--) {
301     if (!r_is_at_infinity && !EC_POINT_dbl(group, r, r, ctx)) {
302       goto err;
303     }
304
305     if (g_scalar != NULL) {
306       if (g_wNAF[k] != 0) {
307         if (!lookup_precomp(group, tmp, g_precomp, g_wNAF[k], ctx)) {
308           goto err;
309         }
310         if (r_is_at_infinity) {
311           if (!EC_POINT_copy(r, tmp)) {
312             goto err;
313           }
314           r_is_at_infinity = 0;
315         } else if (!EC_POINT_add(group, r, r, tmp, ctx)) {
316           goto err;
317         }
318       }
319     }
320
321     if (p_scalar != NULL) {
322       if (p_wNAF[k] != 0) {
323         if (!lookup_precomp(group, tmp, p_precomp, p_wNAF[k], ctx)) {
324           goto err;
325         }
326         if (r_is_at_infinity) {
327           if (!EC_POINT_copy(r, tmp)) {
328             goto err;
329           }
330           r_is_at_infinity = 0;
331         } else if (!EC_POINT_add(group, r, r, tmp, ctx)) {
332           goto err;
333         }
334       }
335     }
336   }
337
338   if (r_is_at_infinity &&
339       !EC_POINT_set_to_infinity(group, r)) {
340     goto err;
341   }
342
343   ret = 1;
344
345 err:
346   BN_CTX_free(new_ctx);
347   EC_POINT_free(tmp);
348   OPENSSL_cleanse(&g_wNAF, sizeof(g_wNAF));
349   OPENSSL_cleanse(&p_wNAF, sizeof(p_wNAF));
350   for (size_t i = 0; i < OPENSSL_ARRAY_SIZE(precomp_storage); i++) {
351     EC_POINT_free(precomp_storage[i]);
352   }
353   return ret;
354 }