Coverage Report

Created: 2026-09-12 06:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl35/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 "crypto/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
692k
#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
225k
{
100
225k
    int ret;
101
102
225k
    bn_check_top(a);
103
225k
    bn_check_top(p);
104
225k
    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
225k
#define MONT_MUL_MOD
138
225k
#define MONT_EXP_WORD
139
225k
#define RECP_MUL_MOD
140
141
225k
#ifdef MONT_MUL_MOD
142
225k
    if (BN_is_odd(m)) {
143
214k
#ifdef MONT_EXP_WORD
144
214k
        if (a->top == 1 && !a->neg
145
76.2k
            && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0)
146
75.3k
            && (BN_get_flags(a, BN_FLG_CONSTTIME) == 0)
147
75.3k
            && (BN_get_flags(m, BN_FLG_CONSTTIME) == 0)) {
148
75.3k
            BN_ULONG A = a->d[0];
149
75.3k
            ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL);
150
75.3k
        } else
151
139k
#endif
152
139k
            ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL);
153
214k
    } else
154
11.2k
#endif
155
11.2k
#ifdef RECP_MUL_MOD
156
11.2k
    {
157
11.2k
        ret = BN_mod_exp_recp(r, a, p, m, ctx);
158
11.2k
    }
159
#else
160
    {
161
        ret = BN_mod_exp_simple(r, a, p, m, ctx);
162
    }
163
#endif
164
165
225k
    bn_check_top(r);
166
225k
    return ret;
167
225k
}
168
169
int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
170
    const BIGNUM *m, BN_CTX *ctx)
171
8.76k
{
172
8.76k
    int i, j, bits, ret = 0, wstart, wend, window;
173
8.76k
    int start = 1;
174
8.76k
    BIGNUM *aa;
175
    /* Table of variables obtained from 'ctx' */
176
8.76k
    BIGNUM *val[TABLE_SIZE];
177
8.76k
    BN_RECP_CTX recp;
178
179
8.76k
    if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
180
8.73k
        || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
181
8.73k
        || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
182
        /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
183
30
        ERR_raise(ERR_LIB_BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
184
30
        return 0;
185
30
    }
186
187
8.73k
    bits = BN_num_bits(p);
188
8.73k
    if (bits == 0) {
189
        /* x**0 mod 1, or x**0 mod -1 is still zero. */
190
306
        if (BN_abs_is_word(m, 1)) {
191
0
            ret = 1;
192
0
            BN_zero(r);
193
306
        } else {
194
306
            ret = BN_one(r);
195
306
        }
196
306
        return ret;
197
306
    }
198
199
8.42k
    BN_RECP_CTX_init(&recp);
200
201
8.42k
    BN_CTX_start(ctx);
202
8.42k
    aa = BN_CTX_get(ctx);
203
8.42k
    val[0] = BN_CTX_get(ctx);
204
8.42k
    if (val[0] == NULL)
205
0
        goto err;
206
207
8.42k
    if (m->neg) {
208
        /* ignore sign of 'm' */
209
1.93k
        if (!BN_copy(aa, m))
210
0
            goto err;
211
1.93k
        aa->neg = 0;
212
1.93k
        if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0)
213
0
            goto err;
214
6.49k
    } else {
215
6.49k
        if (BN_RECP_CTX_set(&recp, m, ctx) <= 0)
216
0
            goto err;
217
6.49k
    }
218
219
8.42k
    if (!BN_nnmod(val[0], a, m, ctx))
220
0
        goto err; /* 1 */
221
8.42k
    if (BN_is_zero(val[0])) {
222
96
        BN_zero(r);
223
96
        ret = 1;
224
96
        goto err;
225
96
    }
226
227
8.33k
    window = BN_window_bits_for_exponent_size(bits);
228
8.33k
    if (window > 1) {
229
2.11k
        if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx))
230
0
            goto err; /* 2 */
231
2.11k
        j = 1 << (window - 1);
232
18.9k
        for (i = 1; i < j; i++) {
233
16.8k
            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
16.8k
        }
236
2.11k
    }
237
238
8.33k
    start = 1; /* This is used to avoid multiplication etc
239
                * when there is only the value '1' in the
240
                * buffer. */
241
8.33k
    wstart = bits - 1; /* The top bit of the window */
242
8.33k
    wend = 0; /* The bottom bit of the window */
243
244
8.33k
    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
8.33k
    if (!BN_one(r))
253
0
        goto err;
254
255
373k
    for (;;) {
256
373k
        int wvalue; /* The 'value' of the window */
257
258
373k
        if (BN_is_bit_set(p, wstart) == 0) {
259
278k
            if (!start)
260
278k
                if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
261
0
                    goto err;
262
278k
            if (wstart == 0)
263
3.88k
                break;
264
274k
            wstart--;
265
274k
            continue;
266
278k
        }
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
95.4k
        wvalue = 1;
273
95.4k
        wend = 0;
274
300k
        for (i = 1; i < window; i++) {
275
206k
            if (wstart - i < 0)
276
946
                break;
277
205k
            if (BN_is_bit_set(p, wstart - i)) {
278
120k
                wvalue <<= (i - wend);
279
120k
                wvalue |= 1;
280
120k
                wend = i;
281
120k
            }
282
205k
        }
283
284
        /* wend is the size of the current window */
285
95.4k
        j = wend + 1;
286
        /* add the 'bytes above' */
287
95.4k
        if (!start)
288
317k
            for (i = 0; i < j; i++) {
289
230k
                if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
290
0
                    goto err;
291
230k
            }
292
293
        /* wvalue will be an odd number < 2^window */
294
95.4k
        if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx))
295
0
            goto err;
296
297
        /* move the 'window' down further */
298
95.4k
        wstart -= wend + 1;
299
95.4k
        start = 0;
300
95.4k
        if (wstart < 0)
301
4.45k
            break;
302
95.4k
    }
303
8.33k
    ret = 1;
304
8.42k
err:
305
8.42k
    BN_CTX_end(ctx);
306
8.42k
    BN_RECP_CTX_free(&recp);
307
8.42k
    bn_check_top(r);
308
8.42k
    return ret;
