bn_exp.c revision 331638
1251875Speter/* crypto/bn/bn_exp.c */
2251875Speter/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3251875Speter * All rights reserved.
4251875Speter *
5251875Speter * This package is an SSL implementation written
6251875Speter * by Eric Young (eay@cryptsoft.com).
7251875Speter * The implementation was written so as to conform with Netscapes SSL.
8251875Speter *
9251875Speter * This library is free for commercial and non-commercial use as long as
10251875Speter * the following conditions are aheared to.  The following conditions
11251875Speter * apply to all code found in this distribution, be it the RC4, RSA,
12251875Speter * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13251875Speter * included with this distribution is covered by the same copyright terms
14251875Speter * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15251875Speter *
16251875Speter * Copyright remains Eric Young's, and as such any Copyright notices in
17251875Speter * the code are not to be removed.
18251875Speter * If this package is used in a product, Eric Young should be given attribution
19251875Speter * as the author of the parts of the library used.
20251875Speter * This can be in the form of a textual message at program startup or
21251875Speter * in documentation (online or textual) provided with the package.
22251875Speter *
23251875Speter * Redistribution and use in source and binary forms, with or without
24251875Speter * modification, are permitted provided that the following conditions
25251875Speter * are met:
26251875Speter * 1. Redistributions of source code must retain the copyright
27251875Speter *    notice, this list of conditions and the following disclaimer.
28251875Speter * 2. Redistributions in binary form must reproduce the above copyright
29251875Speter *    notice, this list of conditions and the following disclaimer in the
30251875Speter *    documentation and/or other materials provided with the distribution.
31251875Speter * 3. All advertising materials mentioning features or use of this software
32251875Speter *    must display the following acknowledgement:
33251875Speter *    "This product includes cryptographic software written by
34251875Speter *     Eric Young (eay@cryptsoft.com)"
35251875Speter *    The word 'cryptographic' can be left out if the rouines from the library
36251875Speter *    being used are not cryptographic related :-).
37251875Speter * 4. If you include any Windows specific code (or a derivative thereof) from
38251875Speter *    the apps directory (application code) you must include an acknowledgement:
39251875Speter *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40251875Speter *
41251875Speter * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42251875Speter * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43251875Speter * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44251875Speter * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45251875Speter * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46251875Speter * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47251875Speter * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48251875Speter * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49251875Speter * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50251875Speter * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51251875Speter * SUCH DAMAGE.
52251875Speter *
53251875Speter * The licence and distribution terms for any publically available version or
54251875Speter * derivative of this code cannot be changed.  i.e. this code cannot simply be
55251875Speter * copied and put under another distribution licence
56251875Speter * [including the GNU Public Licence.]
57251875Speter */
58251875Speter/* ====================================================================
59251875Speter * Copyright (c) 1998-2018 The OpenSSL Project.  All rights reserved.
60251875Speter *
61251875Speter * Redistribution and use in source and binary forms, with or without
62251875Speter * modification, are permitted provided that the following conditions
63251875Speter * are met:
64251875Speter *
65251875Speter * 1. Redistributions of source code must retain the above copyright
66251875Speter *    notice, this list of conditions and the following disclaimer.
67251875Speter *
68251875Speter * 2. Redistributions in binary form must reproduce the above copyright
69251875Speter *    notice, this list of conditions and the following disclaimer in
70251875Speter *    the documentation and/or other materials provided with the
71251875Speter *    distribution.
72251875Speter *
73251875Speter * 3. All advertising materials mentioning features or use of this
74251875Speter *    software must display the following acknowledgment:
75251875Speter *    "This product includes software developed by the OpenSSL Project
76251875Speter *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77251875Speter *
78251875Speter * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79251875Speter *    endorse or promote products derived from this software without
80251875Speter *    prior written permission. For written permission, please contact
81251875Speter *    openssl-core@openssl.org.
82251875Speter *
83251875Speter * 5. Products derived from this software may not be called "OpenSSL"
84251875Speter *    nor may "OpenSSL" appear in their names without prior written
85251875Speter *    permission of the OpenSSL Project.
86251875Speter *
87251875Speter * 6. Redistributions of any form whatsoever must retain the following
88251875Speter *    acknowledgment:
89251875Speter *    "This product includes software developed by the OpenSSL Project
90251875Speter *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91251875Speter *
92251875Speter * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93251875Speter * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94251875Speter * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95251875Speter * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96251875Speter * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97251875Speter * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98251875Speter * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99251875Speter * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100251875Speter * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101251875Speter * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102251875Speter * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103251875Speter * OF THE POSSIBILITY OF SUCH DAMAGE.
104251875Speter * ====================================================================
105251875Speter *
106251875Speter * This product includes cryptographic software written by Eric Young
107251875Speter * (eay@cryptsoft.com).  This product includes software written by Tim
108251875Speter * Hudson (tjh@cryptsoft.com).
109251875Speter *
110251875Speter */
111251875Speter
112251875Speter#include "cryptlib.h"
113251875Speter#include "constant_time_locl.h"
114251875Speter#include "bn_lcl.h"
115251875Speter
116251875Speter#include <stdlib.h>
117251875Speter#ifdef _WIN32
118251875Speter# include <malloc.h>
119251875Speter# ifndef alloca
120253734Speter#  define alloca _alloca
121251875Speter# endif
122251875Speter#elif defined(__GNUC__)
123251875Speter# ifndef alloca
124251875Speter#  define alloca(s) __builtin_alloca((s))
125251875Speter# endif
126251875Speter#elif defined(__sun)
127251875Speter# include <alloca.h>
128#endif
129
130#include "rsaz_exp.h"
131
132#undef SPARC_T4_MONT
133#if defined(OPENSSL_BN_ASM_MONT) && (defined(__sparc__) || defined(__sparc))
134# include "sparc_arch.h"
135extern unsigned int OPENSSL_sparcv9cap_P[];
136# define SPARC_T4_MONT
137#endif
138
139/* maximum precomputation table size for *variable* sliding windows */
140#define TABLE_SIZE      32
141
142/* this one works - simple but works */
143int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
144{
145    int i, bits, ret = 0;
146    BIGNUM *v, *rr;
147
148    if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
149            || BN_get_flags(a, BN_FLG_CONSTTIME) != 0) {
150        /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
151        BNerr(BN_F_BN_EXP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
152        return 0;
153    }
154
155    BN_CTX_start(ctx);
156    if ((r == a) || (r == p))
157        rr = BN_CTX_get(ctx);
158    else
159        rr = r;
160    v = BN_CTX_get(ctx);
161    if (rr == NULL || v == NULL)
162        goto err;
163
164    if (BN_copy(v, a) == NULL)
165        goto err;
166    bits = BN_num_bits(p);
167
168    if (BN_is_odd(p)) {
169        if (BN_copy(rr, a) == NULL)
170            goto err;
171    } else {
172        if (!BN_one(rr))
173            goto err;
174    }
175
176    for (i = 1; i < bits; i++) {
177        if (!BN_sqr(v, v, ctx))
178            goto err;
179        if (BN_is_bit_set(p, i)) {
180            if (!BN_mul(rr, rr, v, ctx))
181                goto err;
182        }
183    }
184    if (r != rr && BN_copy(r, rr) == NULL)
185        goto err;
186
187    ret = 1;
188 err:
189    BN_CTX_end(ctx);
190    bn_check_top(r);
191    return (ret);
192}
193
194int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
195               BN_CTX *ctx)
196{
197    int ret;
198
199    bn_check_top(a);
200    bn_check_top(p);
201    bn_check_top(m);
202
203    /*-
204     * For even modulus  m = 2^k*m_odd,  it might make sense to compute
205     * a^p mod m_odd  and  a^p mod 2^k  separately (with Montgomery
206     * exponentiation for the odd part), using appropriate exponent
207     * reductions, and combine the results using the CRT.
208     *
209     * For now, we use Montgomery only if the modulus is odd; otherwise,
210     * exponentiation using the reciprocal-based quick remaindering
211     * algorithm is used.
212     *
213     * (Timing obtained with expspeed.c [computations  a^p mod m
214     * where  a, p, m  are of the same length: 256, 512, 1024, 2048,
215     * 4096, 8192 bits], compared to the running time of the
216     * standard algorithm:
217     *
218     *   BN_mod_exp_mont   33 .. 40 %  [AMD K6-2, Linux, debug configuration]
219     *                     55 .. 77 %  [UltraSparc processor, but
220     *                                  debug-solaris-sparcv8-gcc conf.]
221     *
222     *   BN_mod_exp_recp   50 .. 70 %  [AMD K6-2, Linux, debug configuration]
223     *                     62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc]
224     *
225     * On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont
226     * at 2048 and more bits, but at 512 and 1024 bits, it was
227     * slower even than the standard algorithm!
228     *
229     * "Real" timings [linux-elf, solaris-sparcv9-gcc configurations]
230     * should be obtained when the new Montgomery reduction code
231     * has been integrated into OpenSSL.)
232     */
233
234#define MONT_MUL_MOD
235#define MONT_EXP_WORD
236#define RECP_MUL_MOD
237
238#ifdef MONT_MUL_MOD
239    /*
240     * I have finally been able to take out this pre-condition of the top bit
241     * being set.  It was caused by an error in BN_div with negatives.  There
242     * was also another problem when for a^b%m a >= m.  eay 07-May-97
243     */
244    /* if ((m->d[m->top-1]&BN_TBIT) && BN_is_odd(m)) */
245
246    if (BN_is_odd(m)) {
247# ifdef MONT_EXP_WORD
248        if (a->top == 1 && !a->neg
249            && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0)
250            && (BN_get_flags(a, BN_FLG_CONSTTIME) == 0)
251            && (BN_get_flags(m, BN_FLG_CONSTTIME) == 0)) {
252            BN_ULONG A = a->d[0];
253            ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL);
254        } else
255# endif
256            ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL);
257    } else
258#endif
259#ifdef RECP_MUL_MOD
260    {
261        ret = BN_mod_exp_recp(r, a, p, m, ctx);
262    }
263#else
264    {
265        ret = BN_mod_exp_simple(r, a, p, m, ctx);
266    }
267#endif
268
269    bn_check_top(r);
270    return (ret);
271}
272
273int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
274                    const BIGNUM *m, BN_CTX *ctx)
275{
276    int i, j, bits, ret = 0, wstart, wend, window, wvalue;
277    int start = 1;
278    BIGNUM *aa;
279    /* Table of variables obtained from 'ctx' */
280    BIGNUM *val[TABLE_SIZE];
281    BN_RECP_CTX recp;
282
283    if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
284            || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
285            || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
286        /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
287        BNerr(BN_F_BN_MOD_EXP_RECP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
288        return 0;
289    }
290
291    bits = BN_num_bits(p);
292    if (bits == 0) {
293        /* x**0 mod 1 is still zero. */
294        if (BN_is_one(m)) {
295            ret = 1;
296            BN_zero(r);
297        } else {
298            ret = BN_one(r);
299        }
300        return ret;
301    }
302
303    BN_CTX_start(ctx);
304    aa = BN_CTX_get(ctx);
305    val[0] = BN_CTX_get(ctx);
306    if (!aa || !val[0])
307        goto err;
308
309    BN_RECP_CTX_init(&recp);
310    if (m->neg) {
311        /* ignore sign of 'm' */
312        if (!BN_copy(aa, m))
313            goto err;
314        aa->neg = 0;
315        if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0)
316            goto err;
317    } else {
318        if (BN_RECP_CTX_set(&recp, m, ctx) <= 0)
319            goto err;
320    }
321
322    if (!BN_nnmod(val[0], a, m, ctx))
323        goto err;               /* 1 */
324    if (BN_is_zero(val[0])) {
325        BN_zero(r);
326        ret = 1;
327        goto err;
328    }
329
330    window = BN_window_bits_for_exponent_size(bits);
331    if (window > 1) {
332        if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx))
333            goto err;           /* 2 */
334        j = 1 << (window - 1);
335        for (i = 1; i < j; i++) {
336            if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
337                !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx))
338                goto err;
339        }
340    }
341
342    start = 1;                  /* This is used to avoid multiplication etc
343                                 * when there is only the value '1' in the
344                                 * buffer. */
345    wvalue = 0;                 /* The 'value' of the window */
346    wstart = bits - 1;          /* The top bit of the window */
347    wend = 0;                   /* The bottom bit of the window */
348
349    if (!BN_one(r))
350        goto err;
351
352    for (;;) {
353        if (BN_is_bit_set(p, wstart) == 0) {
354            if (!start)
355                if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
356                    goto err;
357            if (wstart == 0)
358                break;
359            wstart--;
360            continue;
361        }
362        /*
363         * We now have wstart on a 'set' bit, we now need to work out how bit
364         * a window to do.  To do this we need to scan forward until the last
365         * set bit before the end of the window
366         */
367        j = wstart;
368        wvalue = 1;
369        wend = 0;
370        for (i = 1; i < window; i++) {
371            if (wstart - i < 0)
372                break;
373            if (BN_is_bit_set(p, wstart - i)) {
374                wvalue <<= (i - wend);
375                wvalue |= 1;
376                wend = i;
377            }
378        }
379
380        /* wend is the size of the current window */
381        j = wend + 1;
382        /* add the 'bytes above' */
383        if (!start)
384            for (i = 0; i < j; i++) {
385                if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
386                    goto err;
387            }
388
389        /* wvalue will be an odd number < 2^window */
390        if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx))
391            goto err;
392
393        /* move the 'window' down further */
394        wstart -= wend + 1;
395        wvalue = 0;
396        start = 0;
397        if (wstart < 0)
398            break;
399    }
400    ret = 1;
401 err:
402    BN_CTX_end(ctx);
403    BN_RECP_CTX_free(&recp);
404    bn_check_top(r);
405    return (ret);
406}
407
408int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
409                    const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
410{
411    int i, j, bits, ret = 0, wstart, wend, window, wvalue;
412    int start = 1;
413    BIGNUM *d, *r;
414    const BIGNUM *aa;
415    /* Table of variables obtained from 'ctx' */
416    BIGNUM *val[TABLE_SIZE];
417    BN_MONT_CTX *mont = NULL;
418
419    if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
420            || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
421            || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
422        return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont);
423    }
424
425    bn_check_top(a);
426    bn_check_top(p);
427    bn_check_top(m);
428
429    if (!BN_is_odd(m)) {
430        BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS);
431        return (0);
432    }
433    bits = BN_num_bits(p);
434    if (bits == 0) {
435        /* x**0 mod 1 is still zero. */
436        if (BN_is_one(m)) {
437            ret = 1;
438            BN_zero(rr);
439        } else {
440            ret = BN_one(rr);
441        }
442        return ret;
443    }
444
445    BN_CTX_start(ctx);
446    d = BN_CTX_get(ctx);
447    r = BN_CTX_get(ctx);
448    val[0] = BN_CTX_get(ctx);
449    if (!d || !r || !val[0])
450        goto err;
451
452    /*
453     * If this is not done, things will break in the montgomery part
454     */
455
456    if (in_mont != NULL)
457        mont = in_mont;
458    else {
459        if ((mont = BN_MONT_CTX_new()) == NULL)
460            goto err;
461        if (!BN_MONT_CTX_set(mont, m, ctx))
462            goto err;
463    }
464
465    if (a->neg || BN_ucmp(a, m) >= 0) {
466        if (!BN_nnmod(val[0], a, m, ctx))
467            goto err;
468        aa = val[0];
469    } else
470        aa = a;
471    if (BN_is_zero(aa)) {
472        BN_zero(rr);
473        ret = 1;
474        goto err;
475    }
476    if (!BN_to_montgomery(val[0], aa, mont, ctx))
477        goto err;               /* 1 */
478
479    window = BN_window_bits_for_exponent_size(bits);
480    if (window > 1) {
481        if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx))
482            goto err;           /* 2 */
483        j = 1 << (window - 1);
484        for (i = 1; i < j; i++) {
485            if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
486                !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx))
487                goto err;
488        }
489    }
490
491    start = 1;                  /* This is used to avoid multiplication etc
492                                 * when there is only the value '1' in the
493                                 * buffer. */
494    wvalue = 0;                 /* The 'value' of the window */
495    wstart = bits - 1;          /* The top bit of the window */
496    wend = 0;                   /* The bottom bit of the window */
497
498#if 1                           /* by Shay Gueron's suggestion */
499    j = m->top;                 /* borrow j */
500    if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
501        if (bn_wexpand(r, j) == NULL)
502            goto err;
503        /* 2^(top*BN_BITS2) - m */
504        r->d[0] = (0 - m->d[0]) & BN_MASK2;
505        for (i = 1; i < j; i++)
506            r->d[i] = (~m->d[i]) & BN_MASK2;
507        r->top = j;
508        /*
509         * Upper words will be zero if the corresponding words of 'm' were
510         * 0xfff[...], so decrement r->top accordingly.
511         */
512        bn_correct_top(r);
513    } else
514#endif
515    if (!BN_to_montgomery(r, BN_value_one(), mont, ctx))
516        goto err;
517    for (;;) {
518        if (BN_is_bit_set(p, wstart) == 0) {
519            if (!start) {
520                if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
521                    goto err;
522            }
523            if (wstart == 0)
524                break;
525            wstart--;
526            continue;
527        }
528        /*
529         * We now have wstart on a 'set' bit, we now need to work out how bit
530         * a window to do.  To do this we need to scan forward until the last
531         * set bit before the end of the window
532         */
533        j = wstart;
534        wvalue = 1;
535        wend = 0;
536        for (i = 1; i < window; i++) {
537            if (wstart - i < 0)
538                break;
539            if (BN_is_bit_set(p, wstart - i)) {
540                wvalue <<= (i - wend);
541                wvalue |= 1;
542                wend = i;
543            }
544        }
545
546        /* wend is the size of the current window */
547        j = wend + 1;
548        /* add the 'bytes above' */
549        if (!start)
550            for (i = 0; i < j; i++) {
551                if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
552                    goto err;
553            }
554
555        /* wvalue will be an odd number < 2^window */
556        if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx))
557            goto err;
558
559        /* move the 'window' down further */
560        wstart -= wend + 1;
561        wvalue = 0;
562        start = 0;
563        if (wstart < 0)
564            break;
565    }
566#if defined(SPARC_T4_MONT)
567    if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
568        j = mont->N.top;        /* borrow j */
569        val[0]->d[0] = 1;       /* borrow val[0] */
570        for (i = 1; i < j; i++)
571            val[0]->d[i] = 0;
572        val[0]->top = j;
573        if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx))
574            goto err;
575    } else
576#endif
577    if (!BN_from_montgomery(rr, r, mont, ctx))
578        goto err;
579    ret = 1;
580 err:
581    if ((in_mont == NULL) && (mont != NULL))
582        BN_MONT_CTX_free(mont);
583    BN_CTX_end(ctx);
584    bn_check_top(rr);
585    return (ret);
586}
587
588#if defined(SPARC_T4_MONT)
589static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos)
590{
591    BN_ULONG ret = 0;
592    int wordpos;
593
594    wordpos = bitpos / BN_BITS2;
595    bitpos %= BN_BITS2;
596    if (wordpos >= 0 && wordpos < a->top) {
597        ret = a->d[wordpos] & BN_MASK2;
598        if (bitpos) {
599            ret >>= bitpos;
600            if (++wordpos < a->top)
601                ret |= a->d[wordpos] << (BN_BITS2 - bitpos);
602        }
603    }
604
605    return ret & BN_MASK2;
606}
607#endif
608
609/*
610 * BN_mod_exp_mont_consttime() stores the precomputed powers in a specific
611 * layout so that accessing any of these table values shows the same access
612 * pattern as far as cache lines are concerned.  The following functions are
613 * used to transfer a BIGNUM from/to that table.
614 */
615
616static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top,
617                                        unsigned char *buf, int idx,
618                                        int window)
619{
620    int i, j;
621    int width = 1 << window;
622    BN_ULONG *table = (BN_ULONG *)buf;
623
624    if (top > b->top)
625        top = b->top;           /* this works because 'buf' is explicitly
626                                 * zeroed */
627    for (i = 0, j = idx; i < top; i++, j += width) {
628        table[j] = b->d[i];
629    }
630
631    return 1;
632}
633
634static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top,
635                                          unsigned char *buf, int idx,
636                                          int window)
637{
638    int i, j;
639    int width = 1 << window;
640    volatile BN_ULONG *table = (volatile BN_ULONG *)buf;
641
642    if (bn_wexpand(b, top) == NULL)
643        return 0;
644
645    if (window <= 3) {
646        for (i = 0; i < top; i++, table += width) {
647            BN_ULONG acc = 0;
648
649            for (j = 0; j < width; j++) {
650                acc |= table[j] &
651                       ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
652            }
653
654            b->d[i] = acc;
655        }
656    } else {
657        int xstride = 1 << (window - 2);
658        BN_ULONG y0, y1, y2, y3;
659
660        i = idx >> (window - 2);        /* equivalent of idx / xstride */
661        idx &= xstride - 1;             /* equivalent of idx % xstride */
662
663        y0 = (BN_ULONG)0 - (constant_time_eq_int(i,0)&1);
664        y1 = (BN_ULONG)0 - (constant_time_eq_int(i,1)&1);
665        y2 = (BN_ULONG)0 - (constant_time_eq_int(i,2)&1);
666        y3 = (BN_ULONG)0 - (constant_time_eq_int(i,3)&1);
667
668        for (i = 0; i < top; i++, table += width) {
669            BN_ULONG acc = 0;
670
671            for (j = 0; j < xstride; j++) {
672                acc |= ( (table[j + 0 * xstride] & y0) |
673                         (table[j + 1 * xstride] & y1) |
674                         (table[j + 2 * xstride] & y2) |
675                         (table[j + 3 * xstride] & y3) )
676                       & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
677            }
678
679            b->d[i] = acc;
680        }
681    }
682
683    b->top = top;
684    bn_correct_top(b);
685    return 1;
686}
687
688/*
689 * Given a pointer value, compute the next address that is a cache line
690 * multiple.
691 */
692#define MOD_EXP_CTIME_ALIGN(x_) \
693        ((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK))))
694
695/*
696 * This variant of BN_mod_exp_mont() uses fixed windows and the special
697 * precomputation memory layout to limit data-dependency to a minimum to
698 * protect secret exponents (cf. the hyper-threading timing attacks pointed
699 * out by Colin Percival,
700 * http://www.daemonology.net/hyperthreading-considered-harmful/)
701 */
702int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
703                              const BIGNUM *m, BN_CTX *ctx,
704                              BN_MONT_CTX *in_mont)
705{
706    int i, bits, ret = 0, window, wvalue;
707    int top;
708    BN_MONT_CTX *mont = NULL;
709
710    int numPowers;
711    unsigned char *powerbufFree = NULL;
712    int powerbufLen = 0;
713    unsigned char *powerbuf = NULL;
714    BIGNUM tmp, am;
715#if defined(SPARC_T4_MONT)
716    unsigned int t4 = 0;
717#endif
718
719    bn_check_top(a);
720    bn_check_top(p);
721    bn_check_top(m);
722
723    if (!BN_is_odd(m)) {
724        BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS);
725        return (0);
726    }
727
728    top = m->top;
729
730    /*
731     * Use all bits stored in |p|, rather than |BN_num_bits|, so we do not leak
732     * whether the top bits are zero.
733     */
734    bits = p->top * BN_BITS2;
735    if (bits == 0) {
736        /* x**0 mod 1 is still zero. */
737        if (BN_is_one(m)) {
738            ret = 1;
739            BN_zero(rr);
740        } else {
741            ret = BN_one(rr);
742        }
743        return ret;
744    }
745
746    BN_CTX_start(ctx);
747
748    /*
749     * Allocate a montgomery context if it was not supplied by the caller. If
750     * this is not done, things will break in the montgomery part.
751     */
752    if (in_mont != NULL)
753        mont = in_mont;
754    else {
755        if ((mont = BN_MONT_CTX_new()) == NULL)
756            goto err;
757        if (!BN_MONT_CTX_set(mont, m, ctx))
758            goto err;
759    }
760
761#ifdef RSAZ_ENABLED
762    /*
763     * If the size of the operands allow it, perform the optimized
764     * RSAZ exponentiation. For further information see
765     * crypto/bn/rsaz_exp.c and accompanying assembly modules.
766     */
767    if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024)
768        && rsaz_avx2_eligible()) {
769        if (NULL == bn_wexpand(rr, 16))
770            goto err;
771        RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d,
772                               mont->n0[0]);
773        rr->top = 16;
774        rr->neg = 0;
775        bn_correct_top(rr);
776        ret = 1;
777        goto err;
778    } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {
779        if (NULL == bn_wexpand(rr, 8))
780            goto err;
781        RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);
782        rr->top = 8;
783        rr->neg = 0;
784        bn_correct_top(rr);
785        ret = 1;
786        goto err;
787    }
788#endif
789
790    /* Get the window size to use with size of p. */
791    window = BN_window_bits_for_ctime_exponent_size(bits);
792#if defined(SPARC_T4_MONT)
793    if (window >= 5 && (top & 15) == 0 && top <= 64 &&
794        (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) ==
795        (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0]))
796        window = 5;
797    else
798#endif
799#if defined(OPENSSL_BN_ASM_MONT5)
800    if (window >= 5) {
801        window = 5;             /* ~5% improvement for RSA2048 sign, and even
802                                 * for RSA4096 */
803        /* reserve space for mont->N.d[] copy */
804        powerbufLen += top * sizeof(mont->N.d[0]);
805    }
806#endif
807    (void)0;
808
809    /*
810     * Allocate a buffer large enough to hold all of the pre-computed powers
811     * of am, am itself and tmp.
812     */
813    numPowers = 1 << window;
814    powerbufLen += sizeof(m->d[0]) * (top * numPowers +
815                                      ((2 * top) >
816                                       numPowers ? (2 * top) : numPowers));
817#ifdef alloca
818    if (powerbufLen < 3072)
819        powerbufFree =
820            alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
821    else
822#endif
823        if ((powerbufFree =
824             (unsigned char *)OPENSSL_malloc(powerbufLen +
825                                             MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))
826            == NULL)
827        goto err;
828
829    powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
830    memset(powerbuf, 0, powerbufLen);
831
832#ifdef alloca
833    if (powerbufLen < 3072)
834        powerbufFree = NULL;
835#endif
836
837    /* lay down tmp and am right after powers table */
838    tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
839    am.d = tmp.d + top;
840    tmp.top = am.top = 0;
841    tmp.dmax = am.dmax = top;
842    tmp.neg = am.neg = 0;
843    tmp.flags = am.flags = BN_FLG_STATIC_DATA;
844
845    /* prepare a^0 in Montgomery domain */
846#if 1                           /* by Shay Gueron's suggestion */
847    if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
848        /* 2^(top*BN_BITS2) - m */
849        tmp.d[0] = (0 - m->d[0]) & BN_MASK2;
850        for (i = 1; i < top; i++)
851            tmp.d[i] = (~m->d[i]) & BN_MASK2;
852        tmp.top = top;
853    } else
854#endif
855    if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx))
856        goto err;
857
858    /* prepare a^1 in Montgomery domain */
859    if (a->neg || BN_ucmp(a, m) >= 0) {
860        if (!BN_mod(&am, a, m, ctx))
861            goto err;
862        if (!BN_to_montgomery(&am, &am, mont, ctx))
863            goto err;
864    } else if (!BN_to_montgomery(&am, a, mont, ctx))
865        goto err;
866
867#if defined(SPARC_T4_MONT)
868    if (t4) {
869        typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np,
870                                       const BN_ULONG *n0, const void *table,
871                                       int power, int bits);
872        int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np,
873                              const BN_ULONG *n0, const void *table,
874                              int power, int bits);
875        int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np,
876                               const BN_ULONG *n0, const void *table,
877                               int power, int bits);
878        int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np,
879                               const BN_ULONG *n0, const void *table,
880                               int power, int bits);
881        int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np,
882                               const BN_ULONG *n0, const void *table,
883                               int power, int bits);
884        static const bn_pwr5_mont_f pwr5_funcs[4] = {
885            bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16,
886            bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32
887        };
888        bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1];
889
890        typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap,
891                                      const void *bp, const BN_ULONG *np,
892                                      const BN_ULONG *n0);
893        int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp,
894                             const BN_ULONG *np, const BN_ULONG *n0);
895        int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap,
896                              const void *bp, const BN_ULONG *np,
897                              const BN_ULONG *n0);
898        int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap,
899                              const void *bp, const BN_ULONG *np,
900                              const BN_ULONG *n0);
901        int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap,
902                              const void *bp, const BN_ULONG *np,
903                              const BN_ULONG *n0);
904        static const bn_mul_mont_f mul_funcs[4] = {
905            bn_mul_mont_t4_8, bn_mul_mont_t4_16,
906            bn_mul_mont_t4_24, bn_mul_mont_t4_32
907        };
908        bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1];
909
910        void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap,
911                              const void *bp, const BN_ULONG *np,
912                              const BN_ULONG *n0, int num);
913        void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap,
914                            const void *bp, const BN_ULONG *np,
915                            const BN_ULONG *n0, int num);
916        void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap,
917                                    const void *table, const BN_ULONG *np,
918                                    const BN_ULONG *n0, int num, int power);
919        void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num,
920                                   void *table, size_t power);
921        void bn_gather5_t4(BN_ULONG *out, size_t num,
922                           void *table, size_t power);
923        void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num);
924
925        BN_ULONG *np = mont->N.d, *n0 = mont->n0;
926        int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less
927                                                * than 32 */
928
929        /*
930         * BN_to_montgomery can contaminate words above .top [in
931         * BN_DEBUG[_DEBUG] build]...
932         */
933        for (i = am.top; i < top; i++)
934            am.d[i] = 0;
935        for (i = tmp.top; i < top; i++)
936            tmp.d[i] = 0;
937
938        bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0);
939        bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1);
940        if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) &&
941            !(*mul_worker) (tmp.d, am.d, am.d, np, n0))
942            bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top);
943        bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2);
944
945        for (i = 3; i < 32; i++) {
946            /* Calculate a^i = a^(i-1) * a */
947            if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) &&
948                !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0))
949                bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top);
950            bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i);
951        }
952
953        /* switch to 64-bit domain */
954        np = alloca(top * sizeof(BN_ULONG));
955        top /= 2;
956        bn_flip_t4(np, mont->N.d, top);
957
958        bits--;
959        for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
960            wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
961        bn_gather5_t4(tmp.d, top, powerbuf, wvalue);
962
963        /*
964         * Scan the exponent one window at a time starting from the most
965         * significant bits.
966         */
967        while (bits >= 0) {
968            if (bits < stride)
969                stride = bits + 1;
970            bits -= stride;
971            wvalue = bn_get_bits(p, bits + 1);
972
973            if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
974                continue;
975            /* retry once and fall back */
976            if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
977                continue;
978
979            bits += stride - 5;
980            wvalue >>= stride - 5;
981            wvalue &= 31;
982            bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
983            bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
984            bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
985            bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
986            bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
987            bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top,
988                                   wvalue);
989        }
990
991        bn_flip_t4(tmp.d, tmp.d, top);
992        top *= 2;
993        /* back to 32-bit domain */
994        tmp.top = top;
995        bn_correct_top(&tmp);
996        OPENSSL_cleanse(np, top * sizeof(BN_ULONG));
997    } else
998#endif
999#if defined(OPENSSL_BN_ASM_MONT5)
1000    if (window == 5 && top > 1) {
1001        /*
1002         * This optimization uses ideas from http://eprint.iacr.org/2011/239,
1003         * specifically optimization of cache-timing attack countermeasures
1004         * and pre-computation optimization.
1005         */
1006
1007        /*
1008         * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
1009         * 512-bit RSA is hardly relevant, we omit it to spare size...
1010         */
1011        void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
1012                                 const void *table, const BN_ULONG *np,
1013                                 const BN_ULONG *n0, int num, int power);
1014        void bn_scatter5(const BN_ULONG *inp, size_t num,
1015                         void *table, size_t power);
1016        void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
1017        void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,
1018                       const void *table, const BN_ULONG *np,
1019                       const BN_ULONG *n0, int num, int power);
1020        int bn_get_bits5(const BN_ULONG *ap, int off);
1021        int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap,
1022                               const BN_ULONG *not_used, const BN_ULONG *np,
1023                               const BN_ULONG *n0, int num);
1024
1025        BN_ULONG *n0 = mont->n0, *np;
1026
1027        /*
1028         * BN_to_montgomery can contaminate words above .top [in
1029         * BN_DEBUG[_DEBUG] build]...
1030         */
1031        for (i = am.top; i < top; i++)
1032            am.d[i] = 0;
1033        for (i = tmp.top; i < top; i++)
1034            tmp.d[i] = 0;
1035
1036        /*
1037         * copy mont->N.d[] to improve cache locality
1038         */
1039        for (np = am.d + top, i = 0; i < top; i++)
1040            np[i] = mont->N.d[i];
1041
1042        bn_scatter5(tmp.d, top, powerbuf, 0);
1043        bn_scatter5(am.d, am.top, powerbuf, 1);
1044        bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
1045        bn_scatter5(tmp.d, top, powerbuf, 2);
1046
1047# if 0
1048        for (i = 3; i < 32; i++) {
1049            /* Calculate a^i = a^(i-1) * a */
1050            bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
1051            bn_scatter5(tmp.d, top, powerbuf, i);
1052        }
1053# else
1054        /* same as above, but uses squaring for 1/2 of operations */
1055        for (i = 4; i < 32; i *= 2) {
1056            bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1057            bn_scatter5(tmp.d, top, powerbuf, i);
1058        }
1059        for (i = 3; i < 8; i += 2) {
1060            int j;
1061            bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
1062            bn_scatter5(tmp.d, top, powerbuf, i);
1063            for (j = 2 * i; j < 32; j *= 2) {
1064                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1065                bn_scatter5(tmp.d, top, powerbuf, j);
1066            }
1067        }
1068        for (; i < 16; i += 2) {
1069            bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
1070            bn_scatter5(tmp.d, top, powerbuf, i);
1071            bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1072            bn_scatter5(tmp.d, top, powerbuf, 2 * i);
1073        }
1074        for (; i < 32; i += 2) {
1075            bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
1076            bn_scatter5(tmp.d, top, powerbuf, i);
1077        }
1078# endif
1079        bits--;
1080        for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
1081            wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1082        bn_gather5(tmp.d, top, powerbuf, wvalue);
1083
1084        /*
1085         * Scan the exponent one window at a time starting from the most
1086         * significant bits.
1087         */
1088        if (top & 7)
1089            while (bits >= 0) {
1090                for (wvalue = 0, i = 0; i < 5; i++, bits--)
1091                    wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1092
1093                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1094                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1095                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1096                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1097                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1098                bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,
1099                                    wvalue);
1100        } else {
1101            while (bits >= 0) {
1102                wvalue = bn_get_bits5(p->d, bits - 4);
1103                bits -= 5;
1104                bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
1105            }
1106        }
1107
1108        ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top);
1109        tmp.top = top;
1110        bn_correct_top(&tmp);
1111        if (ret) {
1112            if (!BN_copy(rr, &tmp))
1113                ret = 0;
1114            goto err;           /* non-zero ret means it's not error */
1115        }
1116    } else
1117#endif
1118    {
1119        if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window))
1120            goto err;
1121        if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window))
1122            goto err;
1123
1124        /*
1125         * If the window size is greater than 1, then calculate
1126         * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
1127         * powers could instead be computed as (a^(i/2))^2 to use the slight
1128         * performance advantage of sqr over mul).
1129         */
1130        if (window > 1) {
1131            if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx))
1132                goto err;
1133            if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
1134                                              window))
1135                goto err;
1136            for (i = 3; i < numPowers; i++) {
1137                /* Calculate a^i = a^(i-1) * a */
1138                if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx))
1139                    goto err;
1140                if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
1141                                                  window))
1142                    goto err;
1143            }
1144        }
1145
1146        bits--;
1147        for (wvalue = 0, i = bits % window; i >= 0; i--, bits--)
1148            wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1149        if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue,
1150                                            window))
1151            goto err;
1152
1153        /*
1154         * Scan the exponent one window at a time starting from the most
1155         * significant bits.
1156         */
1157        while (bits >= 0) {
1158            wvalue = 0;         /* The 'value' of the window */
1159
1160            /* Scan the window, squaring the result as we go */
1161            for (i = 0; i < window; i++, bits--) {
1162                if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx))
1163                    goto err;
1164                wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
1165            }
1166
1167            /*
1168             * Fetch the appropriate pre-computed value from the pre-buf
1169             */
1170            if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue,
1171                                                window))
1172                goto err;
1173
1174            /* Multiply the result into the intermediate result */
1175            if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx))
1176                goto err;
1177        }
1178    }
1179
1180    /* Convert the final result from montgomery to standard format */
1181#if defined(SPARC_T4_MONT)
1182    if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
1183        am.d[0] = 1;            /* borrow am */
1184        for (i = 1; i < top; i++)
1185            am.d[i] = 0;
1186        if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))
1187            goto err;
1188    } else
1189#endif
1190    if (!BN_from_montgomery(rr, &tmp, mont, ctx))
1191        goto err;
1192    ret = 1;
1193 err:
1194    if ((in_mont == NULL) && (mont != NULL))
1195        BN_MONT_CTX_free(mont);
1196    if (powerbuf != NULL) {
1197        OPENSSL_cleanse(powerbuf, powerbufLen);
1198        if (powerbufFree)
1199            OPENSSL_free(powerbufFree);
1200    }
1201    BN_CTX_end(ctx);
1202    return (ret);
1203}
1204
1205int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
1206                         const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
1207{
1208    BN_MONT_CTX *mont = NULL;
1209    int b, bits, ret = 0;
1210    int r_is_one;
1211    BN_ULONG w, next_w;
1212    BIGNUM *d, *r, *t;
1213    BIGNUM *swap_tmp;
1214#define BN_MOD_MUL_WORD(r, w, m) \
1215                (BN_mul_word(r, (w)) && \
1216                (/* BN_ucmp(r, (m)) < 0 ? 1 :*/  \
1217                        (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
1218    /*
1219     * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
1220     * probably more overhead than always using BN_mod (which uses BN_copy if
1221     * a similar test returns true).
1222     */
1223    /*
1224     * We can use BN_mod and do not need BN_nnmod because our accumulator is
1225     * never negative (the result of BN_mod does not depend on the sign of
1226     * the modulus).
1227     */
1228#define BN_TO_MONTGOMERY_WORD(r, w, mont) \
1229                (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
1230
1231    if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
1232            || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
1233        /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1234        BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1235        return 0;
1236    }
1237
1238    bn_check_top(p);
1239    bn_check_top(m);
1240
1241    if (!BN_is_odd(m)) {
1242        BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS);
1243        return (0);
1244    }
1245    if (m->top == 1)
1246        a %= m->d[0];           /* make sure that 'a' is reduced */
1247
1248    bits = BN_num_bits(p);
1249    if (bits == 0) {
1250        /* x**0 mod 1 is still zero. */
1251        if (BN_is_one(m)) {
1252            ret = 1;
1253            BN_zero(rr);
1254        } else {
1255            ret = BN_one(rr);
1256        }
1257        return ret;
1258    }
1259    if (a == 0) {
1260        BN_zero(rr);
1261        ret = 1;
1262        return ret;
1263    }
1264
1265    BN_CTX_start(ctx);
1266    d = BN_CTX_get(ctx);
1267    r = BN_CTX_get(ctx);
1268    t = BN_CTX_get(ctx);
1269    if (d == NULL || r == NULL || t == NULL)
1270        goto err;
1271
1272    if (in_mont != NULL)
1273        mont = in_mont;
1274    else {
1275        if ((mont = BN_MONT_CTX_new()) == NULL)
1276            goto err;
1277        if (!BN_MONT_CTX_set(mont, m, ctx))
1278            goto err;
1279    }
1280
1281    r_is_one = 1;               /* except for Montgomery factor */
1282
1283    /* bits-1 >= 0 */
1284
1285    /* The result is accumulated in the product r*w. */
1286    w = a;                      /* bit 'bits-1' of 'p' is always set */
1287    for (b = bits - 2; b >= 0; b--) {
1288        /* First, square r*w. */
1289        next_w = w * w;
1290        if ((next_w / w) != w) { /* overflow */
1291            if (r_is_one) {
1292                if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1293                    goto err;
1294                r_is_one = 0;
1295            } else {
1296                if (!BN_MOD_MUL_WORD(r, w, m))
1297                    goto err;
1298            }
1299            next_w = 1;
1300        }
1301        w = next_w;
1302        if (!r_is_one) {
1303            if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
1304                goto err;
1305        }
1306
1307        /* Second, multiply r*w by 'a' if exponent bit is set. */
1308        if (BN_is_bit_set(p, b)) {
1309            next_w = w * a;
1310            if ((next_w / a) != w) { /* overflow */
1311                if (r_is_one) {
1312                    if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1313                        goto err;
1314                    r_is_one = 0;
1315                } else {
1316                    if (!BN_MOD_MUL_WORD(r, w, m))
1317                        goto err;
1318                }
1319                next_w = a;
1320            }
1321            w = next_w;
1322        }
1323    }
1324
1325    /* Finally, set r:=r*w. */
1326    if (w != 1) {
1327        if (r_is_one) {
1328            if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1329                goto err;
1330            r_is_one = 0;
1331        } else {
1332            if (!BN_MOD_MUL_WORD(r, w, m))
1333                goto err;
1334        }
1335    }
1336
1337    if (r_is_one) {             /* can happen only if a == 1 */
1338        if (!BN_one(rr))
1339            goto err;
1340    } else {
1341        if (!BN_from_montgomery(rr, r, mont, ctx))
1342            goto err;
1343    }
1344    ret = 1;
1345 err:
1346    if ((in_mont == NULL) && (mont != NULL))
1347        BN_MONT_CTX_free(mont);
1348    BN_CTX_end(ctx);
1349    bn_check_top(rr);
1350    return (ret);
1351}
1352
1353/* The old fallback, simple version :-) */
1354int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1355                      const BIGNUM *m, BN_CTX *ctx)
1356{
1357    int i, j, bits, ret = 0, wstart, wend, window, wvalue;
1358    int start = 1;
1359    BIGNUM *d;
1360    /* Table of variables obtained from 'ctx' */
1361    BIGNUM *val[TABLE_SIZE];
1362
1363    if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
1364            || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
1365            || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
1366        /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1367        BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1368        return 0;
1369    }
1370
1371    bits = BN_num_bits(p);
1372   if (bits == 0) {
1373        /* x**0 mod 1 is still zero. */
1374        if (BN_is_one(m)) {
1375            ret = 1;
1376            BN_zero(r);
1377        } else {
1378            ret = BN_one(r);
1379        }
1380        return ret;
1381    }
1382
1383    BN_CTX_start(ctx);
1384    d = BN_CTX_get(ctx);
1385    val[0] = BN_CTX_get(ctx);
1386    if (!d || !val[0])
1387        goto err;
1388
1389    if (!BN_nnmod(val[0], a, m, ctx))
1390        goto err;               /* 1 */
1391    if (BN_is_zero(val[0])) {
1392        BN_zero(r);
1393        ret = 1;
1394        goto err;
1395    }
1396
1397    window = BN_window_bits_for_exponent_size(bits);
1398    if (window > 1) {
1399        if (!BN_mod_mul(d, val[0], val[0], m, ctx))
1400            goto err;           /* 2 */
1401        j = 1 << (window - 1);
1402        for (i = 1; i < j; i++) {
1403            if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
1404                !BN_mod_mul(val[i], val[i - 1], d, m, ctx))
1405                goto err;
1406        }
1407    }
1408
1409    start = 1;                  /* This is used to avoid multiplication etc
1410                                 * when there is only the value '1' in the
1411                                 * buffer. */
1412    wvalue = 0;                 /* The 'value' of the window */
1413    wstart = bits - 1;          /* The top bit of the window */
1414    wend = 0;                   /* The bottom bit of the window */
1415
1416    if (!BN_one(r))
1417        goto err;
1418
1419    for (;;) {
1420        if (BN_is_bit_set(p, wstart) == 0) {
1421            if (!start)
1422                if (!BN_mod_mul(r, r, r, m, ctx))
1423                    goto err;
1424            if (wstart == 0)
1425                break;
1426            wstart--;
1427            continue;
1428        }
1429        /*
1430         * We now have wstart on a 'set' bit, we now need to work out how bit
1431         * a window to do.  To do this we need to scan forward until the last
1432         * set bit before the end of the window
1433         */
1434        j = wstart;
1435        wvalue = 1;
1436        wend = 0;
1437        for (i = 1; i < window; i++) {
1438            if (wstart - i < 0)
1439                break;
1440            if (BN_is_bit_set(p, wstart - i)) {
1441                wvalue <<= (i - wend);
1442                wvalue |= 1;
1443                wend = i;
1444            }
1445        }
1446
1447        /* wend is the size of the current window */
1448        j = wend + 1;
1449        /* add the 'bytes above' */
1450        if (!start)
1451            for (i = 0; i < j; i++) {
1452                if (!BN_mod_mul(r, r, r, m, ctx))
1453                    goto err;
1454            }
1455
1456        /* wvalue will be an odd number < 2^window */
1457        if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
1458            goto err;
1459
1460        /* move the 'window' down further */
1461        wstart -= wend + 1;
1462        wvalue = 0;
1463        start = 0;
1464        if (wstart < 0)
1465            break;
1466    }
1467    ret = 1;
1468 err:
1469    BN_CTX_end(ctx);
1470    bn_check_top(r);
1471    return (ret);
1472}
1473