2 * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
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
10 #include "internal/cryptlib.h"
11 #include "internal/constant_time.h"
18 # define alloca _alloca
20 #elif defined(__GNUC__)
22 # define alloca(s) __builtin_alloca((s))
31 #if defined(OPENSSL_BN_ASM_MONT) && (defined(__sparc__) || defined(__sparc))
32 # include "crypto/sparc_arch.h"
33 # define SPARC_T4_MONT
36 /* maximum precomputation table size for *variable* sliding windows */
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.
46 #define BN_CONSTTIME_SIZE_LIMIT (INT_MAX / BN_BYTES / 256)
48 /* this one works - simple but works */
49 int BN_exp(BIGNUM
*r
, const BIGNUM
*a
, const BIGNUM
*p
, BN_CTX
*ctx
)
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
);
62 rr
= ((r
== a
) || (r
== p
)) ? BN_CTX_get(ctx
) : r
;
64 if (rr
== NULL
|| v
== NULL
)
67 if (BN_copy(v
, a
) == NULL
)
69 bits
= BN_num_bits(p
);
72 if (BN_copy(rr
, a
) == NULL
)
79 for (i
= 1; i
< bits
; i
++) {
80 if (!BN_sqr(v
, v
, ctx
))
82 if (BN_is_bit_set(p
, i
)) {
83 if (!BN_mul(rr
, rr
, v
, ctx
))
87 if (r
!= rr
&& BN_copy(r
, rr
) == NULL
)
97 int BN_mod_exp(BIGNUM
*r
, const BIGNUM
*a
, const BIGNUM
*p
, const BIGNUM
*m
,
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.
112 * For now, we use Montgomery only if the modulus is odd; otherwise,
113 * exponentiation using the reciprocal-based quick remaindering
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:
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.]
125 * BN_mod_exp_recp 50 .. 70 % [AMD K6-2, Linux, debug configuration]
126 * 62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc]
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!
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.)
138 #define MONT_EXP_WORD
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
);
152 ret
= BN_mod_exp_mont(r
, a
, p
, m
, ctx
, NULL
);
157 ret
= BN_mod_exp_recp(r
, a
, p
, m
, ctx
);
161 ret
= BN_mod_exp_simple(r
, a
, p
, m
, ctx
);
169 int BN_mod_exp_recp(BIGNUM
*r
, const BIGNUM
*a
, const BIGNUM
*p
,
170 const BIGNUM
*m
, BN_CTX
*ctx
)
172 int i
, j
, bits
, ret
= 0, wstart
, wend
, window
;
175 /* Table of variables obtained from 'ctx' */
176 BIGNUM
*val
[TABLE_SIZE
];
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
);
187 bits
= BN_num_bits(p
);
189 /* x**0 mod 1, or x**0 mod -1 is still zero. */
190 if (BN_abs_is_word(m
, 1)) {
199 BN_RECP_CTX_init(&recp
);
202 aa
= BN_CTX_get(ctx
);
203 val
[0] = BN_CTX_get(ctx
);
208 /* ignore sign of 'm' */
212 if (BN_RECP_CTX_set(&recp
, aa
, ctx
) <= 0)
215 if (BN_RECP_CTX_set(&recp
, m
, ctx
) <= 0)
219 if (!BN_nnmod(val
[0], a
, m
, ctx
))
221 if (BN_is_zero(val
[0])) {
227 window
= BN_window_bits_for_exponent_size(bits
);
229 if (!BN_mod_mul_reciprocal(aa
, val
[0], val
[0], &recp
, ctx
))
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
))
239 start
= 1; /* This is used to avoid multiplication etc
240 * when there is only the value '1' in the
242 wstart
= bits
- 1; /* The top bit of the window */
243 wend
= 0; /* The bottom bit of the window */
249 int wvalue
; /* The 'value' of the window */
251 if (BN_is_bit_set(p
, wstart
) == 0) {
253 if (!BN_mod_mul_reciprocal(r
, r
, r
, &recp
, ctx
))
261 * We now have wstart on a 'set' bit, we now need to work out how bit
262 * a window to do. To do this we need to scan forward until the last
263 * set bit before the end of the window
267 for (i
= 1; i
< window
; i
++) {
270 if (BN_is_bit_set(p
, wstart
- i
)) {
271 wvalue
<<= (i
- wend
);
277 /* wend is the size of the current window */
279 /* add the 'bytes above' */
281 for (i
= 0; i
< j
; i
++) {
282 if (!BN_mod_mul_reciprocal(r
, r
, r
, &recp
, ctx
))
286 /* wvalue will be an odd number < 2^window */
287 if (!BN_mod_mul_reciprocal(r
, r
, val
[wvalue
>> 1], &recp
, ctx
))
290 /* move the 'window' down further */
299 BN_RECP_CTX_free(&recp
);
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
)
307 int i
, j
, bits
, ret
= 0, wstart
, wend
, window
;
311 /* Table of variables obtained from 'ctx' */
312 BIGNUM
*val
[TABLE_SIZE
];
313 BN_MONT_CTX
*mont
= NULL
;
320 ERR_raise(ERR_LIB_BN
, BN_R_CALLED_WITH_EVEN_MODULUS
);
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
);
331 bits
= BN_num_bits(p
);
333 /* x**0 mod 1, or x**0 mod -1 is still zero. */
334 if (BN_abs_is_word(m
, 1)) {
346 val
[0] = BN_CTX_get(ctx
);
351 * If this is not done, things will break in the montgomery part
357 if ((mont
= BN_MONT_CTX_new()) == NULL
)
359 if (!BN_MONT_CTX_set(mont
, m
, ctx
))
363 if (a
->neg
|| BN_ucmp(a
, m
) >= 0) {
364 if (!BN_nnmod(val
[0], a
, m
, ctx
))
369 if (!bn_to_mont_fixed_top(val
[0], aa
, mont
, ctx
))
372 window
= BN_window_bits_for_exponent_size(bits
);
374 if (!bn_mul_mont_fixed_top(d
, val
[0], val
[0], mont
, ctx
))
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
))
384 start
= 1; /* This is used to avoid multiplication etc
385 * when there is only the value '1' in the
387 wstart
= bits
- 1; /* The top bit of the window */
388 wend
= 0; /* The bottom bit of the window */
390 #if 1 /* by Shay Gueron's suggestion */
391 j
= m
->top
; /* borrow j */
392 if (m
->d
[j
- 1] & (((BN_ULONG
)1) << (BN_BITS2
- 1))) {
393 if (bn_wexpand(r
, j
) == NULL
)
395 /* 2^(top*BN_BITS2) - m */
396 r
->d
[0] = (0 - m
->d
[0]) & BN_MASK2
;
397 for (i
= 1; i
< j
; i
++)
398 r
->d
[i
] = (~m
->d
[i
]) & BN_MASK2
;
400 r
->flags
|= BN_FLG_FIXED_TOP
;
403 if (!bn_to_mont_fixed_top(r
, BN_value_one(), mont
, ctx
))
406 int wvalue
; /* The 'value' of the window */
408 if (BN_is_bit_set(p
, wstart
) == 0) {
410 if (!bn_mul_mont_fixed_top(r
, r
, r
, mont
, ctx
))
419 * We now have wstart on a 'set' bit, we now need to work out how bit
420 * a window to do. To do this we need to scan forward until the last
421 * set bit before the end of the window
425 for (i
= 1; i
< window
; i
++) {
428 if (BN_is_bit_set(p
, wstart
- i
)) {
429 wvalue
<<= (i
- wend
);
435 /* wend is the size of the current window */
437 /* add the 'bytes above' */
439 for (i
= 0; i
< j
; i
++) {
440 if (!bn_mul_mont_fixed_top(r
, r
, r
, mont
, ctx
))
444 /* wvalue will be an odd number < 2^window */
445 if (!bn_mul_mont_fixed_top(r
, r
, val
[wvalue
>> 1], mont
, ctx
))
448 /* move the 'window' down further */
455 * Done with zero-padded intermediate BIGNUMs. Final BN_from_montgomery
456 * removes padding [if any] and makes return value suitable for public
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
++)
466 if (!BN_mod_mul_montgomery(rr
, r
, val
[0], mont
, ctx
))
470 if (!BN_from_montgomery(rr
, r
, mont
, ctx
))
475 BN_MONT_CTX_free(mont
);
481 static BN_ULONG
bn_get_bits(const BIGNUM
*a
, int bitpos
)
486 wordpos
= bitpos
/ BN_BITS2
;
488 if (wordpos
>= 0 && wordpos
< a
->top
) {
489 ret
= a
->d
[wordpos
] & BN_MASK2
;
492 if (++wordpos
< a
->top
)
493 ret
|= a
->d
[wordpos
] << (BN_BITS2
- bitpos
);
497 return ret
& BN_MASK2
;
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.
507 static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM
*b
, int top
,
508 unsigned char *buf
, int idx
,
512 int width
= 1 << window
;
513 BN_ULONG
*table
= (BN_ULONG
*)buf
;
516 top
= b
->top
; /* this works because 'buf' is explicitly
518 for (i
= 0, j
= idx
; i
< top
; i
++, j
+= width
) {
525 static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM
*b
, int top
,
526 unsigned char *buf
, int idx
,
530 int width
= 1 << window
;
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...
539 volatile BN_ULONG
*table
= (volatile BN_ULONG
*)buf
;
541 if (bn_wexpand(b
, top
) == NULL
)
545 for (i
= 0; i
< top
; i
++, table
+= width
) {
548 for (j
= 0; j
< width
; j
++) {
550 ((BN_ULONG
)0 - (constant_time_eq_int(j
,idx
)&1));
556 int xstride
= 1 << (window
- 2);
557 BN_ULONG y0
, y1
, y2
, y3
;
559 i
= idx
>> (window
- 2); /* equivalent of idx / xstride */
560 idx
&= xstride
- 1; /* equivalent of idx % xstride */
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);
567 for (i
= 0; i
< top
; i
++, table
+= width
) {
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));
583 b
->flags
|= BN_FLG_FIXED_TOP
;
588 * Given a pointer value, compute the next address that is a cache line
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))))
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/)
601 int BN_mod_exp_mont_consttime(BIGNUM
*rr
, const BIGNUM
*a
, const BIGNUM
*p
,
602 const BIGNUM
*m
, BN_CTX
*ctx
,
603 BN_MONT_CTX
*in_mont
)
605 int i
, bits
, ret
= 0, window
, wvalue
, wmask
, window0
;
607 BN_MONT_CTX
*mont
= NULL
;
610 unsigned char *powerbufFree
= NULL
;
612 unsigned char *powerbuf
= NULL
;
614 #if defined(SPARC_T4_MONT)
623 ERR_raise(ERR_LIB_BN
, BN_R_CALLED_WITH_EVEN_MODULUS
);
629 if (top
> BN_CONSTTIME_SIZE_LIMIT
) {
630 /* Prevent overflowing the powerbufLen computation below */
631 return BN_mod_exp_mont(rr
, a
, p
, m
, ctx
, in_mont
);
635 * Use all bits stored in |p|, rather than |BN_num_bits|, so we do not leak
636 * whether the top bits are zero.
638 bits
= p
->top
* BN_BITS2
;
640 /* x**0 mod 1, or x**0 mod -1 is still zero. */
641 if (BN_abs_is_word(m
, 1)) {
653 * Allocate a montgomery context if it was not supplied by the caller. If
654 * this is not done, things will break in the montgomery part.
659 if ((mont
= BN_MONT_CTX_new()) == NULL
)
661 if (!BN_MONT_CTX_set(mont
, m
, ctx
))
665 if (a
->neg
|| BN_ucmp(a
, m
) >= 0) {
666 BIGNUM
*reduced
= BN_CTX_get(ctx
);
668 || !BN_nnmod(reduced
, a
, m
, ctx
)) {
676 * If the size of the operands allow it, perform the optimized
677 * RSAZ exponentiation. For further information see
678 * crypto/bn/rsaz_exp.c and accompanying assembly modules.
680 if ((16 == a
->top
) && (16 == p
->top
) && (BN_num_bits(m
) == 1024)
681 && rsaz_avx2_eligible()) {
682 if (NULL
== bn_wexpand(rr
, 16))
684 RSAZ_1024_mod_exp_avx2(rr
->d
, a
->d
, p
->d
, m
->d
, mont
->RR
.d
,
691 } else if ((8 == a
->top
) && (8 == p
->top
) && (BN_num_bits(m
) == 512)) {
692 if (NULL
== bn_wexpand(rr
, 8))
694 RSAZ_512_mod_exp(rr
->d
, a
->d
, p
->d
, m
->d
, mont
->n0
[0], mont
->RR
.d
);
703 /* Get the window size to use with size of p. */
704 window
= BN_window_bits_for_ctime_exponent_size(bits
);
705 #if defined(SPARC_T4_MONT)
706 if (window
>= 5 && (top
& 15) == 0 && top
<= 64 &&
707 (OPENSSL_sparcv9cap_P
[1] & (CFR_MONTMUL
| CFR_MONTSQR
)) ==
708 (CFR_MONTMUL
| CFR_MONTSQR
) && (t4
= OPENSSL_sparcv9cap_P
[0]))
712 #if defined(OPENSSL_BN_ASM_MONT5)
713 if (window
>= 5 && top
<= BN_SOFT_LIMIT
) {
714 window
= 5; /* ~5% improvement for RSA2048 sign, and even
716 /* reserve space for mont->N.d[] copy */
717 powerbufLen
+= top
* sizeof(mont
->N
.d
[0]);
723 * Allocate a buffer large enough to hold all of the pre-computed powers
724 * of am, am itself and tmp.
726 numPowers
= 1 << window
;
727 powerbufLen
+= sizeof(m
->d
[0]) * (top
* numPowers
+
729 numPowers
? (2 * top
) : numPowers
));
731 if (powerbufLen
< 3072)
733 alloca(powerbufLen
+ MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH
);
737 OPENSSL_malloc(powerbufLen
+ MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH
))
741 powerbuf
= MOD_EXP_CTIME_ALIGN(powerbufFree
);
742 memset(powerbuf
, 0, powerbufLen
);
745 if (powerbufLen
< 3072)
749 /* lay down tmp and am right after powers table */
750 tmp
.d
= (BN_ULONG
*)(powerbuf
+ sizeof(m
->d
[0]) * top
* numPowers
);
752 tmp
.top
= am
.top
= 0;
753 tmp
.dmax
= am
.dmax
= top
;
754 tmp
.neg
= am
.neg
= 0;
755 tmp
.flags
= am
.flags
= BN_FLG_STATIC_DATA
;
757 /* prepare a^0 in Montgomery domain */
758 #if 1 /* by Shay Gueron's suggestion */
759 if (m
->d
[top
- 1] & (((BN_ULONG
)1) << (BN_BITS2
- 1))) {
760 /* 2^(top*BN_BITS2) - m */
761 tmp
.d
[0] = (0 - m
->d
[0]) & BN_MASK2
;
762 for (i
= 1; i
< top
; i
++)
763 tmp
.d
[i
] = (~m
->d
[i
]) & BN_MASK2
;
767 if (!bn_to_mont_fixed_top(&tmp
, BN_value_one(), mont
, ctx
))
770 /* prepare a^1 in Montgomery domain */
771 if (!bn_to_mont_fixed_top(&am
, a
, mont
, ctx
))
774 if (top
> BN_SOFT_LIMIT
)
777 #if defined(SPARC_T4_MONT)
779 typedef int (*bn_pwr5_mont_f
) (BN_ULONG
*tp
, const BN_ULONG
*np
,
780 const BN_ULONG
*n0
, const void *table
,
781 int power
, int bits
);
782 int bn_pwr5_mont_t4_8(BN_ULONG
*tp
, const BN_ULONG
*np
,
783 const BN_ULONG
*n0
, const void *table
,
784 int power
, int bits
);
785 int bn_pwr5_mont_t4_16(BN_ULONG
*tp
, const BN_ULONG
*np
,
786 const BN_ULONG
*n0
, const void *table
,
787 int power
, int bits
);
788 int bn_pwr5_mont_t4_24(BN_ULONG
*tp
, const BN_ULONG
*np
,
789 const BN_ULONG
*n0
, const void *table
,
790 int power
, int bits
);
791 int bn_pwr5_mont_t4_32(BN_ULONG
*tp
, const BN_ULONG
*np
,
792 const BN_ULONG
*n0
, const void *table
,
793 int power
, int bits
);
794 static const bn_pwr5_mont_f pwr5_funcs
[4] = {
795 bn_pwr5_mont_t4_8
, bn_pwr5_mont_t4_16
,
796 bn_pwr5_mont_t4_24
, bn_pwr5_mont_t4_32
798 bn_pwr5_mont_f pwr5_worker
= pwr5_funcs
[top
/ 16 - 1];
800 typedef int (*bn_mul_mont_f
) (BN_ULONG
*rp
, const BN_ULONG
*ap
,
801 const void *bp
, const BN_ULONG
*np
,
803 int bn_mul_mont_t4_8(BN_ULONG
*rp
, const BN_ULONG
*ap
, const void *bp
,
804 const BN_ULONG
*np
, const BN_ULONG
*n0
);
805 int bn_mul_mont_t4_16(BN_ULONG
*rp
, const BN_ULONG
*ap
,
806 const void *bp
, const BN_ULONG
*np
,
808 int bn_mul_mont_t4_24(BN_ULONG
*rp
, const BN_ULONG
*ap
,
809 const void *bp
, const BN_ULONG
*np
,
811 int bn_mul_mont_t4_32(BN_ULONG
*rp
, const BN_ULONG
*ap
,
812 const void *bp
, const BN_ULONG
*np
,
814 static const bn_mul_mont_f mul_funcs
[4] = {
815 bn_mul_mont_t4_8
, bn_mul_mont_t4_16
,
816 bn_mul_mont_t4_24
, bn_mul_mont_t4_32
818 bn_mul_mont_f mul_worker
= mul_funcs
[top
/ 16 - 1];
820 void bn_mul_mont_vis3(BN_ULONG
*rp
, const BN_ULONG
*ap
,
821 const void *bp
, const BN_ULONG
*np
,
822 const BN_ULONG
*n0
, int num
);
823 void bn_mul_mont_t4(BN_ULONG
*rp
, const BN_ULONG
*ap
,
824 const void *bp
, const BN_ULONG
*np
,
825 const BN_ULONG
*n0
, int num
);
826 void bn_mul_mont_gather5_t4(BN_ULONG
*rp
, const BN_ULONG
*ap
,
827 const void *table
, const BN_ULONG
*np
,
828 const BN_ULONG
*n0
, int num
, int power
);
829 void bn_flip_n_scatter5_t4(const BN_ULONG
*inp
, size_t num
,
830 void *table
, size_t power
);
831 void bn_gather5_t4(BN_ULONG
*out
, size_t num
,
832 void *table
, size_t power
);
833 void bn_flip_t4(BN_ULONG
*dst
, BN_ULONG
*src
, size_t num
);
835 BN_ULONG
*np
= mont
->N
.d
, *n0
= mont
->n0
;
836 int stride
= 5 * (6 - (top
/ 16 - 1)); /* multiple of 5, but less
840 * BN_to_montgomery can contaminate words above .top [in
843 for (i
= am
.top
; i
< top
; i
++)
845 for (i
= tmp
.top
; i
< top
; i
++)
848 bn_flip_n_scatter5_t4(tmp
.d
, top
, powerbuf
, 0);
849 bn_flip_n_scatter5_t4(am
.d
, top
, powerbuf
, 1);
850 if (!(*mul_worker
) (tmp
.d
, am
.d
, am
.d
, np
, n0
) &&
851 !(*mul_worker
) (tmp
.d
, am
.d
, am
.d
, np
, n0
))
852 bn_mul_mont_vis3(tmp
.d
, am
.d
, am
.d
, np
, n0
, top
);
853 bn_flip_n_scatter5_t4(tmp
.d
, top
, powerbuf
, 2);
855 for (i
= 3; i
< 32; i
++) {
856 /* Calculate a^i = a^(i-1) * a */
857 if (!(*mul_worker
) (tmp
.d
, tmp
.d
, am
.d
, np
, n0
) &&
858 !(*mul_worker
) (tmp
.d
, tmp
.d
, am
.d
, np
, n0
))
859 bn_mul_mont_vis3(tmp
.d
, tmp
.d
, am
.d
, np
, n0
, top
);
860 bn_flip_n_scatter5_t4(tmp
.d
, top
, powerbuf
, i
);
863 /* switch to 64-bit domain */
864 np
= alloca(top
* sizeof(BN_ULONG
));
866 bn_flip_t4(np
, mont
->N
.d
, top
);
869 * The exponent may not have a whole number of fixed-size windows.
870 * To simplify the main loop, the initial window has between 1 and
871 * full-window-size bits such that what remains is always a whole
874 window0
= (bits
- 1) % 5 + 1;
875 wmask
= (1 << window0
) - 1;
877 wvalue
= bn_get_bits(p
, bits
) & wmask
;
878 bn_gather5_t4(tmp
.d
, top
, powerbuf
, wvalue
);
881 * Scan the exponent one window at a time starting from the most
888 wvalue
= bn_get_bits(p
, bits
);
890 if ((*pwr5_worker
) (tmp
.d
, np
, n0
, powerbuf
, wvalue
, stride
))
892 /* retry once and fall back */
893 if ((*pwr5_worker
) (tmp
.d
, np
, n0
, powerbuf
, wvalue
, stride
))
897 wvalue
>>= stride
- 5;
899 bn_mul_mont_t4(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
900 bn_mul_mont_t4(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
901 bn_mul_mont_t4(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
902 bn_mul_mont_t4(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
903 bn_mul_mont_t4(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
904 bn_mul_mont_gather5_t4(tmp
.d
, tmp
.d
, powerbuf
, np
, n0
, top
,
908 bn_flip_t4(tmp
.d
, tmp
.d
, top
);
910 /* back to 32-bit domain */
912 bn_correct_top(&tmp
);
913 OPENSSL_cleanse(np
, top
* sizeof(BN_ULONG
));
916 #if defined(OPENSSL_BN_ASM_MONT5)
917 if (window
== 5 && top
> 1) {
919 * This optimization uses ideas from https://eprint.iacr.org/2011/239,
920 * specifically optimization of cache-timing attack countermeasures,
921 * pre-computation optimization, and Almost Montgomery Multiplication.
923 * The paper discusses a 4-bit window to optimize 512-bit modular
924 * exponentiation, used in RSA-1024 with CRT, but RSA-1024 is no longer
927 * |bn_mul_mont_gather5| and |bn_power5| implement the "almost"
928 * reduction variant, so the values here may not be fully reduced.
929 * They are bounded by R (i.e. they fit in |top| words), not |m|.
930 * Additionally, we pass these "almost" reduced inputs into
931 * |bn_mul_mont|, which implements the normal reduction variant.
932 * Given those inputs, |bn_mul_mont| may not give reduced
933 * output, but it will still produce "almost" reduced output.
935 void bn_mul_mont_gather5(BN_ULONG
*rp
, const BN_ULONG
*ap
,
936 const void *table
, const BN_ULONG
*np
,
937 const BN_ULONG
*n0
, int num
, int power
);
938 void bn_scatter5(const BN_ULONG
*inp
, size_t num
,
939 void *table
, size_t power
);
940 void bn_gather5(BN_ULONG
*out
, size_t num
, void *table
, size_t power
);
941 void bn_power5(BN_ULONG
*rp
, const BN_ULONG
*ap
,
942 const void *table
, const BN_ULONG
*np
,
943 const BN_ULONG
*n0
, int num
, int power
);
944 int bn_get_bits5(const BN_ULONG
*ap
, int off
);
946 BN_ULONG
*n0
= mont
->n0
, *np
;
949 * BN_to_montgomery can contaminate words above .top [in
952 for (i
= am
.top
; i
< top
; i
++)
954 for (i
= tmp
.top
; i
< top
; i
++)
958 * copy mont->N.d[] to improve cache locality
960 for (np
= am
.d
+ top
, i
= 0; i
< top
; i
++)
961 np
[i
] = mont
->N
.d
[i
];
963 bn_scatter5(tmp
.d
, top
, powerbuf
, 0);
964 bn_scatter5(am
.d
, am
.top
, powerbuf
, 1);
965 bn_mul_mont(tmp
.d
, am
.d
, am
.d
, np
, n0
, top
);
966 bn_scatter5(tmp
.d
, top
, powerbuf
, 2);
969 for (i
= 3; i
< 32; i
++) {
970 /* Calculate a^i = a^(i-1) * a */
971 bn_mul_mont_gather5(tmp
.d
, am
.d
, powerbuf
, np
, n0
, top
, i
- 1);
972 bn_scatter5(tmp
.d
, top
, powerbuf
, i
);
975 /* same as above, but uses squaring for 1/2 of operations */
976 for (i
= 4; i
< 32; i
*= 2) {
977 bn_mul_mont(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
978 bn_scatter5(tmp
.d
, top
, powerbuf
, i
);
980 for (i
= 3; i
< 8; i
+= 2) {
982 bn_mul_mont_gather5(tmp
.d
, am
.d
, powerbuf
, np
, n0
, top
, i
- 1);
983 bn_scatter5(tmp
.d
, top
, powerbuf
, i
);
984 for (j
= 2 * i
; j
< 32; j
*= 2) {
985 bn_mul_mont(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
986 bn_scatter5(tmp
.d
, top
, powerbuf
, j
);
989 for (; i
< 16; i
+= 2) {
990 bn_mul_mont_gather5(tmp
.d
, am
.d
, powerbuf
, np
, n0
, top
, i
- 1);
991 bn_scatter5(tmp
.d
, top
, powerbuf
, i
);
992 bn_mul_mont(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
993 bn_scatter5(tmp
.d
, top
, powerbuf
, 2 * i
);
995 for (; i
< 32; i
+= 2) {
996 bn_mul_mont_gather5(tmp
.d
, am
.d
, powerbuf
, np
, n0
, top
, i
- 1);
997 bn_scatter5(tmp
.d
, top
, powerbuf
, i
);
1001 * The exponent may not have a whole number of fixed-size windows.
1002 * To simplify the main loop, the initial window has between 1 and
1003 * full-window-size bits such that what remains is always a whole
1006 window0
= (bits
- 1) % 5 + 1;
1007 wmask
= (1 << window0
) - 1;
1009 wvalue
= bn_get_bits(p
, bits
) & wmask
;
1010 bn_gather5(tmp
.d
, top
, powerbuf
, wvalue
);
1013 * Scan the exponent one window at a time starting from the most
1018 bn_mul_mont(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
1019 bn_mul_mont(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
1020 bn_mul_mont(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
1021 bn_mul_mont(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
1022 bn_mul_mont(tmp
.d
, tmp
.d
, tmp
.d
, np
, n0
, top
);
1023 bn_mul_mont_gather5(tmp
.d
, tmp
.d
, powerbuf
, np
, n0
, top
,
1024 bn_get_bits5(p
->d
, bits
-= 5));
1028 bn_power5(tmp
.d
, tmp
.d
, powerbuf
, np
, n0
, top
,
1029 bn_get_bits5(p
->d
, bits
-= 5));
1035 * The result is now in |tmp| in Montgomery form, but it may not be
1036 * fully reduced. This is within bounds for |BN_from_montgomery|
1037 * (tmp < R <= m*R) so it will, when converting from Montgomery form,
1038 * produce a fully reduced result.
1040 * This differs from Figure 2 of the paper, which uses AMM(h, 1) to
1041 * convert from Montgomery form with unreduced output, followed by an
1042 * extra reduction step. In the paper's terminology, we replace
1043 * steps 9 and 10 with MM(h, 1).
1049 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp
, top
, powerbuf
, 0, window
))
1051 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am
, top
, powerbuf
, 1, window
))
1055 * If the window size is greater than 1, then calculate
1056 * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
1057 * powers could instead be computed as (a^(i/2))^2 to use the slight
1058 * performance advantage of sqr over mul).
1061 if (!bn_mul_mont_fixed_top(&tmp
, &am
, &am
, mont
, ctx
))
1063 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp
, top
, powerbuf
, 2,
1066 for (i
= 3; i
< numPowers
; i
++) {
1067 /* Calculate a^i = a^(i-1) * a */
1068 if (!bn_mul_mont_fixed_top(&tmp
, &am
, &tmp
, mont
, ctx
))
1070 if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp
, top
, powerbuf
, i
,
1077 * The exponent may not have a whole number of fixed-size windows.
1078 * To simplify the main loop, the initial window has between 1 and
1079 * full-window-size bits such that what remains is always a whole
1082 window0
= (bits
- 1) % window
+ 1;
1083 wmask
= (1 << window0
) - 1;
1085 wvalue
= bn_get_bits(p
, bits
) & wmask
;
1086 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp
, top
, powerbuf
, wvalue
,
1090 wmask
= (1 << window
) - 1;
1092 * Scan the exponent one window at a time starting from the most
1097 /* Square the result window-size times */
1098 for (i
= 0; i
< window
; i
++)
1099 if (!bn_mul_mont_fixed_top(&tmp
, &tmp
, &tmp
, mont
, ctx
))
1103 * Get a window's worth of bits from the exponent
1104 * This avoids calling BN_is_bit_set for each bit, which
1105 * is not only slower but also makes each bit vulnerable to
1106 * EM (and likely other) side-channel attacks like One&Done
1107 * (for details see "One&Done: A Single-Decryption EM-Based
1108 * Attack on OpenSSL's Constant-Time Blinded RSA" by M. Alam,
1109 * H. Khan, M. Dey, N. Sinha, R. Callan, A. Zajic, and
1110 * M. Prvulovic, in USENIX Security'18)
1113 wvalue
= bn_get_bits(p
, bits
) & wmask
;
1115 * Fetch the appropriate pre-computed value from the pre-buf
1117 if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am
, top
, powerbuf
, wvalue
,
1121 /* Multiply the result into the intermediate result */
1122 if (!bn_mul_mont_fixed_top(&tmp
, &tmp
, &am
, mont
, ctx
))
1128 * Done with zero-padded intermediate BIGNUMs. Final BN_from_montgomery
1129 * removes padding [if any] and makes return value suitable for public
1132 #if defined(SPARC_T4_MONT)
1133 if (OPENSSL_sparcv9cap_P
[0] & (SPARCV9_VIS3
| SPARCV9_PREFER_FPU
)) {
1134 am
.d
[0] = 1; /* borrow am */
1135 for (i
= 1; i
< top
; i
++)
1137 if (!BN_mod_mul_montgomery(rr
, &tmp
, &am
, mont
, ctx
))
1141 if (!BN_from_montgomery(rr
, &tmp
, mont
, ctx
))
1145 if (in_mont
== NULL
)
1146 BN_MONT_CTX_free(mont
);
1147 if (powerbuf
!= NULL
) {
1148 OPENSSL_cleanse(powerbuf
, powerbufLen
);
1149 OPENSSL_free(powerbufFree
);
1155 int BN_mod_exp_mont_word(BIGNUM
*rr
, BN_ULONG a
, const BIGNUM
*p
,
1156 const BIGNUM
*m
, BN_CTX
*ctx
, BN_MONT_CTX
*in_mont
)
1158 BN_MONT_CTX
*mont
= NULL
;
1159 int b
, bits
, ret
= 0;
1164 #define BN_MOD_MUL_WORD(r, w, m) \
1165 (BN_mul_word(r, (w)) && \
1166 (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
1167 (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
1169 * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
1170 * probably more overhead than always using BN_mod (which uses BN_copy if
1171 * a similar test returns true).
1174 * We can use BN_mod and do not need BN_nnmod because our accumulator is
1175 * never negative (the result of BN_mod does not depend on the sign of
1178 #define BN_TO_MONTGOMERY_WORD(r, w, mont) \
1179 (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
1181 if (BN_get_flags(p
, BN_FLG_CONSTTIME
) != 0
1182 || BN_get_flags(m
, BN_FLG_CONSTTIME
) != 0) {
1183 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1184 ERR_raise(ERR_LIB_BN
, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED
);
1191 if (!BN_is_odd(m
)) {
1192 ERR_raise(ERR_LIB_BN
, BN_R_CALLED_WITH_EVEN_MODULUS
);
1196 a
%= m
->d
[0]; /* make sure that 'a' is reduced */
1198 bits
= BN_num_bits(p
);
1200 /* x**0 mod 1, or x**0 mod -1 is still zero. */
1201 if (BN_abs_is_word(m
, 1)) {
1216 r
= BN_CTX_get(ctx
);
1217 t
= BN_CTX_get(ctx
);
1221 if (in_mont
!= NULL
)
1224 if ((mont
= BN_MONT_CTX_new()) == NULL
)
1226 if (!BN_MONT_CTX_set(mont
, m
, ctx
))
1230 r_is_one
= 1; /* except for Montgomery factor */
1234 /* The result is accumulated in the product r*w. */
1235 w
= a
; /* bit 'bits-1' of 'p' is always set */
1236 for (b
= bits
- 2; b
>= 0; b
--) {
1237 /* First, square r*w. */
1239 if ((next_w
/ w
) != w
) { /* overflow */
1241 if (!BN_TO_MONTGOMERY_WORD(r
, w
, mont
))
1245 if (!BN_MOD_MUL_WORD(r
, w
, m
))
1252 if (!BN_mod_mul_montgomery(r
, r
, r
, mont
, ctx
))
1256 /* Second, multiply r*w by 'a' if exponent bit is set. */
1257 if (BN_is_bit_set(p
, b
)) {
1259 if ((next_w
/ a
) != w
) { /* overflow */
1261 if (!BN_TO_MONTGOMERY_WORD(r
, w
, mont
))
1265 if (!BN_MOD_MUL_WORD(r
, w
, m
))
1274 /* Finally, set r:=r*w. */
1277 if (!BN_TO_MONTGOMERY_WORD(r
, w
, mont
))
1281 if (!BN_MOD_MUL_WORD(r
, w
, m
))
1286 if (r_is_one
) { /* can happen only if a == 1 */
1290 if (!BN_from_montgomery(rr
, r
, mont
, ctx
))
1295 if (in_mont
== NULL
)
1296 BN_MONT_CTX_free(mont
);
1302 /* The old fallback, simple version :-) */
1303 int BN_mod_exp_simple(BIGNUM
*r
, const BIGNUM
*a
, const BIGNUM
*p
,
1304 const BIGNUM
*m
, BN_CTX
*ctx
)
1306 int i
, j
, bits
, ret
= 0, wstart
, wend
, window
;
1309 /* Table of variables obtained from 'ctx' */
1310 BIGNUM
*val
[TABLE_SIZE
];
1312 if (BN_get_flags(p
, BN_FLG_CONSTTIME
) != 0
1313 || BN_get_flags(a
, BN_FLG_CONSTTIME
) != 0
1314 || BN_get_flags(m
, BN_FLG_CONSTTIME
) != 0) {
1315 /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1316 ERR_raise(ERR_LIB_BN
, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED
);
1320 bits
= BN_num_bits(p
);
1322 /* x**0 mod 1, or x**0 mod -1 is still zero. */
1323 if (BN_abs_is_word(m
, 1)) {
1333 d
= BN_CTX_get(ctx
);
1334 val
[0] = BN_CTX_get(ctx
);
1338 if (!BN_nnmod(val
[0], a
, m
, ctx
))
1340 if (BN_is_zero(val
[0])) {
1346 window
= BN_window_bits_for_exponent_size(bits
);
1348 if (!BN_mod_mul(d
, val
[0], val
[0], m
, ctx
))
1350 j
= 1 << (window
- 1);
1351 for (i
= 1; i
< j
; i
++) {
1352 if (((val
[i
] = BN_CTX_get(ctx
)) == NULL
) ||
1353 !BN_mod_mul(val
[i
], val
[i
- 1], d
, m
, ctx
))
1358 start
= 1; /* This is used to avoid multiplication etc
1359 * when there is only the value '1' in the
1361 wstart
= bits
- 1; /* The top bit of the window */
1362 wend
= 0; /* The bottom bit of the window */
1368 int wvalue
; /* The 'value' of the window */
1370 if (BN_is_bit_set(p
, wstart
) == 0) {
1372 if (!BN_mod_mul(r
, r
, r
, m
, ctx
))
1380 * We now have wstart on a 'set' bit, we now need to work out how bit
1381 * a window to do. To do this we need to scan forward until the last
1382 * set bit before the end of the window
1386 for (i
= 1; i
< window
; i
++) {
1389 if (BN_is_bit_set(p
, wstart
- i
)) {
1390 wvalue
<<= (i
- wend
);
1396 /* wend is the size of the current window */
1398 /* add the 'bytes above' */
1400 for (i
= 0; i
< j
; i
++) {
1401 if (!BN_mod_mul(r
, r
, r
, m
, ctx
))
1405 /* wvalue will be an odd number < 2^window */
1406 if (!BN_mod_mul(r
, r
, val
[wvalue
>> 1], m
, ctx
))
1409 /* move the 'window' down further */
1423 * This is a variant of modular exponentiation optimization that does
1424 * parallel 2-primes exponentiation using 256-bit (AVX512VL) AVX512_IFMA ISA
1425 * in 52-bit binary redundant representation.
1426 * If such instructions are not available, or input data size is not supported,
1427 * it falls back to two BN_mod_exp_mont_consttime() calls.
1429 int BN_mod_exp_mont_consttime_x2(BIGNUM
*rr1
, const BIGNUM
*a1
, const BIGNUM
*p1
,
1430 const BIGNUM
*m1
, BN_MONT_CTX
*in_mont1
,
1431 BIGNUM
*rr2
, const BIGNUM
*a2
, const BIGNUM
*p2
,
1432 const BIGNUM
*m2
, BN_MONT_CTX
*in_mont2
,
1438 BN_MONT_CTX
*mont1
= NULL
;
1439 BN_MONT_CTX
*mont2
= NULL
;
1441 if (ossl_rsaz_avx512ifma_eligible() &&
1442 (((a1
->top
== 16) && (p1
->top
== 16) && (BN_num_bits(m1
) == 1024) &&
1443 (a2
->top
== 16) && (p2
->top
== 16) && (BN_num_bits(m2
) == 1024)) ||
1444 ((a1
->top
== 24) && (p1
->top
== 24) && (BN_num_bits(m1
) == 1536) &&
1445 (a2
->top
== 24) && (p2
->top
== 24) && (BN_num_bits(m2
) == 1536)) ||
1446 ((a1
->top
== 32) && (p1
->top
== 32) && (BN_num_bits(m1
) == 2048) &&
1447 (a2
->top
== 32) && (p2
->top
== 32) && (BN_num_bits(m2
) == 2048)))) {
1450 /* Modulus bits of |m1| and |m2| are equal */
1451 int mod_bits
= BN_num_bits(m1
);
1453 if (bn_wexpand(rr1
, topn
) == NULL
)
1455 if (bn_wexpand(rr2
, topn
) == NULL
)
1458 /* Ensure that montgomery contexts are initialized */
1459 if (in_mont1
!= NULL
) {
1462 if ((mont1
= BN_MONT_CTX_new()) == NULL
)
1464 if (!BN_MONT_CTX_set(mont1
, m1
, ctx
))
1467 if (in_mont2
!= NULL
) {
1470 if ((mont2
= BN_MONT_CTX_new()) == NULL
)
1472 if (!BN_MONT_CTX_set(mont2
, m2
, ctx
))
1476 ret
= ossl_rsaz_mod_exp_avx512_x2(rr1
->d
, a1
->d
, p1
->d
, m1
->d
,
1477 mont1
->RR
.d
, mont1
->n0
[0],
1478 rr2
->d
, a2
->d
, p2
->d
, m2
->d
,
1479 mont2
->RR
.d
, mont2
->n0
[0],
1484 bn_correct_top(rr1
);
1489 bn_correct_top(rr2
);
1496 /* rr1 = a1^p1 mod m1 */
1497 ret
= BN_mod_exp_mont_consttime(rr1
, a1
, p1
, m1
, ctx
, in_mont1
);
1498 /* rr2 = a2^p2 mod m2 */
1499 ret
&= BN_mod_exp_mont_consttime(rr2
, a2
, p2
, m2
, ctx
, in_mont2
);
1503 if (in_mont2
== NULL
)
1504 BN_MONT_CTX_free(mont2
);
1505 if (in_mont1
== NULL
)
1506 BN_MONT_CTX_free(mont1
);