| // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | #include <openssl/bn.h> |
| 16 |
| 17 | #include <assert.h> |
| 18 | #include <limits.h> |
| 19 | #include <stdlib.h> |
| 20 | #include <string.h> |
| 21 |
| 22 | #include <openssl/err.h> |
| 23 | #include <openssl/mem.h> |
| 24 |
| 25 | #include "internal.h" |
| 26 | #include "rsaz_exp.h" |
| 27 |
| 28 | #if defined(OPENSSL_BN_ASM_MONT5) |
| 29 |
| 30 | // bn_mul_mont_gather5 multiples loads index |power| of |table|, multiplies it |
| 31 | // by |ap| modulo |np|, and stores the result in |rp|. The values are |num| |
| 32 | // words long and represented in Montgomery form. |n0| is a pointer to the |
| 33 | // corresponding field in |BN_MONT_CTX|. |table| must be aligned to at least |
| 34 | // 16 bytes. |power| must be less than 32 and is treated as secret. |
| 35 | // |
| 36 | // WARNING: This function implements Almost Montgomery Multiplication from |
| 37 | // https://eprint.iacr.org/2011/239. The inputs do not need to be fully reduced. |
| 38 | // However, even if they are fully reduced, the output may not be. |
| 39 | static void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, |
| 40 | const BN_ULONG *table, const BN_ULONG *np, |
| 41 | const BN_ULONG *n0, int num, int power) { |
| 42 | if (bn_mulx4x_mont_gather5_capable(num)) { |
| 43 | bn_mulx4x_mont_gather5(rp, ap, table, np, n0, num, power); |
| 44 | } else if (bn_mul4x_mont_gather5_capable(num)) { |
| 45 | bn_mul4x_mont_gather5(rp, ap, table, np, n0, num, power); |
| 46 | } else { |
| 47 | bn_mul_mont_gather5_nohw(rp, ap, table, np, n0, num, power); |
| 48 | } |
| 49 | } |
| 50 |
| 51 | // bn_power5 squares |ap| five times and multiplies it by the value stored at |
| 52 | // index |power| of |table|, modulo |np|. It stores the result in |rp|. The |
| 53 | // values are |num| words long and represented in Montgomery form. |n0| is a |
| 54 | // pointer to the corresponding field in |BN_MONT_CTX|. |num| must be divisible |
| 55 | // by 8. |power| must be less than 32 and is treated as secret. |
| 56 | // |
| 57 | // WARNING: This function implements Almost Montgomery Multiplication from |
| 58 | // https://eprint.iacr.org/2011/239. The inputs do not need to be fully reduced. |
| 59 | // However, even if they are fully reduced, the output may not be. |
| 60 | static void bn_power5(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *table, |
| 61 | const BN_ULONG *np, const BN_ULONG *n0, int num, |
| 62 | int power) { |
| 63 | assert(bn_power5_capable(num)); |
| 64 | if (bn_powerx5_capable(num)) { |
| 65 | bn_powerx5(rp, ap, table, np, n0, num, power); |
| 66 | } else { |
| 67 | bn_power5_nohw(rp, ap, table, np, n0, num, power); |
| 68 | } |
| 69 | } |
| 70 |
| 71 | #endif // defined(OPENSSL_BN_ASM_MONT5) |
| 72 |
| 73 | // BN_window_bits_for_exponent_size returns sliding window size for mod_exp with |
| 74 | // a |b| bit exponent. |
| 75 | // |
| 76 | // For window size 'w' (w >= 2) and a random 'b' bits exponent, the number of |
| 77 | // multiplications is a constant plus on average |
| 78 | // |
| 79 | // 2^(w-1) + (b-w)/(w+1); |
| 80 | // |
| 81 | // here 2^(w-1) is for precomputing the table (we actually need entries only |
| 82 | // for windows that have the lowest bit set), and (b-w)/(w+1) is an |
| 83 | // approximation for the expected number of w-bit windows, not counting the |
| 84 | // first one. |
| 85 | // |
| 86 | // Thus we should use |
| 87 | // |
| 88 | // w >= 6 if b > 671 |
| 89 | // w = 5 if 671 > b > 239 |
| 90 | // w = 4 if 239 > b > 79 |
| 91 | // w = 3 if 79 > b > 23 |
| 92 | // w <= 2 if 23 > b |
| 93 | // |
| 94 | // (with draws in between). Very small exponents are often selected |
| 95 | // with low Hamming weight, so we use w = 1 for b <= 23. |
| 96 | static int BN_window_bits_for_exponent_size(size_t b) { |
| 97 | if (b > 671) { |
| 98 | return 6; |
| 99 | } |
| 100 | if (b > 239) { |
| 101 | return 5; |
| 102 | } |
| 103 | if (b > 79) { |
| 104 | return 4; |
| 105 | } |
| 106 | if (b > 23) { |
| 107 | return 3; |
| 108 | } |
| 109 | return 1; |
| 110 | } |
| 111 |
| 112 | // TABLE_SIZE is the maximum precomputation table size for *variable* sliding |
| 113 | // windows. This must be 2^(max_window - 1), where max_window is the largest |
| 114 | // value returned from |BN_window_bits_for_exponent_size|. |
| 115 | #define TABLE_SIZE 32 |
| 116 |
| 117 | // TABLE_BITS_SMALL is the smallest value returned from |
| 118 | // |BN_window_bits_for_exponent_size| when |b| is at most |BN_BITS2| * |
| 119 | // |BN_SMALL_MAX_WORDS| words. |
| 120 | #define TABLE_BITS_SMALL 5 |
| 121 |
| 122 | // TABLE_SIZE_SMALL is the same as |TABLE_SIZE|, but when |b| is at most |
| 123 | // |BN_BITS2| * |BN_SMALL_MAX_WORDS|. |
| 124 | #define TABLE_SIZE_SMALL (1 << (TABLE_BITS_SMALL - 1)) |
| 125 |
| 126 | int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, |
| 127 | const BIGNUM *m, BN_CTX *ctx, const BN_MONT_CTX *mont) { |
| 128 | if (!BN_is_odd(m)) { |
| 129 | OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS); |
| 130 | return 0; |
| 131 | } |
| 132 | if (m->neg) { |
| 133 | OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); |
| 134 | return 0; |
| 135 | } |
| 136 | // |a| is secret, but |a < m| is not. |
| 137 | if (a->neg || constant_time_declassify_int(BN_ucmp(a, m)) >= 0) { |
| 138 | OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED); |
| 139 | return 0; |
| 140 | } |
| 141 |
| 142 | int bits = BN_num_bits(p); |
| 143 | if (bits == 0) { |
| 144 | // x**0 mod 1 is still zero. |
| 145 | if (BN_abs_is_word(m, 1)) { |
| 146 | BN_zero(rr); |
| 147 | return 1; |
| 148 | } |
| 149 | return BN_one(rr); |
| 150 | } |
| 151 |
| 152 | BIGNUM *val[TABLE_SIZE]; |
| 153 |
| 154 | bssl::BN_CTXScope scope(ctx); |
| 155 | BIGNUM *r = BN_CTX_get(ctx); |
| 156 | val[0] = BN_CTX_get(ctx); |
| 157 | if (r == NULL || val[0] == NULL) { |
| 158 | return 0; |
| 159 | } |
| 160 |
| 161 | // Allocate a montgomery context if it was not supplied by the caller. |
| 162 | bssl::UniquePtr<BN_MONT_CTX> new_mont; |
| 163 | if (mont == nullptr) { |
| 164 | new_mont.reset(BN_MONT_CTX_new_consttime(m, ctx)); |
| 165 | if (new_mont == nullptr) { |
| 166 | return 0; |
| 167 | } |
| 168 | mont = new_mont.get(); |
| 169 | } |
| 170 |
| 171 | // We exponentiate by looking at sliding windows of the exponent and |
| 172 | // precomputing powers of |a|. Windows may be shifted so they always end on a |
| 173 | // set bit, so only precompute odd powers. We compute val[i] = a^(2*i + 1) |
| 174 | // for i = 0 to 2^(window-1), all in Montgomery form. |
| 175 | int window = BN_window_bits_for_exponent_size(bits); |
| 176 | if (!BN_to_montgomery(val[0], a, mont, ctx)) { |
| 177 | return 0; |
| 178 | } |
| 179 | if (window > 1) { |
| 180 | BIGNUM *d = BN_CTX_get(ctx); |
| 181 | if (d == NULL || !BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx)) { |
| 182 | return 0; |
| 183 | } |
| 184 | for (int i = 1; i < 1 << (window - 1); i++) { |
| 185 | val[i] = BN_CTX_get(ctx); |
| 186 | if (val[i] == NULL || |
| 187 | !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx)) { |
| 188 | return 0; |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 |
| 193 | // |p| is non-zero, so at least one window is non-zero. To save some |
| 194 | // multiplications, defer initializing |r| until then. |
| 195 | int r_is_one = 1; |
| 196 | int wstart = bits - 1; // The top bit of the window. |
| 197 | for (;;) { |
| 198 | if (!BN_is_bit_set(p, wstart)) { |
| 199 | if (!r_is_one && !BN_mod_mul_montgomery(r, r, r, mont, ctx)) { |
| 200 | return 0; |
| 201 | } |
| 202 | if (wstart == 0) { |
| 203 | break; |
| 204 | } |
| 205 | wstart--; |
| 206 | continue; |
| 207 | } |
| 208 |
| 209 | // We now have wstart on a set bit. Find the largest window we can use. |
| 210 | int wvalue = 1; |
| 211 | int wsize = 0; |
| 212 | for (int i = 1; i < window && i <= wstart; i++) { |
| 213 | if (BN_is_bit_set(p, wstart - i)) { |
| 214 | wvalue <<= (i - wsize); |
| 215 | wvalue |= 1; |
| 216 | wsize = i; |
| 217 | } |
| 218 | } |
| 219 |
| 220 | // Shift |r| to the end of the window. |
| 221 | if (!r_is_one) { |
| 222 | for (int i = 0; i < wsize + 1; i++) { |
| 223 | if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) { |
| 224 | return 0; |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 |
| 229 | assert(wvalue & 1); |
| 230 | assert(wvalue < (1 << window)); |
| 231 | if (r_is_one) { |
| 232 | if (!BN_copy(r, val[wvalue >> 1])) { |
| 233 | return 0; |
| 234 | } |
| 235 | } else if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx)) { |
| 236 | return 0; |
| 237 | } |
| 238 |
| 239 | r_is_one = 0; |
| 240 | if (wstart == wsize) { |
| 241 | break; |
| 242 | } |
| 243 | wstart -= wsize + 1; |
| 244 | } |
| 245 |
| 246 | // |p| is non-zero, so |r_is_one| must be cleared at some point. |
| 247 | assert(!r_is_one); |
| 248 |
| 249 | return BN_from_montgomery(rr, r, mont, ctx); |
| 250 | } |
| 251 |
| 252 | void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num, |
| 253 | const BN_ULONG *p, size_t num_p, |
| 254 | const BN_MONT_CTX *mont) { |
| 255 | if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS || |
| 256 | num_p > SIZE_MAX / BN_BITS2) { |
| 257 | abort(); |
| 258 | } |
| 259 | assert(BN_is_odd(&mont->N)); |
| 260 |
| 261 | // Count the number of bits in |p|, skipping leading zeros. Note this function |
| 262 | // treats |p| as public. |
| 263 | while (num_p != 0 && p[num_p - 1] == 0) { |
| 264 | num_p--; |
| 265 | } |
| 266 | if (num_p == 0) { |
| 267 | bn_from_montgomery_small(r, num, mont->RR.d, num, mont); |
| 268 | return; |
| 269 | } |
| 270 | size_t bits = BN_num_bits_word(p[num_p - 1]) + (num_p - 1) * BN_BITS2; |
| 271 | assert(bits != 0); |
| 272 |
| 273 | // We exponentiate by looking at sliding windows of the exponent and |
| 274 | // precomputing powers of |a|. Windows may be shifted so they always end on a |
| 275 | // set bit, so only precompute odd powers. We compute val[i] = a^(2*i + 1) for |
| 276 | // i = 0 to 2^(window-1), all in Montgomery form. |
| 277 | unsigned window = BN_window_bits_for_exponent_size(bits); |
| 278 | if (window > TABLE_BITS_SMALL) { |
| 279 | window = TABLE_BITS_SMALL; // Tolerate excessively large |p|. |
| 280 | } |
| 281 | BN_ULONG val[TABLE_SIZE_SMALL][BN_SMALL_MAX_WORDS]; |
| 282 | OPENSSL_memcpy(val[0], a, num * sizeof(BN_ULONG)); |
| 283 | if (window > 1) { |
| 284 | BN_ULONG d[BN_SMALL_MAX_WORDS]; |
| 285 | bn_mod_mul_montgomery_small(d, val[0], val[0], num, mont); |
| 286 | for (unsigned i = 1; i < 1u << (window - 1); i++) { |
| 287 | bn_mod_mul_montgomery_small(val[i], val[i - 1], d, num, mont); |
| 288 | } |
| 289 | } |
| 290 |
| 291 | // |p| is non-zero, so at least one window is non-zero. To save some |
| 292 | // multiplications, defer initializing |r| until then. |
| 293 | int r_is_one = 1; |
| 294 | size_t wstart = bits - 1; // The top bit of the window. |
| 295 | for (;;) { |
| 296 | if (!bn_is_bit_set_words(p, num_p, wstart)) { |
| 297 | if (!r_is_one) { |
| 298 | bn_mod_mul_montgomery_small(r, r, r, num, mont); |
| 299 | } |
| 300 | if (wstart == 0) { |
| 301 | break; |
| 302 | } |
| 303 | wstart--; |
| 304 | continue; |
| 305 | } |
| 306 |
| 307 | // We now have wstart on a set bit. Find the largest window we can use. |
| 308 | unsigned wvalue = 1; |
| 309 | unsigned wsize = 0; |
| 310 | for (unsigned i = 1; i < window && i <= wstart; i++) { |
| 311 | if (bn_is_bit_set_words(p, num_p, wstart - i)) { |
| 312 | wvalue <<= (i - wsize); |
| 313 | wvalue |= 1; |
| 314 | wsize = i; |
| 315 | } |
| 316 | } |
| 317 |
| 318 | // Shift |r| to the end of the window. |
| 319 | if (!r_is_one) { |
| 320 | for (unsigned i = 0; i < wsize + 1; i++) { |
| 321 | bn_mod_mul_montgomery_small(r, r, r, num, mont); |
| 322 | } |
| 323 | } |
| 324 |
| 325 | assert(wvalue & 1); |
| 326 | assert(wvalue < (1u << window)); |
| 327 | if (r_is_one) { |
| 328 | OPENSSL_memcpy(r, val[wvalue >> 1], num * sizeof(BN_ULONG)); |
| 329 | } else { |
| 330 | bn_mod_mul_montgomery_small(r, r, val[wvalue >> 1], num, mont); |
| 331 | } |
| 332 | r_is_one = 0; |
| 333 | if (wstart == wsize) { |
| 334 | break; |
| 335 | } |
| 336 | wstart -= wsize + 1; |
| 337 | } |
| 338 |
| 339 | // |p| is non-zero, so |r_is_one| must be cleared at some point. |
| 340 | assert(!r_is_one); |
| 341 | OPENSSL_cleanse(val, sizeof(val)); |
| 342 | } |
| 343 |
| 344 | void bn_mod_inverse0_prime_mont_small(BN_ULONG *r, const BN_ULONG *a, |
| 345 | size_t num, const BN_MONT_CTX *mont) { |
| 346 | if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS) { |
| 347 | abort(); |
| 348 | } |
| 349 |
| 350 | // Per Fermat's Little Theorem, a^-1 = a^(p-2) (mod p) for p prime. |
| 351 | BN_ULONG p_minus_two[BN_SMALL_MAX_WORDS]; |
| 352 | const BN_ULONG *p = mont->N.d; |
| 353 | OPENSSL_memcpy(p_minus_two, p, num * sizeof(BN_ULONG)); |
| 354 | if (p_minus_two[0] >= 2) { |
| 355 | p_minus_two[0] -= 2; |
| 356 | } else { |
| 357 | p_minus_two[0] -= 2; |
| 358 | for (size_t i = 1; i < num; i++) { |
| 359 | if (p_minus_two[i]-- != 0) { |
| 360 | break; |
| 361 | } |
| 362 | } |
| 363 | } |
| 364 |
| 365 | bn_mod_exp_mont_small(r, a, num, p_minus_two, num, mont); |
| 366 | } |
| 367 |
| 368 | static void copy_to_prebuf(const BIGNUM *b, int top, BN_ULONG *table, int idx, |
| 369 | int window) { |
| 370 | int ret = bn_copy_words(table + idx * top, top, b); |
| 371 | assert(ret); // |b| is guaranteed to fit. |
| 372 | (void)ret; |
| 373 | } |
| 374 |
| 375 | static int copy_from_prebuf(BIGNUM *b, int top, const BN_ULONG *table, int idx, |
| 376 | int window) { |
| 377 | if (!bn_wexpand(b, top)) { |
| 378 | return 0; |
| 379 | } |
| 380 |
| 381 | OPENSSL_memset(b->d, 0, sizeof(BN_ULONG) * top); |
| 382 | const int width = 1 << window; |
| 383 | for (int i = 0; i < width; i++, table += top) { |
| 384 | // Use a value barrier to prevent Clang from adding a branch when |i != idx| |
| 385 | // and making this copy not constant time. Clang is still allowed to learn |
| 386 | // that |mask| is constant across the inner loop, so this won't inhibit any |
| 387 | // vectorization it might do. |
| 388 | BN_ULONG mask = value_barrier_w(constant_time_eq_int(i, idx)); |
| 389 | for (int j = 0; j < top; j++) { |
| 390 | b->d[j] |= table[j] & mask; |
| 391 | } |
| 392 | } |
| 393 |
| 394 | b->width = top; |
| 395 | return 1; |
| 396 | } |
| 397 |
| 398 | // Window sizes optimized for fixed window size modular exponentiation |
| 399 | // algorithm (BN_mod_exp_mont_consttime). |
| 400 | // |
| 401 | // TODO(davidben): These window sizes were originally set for 64-byte cache |
| 402 | // lines with a cache-line-dependent constant-time mitigation. They can probably |
| 403 | // be revised now that our implementation is no longer cache-time-dependent. |
| 404 | #define BN_window_bits_for_ctime_exponent_size(b) \ |
| 405 | ((b) > 937 ? 6 : (b) > 306 ? 5 : (b) > 89 ? 4 : (b) > 22 ? 3 : 1) |
| 406 | #define BN_MAX_MOD_EXP_CTIME_WINDOW (6) |
| 407 |
| 408 | // This variant of |BN_mod_exp_mont| uses fixed windows and fixed memory access |
| 409 | // patterns to protect secret exponents (cf. the hyper-threading timing attacks |
| 410 | // pointed out by Colin Percival, |
| 411 | // http://www.daemonology.net/hyperthreading-considered-harmful/) |
| 412 | int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, |
| 413 | const BIGNUM *m, BN_CTX *ctx, |
| 414 | const BN_MONT_CTX *mont) { |
| 415 | int i, ret = 0, wvalue; |
| 416 | BN_MONT_CTX *new_mont = NULL; |
| 417 |
| 418 | void *powerbuf_free = NULL; |
| 419 | size_t powerbuf_len = 0; |
| 420 | BN_ULONG *powerbuf = NULL; |
| 421 |
| 422 | if (!BN_is_odd(m)) { |
| 423 | OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS); |
| 424 | return 0; |
| 425 | } |
| 426 | if (m->neg) { |
| 427 | OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); |
| 428 | return 0; |
| 429 | } |
| 430 | // |a| is secret, but it is required to be in range, so these comparisons may |
| 431 | // be leaked. |
| 432 | if (a->neg || constant_time_declassify_int(BN_ucmp(a, m) >= 0)) { |
| 433 | OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED); |
| 434 | return 0; |
| 435 | } |
| 436 |
| 437 | // Use all bits stored in |p|, rather than |BN_num_bits|, so we do not leak |
| 438 | // whether the top bits are zero. |
| 439 | int max_bits = p->width * BN_BITS2; |
| 440 | int bits = max_bits; |
| 441 | if (bits == 0) { |
| 442 | // x**0 mod 1 is still zero. |
| 443 | if (BN_abs_is_word(m, 1)) { |
| 444 | BN_zero(rr); |
| 445 | return 1; |
| 446 | } |
| 447 | return BN_one(rr); |
| 448 | } |
| 449 |
| 450 | // Allocate a montgomery context if it was not supplied by the caller. |
| 451 | int top, num_powers, window; |
| 452 | if (mont == NULL) { |
| 453 | new_mont = BN_MONT_CTX_new_consttime(m, ctx); |
| 454 | if (new_mont == NULL) { |
| 455 | goto err; |
| 456 | } |
| 457 | mont = new_mont; |
| 458 | } |
| 459 |
| 460 | // Use the width in |mont->N|, rather than the copy in |m|. The assembly |
| 461 | // implementation assumes it can use |top| to size R. |
| 462 | top = mont->N.width; |
| 463 |
| 464 | #if defined(OPENSSL_BN_ASM_MONT5) || defined(RSAZ_ENABLED) |
| 465 | // Share one large stack-allocated buffer between the RSAZ and non-RSAZ code |
| 466 | // paths. If we were to use separate static buffers for each then there is |
| 467 | // some chance that both large buffers would be allocated on the stack, |
| 468 | // causing the stack space requirement to be truly huge (~10KB). |
| 469 | alignas(MOD_EXP_CTIME_ALIGN) BN_ULONG storage[MOD_EXP_CTIME_STORAGE_LEN]; |
| 470 | #endif |
| 471 | #if defined(RSAZ_ENABLED) |
| 472 | // If the size of the operands allow it, perform the optimized RSAZ |
| 473 | // exponentiation. For further information see crypto/fipsmodule/bn/rsaz_exp.c |
| 474 | // and accompanying assembly modules. |
| 475 | if (a->width == 16 && p->width == 16 && BN_num_bits(m) == 1024 && |
| 476 | rsaz_avx2_preferred()) { |
| 477 | if (!bn_wexpand(rr, 16)) { |
| 478 | goto err; |
| 479 | } |
| 480 | RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d, mont->n0[0], |
| 481 | storage); |
| 482 | rr->width = 16; |
| 483 | rr->neg = 0; |
| 484 | ret = 1; |
| 485 | goto err; |
| 486 | } |
| 487 | #endif |
| 488 |
| 489 | // Get the window size to use with size of p. |
| 490 | window = BN_window_bits_for_ctime_exponent_size(bits); |
| 491 | assert(window <= BN_MAX_MOD_EXP_CTIME_WINDOW); |
| 492 |
| 493 | // Calculating |powerbuf_len| below cannot overflow because of the bound on |
| 494 | // Montgomery reduction. |
| 495 | assert((size_t)top <= BN_MONTGOMERY_MAX_WORDS); |
| 496 | static_assert( |
| 497 | BN_MONTGOMERY_MAX_WORDS <= |
| 498 | INT_MAX / sizeof(BN_ULONG) / ((1 << BN_MAX_MOD_EXP_CTIME_WINDOW) + 3), |
| 499 | "powerbuf_len may overflow"); |
| 500 |
| 501 | #if defined(OPENSSL_BN_ASM_MONT5) |
| 502 | if (window >= 5) { |
| 503 | window = 5; // ~5% improvement for RSA2048 sign, and even for RSA4096 |
| 504 | // Reserve space for the |mont->N| copy. |
| 505 | powerbuf_len += top * sizeof(mont->N.d[0]); |
| 506 | } |
| 507 | #endif |
| 508 |
| 509 | // Allocate a buffer large enough to hold all of the pre-computed |
| 510 | // powers of |am|, |am| itself, and |tmp|. |
| 511 | num_powers = 1 << window; |
| 512 | powerbuf_len += sizeof(m->d[0]) * top * (num_powers + 2); |
| 513 |
| 514 | #if defined(OPENSSL_BN_ASM_MONT5) |
| 515 | if (powerbuf_len <= sizeof(storage)) { |
| 516 | powerbuf = storage; |
| 517 | } |
| 518 | // |storage| is more than large enough to handle 1024-bit inputs. |
| 519 | assert(powerbuf != NULL || top * BN_BITS2 > 1024); |
| 520 | #endif |
| 521 | if (powerbuf == NULL) { |
| 522 | powerbuf_free = OPENSSL_malloc(powerbuf_len + MOD_EXP_CTIME_ALIGN); |
| 523 | if (powerbuf_free == NULL) { |
| 524 | goto err; |
| 525 | } |
| 526 | powerbuf = reinterpret_cast<BN_ULONG *>( |
| 527 | align_pointer(powerbuf_free, MOD_EXP_CTIME_ALIGN)); |
| 528 | } |
| 529 | OPENSSL_memset(powerbuf, 0, powerbuf_len); |
| 530 |
| 531 | // Place |tmp| and |am| right after powers table. |
| 532 | BIGNUM tmp, am; |
| 533 | tmp.d = powerbuf + top * num_powers; |
| 534 | am.d = tmp.d + top; |
| 535 | tmp.width = am.width = 0; |
| 536 | tmp.dmax = am.dmax = top; |
| 537 | tmp.neg = am.neg = 0; |
| 538 | tmp.flags = am.flags = BN_FLG_STATIC_DATA; |
| 539 |
| 540 | if (!bn_one_to_montgomery(&tmp, mont, ctx) || !bn_resize_words(&tmp, top)) { |
| 541 | goto err; |
| 542 | } |
| 543 |
| 544 | // Prepare a^1 in the Montgomery domain. |
| 545 | assert(!a->neg); |
| 546 | declassify_assert(BN_ucmp(a, m) < 0); |
| 547 | if (!BN_to_montgomery(&am, a, mont, ctx) || !bn_resize_words(&am, top)) { |
| 548 | goto err; |
| 549 | } |
| 550 |
| 551 | #if defined(OPENSSL_BN_ASM_MONT5) |
| 552 | // This optimization uses ideas from https://eprint.iacr.org/2011/239, |
| 553 | // specifically optimization of cache-timing attack countermeasures, |
| 554 | // pre-computation optimization, and Almost Montgomery Multiplication. |
| 555 | // |
| 556 | // The paper discusses a 4-bit window to optimize 512-bit modular |
| 557 | // exponentiation, used in RSA-1024 with CRT, but RSA-1024 is no longer |
| 558 | // important. |
| 559 | // |
| 560 | // |bn_mul_mont_gather5| and |bn_power5| implement the "almost" reduction |
| 561 | // variant, so the values here may not be fully reduced. They are bounded by R |
| 562 | // (i.e. they fit in |top| words), not |m|. Additionally, we pass these |
| 563 | // "almost" reduced inputs into |bn_mul_mont|, which implements the normal |
| 564 | // reduction variant. Given those inputs, |bn_mul_mont| may not give reduced |
| 565 | // output, but it will still produce "almost" reduced output. |
| 566 | // |
| 567 | // TODO(davidben): Using "almost" reduction complicates analysis of this code, |
| 568 | // and its interaction with other parts of the project. Determine whether this |
| 569 | // is actually necessary for performance. |
| 570 | if (window == 5 && top > 1) { |
| 571 | // Copy |mont->N| to improve cache locality. |
| 572 | BN_ULONG *np = am.d + top; |
| 573 | for (i = 0; i < top; i++) { |
| 574 | np[i] = mont->N.d[i]; |
| 575 | } |
| 576 |
| 577 | // Fill |powerbuf| with the first 32 powers of |am|. |
| 578 | const BN_ULONG *n0 = mont->n0; |
| 579 | bn_scatter5(tmp.d, top, powerbuf, 0); |
| 580 | bn_scatter5(am.d, am.width, powerbuf, 1); |
| 581 | bn_mul_mont(tmp.d, am.d, am.d, np, n0, top); |
| 582 | bn_scatter5(tmp.d, top, powerbuf, 2); |
| 583 |
| 584 | // Square to compute powers of two. |
| 585 | for (i = 4; i < 32; i *= 2) { |
| 586 | bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); |
| 587 | bn_scatter5(tmp.d, top, powerbuf, i); |
| 588 | } |
| 589 | // Compute odd powers |i| based on |i - 1|, then all powers |i * 2^j|. |
| 590 | for (i = 3; i < 32; i += 2) { |
| 591 | bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); |
| 592 | bn_scatter5(tmp.d, top, powerbuf, i); |
| 593 | for (int j = 2 * i; j < 32; j *= 2) { |
| 594 | bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); |
| 595 | bn_scatter5(tmp.d, top, powerbuf, j); |
| 596 | } |
| 597 | } |
| 598 |
| 599 | bits--; |
| 600 | for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--) { |
| 601 | wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); |
| 602 | } |
| 603 | bn_gather5(tmp.d, top, powerbuf, wvalue); |
| 604 |
| 605 | // At this point |bits| is 4 mod 5 and at least -1. (|bits| is the first bit |
| 606 | // that has not been read yet.) |
| 607 | assert(bits >= -1 && (bits == -1 || bits % 5 == 4)); |
| 608 |
| 609 | // Scan the exponent one window at a time starting from the most |
| 610 | // significant bits. |
| 611 | if (!bn_power5_capable(top)) { |
| 612 | while (bits >= 0) { |
| 613 | for (wvalue = 0, i = 0; i < 5; i++, bits--) { |
| 614 | wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); |
| 615 | } |
| 616 |
| 617 | bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); |
| 618 | bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); |
| 619 | bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); |
| 620 | bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); |
| 621 | bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); |
| 622 | bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue); |
| 623 | } |
| 624 | } else { |
| 625 | const uint8_t *p_bytes = (const uint8_t *)p->d; |
| 626 | assert(bits < max_bits); |
| 627 | // |p = 0| has been handled as a special case, so |max_bits| is at least |
| 628 | // one word. |
| 629 | assert(max_bits >= 64); |
| 630 |
| 631 | // If the first bit to be read lands in the last byte, unroll the first |
| 632 | // iteration to avoid reading past the bounds of |p->d|. (After the first |
| 633 | // iteration, we are guaranteed to be past the last byte.) Note |bits| |
| 634 | // here is the top bit, inclusive. |
| 635 | if (bits - 4 >= max_bits - 8) { |
| 636 | // Read five bits from |bits-4| through |bits|, inclusive. |
| 637 | wvalue = p_bytes[p->width * BN_BYTES - 1]; |
| 638 | wvalue >>= (bits - 4) & 7; |
| 639 | wvalue &= 0x1f; |
| 640 | bits -= 5; |
| 641 | bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue); |
| 642 | } |
| 643 | while (bits >= 0) { |
| 644 | // Read five bits from |bits-4| through |bits|, inclusive. |
| 645 | int first_bit = bits - 4; |
| 646 | uint16_t val; |
| 647 | OPENSSL_memcpy(&val, p_bytes + (first_bit >> 3), sizeof(val)); |
| 648 | val >>= first_bit & 7; |
| 649 | val &= 0x1f; |
| 650 | bits -= 5; |
| 651 | bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, val); |
| 652 | } |
| 653 | } |
| 654 | // The result is now in |tmp| in Montgomery form, but it may not be fully |
| 655 | // reduced. This is within bounds for |BN_from_montgomery| (tmp < R <= m*R) |
| 656 | // so it will, when converting from Montgomery form, produce a fully reduced |
| 657 | // result. |
| 658 | // |
| 659 | // This differs from Figure 2 of the paper, which uses AMM(h, 1) to convert |
| 660 | // from Montgomery form with unreduced output, followed by an extra |
| 661 | // reduction step. In the paper's terminology, we replace steps 9 and 10 |
| 662 | // with MM(h, 1). |
| 663 | } else |
| 664 | #endif |
| 665 | { |
| 666 | copy_to_prebuf(&tmp, top, powerbuf, 0, window); |
| 667 | copy_to_prebuf(&am, top, powerbuf, 1, window); |
| 668 |
| 669 | // If the window size is greater than 1, then calculate |
| 670 | // val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) |
| 671 | // (even powers could instead be computed as (a^(i/2))^2 |
| 672 | // to use the slight performance advantage of sqr over mul). |
| 673 | if (window > 1) { |
| 674 | if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx)) { |
| 675 | goto err; |
| 676 | } |
| 677 |
| 678 | copy_to_prebuf(&tmp, top, powerbuf, 2, window); |
| 679 |
| 680 | for (i = 3; i < num_powers; i++) { |
| 681 | // Calculate a^i = a^(i-1) * a |
| 682 | if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx)) { |
| 683 | goto err; |
| 684 | } |
| 685 |
| 686 | copy_to_prebuf(&tmp, top, powerbuf, i, window); |
| 687 | } |
| 688 | } |
| 689 |
| 690 | bits--; |
| 691 | for (wvalue = 0, i = bits % window; i >= 0; i--, bits--) { |
| 692 | wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); |
| 693 | } |
| 694 | if (!copy_from_prebuf(&tmp, top, powerbuf, wvalue, window)) { |
| 695 | goto err; |
| 696 | } |
| 697 |
| 698 | // Scan the exponent one window at a time starting from the most |
| 699 | // significant bits. |
| 700 | while (bits >= 0) { |
| 701 | wvalue = 0; // The 'value' of the window |
| 702 |
| 703 | // Scan the window, squaring the result as we go |
| 704 | for (i = 0; i < window; i++, bits--) { |
| 705 | if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx)) { |
| 706 | goto err; |
| 707 | } |
| 708 | wvalue = (wvalue << 1) + BN_is_bit_set(p, bits); |
| 709 | } |
| 710 |
| 711 | // Fetch the appropriate pre-computed value from the pre-buf |
| 712 | if (!copy_from_prebuf(&am, top, powerbuf, wvalue, window)) { |
| 713 | goto err; |
| 714 | } |
| 715 |
| 716 | // Multiply the result into the intermediate result |
| 717 | if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx)) { |
| 718 | goto err; |
| 719 | } |
| 720 | } |
| 721 | } |
| 722 |
| 723 | // Convert the final result from Montgomery to standard format. If we used the |
| 724 | // |OPENSSL_BN_ASM_MONT5| codepath, |tmp| may not be fully reduced. It is only |
| 725 | // bounded by R rather than |m|. However, that is still within bounds for |
| 726 | // |BN_from_montgomery|, which implements full Montgomery reduction, not |
| 727 | // "almost" Montgomery reduction. |
| 728 | if (!BN_from_montgomery(rr, &tmp, mont, ctx)) { |
| 729 | goto err; |
| 730 | } |
| 731 | ret = 1; |
| 732 |
| 733 | err: |
| 734 | BN_MONT_CTX_free(new_mont); |
| 735 | if (powerbuf != NULL && powerbuf_free == NULL) { |
| 736 | OPENSSL_cleanse(powerbuf, powerbuf_len); |
| 737 | } |
| 738 | OPENSSL_free(powerbuf_free); |
| 739 | return ret; |
| 740 | } |
| 741 |