1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
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.
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).
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.
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
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)"
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
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.]
57 /* ====================================================================
58 * Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
64 * 1. Redistributions of source code must retain the above copyright
65 * notice, this list of conditions and the following disclaimer.
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
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/)"
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.
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.
86 * 6. Redistributions of any form whatsoever must retain the following
88 * "This product includes software developed by the OpenSSL Project
89 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
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 * ====================================================================
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). */
109 #include <openssl/bn.h>
114 #include <openssl/cpu.h>
115 #include <openssl/err.h>
116 #include <openssl/mem.h>
118 #include "internal.h"
121 #if !defined(OPENSSL_NO_ASM) && defined(OPENSSL_X86_64)
122 #define OPENSSL_BN_ASM_MONT5
125 #include "rsaz_exp.h"
127 void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, const void *table,
128 const BN_ULONG *np, const BN_ULONG *n0, int num,
130 void bn_scatter5(const BN_ULONG *inp, size_t num, void *table, size_t power);
131 void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
132 void bn_power5(BN_ULONG *rp, const BN_ULONG *ap, const void *table,
133 const BN_ULONG *np, const BN_ULONG *n0, int num, int power);
134 int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap,
135 const BN_ULONG *not_used, const BN_ULONG *np,
136 const BN_ULONG *n0, int num);
139 int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) {
140 int i, bits, ret = 0;
144 if (r == a || r == p) {
145 rr = BN_CTX_get(ctx);
151 if (rr == NULL || v == NULL) {
155 if (BN_copy(v, a) == NULL) {
158 bits = BN_num_bits(p);
161 if (BN_copy(rr, a) == NULL) {
170 for (i = 1; i < bits; i++) {
171 if (!BN_sqr(v, v, ctx)) {
174 if (BN_is_bit_set(p, i)) {
175 if (!BN_mul(rr, rr, v, ctx)) {
181 if (r != rr && !BN_copy(r, rr)) {
191 typedef struct bn_recp_ctx_st {
192 BIGNUM N; // the divisor
193 BIGNUM Nr; // the reciprocal
199 static void BN_RECP_CTX_init(BN_RECP_CTX *recp) {
207 static void BN_RECP_CTX_free(BN_RECP_CTX *recp) {
216 static int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *d, BN_CTX *ctx) {
217 if (!BN_copy(&(recp->N), d)) {
221 recp->num_bits = BN_num_bits(d);
227 // len is the expected size of the result We actually calculate with an extra
228 // word of precision, so we can do faster division if the remainder is not
231 static int BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx) {
241 if (!BN_set_bit(t, len)) {
245 if (!BN_div(r, NULL, t, m, ctx)) {
256 static int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m,
257 BN_RECP_CTX *recp, BN_CTX *ctx) {
259 BIGNUM *a, *b, *d, *r;
276 if (a == NULL || b == NULL || d == NULL || r == NULL) {
280 if (BN_ucmp(m, &recp->N) < 0) {
282 if (!BN_copy(r, m)) {
289 // We want the remainder
290 // Given input of ABCDEF / ab
291 // we need multiply ABCDEF by 3 digests of the reciprocal of ab
293 // i := max(BN_num_bits(m), 2*BN_num_bits(N))
295 j = recp->num_bits << 1;
300 // Nr := round(2^i / N)
301 if (i != recp->shift) {
303 BN_reciprocal(&(recp->Nr), &(recp->N), i,
304 ctx); // BN_reciprocal returns i, or -1 for an error
307 if (recp->shift == -1) {
311 // d := |round(round(m / 2^BN_num_bits(N)) * recp->Nr / 2^(i -
313 // = |round(round(m / 2^BN_num_bits(N)) * round(2^i / N) / 2^(i -
315 // <= |(m / 2^BN_num_bits(N)) * (2^i / N) * (2^BN_num_bits(N) / 2^i)|
317 if (!BN_rshift(a, m, recp->num_bits)) {
320 if (!BN_mul(b, a, &(recp->Nr), ctx)) {
323 if (!BN_rshift(d, b, i - recp->num_bits)) {
328 if (!BN_mul(b, &(recp->N), d, ctx)) {
331 if (!BN_usub(r, m, b)) {
337 while (BN_ucmp(r, &(recp->N)) >= 0) {
339 OPENSSL_PUT_ERROR(BN, BN_R_BAD_RECIPROCAL);
342 if (!BN_usub(r, r, &(recp->N))) {
345 if (!BN_add_word(d, 1)) {
350 r->neg = BN_is_zero(r) ? 0 : m->neg;
351 d->neg = m->neg ^ recp->N.neg;
359 static int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y,
360 BN_RECP_CTX *recp, BN_CTX *ctx) {
373 if (!BN_sqr(a, x, ctx)) {
377 if (!BN_mul(a, x, y, ctx)) {
383 ca = x; // Just do the mod
386 ret = BN_div_recp(NULL, r, ca, recp, ctx);
393 // BN_window_bits_for_exponent_size returns sliding window size for mod_exp with
394 // a |b| bit exponent.
396 // For window size 'w' (w >= 2) and a random 'b' bits exponent, the number of
397 // multiplications is a constant plus on average
399 // 2^(w-1) + (b-w)/(w+1);
401 // here 2^(w-1) is for precomputing the table (we actually need entries only
402 // for windows that have the lowest bit set), and (b-w)/(w+1) is an
403 // approximation for the expected number of w-bit windows, not counting the
406 // Thus we should use
409 // w = 5 if 671 > b > 239
410 // w = 4 if 239 > b > 79
411 // w = 3 if 79 > b > 23
414 // (with draws in between). Very small exponents are often selected
415 // with low Hamming weight, so we use w = 1 for b <= 23.
416 static int BN_window_bits_for_exponent_size(int b) {
432 // TABLE_SIZE is the maximum precomputation table size for *variable* sliding
433 // windows. This must be 2^(max_window - 1), where max_window is the largest
434 // value returned from |BN_window_bits_for_exponent_size|.
435 #define TABLE_SIZE 32
437 // TABLE_BITS_SMALL is the smallest value returned from
438 // |BN_window_bits_for_exponent_size| when |b| is at most |BN_BITS2| *
439 // |BN_SMALL_MAX_WORDS| words.
440 #define TABLE_BITS_SMALL 5
442 // TABLE_SIZE_SMALL is the same as |TABLE_SIZE|, but when |b| is at most
443 // |BN_BITS2| * |BN_SMALL_MAX_WORDS|.
444 #define TABLE_SIZE_SMALL (1 << (TABLE_BITS_SMALL - 1))
446 static int mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
447 const BIGNUM *m, BN_CTX *ctx) {
448 int i, j, bits, ret = 0, wstart, window;
451 // Table of variables obtained from 'ctx'
452 BIGNUM *val[TABLE_SIZE];
455 bits = BN_num_bits(p);
458 // x**0 mod 1 is still zero.
467 aa = BN_CTX_get(ctx);
468 val[0] = BN_CTX_get(ctx);
469 if (!aa || !val[0]) {
473 BN_RECP_CTX_init(&recp);
475 // ignore sign of 'm'
476 if (!BN_copy(aa, m)) {
480 if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0) {
484 if (BN_RECP_CTX_set(&recp, m, ctx) <= 0) {
489 if (!BN_nnmod(val[0], a, m, ctx)) {
492 if (BN_is_zero(val[0])) {
498 window = BN_window_bits_for_exponent_size(bits);
500 if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx)) {
503 j = 1 << (window - 1);
504 for (i = 1; i < j; i++) {
505 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
506 !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx)) {
512 start = 1; // This is used to avoid multiplication etc
513 // when there is only the value '1' in the
515 wstart = bits - 1; // The top bit of the window
522 int wvalue; // The 'value' of the window
523 int wend; // The bottom bit of the window
525 if (!BN_is_bit_set(p, wstart)) {
527 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) {
538 // We now have wstart on a 'set' bit, we now need to work out
539 // how bit a window to do. To do this we need to scan
540 // forward until the last set bit before the end of the
544 for (i = 1; i < window; i++) {
545 if (wstart - i < 0) {
548 if (BN_is_bit_set(p, wstart - i)) {
549 wvalue <<= (i - wend);
555 // wend is the size of the current window
557 // add the 'bytes above'
559 for (i = 0; i < j; i++) {
560 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) {
566 // wvalue will be an odd number < 2^window
567 if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx)) {
571 // move the 'window' down further
582 BN_RECP_CTX_free(&recp);
586 int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
589 return BN_mod_exp_mont(r, a, p, m, ctx, NULL);
592 return mod_exp_recp(r, a, p, m, ctx);
595 int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
596 const BIGNUM *m, BN_CTX *ctx, const BN_MONT_CTX *mont) {
598 OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS);
601 int bits = BN_num_bits(p);
603 // x**0 mod 1 is still zero.
612 BIGNUM *val[TABLE_SIZE];
613 BN_MONT_CTX *new_mont = NULL;
616 BIGNUM *d = BN_CTX_get(ctx);
617 BIGNUM *r = BN_CTX_get(ctx);
618 val[0] = BN_CTX_get(ctx);
619 if (!d || !r || !val[0]) {
623 // Allocate a montgomery context if it was not supplied by the caller.
625 new_mont = BN_MONT_CTX_new_for_modulus(m, ctx);
626 if (new_mont == NULL) {
633 if (a->neg || BN_ucmp(a, m) >= 0) {
634 if (!BN_nnmod(val[0], a, m, ctx)) {
642 if (BN_is_zero(aa)) {
648 // We exponentiate by looking at sliding windows of the exponent and
649 // precomputing powers of |aa|. Windows may be shifted so they always end on a
650 // set bit, so only precompute odd powers. We compute val[i] = aa^(2*i + 1)
651 // for i = 0 to 2^(window-1), all in Montgomery form.
652 int window = BN_window_bits_for_exponent_size(bits);
653 if (!BN_to_montgomery(val[0], aa, mont, ctx)) {
657 if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx)) {
660 for (int i = 1; i < 1 << (window - 1); i++) {
661 val[i] = BN_CTX_get(ctx);
662 if (val[i] == NULL ||
663 !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx)) {
669 if (!bn_one_to_montgomery(r, mont, ctx)) {
674 int wstart = bits - 1; // The top bit of the window.
676 if (!BN_is_bit_set(p, wstart)) {
677 if (!r_is_one && !BN_mod_mul_montgomery(r, r, r, mont, ctx)) {
687 // We now have wstart on a set bit. Find the largest window we can use.
690 for (int i = 1; i < window && i <= wstart; i++) {
691 if (BN_is_bit_set(p, wstart - i)) {
692 wvalue <<= (i - wsize);
698 // Shift |r| to the end of the window.
700 for (int i = 0; i < wsize + 1; i++) {
701 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) {
708 assert(wvalue < (1 << window));
709 if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx)) {
714 if (wstart == wsize) {
720 if (!BN_from_montgomery(rr, r, mont, ctx)) {
726 BN_MONT_CTX_free(new_mont);
731 int bn_mod_exp_mont_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a,
732 size_t num_a, const BN_ULONG *p, size_t num_p,
733 const BN_MONT_CTX *mont) {
734 size_t num_n = mont->N.width;
735 if (num_n != num_a || num_n != num_r || num_n > BN_SMALL_MAX_WORDS) {
736 OPENSSL_PUT_ERROR(BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
739 if (!BN_is_odd(&mont->N)) {
740 OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS);
745 bits = BN_num_bits_word(p[num_p - 1]) + (num_p - 1) * BN_BITS2;
748 OPENSSL_memset(r, 0, num_r * sizeof(BN_ULONG));
749 if (!BN_is_one(&mont->N)) {
755 // We exponentiate by looking at sliding windows of the exponent and
756 // precomputing powers of |a|. Windows may be shifted so they always end on a
757 // set bit, so only precompute odd powers. We compute val[i] = a^(2*i + 1) for
758 // i = 0 to 2^(window-1), all in Montgomery form.
759 unsigned window = BN_window_bits_for_exponent_size(bits);
760 if (window > TABLE_BITS_SMALL) {
761 window = TABLE_BITS_SMALL; // Tolerate excessively large |p|.
764 BN_ULONG val[TABLE_SIZE_SMALL][BN_SMALL_MAX_WORDS];
765 OPENSSL_memcpy(val[0], a, num_n * sizeof(BN_ULONG));
767 BN_ULONG d[BN_SMALL_MAX_WORDS];
768 if (!bn_mod_mul_montgomery_small(d, num_n, val[0], num_n, val[0], num_n,
772 for (unsigned i = 1; i < 1u << (window - 1); i++) {
773 if (!bn_mod_mul_montgomery_small(val[i], num_n, val[i - 1], num_n, d,
780 if (!bn_one_to_montgomery_small(r, num_r, mont)) {
785 unsigned wstart = bits - 1; // The top bit of the window.
787 if (!bn_is_bit_set_words(p, num_p, wstart)) {
789 !bn_mod_mul_montgomery_small(r, num_r, r, num_r, r, num_r, mont)) {
799 // We now have wstart on a set bit. Find the largest window we can use.
802 for (unsigned i = 1; i < window && i <= wstart; i++) {
803 if (bn_is_bit_set_words(p, num_p, wstart - i)) {
804 wvalue <<= (i - wsize);
810 // Shift |r| to the end of the window.
812 for (unsigned i = 0; i < wsize + 1; i++) {
813 if (!bn_mod_mul_montgomery_small(r, num_r, r, num_r, r, num_r, mont)) {
820 assert(wvalue < (1u << window));
821 if (!bn_mod_mul_montgomery_small(r, num_r, r, num_r, val[wvalue >> 1],
827 if (wstart == wsize) {
836 OPENSSL_cleanse(val, sizeof(val));
840 int bn_mod_inverse_prime_mont_small(BN_ULONG *r, size_t num_r,
841 const BN_ULONG *a, size_t num_a,
842 const BN_MONT_CTX *mont) {
843 const BN_ULONG *p = mont->N.d;
844 size_t num_p = mont->N.width;
845 if (num_p > BN_SMALL_MAX_WORDS || num_p == 0) {
846 OPENSSL_PUT_ERROR(BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
850 // Per Fermat's Little Theorem, a^-1 = a^(p-2) (mod p) for p prime.
851 BN_ULONG p_minus_two[BN_SMALL_MAX_WORDS];
852 OPENSSL_memcpy(p_minus_two, p, num_p * sizeof(BN_ULONG));
853 if (p_minus_two[0] >= 2) {
857 for (size_t i = 1; i < num_p; i++) {
858 if (p_minus_two[i]-- != 0) {
864 return bn_mod_exp_mont_small(r, num_r, a, num_a, p_minus_two, num_p, mont);
868 // |BN_mod_exp_mont_consttime| stores the precomputed powers in a specific
869 // layout so that accessing any of these table values shows the same access
870 // pattern as far as cache lines are concerned. The following functions are
871 // used to transfer a BIGNUM from/to that table.
873 static void copy_to_prebuf(const BIGNUM *b, int top, unsigned char *buf,
874 int idx, int window) {
876 const int width = 1 << window;
877 BN_ULONG *table = (BN_ULONG *) buf;
879 if (top > b->width) {
880 top = b->width; // this works because 'buf' is explicitly zeroed
883 for (i = 0, j = idx; i < top; i++, j += width) {
888 static int copy_from_prebuf(BIGNUM *b, int top, unsigned char *buf, int idx,
891 const int width = 1 << window;
892 volatile BN_ULONG *table = (volatile BN_ULONG *)buf;
894 if (!bn_wexpand(b, top)) {
899 for (i = 0; i < top; i++, table += width) {
902 for (j = 0; j < width; j++) {
903 acc |= table[j] & ((BN_ULONG)0 - (constant_time_eq_int(j, idx) & 1));
909 int xstride = 1 << (window - 2);
910 BN_ULONG y0, y1, y2, y3;
912 i = idx >> (window - 2); // equivalent of idx / xstride
913 idx &= xstride - 1; // equivalent of idx % xstride
915 y0 = (BN_ULONG)0 - (constant_time_eq_int(i, 0) & 1);
916 y1 = (BN_ULONG)0 - (constant_time_eq_int(i, 1) & 1);
917 y2 = (BN_ULONG)0 - (constant_time_eq_int(i, 2) & 1);
918 y3 = (BN_ULONG)0 - (constant_time_eq_int(i, 3) & 1);
920 for (i = 0; i < top; i++, table += width) {
923 for (j = 0; j < xstride; j++) {
924 acc |= ((table[j + 0 * xstride] & y0) | (table[j + 1 * xstride] & y1) |
925 (table[j + 2 * xstride] & y2) | (table[j + 3 * xstride] & y3)) &
926 ((BN_ULONG)0 - (constant_time_eq_int(j, idx) & 1));
937 // BN_mod_exp_mont_conttime is based on the assumption that the L1 data cache
938 // line width of the target processor is at least the following value.
939 #define MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH (64)
940 #define MOD_EXP_CTIME_MIN_CACHE_LINE_MASK \
941 (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - 1)
943 // Window sizes optimized for fixed window size modular exponentiation
944 // algorithm (BN_mod_exp_mont_consttime).
946 // To achieve the security goals of BN_mode_exp_mont_consttime, the maximum
947 // size of the window must not exceed
948 // log_2(MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH).
950 // Window size thresholds are defined for cache line sizes of 32 and 64, cache
951 // line sizes where log_2(32)=5 and log_2(64)=6 respectively. A window size of
952 // 7 should only be used on processors that have a 128 byte or greater cache
954 #if MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 64
956 #define BN_window_bits_for_ctime_exponent_size(b) \
957 ((b) > 937 ? 6 : (b) > 306 ? 5 : (b) > 89 ? 4 : (b) > 22 ? 3 : 1)
958 #define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE (6)
960 #elif MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 32
962 #define BN_window_bits_for_ctime_exponent_size(b) \
963 ((b) > 306 ? 5 : (b) > 89 ? 4 : (b) > 22 ? 3 : 1)
964 #define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE (5)
968 // Given a pointer value, compute the next address that is a cache line
970 #define MOD_EXP_CTIME_ALIGN(x_) \
971 ((unsigned char *)(x_) + \
972 (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - \
973 (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK))))
975 // This variant of BN_mod_exp_mont() uses fixed windows and the special
976 // precomputation memory layout to limit data-dependency to a minimum
977 // to protect secret exponents (cf. the hyper-threading timing attacks
978 // pointed out by Colin Percival,
979 // http://www.daemonology.net/hyperthreading-considered-harmful/)
980 int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
981 const BIGNUM *m, BN_CTX *ctx,
982 const BN_MONT_CTX *mont) {
983 int i, ret = 0, window, wvalue;
984 BN_MONT_CTX *new_mont = NULL;
987 unsigned char *powerbufFree = NULL;
989 unsigned char *powerbuf = NULL;
991 BIGNUM *new_a = NULL;
994 OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS);
998 // Use all bits stored in |p|, rather than |BN_num_bits|, so we do not leak
999 // whether the top bits are zero.
1000 int max_bits = p->width * BN_BITS2;
1001 int bits = max_bits;
1003 // x**0 mod 1 is still zero.
1011 // Allocate a montgomery context if it was not supplied by the caller.
1013 new_mont = BN_MONT_CTX_new_for_modulus(m, ctx);
1014 if (new_mont == NULL) {
1020 // Use the width in |mont->N|, rather than the copy in |m|. The assembly
1021 // implementation assumes it can use |top| to size R.
1022 int top = mont->N.width;
1024 if (a->neg || BN_ucmp(a, m) >= 0) {
1026 if (new_a == NULL ||
1027 !BN_nnmod(new_a, a, m, ctx)) {
1034 // If the size of the operands allow it, perform the optimized
1035 // RSAZ exponentiation. For further information see
1036 // crypto/bn/rsaz_exp.c and accompanying assembly modules.
1037 if ((16 == a->width) && (16 == p->width) && (BN_num_bits(m) == 1024) &&
1038 rsaz_avx2_eligible()) {
1039 if (!bn_wexpand(rr, 16)) {
1042 RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d, mont->n0[0]);
1050 // Get the window size to use with size of p.
1051 window = BN_window_bits_for_ctime_exponent_size(bits);
1052 #if defined(OPENSSL_BN_ASM_MONT5)
1054 window = 5; // ~5% improvement for RSA2048 sign, and even for RSA4096
1055 // reserve space for mont->N.d[] copy
1056 powerbufLen += top * sizeof(mont->N.d[0]);
1060 // Allocate a buffer large enough to hold all of the pre-computed
1061 // powers of am, am itself and tmp.
1062 numPowers = 1 << window;
1065 (top * numPowers + ((2 * top) > numPowers ? (2 * top) : numPowers));
1067 if (powerbufLen < 3072) {
1068 powerbufFree = alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
1072 if ((powerbufFree = OPENSSL_malloc(
1073 powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH)) == NULL) {
1078 powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
1079 OPENSSL_memset(powerbuf, 0, powerbufLen);
1082 if (powerbufLen < 3072) {
1083 powerbufFree = NULL;
1087 // lay down tmp and am right after powers table
1088 tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
1090 tmp.width = am.width = 0;
1091 tmp.dmax = am.dmax = top;
1092 tmp.neg = am.neg = 0;
1093 tmp.flags = am.flags = BN_FLG_STATIC_DATA;
1095 if (!bn_one_to_montgomery(&tmp, mont, ctx)) {
1099 // prepare a^1 in Montgomery domain
1101 assert(BN_ucmp(a, m) < 0);
1102 if (!BN_to_montgomery(&am, a, mont, ctx)) {
1106 #if defined(OPENSSL_BN_ASM_MONT5)
1107 // This optimization uses ideas from http://eprint.iacr.org/2011/239,
1108 // specifically optimization of cache-timing attack countermeasures
1109 // and pre-computation optimization.
1111 // Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
1112 // 512-bit RSA is hardly relevant, we omit it to spare size...
1113 if (window == 5 && top > 1) {
1114 const BN_ULONG *n0 = mont->n0;
1117 // BN_to_montgomery can contaminate words above .top
1118 // [in BN_DEBUG[_DEBUG] build]...
1119 for (i = am.width; i < top; i++) {
1122 for (i = tmp.width; i < top; i++) {
1126 // copy mont->N.d[] to improve cache locality
1127 for (np = am.d + top, i = 0; i < top; i++) {
1128 np[i] = mont->N.d[i];
1131 bn_scatter5(tmp.d, top, powerbuf, 0);
1132 bn_scatter5(am.d, am.width, powerbuf, 1);
1133 bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
1134 bn_scatter5(tmp.d, top, powerbuf, 2);
1136 // same as above, but uses squaring for 1/2 of operations
1137 for (i = 4; i < 32; i *= 2) {
1138 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1139 bn_scatter5(tmp.d, top, powerbuf, i);
1141 for (i = 3; i < 8; i += 2) {
1143 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
1144 bn_scatter5(tmp.d, top, powerbuf, i);
1145 for (j = 2 * i; j < 32; j *= 2) {
1146 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1147 bn_scatter5(tmp.d, top, powerbuf, j);
1150 for (; i < 16; i += 2) {
1151 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
1152 bn_scatter5(tmp.d, top, powerbuf, i);
1153 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1154 bn_scatter5(tmp.d, top, powerbuf, 2 * i);
1156 for (; i < 32; i += 2) {
1157 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
1158 bn_scatter5(tmp.d, top, powerbuf, i);
1162 for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--) {
1163 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1165 bn_gather5(tmp.d, top, powerbuf, wvalue);
1167 // At this point |bits| is 4 mod 5 and at least -1. (|bits| is the first bit
1168 // that has not been read yet.)
1169 assert(bits >= -1 && (bits == -1 || bits % 5 == 4));
1171 // Scan the exponent one window at a time starting from the most
1172 // significant bits.
1175 for (wvalue = 0, i = 0; i < 5; i++, bits--) {
1176 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1179 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1180 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1181 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1182 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1183 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1184 bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
1187 const uint8_t *p_bytes = (const uint8_t *)p->d;
1188 assert(bits < max_bits);
1189 // |p = 0| has been handled as a special case, so |max_bits| is at least
1191 assert(max_bits >= 64);
1193 // If the first bit to be read lands in the last byte, unroll the first
1194 // iteration to avoid reading past the bounds of |p->d|. (After the first
1195 // iteration, we are guaranteed to be past the last byte.) Note |bits|
1196 // here is the top bit, inclusive.
1197 if (bits - 4 >= max_bits - 8) {
1198 // Read five bits from |bits-4| through |bits|, inclusive.
1199 wvalue = p_bytes[p->width * BN_BYTES - 1];
1200 wvalue >>= (bits - 4) & 7;
1203 bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
1206 // Read five bits from |bits-4| through |bits|, inclusive.
1207 int first_bit = bits - 4;
1209 OPENSSL_memcpy(&val, p_bytes + (first_bit >> 3), sizeof(val));
1210 val >>= first_bit & 7;
1213 bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, val);
1217 ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top);
1220 if (!BN_copy(rr, &tmp)) {
1223 goto err; // non-zero ret means it's not error
1228 copy_to_prebuf(&tmp, top, powerbuf, 0, window);
1229 copy_to_prebuf(&am, top, powerbuf, 1, window);
1231 // If the window size is greater than 1, then calculate
1232 // val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1)
1233 // (even powers could instead be computed as (a^(i/2))^2
1234 // to use the slight performance advantage of sqr over mul).
1236 if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx)) {
1240 copy_to_prebuf(&tmp, top, powerbuf, 2, window);
1242 for (i = 3; i < numPowers; i++) {
1243 // Calculate a^i = a^(i-1) * a
1244 if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx)) {
1248 copy_to_prebuf(&tmp, top, powerbuf, i, window);
1253 for (wvalue = 0, i = bits % window; i >= 0; i--, bits--) {
1254 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1256 if (!copy_from_prebuf(&tmp, top, powerbuf, wvalue, window)) {
1260 // Scan the exponent one window at a time starting from the most
1261 // significant bits.
1263 wvalue = 0; // The 'value' of the window
1265 // Scan the window, squaring the result as we go
1266 for (i = 0; i < window; i++, bits--) {
1267 if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx)) {
1270 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1273 // Fetch the appropriate pre-computed value from the pre-buf
1274 if (!copy_from_prebuf(&am, top, powerbuf, wvalue, window)) {
1278 // Multiply the result into the intermediate result
1279 if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx)) {
1285 // Convert the final result from montgomery to standard format
1286 if (!BN_from_montgomery(rr, &tmp, mont, ctx)) {
1292 BN_MONT_CTX_free(new_mont);
1293 BN_clear_free(new_a);
1294 OPENSSL_free(powerbufFree);
1298 int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
1299 const BIGNUM *m, BN_CTX *ctx,
1300 const BN_MONT_CTX *mont) {
1306 if (!BN_set_word(&a_bignum, a)) {
1307 OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR);
1311 ret = BN_mod_exp_mont(rr, &a_bignum, p, m, ctx, mont);
1319 #define TABLE_SIZE 32
1321 int BN_mod_exp2_mont(BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1,
1322 const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m,
1323 BN_CTX *ctx, const BN_MONT_CTX *mont) {
1328 BN_MONT_CTX *new_mont = NULL;
1330 // Allocate a montgomery context if it was not supplied by the caller.
1332 new_mont = BN_MONT_CTX_new_for_modulus(m, ctx);
1333 if (new_mont == NULL) {
1339 // BN_mod_mul_montgomery removes one Montgomery factor, so passing one
1340 // Montgomery-encoded and one non-Montgomery-encoded value gives a
1341 // non-Montgomery-encoded result.
1342 if (!BN_mod_exp_mont(rr, a1, p1, m, ctx, mont) ||
1343 !BN_mod_exp_mont(&tmp, a2, p2, m, ctx, mont) ||
1344 !BN_to_montgomery(rr, rr, mont, ctx) ||
1345 !BN_mod_mul_montgomery(rr, rr, &tmp, mont, ctx)) {
1352 BN_MONT_CTX_free(new_mont);