309
8.33k
}
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
305k
{
314
305k
    int i, j, bits, ret = 0, wstart, wend, window;
315
305k
    int start = 1;
316
305k
    BIGNUM *d, *r;
317
305k
    const BIGNUM *aa;
318
    /* Table of variables obtained from 'ctx' */
319
305k
    BIGNUM *val[TABLE_SIZE];
320
305k
    BN_MONT_CTX *mont = NULL;
321
322
305k
    bn_check_top(a);
323
305k
    bn_check_top(p);
324
305k
    bn_check_top(m);
325
326
305k
    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
305k
    if (m->top <= BN_CONSTTIME_SIZE_LIMIT
332
305k
        && (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
333
293k
            || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
334
293k
            || BN_get_flags(m, BN_FLG_CONSTTIME) != 0)) {
335
55.6k
        return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont);
336
55.6k
    }
337
338
249k
    bits = BN_num_bits(p);
339
249k
    if (bits == 0) {
340
        /* x**0 mod 1, or x**0 mod -1 is still zero. */
341
1.03k
        if (BN_abs_is_word(m, 1)) {
342
17
            ret = 1;
343
17
            BN_zero(rr);
344
1.02k
        } else {
345
1.02k
            ret = BN_one(rr);
346
1.02k
        }
347
1.03k
        return ret;
348
1.03k
    }
349
350
248k
    BN_CTX_start(ctx);
351
248k
    d = BN_CTX_get(ctx);
352
248k
    r = BN_CTX_get(ctx);
353
248k
    val[0] = BN_CTX_get(ctx);
354
248k
    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
248k
    if (in_mont != NULL)
362
113k
        mont = in_mont;
363
135k
    else {
364
135k
        if ((mont = BN_MONT_CTX_new()) == NULL)
365
0
            goto err;
366
135k
        if (!BN_MONT_CTX_set(mont, m, ctx))
367
0
            goto err;
368
135k
    }
369
370
248k
    if (a->neg || BN_ucmp(a, m) >= 0) {
371
1.44k
        if (!BN_nnmod(val[0], a, m, ctx))
372
0
            goto err;
373
1.44k
        aa = val[0];
374
1.44k
    } else
375
246k
        aa = a;
376
248k
    if (!bn_to_mont_fixed_top(val[0], aa, mont, ctx))
377
0
        goto err; /* 1 */
378
379
248k
    window = BN_window_bits_for_exponent_size(bits);
380
248k
    if (window > 1) {
381
183k
        if (!bn_mul_mont_fixed_top(d, val[0], val[0], mont, ctx))
382
0
            goto err; /* 2 */
383
183k
        j = 1 << (window - 1);
384
1.76M
        for (i = 1; i < j; i++) {
385
1.57M
            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.57M
        }
388
183k
    }
389
390
248k
    start = 1; /* This is used to avoid multiplication etc
391
                * when there is only the value '1' in the
392
                * buffer. */
393
248k
    wstart = bits - 1; /* The top bit of the window */
394
248k
    wend = 0; /* The bottom bit of the window */
395
396
248k
#if 1 /* by Shay Gueron's suggestion */
397
248k
    j = m->top; /* borrow j */
398
248k
    if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
399
80.4k
        if (bn_wexpand(r, j) == NULL)
400
0
            goto err;
401
        /* 2^(top*BN_BITS2) - m */
402
80.4k
        r->d[0] = (0 - m->d[0]) & BN_MASK2;
403
970k
        for (i = 1; i < j; i++)
404
890k
            r->d[i] = (~m->d[i]) & BN_MASK2;
405
80.4k
        r->top = j;
406
80.4k
        r->flags |= BN_FLG_FIXED_TOP;
407
80.4k
    } else
408
167k
#endif
409
167k
        if (!bn_to_mont_fixed_top(r, BN_value_one(), mont, ctx))
410
0
        goto err;
411
26.2M
    for (;;) {
412
26.2M
        int wvalue; /* The 'value' of the window */
413
414
26.2M
        if (BN_is_bit_set(p, wstart) == 0) {
415
20.4M
            if (!start) {
416
20.4M
                if (!bn_mul_mont_fixed_top(r, r, r, mont, ctx))
417
0
                    goto err;
418
20.4M
            }
419
20.4M
            if (wstart == 0)
420
71.9k
                break;
421
20.4M
            wstart--;
422
20.4M
            continue;
423
20.4M
        }
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
5.79M
        wvalue = 1;
430
5.79M
        wend = 0;
431
23.8M
        for (i = 1; i < window; i++) {
432
18.1M
            if (wstart - i < 0)
433
102k
                break;
434
18.0M
            if (BN_is_bit_set(p, wstart - i)) {
435
14.8M
                wvalue <<= (i - wend);
436
14.8M
                wvalue |= 1;
437
14.8M
                wend = i;
438
14.8M
            }
439
18.0M
        }
440
441
        /* wend is the size of the current window */
442
5.79M
        j = wend + 1;
443
        /* add the 'bytes above' */
444
5.79M
        if (!start)
445
26.5M
            for (i = 0; i < j; i++) {
446
20.9M
                if (!bn_mul_mont_fixed_top(r, r, r, mont, ctx))
447
0
                    goto err;
448
20.9M
            }
449
450
        /* wvalue will be an odd number < 2^window */
451
5.79M
        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
5.79M
        wstart -= wend + 1;
456
5.79M
        start = 0;
457
5.79M
        if (wstart < 0)
458
176k
            break;
459
5.79M
    }
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
248k
        if (!BN_from_montgomery(rr, r, mont, ctx))
477
0
        goto err;
478
248k
    ret = 1;
479
248k
err:
480
248k
    if (in_mont == NULL)
481
135k
        BN_MONT_CTX_free(mont);
482
248k
    BN_CTX_end(ctx);
483
248k
    bn_check_top(rr);
484
248k
    return ret;
