Coverage Report

Created: 2024-07-27 06:39

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