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