485
248k
}
486
487
static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos)
488
1.05M
{
489
1.05M
    BN_ULONG ret = 0;
490
1.05M
    int wordpos;
491
492
1.05M
    wordpos = bitpos / BN_BITS2;
493
1.05M
    bitpos %= BN_BITS2;
494
1.05M
    if (wordpos >= 0 && wordpos < a->top) {
495
1.05M
        ret = a->d[wordpos] & BN_MASK2;
496
1.05M
        if (bitpos) {
497
1.00M
            ret >>= bitpos;
498
1.00M
            if (++wordpos < a->top)
499
185k
                ret |= a->d[wordpos] << (BN_BITS2 - bitpos);
500
1.00M
        }
501
1.05M
    }
502
503
1.05M
    return ret & BN_MASK2;
504
1.05M
}
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
369k
{
517
369k
    int i, j;
518
369k
    int width = 1 << window;
519
369k
    BN_ULONG *table = (BN_ULONG *)buf;
520
521
369k
    if (top > b->top)
522
0
        top = b->top; /* this works because 'buf' is explicitly
523
                       * zeroed */
524
9.52M
    for (i = 0, j = idx; i < top; i++, j += width) {
525
9.15M
        table[j] = b->d[i];
526
9.15M
    }
527
528
369k
    return 1;
529
369k
}
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.01M
{
535
1.01M
    int i, j;
536
1.01M
    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.01M
    volatile BN_ULONG *table = (volatile BN_ULONG *)buf;
546
547
1.01M
    if (bn_wexpand(b, top) == NULL)
548
0
        return 0;
549
550
1.01M
    if (window <= 3) {
551
13.0M
        for (i = 0; i < top; i++, table += width) {
552
12.3M
            BN_ULONG acc = 0;
553
554
110M
            for (j = 0; j < width; j++) {
555
98.5M
                acc |= table[j] & value_barrier_bn((BN_ULONG)0 - (constant_time_eq_int(j, idx) & 1));
556
98.5M
            }
557
558
12.3M
            b->d[i] = acc;
559
12.3M
        }
560
701k
    } else {
561
312k
        int xstride = 1 << (window - 2);
562
312k
        BN_ULONG y0, y1, y2, y3;
563
564
312k
        i = idx >> (window - 2); /* equivalent of idx / xstride */
565
312k
        idx &= xstride - 1; /* equivalent of idx % xstride */
566
567
312k
        y0 = (BN_ULONG)0 - (constant_time_eq_int(i, 0) & 1);
568
312k
        y1 = (BN_ULONG)0 - (constant_time_eq_int(i, 1) & 1);
569
312k
        y2 = (BN_ULONG)0 - (constant_time_eq_int(i, 2) & 1);
570
312k
        y3 = (BN_ULONG)0 - (constant_time_eq_int(i, 3) & 1);
571
572
16.7M
        for (i = 0; i < top; i++, table += width) {
573
16.4M
            BN_ULONG acc = 0;
574
575
116M
            for (j = 0; j < xstride; j++) {
576
99.6M
                acc |= ((table[j + 0 * xstride] & value_barrier_bn(y0)) | (table[j + 1 * xstride] & value_barrier_bn(y1))
577
99.6M
                           | (table[j + 2 * xstride] & value_barrier_bn(y2)) | (table[j + 3 * xstride] & value_barrier_bn(y3)))
578
99.6M
                    & value_barrier_bn((BN_ULONG)0 - (constant_time_eq_int(j, idx) & 1));
579
99.6M
            }
580
581
16.4M
            b->d[i] = acc;
582
16.4M
        }
583
312k
    }
584
585
1.01M
    b->top = top;
586
1.01M
    b->flags |= BN_FLG_FIXED_TOP;
587
1.01M
    return 1;
588
1.01M
}
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
81.7k
    ((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
82.6k
{
608
82.6k
    int i, bits, ret = 0, window, wvalue, wmask, window0;
609
82.6k
    int top;
610
82.6k
    BN_MONT_CTX *mont = NULL;
611
612
82.6k
    int numPowers;
613
82.6k
    unsigned char *powerbufFree = NULL;
614
82.6k
    int powerbufLen = 0;
615
82.6k
    unsigned char *powerbuf = NULL;
616
82.6k
    BIGNUM tmp, am;
617
#if defined(SPARC_T4_MONT)
618
    unsigned int t4 = 0;
619
#endif
620
621
82.6k
    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
82.6k
    top = m->top;
627
628
82.6k
    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
82.6k
    bits = p->top * BN_BITS2;
638
82.6k
    if (bits == 0) {
639
        /* x**0 mod 1, or x**0 mod -1 is still zero. */
640
75
        if (BN_abs_is_word(m, 1)) {
641
8
            ret = 1;
642
8
            BN_zero(rr);
643
67
        } else {
644
67
            ret = BN_one(rr);
645
67
        }
646
75
        return ret;
647
75
    }
648
649
82.5k
    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
82.5k
    if (in_mont != NULL)
656
79.0k
        mont = in_mont;
657
3.46k
    else {
658
3.46k
        if ((mont = BN_MONT_CTX_new()) == NULL)
659
0
            goto err;
660
3.46k
        if (!BN_MONT_CTX_set(mont, m, ctx))
661
0
            goto err;
662
3.46k
    }
663
664
82.5k
    if (a->neg || BN_ucmp(a, m) >= 0) {
665
851
        BIGNUM *reduced = BN_CTX_get(ctx);
666
851
        if (reduced == NULL
667
851
            || !BN_nnmod(reduced, a, m, ctx)) {
668
0
            goto err;
669
0
        }
670
851
        a = reduced;
671
851
    }
672
673
82.5k
#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
82.5k
    if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024)
680
27.4k
        && 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
82.5k
    } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {
691
782
        if (NULL == bn_wexpand(rr, 8))
692
0
            goto err;
693
782
        RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);
694
782
        rr->top = 8;
695
782
        rr->neg = 0;
696
782
        bn_correct_top(rr);
697
782
        ret = 1;
698
782
        goto err;
699
782
    }
700
81.7k
#endif
701
702
    /* Get the window size to use with size of p. */
703
81.7k
    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
81.7k
#if defined(OPENSSL_BN_ASM_MONT5)
710
81.7k
        if (window >= 5 && top <= BN_SOFT_LIMIT) {
711
42.7k
        window = 5; /* ~5% improvement for RSA2048 sign, and even
712
                     * for RSA4096 */
713
        /* reserve space for mont->N.d[] copy */
714
42.7k
        powerbufLen += top * sizeof(mont->N.d[0]);
715
42.7k
    }
