1 /* 2 * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved. 3 * 4 * Licensed under the OpenSSL license (the "License"). You may not use 5 * this file except in compliance with the License. You can obtain a copy 6 * in the file LICENSE in the source distribution or at 7 * https://www.openssl.org/source/license.html 8 */ 9 10 #include "internal/cryptlib.h" 11 #include "internal/constant_time.h" 12 #include "bn_local.h" 13 14 #include <stdlib.h> 15 #ifdef _WIN32 16 # include <malloc.h> 17 # ifndef alloca 18 # define alloca _alloca 19 # endif 20 #elif defined(__GNUC__) 21 # ifndef __SSP__ 22 # ifndef alloca 23 # define alloca(s) __builtin_alloca((s)) 24 # endif 25 # else 26 # undef alloca 27 # endif 28 #elif defined(__sun) 29 # include <alloca.h> 30 #endif 31 32 #include "rsaz_exp.h" 33 34 #undef SPARC_T4_MONT 35 #if defined(OPENSSL_BN_ASM_MONT) && (defined(__sparc__) || defined(__sparc)) 36 # include "sparc_arch.h" 37 extern unsigned int OPENSSL_sparcv9cap_P[]; 38 # define SPARC_T4_MONT 39 #endif 40 41 /* maximum precomputation table size for *variable* sliding windows */ 42 #define TABLE_SIZE 32 43 44 /* this one works - simple but works */ 45 int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) 46 { 47 int i, bits, ret = 0; 48 BIGNUM *v, *rr; 49 50 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 51 || BN_get_flags(a, BN_FLG_CONSTTIME) != 0) { 52 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ 53 BNerr(BN_F_BN_EXP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); 54 return 0; 55 } 56 57 BN_CTX_start(ctx); 58 rr = ((r == a) || (r == p)) ? BN_CTX_get(ctx) : r; 59 v = BN_CTX_get(ctx); 60 if (rr == NULL || v == NULL) 61 goto err; 62 63 if (BN_copy(v, a) == NULL) 64 goto err; 65 bits = BN_num_bits(p); 66 67 if (BN_is_odd(p)) { 68 if (BN_copy(rr, a) == NULL) 69 goto err; 70 } else { 71 if (!BN_one(rr)) 72 goto err; 73 } 74 75 for (i = 1; i < bits; i++) { 76 if (!BN_sqr(v, v, ctx)) 77 goto err; 78 if (BN_is_bit_set(p, i)) { 79 if (!BN_mul(rr, rr, v, ctx)) 80 goto err; 81 } 82 } 83 if (r != rr && BN_copy(r, rr) == NULL) 84 goto err; 85 86 ret = 1; 87 err: 88 BN_CTX_end(ctx); 89 bn_check_top(r); 90 return ret; 91 } 92 93 int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m, 94 BN_CTX *ctx) 95 { 96 int ret; 97 98 bn_check_top(a); 99 bn_check_top(p); 100 bn_check_top(m); 101 102 /*- 103 * For even modulus m = 2^k*m_odd, it might make sense to compute 104 * a^p mod m_odd and a^p mod 2^k separately (with Montgomery 105 * exponentiation for the odd part), using appropriate exponent 106 * reductions, and combine the results using the CRT. 107 * 108 * For now, we use Montgomery only if the modulus is odd; otherwise, 109 * exponentiation using the reciprocal-based quick remaindering 110 * algorithm is used. 111 * 112 * (Timing obtained with expspeed.c [computations a^p mod m 113 * where a, p, m are of the same length: 256, 512, 1024, 2048, 114 * 4096, 8192 bits], compared to the running time of the 115 * standard algorithm: 116 * 117 * BN_mod_exp_mont 33 .. 40 % [AMD K6-2, Linux, debug configuration] 118 * 55 .. 77 % [UltraSparc processor, but 119 * debug-solaris-sparcv8-gcc conf.] 120 * 121 * BN_mod_exp_recp 50 .. 70 % [AMD K6-2, Linux, debug configuration] 122 * 62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc] 123 * 124 * On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont 125 * at 2048 and more bits, but at 512 and 1024 bits, it was 126 * slower even than the standard algorithm! 127 * 128 * "Real" timings [linux-elf, solaris-sparcv9-gcc configurations] 129 * should be obtained when the new Montgomery reduction code 130 * has been integrated into OpenSSL.) 131 */ 132 133 #define MONT_MUL_MOD 134 #define MONT_EXP_WORD 135 #define RECP_MUL_MOD 136 137 #ifdef MONT_MUL_MOD 138 if (BN_is_odd(m)) { 139 # ifdef MONT_EXP_WORD 140 if (a->top == 1 && !a->neg 141 && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0) 142 && (BN_get_flags(a, BN_FLG_CONSTTIME) == 0) 143 && (BN_get_flags(m, BN_FLG_CONSTTIME) == 0)) { 144 BN_ULONG A = a->d[0]; 145 ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL); 146 } else 147 # endif 148 ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL); 149 } else 150 #endif 151 #ifdef RECP_MUL_MOD 152 { 153 ret = BN_mod_exp_recp(r, a, p, m, ctx); 154 } 155 #else 156 { 157 ret = BN_mod_exp_simple(r, a, p, m, ctx); 158 } 159 #endif 160 161 bn_check_top(r); 162 return ret; 163 } 164 165 int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, 166 const BIGNUM *m, BN_CTX *ctx) 167 { 168 int i, j, bits, ret = 0, wstart, wend, window, wvalue; 169 int start = 1; 170 BIGNUM *aa; 171 /* Table of variables obtained from 'ctx' */ 172 BIGNUM *val[TABLE_SIZE]; 173 BN_RECP_CTX recp; 174 175 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 176 || BN_get_flags(a, BN_FLG_CONSTTIME) != 0 177 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) { 178 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ 179 BNerr(BN_F_BN_MOD_EXP_RECP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); 180 return 0; 181 } 182 183 bits = BN_num_bits(p); 184 if (bits == 0) { 185 /* x**0 mod 1, or x**0 mod -1 is still zero. */ 186 if (BN_abs_is_word(m, 1)) { 187 ret = 1; 188 BN_zero(r); 189 } else { 190 ret = BN_one(r); 191 } 192 return ret; 193 } 194 195 BN_CTX_start(ctx); 196 aa = BN_CTX_get(ctx); 197 val[0] = BN_CTX_get(ctx); 198 if (val[0] == NULL) 199 goto err; 200 201 BN_RECP_CTX_init(&recp); 202 if (m->neg) { 203 /* ignore sign of 'm' */ 204 if (!BN_copy(aa, m)) 205 goto err; 206 aa->neg = 0; 207 if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0) 208 goto err; 209 } else { 210 if (BN_RECP_CTX_set(&recp, m, ctx) <= 0) 211 goto err; 212 } 213 214 if (!BN_nnmod(val[0], a, m, ctx)) 215 goto err; /* 1 */ 216 if (BN_is_zero(val[0])) { 217 BN_zero(r); 218 ret = 1; 219 goto err; 220 } 221 222 window = BN_window_bits_for_exponent_size(bits); 223 if (window > 1) { 224 if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx)) 225 goto err; /* 2 */ 226 j = 1 << (window - 1); 227 for (i = 1; i < j; i++) { 228 if (((val[i] = BN_CTX_get(ctx)) == NULL) || 229 !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx)) 230 goto err; 231 } 232 } 233 234 start = 1; /* This is used to avoid multiplication etc 235 * when there is only the value '1' in the 236 * buffer. */ 237 wvalue = 0; /* The 'value' of the window */ 238 wstart = bits - 1; /* The top bit of the window */ 239 wend = 0; /* The bottom bit of the window */ 240 241 if (!BN_one(r)) 242 goto err; 243 244 for (;;) { 245 if (BN_is_bit_set(p, wstart) == 0) { 246 if (!start) 247 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) 248 goto err; 249 if (wstart == 0) 250 break; 251 wstart--; 252 continue; 253 } 254 /* 255 * We now have wstart on a 'set' bit, we now need to work out how bit 256 * a window to do. To do this we need to scan forward until the last 257 * set bit before the end of the window 258 */ 259 j = wstart; 260 wvalue = 1; 261 wend = 0; 262 for (i = 1; i < window; i++) { 263 if (wstart - i < 0) 264 break; 265 if (BN_is_bit_set(p, wstart - i)) { 266 wvalue <<= (i - wend); 267 wvalue |= 1; 268 wend = i; 269 } 270 } 271 272 /* wend is the size of the current window */ 273 j = wend + 1; 274 /* add the 'bytes above' */ 275 if (!start) 276 for (i = 0; i < j; i++) { 277 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) 278 goto err; 279 } 280 281 /* wvalue will be an odd number < 2^window */ 282 if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx)) 283 goto err; 284 285 /* move the 'window' down further */ 286 wstart -= wend + 1; 287 wvalue = 0; 288 start = 0; 289 if (wstart < 0) 290 break; 291 } 292 ret = 1; 293 err: 294 BN_CTX_end(ctx); 295 BN_RECP_CTX_free(&recp); 296 bn_check_top(r); 297 return ret; 298 } 299 300 int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, 301 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) 302 { 303 int i, j, bits, ret = 0, wstart, wend, window, wvalue; 304 int start = 1; 305 BIGNUM *d, *r; 306 const BIGNUM *aa; 307 /* Table of variables obtained from 'ctx' */ 308 BIGNUM *val[TABLE_SIZE]; 309 BN_MONT_CTX *mont = NULL; 310 311 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 312 || BN_get_flags(a, BN_FLG_CONSTTIME) != 0 313 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) { 314 return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont); 315 } 316 317 bn_check_top(a); 318 bn_check_top(p); 319 bn_check_top(m); 320 321 if (!BN_is_odd(m)) { 322 BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS); 323 return 0; 324 } 325 bits = BN_num_bits(p); 326 if (bits == 0) { 327 /* x**0 mod 1, or x**0 mod -1 is still zero. */ 328 if (BN_abs_is_word(m, 1)) { 329 ret = 1; 330 BN_zero(rr); 331 } else { 332 ret = BN_one(rr); 333 } 334 return ret; 335 } 336 337 BN_CTX_start(ctx); 338 d = BN_CTX_get(ctx); 339 r = BN_CTX_get(ctx); 340 val[0] = BN_CTX_get(ctx); 341 if (val[0] == NULL) 342 goto err; 343 344 /* 345 * If this is not done, things will break in the montgomery part 346 */ 347 348 if (in_mont != NULL) 349 mont = in_mont; 350 else { 351 if ((mont = BN_MONT_CTX_new()) == NULL) 352 goto err; 353 if (!BN_MONT_CTX_set(mont, m, ctx)) 354 goto err; 355 } 356 357 if (a->neg || BN_ucmp(a, m) >= 0) { 358 if (!BN_nnmod(val[0], a, m, ctx)) 359 goto err; 360 aa = val[0]; 361 } else 362 aa = a; 363 if (!bn_to_mont_fixed_top(val[0], aa, mont, ctx)) 364 goto err; /* 1 */ 365 366 window = BN_window_bits_for_exponent_size(bits); 367 if (window > 1) { 368 if (!bn_mul_mont_fixed_top(d, val[0], val[0], mont, ctx)) 369 goto err; /* 2 */ 370 j = 1 << (window - 1); 371 for (i = 1; i < j; i++) { 372 if (((val[i] = BN_CTX_get(ctx)) == NULL) || 373 !bn_mul_mont_fixed_top(val[i], val[i - 1], d, mont, ctx)) 374 goto err; 375 } 376 } 377 378 start = 1; /* This is used to avoid multiplication etc 379 * when there is only the value '1' in the 380 * buffer. */ 381 wvalue = 0; /* The 'value' of the window */ 382 wstart = bits - 1; /* The top bit of the window */ 383 wend = 0; /* The bottom bit of the window */ 384 385 #if 1 /* by Shay Gueron's suggestion */ 386 j = m->top; /* borrow j */ 387 if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) { 388 if (bn_wexpand(r, j) == NULL) 389 goto err; 390 /* 2^(top*BN_BITS2) - m */ 391 r->d[0] = (0 - m->d[0]) & BN_MASK2; 392 for (i = 1; i < j; i++) 393 r->d[i] = (~m->d[i]) & BN_MASK2; 394 r->top = j; 395 r->flags |= BN_FLG_FIXED_TOP; 396 } else 397 #endif 398 if (!bn_to_mont_fixed_top(r, BN_value_one(), mont, ctx)) 399 goto err; 400 for (;;) { 401 if (BN_is_bit_set(p, wstart) == 0) { 402 if (!start) { 403 if (!bn_mul_mont_fixed_top(r, r, r, mont, ctx)) 404 goto err; 405 } 406 if (wstart == 0) 407 break; 408 wstart--; 409 continue; 410 } 411 /* 412 * We now have wstart on a 'set' bit, we now need to work out how bit 413 * a window to do. To do this we need to scan forward until the last 414 * set bit before the end of the window 415 */ 416 j = wstart; 417 wvalue = 1; 418 wend = 0; 419 for (i = 1; i < window; i++) { 420 if (wstart - i < 0) 421 break; 422 if (BN_is_bit_set(p, wstart - i)) { 423 wvalue <<= (i - wend); 424 wvalue |= 1; 425 wend = i; 426 } 427 } 428 429 /* wend is the size of the current window */ 430 j = wend + 1; 431 /* add the 'bytes above' */ 432 if (!start) 433 for (i = 0; i < j; i++) { 434 if (!bn_mul_mont_fixed_top(r, r, r, mont, ctx)) 435 goto err; 436 } 437 438 /* wvalue will be an odd number < 2^window */ 439 if (!bn_mul_mont_fixed_top(r, r, val[wvalue >> 1], mont, ctx)) 440 goto err; 441 442 /* move the 'window' down further */ 443 wstart -= wend + 1; 444 wvalue = 0; 445 start = 0; 446 if (wstart < 0) 447 break; 448 } 449 /* 450 * Done with zero-padded intermediate BIGNUMs. Final BN_from_montgomery 451 * removes padding [if any] and makes return value suitable for public 452 * API consumer. 453 */ 454 #if defined(SPARC_T4_MONT) 455 if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) { 456 j = mont->N.top; /* borrow j */ 457 val[0]->d[0] = 1; /* borrow val[0] */ 458 for (i = 1; i < j; i++) 459 val[0]->d[i] = 0; 460 val[0]->top = j; 461 if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx)) 462 goto err; 463 } else 464 #endif 465 if (!BN_from_montgomery(rr, r, mont, ctx)) 466 goto err; 467 ret = 1; 468 err: 469 if (in_mont == NULL) 470 BN_MONT_CTX_free(mont); 471 BN_CTX_end(ctx); 472 bn_check_top(rr); 473 return ret; 474 } 475 476 static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos) 477 { 478 BN_ULONG ret = 0; 479 int wordpos; 480 481 wordpos = bitpos / BN_BITS2; 482 bitpos %= BN_BITS2; 483 if (wordpos >= 0 && wordpos < a->top) { 484 ret = a->d[wordpos] & BN_MASK2; 485 if (bitpos) { 486 ret >>= bitpos; 487 if (++wordpos < a->top) 488 ret |= a->d[wordpos] << (BN_BITS2 - bitpos); 489 } 490 } 491 492 return ret & BN_MASK2; 493 } 494 495 /* 496 * BN_mod_exp_mont_consttime() stores the precomputed powers in a specific 497 * layout so that accessing any of these table values shows the same access 498 * pattern as far as cache lines are concerned. The following functions are 499 * used to transfer a BIGNUM from/to that table. 500 */ 501 502 static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top, 503 unsigned char *buf, int idx, 504 int window) 505 { 506 int i, j; 507 int width = 1 << window; 508 BN_ULONG *table = (BN_ULONG *)buf; 509 510 if (top > b->top) 511 top = b->top; /* this works because 'buf' is explicitly 512 * zeroed */ 513 for (i = 0, j = idx; i < top; i++, j += width) { 514 table[j] = b->d[i]; 515 } 516 517 return 1; 518 } 519 520 static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top, 521 unsigned char *buf, int idx, 522 int window) 523 { 524 int i, j; 525 int width = 1 << window; 526 /* 527 * We declare table 'volatile' in order to discourage compiler 528 * from reordering loads from the table. Concern is that if 529 * reordered in specific manner loads might give away the 530 * information we are trying to conceal. Some would argue that 531 * compiler can reorder them anyway, but it can as well be 532 * argued that doing so would be violation of standard... 533 */ 534 volatile BN_ULONG *table = (volatile BN_ULONG *)buf; 535 536 if (bn_wexpand(b, top) == NULL) 537 return 0; 538 539 if (window <= 3) { 540 for (i = 0; i < top; i++, table += width) { 541 BN_ULONG acc = 0; 542 543 for (j = 0; j < width; j++) { 544 acc |= table[j] & 545 ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1)); 546 } 547 548 b->d[i] = acc; 549 } 550 } else { 551 int xstride = 1 << (window - 2); 552 BN_ULONG y0, y1, y2, y3; 553 554 i = idx >> (window - 2); /* equivalent of idx / xstride */ 555 idx &= xstride - 1; /* equivalent of idx % xstride */ 556 557 y0 = (BN_ULONG)0 - (constant_time_eq_int(i,0)&1); 558 y1 = (BN_ULONG)0 - (constant_time_eq_int(i,1)&1); 559 y2 = (BN_ULONG)0 - (constant_time_eq_int(i,2)&1); 560 y3 = (BN_ULONG)0 - (constant_time_eq_int(i,3)&1); 561 562 for (i = 0; i < top; i++, table += width) { 563 BN_ULONG acc = 0; 564 565 for (j = 0; j < xstride; j++) { 566 acc |= ( (table[j + 0 * xstride] & y0) | 567 (table[j + 1 * xstride] & y1) | 568 (table[j + 2 * xstride] & y2) | 569 (table[j + 3 * xstride] & y3) ) 570 & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1)); 571 } 572 573 b->d[i] = acc; 574 } 575 } 576 577 b->top = top; 578 b->flags |= BN_FLG_FIXED_TOP; 579 return 1; 580 } 581 582 /* 583 * Given a pointer value, compute the next address that is a cache line 584 * multiple. 585 */ 586 #define MOD_EXP_CTIME_ALIGN(x_) \ 587 ((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK)))) 588 589 /* 590 * This variant of BN_mod_exp_mont() uses fixed windows and the special 591 * precomputation memory layout to limit data-dependency to a minimum to 592 * protect secret exponents (cf. the hyper-threading timing attacks pointed 593 * out by Colin Percival, 594 * http://www.daemonology.net/hyperthreading-considered-harmful/) 595 */ 596 int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p, 597 const BIGNUM *m, BN_CTX *ctx, 598 BN_MONT_CTX *in_mont) 599 { 600 int i, bits, ret = 0, window, wvalue, wmask, window0; 601 int top; 602 BN_MONT_CTX *mont = NULL; 603 604 int numPowers; 605 unsigned char *powerbufFree = NULL; 606 int powerbufLen = 0; 607 unsigned char *powerbuf = NULL; 608 BIGNUM tmp, am; 609 #if defined(SPARC_T4_MONT) 610 unsigned int t4 = 0; 611 #endif 612 613 bn_check_top(a); 614 bn_check_top(p); 615 bn_check_top(m); 616 617 if (!BN_is_odd(m)) { 618 BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS); 619 return 0; 620 } 621 622 top = m->top; 623 624 /* 625 * Use all bits stored in |p|, rather than |BN_num_bits|, so we do not leak 626 * whether the top bits are zero. 627 */ 628 bits = p->top * BN_BITS2; 629 if (bits == 0) { 630 /* x**0 mod 1, or x**0 mod -1 is still zero. */ 631 if (BN_abs_is_word(m, 1)) { 632 ret = 1; 633 BN_zero(rr); 634 } else { 635 ret = BN_one(rr); 636 } 637 return ret; 638 } 639 640 BN_CTX_start(ctx); 641 642 /* 643 * Allocate a montgomery context if it was not supplied by the caller. If 644 * this is not done, things will break in the montgomery part. 645 */ 646 if (in_mont != NULL) 647 mont = in_mont; 648 else { 649 if ((mont = BN_MONT_CTX_new()) == NULL) 650 goto err; 651 if (!BN_MONT_CTX_set(mont, m, ctx)) 652 goto err; 653 } 654 655 if (a->neg || BN_ucmp(a, m) >= 0) { 656 BIGNUM *reduced = BN_CTX_get(ctx); 657 if (reduced == NULL 658 || !BN_nnmod(reduced, a, m, ctx)) { 659 goto err; 660 } 661 a = reduced; 662 } 663 664 #ifdef RSAZ_ENABLED 665 /* 666 * If the size of the operands allow it, perform the optimized 667 * RSAZ exponentiation. For further information see 668 * crypto/bn/rsaz_exp.c and accompanying assembly modules. 669 */ 670 if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024) 671 && rsaz_avx2_eligible()) { 672 if (NULL == bn_wexpand(rr, 16)) 673 goto err; 674 RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d, 675 mont->n0[0]); 676 rr->top = 16; 677 rr->neg = 0; 678 bn_correct_top(rr); 679 ret = 1; 680 goto err; 681 } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) { 682 if (NULL == bn_wexpand(rr, 8)) 683 goto err; 684 RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d); 685 rr->top = 8; 686 rr->neg = 0; 687 bn_correct_top(rr); 688 ret = 1; 689 goto err; 690 } 691 #endif 692 693 /* Get the window size to use with size of p. */ 694 window = BN_window_bits_for_ctime_exponent_size(bits); 695 #if defined(SPARC_T4_MONT) 696 if (window >= 5 && (top & 15) == 0 && top <= 64 && 697 (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) == 698 (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0])) 699 window = 5; 700 else 701 #endif 702 #if defined(OPENSSL_BN_ASM_MONT5) 703 if (window >= 5) { 704 window = 5; /* ~5% improvement for RSA2048 sign, and even 705 * for RSA4096 */ 706 /* reserve space for mont->N.d[] copy */ 707 powerbufLen += top * sizeof(mont->N.d[0]); 708 } 709 #endif 710 (void)0; 711 712 /* 713 * Allocate a buffer large enough to hold all of the pre-computed powers 714 * of am, am itself and tmp. 715 */ 716 numPowers = 1 << window; 717 powerbufLen += sizeof(m->d[0]) * (top * numPowers + 718 ((2 * top) > 719 numPowers ? (2 * top) : numPowers)); 720 #ifdef alloca 721 if (powerbufLen < 3072) 722 powerbufFree = 723 alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH); 724 else 725 #endif 726 if ((powerbufFree = 727 OPENSSL_malloc(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH)) 728 == NULL) 729 goto err; 730 731 powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree); 732 memset(powerbuf, 0, powerbufLen); 733 734 #ifdef alloca 735 if (powerbufLen < 3072) 736 powerbufFree = NULL; 737 #endif 738 739 /* lay down tmp and am right after powers table */ 740 tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers); 741 am.d = tmp.d + top; 742 tmp.top = am.top = 0; 743 tmp.dmax = am.dmax = top; 744 tmp.neg = am.neg = 0; 745 tmp.flags = am.flags = BN_FLG_STATIC_DATA; 746 747 /* prepare a^0 in Montgomery domain */ 748 #if 1 /* by Shay Gueron's suggestion */ 749 if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) { 750 /* 2^(top*BN_BITS2) - m */ 751 tmp.d[0] = (0 - m->d[0]) & BN_MASK2; 752 for (i = 1; i < top; i++) 753 tmp.d[i] = (~m->d[i]) & BN_MASK2; 754 tmp.top = top; 755 } else 756 #endif 757 if (!bn_to_mont_fixed_top(&tmp, BN_value_one(), mont, ctx)) 758 goto err; 759 760 /* prepare a^1 in Montgomery domain */ 761 if (!bn_to_mont_fixed_top(&am, a, mont, ctx)) 762 goto err; 763 764 #if defined(SPARC_T4_MONT) 765 if (t4) { 766 typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np, 767 const BN_ULONG *n0, const void *table, 768 int power, int bits); 769 int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np, 770 const BN_ULONG *n0, const void *table, 771 int power, int bits); 772 int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np, 773 const BN_ULONG *n0, const void *table, 774 int power, int bits); 775 int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np, 776 const BN_ULONG *n0, const void *table, 777 int power, int bits); 778 int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np, 779 const BN_ULONG *n0, const void *table, 780 int power, int bits); 781 static const bn_pwr5_mont_f pwr5_funcs[4] = { 782 bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16, 783 bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32 784 }; 785 bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1]; 786 787 typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap, 788 const void *bp, const BN_ULONG *np, 789 const BN_ULONG *n0); 790 int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp, 791 const BN_ULONG *np, const BN_ULONG *n0); 792 int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap, 793 const void *bp, const BN_ULONG *np, 794 const BN_ULONG *n0); 795 int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap, 796 const void *bp, const BN_ULONG *np, 797 const BN_ULONG *n0); 798 int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap, 799 const void *bp, const BN_ULONG *np, 800 const BN_ULONG *n0); 801 static const bn_mul_mont_f mul_funcs[4] = { 802 bn_mul_mont_t4_8, bn_mul_mont_t4_16, 803 bn_mul_mont_t4_24, bn_mul_mont_t4_32 804 }; 805 bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1]; 806 807 void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap, 808 const void *bp, const BN_ULONG *np, 809 const BN_ULONG *n0, int num); 810 void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap, 811 const void *bp, const BN_ULONG *np, 812 const BN_ULONG *n0, int num); 813 void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap, 814 const void *table, const BN_ULONG *np, 815 const BN_ULONG *n0, int num, int power); 816 void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num, 817 void *table, size_t power); 818 void bn_gather5_t4(BN_ULONG *out, size_t num, 819 void *table, size_t power); 820 void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num); 821 822 BN_ULONG *np = mont->N.d, *n0 = mont->n0; 823 int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less 824 * than 32 */ 825 826 /* 827 * BN_to_montgomery can contaminate words above .top [in 828 * BN_DEBUG[_DEBUG] build]... 829 */ 830 for (i = am.top; i < top; i++) 831 am.d[i] = 0; 832 for (i = tmp.top; i < top; i++) 833 tmp.d[i] = 0; 834 835 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0); 836 bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1); 837 if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) && 838 !(*mul_worker) (tmp.d, am.d, am.d, np, n0)) 839 bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top); 840 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2); 841 842 for (i = 3; i < 32; i++) { 843 /* Calculate a^i = a^(i-1) * a */ 844 if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) && 845 !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0)) 846 bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top); 847 bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i); 848 } 849 850 /* switch to 64-bit domain */ 851 np = alloca(top * sizeof(BN_ULONG)); 852 top /= 2; 853 bn_flip_t4(np, mont->N.d, top); 854 855 /* 856 * The exponent may not have a whole number of fixed-size windows. 857 * To simplify the main loop, the initial window has between 1 and 858 * full-window-size bits such that what remains is always a whole 859 * number of windows 860 */ 861 window0 = (bits - 1) % 5 + 1; 862 wmask = (1 << window0) - 1; 863 bits -= window0; 864 wvalue = bn_get_bits(p, bits) & wmask; 865 bn_gather5_t4(tmp.d, top, powerbuf, wvalue); 866 867 /* 868 * Scan the exponent one window at a time starting from the most 869 * significant bits. 870 */ 871 while (bits > 0) { 872 if (bits < stride) 873 stride = bits; 874 bits -= stride; 875 wvalue = bn_get_bits(p, bits); 876 877 if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride)) 878 continue; 879 /* retry once and fall back */ 880 if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride)) 881 continue; 882 883 bits += stride - 5; 884 wvalue >>= stride - 5; 885 wvalue &= 31; 886 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); 887 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); 888 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); 889 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); 890 bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top); 891 bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top, 892 wvalue); 893 } 894 895 bn_flip_t4(tmp.d, tmp.d, top); 896 top *= 2; 897 /* back to 32-bit domain */ 898 tmp.top = top; 899 bn_correct_top(&tmp); 900 OPENSSL_cleanse(np, top * sizeof(BN_ULONG)); 901 } else 902 #endif 903 #if defined(OPENSSL_BN_ASM_MONT5) 904 if (window == 5 && top > 1) { 905 /* 906 * This optimization uses ideas from http://eprint.iacr.org/2011/239, 907 * specifically optimization of cache-timing attack countermeasures 908 * and pre-computation optimization. 909 */ 910 911 /* 912 * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as 913 * 512-bit RSA is hardly relevant, we omit it to spare size... 914 */ 915 void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap, 916 const void *table, const BN_ULONG *np, 917 const BN_ULONG *n0, int num, int power); 918 void bn_scatter5(const BN_ULONG *inp, size_t num, 919 void *table, size_t power); 920 void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power); 921 void bn_power5(BN_ULONG *rp, const BN_ULONG *ap, 922 const void *table, const BN_ULONG *np, 923 const BN_ULONG *n0, int num, int power); 924 int bn_get_bits5(const BN_ULONG *ap, int off); 925 int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap, 926 const BN_ULONG *not_used, const BN_ULONG *np, 927 const BN_ULONG *n0, int num); 928 929 BN_ULONG *n0 = mont->n0, *np; 930 931 /* 932 * BN_to_montgomery can contaminate words above .top [in 933 * BN_DEBUG[_DEBUG] build]... 934 */ 935 for (i = am.top; i < top; i++) 936 am.d[i] = 0; 937 for (i = tmp.top; i < top; i++) 938 tmp.d[i] = 0; 939 940 /* 941 * copy mont->N.d[] to improve cache locality 942 */ 943 for (np = am.d + top, i = 0; i < top; i++) 944 np[i] = mont->N.d[i]; 945 946 bn_scatter5(tmp.d, top, powerbuf, 0); 947 bn_scatter5(am.d, am.top, powerbuf, 1); 948 bn_mul_mont(tmp.d, am.d, am.d, np, n0, top); 949 bn_scatter5(tmp.d, top, powerbuf, 2); 950 951 # if 0 952 for (i = 3; i < 32; i++) { 953 /* Calculate a^i = a^(i-1) * a */ 954 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); 955 bn_scatter5(tmp.d, top, powerbuf, i); 956 } 957 # else 958 /* same as above, but uses squaring for 1/2 of operations */ 959 for (i = 4; i < 32; i *= 2) { 960 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); 961 bn_scatter5(tmp.d, top, powerbuf, i); 962 } 963 for (i = 3; i < 8; i += 2) { 964 int j; 965 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); 966 bn_scatter5(tmp.d, top, powerbuf, i); 967 for (j = 2 * i; j < 32; j *= 2) { 968 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); 969 bn_scatter5(tmp.d, top, powerbuf, j); 970 } 971 } 972 for (; i < 16; i += 2) { 973 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); 974 bn_scatter5(tmp.d, top, powerbuf, i); 975 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); 976 bn_scatter5(tmp.d, top, powerbuf, 2 * i); 977 } 978 for (; i < 32; i += 2) { 979 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1); 980 bn_scatter5(tmp.d, top, powerbuf, i); 981 } 982 # endif 983 /* 984 * The exponent may not have a whole number of fixed-size windows. 985 * To simplify the main loop, the initial window has between 1 and 986 * full-window-size bits such that what remains is always a whole 987 * number of windows 988 */ 989 window0 = (bits - 1) % 5 + 1; 990 wmask = (1 << window0) - 1; 991 bits -= window0; 992 wvalue = bn_get_bits(p, bits) & wmask; 993 bn_gather5(tmp.d, top, powerbuf, wvalue); 994 995 /* 996 * Scan the exponent one window at a time starting from the most 997 * significant bits. 998 */ 999 if (top & 7) { 1000 while (bits > 0) { 1001 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); 1002 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); 1003 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); 1004 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); 1005 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top); 1006 bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top, 1007 bn_get_bits5(p->d, bits -= 5)); 1008 } 1009 } else { 1010 while (bits > 0) { 1011 bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, 1012 bn_get_bits5(p->d, bits -= 5)); 1013 } 1014 } 1015 1016 ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top); 1017 tmp.top = top; 1018 bn_correct_top(&tmp); 1019 if (ret) { 1020 if (!BN_copy(rr, &tmp)) 1021 ret = 0; 1022 goto err; /* non-zero ret means it's not error */ 1023 } 1024 } else 1025 #endif 1026 { 1027 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window)) 1028 goto err; 1029 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window)) 1030 goto err; 1031 1032 /* 1033 * If the window size is greater than 1, then calculate 1034 * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even 1035 * powers could instead be computed as (a^(i/2))^2 to use the slight 1036 * performance advantage of sqr over mul). 1037 */ 1038 if (window > 1) { 1039 if (!bn_mul_mont_fixed_top(&tmp, &am, &am, mont, ctx)) 1040 goto err; 1041 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2, 1042 window)) 1043 goto err; 1044 for (i = 3; i < numPowers; i++) { 1045 /* Calculate a^i = a^(i-1) * a */ 1046 if (!bn_mul_mont_fixed_top(&tmp, &am, &tmp, mont, ctx)) 1047 goto err; 1048 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i, 1049 window)) 1050 goto err; 1051 } 1052 } 1053 1054 /* 1055 * The exponent may not have a whole number of fixed-size windows. 1056 * To simplify the main loop, the initial window has between 1 and 1057 * full-window-size bits such that what remains is always a whole 1058 * number of windows 1059 */ 1060 window0 = (bits - 1) % window + 1; 1061 wmask = (1 << window0) - 1; 1062 bits -= window0; 1063 wvalue = bn_get_bits(p, bits) & wmask; 1064 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue, 1065 window)) 1066 goto err; 1067 1068 wmask = (1 << window) - 1; 1069 /* 1070 * Scan the exponent one window at a time starting from the most 1071 * significant bits. 1072 */ 1073 while (bits > 0) { 1074 1075 /* Square the result window-size times */ 1076 for (i = 0; i < window; i++) 1077 if (!bn_mul_mont_fixed_top(&tmp, &tmp, &tmp, mont, ctx)) 1078 goto err; 1079 1080 /* 1081 * Get a window's worth of bits from the exponent 1082 * This avoids calling BN_is_bit_set for each bit, which 1083 * is not only slower but also makes each bit vulnerable to 1084 * EM (and likely other) side-channel attacks like One&Done 1085 * (for details see "One&Done: A Single-Decryption EM-Based 1086 * Attack on OpenSSL's Constant-Time Blinded RSA" by M. Alam, 1087 * H. Khan, M. Dey, N. Sinha, R. Callan, A. Zajic, and 1088 * M. Prvulovic, in USENIX Security'18) 1089 */ 1090 bits -= window; 1091 wvalue = bn_get_bits(p, bits) & wmask; 1092 /* 1093 * Fetch the appropriate pre-computed value from the pre-buf 1094 */ 1095 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue, 1096 window)) 1097 goto err; 1098 1099 /* Multiply the result into the intermediate result */ 1100 if (!bn_mul_mont_fixed_top(&tmp, &tmp, &am, mont, ctx)) 1101 goto err; 1102 } 1103 } 1104 1105 /* 1106 * Done with zero-padded intermediate BIGNUMs. Final BN_from_montgomery 1107 * removes padding [if any] and makes return value suitable for public 1108 * API consumer. 1109 */ 1110 #if defined(SPARC_T4_MONT) 1111 if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) { 1112 am.d[0] = 1; /* borrow am */ 1113 for (i = 1; i < top; i++) 1114 am.d[i] = 0; 1115 if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx)) 1116 goto err; 1117 } else 1118 #endif 1119 if (!BN_from_montgomery(rr, &tmp, mont, ctx)) 1120 goto err; 1121 ret = 1; 1122 err: 1123 if (in_mont == NULL) 1124 BN_MONT_CTX_free(mont); 1125 if (powerbuf != NULL) { 1126 OPENSSL_cleanse(powerbuf, powerbufLen); 1127 OPENSSL_free(powerbufFree); 1128 } 1129 BN_CTX_end(ctx); 1130 return ret; 1131 } 1132 1133 int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p, 1134 const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont) 1135 { 1136 BN_MONT_CTX *mont = NULL; 1137 int b, bits, ret = 0; 1138 int r_is_one; 1139 BN_ULONG w, next_w; 1140 BIGNUM *r, *t; 1141 BIGNUM *swap_tmp; 1142 #define BN_MOD_MUL_WORD(r, w, m) \ 1143 (BN_mul_word(r, (w)) && \ 1144 (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \ 1145 (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1)))) 1146 /* 1147 * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is 1148 * probably more overhead than always using BN_mod (which uses BN_copy if 1149 * a similar test returns true). 1150 */ 1151 /* 1152 * We can use BN_mod and do not need BN_nnmod because our accumulator is 1153 * never negative (the result of BN_mod does not depend on the sign of 1154 * the modulus). 1155 */ 1156 #define BN_TO_MONTGOMERY_WORD(r, w, mont) \ 1157 (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx)) 1158 1159 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 1160 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) { 1161 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ 1162 BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); 1163 return 0; 1164 } 1165 1166 bn_check_top(p); 1167 bn_check_top(m); 1168 1169 if (!BN_is_odd(m)) { 1170 BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS); 1171 return 0; 1172 } 1173 if (m->top == 1) 1174 a %= m->d[0]; /* make sure that 'a' is reduced */ 1175 1176 bits = BN_num_bits(p); 1177 if (bits == 0) { 1178 /* x**0 mod 1, or x**0 mod -1 is still zero. */ 1179 if (BN_abs_is_word(m, 1)) { 1180 ret = 1; 1181 BN_zero(rr); 1182 } else { 1183 ret = BN_one(rr); 1184 } 1185 return ret; 1186 } 1187 if (a == 0) { 1188 BN_zero(rr); 1189 ret = 1; 1190 return ret; 1191 } 1192 1193 BN_CTX_start(ctx); 1194 r = BN_CTX_get(ctx); 1195 t = BN_CTX_get(ctx); 1196 if (t == NULL) 1197 goto err; 1198 1199 if (in_mont != NULL) 1200 mont = in_mont; 1201 else { 1202 if ((mont = BN_MONT_CTX_new()) == NULL) 1203 goto err; 1204 if (!BN_MONT_CTX_set(mont, m, ctx)) 1205 goto err; 1206 } 1207 1208 r_is_one = 1; /* except for Montgomery factor */ 1209 1210 /* bits-1 >= 0 */ 1211 1212 /* The result is accumulated in the product r*w. */ 1213 w = a; /* bit 'bits-1' of 'p' is always set */ 1214 for (b = bits - 2; b >= 0; b--) { 1215 /* First, square r*w. */ 1216 next_w = w * w; 1217 if ((next_w / w) != w) { /* overflow */ 1218 if (r_is_one) { 1219 if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) 1220 goto err; 1221 r_is_one = 0; 1222 } else { 1223 if (!BN_MOD_MUL_WORD(r, w, m)) 1224 goto err; 1225 } 1226 next_w = 1; 1227 } 1228 w = next_w; 1229 if (!r_is_one) { 1230 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) 1231 goto err; 1232 } 1233 1234 /* Second, multiply r*w by 'a' if exponent bit is set. */ 1235 if (BN_is_bit_set(p, b)) { 1236 next_w = w * a; 1237 if ((next_w / a) != w) { /* overflow */ 1238 if (r_is_one) { 1239 if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) 1240 goto err; 1241 r_is_one = 0; 1242 } else { 1243 if (!BN_MOD_MUL_WORD(r, w, m)) 1244 goto err; 1245 } 1246 next_w = a; 1247 } 1248 w = next_w; 1249 } 1250 } 1251 1252 /* Finally, set r:=r*w. */ 1253 if (w != 1) { 1254 if (r_is_one) { 1255 if (!BN_TO_MONTGOMERY_WORD(r, w, mont)) 1256 goto err; 1257 r_is_one = 0; 1258 } else { 1259 if (!BN_MOD_MUL_WORD(r, w, m)) 1260 goto err; 1261 } 1262 } 1263 1264 if (r_is_one) { /* can happen only if a == 1 */ 1265 if (!BN_one(rr)) 1266 goto err; 1267 } else { 1268 if (!BN_from_montgomery(rr, r, mont, ctx)) 1269 goto err; 1270 } 1271 ret = 1; 1272 err: 1273 if (in_mont == NULL) 1274 BN_MONT_CTX_free(mont); 1275 BN_CTX_end(ctx); 1276 bn_check_top(rr); 1277 return ret; 1278 } 1279 1280 /* The old fallback, simple version :-) */ 1281 int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, 1282 const BIGNUM *m, BN_CTX *ctx) 1283 { 1284 int i, j, bits, ret = 0, wstart, wend, window, wvalue; 1285 int start = 1; 1286 BIGNUM *d; 1287 /* Table of variables obtained from 'ctx' */ 1288 BIGNUM *val[TABLE_SIZE]; 1289 1290 if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0 1291 || BN_get_flags(a, BN_FLG_CONSTTIME) != 0 1292 || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) { 1293 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */ 1294 BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED); 1295 return 0; 1296 } 1297 1298 bits = BN_num_bits(p); 1299 if (bits == 0) { 1300 /* x**0 mod 1, or x**0 mod -1 is still zero. */ 1301 if (BN_abs_is_word(m, 1)) { 1302 ret = 1; 1303 BN_zero(r); 1304 } else { 1305 ret = BN_one(r); 1306 } 1307 return ret; 1308 } 1309 1310 BN_CTX_start(ctx); 1311 d = BN_CTX_get(ctx); 1312 val[0] = BN_CTX_get(ctx); 1313 if (val[0] == NULL) 1314 goto err; 1315 1316 if (!BN_nnmod(val[0], a, m, ctx)) 1317 goto err; /* 1 */ 1318 if (BN_is_zero(val[0])) { 1319 BN_zero(r); 1320 ret = 1; 1321 goto err; 1322 } 1323 1324 window = BN_window_bits_for_exponent_size(bits); 1325 if (window > 1) { 1326 if (!BN_mod_mul(d, val[0], val[0], m, ctx)) 1327 goto err; /* 2 */ 1328 j = 1 << (window - 1); 1329 for (i = 1; i < j; i++) { 1330 if (((val[i] = BN_CTX_get(ctx)) == NULL) || 1331 !BN_mod_mul(val[i], val[i - 1], d, m, ctx)) 1332 goto err; 1333 } 1334 } 1335 1336 start = 1; /* This is used to avoid multiplication etc 1337 * when there is only the value '1' in the 1338 * buffer. */ 1339 wvalue = 0; /* The 'value' of the window */ 1340 wstart = bits - 1; /* The top bit of the window */ 1341 wend = 0; /* The bottom bit of the window */ 1342 1343 if (!BN_one(r)) 1344 goto err; 1345 1346 for (;;) { 1347 if (BN_is_bit_set(p, wstart) == 0) { 1348 if (!start) 1349 if (!BN_mod_mul(r, r, r, m, ctx)) 1350 goto err; 1351 if (wstart == 0) 1352 break; 1353 wstart--; 1354 continue; 1355 } 1356 /* 1357 * We now have wstart on a 'set' bit, we now need to work out how bit 1358 * a window to do. To do this we need to scan forward until the last 1359 * set bit before the end of the window 1360 */ 1361 j = wstart; 1362 wvalue = 1; 1363 wend = 0; 1364 for (i = 1; i < window; i++) { 1365 if (wstart - i < 0) 1366 break; 1367 if (BN_is_bit_set(p, wstart - i)) { 1368 wvalue <<= (i - wend); 1369 wvalue |= 1; 1370 wend = i; 1371 } 1372 } 1373 1374 /* wend is the size of the current window */ 1375 j = wend + 1; 1376 /* add the 'bytes above' */ 1377 if (!start) 1378 for (i = 0; i < j; i++) { 1379 if (!BN_mod_mul(r, r, r, m, ctx)) 1380 goto err; 1381 } 1382 1383 /* wvalue will be an odd number < 2^window */ 1384 if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx)) 1385 goto err; 1386 1387 /* move the 'window' down further */ 1388 wstart -= wend + 1; 1389 wvalue = 0; 1390 start = 0; 1391 if (wstart < 0) 1392 break; 1393 } 1394 ret = 1; 1395 err: 1396 BN_CTX_end(ctx); 1397 bn_check_top(r); 1398 return ret; 1399 } 1400