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