716
81.7k
#endif
717
81.7k
    (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
81.7k
    numPowers = 1 << window;
724
81.7k
    powerbufLen += sizeof(m->d[0]) * (top * numPowers + ((2 * top) > numPowers ? (2 * top) : numPowers));
725
81.7k
#ifdef alloca
726
81.7k
    if (powerbufLen < 3072)
727
42.5k
        powerbufFree = alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
728
39.2k
    else
729
39.2k
#endif
730
39.2k
        if ((powerbufFree = OPENSSL_malloc(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))
731
39.2k
            == NULL)
732
0
        goto err;
733
734
81.7k
    powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
735
81.7k
    memset(powerbuf, 0, powerbufLen);
736
737
81.7k
#ifdef alloca
738
81.7k
    if (powerbufLen < 3072)
739
42.5k
        powerbufFree = NULL;
740
81.7k
#endif
741
742
    /* lay down tmp and am right after powers table */
743
81.7k
    tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
744
81.7k
    am.d = tmp.d + top;
745
81.7k
    tmp.top = am.top = 0;
746
81.7k
    tmp.dmax = am.dmax = top;
747
81.7k
    tmp.neg = am.neg = 0;
748
81.7k
    tmp.flags = am.flags = BN_FLG_STATIC_DATA;
749
750
    /* prepare a^0 in Montgomery domain */
751
81.7k
#if 1 /* by Shay Gueron's suggestion */
752
81.7k
    if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
753
        /* 2^(top*BN_BITS2) - m */
754
51.7k
        tmp.d[0] = (0 - m->d[0]) & BN_MASK2;
755
1.03M
        for (i = 1; i < top; i++)
756
983k
            tmp.d[i] = (~m->d[i]) & BN_MASK2;
757
51.7k
        tmp.top = top;
758
51.7k
    } else
759
30.0k
#endif
760
30.0k
        if (!bn_to_mont_fixed_top(&tmp, BN_value_one(), mont, ctx))
761
0
        goto err;
762
763
    /* prepare a^1 in Montgomery domain */
764
81.7k
    if (!bn_to_mont_fixed_top(&am, a, mont, ctx))
765
0
        goto err;
766
767
81.7k
    if (top > BN_SOFT_LIMIT)
768
221
        goto fallback;
769
770
#if defined(SPARC_T4_MONT)
771
    if (t4) {
772
        typedef int (*bn_pwr5_mont_f)(BN_ULONG *tp, const BN_ULONG *np,
773
            const BN_ULONG *n0, const void *table,
774
            int power, int bits);
775
        int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np,
776
            const BN_ULONG *n0, const void *table,
777
            int power, int bits);
778
        int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np,
779
            const BN_ULONG *n0, const void *table,
780
            int power, int bits);
781
        int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np,
782
            const BN_ULONG *n0, const void *table,
783
            int power, int bits);
784
        int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np,
785
            const BN_ULONG *n0, const void *table,
786
            int power, int bits);
787
        static const bn_pwr5_mont_f pwr5_funcs[4] = {
788
            bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16,
789
            bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32
790
        };
791
        bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1];
792
793
        typedef int (*bn_mul_mont_f)(BN_ULONG *rp, const BN_ULONG *ap,
794
            const void *bp, const BN_ULONG *np,
795
            const BN_ULONG *n0);
796
        int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp,
797
            const BN_ULONG *np, const BN_ULONG *n0);
798
        int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap,
799
            const void *bp, const BN_ULONG *np,
800
            const BN_ULONG *n0);
801
        int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap,
802
            const void *bp, const BN_ULONG *np,
803
            const BN_ULONG *n0);
804
        int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap,
805
            const void *bp, const BN_ULONG *np,
806
            const BN_ULONG *n0);
807
        static const bn_mul_mont_f mul_funcs[4] = {
808
            bn_mul_mont_t4_8, bn_mul_mont_t4_16,
809
            bn_mul_mont_t4_24, bn_mul_mont_t4_32
810
        };
811
        bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1];
812
813
        void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap,
814
            const void *bp, const BN_ULONG *np,
815
            const BN_ULONG *n0, int num);
816
        void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap,
817
            const void *bp, const BN_ULONG *np,
818
            const BN_ULONG *n0, int num);
819
        void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap,
820
            const void *table, const BN_ULONG *np,
821
            const BN_ULONG *n0, int num, int power);
822
        void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num,
823
            void *table, size_t power);
824
        void bn_gather5_t4(BN_ULONG *out, size_t num,
825
            void *table, size_t power);
826
        void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num);
827
828
        BN_ULONG *np = mont->N.d, *n0 = mont->n0;
829
        int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less
830
                                                * than 32 */
831
832
        /*
833
         * BN_to_montgomery can contaminate words above .top [in
834
         * BN_DEBUG build...
835
         */
836
        for (i = am.top; i < top; i++)
837
            am.d[i] = 0;
838
        for (i = tmp.top; i < top; i++)
839
            tmp.d[i] = 0;
840
841
        bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0);
842
        bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1);
843
        if (!(*mul_worker)(tmp.d, am.d, am.d, np, n0) && !(*mul_worker)(tmp.d, am.d, am.d, np, n0))
844
            bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top);
845
        bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2);
846
847
        for (i = 3; i < 32; i++) {
848
            /* Calculate a^i = a^(i-1) * a */
849
            if (!(*mul_worker)(tmp.d, tmp.d, am.d, np, n0) && !(*mul_worker)(tmp.d, tmp.d, am.d, np, n0))
850
                bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top);
851
            bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i);
852
        }
853
854
        /* switch to 64-bit domain */
855
        np = alloca(top * sizeof(BN_ULONG));
856
        top /= 2;
857
        bn_flip_t4(np, mont->N.d, top);
858
859
        /*
860
         * The exponent may not have a whole number of fixed-size windows.
861
         * To simplify the main loop, the initial window has between 1 and
862
         * full-window-size bits such that what remains is always a whole
863
         * number of windows
864
         */
865
        window0 = (bits - 1) % 5 + 1;
866
        wmask = (1 << window0) - 1;
867
        bits -= window0;
868
        wvalue = bn_get_bits(p, bits) & wmask;
869
        bn_gather5_t4(tmp.d, top, powerbuf, wvalue);
870
871
        /*
872
         * Scan the exponent one window at a time starting from the most
873
         * significant bits.
874
         */
875
        while (bits > 0) {
876
            if (bits < stride)
877
                stride = bits;
878
            bits -= stride;
879
            wvalue = bn_get_bits(p, bits);
880
881
            if ((*pwr5_worker)(tmp.d, np, n0, powerbuf, wvalue, stride))
882
                continue;
883
            /* retry once and fall back */
884
            if ((*pwr5_worker)(tmp.d, np, n0, powerbuf, wvalue, stride))
885
                continue;
886
887
            bits += stride - 5;
888
            wvalue >>= stride - 5;
889
            wvalue &= 31;
890
            bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
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_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top,
896
                wvalue);
897
        }
898
899
        bn_flip_t4(tmp.d, tmp.d, top);
900
        top *= 2;
901
        /* back to 32-bit domain */
902
        tmp.top = top;
903
        bn_correct_top(&tmp);
