Coverage Report

Created: 2025-12-31 06:58

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