1 /* crypto/bn/bn_exp.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 
112 #include "cryptlib.h"
113 #include "bn_lcl.h"
114 
115 #include <stdlib.h>
116 #ifdef _WIN32
117 # include <malloc.h>
118 # ifndef alloca
119 #  define alloca _alloca
120 # endif
121 #elif defined(__GNUC__)
122 # ifndef __SSP__
123 #  ifndef alloca
124 #   define alloca(s) __builtin_alloca((s))
125 #  endif
126 # else
127 #   undef alloca
128 # endif
129 #endif
130 
131 /* maximum precomputation table size for *variable* sliding windows */
132 #define TABLE_SIZE      32
133 
134 /* this one works - simple but works */
BN_exp(BIGNUM * r,const BIGNUM * a,const BIGNUM * p,BN_CTX * ctx)135 int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
136 {
137     int i, bits, ret = 0;
138     BIGNUM *v, *rr;
139 
140     if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
141         /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
142         BNerr(BN_F_BN_EXP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
143         return -1;
144     }
145 
146     BN_CTX_start(ctx);
147     if ((r == a) || (r == p))
148         rr = BN_CTX_get(ctx);
149     else
150         rr = r;
151     v = BN_CTX_get(ctx);
152     if (rr == NULL || v == NULL)
153         goto err;
154 
155     if (BN_copy(v, a) == NULL)
156         goto err;
157     bits = BN_num_bits(p);
158 
159     if (BN_is_odd(p)) {
160         if (BN_copy(rr, a) == NULL)
161             goto err;
162     } else {
163         if (!BN_one(rr))
164             goto err;
165     }
166 
167     for (i = 1; i < bits; i++) {
168         if (!BN_sqr(v, v, ctx))
169             goto err;
170         if (BN_is_bit_set(p, i)) {
171             if (!BN_mul(rr, rr, v, ctx))
172                 goto err;
173         }
174     }
175     if (r != rr)
176         BN_copy(r, rr);
177     ret = 1;
178  err:
179     BN_CTX_end(ctx);
180     bn_check_top(r);
181     return (ret);
182 }
183 
BN_mod_exp(BIGNUM * r,const BIGNUM * a,const BIGNUM * p,const BIGNUM * m,BN_CTX * ctx)184 int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
185                BN_CTX *ctx)
186 {
187     int ret;
188 
189     bn_check_top(a);
190     bn_check_top(p);
191     bn_check_top(m);
192 
193     /*-
194      * For even modulus  m = 2^k*m_odd,  it might make sense to compute
195      * a^p mod m_odd  and  a^p mod 2^k  separately (with Montgomery
196      * exponentiation for the odd part), using appropriate exponent
197      * reductions, and combine the results using the CRT.
198      *
199      * For now, we use Montgomery only if the modulus is odd; otherwise,
200      * exponentiation using the reciprocal-based quick remaindering
201      * algorithm is used.
202      *
203      * (Timing obtained with expspeed.c [computations  a^p mod m
204      * where  a, p, m  are of the same length: 256, 512, 1024, 2048,
205      * 4096, 8192 bits], compared to the running time of the
206      * standard algorithm:
207      *
208      *   BN_mod_exp_mont   33 .. 40 %  [AMD K6-2, Linux, debug configuration]
209      *                     55 .. 77 %  [UltraSparc processor, but
210      *                                  debug-solaris-sparcv8-gcc conf.]
211      *
212      *   BN_mod_exp_recp   50 .. 70 %  [AMD K6-2, Linux, debug configuration]
213      *                     62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc]
214      *
215      * On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont
216      * at 2048 and more bits, but at 512 and 1024 bits, it was
217      * slower even than the standard algorithm!
218      *
219      * "Real" timings [linux-elf, solaris-sparcv9-gcc configurations]
220      * should be obtained when the new Montgomery reduction code
221      * has been integrated into OpenSSL.)
222      */
223 
224 #define MONT_MUL_MOD
225 #define MONT_EXP_WORD
226 #define RECP_MUL_MOD
227 
228 #ifdef MONT_MUL_MOD
229     /*
230      * I have finally been able to take out this pre-condition of the top bit
231      * being set.  It was caused by an error in BN_div with negatives.  There
232      * was also another problem when for a^b%m a >= m.  eay 07-May-97
233      */
234     /* if ((m->d[m->top-1]&BN_TBIT) && BN_is_odd(m)) */
235 
236     if (BN_is_odd(m)) {
237 # ifdef MONT_EXP_WORD
238         if (a->top == 1 && !a->neg
239             && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0)) {
240             BN_ULONG A = a->d[0];
241             ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL);
242         } else
243 # endif
244             ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL);
245     } else
246 #endif
247 #ifdef RECP_MUL_MOD
248     {
249         ret = BN_mod_exp_recp(r, a, p, m, ctx);
250     }
251 #else
252     {
253         ret = BN_mod_exp_simple(r, a, p, m, ctx);
254     }
255 #endif
256 
257     bn_check_top(r);
258     return (ret);
259 }
260 
BN_mod_exp_recp(BIGNUM * r,const BIGNUM * a,const BIGNUM * p,const BIGNUM * m,BN_CTX * ctx)261 int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
262                     const BIGNUM *m, BN_CTX *ctx)
263 {
264     int i, j, bits, ret = 0, wstart, wend, window, wvalue;
265     int start = 1;
266     BIGNUM *aa;
267     /* Table of variables obtained from 'ctx' */
268     BIGNUM *val[TABLE_SIZE];
269     BN_RECP_CTX recp;
270 
271     if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
272         /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
273         BNerr(BN_F_BN_MOD_EXP_RECP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
274         return -1;
275     }
276 
277     bits = BN_num_bits(p);
278 
279     if (bits == 0) {
280         ret = BN_one(r);
281         return ret;
282     }
283 
284     BN_CTX_start(ctx);
285     aa = BN_CTX_get(ctx);
286     val[0] = BN_CTX_get(ctx);
287     if (!aa || !val[0])
288         goto err;
289 
290     BN_RECP_CTX_init(&recp);
291     if (m->neg) {
292         /* ignore sign of 'm' */
293         if (!BN_copy(aa, m))
294             goto err;
295         aa->neg = 0;
296         if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0)
297             goto err;
298     } else {
299         if (BN_RECP_CTX_set(&recp, m, ctx) <= 0)
300             goto err;
301     }
302 
303     if (!BN_nnmod(val[0], a, m, ctx))
304         goto err;               /* 1 */
305     if (BN_is_zero(val[0])) {
306         BN_zero(r);
307         ret = 1;
308         goto err;
309     }
310 
311     window = BN_window_bits_for_exponent_size(bits);
312     if (window > 1) {
313         if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx))
314             goto err;           /* 2 */
315         j = 1 << (window - 1);
316         for (i = 1; i < j; i++) {
317             if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
318                 !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx))
319                 goto err;
320         }
321     }
322 
323     start = 1;                  /* This is used to avoid multiplication etc
324                                  * when there is only the value '1' in the
325                                  * buffer. */
326     wvalue = 0;                 /* The 'value' of the window */
327     wstart = bits - 1;          /* The top bit of the window */
328     wend = 0;                   /* The bottom bit of the window */
329 
330     if (!BN_one(r))
331         goto err;
332 
333     for (;;) {
334         if (BN_is_bit_set(p, wstart) == 0) {
335             if (!start)
336                 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
337                     goto err;
338             if (wstart == 0)
339                 break;
340             wstart--;
341             continue;
342         }
343         /*
344          * We now have wstart on a 'set' bit, we now need to work out how bit
345          * a window to do.  To do this we need to scan forward until the last
346          * set bit before the end of the window
347          */
348         j = wstart;
349         wvalue = 1;
350         wend = 0;
351         for (i = 1; i < window; i++) {
352             if (wstart - i < 0)
353                 break;
354             if (BN_is_bit_set(p, wstart - i)) {
355                 wvalue <<= (i - wend);
356                 wvalue |= 1;
357                 wend = i;
358             }
359         }
360 
361         /* wend is the size of the current window */
362         j = wend + 1;
363         /* add the 'bytes above' */
364         if (!start)
365             for (i = 0; i < j; i++) {
366                 if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
367                     goto err;
368             }
369 
370         /* wvalue will be an odd number < 2^window */
371         if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx))
372             goto err;
373 
374         /* move the 'window' down further */
375         wstart -= wend + 1;
376         wvalue = 0;
377         start = 0;
378         if (wstart < 0)
379             break;
380     }
381     ret = 1;
382  err:
383     BN_CTX_end(ctx);
384     BN_RECP_CTX_free(&recp);
385     bn_check_top(r);
386     return (ret);
387 }
388 
BN_mod_exp_mont(BIGNUM * rr,const BIGNUM * a,const BIGNUM * p,const BIGNUM * m,BN_CTX * ctx,BN_MONT_CTX * in_mont)389 int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
390                     const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
391 {
392     int i, j, bits, ret = 0, wstart, wend, window, wvalue;
393     int start = 1;
394     BIGNUM *d, *r;
395     const BIGNUM *aa;
396     /* Table of variables obtained from 'ctx' */
397     BIGNUM *val[TABLE_SIZE];
398     BN_MONT_CTX *mont = NULL;
399 
400     if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
401         return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont);
402     }
403 
404     bn_check_top(a);
405     bn_check_top(p);
406     bn_check_top(m);
407 
408     if (!BN_is_odd(m)) {
409         BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS);
410         return (0);
411     }
412     bits = BN_num_bits(p);
413     if (bits == 0) {
414         ret = BN_one(rr);
415         return ret;
416     }
417 
418     BN_CTX_start(ctx);
419     d = BN_CTX_get(ctx);
420     r = BN_CTX_get(ctx);
421     val[0] = BN_CTX_get(ctx);
422     if (!d || !r || !val[0])
423         goto err;
424 
425     /*
426      * If this is not done, things will break in the montgomery part
427      */
428 
429     if (in_mont != NULL)
430         mont = in_mont;
431     else {
432         if ((mont = BN_MONT_CTX_new()) == NULL)
433             goto err;
434         if (!BN_MONT_CTX_set(mont, m, ctx))
435             goto err;
436     }
437 
438     if (a->neg || BN_ucmp(a, m) >= 0) {
439         if (!BN_nnmod(val[0], a, m, ctx))
440             goto err;
441         aa = val[0];
442     } else
443         aa = a;
444     if (BN_is_zero(aa)) {
445         BN_zero(rr);
446         ret = 1;
447         goto err;
448     }
449     if (!BN_to_montgomery(val[0], aa, mont, ctx))
450         goto err;               /* 1 */
451 
452     window = BN_window_bits_for_exponent_size(bits);
453     if (window > 1) {
454         if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx))
455             goto err;           /* 2 */
456         j = 1 << (window - 1);
457         for (i = 1; i < j; i++) {
458             if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
459                 !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx))
460                 goto err;
461         }
462     }
463 
464     start = 1;                  /* This is used to avoid multiplication etc
465                                  * when there is only the value '1' in the
466                                  * buffer. */
467     wvalue = 0;                 /* The 'value' of the window */
468     wstart = bits - 1;          /* The top bit of the window */
469     wend = 0;                   /* The bottom bit of the window */
470 
471     if (!BN_to_montgomery(r, BN_value_one(), mont, ctx))
472         goto err;
473     for (;;) {
474         if (BN_is_bit_set(p, wstart) == 0) {
475             if (!start) {
476                 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
477                     goto err;
478             }
479             if (wstart == 0)
480                 break;
481             wstart--;
482             continue;
483         }
484         /*
485          * We now have wstart on a 'set' bit, we now need to work out how bit
486          * a window to do.  To do this we need to scan forward until the last
487          * set bit before the end of the window
488          */
489         j = wstart;
490         wvalue = 1;
491         wend = 0;
492         for (i = 1; i < window; i++) {
493             if (wstart - i < 0)
494                 break;
495             if (BN_is_bit_set(p, wstart - i)) {
496                 wvalue <<= (i - wend);
497                 wvalue |= 1;
498                 wend = i;
499             }
500         }
501 
502         /* wend is the size of the current window */
503         j = wend + 1;
504         /* add the 'bytes above' */
505         if (!start)
506             for (i = 0; i < j; i++) {
507                 if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
508                     goto err;
509             }
510 
511         /* wvalue will be an odd number < 2^window */
512         if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx))
513             goto err;
514 
515         /* move the 'window' down further */
516         wstart -= wend + 1;
517         wvalue = 0;
518         start = 0;
519         if (wstart < 0)
520             break;
521     }
522     if (!BN_from_montgomery(rr, r, mont, ctx))
523         goto err;
524     ret = 1;
525  err:
526     if ((in_mont == NULL) && (mont != NULL))
527         BN_MONT_CTX_free(mont);
528     BN_CTX_end(ctx);
529     bn_check_top(rr);
530     return (ret);
531 }
532 
533 /*
534  * BN_mod_exp_mont_consttime() stores the precomputed powers in a specific
535  * layout so that accessing any of these table values shows the same access
536  * pattern as far as cache lines are concerned.  The following functions are
537  * used to transfer a BIGNUM from/to that table.
538  */
539 
MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM * b,int top,unsigned char * buf,int idx,int width)540 static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top,
541                                         unsigned char *buf, int idx,
542                                         int width)
543 {
544     size_t i, j;
545 
546     if (top > b->top)
547         top = b->top;           /* this works because 'buf' is explicitly
548                                  * zeroed */
549     for (i = 0, j = idx; i < top * sizeof b->d[0]; i++, j += width) {
550         buf[j] = ((unsigned char *)b->d)[i];
551     }
552 
553     return 1;
554 }
555 
MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM * b,int top,unsigned char * buf,int idx,int width)556 static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top,
557                                           unsigned char *buf, int idx,
558                                           int width)
559 {
560     size_t i, j;
561 
562     if (bn_wexpand(b, top) == NULL)
563         return 0;
564 
565     for (i = 0, j = idx; i < top * sizeof b->d[0]; i++, j += width) {
566         ((unsigned char *)b->d)[i] = buf[j];
567     }
568 
569     b->top = top;
570     bn_correct_top(b);
571     return 1;
572 }
573 
574 /*
575  * Given a pointer value, compute the next address that is a cache line
576  * multiple.
577  */
578 #define MOD_EXP_CTIME_ALIGN(x_) \
579         ((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK))))
580 
581 /*
582  * This variant of BN_mod_exp_mont() uses fixed windows and the special
583  * precomputation memory layout to limit data-dependency to a minimum to
584  * protect secret exponents (cf. the hyper-threading timing attacks pointed
585  * out by Colin Percival,
586  * http://www.daemong-consideredperthreading-considered-harmful/)
587  */
BN_mod_exp_mont_consttime(BIGNUM * rr,const BIGNUM * a,const BIGNUM * p,const BIGNUM * m,BN_CTX * ctx,BN_MONT_CTX * in_mont)588 int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
589                               const BIGNUM *m, BN_CTX *ctx,
590                               BN_MONT_CTX *in_mont)
591 {
592     int i, bits, ret = 0, window, wvalue;
593     int top;
594     BN_MONT_CTX *mont = NULL;
595 
596     int numPowers;
597     unsigned char *powerbufFree = NULL;
598     int powerbufLen = 0;
599     unsigned char *powerbuf = NULL;
600     BIGNUM tmp, am;
601 
602     bn_check_top(a);
603     bn_check_top(p);
604     bn_check_top(m);
605 
606     top = m->top;
607 
608     if (!(m->d[0] & 1)) {
609         BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS);
610         return (0);
611     }
612     bits = BN_num_bits(p);
613     if (bits == 0) {
614         ret = BN_one(rr);
615         return ret;
616     }
617 
618     BN_CTX_start(ctx);
619 
620     /*
621      * Allocate a montgomery context if it was not supplied by the caller. If
622      * this is not done, things will break in the montgomery part.
623      */
624     if (in_mont != NULL)
625         mont = in_mont;
626     else {
627         if ((mont = BN_MONT_CTX_new()) == NULL)
628             goto err;
629         if (!BN_MONT_CTX_set(mont, m, ctx))
630             goto err;
631     }
632 
633     /* Get the window size to use with size of p. */
634     window = BN_window_bits_for_ctime_exponent_size(bits);
635 #if defined(OPENSSL_BN_ASM_MONT5)
636     if (window == 6 && bits <= 1024)
637         window = 5;             /* ~5% improvement of 2048-bit RSA sign */
638 #endif
639 
640     /*
641      * Allocate a buffer large enough to hold all of the pre-computed powers
642      * of am, am itself and tmp.
643      */
644     numPowers = 1 << window;
645     powerbufLen = sizeof(m->d[0]) * (top * numPowers +
646                                      ((2 * top) >
647                                       numPowers ? (2 * top) : numPowers));
648 #ifdef alloca
649     if (powerbufLen < 3072)
650         powerbufFree =
651             alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
652     else
653 #endif
654         if ((powerbufFree =
655              (unsigned char *)OPENSSL_malloc(powerbufLen +
656                                              MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))
657             == NULL)
658         goto err;
659 
660     powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
661     memset(powerbuf, 0, powerbufLen);
662 
663 #ifdef alloca
664     if (powerbufLen < 3072)
665         powerbufFree = NULL;
666 #endif
667 
668     /* lay down tmp and am right after powers table */
669     tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
670     am.d = tmp.d + top;
671     tmp.top = am.top = 0;
672     tmp.dmax = am.dmax = top;
673     tmp.neg = am.neg = 0;
674     tmp.flags = am.flags = BN_FLG_STATIC_DATA;
675 
676     /* prepare a^0 in Montgomery domain */
677 #if 1
678     if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx))
679         goto err;
680 #else
681     tmp.d[0] = (0 - m->d[0]) & BN_MASK2; /* 2^(top*BN_BITS2) - m */
682     for (i = 1; i < top; i++)
683         tmp.d[i] = (~m->d[i]) & BN_MASK2;
684     tmp.top = top;
685 #endif
686 
687     /* prepare a^1 in Montgomery domain */
688     if (a->neg || BN_ucmp(a, m) >= 0) {
689         if (!BN_mod(&am, a, m, ctx))
690             goto err;
691         if (!BN_to_montgomery(&am, &am, mont, ctx))
692             goto err;
693     } else if (!BN_to_montgomery(&am, a, mont, ctx))
694         goto err;
695 
696 #if defined(OPENSSL_BN_ASM_MONT5)
697     if (window == 5 && top > 1) {
698         /*
699          * This optimization uses ideas from http://eprint.iacr.org/2011/239,
700          * specifically optimization of cache-timing attack countermeasures
701          * and pre-computation optimization.
702          */
703 
704         /*
705          * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
706          * 512-bit RSA is hardly relevant, we omit it to spare size...
707          */
708         void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
709                                  const void *table, const BN_ULONG *np,
710                                  const BN_ULONG *n0, int num, int power);
711         void bn_scatter5(const BN_ULONG *inp, size_t num,
712                          void *table, size_t power);
713         void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
714 
715         BN_ULONG *np = mont->N.d, *n0 = mont->n0;
716 
717         /*
718          * BN_to_montgomery can contaminate words above .top [in
719          * BN_DEBUG[_DEBUG] build]...
720          */
721         for (i = am.top; i < top; i++)
722             am.d[i] = 0;
723         for (i = tmp.top; i < top; i++)
724             tmp.d[i] = 0;
725 
726         bn_scatter5(tmp.d, top, powerbuf, 0);
727         bn_scatter5(am.d, am.top, powerbuf, 1);
728         bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
729         bn_scatter5(tmp.d, top, powerbuf, 2);
730 
731 # if 0
732         for (i = 3; i < 32; i++) {
733             /* Calculate a^i = a^(i-1) * a */
734             bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
735             bn_scatter5(tmp.d, top, powerbuf, i);
736         }
737 # else
738         /* same as above, but uses squaring for 1/2 of operations */
739         for (i = 4; i < 32; i *= 2) {
740             bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
741             bn_scatter5(tmp.d, top, powerbuf, i);
742         }
743         for (i = 3; i < 8; i += 2) {
744             int j;
745             bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
746             bn_scatter5(tmp.d, top, powerbuf, i);
747             for (j = 2 * i; j < 32; j *= 2) {
748                 bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
749                 bn_scatter5(tmp.d, top, powerbuf, j);
750             }
751         }
752         for (; i < 16; i += 2) {
753             bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
754             bn_scatter5(tmp.d, top, powerbuf, i);
755             bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
756             bn_scatter5(tmp.d, top, powerbuf, 2 * i);
757         }
758         for (; i < 32; i += 2) {
759             bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
760             bn_scatter5(tmp.d, top, powerbuf, i);
761         }
762 # endif
763         bits--;
764         for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
765             wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
766         bn_gather5(tmp.d, top, powerbuf, wvalue);
767 
768         /*
769          * Scan the exponent one window at a time starting from the most
770          * significant bits.
771          */
772         while (bits >= 0) {
773             for (wvalue = 0, i = 0; i < 5; i++, bits--)
774                 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
775 
776             bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
777             bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
778             bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
779             bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
780             bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
781             bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
782         }
783 
784         tmp.top = top;
785         bn_correct_top(&tmp);
786     } else
787 #endif
788     {
789         if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, numPowers))
790             goto err;
791         if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, numPowers))
792             goto err;
793 
794         /*
795          * If the window size is greater than 1, then calculate
796          * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
797          * powers could instead be computed as (a^(i/2))^2 to use the slight
798          * performance advantage of sqr over mul).
799          */
800         if (window > 1) {
801             if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx))
802                 goto err;
803             if (!MOD_EXP_CTIME_COPY_TO_PREBUF
804                 (&tmp, top, powerbuf, 2, numPowers))
805                 goto err;
806             for (i = 3; i < numPowers; i++) {
807                 /* Calculate a^i = a^(i-1) * a */
808                 if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx))
809                     goto err;
810                 if (!MOD_EXP_CTIME_COPY_TO_PREBUF
811                     (&tmp, top, powerbuf, i, numPowers))
812                     goto err;
813             }
814         }
815 
816         bits--;
817         for (wvalue = 0, i = bits % window; i >= 0; i--, bits--)
818             wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
819         if (!MOD_EXP_CTIME_COPY_FROM_PREBUF
820             (&tmp, top, powerbuf, wvalue, numPowers))
821             goto err;
822 
823         /*
824          * Scan the exponent one window at a time starting from the most
825          * significant bits.
826          */
827         while (bits >= 0) {
828             wvalue = 0;         /* The 'value' of the window */
829 
830             /* Scan the window, squaring the result as we go */
831             for (i = 0; i < window; i++, bits--) {
832                 if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx))
833                     goto err;
834                 wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
835             }
836 
837             /*
838              * Fetch the appropriate pre-computed value from the pre-buf
839              */
840             if (!MOD_EXP_CTIME_COPY_FROM_PREBUF
841                 (&am, top, powerbuf, wvalue, numPowers))
842                 goto err;
843 
844             /* Multiply the result into the intermediate result */
845             if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx))
846                 goto err;
847         }
848     }
849 
850     /* Convert the final result from montgomery to standard format */
851     if (!BN_from_montgomery(rr, &tmp, mont, ctx))
852         goto err;
853     ret = 1;
854  err:
855     if ((in_mont == NULL) && (mont != NULL))
856         BN_MONT_CTX_free(mont);
857     if (powerbuf != NULL) {
858         OPENSSL_cleanse(powerbuf, powerbufLen);
859         if (powerbufFree)
860             OPENSSL_free(powerbufFree);
861     }
862     BN_CTX_end(ctx);
863     return (ret);
864 }
865 
BN_mod_exp_mont_word(BIGNUM * rr,BN_ULONG a,const BIGNUM * p,const BIGNUM * m,BN_CTX * ctx,BN_MONT_CTX * in_mont)866 int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
867                          const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
868 {
869     BN_MONT_CTX *mont = NULL;
870     int b, bits, ret = 0;
871     int r_is_one;
872     BN_ULONG w, next_w;
873     BIGNUM *d, *r, *t;
874     BIGNUM *swap_tmp;
875 #define BN_MOD_MUL_WORD(r, w, m) \
876                 (BN_mul_word(r, (w)) && \
877                 (/* BN_ucmp(r, (m)) < 0 ? 1 :*/  \
878                         (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
879     /*
880      * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
881      * probably more overhead than always using BN_mod (which uses BN_copy if
882      * a similar test returns true).
883      */
884     /*
885      * We can use BN_mod and do not need BN_nnmod because our accumulator is
886      * never negative (the result of BN_mod does not depend on the sign of
887      * the modulus).
888      */
889 #define BN_TO_MONTGOMERY_WORD(r, w, mont) \
890                 (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
891 
892     if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
893         /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
894         BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
895         return -1;
896     }
897 
898     bn_check_top(p);
899     bn_check_top(m);
900 
901     if (!BN_is_odd(m)) {
902         BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS);
903         return (0);
904     }
905     if (m->top == 1)
906         a %= m->d[0];           /* make sure that 'a' is reduced */
907 
908     bits = BN_num_bits(p);
909     if (bits == 0) {
910         /* x**0 mod 1 is still zero. */
911         if (BN_is_one(m)) {
912             ret = 1;
913             BN_zero(rr);
914         } else
915             ret = BN_one(rr);
916         return ret;
917     }
918     if (a == 0) {
919         BN_zero(rr);
920         ret = 1;
921         return ret;
922     }
923 
924     BN_CTX_start(ctx);
925     d = BN_CTX_get(ctx);
926     r = BN_CTX_get(ctx);
927     t = BN_CTX_get(ctx);
928     if (d == NULL || r == NULL || t == NULL)
929         goto err;
930 
931     if (in_mont != NULL)
932         mont = in_mont;
933     else {
934         if ((mont = BN_MONT_CTX_new()) == NULL)
935             goto err;
936         if (!BN_MONT_CTX_set(mont, m, ctx))
937             goto err;
938     }
939 
940     r_is_one = 1;               /* except for Montgomery factor */
941 
942     /* bits-1 >= 0 */
943 
944     /* The result is accumulated in the product r*w. */
945     w = a;                      /* bit 'bits-1' of 'p' is always set */
946     for (b = bits - 2; b >= 0; b--) {
947         /* First, square r*w. */
948         next_w = w * w;
949         if ((next_w / w) != w) { /* overflow */
950             if (r_is_one) {
951                 if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
952                     goto err;
953                 r_is_one = 0;
954             } else {
955                 if (!BN_MOD_MUL_WORD(r, w, m))
956                     goto err;
957             }
958             next_w = 1;
959         }
960         w = next_w;
961         if (!r_is_one) {
962             if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
963                 goto err;
964         }
965 
966         /* Second, multiply r*w by 'a' if exponent bit is set. */
967         if (BN_is_bit_set(p, b)) {
968             next_w = w * a;
969             if ((next_w / a) != w) { /* overflow */
970                 if (r_is_one) {
971                     if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
972                         goto err;
973                     r_is_one = 0;
974                 } else {
975                     if (!BN_MOD_MUL_WORD(r, w, m))
976                         goto err;
977                 }
978                 next_w = a;
979             }
980             w = next_w;
981         }
982     }
983 
984     /* Finally, set r:=r*w. */
985     if (w != 1) {
986         if (r_is_one) {
987             if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
988                 goto err;
989             r_is_one = 0;
990         } else {
991             if (!BN_MOD_MUL_WORD(r, w, m))
992                 goto err;
993         }
994     }
995 
996     if (r_is_one) {             /* can happen only if a == 1 */
997         if (!BN_one(rr))
998             goto err;
999     } else {
1000         if (!BN_from_montgomery(rr, r, mont, ctx))
1001             goto err;
1002     }
1003     ret = 1;
1004  err:
1005     if ((in_mont == NULL) && (mont != NULL))
1006         BN_MONT_CTX_free(mont);
1007     BN_CTX_end(ctx);
1008     bn_check_top(rr);
1009     return (ret);
1010 }
1011 
1012 /* The old fallback, simple version :-) */
BN_mod_exp_simple(BIGNUM * r,const BIGNUM * a,const BIGNUM * p,const BIGNUM * m,BN_CTX * ctx)1013 int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1014                       const BIGNUM *m, BN_CTX *ctx)
1015 {
1016     int i, j, bits, ret = 0, wstart, wend, window, wvalue;
1017     int start = 1;
1018     BIGNUM *d;
1019     /* Table of variables obtained from 'ctx' */
1020     BIGNUM *val[TABLE_SIZE];
1021 
1022     if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0) {
1023         /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1024         BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1025         return -1;
1026     }
1027 
1028     bits = BN_num_bits(p);
1029 
1030     if (bits == 0) {
1031         ret = BN_one(r);
1032         return ret;
1033     }
1034 
1035     BN_CTX_start(ctx);
1036     d = BN_CTX_get(ctx);
1037     val[0] = BN_CTX_get(ctx);
1038     if (!d || !val[0])
1039         goto err;
1040 
1041     if (!BN_nnmod(val[0], a, m, ctx))
1042         goto err;               /* 1 */
1043     if (BN_is_zero(val[0])) {
1044         BN_zero(r);
1045         ret = 1;
1046         goto err;
1047     }
1048 
1049     window = BN_window_bits_for_exponent_size(bits);
1050     if (window > 1) {
1051         if (!BN_mod_mul(d, val[0], val[0], m, ctx))
1052             goto err;           /* 2 */
1053         j = 1 << (window - 1);
1054         for (i = 1; i < j; i++) {
1055             if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
1056                 !BN_mod_mul(val[i], val[i - 1], d, m, ctx))
1057                 goto err;
1058         }
1059     }
1060 
1061     start = 1;                  /* This is used to avoid multiplication etc
1062                                  * when there is only the value '1' in the
1063                                  * buffer. */
1064     wvalue = 0;                 /* The 'value' of the window */
1065     wstart = bits - 1;          /* The top bit of the window */
1066     wend = 0;                   /* The bottom bit of the window */
1067 
1068     if (!BN_one(r))
1069         goto err;
1070 
1071     for (;;) {
1072         if (BN_is_bit_set(p, wstart) == 0) {
1073             if (!start)
1074                 if (!BN_mod_mul(r, r, r, m, ctx))
1075                     goto err;
1076             if (wstart == 0)
1077                 break;
1078             wstart--;
1079             continue;
1080         }
1081         /*
1082          * We now have wstart on a 'set' bit, we now need to work out how bit
1083          * a window to do.  To do this we need to scan forward until the last
1084          * set bit before the end of the window
1085          */
1086         j = wstart;
1087         wvalue = 1;
1088         wend = 0;
1089         for (i = 1; i < window; i++) {
1090             if (wstart - i < 0)
1091                 break;
1092             if (BN_is_bit_set(p, wstart - i)) {
1093                 wvalue <<= (i - wend);
1094                 wvalue |= 1;
1095                 wend = i;
1096             }
1097         }
1098 
1099         /* wend is the size of the current window */
1100         j = wend + 1;
1101         /* add the 'bytes above' */
1102         if (!start)
1103             for (i = 0; i < j; i++) {
1104                 if (!BN_mod_mul(r, r, r, m, ctx))
1105                     goto err;
1106             }
1107 
1108         /* wvalue will be an odd number < 2^window */
1109         if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
1110             goto err;
1111 
1112         /* move the 'window' down further */
1113         wstart -= wend + 1;
1114         wvalue = 0;
1115         start = 0;
1116         if (wstart < 0)
1117             break;
1118     }
1119     ret = 1;
1120  err:
1121     BN_CTX_end(ctx);
1122     bn_check_top(r);
1123     return (ret);
1124 }
1125