904
        OPENSSL_cleanse(np, top * sizeof(BN_ULONG));
905
    } else
906
#endif
907
81.5k
#if defined(OPENSSL_BN_ASM_MONT5)
908
81.5k
        if (window == 5 && top > 1) {
909
        /*
910
         * This optimization uses ideas from https://eprint.iacr.org/2011/239,
911
         * specifically optimization of cache-timing attack countermeasures,
912
         * pre-computation optimization, and Almost Montgomery Multiplication.
913
         *
914
         * The paper discusses a 4-bit window to optimize 512-bit modular
915
         * exponentiation, used in RSA-1024 with CRT, but RSA-1024 is no longer
916
         * important.
917
         *
918
         * |bn_mul_mont_gather5| and |bn_power5| implement the "almost"
919
         * reduction variant, so the values here may not be fully reduced.
920
         * They are bounded by R (i.e. they fit in |top| words), not |m|.
921
         * Additionally, we pass these "almost" reduced inputs into
922
         * |bn_mul_mont|, which implements the normal reduction variant.
923
         * Given those inputs, |bn_mul_mont| may not give reduced
924
         * output, but it will still produce "almost" reduced output.
925
         */
926
42.7k
        void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
927
42.7k
            const void *table, const BN_ULONG *np,
928
42.7k
            const BN_ULONG *n0, int num, int power);
929
42.7k
        void bn_scatter5(const BN_ULONG *inp, size_t num,
930
42.7k
            void *table, size_t power);
931
42.7k
        void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
932
42.7k
        void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,
933
42.7k
            const void *table, const BN_ULONG *np,
934
42.7k
            const BN_ULONG *n0, int num, int power);
935
42.7k
        int bn_get_bits5(const BN_ULONG *ap, int off);
936
937
42.7k
        BN_ULONG *n0 = mont->n0, *np;
938
939
        /*
940
         * BN_to_montgomery can contaminate words above .top [in
941
         * BN_DEBUG build...
942
         */
943
42.7k
        for (i = am.top; i < top; i++)
944
0
            am.d[i] = 0;
945
42.7k
        for (i = tmp.top; i < top; i++)
946
0
            tmp.d[i] = 0;
947
948
        /*
949
         * copy mont->N.d[] to improve cache locality
950
         */
951
796k
        for (np = am.d + top, i = 0; i < top; i++)
952
753k
            np[i] = mont->N.d[i];
953
954
42.7k
        bn_scatter5(tmp.d, top, powerbuf, 0);
955
42.7k
        bn_scatter5(am.d, am.top, powerbuf, 1);
956
42.7k
        bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
957
42.7k
        bn_scatter5(tmp.d, top, powerbuf, 2);
958
959
#if 0
960
        for (i = 3; i < 32; i++) {
961
            /* Calculate a^i = a^(i-1) * a */
962
            bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
963
            bn_scatter5(tmp.d, top, powerbuf, i);
964
        }
965
#else
966
        /* same as above, but uses squaring for 1/2 of operations */
967
170k
        for (i = 4; i < 32; i *= 2) {
968
128k
            bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
969
128k
            bn_scatter5(tmp.d, top, powerbuf, i);
970
128k
        }
971
170k
        for (i = 3; i < 8; i += 2) {
972
128k
            int j;
973
128k
            bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
974
128k
            bn_scatter5(tmp.d, top, powerbuf, i);
975
427k
            for (j = 2 * i; j < 32; j *= 2) {
976
299k
                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
977
299k
                bn_scatter5(tmp.d, top, powerbuf, j);
978
299k
            }
979
128k
        }
980
213k
        for (; i < 16; i += 2) {
981
170k
            bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
982
170k
            bn_scatter5(tmp.d, top, powerbuf, i);
983
170k
            bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
984
170k
            bn_scatter5(tmp.d, top, powerbuf, 2 * i);
985
170k
        }
986
384k
        for (; i < 32; i += 2) {
987
341k
            bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
988
341k
            bn_scatter5(tmp.d, top, powerbuf, i);
989
341k
        }
990
42.7k
#endif
991
        /*
992
         * The exponent may not have a whole number of fixed-size windows.
993
         * To simplify the main loop, the initial window has between 1 and
994
         * full-window-size bits such that what remains is always a whole
995
         * number of windows
996
         */
997
42.7k
        window0 = (bits - 1) % 5 + 1;
998
42.7k
        wmask = (1 << window0) - 1;
999
42.7k
        bits -= window0;
1000
42.7k
        wvalue = bn_get_bits(p, bits) & wmask;
1001
42.7k
        bn_gather5(tmp.d, top, powerbuf, wvalue);
1002
1003
        /*
1004
         * Scan the exponent one window at a time starting from the most
1005
         * significant bits.
1006
         */
1007
42.7k
        if (top & 7) {
1008
2.02M
            while (bits > 0) {
1009
2.01M
                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1010
2.01M
                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1011
2.01M
                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1012
2.01M
                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1013
2.01M
                bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
1014
2.01M
                bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,
1015
2.01M
                    bn_get_bits5(p->d, bits -= 5));
1016
2.01M
            }
1017
33.7k
        } else {
1018
7.22M
            while (bits > 0) {
1019
7.19M
                bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top,
1020
7.19M
                    bn_get_bits5(p->d, bits -= 5));
1021
7.19M
            }
1022
33.7k
        }
1023
1024
42.7k
        tmp.top = top;
1025
        /*
1026
         * The result is now in |tmp| in Montgomery form, but it may not be
1027
         * fully reduced. This is within bounds for |BN_from_montgomery|
1028
         * (tmp < R <= m*R) so it will, when converting from Montgomery form,
1029
         * produce a fully reduced result.
1030
         *
1031
         * This differs from Figure 2 of the paper, which uses AMM(h, 1) to
1032
         * convert from Montgomery form with unreduced output, followed by an
1033
         * extra reduction step. In the paper's terminology, we replace
1034
         * steps 9 and 10 with MM(h, 1).
1035
         */
1036
42.7k
    } else
1037
38.8k
#endif
1038
38.8k
    {
1039
39.0k
    fallback:
1040
39.0k
        if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window))
1041
0
            goto err;
1042
39.0k
        if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window))
1043
0
            goto err;
1044
1045
        /*
1046
         * If the window size is greater than 1, then calculate
1047
         * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
1048
         * powers could instead be computed as (a^(i/2))^2 to use the slight
1049
         * performance advantage of sqr over mul).
1050
         */
