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