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