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