Home | History | Annotate | Download | only in bn
      1 /* Copyright (C) 1995-1998 Eric Young (eay (at) cryptsoft.com)
      2  * All rights reserved.
      3  *
      4  * This package is an SSL implementation written
      5  * by Eric Young (eay (at) 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 (at) 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 (at) 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 (at) 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 (at) 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 (at) cryptsoft.com).  This product includes software written by Tim
    107  * Hudson (tjh (at) cryptsoft.com). */
    108 
    109 #include <openssl/bn.h>
    110 
    111 #include <assert.h>
    112 #include <stdio.h>
    113 #include <stdlib.h>
    114 #include <string.h>
    115 
    116 #include <openssl/err.h>
    117 #include <openssl/mem.h>
    118 #include <openssl/thread.h>
    119 #include <openssl/type_check.h>
    120 
    121 #include "internal.h"
    122 #include "../../internal.h"
    123 
    124 
    125 BN_MONT_CTX *BN_MONT_CTX_new(void) {
    126   BN_MONT_CTX *ret = OPENSSL_malloc(sizeof(BN_MONT_CTX));
    127 
    128   if (ret == NULL) {
    129     return NULL;
    130   }
    131 
    132   OPENSSL_memset(ret, 0, sizeof(BN_MONT_CTX));
    133   BN_init(&ret->RR);
    134   BN_init(&ret->N);
    135 
    136   return ret;
    137 }
    138 
    139 void BN_MONT_CTX_free(BN_MONT_CTX *mont) {
    140   if (mont == NULL) {
    141     return;
    142   }
    143 
    144   BN_free(&mont->RR);
    145   BN_free(&mont->N);
    146   OPENSSL_free(mont);
    147 }
    148 
    149 BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, const BN_MONT_CTX *from) {
    150   if (to == from) {
    151     return to;
    152   }
    153 
    154   if (!BN_copy(&to->RR, &from->RR) ||
    155       !BN_copy(&to->N, &from->N)) {
    156     return NULL;
    157   }
    158   to->n0[0] = from->n0[0];
    159   to->n0[1] = from->n0[1];
    160   return to;
    161 }
    162 
    163 static int bn_mont_ctx_set_N_and_n0(BN_MONT_CTX *mont, const BIGNUM *mod) {
    164   if (BN_is_zero(mod)) {
    165     OPENSSL_PUT_ERROR(BN, BN_R_DIV_BY_ZERO);
    166     return 0;
    167   }
    168   if (!BN_is_odd(mod)) {
    169     OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS);
    170     return 0;
    171   }
    172   if (BN_is_negative(mod)) {
    173     OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
    174     return 0;
    175   }
    176 
    177   // Save the modulus.
    178   if (!BN_copy(&mont->N, mod)) {
    179     OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR);
    180     return 0;
    181   }
    182   // |mont->N| is always stored minimally. Computing RR efficiently leaks the
    183   // size of the modulus. While the modulus may be private in RSA (one of the
    184   // primes), their sizes are public, so this is fine.
    185   bn_set_minimal_width(&mont->N);
    186 
    187   // Find n0 such that n0 * N == -1 (mod r).
    188   //
    189   // Only certain BN_BITS2<=32 platforms actually make use of n0[1]. For the
    190   // others, we could use a shorter R value and use faster |BN_ULONG|-based
    191   // math instead of |uint64_t|-based math, which would be double-precision.
    192   // However, currently only the assembler files know which is which.
    193   OPENSSL_STATIC_ASSERT(BN_MONT_CTX_N0_LIMBS == 1 || BN_MONT_CTX_N0_LIMBS == 2,
    194                         "BN_MONT_CTX_N0_LIMBS value is invalid");
    195   OPENSSL_STATIC_ASSERT(
    196       sizeof(BN_ULONG) * BN_MONT_CTX_N0_LIMBS == sizeof(uint64_t),
    197       "uint64_t is insufficient precision for n0");
    198   uint64_t n0 = bn_mont_n0(&mont->N);
    199   mont->n0[0] = (BN_ULONG)n0;
    200 #if BN_MONT_CTX_N0_LIMBS == 2
    201   mont->n0[1] = (BN_ULONG)(n0 >> BN_BITS2);
    202 #else
    203   mont->n0[1] = 0;
    204 #endif
    205   return 1;
    206 }
    207 
    208 int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx) {
    209   if (!bn_mont_ctx_set_N_and_n0(mont, mod)) {
    210     return 0;
    211   }
    212 
    213   BN_CTX *new_ctx = NULL;
    214   if (ctx == NULL) {
    215     new_ctx = BN_CTX_new();
    216     if (new_ctx == NULL) {
    217       return 0;
    218     }
    219     ctx = new_ctx;
    220   }
    221 
    222   // Save RR = R**2 (mod N). R is the smallest power of 2**BN_BITS2 such that R
    223   // > mod. Even though the assembly on some 32-bit platforms works with 64-bit
    224   // values, using |BN_BITS2| here, rather than |BN_MONT_CTX_N0_LIMBS *
    225   // BN_BITS2|, is correct because R**2 will still be a multiple of the latter
    226   // as |BN_MONT_CTX_N0_LIMBS| is either one or two.
    227   unsigned lgBigR = mont->N.width * BN_BITS2;
    228   BN_zero(&mont->RR);
    229   int ok = BN_set_bit(&mont->RR, lgBigR * 2) &&
    230            BN_mod(&mont->RR, &mont->RR, &mont->N, ctx) &&
    231            bn_resize_words(&mont->RR, mont->N.width);
    232   BN_CTX_free(new_ctx);
    233   return ok;
    234 }
    235 
    236 BN_MONT_CTX *BN_MONT_CTX_new_for_modulus(const BIGNUM *mod, BN_CTX *ctx) {
    237   BN_MONT_CTX *mont = BN_MONT_CTX_new();
    238   if (mont == NULL ||
    239       !BN_MONT_CTX_set(mont, mod, ctx)) {
    240     BN_MONT_CTX_free(mont);
    241     return NULL;
    242   }
    243   return mont;
    244 }
    245 
    246 BN_MONT_CTX *BN_MONT_CTX_new_consttime(const BIGNUM *mod, BN_CTX *ctx) {
    247   BN_MONT_CTX *mont = BN_MONT_CTX_new();
    248   if (mont == NULL ||
    249       !bn_mont_ctx_set_N_and_n0(mont, mod)) {
    250     goto err;
    251   }
    252   unsigned lgBigR = mont->N.width * BN_BITS2;
    253   if (!bn_mod_exp_base_2_consttime(&mont->RR, lgBigR * 2, &mont->N, ctx) ||
    254       !bn_resize_words(&mont->RR, mont->N.width)) {
    255     goto err;
    256   }
    257   return mont;
    258 
    259 err:
    260   BN_MONT_CTX_free(mont);
    261   return NULL;
    262 }
    263 
    264 int BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_MUTEX *lock,
    265                            const BIGNUM *mod, BN_CTX *bn_ctx) {
    266   CRYPTO_MUTEX_lock_read(lock);
    267   BN_MONT_CTX *ctx = *pmont;
    268   CRYPTO_MUTEX_unlock_read(lock);
    269 
    270   if (ctx) {
    271     return 1;
    272   }
    273 
    274   CRYPTO_MUTEX_lock_write(lock);
    275   if (*pmont == NULL) {
    276     *pmont = BN_MONT_CTX_new_for_modulus(mod, bn_ctx);
    277   }
    278   const int ok = *pmont != NULL;
    279   CRYPTO_MUTEX_unlock_write(lock);
    280   return ok;
    281 }
    282 
    283 int BN_to_montgomery(BIGNUM *ret, const BIGNUM *a, const BN_MONT_CTX *mont,
    284                      BN_CTX *ctx) {
    285   return BN_mod_mul_montgomery(ret, a, &mont->RR, mont, ctx);
    286 }
    287 
    288 static int bn_from_montgomery_in_place(BN_ULONG *r, size_t num_r, BN_ULONG *a,
    289                                        size_t num_a, const BN_MONT_CTX *mont) {
    290   const BN_ULONG *n = mont->N.d;
    291   size_t num_n = mont->N.width;
    292   if (num_r != num_n || num_a != 2 * num_n) {
    293     OPENSSL_PUT_ERROR(BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
    294     return 0;
    295   }
    296 
    297   // Add multiples of |n| to |r| until R = 2^(nl * BN_BITS2) divides it. On
    298   // input, we had |r| < |n| * R, so now |r| < 2 * |n| * R. Note that |r|
    299   // includes |carry| which is stored separately.
    300   BN_ULONG n0 = mont->n0[0];
    301   BN_ULONG carry = 0;
    302   for (size_t i = 0; i < num_n; i++) {
    303     BN_ULONG v = bn_mul_add_words(a + i, n, num_n, a[i] * n0);
    304     v += carry + a[i + num_n];
    305     carry |= (v != a[i + num_n]);
    306     carry &= (v <= a[i + num_n]);
    307     a[i + num_n] = v;
    308   }
    309 
    310   // Shift |num_n| words to divide by R. We have |a| < 2 * |n|. Note that |a|
    311   // includes |carry| which is stored separately.
    312   a += num_n;
    313 
    314   // |a| thus requires at most one additional subtraction |n| to be reduced.
    315   bn_reduce_once(r, a, carry, n, num_n);
    316   return 1;
    317 }
    318 
    319 static int BN_from_montgomery_word(BIGNUM *ret, BIGNUM *r,
    320                                    const BN_MONT_CTX *mont) {
    321   if (r->neg) {
    322     OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
    323     return 0;
    324   }
    325 
    326   const BIGNUM *n = &mont->N;
    327   if (n->width == 0) {
    328     ret->width = 0;
    329     return 1;
    330   }
    331 
    332   int max = 2 * n->width;  // carry is stored separately
    333   if (!bn_resize_words(r, max) ||
    334       !bn_wexpand(ret, n->width)) {
    335     return 0;
    336   }
    337 
    338   ret->width = n->width;
    339   ret->neg = 0;
    340   return bn_from_montgomery_in_place(ret->d, ret->width, r->d, r->width, mont);
    341 }
    342 
    343 int BN_from_montgomery(BIGNUM *r, const BIGNUM *a, const BN_MONT_CTX *mont,
    344                        BN_CTX *ctx) {
    345   int ret = 0;
    346   BIGNUM *t;
    347 
    348   BN_CTX_start(ctx);
    349   t = BN_CTX_get(ctx);
    350   if (t == NULL ||
    351       !BN_copy(t, a)) {
    352     goto err;
    353   }
    354 
    355   ret = BN_from_montgomery_word(r, t, mont);
    356 
    357 err:
    358   BN_CTX_end(ctx);
    359 
    360   return ret;
    361 }
    362 
    363 int bn_one_to_montgomery(BIGNUM *r, const BN_MONT_CTX *mont, BN_CTX *ctx) {
    364   // If the high bit of |n| is set, R = 2^(width*BN_BITS2) < 2 * |n|, so we
    365   // compute R - |n| rather than perform Montgomery reduction.
    366   const BIGNUM *n = &mont->N;
    367   if (n->width > 0 && (n->d[n->width - 1] >> (BN_BITS2 - 1)) != 0) {
    368     if (!bn_wexpand(r, n->width)) {
    369       return 0;
    370     }
    371     r->d[0] = 0 - n->d[0];
    372     for (int i = 1; i < n->width; i++) {
    373       r->d[i] = ~n->d[i];
    374     }
    375     r->width = n->width;
    376     r->neg = 0;
    377     return 1;
    378   }
    379 
    380   return BN_from_montgomery(r, &mont->RR, mont, ctx);
    381 }
    382 
    383 static int bn_mod_mul_montgomery_fallback(BIGNUM *r, const BIGNUM *a,
    384                                           const BIGNUM *b,
    385                                           const BN_MONT_CTX *mont,
    386                                           BN_CTX *ctx) {
    387   int ret = 0;
    388 
    389   BN_CTX_start(ctx);
    390   BIGNUM *tmp = BN_CTX_get(ctx);
    391   if (tmp == NULL) {
    392     goto err;
    393   }
    394 
    395   if (a == b) {
    396     if (!bn_sqr_consttime(tmp, a, ctx)) {
    397       goto err;
    398     }
    399   } else {
    400     if (!bn_mul_consttime(tmp, a, b, ctx)) {
    401       goto err;
    402     }
    403   }
    404 
    405   // reduce from aRR to aR
    406   if (!BN_from_montgomery_word(r, tmp, mont)) {
    407     goto err;
    408   }
    409 
    410   ret = 1;
    411 
    412 err:
    413   BN_CTX_end(ctx);
    414   return ret;
    415 }
    416 
    417 int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
    418                           const BN_MONT_CTX *mont, BN_CTX *ctx) {
    419   if (a->neg || b->neg) {
    420     OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
    421     return 0;
    422   }
    423 
    424 #if defined(OPENSSL_BN_ASM_MONT)
    425   // |bn_mul_mont| requires at least 128 bits of limbs, at least for x86.
    426   int num = mont->N.width;
    427   if (num >= (128 / BN_BITS2) &&
    428       a->width == num &&
    429       b->width == num) {
    430     if (!bn_wexpand(r, num)) {
    431       return 0;
    432     }
    433     if (!bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num)) {
    434       // The check above ensures this won't happen.
    435       assert(0);
    436       OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR);
    437       return 0;
    438     }
    439     r->neg = 0;
    440     r->width = num;
    441     return 1;
    442   }
    443 #endif
    444 
    445   return bn_mod_mul_montgomery_fallback(r, a, b, mont, ctx);
    446 }
    447 
    448 int bn_less_than_montgomery_R(const BIGNUM *bn, const BN_MONT_CTX *mont) {
    449   return !BN_is_negative(bn) &&
    450          bn_fits_in_words(bn, mont->N.width);
    451 }
    452 
    453 void bn_to_montgomery_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
    454                             const BN_MONT_CTX *mont) {
    455   bn_mod_mul_montgomery_small(r, a, mont->RR.d, num, mont);
    456 }
    457 
    458 void bn_from_montgomery_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
    459                               const BN_MONT_CTX *mont) {
    460   if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS) {
    461     abort();
    462   }
    463   BN_ULONG tmp[BN_SMALL_MAX_WORDS * 2];
    464   OPENSSL_memcpy(tmp, a, num * sizeof(BN_ULONG));
    465   OPENSSL_memset(tmp + num, 0, num * sizeof(BN_ULONG));
    466   if (!bn_from_montgomery_in_place(r, num, tmp, 2 * num, mont)) {
    467     abort();
    468   }
    469   OPENSSL_cleanse(tmp, 2 * num * sizeof(BN_ULONG));
    470 }
    471 
    472 void bn_mod_mul_montgomery_small(BN_ULONG *r, const BN_ULONG *a,
    473                                  const BN_ULONG *b, size_t num,
    474                                  const BN_MONT_CTX *mont) {
    475   if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS) {
    476     abort();
    477   }
    478 
    479 #if defined(OPENSSL_BN_ASM_MONT)
    480   // |bn_mul_mont| requires at least 128 bits of limbs, at least for x86.
    481   if (num >= (128 / BN_BITS2)) {
    482     if (!bn_mul_mont(r, a, b, mont->N.d, mont->n0, num)) {
    483       abort();  // The check above ensures this won't happen.
    484     }
    485     return;
    486   }
    487 #endif
    488 
    489   // Compute the product.
    490   BN_ULONG tmp[2 * BN_SMALL_MAX_WORDS];
    491   if (a == b) {
    492     bn_sqr_small(tmp, 2 * num, a, num);
    493   } else {
    494     bn_mul_small(tmp, 2 * num, a, num, b, num);
    495   }
    496 
    497   // Reduce.
    498   if (!bn_from_montgomery_in_place(r, num, tmp, 2 * num, mont)) {
    499     abort();
    500   }
    501   OPENSSL_cleanse(tmp, 2 * num * sizeof(BN_ULONG));
    502 }
    503