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