Debian Codegraph @

debian/rust-vendor/aws-lc-sys/aws-lc/crypto/fipsmodule/bn/exponentiation.c

raw
1 // Copyright (C) 1995-1998 Eric Young ([email protected])
2 // Copyright (c) 1998-2005 The OpenSSL Project. All rights reserved.
3 // SPDX-License-Identifier: Apache-2.0
4
5 #include <openssl/bn.h>
6
7 #include <assert.h>
8 #include <limits.h>
9 #include <stdlib.h>
10 #include <string.h>
11
12 #include <openssl/err.h>
13 #include <openssl/mem.h>
14
15 #include "internal.h"
16 #include "rsaz_exp.h"
17
18 #if !defined(OPENSSL_NO_ASM) && \
19 (defined(OPENSSL_LINUX) || defined(OPENSSL_APPLE) || \
20 defined(OPENSSL_OPENBSD) || defined(OPENSSL_FREEBSD) || \
21 defined(OPENSSL_NETBSD)) && \
22 defined(OPENSSL_AARCH64)
23
24 #include "../../../third_party/s2n-bignum/s2n-bignum_aws-lc.h"
25
26 #define BN_EXPONENTIATION_S2N_BIGNUM_CAPABLE 1
27
28 OPENSSL_INLINE int exponentiation_use_s2n_bignum(void) {
29 return CRYPTO_is_NEON_capable();
30 }
31
32 #else
33
34 OPENSSL_INLINE int exponentiation_use_s2n_bignum(void) { return 0; }
35
36 #endif
37
38 static void exponentiation_s2n_bignum_copy_from_prebuf(BN_ULONG *dest, int width,
39 const BN_ULONG *table, int rowidx,
40 int window) {
41
42 #if defined(BN_EXPONENTIATION_S2N_BIGNUM_CAPABLE)
43
44 int table_height = 1 << window;
45 if (width == 32) {
46 bignum_copy_row_from_table_32(dest, table, table_height, rowidx);
47 } else if (width == 16) {
48 bignum_copy_row_from_table_16(dest, table, table_height, rowidx);
49 } else if (width % 8 == 0) {
50 bignum_copy_row_from_table_8n(dest, table, table_height, width, rowidx);
51 } else {
52 bignum_copy_row_from_table(dest, table, table_height, width, rowidx);
53 }
54
55 #else
56
57 // Should not call this function unless s2n-bignum is supported.
58 abort();
59
60 #endif
61 }
62
63
64 int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) {
65 int i, bits, ret = 0;
66 BIGNUM *v, *rr;
67
68 BN_CTX_start(ctx);
69 if (r == a || r == p) {
70 rr = BN_CTX_get(ctx);
71 } else {
72 rr = r;
73 }
74
75 v = BN_CTX_get(ctx);
76 if (rr == NULL || v == NULL) {
77 goto err;
78 }
79
80 if (BN_copy(v, a) == NULL) {
81 goto err;
82 }
83 bits = BN_num_bits(p);
84
85 if (BN_is_odd(p)) {
86 if (BN_copy(rr, a) == NULL) {
87 goto err;
88 }
89 } else {
90 if (!BN_one(rr)) {
91 goto err;
92 }
93 }
94
95 for (i = 1; i < bits; i++) {
96 if (!BN_sqr(v, v, ctx)) {
97 goto err;
98 }
99 if (BN_is_bit_set(p, i)) {
100 if (!BN_mul(rr, rr, v, ctx)) {
101 goto err;
102 }
103 }
104 }
105
106 if (r != rr && !BN_copy(r, rr)) {
107 goto err;
108 }
109 ret = 1;
110
111 err:
112 BN_CTX_end(ctx);
113 return ret;
114 }
115
116 typedef struct bn_recp_ctx_st {
117 BIGNUM N; // the divisor
118 BIGNUM Nr; // the reciprocal
119 int num_bits;
120 int shift;
121 int flags;
122 } BN_RECP_CTX;
123
124 static void BN_RECP_CTX_init(BN_RECP_CTX *recp) {
125 BN_init(&recp->N);
126 BN_init(&recp->Nr);
127 recp->num_bits = 0;
128 recp->shift = 0;
129 recp->flags = 0;
130 }
131
132 static void BN_RECP_CTX_free(BN_RECP_CTX *recp) {
133 if (recp == NULL) {
134 return;
135 }
136
137 BN_free(&recp->N);
138 BN_free(&recp->Nr);
139 }
140
141 static int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *d, BN_CTX *ctx) {
142 if (!BN_copy(&(recp->N), d)) {
143 return 0;
144 }
145 BN_zero(&recp->Nr);
146 recp->num_bits = BN_num_bits(d);
147 recp->shift = 0;
148
149 return 1;
150 }
151
152 // len is the expected size of the result We actually calculate with an extra
153 // word of precision, so we can do faster division if the remainder is not
154 // required.
155 // r := 2^len / m
156 static int BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx) {
157 int ret = -1;
158 BIGNUM *t;
159
160 BN_CTX_start(ctx);
161 t = BN_CTX_get(ctx);
162 if (t == NULL) {
163 goto err;
164 }
165
166 if (!BN_set_bit(t, len)) {
167 goto err;
168 }
169
170 if (!BN_div(r, NULL, t, m, ctx)) {
171 goto err;
172 }
173
174 ret = len;
175
176 err:
177 BN_CTX_end(ctx);
178 return ret;
179 }
180
181 static int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m,
182 BN_RECP_CTX *recp, BN_CTX *ctx) {
183 int i, j, ret = 0;
184 BIGNUM *a, *b, *d, *r;
185
186 BN_CTX_start(ctx);
187 a = BN_CTX_get(ctx);
188 b = BN_CTX_get(ctx);
189 if (dv != NULL) {
190 d = dv;
191 } else {
192 d = BN_CTX_get(ctx);
193 }
194
195 if (rem != NULL) {
196 r = rem;
197 } else {
198 r = BN_CTX_get(ctx);
199 }
200
201 if (a == NULL || b == NULL || d == NULL || r == NULL) {
202 goto err;
203 }
204
205 if (BN_ucmp(m, &recp->N) < 0) {
206 BN_zero(d);
207 if (!BN_copy(r, m)) {
208 goto err;
209 }
210 BN_CTX_end(ctx);
211 return 1;
212 }
213
214 // We want the remainder
215 // Given input of ABCDEF / ab
216 // we need multiply ABCDEF by 3 digests of the reciprocal of ab
217
218 // i := max(BN_num_bits(m), 2*BN_num_bits(N))
219 i = BN_num_bits(m);
220 j = recp->num_bits << 1;
221 if (j > i) {
222 i = j;
223 }
224
225 // Nr := round(2^i / N)
226 if (i != recp->shift) {
227 recp->shift =
228 BN_reciprocal(&(recp->Nr), &(recp->N), i,
229 ctx); // BN_reciprocal returns i, or -1 for an error
230 }
231
232 if (recp->shift == -1) {
233 goto err;
234 }
235
236 // d := |round(round(m / 2^BN_num_bits(N)) * recp->Nr / 2^(i -
237 // BN_num_bits(N)))|
238 // = |round(round(m / 2^BN_num_bits(N)) * round(2^i / N) / 2^(i -
239 // BN_num_bits(N)))|
240 // <= |(m / 2^BN_num_bits(N)) * (2^i / N) * (2^BN_num_bits(N) / 2^i)|
241 // = |m/N|
242 if (!BN_rshift(a, m, recp->num_bits)) {
243 goto err;
244 }
245 if (!BN_mul(b, a, &(recp->Nr), ctx)) {
246 goto err;
247 }
248 if (!BN_rshift(d, b, i - recp->num_bits)) {
249 goto err;
250 }
251 d->neg = 0;
252
253 if (!BN_mul(b, &(recp->N), d, ctx)) {
254 goto err;
255 }
256 if (!BN_usub(r, m, b)) {
257 goto err;
258 }
259 r->neg = 0;
260
261 j = 0;
262 while (BN_ucmp(r, &(recp->N)) >= 0) {
263 if (j++ > 2) {
264 OPENSSL_PUT_ERROR(BN, BN_R_BAD_RECIPROCAL);
265 goto err;
266 }
267 if (!BN_usub(r, r, &(recp->N))) {
268 goto err;
269 }
270 if (!BN_add_word(d, 1)) {
271 goto err;
272 }
273 }
274
275 r->neg = BN_is_zero(r) ? 0 : m->neg;
276 d->neg = m->neg ^ recp->N.neg;
277 ret = 1;
278
279 err:
280 BN_CTX_end(ctx);
281 return ret;
282 }
283
284 static int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y,
285 BN_RECP_CTX *recp, BN_CTX *ctx) {
286 int ret = 0;
287 BIGNUM *a;
288 const BIGNUM *ca;
289
290 BN_CTX_start(ctx);
291 a = BN_CTX_get(ctx);
292 if (a == NULL) {
293 goto err;
294 }
295
296 if (y != NULL) {
297 if (x == y) {
298 if (!BN_sqr(a, x, ctx)) {
299 goto err;
300 }
301 } else {
302 if (!BN_mul(a, x, y, ctx)) {
303 goto err;
304 }
305 }
306 ca = a;
307 } else {
308 ca = x; // Just do the mod
309 }
310
311 ret = BN_div_recp(NULL, r, ca, recp, ctx);
312
313 err:
314 BN_CTX_end(ctx);
315 return ret;
316 }
317
318 // BN_window_bits_for_exponent_size returns sliding window size for mod_exp with
319 // a |b| bit exponent.
320 //
321 // For window size 'w' (w >= 2) and a random 'b' bits exponent, the number of
322 // multiplications is a constant plus on average
323 //
324 // 2^(w-1) + (b-w)/(w+1);
325 //
326 // here 2^(w-1) is for precomputing the table (we actually need entries only
327 // for windows that have the lowest bit set), and (b-w)/(w+1) is an
328 // approximation for the expected number of w-bit windows, not counting the
329 // first one.
330 //
331 // Thus we should use
332 //
333 // w >= 6 if b > 671
334 // w = 5 if 671 > b > 239
335 // w = 4 if 239 > b > 79
336 // w = 3 if 79 > b > 23
337 // w <= 2 if 23 > b
338 //
339 // (with draws in between). Very small exponents are often selected
340 // with low Hamming weight, so we use w = 1 for b <= 23.
341 static int BN_window_bits_for_exponent_size(size_t b) {
342 if (b > 671) {
343 return 6;
344 }
345 if (b > 239) {
346 return 5;
347 }
348 if (b > 79) {
349 return 4;
350 }
351 if (b > 23) {
352 return 3;
353 }
354 return 1;
355 }
356
357 // TABLE_SIZE is the maximum precomputation table size for *variable* sliding
358 // windows. This must be 2^(max_window - 1), where max_window is the largest
359 // value returned from |BN_window_bits_for_exponent_size|.
360 #define TABLE_SIZE 32
361
362 // TABLE_BITS_SMALL is the smallest value returned from
363 // |BN_window_bits_for_exponent_size| when |b| is at most |BN_BITS2| *
364 // |BN_SMALL_MAX_WORDS| words.
365 #define TABLE_BITS_SMALL 5
366
367 // TABLE_SIZE_SMALL is the same as |TABLE_SIZE|, but when |b| is at most
368 // |BN_BITS2| * |BN_SMALL_MAX_WORDS|.
369 #define TABLE_SIZE_SMALL (1 << (TABLE_BITS_SMALL - 1))
370
371 static int mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
372 const BIGNUM *m, BN_CTX *ctx) {
373 int i, j, ret = 0, wstart, window;
374 int start = 1;
375 BIGNUM *aa;
376 // Table of variables obtained from 'ctx'
377 BIGNUM *val[TABLE_SIZE];
378 BN_RECP_CTX recp;
379
380 // This function is only called on even moduli.
381 assert(!BN_is_odd(m));
382
383 int bits = BN_num_bits(p);
384 if (bits == 0) {
385 return BN_one(r);
386 }
387
388 BN_RECP_CTX_init(&recp);
389 BN_CTX_start(ctx);
390 aa = BN_CTX_get(ctx);
391 val[0] = BN_CTX_get(ctx);
392 if (!aa || !val[0]) {
393 goto err;
394 }
395
396 if (m->neg) {
397 // ignore sign of 'm'
398 if (!BN_copy(aa, m)) {
399 goto err;
400 }
401 aa->neg = 0;
402 if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0) {
403 goto err;
404 }
405 } else {
406 if (BN_RECP_CTX_set(&recp, m, ctx) <= 0) {
407 goto err;
408 }
409 }
410
411 if (!BN_nnmod(val[0], a, m, ctx)) {
412 goto err; // 1
413 }
414 if (BN_is_zero(val[0])) {
415 BN_zero(r);
416 ret = 1;
417 goto err;
418 }
419
420 window = BN_window_bits_for_exponent_size(bits);
421 if (window > 1) {
422 if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx)) {
423 goto err; // 2
424 }
425 j = 1 << (window - 1);
426 for (i = 1; i < j; i++) {
427 if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
428 !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx)) {
429 goto err;
430 }
431 }
432 }
433
434 start = 1; // This is used to avoid multiplication etc
435 // when there is only the value '1' in the
436 // buffer.
437 wstart = bits - 1; // The top bit of the window
438
439 if (!BN_one(r)) {
440 goto err;
441 }
442
443 for (;;) {
444 int wvalue; // The 'value' of the window
445 int wend; // The bottom bit of the window
446
447 if (!BN_is_bit_set(p, wstart)) {
448 if (!start) {
449 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) {
450 goto err;
451 }
452 }
453 if (wstart == 0) {
454 break;
455 }
456 wstart--;
457 continue;
458 }
459
460 // We now have wstart on a 'set' bit, we now need to work out
461 // how bit a window to do. To do this we need to scan
462 // forward until the last set bit before the end of the
463 // window
464 wvalue = 1;
465 wend = 0;
466 for (i = 1; i < window; i++) {
467 if (wstart - i < 0) {
468 break;
469 }
470 if (BN_is_bit_set(p, wstart - i)) {
471 wvalue <<= (i - wend);
472 wvalue |= 1;
473 wend = i;
474 }
475 }
476
477 // wend is the size of the current window
478 j = wend + 1;
479 // add the 'bytes above'
480 if (!start) {
481 for (i = 0; i < j; i++) {
482 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx)) {
483 goto err;
484 }
485 }
486 }
487
488 // wvalue will be an odd number < 2^window
489 if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx)) {
490 goto err;
491 }
492
493 // move the 'window' down further
494 wstart -= wend + 1;
495 start = 0;
496 if (wstart < 0) {
497 break;
498 }
499 }
500 ret = 1;
501
502 err:
503 BN_CTX_end(ctx);
504 BN_RECP_CTX_free(&recp);
505 return ret;
506 }
507
508 int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
509 BN_CTX *ctx) {
510 if (m->neg) {
511 OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
512 return 0;
513 }
514 if (a->neg || BN_ucmp(a, m) >= 0) {
515 if (!BN_nnmod(r, a, m, ctx)) {
516 return 0;
517 }
518 a = r;
519 }
520
521 if (BN_is_odd(m)) {
522 return BN_mod_exp_mont(r, a, p, m, ctx, NULL);
523 }
524
525 return mod_exp_recp(r, a, p, m, ctx);
526 }
527
528 int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
529 const BIGNUM *m, BN_CTX *ctx, const BN_MONT_CTX *mont) {
530 if (!BN_is_odd(m)) {
531 OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS);
532 return 0;
533 }
534 if (m->neg) {
535 OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
536 return 0;
537 }
538 // |a| is secret, but |a < m| is not.
539 if (a->neg || constant_time_declassify_int(BN_ucmp(a, m)) >= 0) {
540 OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED);
541 return 0;
542 }
543
544 int bits = BN_num_bits(p);
545 if (bits == 0) {
546 // x**0 mod 1 is still zero.
547 if (BN_abs_is_word(m, 1)) {
548 BN_zero(rr);
549 return 1;
550 }
551 return BN_one(rr);
552 }
553
554 int ret = 0;
555 BIGNUM *val[TABLE_SIZE];
556 BN_MONT_CTX *new_mont = NULL;
557
558 BN_CTX_start(ctx);
559 BIGNUM *r = BN_CTX_get(ctx);
560 val[0] = BN_CTX_get(ctx);
561 if (r == NULL || val[0] == NULL) {
562 goto err;
563 }
564
565 // Allocate a montgomery context if it was not supplied by the caller.
566 if (mont == NULL) {
567 new_mont = BN_MONT_CTX_new_consttime(m, ctx);
568 if (new_mont == NULL) {
569 goto err;
570 }
571 mont = new_mont;
572 }
573
574 // We exponentiate by looking at sliding windows of the exponent and
575 // precomputing powers of |a|. Windows may be shifted so they always end on a
576 // set bit, so only precompute odd powers. We compute val[i] = a^(2*i + 1)
577 // for i = 0 to 2^(window-1), all in Montgomery form.
578 int window = BN_window_bits_for_exponent_size(bits);
579 if (!BN_to_montgomery(val[0], a, mont, ctx)) {
580 goto err;
581 }
582 if (window > 1) {
583 BIGNUM *d = BN_CTX_get(ctx);
584 if (d == NULL ||
585 !BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx)) {
586 goto err;
587 }
588 for (int i = 1; i < 1 << (window - 1); i++) {
589 val[i] = BN_CTX_get(ctx);
590 if (val[i] == NULL ||
591 !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx)) {
592 goto err;
593 }
594 }
595 }
596
597 // |p| is non-zero, so at least one window is non-zero. To save some
598 // multiplications, defer initializing |r| until then.
599 int r_is_one = 1;
600 int wstart = bits - 1; // The top bit of the window.
601 for (;;) {
602 if (!BN_is_bit_set(p, wstart)) {
603 if (!r_is_one && !BN_mod_mul_montgomery(r, r, r, mont, ctx)) {
604 goto err;
605 }
606 if (wstart == 0) {
607 break;
608 }
609 wstart--;
610 continue;
611 }
612
613 // We now have wstart on a set bit. Find the largest window we can use.
614 int wvalue = 1;
615 int wsize = 0;
616 for (int i = 1; i < window && i <= wstart; i++) {
617 if (BN_is_bit_set(p, wstart - i)) {
618 wvalue <<= (i - wsize);
619 wvalue |= 1;
620 wsize = i;
621 }
622 }
623
624 // Shift |r| to the end of the window.
625 if (!r_is_one) {
626 for (int i = 0; i < wsize + 1; i++) {
627 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx)) {
628 goto err;
629 }
630 }
631 }
632
633 assert(wvalue & 1);
634 assert(wvalue < (1 << window));
635 if (r_is_one) {
636 if (!BN_copy(r, val[wvalue >> 1])) {
637 goto err;
638 }
639 } else if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx)) {
640 goto err;
641 }
642
643 r_is_one = 0;
644 if (wstart == wsize) {
645 break;
646 }
647 wstart -= wsize + 1;
648 }
649
650 // |p| is non-zero, so |r_is_one| must be cleared at some point.
651 assert(!r_is_one);
652
653 if (!BN_from_montgomery(rr, r, mont, ctx)) {
654 goto err;
655 }
656 ret = 1;
657
658 err:
659 BN_MONT_CTX_free(new_mont);
660 BN_CTX_end(ctx);
661 return ret;
662 }
663
664 void bn_mod_exp_mont_small(BN_ULONG *r, const BN_ULONG *a, size_t num,
665 const BN_ULONG *p, size_t num_p,
666 const BN_MONT_CTX *mont) {
667 if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS ||
668 num_p > SIZE_MAX / BN_BITS2) {
669 abort();
670 }
671 assert(BN_is_odd(&mont->N));
672
673 // Count the number of bits in |p|, skipping leading zeros. Note this function
674 // treats |p| as public.
675 while (num_p != 0 && p[num_p - 1] == 0) {
676 num_p--;
677 }
678 if (num_p == 0) {
679 bn_from_montgomery_small(r, num, mont->RR.d, num, mont);
680 return;
681 }
682 size_t bits = BN_num_bits_word(p[num_p - 1]) + (num_p - 1) * BN_BITS2;
683 assert(bits != 0);
684
685 // We exponentiate by looking at sliding windows of the exponent and
686 // precomputing powers of |a|. Windows may be shifted so they always end on a
687 // set bit, so only precompute odd powers. We compute val[i] = a^(2*i + 1) for
688 // i = 0 to 2^(window-1), all in Montgomery form.
689 unsigned window = BN_window_bits_for_exponent_size(bits);
690 if (window > TABLE_BITS_SMALL) {
691 window = TABLE_BITS_SMALL; // Tolerate excessively large |p|.
692 }
693 BN_ULONG val[TABLE_SIZE_SMALL][BN_SMALL_MAX_WORDS];
694 OPENSSL_memcpy(val[0], a, num * sizeof(BN_ULONG));
695 if (window > 1) {
696 BN_ULONG d[BN_SMALL_MAX_WORDS];
697 bn_mod_mul_montgomery_small(d, val[0], val[0], num, mont);
698 for (unsigned i = 1; i < 1u << (window - 1); i++) {
699 bn_mod_mul_montgomery_small(val[i], val[i - 1], d, num, mont);
700 }
701 }
702
703 // |p| is non-zero, so at least one window is non-zero. To save some
704 // multiplications, defer initializing |r| until then.
705 int r_is_one = 1;
706 size_t wstart = bits - 1; // The top bit of the window.
707 for (;;) {
708 if (!bn_is_bit_set_words(p, num_p, wstart)) {
709 if (!r_is_one) {
710 bn_mod_mul_montgomery_small(r, r, r, num, mont);
711 }
712 if (wstart == 0) {
713 break;
714 }
715 wstart--;
716 continue;
717 }
718
719 // We now have wstart on a set bit. Find the largest window we can use.
720 unsigned wvalue = 1;
721 unsigned wsize = 0;
722 for (unsigned i = 1; i < window && i <= wstart; i++) {
723 if (bn_is_bit_set_words(p, num_p, wstart - i)) {
724 wvalue <<= (i - wsize);
725 wvalue |= 1;
726 wsize = i;
727 }
728 }
729
730 // Shift |r| to the end of the window.
731 if (!r_is_one) {
732 for (unsigned i = 0; i < wsize + 1; i++) {
733 bn_mod_mul_montgomery_small(r, r, r, num, mont);
734 }
735 }
736
737 assert(wvalue & 1);
738 assert(wvalue < (1u << window));
739 if (r_is_one) {
740 OPENSSL_memcpy(r, val[wvalue >> 1], num * sizeof(BN_ULONG));
741 } else {
742 bn_mod_mul_montgomery_small(r, r, val[wvalue >> 1], num, mont);
743 }
744 r_is_one = 0;
745 if (wstart == wsize) {
746 break;
747 }
748 wstart -= wsize + 1;
749 }
750
751 // |p| is non-zero, so |r_is_one| must be cleared at some point.
752 assert(!r_is_one);
753 OPENSSL_cleanse(val, sizeof(val));
754 }
755
756 void bn_mod_inverse0_prime_mont_small(BN_ULONG *r, const BN_ULONG *a,
757 size_t num, const BN_MONT_CTX *mont) {
758 if (num != (size_t)mont->N.width || num > BN_SMALL_MAX_WORDS) {
759 abort();
760 }
761
762 // Per Fermat's Little Theorem, a^-1 = a^(p-2) (mod p) for p prime.
763 BN_ULONG p_minus_two[BN_SMALL_MAX_WORDS];
764 const BN_ULONG *p = mont->N.d;
765 OPENSSL_memcpy(p_minus_two, p, num * sizeof(BN_ULONG));
766 if (p_minus_two[0] >= 2) {
767 p_minus_two[0] -= 2;
768 } else {
769 p_minus_two[0] -= 2;
770 for (size_t i = 1; i < num; i++) {
771 if (p_minus_two[i]-- != 0) {
772 break;
773 }
774 }
775 }
776
777 bn_mod_exp_mont_small(r, a, num, p_minus_two, num, mont);
778 }
779
780 static void copy_to_prebuf(const BIGNUM *b, int top, BN_ULONG *table, int idx,
781 int window) {
782 int ret = bn_copy_words(table + idx * top, top, b);
783 assert(ret); // |b| is guaranteed to fit.
784 (void)ret;
785 }
786
787 static int copy_from_prebuf(BIGNUM *b, int top, const BN_ULONG *table, int idx,
788 int window) {
789 if (!bn_wexpand(b, top)) {
790 return 0;
791 }
792
793 if (exponentiation_use_s2n_bignum()) {
794 exponentiation_s2n_bignum_copy_from_prebuf(b->d, top, table, idx, window);
795 b->width = top;
796 return 1;
797 }
798
799 OPENSSL_memset(b->d, 0, sizeof(BN_ULONG) * top);
800 const int width = 1 << window;
801 for (int i = 0; i < width; i++, table += top) {
802 // Use a value barrier to prevent Clang from adding a branch when |i != idx|
803 // and making this copy not constant time. Clang is still allowed to learn
804 // that |mask| is constant across the inner loop, so this won't inhibit any
805 // vectorization it might do.
806 BN_ULONG mask = value_barrier_w(constant_time_eq_int(i, idx));
807 for (int j = 0; j < top; j++) {
808 b->d[j] |= table[j] & mask;
809 }
810 }
811
812 b->width = top;
813 return 1;
814 }
815
816 // Window sizes optimized for fixed window size modular exponentiation
817 // algorithm (BN_mod_exp_mont_consttime).
818 #define BN_window_bits_for_ctime_exponent_size 5
819
820 // This variant of |BN_mod_exp_mont| uses fixed windows and fixed memory access
821 // patterns to protect secret exponents (cf. the hyper-threading timing attacks
822 // pointed out by Colin Percival,
823 // http://www.daemonology.net/hyperthreading-considered-harmful/)
824 int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
825 const BIGNUM *m, BN_CTX *ctx,
826 const BN_MONT_CTX *mont) {
827 int i, ret = 0, wvalue;
828 BN_MONT_CTX *new_mont = NULL;
829
830 unsigned char *powerbuf_free = NULL;
831 size_t powerbuf_len = 0;
832 BN_ULONG *powerbuf = NULL;
833
834 if (!BN_is_odd(m)) {
835 OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS);
836 return 0;
837 }
838 if (m->neg) {
839 OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
840 return 0;
841 }
842 // |a| is secret, but it is required to be in range, so these comparisons may
843 // be leaked.
844 if (a->neg || constant_time_declassify_int(BN_ucmp(a, m) >= 0)) {
845 OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED);
846 return 0;
847 }
848
849 // Use all bits stored in |p|, rather than |BN_num_bits|, so we do not leak
850 // whether the top bits are zero.
851 int max_bits = p->width * BN_BITS2;
852 int bits = max_bits;
853 if (bits == 0) {
854 // x**0 mod 1 is still zero.
855 if (BN_abs_is_word(m, 1)) {
856 BN_zero(rr);
857 return 1;
858 }
859 return BN_one(rr);
860 }
861
862 // Allocate a montgomery context if it was not supplied by the caller.
863 if (mont == NULL) {
864 new_mont = BN_MONT_CTX_new_consttime(m, ctx);
865 if (new_mont == NULL) {
866 goto err;
867 }
868 mont = new_mont;
869 }
870
871 // Use the width in |mont->N|, rather than the copy in |m|. The assembly
872 // implementation assumes it can use |top| to size R.
873 int top = mont->N.width;
874
875 #if defined(OPENSSL_BN_ASM_MONT5) || defined(RSAZ_ENABLED)
876 // Share one large stack-allocated buffer between the RSAZ and non-RSAZ code
877 // paths. If we were to use separate static buffers for each then there is
878 // some chance that both large buffers would be allocated on the stack,
879 // causing the stack space requirement to be truly huge (~10KB).
880 alignas(MOD_EXP_CTIME_ALIGN) BN_ULONG storage[MOD_EXP_CTIME_STORAGE_LEN];
881 #endif
882 #if defined(RSAZ_ENABLED)
883 // If the size of the operands allow it, perform the optimized RSAZ
884 // exponentiation. For further information see crypto/fipsmodule/bn/rsaz_exp.c
885 // and accompanying assembly modules.
886 if (a->width == 16 && p->width == 16 && BN_num_bits(m) == 1024 &&
887 rsaz_avx2_preferred()) {
888 if (!bn_wexpand(rr, 16)) {
889 goto err;
890 }
891 RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d, mont->n0[0],
892 storage);
893 rr->width = 16;
894 rr->neg = 0;
895 ret = 1;
896 goto err;
897 }
898 #endif
899
900 // Get the window size to use with size of p.
901 int window = BN_window_bits_for_ctime_exponent_size;
902
903 // Calculating |powerbuf_len| below cannot overflow because of the bound on
904 // Montgomery reduction.
905 assert((size_t)top <= BN_MONTGOMERY_MAX_WORDS);
906 OPENSSL_STATIC_ASSERT(
907 BN_MONTGOMERY_MAX_WORDS <=
908 INT_MAX / sizeof(BN_ULONG) / ((1 <<
909 BN_window_bits_for_ctime_exponent_size) + 3),
910 powerbuf_len_may_overflow);
911
912 #if defined(OPENSSL_BN_ASM_MONT5)
913 // Reserve space for the |mont->N| copy.
914 powerbuf_len += top * sizeof(mont->N.d[0]);
915 #endif
916
917 // Allocate a buffer large enough to hold all of the pre-computed
918 // powers of |am|, |am| itself, and |tmp|.
919 int num_powers = 1 << window;
920 powerbuf_len += sizeof(m->d[0]) * top * (num_powers + 2);
921
922 #if defined(OPENSSL_BN_ASM_MONT5)
923 if (powerbuf_len <= sizeof(storage)) {
924 powerbuf = storage;
925 }
926 // |storage| is more than large enough to handle 1024-bit inputs.
927 assert(powerbuf != NULL || top * BN_BITS2 > 1024);
928 #endif
929 if (powerbuf == NULL) {
930 powerbuf_free = OPENSSL_zalloc(powerbuf_len + MOD_EXP_CTIME_ALIGN);
931 if (powerbuf_free == NULL) {
932 goto err;
933 }
934 powerbuf = align_pointer(powerbuf_free, MOD_EXP_CTIME_ALIGN);
935 } else {
936 OPENSSL_memset(powerbuf, 0, powerbuf_len);
937 }
938
939 // Place |tmp| and |am| right after powers table.
940 BIGNUM tmp, am;
941 tmp.d = powerbuf + top * num_powers;
942 am.d = tmp.d + top;
943 tmp.width = am.width = 0;
944 tmp.dmax = am.dmax = top;
945 tmp.neg = am.neg = 0;
946 tmp.flags = am.flags = BN_FLG_STATIC_DATA;
947
948 if (!bn_one_to_montgomery(&tmp, mont, ctx) ||
949 !bn_resize_words(&tmp, top)) {
950 goto err;
951 }
952
953 // Prepare a^1 in the Montgomery domain.
954 assert(!a->neg);
955 declassify_assert(BN_ucmp(a, m) < 0);
956 if (!BN_to_montgomery(&am, a, mont, ctx) ||
957 !bn_resize_words(&am, top)) {
958 goto err;
959 }
960
961 #if defined(OPENSSL_BN_ASM_MONT5)
962 // This optimization uses ideas from https://eprint.iacr.org/2011/239,
963 // specifically optimization of cache-timing attack countermeasures,
964 // pre-computation optimization, and Almost Montgomery Multiplication.
965 //
966 // The paper discusses a 4-bit window to optimize 512-bit modular
967 // exponentiation, used in RSA-1024 with CRT, but RSA-1024 is no longer
968 // important.
969 //
970 // |bn_mul_mont_gather5| and |bn_power5| implement the "almost" reduction
971 // variant, so the values here may not be fully reduced. They are bounded by R
972 // (i.e. they fit in |top| words), not |m|. Additionally, we pass these
973 // "almost" reduced inputs into |bn_mul_mont|, which implements the normal
974 // reduction variant. Given those inputs, |bn_mul_mont| may not give reduced
975 // output, but it will still produce "almost" reduced output.
976 //
977 // TODO(davidben): Using "almost" reduction complicates analysis of this code,
978 // and its interaction with other parts of the project. Determine whether this
979 // is actually necessary for performance.
980 if (top > 1) {
981 assert(window == 5);
982 // Copy |mont->N| to improve cache locality.
983 BN_ULONG *np = am.d + top;
984 for (i = 0; i < top; i++) {
985 np[i] = mont->N.d[i];
986 }
987
988 // Fill |powerbuf| with the first 32 powers of |am|.
989 const BN_ULONG *n0 = mont->n0;
990 bn_scatter5(tmp.d, top, powerbuf, 0);
991 bn_scatter5(am.d, am.width, powerbuf, 1);
992 bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
993 bn_scatter5(tmp.d, top, powerbuf, 2);
994
995 // Square to compute powers of two.
996 for (i = 4; i < 32; i *= 2) {
997 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
998 bn_scatter5(tmp.d, top, powerbuf, i);
999 }
1000 // Compute odd powers |i| based on |i - 1|, then all powers |i * 2^j|.
1001 for (i = 3; i < 32; i += 2) {
1002 bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
1003 bn_scatter5(tmp.d, top, powerbuf, i);
1004 for (int j = 2 * i; j < 32; j *= 2) {
1005 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1006 bn_scatter5(tmp.d, top, powerbuf, j);
1007 }
1008 }
1009
1010 bits--;
1011 for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--) {
1012 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1013 }
1014 bn_gather5(tmp.d, top, powerbuf, wvalue);
1015
1016 // At this point |bits| is 4 mod 5 and at least -1. (|bits| is the first bit
1017 // that has not been read yet.)
1018 assert(bits >= -1 && (bits == -1 || bits % 5 == 4));
1019
1020 // Scan the exponent one window at a time starting from the most
1021 // significant bits.
1022 if (top & 7) {
1023 while (bits >= 0) {
1024 for (wvalue = 0, i = 0; i < 5; i++, bits--) {
1025 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1026 }
1027
1028 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1029 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1030 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1031 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1032 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1033 bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
1034 }
1035 } else {
1036 const uint8_t *p_bytes = (const uint8_t *)p->d;
1037 assert(bits < max_bits);
1038 // |p = 0| has been handled as a special case, so |max_bits| is at least
1039 // one word.
1040 assert(max_bits >= 64);
1041
1042 // If the first bit to be read lands in the last byte, unroll the first
1043 // iteration to avoid reading past the bounds of |p->d|. (After the first
1044 // iteration, we are guaranteed to be past the last byte.) Note |bits|
1045 // here is the top bit, inclusive.
1046 if (bits - 4 >= max_bits - 8) {
1047 // Read five bits from |bits-4| through |bits|, inclusive.
1048 wvalue = p_bytes[p->width * BN_BYTES - 1];
1049 wvalue >>= (bits - 4) & 7;
1050 wvalue &= 0x1f;
1051 bits -= 5;
1052 bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
1053 }
1054 while (bits >= 0) {
1055 // Read five bits from |bits-4| through |bits|, inclusive.
1056 int first_bit = bits - 4;
1057 uint16_t val;
1058 OPENSSL_memcpy(&val, p_bytes + (first_bit >> 3), sizeof(val));
1059 val >>= first_bit & 7;
1060 val &= 0x1f;
1061 bits -= 5;
1062 bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, val);
1063 }
1064 }
1065 // The result is now in |tmp| in Montgomery form, but it may not be fully
1066 // reduced. This is within bounds for |BN_from_montgomery| (tmp < R <= m*R)
1067 // so it will, when converting from Montgomery form, produce a fully reduced
1068 // result.
1069 //
1070 // This differs from Figure 2 of the paper, which uses AMM(h, 1) to convert
1071 // from Montgomery form with unreduced output, followed by an extra
1072 // reduction step. In the paper's terminology, we replace steps 9 and 10
1073 // with MM(h, 1).
1074 } else
1075 #endif
1076 {
1077 copy_to_prebuf(&tmp, top, powerbuf, 0, window);
1078 copy_to_prebuf(&am, top, powerbuf, 1, window);
1079
1080 // If the window size is greater than 1, then calculate
1081 // val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1)
1082 // (even powers could instead be computed as (a^(i/2))^2
1083 // to use the slight performance advantage of sqr over mul).
1084 if (window > 1) {
1085 if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx)) {
1086 goto err;
1087 }
1088
1089 copy_to_prebuf(&tmp, top, powerbuf, 2, window);
1090
1091 for (i = 3; i < num_powers; i++) {
1092 // Calculate a^i = a^(i-1) * a
1093 if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx)) {
1094 goto err;
1095 }
1096
1097 copy_to_prebuf(&tmp, top, powerbuf, i, window);
1098 }
1099 }
1100
1101 bits--;
1102 for (wvalue = 0, i = bits % window; i >= 0; i--, bits--) {
1103 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1104 }
1105 if (!copy_from_prebuf(&tmp, top, powerbuf, wvalue, window)) {
1106 goto err;
1107 }
1108
1109 // Scan the exponent one window at a time starting from the most
1110 // significant bits.
1111 while (bits >= 0) {
1112 wvalue = 0; // The 'value' of the window
1113
1114 // Scan the window, squaring the result as we go
1115 for (i = 0; i < window; i++, bits--) {
1116 if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx)) {
1117 goto err;
1118 }
1119 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1120 }
1121
1122 // Fetch the appropriate pre-computed value from the pre-buf
1123 if (!copy_from_prebuf(&am, top, powerbuf, wvalue, window)) {
1124 goto err;
1125 }
1126
1127 // Multiply the result into the intermediate result
1128 if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx)) {
1129 goto err;
1130 }
1131 }
1132 }
1133
1134 // Convert the final result from Montgomery to standard format. If we used the
1135 // |OPENSSL_BN_ASM_MONT5| codepath, |tmp| may not be fully reduced. It is only
1136 // bounded by R rather than |m|. However, that is still within bounds for
1137 // |BN_from_montgomery|, which implements full Montgomery reduction, not
1138 // "almost" Montgomery reduction.
1139 if (!BN_from_montgomery(rr, &tmp, mont, ctx)) {
1140 goto err;
1141 }
1142 ret = 1;
1143
1144 err:
1145 BN_MONT_CTX_free(new_mont);
1146 if (powerbuf != NULL && powerbuf_free == NULL) {
1147 OPENSSL_cleanse(powerbuf, powerbuf_len);
1148 }
1149 OPENSSL_free(powerbuf_free);
1150 return ret;
1151 }
1152
1153
1154 // This is a variant of modular exponentiation optimization that does
1155 // parallel 2-primes exponentiation using 256-bit (AVX512VL)
1156 // AVX512_IFMA ISA in 52-bit binary redundant representation. If such
1157 // instructions are not available, or input data size is not
1158 // supported, it falls back to two BN_mod_exp_mont_consttime() calls.
1159 //
1160 // Computes `rr = a^p mod m` using montgomery multiplication.
1161 //
1162 // rr[i] - Result
1163 // a[i] - Base
1164 // p[i] - Exponent
1165 // m[i] - Modulus
1166 // in_mont[i] - Montgomery multiplication context
1167 // ctx - Bignum context.
1168 //
1169 // The width of each base, exponent, and modulus must match and the
1170 // contexts are expected to be initialized.
1171 int BN_mod_exp_mont_consttime_x2(BIGNUM *rr1, const BIGNUM *a1, const BIGNUM *p1,
1172 const BIGNUM *m1, const BN_MONT_CTX *in_mont1,
1173 BIGNUM *rr2, const BIGNUM *a2, const BIGNUM *p2,
1174 const BIGNUM *m2, const BN_MONT_CTX *in_mont2,
1175 BN_CTX *ctx)
1176 {
1177 int ret = 0;
1178
1179 #ifdef RSAZ_512_ENABLED
1180 if (CRYPTO_is_AVX512IFMA_capable() &&
1181 (((a1->width == 16) && (p1->width == 16) && (BN_num_bits(m1) == 1024) &&
1182 (a2->width == 16) && (p2->width == 16) && (BN_num_bits(m2) == 1024)) ||
1183 ((a1->width == 24) && (p1->width == 24) && (BN_num_bits(m1) == 1536) &&
1184 (a2->width == 24) && (p2->width == 24) && (BN_num_bits(m2) == 1536)) ||
1185 ((a1->width == 32) && (p1->width == 32) && (BN_num_bits(m1) == 2048) &&
1186 (a2->width == 32) && (p2->width == 32) && (BN_num_bits(m2) == 2048)))) {
1187
1188 int widthn = a1->width;
1189
1190 if (!bn_wexpand(rr1, widthn)) {
1191 return ret;
1192 }
1193 if (!bn_wexpand(rr2, widthn)) {
1194 return ret;
1195 }
1196
1197 /* Ensure that montgomery contexts are initialized */
1198 if (in_mont1 == NULL) {
1199 return ret;
1200 }
1201
1202 if (in_mont2 == NULL) {
1203 return ret;
1204 }
1205
1206
1207 if (!BN_is_odd(m1) || !BN_is_odd(m2)) {
1208 OPENSSL_PUT_ERROR(BN, BN_R_CALLED_WITH_EVEN_MODULUS);
1209 return 0;
1210 }
1211 if (m1->neg || m2->neg) {
1212 OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
1213 return 0;
1214 }
1215 if ((a1->neg || BN_ucmp(a1, m1) >= 0) ||
1216 (a2->neg || BN_ucmp(a2, m2) >= 0)) {
1217 OPENSSL_PUT_ERROR(BN, BN_R_INPUT_NOT_REDUCED);
1218 return 0;
1219 }
1220
1221 int mod_bits = BN_num_bits(m1);
1222 ret = RSAZ_mod_exp_avx512_x2(rr1->d, a1->d, p1->d, m1->d,
1223 in_mont1->RR.d, in_mont1->n0[0],
1224 rr2->d, a2->d, p2->d, m2->d,
1225 in_mont2->RR.d, in_mont2->n0[0],
1226 mod_bits);
1227
1228 rr1->width = widthn;
1229 rr1->neg = 0;
1230
1231 rr2->width = widthn;
1232 rr2->neg = 0;
1233 } else {
1234 // rr1 = a1^p1 mod m1
1235 ret = BN_mod_exp_mont_consttime(rr1, a1, p1, m1, ctx, in_mont1);
1236 // rr2 = a2^p2 mod m2
1237 ret &= BN_mod_exp_mont_consttime(rr2, a2, p2, m2, ctx, in_mont2);
1238 }
1239
1240 #else
1241
1242 /* rr1 = a1^p1 mod m1 */
1243 ret = BN_mod_exp_mont_consttime(rr1, a1, p1, m1, ctx, in_mont1);
1244 /* rr2 = a2^p2 mod m2 */
1245 ret &= BN_mod_exp_mont_consttime(rr2, a2, p2, m2, ctx, in_mont2);
1246
1247 #endif
1248 return ret;
1249 }
1250
1251 int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
1252 const BIGNUM *m, BN_CTX *ctx,
1253 const BN_MONT_CTX *mont) {
1254 BIGNUM a_bignum;
1255 BN_init(&a_bignum);
1256
1257 int ret = 0;
1258
1259 // BN_mod_exp_mont requires reduced inputs.
1260 if (bn_minimal_width(m) == 1) {
1261 a %= m->d[0];
1262 }
1263
1264 if (!BN_set_word(&a_bignum, a)) {
1265 OPENSSL_PUT_ERROR(BN, ERR_R_INTERNAL_ERROR);
1266 goto err;
1267 }
1268
1269 ret = BN_mod_exp_mont(rr, &a_bignum, p, m, ctx, mont);
1270
1271 err:
1272 BN_free(&a_bignum);
1273
1274 return ret;
1275 }
1276
1277 #define TABLE_SIZE 32
1278
1279 int BN_mod_exp2_mont(BIGNUM *rr, const BIGNUM *a1, const BIGNUM *p1,
1280 const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m,
1281 BN_CTX *ctx, const BN_MONT_CTX *mont) {
1282 BIGNUM tmp;
1283 BN_init(&tmp);
1284
1285 int ret = 0;
1286 BN_MONT_CTX *new_mont = NULL;
1287
1288 // Allocate a montgomery context if it was not supplied by the caller.
1289 if (mont == NULL) {
1290 new_mont = BN_MONT_CTX_new_for_modulus(m, ctx);
1291 if (new_mont == NULL) {
1292 goto err;
1293 }
1294 mont = new_mont;
1295 }
1296
1297 // BN_mod_mul_montgomery removes one Montgomery factor, so passing one
1298 // Montgomery-encoded and one non-Montgomery-encoded value gives a
1299 // non-Montgomery-encoded result.
1300 if (!BN_mod_exp_mont(rr, a1, p1, m, ctx, mont) ||
1301 !BN_mod_exp_mont(&tmp, a2, p2, m, ctx, mont) ||
1302 !BN_to_montgomery(rr, rr, mont, ctx) ||
1303 !BN_mod_mul_montgomery(rr, rr, &tmp, mont, ctx)) {
1304 goto err;
1305 }
1306
1307 ret = 1;
1308
1309 err:
1310 BN_MONT_CTX_free(new_mont);
1311 BN_free(&tmp);
1312
1313 return ret;
1314 }