1051
39.0k
        if (window > 1) {
1052
39.0k
            if (!bn_mul_mont_fixed_top(&tmp, &am, &am, mont, ctx))
1053
0
                goto err;
1054
39.0k
            if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
1055
39.0k
                    window))
1056
0
                goto err;
1057
291k
            for (i = 3; i < numPowers; i++) {
1058
                /* Calculate a^i = a^(i-1) * a */
1059
252k
                if (!bn_mul_mont_fixed_top(&tmp, &am, &tmp, mont, ctx))
1060
0
                    goto err;
1061
252k
                if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
1062
252k
                        window))
1063
0
                    goto err;
1064
252k
            }
1065
39.0k
        }
1066
1067
        /*
1068
         * The exponent may not have a whole number of fixed-size windows.
1069
         * To simplify the main loop, the initial window has between 1 and
1070
         * full-window-size bits such that what remains is always a whole
1071
         * number of windows
1072
         */
1073
39.0k
        window0 = (bits - 1) % window + 1;
1074
39.0k
        wmask = (1 << window0) - 1;
1075
39.0k
        bits -= window0;
1076
39.0k
        wvalue = bn_get_bits(p, bits) & wmask;
1077
39.0k
        if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue,
1078
39.0k
                window))
1079
0
            goto err;
1080
1081
39.0k
        wmask = (1 << window) - 1;
1082
        /*
1083
         * Scan the exponent one window at a time starting from the most
1084
         * significant bits.
1085
         */
1086
1.01M
        while (bits > 0) {
1087
1088
            /* Square the result window-size times */
1089
4.21M
            for (i = 0; i < window; i++)
1090
3.24M
                if (!bn_mul_mont_fixed_top(&tmp, &tmp, &tmp, mont, ctx))
1091
0
                    goto err;
1092
1093
            /*
1094
             * Get a window's worth of bits from the exponent
1095
             * This avoids calling BN_is_bit_set for each bit, which
1096
             * is not only slower but also makes each bit vulnerable to
1097
             * EM (and likely other) side-channel attacks like One&Done
1098
             * (for details see "One&Done: A Single-Decryption EM-Based
1099
             *  Attack on OpenSSL's Constant-Time Blinded RSA" by M. Alam,
1100
             *  H. Khan, M. Dey, N. Sinha, R. Callan, A. Zajic, and
1101
             *  M. Prvulovic, in USENIX Security'18)
1102
             */
1103
974k
            bits -= window;
1104
974k
            wvalue = bn_get_bits(p, bits) & wmask;
1105
            /*
1106
             * Fetch the appropriate pre-computed value from the pre-buf
1107
             */
1108
974k
            if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue,
1109
974k
                    window))
1110
0
                goto err;
1111
1112
            /* Multiply the result into the intermediate result */
1113
974k
            if (!bn_mul_mont_fixed_top(&tmp, &tmp, &am, mont, ctx))
1114
0
                goto err;
1115
974k
        }
1116
39.0k
    }
1117
1118
    /*
1119
     * Done with zero-padded intermediate BIGNUMs. Final BN_from_montgomery
1120
     * removes padding [if any] and makes return value suitable for public
1121
     * API consumer.
1122
     */
1123
#if defined(SPARC_T4_MONT)
1124
    if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
1125
        am.d[0] = 1; /* borrow am */
1126
        for (i = 1; i < top; i++)
1127
            am.d[i] = 0;
1128
        if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))
1129
            goto err;
1130
    } else
1131
#endif
1132
81.7k
        if (!bn_from_mont_fixed_top(rr, &tmp, mont, ctx))
1133
0
        goto err;
1134
81.7k
    ret = 1;
1135
82.5k
err:
1136
82.5k
    if (in_mont == NULL)
1137
3.46k
        BN_MONT_CTX_free(mont);
1138
82.5k
    if (powerbuf != NULL) {
1139
81.7k
        OPENSSL_cleanse(powerbuf, powerbufLen);
1140
81.7k
        OPENSSL_free(powerbufFree);
1141
81.7k
    }
1142
82.5k
    BN_CTX_end(ctx);
1143
82.5k
    return ret;
1144
81.7k
}
1145
1146
int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
1147
    const BIGNUM *m, BN_CTX *ctx,
1148
    BN_MONT_CTX *in_mont)
1149
82.2k
{
1150
82.2k
    bn_check_top(a);
1151
82.2k
    bn_check_top(p);
1152
82.2k
    bn_check_top(m);
1153
82.2k
    if (!bn_mod_exp_mont_fixed_top(rr, a, p, m, ctx, in_mont))
1154
0
        return 0;
1155
82.2k
    bn_correct_top(rr);
1156
82.2k
    return 1;
1157
82.2k
}
1158
1159
int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
1160
    const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
