Coverage Report

Created: 2026-10-28 06:28

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