Coverage Report

Created: 2023-06-08 06:41

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