Coverage Report

Created: 2023-06-08 06:43

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