1// Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 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 20#include <openssl/err.h> 21 22#include "internal.h" 23 24#if (defined(OPENSSL_X86) || defined(OPENSSL_X86_64)) && defined(_MSC_VER) && \ 25 !defined(__clang__) 26#define HAVE_MSVC_DIV_INTRINSICS 27#include <immintrin.h> 28#if defined(OPENSSL_X86) 29#pragma intrinsic(_udiv64) 30#else 31#pragma intrinsic(_udiv128) 32#endif 33#endif 34 35 36// bn_div_words divides a double-width |h|,|l| by |d| and returns the result, 37// which must fit in a |BN_ULONG|, i.e. |h < d|. 38static inline BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d) { 39 assert(h < d); 40 BN_ULONG dh, dl, q, ret = 0, th, tl, t; 41 int i, count = 2; 42 43 if (d == 0) { 44 return BN_MASK2; 45 } 46 47 i = BN_num_bits_word(d); 48 assert((i == BN_BITS2) || (h <= (BN_ULONG)1 << i)); 49 50 i = BN_BITS2 - i; 51 if (h >= d) { 52 h -= d; 53 } 54 55 if (i) { 56 d <<= i; 57 h = (h << i) | (l >> (BN_BITS2 - i)); 58 l <<= i; 59 } 60 dh = (d & BN_MASK2h) >> BN_BITS4; 61 dl = (d & BN_MASK2l); 62 for (;;) { 63 if ((h >> BN_BITS4) == dh) { 64 q = BN_MASK2l; 65 } else { 66 q = h / dh; 67 } 68 69 th = q * dh; 70 tl = dl * q; 71 for (;;) { 72 t = h - th; 73 if ((t & BN_MASK2h) || 74 ((tl) <= ((t << BN_BITS4) | ((l & BN_MASK2h) >> BN_BITS4)))) { 75 break; 76 } 77 q--; 78 th -= dh; 79 tl -= dl; 80 } 81 t = (tl >> BN_BITS4); 82 tl = (tl << BN_BITS4) & BN_MASK2h; 83 th += t; 84 85 if (l < tl) { 86 th++; 87 } 88 l -= tl; 89 if (h < th) { 90 h += d; 91 q--; 92 } 93 h -= th; 94 95 if (--count == 0) { 96 break; 97 } 98 99 ret = q << BN_BITS4; 100 h = (h << BN_BITS4) | (l >> BN_BITS4); 101 l = (l & BN_MASK2l) << BN_BITS4; 102 } 103 104 ret |= q; 105 return ret; 106} 107 108// bn_div_rem_words divides a double-width numerator (high half |nh| and low 109// half |nl|) with a single-width divisor. It sets |*quotient_out| and 110// |*rem_out| to be the quotient and numerator, respectively. The quotient must 111// fit in a |BN_ULONG|, i.e. |nh < d|. 112static inline void bn_div_rem_words(BN_ULONG *quotient_out, BN_ULONG *rem_out, 113 BN_ULONG nh, BN_ULONG nl, BN_ULONG d) { 114 assert(nh < d); 115 // This operation is the x86 and x86_64 DIV instruction, but it is difficult 116 // for the compiler to emit it. Dividing a |BN_ULLONG| by a |BN_ULONG| does 117 // not work because, a priori, the quotient may not fit in |BN_ULONG| and DIV 118 // will trap on overflow, not truncate. The compiler will instead emit a call 119 // to a more expensive support function (e.g. |__udivdi3|). Thus we use inline 120 // assembly or intrinsics to get the instruction. 121 // 122 // These is specific to x86 and x86_64; Arm and RISC-V do not have double-wide 123 // division instructions. 124#if defined(BN_CAN_USE_INLINE_ASM) && defined(OPENSSL_X86) 125 __asm__ volatile("divl %4" 126 : "=a"(*quotient_out), "=d"(*rem_out) 127 : "a"(nl), "d"(nh), "rm"(d) 128 : "cc"); 129#elif defined(BN_CAN_USE_INLINE_ASM) && defined(OPENSSL_X86_64) 130 __asm__ volatile("divq %4" 131 : "=a"(*quotient_out), "=d"(*rem_out) 132 : "a"(nl), "d"(nh), "rm"(d) 133 : "cc"); 134#elif defined(HAVE_MSVC_DIV_INTRINSICS) && defined(OPENSSL_X86) 135 BN_ULLONG n = (((BN_ULLONG)nh) << BN_BITS2) | nl; 136 unsigned rem; 137 *quotient_out = _udiv64(n, d, &rem); 138 *rem_out = rem; 139#elif defined(HAVE_MSVC_DIV_INTRINSICS) && defined(OPENSSL_X86_64) 140 unsigned __int64 rem; 141 *quotient_out = _udiv128(nh, nl, d, &rem); 142 *rem_out = rem; 143#else 144#if defined(BN_CAN_DIVIDE_ULLONG) 145 BN_ULLONG n = (((BN_ULLONG)nh) << BN_BITS2) | nl; 146 *quotient_out = (BN_ULONG)(n / d); 147#else 148 *quotient_out = bn_div_words(nh, nl, d); 149#endif // BN_CAN_DIVIDE_ULLONG 150 *rem_out = nl - (*quotient_out * d); 151#endif 152} 153 154int BN_div(BIGNUM *quotient, BIGNUM *rem, const BIGNUM *numerator, 155 const BIGNUM *divisor, BN_CTX *ctx) { 156 // This function implements long division, per Knuth, The Art of Computer 157 // Programming, Volume 2, Chapter 4.3.1, Algorithm D. This algorithm only 158 // divides non-negative integers, but we round towards zero, so we divide 159 // absolute values and adjust the signs separately. 160 // 161 // Inputs to this function are assumed public and may be leaked by timing and 162 // cache side channels. Division with secret inputs should use other 163 // implementation strategies such as Montgomery reduction. 164 if (BN_is_zero(divisor)) { 165 OPENSSL_PUT_ERROR(BN, BN_R_DIV_BY_ZERO); 166 return 0; 167 } 168 169 bssl::BN_CTXScope scope(ctx); 170 BIGNUM *tmp = BN_CTX_get(ctx); 171 BIGNUM *snum = BN_CTX_get(ctx); 172 BIGNUM *sdiv = BN_CTX_get(ctx); 173 BIGNUM *res = quotient == NULL ? BN_CTX_get(ctx) : quotient; 174 int norm_shift, num_n, loop, div_n; 175 BN_ULONG d0, d1; 176 if (tmp == NULL || snum == NULL || sdiv == NULL || res == NULL) { 177 return 0; 178 } 179 180 // Knuth step D1: Normalise the numbers such that the divisor's MSB is set. 181 // This ensures, in Knuth's terminology, that v1 >= b/2, needed for the 182 // quotient estimation step. 183 norm_shift = BN_BITS2 - (BN_num_bits(divisor) % BN_BITS2); 184 if (!BN_lshift(sdiv, divisor, norm_shift) || 185 !BN_lshift(snum, numerator, norm_shift)) { 186 return 0; 187 } 188 189 // This algorithm relies on |sdiv| being minimal width. We do not use this 190 // function on secret inputs, so leaking this is fine. Also minimize |snum| to 191 // avoid looping on leading zeros, as we're not trying to be leak-free. 192 bn_set_minimal_width(sdiv); 193 bn_set_minimal_width(snum); 194 div_n = sdiv->width; 195 d0 = sdiv->d[div_n - 1]; 196 d1 = (div_n == 1) ? 0 : sdiv->d[div_n - 2]; 197 assert(d0 & (((BN_ULONG)1) << (BN_BITS2 - 1))); 198 199 // Extend |snum| with zeros to satisfy the long division invariants: 200 // - |snum| must have at least |div_n| + 1 words. 201 // - |snum|'s most significant word must be zero to guarantee the first loop 202 // iteration works with a prefix greater than |sdiv|. (This is the extra u0 203 // digit in Knuth step D1.) 204 num_n = snum->width <= div_n ? div_n + 1 : snum->width + 1; 205 if (!bn_resize_words(snum, num_n)) { 206 return 0; 207 } 208 209 // Knuth step D2: The quotient's width is the difference between numerator and 210 // denominator. Also set up its sign and size a temporary for the loop. 211 loop = num_n - div_n; 212 res->neg = snum->neg ^ sdiv->neg; 213 if (!bn_wexpand(res, loop) || // 214 !bn_wexpand(tmp, div_n + 1)) { 215 return 0; 216 } 217 res->width = loop; 218 219 // Knuth steps D2 through D7: Compute the quotient with a word-by-word long 220 // division. Note that Knuth indexes words from most to least significant, so 221 // our index is reversed. Each loop iteration computes res->d[i] of the 222 // quotient and updates snum with the running remainder. Before each loop 223 // iteration, the div_n words beginning at snum->d[i+1] must be less than 224 // snum. 225 for (int i = loop - 1; i >= 0; i--) { 226 // The next word of the quotient, q, is floor(wnum / sdiv), where wnum is 227 // the div_n + 1 words beginning at snum->d[i]. i starts at 228 // num_n - div_n - 1, so there are at least div_n + 1 words available. 229 // 230 // Knuth step D3: Compute q', an estimate of q by looking at the top words 231 // of wnum and sdiv. We must estimate such that q' = q or q' = q + 1. 232 BN_ULONG q, rm = 0; 233 BN_ULONG *wnum = snum->d + i; 234 BN_ULONG n0 = wnum[div_n]; 235 BN_ULONG n1 = wnum[div_n - 1]; 236 if (n0 == d0) { 237 // Estimate q' = b - 1, where b is the base. 238 q = BN_MASK2; 239 // Knuth also runs the fixup routine in this case, but this would require 240 // computing rm and is unnecessary. q' is already close enough. That is, 241 // the true quotient, q is either b - 1 or b - 2. 242 // 243 // By the loop invariant, q <= b - 1, so we must show that q >= b - 2. We 244 // do this by showing wnum / sdiv >= b - 2. Suppose wnum / sdiv < b - 2. 245 // wnum and sdiv have the same most significant word, so: 246 // 247 // wnum >= n0 * b^div_n 248 // sdiv < (n0 + 1) * b^(d_div - 1) 249 // 250 // Thus: 251 // 252 // b - 2 > wnum / sdiv 253 // > (n0 * b^div_n) / (n0 + 1) * b^(div_n - 1) 254 // = (n0 * b) / (n0 + 1) 255 // 256 // (n0 + 1) * (b - 2) > n0 * b 257 // n0 * b + b - 2 * n0 - 2 > n0 * b 258 // b - 2 > 2 * n0 259 // b/2 - 1 > n0 260 // 261 // This contradicts the normalization condition, so q >= b - 2 and our 262 // estimate is close enough. 263 } else { 264 // Estimate q' = floor(n0n1 / d0). Per Theorem B, q' - 2 <= q <= q', which 265 // is slightly outside of our bounds. 266 assert(n0 < d0); 267 bn_div_rem_words(&q, &rm, n0, n1, d0); 268 269 // Fix the estimate by examining one more word and adjusting q' as needed. 270 // This is the second half of step D3 and is sufficient per exercises 19, 271 // 20, and 21. Although only one iteration is needed to correct q + 2 to 272 // q + 1, Knuth uses a loop. A loop will often also correct q + 1 to q, 273 // saving the slightly more expensive underflow handling below. 274 if (div_n > 1) { 275 BN_ULONG n2 = wnum[div_n - 2]; 276#ifdef BN_ULLONG 277 BN_ULLONG t2 = (BN_ULLONG)d1 * q; 278 for (;;) { 279 if (t2 <= ((((BN_ULLONG)rm) << BN_BITS2) | n2)) { 280 break; 281 } 282 q--; 283 rm += d0; 284 if (rm < d0) { 285 // If rm overflows, the true value exceeds BN_ULONG and the next 286 // t2 comparison should exit the loop. 287 break; 288 } 289 t2 -= d1; 290 } 291#else // !BN_ULLONG 292 BN_ULONG t2l, t2h; 293 BN_UMULT_LOHI(t2l, t2h, d1, q); 294 for (;;) { 295 if (t2h < rm || (t2h == rm && t2l <= n2)) { 296 break; 297 } 298 q--; 299 rm += d0; 300 if (rm < d0) { 301 // If rm overflows, the true value exceeds BN_ULONG and the next 302 // t2 comparison should exit the loop. 303 break; 304 } 305 if (t2l < d1) { 306 t2h--; 307 } 308 t2l -= d1; 309 } 310#endif // !BN_ULLONG 311 } 312 } 313 314 // Knuth step D4 through D6: Now q' = q or q' = q + 1, and 315 // -sdiv < wnum - sdiv * q < sdiv. If q' = q + 1, the subtraction will 316 // underflow, and we fix it up below. 317 tmp->d[div_n] = bn_mul_words(tmp->d, sdiv->d, div_n, q); 318 if (bn_sub_words(wnum, wnum, tmp->d, div_n + 1)) { 319 q--; 320 // The final addition is expected to overflow, canceling the underflow. 321 wnum[div_n] += bn_add_words(wnum, wnum, sdiv->d, div_n); 322 } 323 324 // q is now correct, and wnum has been updated to the running remainder. 325 res->d[i] = q; 326 } 327 328 // Trim leading zeros and correct any negative zeros. 329 bn_set_minimal_width(snum); 330 bn_set_minimal_width(res); 331 332 // Knuth step D8: Unnormalize. snum now contains the remainder. 333 if (rem != NULL && !BN_rshift(rem, snum, norm_shift)) { 334 return 0; 335 } 336 337 return 1; 338} 339 340int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx) { 341 if (!(BN_mod(r, m, d, ctx))) { 342 return 0; 343 } 344 if (!r->neg) { 345 return 1; 346 } 347 348 // now -d < r < 0, so we have to set r := r + d. Ignoring the sign bits, this 349 // is r = d - r. 350 return BN_usub(r, d, r); 351} 352 353BN_ULONG bn_reduce_once(BN_ULONG *r, const BN_ULONG *a, BN_ULONG carry, 354 const BN_ULONG *m, size_t num) { 355 assert(r != a); 356 // |r| = |a| - |m|. |bn_sub_words| performs the bulk of the subtraction, and 357 // then we apply the borrow to |carry|. 358 carry -= bn_sub_words(r, a, m, num); 359 // We know 0 <= |a| < 2*|m|, so -|m| <= |r| < |m|. 360 // 361 // If 0 <= |r| < |m|, |r| fits in |num| words and |carry| is zero. We then 362 // wish to select |r| as the answer. Otherwise -m <= r < 0 and we wish to 363 // return |r| + |m|, or |a|. |carry| must then be -1 or all ones. In both 364 // cases, |carry| is a suitable input to |bn_select_words|. 365 // 366 // Although |carry| may be one if it was one on input and |bn_sub_words| 367 // returns zero, this would give |r| > |m|, violating our input assumptions. 368 declassify_assert(carry + 1 <= 1); 369 bn_select_words(r, carry, a /* r < 0 */, r /* r >= 0 */, num); 370 return carry; 371} 372 373BN_ULONG bn_reduce_once_in_place(BN_ULONG *r, BN_ULONG carry, const BN_ULONG *m, 374 BN_ULONG *tmp, size_t num) { 375 // See |bn_reduce_once| for why this logic works. 376 carry -= bn_sub_words(tmp, r, m, num); 377 declassify_assert(carry + 1 <= 1); 378 bn_select_words(r, carry, r /* tmp < 0 */, tmp /* tmp >= 0 */, num); 379 return carry; 380} 381 382void bn_mod_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, 383 const BN_ULONG *m, BN_ULONG *tmp, size_t num) { 384 // r = a - b 385 BN_ULONG borrow = bn_sub_words(r, a, b, num); 386 // tmp = a - b + m 387 bn_add_words(tmp, r, m, num); 388 bn_select_words(r, 0 - borrow, tmp /* r < 0 */, r /* r >= 0 */, num); 389} 390 391void bn_mod_add_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b, 392 const BN_ULONG *m, BN_ULONG *tmp, size_t num) { 393 BN_ULONG carry = bn_add_words(r, a, b, num); 394 bn_reduce_once_in_place(r, carry, m, tmp, num); 395} 396 397int bn_div_consttime(BIGNUM *quotient, BIGNUM *remainder, 398 const BIGNUM *numerator, const BIGNUM *divisor, 399 unsigned divisor_min_bits, BN_CTX *ctx) { 400 if (BN_is_negative(numerator) || BN_is_negative(divisor)) { 401 OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER); 402 return 0; 403 } 404 if (BN_is_zero(divisor)) { 405 OPENSSL_PUT_ERROR(BN, BN_R_DIV_BY_ZERO); 406 return 0; 407 } 408 409 // This function implements long division in binary. It is not very efficient, 410 // but it is simple, easy to make constant-time, and performant enough for RSA 411 // key generation. 412 413 bssl::BN_CTXScope scope(ctx); 414 BIGNUM *q = quotient, *r = remainder; 415 if (quotient == NULL || quotient == numerator || quotient == divisor) { 416 q = BN_CTX_get(ctx); 417 } 418 if (remainder == NULL || remainder == numerator || remainder == divisor) { 419 r = BN_CTX_get(ctx); 420 } 421 BIGNUM *tmp = BN_CTX_get(ctx); 422 int initial_words; 423 if (q == NULL || r == NULL || tmp == NULL || 424 !bn_wexpand(q, numerator->width) || !bn_wexpand(r, divisor->width) || 425 !bn_wexpand(tmp, divisor->width)) { 426 return 0; 427 } 428 429 OPENSSL_memset(q->d, 0, numerator->width * sizeof(BN_ULONG)); 430 q->width = numerator->width; 431 q->neg = 0; 432 433 OPENSSL_memset(r->d, 0, divisor->width * sizeof(BN_ULONG)); 434 r->width = divisor->width; 435 r->neg = 0; 436 437 // Incorporate |numerator| into |r|, one bit at a time, reducing after each 438 // step. We maintain the invariant that |0 <= r < divisor| and 439 // |q * divisor + r = n| where |n| is the portion of |numerator| incorporated 440 // so far. 441 // 442 // First, we short-circuit the loop: if we know |divisor| has at least 443 // |divisor_min_bits| bits, the top |divisor_min_bits - 1| can be incorporated 444 // without reductions. This significantly speeds up |RSA_check_key|. For 445 // simplicity, we round down to a whole number of words. 446 declassify_assert(divisor_min_bits <= BN_num_bits(divisor)); 447 initial_words = 0; 448 if (divisor_min_bits > 0) { 449 initial_words = (divisor_min_bits - 1) / BN_BITS2; 450 if (initial_words > numerator->width) { 451 initial_words = numerator->width; 452 } 453 OPENSSL_memcpy(r->d, numerator->d + numerator->width - initial_words, 454 initial_words * sizeof(BN_ULONG)); 455 } 456 457 for (int i = numerator->width - initial_words - 1; i >= 0; i--) { 458 for (int bit = BN_BITS2 - 1; bit >= 0; bit--) { 459 // Incorporate the next bit of the numerator, by computing 460 // r = 2*r or 2*r + 1. Note the result fits in one more word. We store the 461 // extra word in |carry|. 462 BN_ULONG carry = bn_add_words(r->d, r->d, r->d, divisor->width); 463 r->d[0] |= (numerator->d[i] >> bit) & 1; 464 // |r| was previously fully-reduced, so we know: 465 // 2*0 <= r <= 2*(divisor-1) + 1 466 // 0 <= r <= 2*divisor - 1 < 2*divisor. 467 // Thus |r| satisfies the preconditions for |bn_reduce_once_in_place|. 468 BN_ULONG subtracted = bn_reduce_once_in_place(r->d, carry, divisor->d, 469 tmp->d, divisor->width); 470 // The corresponding bit of the quotient is set iff we needed to subtract. 471 q->d[i] |= (~subtracted & 1) << bit; 472 } 473 } 474 475 if ((quotient != NULL && !BN_copy(quotient, q)) || 476 (remainder != NULL && !BN_copy(remainder, r))) { 477 return 0; 478 } 479 480 return 1; 481} 482 483static BIGNUM *bn_scratch_space_from_ctx(size_t width, BN_CTX *ctx) { 484 BIGNUM *ret = BN_CTX_get(ctx); 485 if (ret == NULL || !bn_wexpand(ret, width)) { 486 return NULL; 487 } 488 ret->neg = 0; 489 ret->width = (int)width; 490 return ret; 491} 492 493// bn_resized_from_ctx returns |bn| with width at least |width| or NULL on 494// error. This is so it may be used with low-level "words" functions. If 495// necessary, it allocates a new |BIGNUM| with a lifetime of the current scope 496// in |ctx|, so the caller does not need to explicitly free it. |bn| must fit in 497// |width| words. 498static const BIGNUM *bn_resized_from_ctx(const BIGNUM *bn, size_t width, 499 BN_CTX *ctx) { 500 if ((size_t)bn->width >= width) { 501 // Any excess words must be zero. 502 assert(bn_fits_in_words(bn, width)); 503 return bn; 504 } 505 BIGNUM *ret = bn_scratch_space_from_ctx(width, ctx); 506 if (ret == NULL || !BN_copy(ret, bn) || !bn_resize_words(ret, width)) { 507 return NULL; 508 } 509 return ret; 510} 511 512int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, 513 BN_CTX *ctx) { 514 if (!BN_add(r, a, b)) { 515 return 0; 516 } 517 return BN_nnmod(r, r, m, ctx); 518} 519 520int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, 521 const BIGNUM *m) { 522 bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new()); 523 return ctx != nullptr && bn_mod_add_consttime(r, a, b, m, ctx.get()); 524} 525 526int bn_mod_add_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, 527 const BIGNUM *m, BN_CTX *ctx) { 528 bssl::BN_CTXScope scope(ctx); 529 a = bn_resized_from_ctx(a, m->width, ctx); 530 b = bn_resized_from_ctx(b, m->width, ctx); 531 BIGNUM *tmp = bn_scratch_space_from_ctx(m->width, ctx); 532 if (a == nullptr || b == nullptr || tmp == nullptr || 533 !bn_wexpand(r, m->width)) { 534 return 0; 535 } 536 bn_mod_add_words(r->d, a->d, b->d, m->d, tmp->d, m->width); 537 r->width = m->width; 538 r->neg = 0; 539 return 1; 540} 541 542int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, 543 BN_CTX *ctx) { 544 if (!BN_sub(r, a, b)) { 545 return 0; 546 } 547 return BN_nnmod(r, r, m, ctx); 548} 549 550int bn_mod_sub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, 551 const BIGNUM *m, BN_CTX *ctx) { 552 bssl::BN_CTXScope scope(ctx); 553 a = bn_resized_from_ctx(a, m->width, ctx); 554 b = bn_resized_from_ctx(b, m->width, ctx); 555 BIGNUM *tmp = bn_scratch_space_from_ctx(m->width, ctx); 556 if (a == nullptr || b == nullptr || tmp == nullptr || 557 !bn_wexpand(r, m->width)) { 558 return 0; 559 } 560 bn_mod_sub_words(r->d, a->d, b->d, m->d, tmp->d, m->width); 561 r->width = m->width; 562 r->neg = 0; 563 return 1; 564} 565 566int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, 567 const BIGNUM *m) { 568 bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new()); 569 return ctx != nullptr && bn_mod_sub_consttime(r, a, b, m, ctx.get()); 570} 571 572int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m, 573 BN_CTX *ctx) { 574 bssl::BN_CTXScope scope(ctx); 575 BIGNUM *t = BN_CTX_get(ctx); 576 if (t == NULL) { 577 return 0; 578 } 579 580 if (a == b) { 581 if (!BN_sqr(t, a, ctx)) { 582 return 0; 583 } 584 } else { 585 if (!BN_mul(t, a, b, ctx)) { 586 return 0; 587 } 588 } 589 590 if (!BN_nnmod(r, t, m, ctx)) { 591 return 0; 592 } 593 594 return 1; 595} 596 597int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) { 598 if (!BN_sqr(r, a, ctx)) { 599 return 0; 600 } 601 602 // r->neg == 0, thus we don't need BN_nnmod 603 return BN_mod(r, r, m, ctx); 604} 605 606int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m, 607 BN_CTX *ctx) { 608 if (!BN_nnmod(r, a, m, ctx)) { 609 return 0; 610 } 611 612 bssl::UniquePtr<BIGNUM> abs_m; 613 if (m->neg) { 614 abs_m.reset(BN_dup(m)); 615 if (abs_m == nullptr) { 616 return 0; 617 } 618 abs_m->neg = 0; 619 } 620 621 return bn_mod_lshift_consttime(r, r, n, (abs_m ? abs_m.get() : m), ctx); 622} 623 624int bn_mod_lshift_consttime(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m, 625 BN_CTX *ctx) { 626 if (!BN_copy(r, a) || !bn_resize_words(r, m->width)) { 627 return 0; 628 } 629 630 bssl::BN_CTXScope scope(ctx); 631 BIGNUM *tmp = bn_scratch_space_from_ctx(m->width, ctx); 632 if (tmp == nullptr) { 633 return 0; 634 } 635 for (int i = 0; i < n; i++) { 636 bn_mod_add_words(r->d, r->d, r->d, m->d, tmp->d, m->width); 637 } 638 r->neg = 0; 639 return 1; 640} 641 642int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m) { 643 bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new()); 644 return ctx != nullptr && bn_mod_lshift_consttime(r, a, n, m, ctx.get()); 645} 646 647int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx) { 648 if (!BN_lshift1(r, a)) { 649 return 0; 650 } 651 652 return BN_nnmod(r, r, m, ctx); 653} 654 655int bn_mod_lshift1_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, 656 BN_CTX *ctx) { 657 return bn_mod_add_consttime(r, a, a, m, ctx); 658} 659 660int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m) { 661 bssl::UniquePtr<BN_CTX> ctx(BN_CTX_new()); 662 return ctx != nullptr && bn_mod_lshift1_consttime(r, a, m, ctx.get()); 663} 664 665BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) { 666 BN_ULONG ret = 0; 667 int i, j; 668 669 if (!w) { 670 // actually this an error (division by zero) 671 return (BN_ULONG)-1; 672 } 673 674 if (a->width == 0) { 675 return 0; 676 } 677 678 // normalize input for |bn_div_rem_words|. 679 j = BN_BITS2 - BN_num_bits_word(w); 680 w <<= j; 681 if (!BN_lshift(a, a, j)) { 682 return (BN_ULONG)-1; 683 } 684 685 for (i = a->width - 1; i >= 0; i--) { 686 BN_ULONG l = a->d[i]; 687 BN_ULONG d; 688 BN_ULONG unused_rem; 689 bn_div_rem_words(&d, &unused_rem, ret, l, w); 690 ret = l - (d * w); 691 a->d[i] = d; 692 } 693 694 bn_set_minimal_width(a); 695 ret >>= j; 696 return ret; 697} 698 699BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w) { 700#ifndef BN_CAN_DIVIDE_ULLONG 701 BN_ULONG ret = 0; 702#else 703 BN_ULLONG ret = 0; 704#endif 705 int i; 706 707 if (w == 0) { 708 return (BN_ULONG)-1; 709 } 710 711#ifndef BN_CAN_DIVIDE_ULLONG 712 // If |w| is too long and we don't have |BN_ULLONG| division then we need to 713 // fall back to using |BN_div_word|. 714 if (w > ((BN_ULONG)1 << BN_BITS4)) { 715 BIGNUM *tmp = BN_dup(a); 716 if (tmp == NULL) { 717 return (BN_ULONG)-1; 718 } 719 ret = BN_div_word(tmp, w); 720 BN_free(tmp); 721 return ret; 722 } 723#endif 724 725 for (i = a->width - 1; i >= 0; i--) { 726#ifndef BN_CAN_DIVIDE_ULLONG 727 ret = ((ret << BN_BITS4) | ((a->d[i] >> BN_BITS4) & BN_MASK2l)) % w; 728 ret = ((ret << BN_BITS4) | (a->d[i] & BN_MASK2l)) % w; 729#else 730 ret = (BN_ULLONG)(((ret << (BN_ULLONG)BN_BITS2) | a->d[i]) % (BN_ULLONG)w); 731#endif 732 } 733 return (BN_ULONG)ret; 734} 735