1161
75.3k
{
1162
75.3k
    BN_MONT_CTX *mont = NULL;
1163
75.3k
    int b, bits, ret = 0;
1164
75.3k
    int r_is_one;
1165
75.3k
    BN_ULONG w, next_w;
1166
75.3k
    BIGNUM *r, *t;
1167
75.3k
    BIGNUM *swap_tmp;
1168
75.3k
#define BN_MOD_MUL_WORD(r, w, m)                            \
1169
3.40M
    (BN_mul_word(r, (w)) && (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
1170
3.40M
         (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
75.3k
#define BN_TO_MONTGOMERY_WORD(r, w, mont) \
1182
75.3k
    (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
1183
1184
75.3k
    if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
1185
75.3k
        || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
1186
        /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1187
0
        ERR_raise(ERR_LIB_BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1188
0
        return 0;
1189
0
    }
1190
1191
75.3k
    bn_check_top(p);
1192
75.3k
    bn_check_top(m);
1193
1194
75.3k
    if (!BN_is_odd(m)) {
1195
0
        ERR_raise(ERR_LIB_BN, BN_R_CALLED_WITH_EVEN_MODULUS);
1196
0
        return 0;
1197
0
    }
1198
75.3k
    if (m->top == 1)
1199
2.82k
        a %= m->d[0]; /* make sure that 'a' is reduced */
1200
1201
75.3k
    bits = BN_num_bits(p);
1202
75.3k
    if (bits == 0) {
1203
        /* x**0 mod 1, or x**0 mod -1 is still zero. */
1204
102
        if (BN_abs_is_word(m, 1)) {
1205
5
            ret = 1;
1206
5
            BN_zero(rr);
1207
97
        } else {
1208
97
            ret = BN_one(rr);
1209
97
        }
1210
102
        return ret;
1211
102
    }
1212
75.2k
    if (a == 0) {
1213
5
        BN_zero(rr);
1214
5
        ret = 1;
1215
5
        return ret;
1216
5
    }
1217
1218
75.2k
    BN_CTX_start(ctx);
1219
75.2k
    r = BN_CTX_get(ctx);
1220
75.2k
    t = BN_CTX_get(ctx);
1221
75.2k
    if (t == NULL)
1222
0
        goto err;
1223
1224
75.2k
    if (in_mont != NULL)
1225
0
        mont = in_mont;
1226
75.2k
    else {
1227
75.2k
        if ((mont = BN_MONT_CTX_new()) == NULL)
1228
0
            goto err;
1229
75.2k
        if (!BN_MONT_CTX_set(mont, m, ctx))
1230
0
            goto err;
1231
75.2k
    }
1232
1233
75.2k
    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
75.2k
    w = a; /* bit 'bits-1' of 'p' is always set */
1239
9.50M
    for (b = bits - 2; b >= 0; b--) {
1240
        /* First, square r*w. */
1241
9.42M
        next_w = w * w;
1242
9.42M
        if ((next_w / w) != w) { /* overflow */
1243
2.45M
            if (r_is_one) {
1244
64.1k
                if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1245
0
                    goto err;
1246
64.1k
                r_is_one = 0;
1247
2.38M
            } else {
1248
2.38M
                if (!BN_MOD_MUL_WORD(r, w, m))
1249
0
                    goto err;
1250
2.38M
            }
1251
2.45M
            next_w = 1;
1252
2.45M
        }
1253
9.42M
        w = next_w;
1254
9.42M
        if (!r_is_one) {
1255
9.22M
            if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
1256
0
                goto err;
1257
9.22M
        }
1258
1259
        /* Second, multiply r*w by 'a' if exponent bit is set. */
1260
9.42M
        if (BN_is_bit_set(p, b)) {
1261
8.56M
            next_w = w * a;
1262
8.56M
            if ((next_w / a) != w) { /* overflow */
1263
961k
                if (r_is_one) {
1264
10.5k
                    if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1265
0
                        goto err;
1266
10.5k
                    r_is_one = 0;
1267
951k
                } else {
1268
951k
                    if (!BN_MOD_MUL_WORD(r, w, m))
1269
0
                        goto err;
1270
951k
                }
1271
961k
                next_w = a;
1272
961k
            }
1273
8.56M
            w = next_w;
1274
8.56M
        }
1275
9.42M
    }
1276
1277
    /* Finally, set r:=r*w. */
1278
75.2k
    if (w != 1) {
1279
71.3k
        if (r_is_one) {
1280
493
            if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
1281
0
                goto err;
1282
493
            r_is_one = 0;
1283
70.8k
        } else {
1284
70.8k
            if (!BN_MOD_MUL_WORD(r, w, m))
1285
0
                goto err;
1286
70.8k
        }
1287
71.3k
    }
1288
1289
75.2k
    if (r_is_one) { /* can happen only if a == 1 */
1290
48
        if (!BN_one(rr))
1291
0
            goto err;
1292
75.2k
    } else {
1293
75.2k
        if (!BN_from_montgomery(rr, r, mont, ctx))
1294
0
            goto err;
1295
75.2k
    }
1296
75.2k
    ret = 1;
1297
75.2k
err:
1298
75.2k
    if (in_mont == NULL)
1299
75.2k
        BN_MONT_CTX_free(mont);
1300
75.2k
    BN_CTX_end(ctx);
1301
75.2k
    bn_check_top(rr);
1302
75.2k
    return ret;
1303
75.2k
}
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
14.0k
{
1309
14.0k
    int i, j, bits, ret = 0, wstart, wend, window;
1310
14.0k
    int start = 1;
1311
14.0k
    BIGNUM *d;
1312
    /* Table of variables obtained from 'ctx' */
1313
14.0k
    BIGNUM *val[TABLE_SIZE];
1314
1315
14.0k
    if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
1316
14.0k
        || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
1317
14.0k
        || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
1318
        /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
1319
0
        ERR_raise(ERR_LIB_BN, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
1320
0
        return 0;
1321
0
    }
1322
1323
14.0k
    if (r == m) {
1324
0
        ERR_raise(ERR_LIB_BN, ERR_R_PASSED_INVALID_ARGUMENT);
1325
0
        return 0;
1326
0
    }
1327
1328
14.0k
    bits = BN_num_bits(p);
1329
14.0k
    if (bits == 0) {
1330
        /* x**0 mod 1, or x**0 mod -1 is still zero. */
1331
796
        if (BN_abs_is_word(m, 1)) {
1332
15
            ret = 1;
1333
15
            BN_zero(r);
1334
781
        } else {
1335
781
            ret = BN_one(r);
1336
781
        }
1337
796
        return ret;
1338
796
    }
1339
1340
13.2k
    BN_CTX_start(ctx);
1341
13.2k
    d = BN_CTX_get(ctx);
1342
13.2k
    val[0] = BN_CTX_get(ctx);
1343
13.2k
    if (val[0] == NULL)
1344
0
        goto err;
1345
1346
13.2k
    if (!BN_nnmod(val[0], a, m, ctx))
1347
0
        goto err; /* 1 */
1348
13.2k
    if (BN_is_zero(val[0])) {
1349
2.92k
        BN_zero(r);
1350
2.92k
        ret = 1;
1351
2.92k
        goto err;
1352
2.92k
    }
1353
1354
10.3k
    window = BN_window_bits_for_exponent_size(bits);
1355
10.3k
    if (window > 1) {
1356
1.86k
        if (!BN_mod_mul(d, val[0], val[0], m, ctx))
1357
0
            goto err; /* 2 */
1358
1.86k
        j = 1 << (window - 1);
1359
14.6k
        for (i = 1; i < j; i++) {
1360
12.8k
            if (((val[i] = BN_CTX_get(ctx)) == NULL) || !BN_mod_mul(val[i], val[i - 1], d, m, ctx))
1361
0
                goto err;
1362
12.8k
        }
1363
1.86k
    }
1364
1365
10.3k
    start = 1; /* This is used to avoid multiplication etc
1366
                * when there is only the value '1' in the
1367
                * buffer. */
1368
10.3k
    wstart = bits - 1; /* The top bit of the window */
1369
10.3k
    wend = 0; /* The bottom bit of the window */
1370
1371
10.3k
    if (r == p) {
1372
0
        BIGNUM *p_dup = BN_CTX_get(ctx);
1373
1374
0
        if (p_dup == NULL || BN_copy(p_dup, p) == NULL)
1375
0
            goto err;
1376
0
        p = p_dup;
1377
0
    }
1378
1379
10.3k
    if (!BN_one(r))
1380
0
        goto err;
1381
1382
256k
    for (;;) {
1383
256k
        int wvalue; /* The 'value' of the window */
1384
1385
256k
        if (BN_is_bit_set(p, wstart) == 0) {
1386
148k
            if (!start)
1387
148k
                if (!BN_mod_mul(r, r, r, m, ctx))
1388
0
                    goto err;
1389
148k
            if (wstart == 0)
1390
3.15k
                break;
1391
144k
            wstart--;
1392
144k
            continue;
1393
148k
        }
1394
        /*
1395
         * We now have wstart on a 'set' bit, we now need to work out how bit
1396
         * a window to do.  To do this we need to scan forward until the last
1397
         * set bit before the end of the window
1398
         */
1399
108k
        wvalue = 1;
1400
108k
        wend = 0;
1401
295k
        for (i = 1; i < window; i++) {
1402
188k
            if (wstart - i < 0)
1403
928
                break;
1404
187k
            if (BN_is_bit_set(p, wstart - i)) {
1405
132k
                wvalue <<= (i - wend);
1406
132k
                wvalue |= 1;
1407
132k
                wend = i;
1408
132k
            }
1409
187k
        }
1410
1411
        /* wend is the size of the current window */
1412
108k
        j = wend + 1;
1413
        /* add the 'bytes above' */
1414
108k
        if (!start)
1415
347k
            for (i = 0; i < j; i++) {
1416
249k
                if (!BN_mod_mul(r, r, r, m, ctx))
1417
0
                    goto err;
1418
249k
            }
1419
1420
        /* wvalue will be an odd number < 2^window */
1421
108k
        if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
1422
0
            goto err;
1423
1424
        /* move the 'window' down further */
1425
108k
        wstart -= wend + 1;
1426
108k
        start = 0;
1427
108k
        if (wstart < 0)
1428
7.17k
            break;
1429
108k
    }
1430
10.3k
    ret = 1;
1431
13.2k
err:
1432
13.2k
    BN_CTX_end(ctx);
1433
13.2k
    bn_check_top(r);
1434
13.2k
    return ret;
1435
10.3k
}
1436
1437
/*
1438
 * This is a variant of modular exponentiation optimization that does
1439
 * parallel 2-primes exponentiation using 256-bit (AVX512VL) AVX512_IFMA ISA
1440
 * or AVX_IFMA ISA in 52-bit binary redundant representation.
1441
 * If such instructions are not available, or input data size is not supported,
1442
 * it falls back to two BN_mod_exp_mont_consttime() calls.
1443
 */
1444
int BN_mod_exp_mont_consttime_x2(BIGNUM *rr1, const BIGNUM *a1, const BIGNUM *p1,
1445
    const BIGNUM *m1, BN_MONT_CTX *in_mont1,
1446
    BIGNUM *rr2, const BIGNUM *a2, const BIGNUM *p2,
1447
    const BIGNUM *m2, BN_MONT_CTX *in_mont2,
1448
    BN_CTX *ctx)
1449
10.0k
{
1450
10.0k
    int ret = 0;
1451
1452
10.0k
#ifdef RSAZ_ENABLED
1453
10.0k
    BN_MONT_CTX *mont1 = NULL;
1454
10.0k
    BN_MONT_CTX *mont2 = NULL;
1455
1456
10.0k
    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)))) {
1457
1458
0
        int topn = a1->top;
1459
        /* Modulus bits of |m1| and |m2| are equal */
1460
0
        int mod_bits = BN_num_bits(m1);
1461
1462
0
        if (bn_wexpand(rr1, topn) == NULL)
1463
0
            goto err;
1464
0
        if (bn_wexpand(rr2, topn) == NULL)
1465
0
            goto err;
1466
1467
        /*  Ensure that montgomery contexts are initialized */
1468
0
        if (in_mont1 != NULL) {
1469
0
            mont1 = in_mont1;
1470
0
        } else {
1471
0
            if ((mont1 = BN_MONT_CTX_new()) == NULL)
1472
0
                goto err;
1473
0
            if (!BN_MONT_CTX_set(mont1, m1, ctx))
1474
0
                goto err;
1475
0
        }
1476
0
        if (in_mont2 != NULL) {
1477
0
            mont2 = in_mont2;
1478
0
        } else {
1479
0
            if ((mont2 = BN_MONT_CTX_new()) == NULL)
1480
0
                goto err;
1481
0
            if (!BN_MONT_CTX_set(mont2, m2, ctx))
1482
0
                goto err;
1483
0
        }
1484
1485
0
        ret = ossl_rsaz_mod_exp_avx512_x2(rr1->d, a1->d, p1->d, m1->d,
1486
0
            mont1->RR.d, mont1->n0[0],
1487
0
            rr2->d, a2->d, p2->d, m2->d,
1488
0
            mont2->RR.d, mont2->n0[0],
1489
0
            mod_bits);
1490
1491
0
        rr1->top = topn;
1492
0
        rr1->neg = 0;
1493
0
        bn_correct_top(rr1);
1494
0
        bn_check_top(rr1);
1495
1496
0
        rr2->top = topn;
1497
0
        rr2->neg = 0;
1498
0
        bn_correct_top(rr2);
1499
0
        bn_check_top(rr2);
1500
1501
0
        goto err;
1502
0
    }
1503
10.0k
#endif
1504
1505
    /* rr1 = a1^p1 mod m1 */
1506
10.0k
    ret = BN_mod_exp_mont_consttime(rr1, a1, p1, m1, ctx, in_mont1);
1507
    /* rr2 = a2^p2 mod m2 */
1508
10.0k
    ret &= BN_mod_exp_mont_consttime(rr2, a2, p2, m2, ctx, in_mont2);
1509
1510
10.0k
#ifdef RSAZ_ENABLED
1511
10.0k
err:
1512
10.0k
    if (in_mont2 == NULL)
1513
0
        BN_MONT_CTX_free(mont2);
1514
10.0k
    if (in_mont1 == NULL)
1515
0
        BN_MONT_CTX_free(mont1);
1516
10.0k
#endif
1517
1518
10.0k
    return ret;
1519
10.0k
}