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