Built motion from commit 6a09e18b.|2.6.11
[motion2.git] / legacy-libs / grpc / deps / grpc / third_party / boringssl / crypto / fipsmodule / bn / montgomery.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57 /* ====================================================================
58  * Copyright (c) 1998-2006 The OpenSSL Project.  All rights reserved.
59  *
60  * Redistribution and use in source and binary forms, with or without
61  * modification, are permitted provided that the following conditions
62  * are met:
63  *
64  * 1. Redistributions of source code must retain the above copyright
65  *    notice, this list of conditions and the following disclaimer.
66  *
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in
69  *    the documentation and/or other materials provided with the
70  *    distribution.
71  *
72  * 3. All advertising materials mentioning features or use of this
73  *    software must display the following acknowledgment:
74  *    "This product includes software developed by the OpenSSL Project
75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76  *
77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78  *    endorse or promote products derived from this software without
79  *    prior written permission. For written permission, please contact
80  *    openssl-core@openssl.org.
81  *
82  * 5. Products derived from this software may not be called "OpenSSL"
83  *    nor may "OpenSSL" appear in their names without prior written
84  *    permission of the OpenSSL Project.
85  *
86  * 6. Redistributions of any form whatsoever must retain the following
87  *    acknowledgment:
88  *    "This product includes software developed by the OpenSSL Project
89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90  *
91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102  * OF THE POSSIBILITY OF SUCH DAMAGE.
103  * ====================================================================
104  *
105  * This product includes cryptographic software written by Eric Young
106  * (eay@cryptsoft.com).  This product includes software written by Tim
107  * Hudson (tjh@cryptsoft.com). */
108
109 #include <openssl/bn.h>
110
111 #include <assert.h>
112 #include <string.h>
113
114 #include <openssl/err.h>
115 #include <openssl/mem.h>
116 #include <openssl/thread.h>
117 #include <openssl/type_check.h>
118
119 #include "internal.h"
120 #include "../../internal.h"
121
122
123 #if !defined(OPENSSL_NO_ASM) &&                         \
124     (defined(OPENSSL_X86) || defined(OPENSSL_X86_64) || \
125      defined(OPENSSL_ARM) || defined(OPENSSL_AARCH64))
126 #define OPENSSL_BN_ASM_MONT
127 #endif
128
129
130 BN_MONT_CTX *BN_MONT_CTX_new(void) {
131   BN_MONT_CTX *ret = OPENSSL_malloc(sizeof(BN_MONT_CTX));
132
133   if (ret == NULL) {
134     return NULL;
135   }
136
137   OPENSSL_memset(ret, 0, sizeof(BN_MONT_CTX));
138   BN_init(&ret->RR);
139   BN_init(&ret->N);
140
141   return ret;
142 }
143
144 void BN_MONT_CTX_free(BN_MONT_CTX *mont) {
145   if (mont == NULL) {
146     return;
147   }
148
149   BN_free(&mont->RR);
150   BN_free(&mont->N);
151   OPENSSL_free(mont);
152 }
153
154 BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, const BN_MONT_CTX *from) {
155   if (to == from) {
156     return to;
157   }
158
159   if (!BN_copy(&to->RR, &from->RR) ||
160       !BN_copy(&to->N, &from->N)) {
161     return NULL;
162   }
163   to->n0[0] = from->n0[0];
164   to->n0[1] = from->n0[1];
165   return to;
166 }
167
168 OPENSSL_COMPILE_ASSERT(BN_MONT_CTX_N0_LIMBS == 1 || BN_MONT_CTX_N0_LIMBS == 2,
169                        BN_MONT_CTX_N0_LIMBS_VALUE_INVALID);
170 OPENSSL_COMPILE_ASSERT(sizeof(BN_ULONG) * BN_MONT_CTX_N0_LIMBS ==
171                        sizeof(uint64_t), BN_MONT_CTX_set_64_bit_mismatch);
172
173 int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx) {
174   if (BN_is_zero(mod)) {
175     OPENSSL_PUT_ERROR(BN, BN_R_DIV_BY_ZERO);
176     return 0;
177   }
178   if (!BN_is_odd(mod)) {
179     OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS);
180     return 0;
181   }
182   if (BN_is_negative(mod)) {
183     OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
184     return 0;
185   }
186
187   // Save the modulus.
188   if (!BN_copy(&mont->N, mod)) {
189     OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR);
190     return 0;
191   }
192   // |mont->N| is always stored minimally. Computing RR efficiently leaks the
193   // size of the modulus. While the modulus may be private in RSA (one of the
194   // primes), their sizes are public, so this is fine.
195   bn_set_minimal_width(&mont->N);
196
197   // Find n0 such that n0 * N == -1 (mod r).
198   //
199   // Only certain BN_BITS2<=32 platforms actually make use of n0[1]. For the
200   // others, we could use a shorter R value and use faster |BN_ULONG|-based
201   // math instead of |uint64_t|-based math, which would be double-precision.
202   // However, currently only the assembler files know which is which.
203   uint64_t n0 = bn_mont_n0(&mont->N);
204   mont->n0[0] = (BN_ULONG)n0;
205 #if BN_MONT_CTX_N0_LIMBS == 2
206   mont->n0[1] = (BN_ULONG)(n0 >> BN_BITS2);
207 #else
208   mont->n0[1] = 0;
209 #endif
210
211   BN_CTX *new_ctx = NULL;
212   if (ctx == NULL) {
213     new_ctx = BN_CTX_new();
214     if (new_ctx == NULL) {
215       return 0;
216     }
217     ctx = new_ctx;
218   }
219
220   // Save RR = R**2 (mod N). R is the smallest power of 2**BN_BITS2 such that R
221   // > mod. Even though the assembly on some 32-bit platforms works with 64-bit
222   // values, using |BN_BITS2| here, rather than |BN_MONT_CTX_N0_LIMBS *
223   // BN_BITS2|, is correct because R**2 will still be a multiple of the latter
224   // as |BN_MONT_CTX_N0_LIMBS| is either one or two.
225   unsigned lgBigR = mont->N.width * BN_BITS2;
226   int ok = bn_mod_exp_base_2_consttime(&mont->RR, lgBigR * 2, &mont->N, ctx);
227   BN_CTX_free(new_ctx);
228   return ok;
229 }
230
231 BN_MONT_CTX *BN_MONT_CTX_new_for_modulus(const BIGNUM *mod, BN_CTX *ctx) {
232   BN_MONT_CTX *mont = BN_MONT_CTX_new();
233   if (mont == NULL ||
234       !BN_MONT_CTX_set(mont, mod, ctx)) {
235     BN_MONT_CTX_free(mont);
236     return NULL;
237   }
238   return mont;
239 }
240
241 int BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_MUTEX *lock,
242                            const BIGNUM *mod, BN_CTX *bn_ctx) {
243   CRYPTO_MUTEX_lock_read(lock);
244   BN_MONT_CTX *ctx = *pmont;
245   CRYPTO_MUTEX_unlock_read(lock);
246
247   if (ctx) {
248     return 1;
249   }
250
251   CRYPTO_MUTEX_lock_write(lock);
252   if (*pmont == NULL) {
253     *pmont = BN_MONT_CTX_new_for_modulus(mod, bn_ctx);
254   }
255   const int ok = *pmont != NULL;
256   CRYPTO_MUTEX_unlock_write(lock);
257   return ok;
258 }
259
260 int BN_to_montgomery(BIGNUM *ret, const BIGNUM *a, const BN_MONT_CTX *mont,
261                      BN_CTX *ctx) {
262   return BN_mod_mul_montgomery(ret, a, &mont->RR, mont, ctx);
263 }
264
265 static int bn_from_montgomery_in_place(BN_ULONG *r, size_t num_r, BN_ULONG *a,
266                                        size_t num_a, const BN_MONT_CTX *mont) {
267   const BN_ULONG *n = mont->N.d;
268   size_t num_n = mont->N.width;
269   if (num_r != num_n || num_a != 2 * num_n) {
270     OPENSSL_PUT_ERROR(BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
271     return 0;
272   }
273
274   // Add multiples of |n| to |r| until R = 2^(nl * BN_BITS2) divides it. On
275   // input, we had |r| < |n| * R, so now |r| < 2 * |n| * R. Note that |r|
276   // includes |carry| which is stored separately.
277   BN_ULONG n0 = mont->n0[0];
278   BN_ULONG carry = 0;
279   for (size_t i = 0; i < num_n; i++) {
280     BN_ULONG v = bn_mul_add_words(a + i, n, num_n, a[i] * n0);
281     v += carry + a[i + num_n];
282     carry |= (v != a[i + num_n]);
283     carry &= (v <= a[i + num_n]);
284     a[i + num_n] = v;
285   }
286
287   // Shift |num_n| words to divide by R. We have |a| < 2 * |n|. Note that |a|
288   // includes |carry| which is stored separately.
289   a += num_n;
290
291   // |a| thus requires at most one additional subtraction |n| to be reduced.
292   // Subtract |n| and select the answer in constant time.
293   OPENSSL_COMPILE_ASSERT(sizeof(BN_ULONG) <= sizeof(crypto_word_t),
294                          crypto_word_t_too_small);
295   BN_ULONG v = bn_sub_words(r, a, n, num_n) - carry;
296   // |v| is one if |a| - |n| underflowed or zero if it did not. Note |v| cannot
297   // be -1. That would imply the subtraction did not fit in |num_n| words, and
298   // we know at most one subtraction is needed.
299   v = 0u - v;
300   for (size_t i = 0; i < num_n; i++) {
301     r[i] = constant_time_select_w(v, a[i], r[i]);
302     a[i] = 0;
303   }
304   return 1;
305 }
306
307 static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r,
308                                    const BN_MONT_CTX *mont) {
309   if (r->neg) {
310     OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
311     return 0;
312   }
313
314   const BIGNUM *n = &mont->N;
315   if (n->width == 0) {
316     ret->width = 0;
317     return 1;
318   }
319
320   int max = 2 * n->width;  // carry is stored separately
321   if (!bn_resize_words(r, max) ||
322       !bn_wexpand(ret, n->width)) {
323     return 0;
324   }
325
326   ret->width = n->width;
327   ret->neg = 0;
328   return bn_from_montgomery_in_place(ret->d, ret->width, r->d, r->width, mont);
329 }
330
331 int BN_from_montgomery(BIGNUM *r, const BIGNUM *a, const BN_MONT_CTX *mont,
332                        BN_CTX *ctx) {
333   int ret = 0;
334   BIGNUM *t;
335
336   BN_CTX_start(ctx);
337   t = BN_CTX_get(ctx);
338   if (t == NULL ||
339       !BN_copy(t, a)) {
340     goto err;
341   }
342
343   ret = BN_from_montgomery_word(r, t, mont);
344
345 err:
346   BN_CTX_end(ctx);
347
348   return ret;
349 }
350
351 int bn_one_to_montgomery(BIGNUM *r, const BN_MONT_CTX *mont, BN_CTX *ctx) {
352   // If the high bit of |n| is set, R = 2^(width*BN_BITS2) < 2 * |n|, so we
353   // compute R - |n| rather than perform Montgomery reduction.
354   const BIGNUM *n = &mont->N;
355   if (n->width > 0 && (n->d[n->width - 1] >> (BN_BITS2 - 1)) != 0) {
356     if (!bn_wexpand(r, n->width)) {
357       return 0;
358     }
359     r->d[0] = 0 - n->d[0];
360     for (int i = 1; i < n->width; i++) {
361       r->d[i] = ~n->d[i];
362     }
363     r->width = n->width;
364     r->neg = 0;
365     return 1;
366   }
367
368   return BN_from_montgomery(r, &mont->RR, mont, ctx);
369 }
370
371 static int bn_mod_mul_montgomery_fallback(BIGNUM *r, const BIGNUM *a,
372                                           const BIGNUM *b,
373                                           const BN_MONT_CTX *mont,
374                                           BN_CTX *ctx) {
375   int ret = 0;
376
377   BN_CTX_start(ctx);
378   BIGNUM *tmp = BN_CTX_get(ctx);
379   if (tmp == NULL) {
380     goto err;
381   }
382
383   if (a == b) {
384     if (!bn_sqr_consttime(tmp, a, ctx)) {
385       goto err;
386     }
387   } else {
388     if (!bn_mul_consttime(tmp, a, b, ctx)) {
389       goto err;
390     }
391   }
392
393   // reduce from aRR to aR
394   if (!BN_from_montgomery_word(r, tmp, mont)) {
395     goto err;
396   }
397
398   ret = 1;
399
400 err:
401   BN_CTX_end(ctx);
402   return ret;
403 }
404
405 int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
406                           const BN_MONT_CTX *mont, BN_CTX *ctx) {
407   if (a->neg || b->neg) {
408     OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
409     return 0;
410   }
411
412 #if defined(OPENSSL_BN_ASM_MONT)
413   // |bn_mul_mont| requires at least 128 bits of limbs, at least for x86.
414   int num = mont->N.width;
415   if (num >= (128 / BN_BITS2) &&
416       a->width == num &&
417       b->width == num) {
418     if (!bn_wexpand(r, num)) {
419       return 0;
420     }
421     if (!bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num)) {
422       // The check above ensures this won't happen.
423       assert(0);
424       OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR);
425       return 0;
426     }
427     r->neg = 0;
428     r->width = num;
429     return 1;
430   }
431 #endif
432
433   return bn_mod_mul_montgomery_fallback(r, a, b, mont, ctx);
434 }
435
436 int bn_less_than_montgomery_R(const BIGNUM *bn, const BN_MONT_CTX *mont) {
437   return !BN_is_negative(bn) &&
438          bn_fits_in_words(bn, mont->N.width);
439 }
440
441 int bn_to_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a,
442                            size_t num_a, const BN_MONT_CTX *mont) {
443   return bn_mod_mul_montgomery_small(r, num_r, a, num_a, mont->RR.d,
444                                      mont->RR.width, mont);
445 }
446
447 int bn_from_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a,
448                              size_t num_a, const BN_MONT_CTX *mont) {
449   size_t num_n = mont->N.width;
450   if (num_a > 2 * num_n || num_r != num_n || num_n > BN_SMALL_MAX_WORDS) {
451     OPENSSL_PUT_ERROR(BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
452     return 0;
453   }
454   BN_ULONG tmp[BN_SMALL_MAX_WORDS * 2];
455   size_t num_tmp = 2 * num_n;
456   OPENSSL_memcpy(tmp, a, num_a * sizeof(BN_ULONG));
457   OPENSSL_memset(tmp + num_a, 0, (num_tmp - num_a) * sizeof(BN_ULONG));
458   int ret = bn_from_montgomery_in_place(r, num_r, tmp, num_tmp, mont);
459   OPENSSL_cleanse(tmp, num_tmp * sizeof(BN_ULONG));
460   return ret;
461 }
462
463 int bn_one_to_montgomery_small(BN_ULONG *r, size_t num_r,
464                                const BN_MONT_CTX *mont) {
465   const BN_ULONG *n = mont->N.d;
466   size_t num_n = mont->N.width;
467   if (num_n == 0 || num_r != num_n) {
468     OPENSSL_PUT_ERROR(BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
469     return 0;
470   }
471
472   // If the high bit of |n| is set, R = 2^(num_n*BN_BITS2) < 2 * |n|, so we
473   // compute R - |n| rather than perform Montgomery reduction.
474   if (num_n > 0 && (n[num_n - 1] >> (BN_BITS2 - 1)) != 0) {
475     r[0] = 0 - n[0];
476     for (size_t i = 1; i < num_n; i++) {
477       r[i] = ~n[i];
478     }
479     return 1;
480   }
481
482   return bn_from_montgomery_small(r, num_r, mont->RR.d, mont->RR.width, mont);
483 }
484
485 int bn_mod_mul_montgomery_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a,
486                                 size_t num_a, const BN_ULONG *b, size_t num_b,
487                                 const BN_MONT_CTX *mont) {
488   size_t num_n = mont->N.width;
489   if (num_r != num_n || num_a + num_b > 2 * num_n ||
490       num_n > BN_SMALL_MAX_WORDS) {
491     OPENSSL_PUT_ERROR(BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
492     return 0;
493   }
494
495 #if defined(OPENSSL_BN_ASM_MONT)
496   // |bn_mul_mont| requires at least 128 bits of limbs, at least for x86.
497   if (num_n >= (128 / BN_BITS2) &&
498       num_a == num_n &&
499       num_b == num_n) {
500     if (!bn_mul_mont(r, a, b, mont->N.d, mont->n0, num_n)) {
501       assert(0);  // The check above ensures this won't happen.
502       OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR);
503       return 0;
504     }
505     return 1;
506   }
507 #endif
508
509   // Compute the product.
510   BN_ULONG tmp[2 * BN_SMALL_MAX_WORDS];
511   size_t num_tmp = 2 * num_n;
512   size_t num_ab = num_a + num_b;
513   if (a == b && num_a == num_b) {
514     if (!bn_sqr_small(tmp, num_ab, a, num_a)) {
515       return 0;
516     }
517   } else if (!bn_mul_small(tmp, num_ab, a, num_a, b, num_b)) {
518     return 0;
519   }
520
521   // Zero-extend to full width and reduce.
522   OPENSSL_memset(tmp + num_ab, 0, (num_tmp - num_ab) * sizeof(BN_ULONG));
523   int ret = bn_from_montgomery_in_place(r, num_r, tmp, num_tmp, mont);
524   OPENSSL_cleanse(tmp, num_tmp * sizeof(BN_ULONG));
525   return ret;
526 }