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