Coverage Report

Created: 2026-04-09 06:50

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl30/crypto/bn/bn_mont.c
Line
Count
Source
1
/*
2
 * Copyright 1995-2026 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
/*
11
 * Details about Montgomery multiplication algorithms can be found in
12
 * https://www.microsoft.com/en-us/research/wp-content/uploads/1996/01/j37acmon.pdf
13
 * and https://cetinkayakoc.net/docs/r01.pdf
14
 */
15
16
#include "internal/cryptlib.h"
17
#include "bn_local.h"
18
19
#define MONT_WORD /* use the faster word-based algorithm */
20
21
#ifdef MONT_WORD
22
static int bn_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont);
23
#endif
24
25
int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
26
    BN_MONT_CTX *mont, BN_CTX *ctx)
27
82.2M
{
28
82.2M
    int ret = bn_mul_mont_fixed_top(r, a, b, mont, ctx);
29
30
82.2M
    bn_correct_top(r);
31
82.2M
    bn_check_top(r);
32
33
82.2M
    return ret;
34
82.2M
}
35
36
int bn_mul_mont_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
37
    BN_MONT_CTX *mont, BN_CTX *ctx)
38
154M
{
39
154M
    BIGNUM *tmp;
40
154M
    int ret = 0;
41
154M
    int num = mont->N.top;
42
43
154M
#if defined(OPENSSL_BN_ASM_MONT) && defined(MONT_WORD)
44
154M
    if (num > 1 && num <= BN_SOFT_LIMIT && a->top == num && b->top == num) {
45
145M
        if (bn_wexpand(r, num) == NULL)
46
0
            return 0;
47
145M
        if (bn_mul_mont(r->d, a->d, b->d, mont->N.d, mont->n0, num)) {
48
145M
            r->neg = a->neg ^ b->neg;
49
145M
            r->top = num;
50
145M
            r->flags |= BN_FLG_FIXED_TOP;
51
145M
            return 1;
52
145M
        }
53
145M
    }
54
9.04M
#endif
55
56
9.04M
    if ((a->top + b->top) > 2 * num)
57
0
        return 0;
58
59
9.04M
    BN_CTX_start(ctx);
60
9.04M
    tmp = BN_CTX_get(ctx);
61
9.04M
    if (tmp == NULL)
62
0
        goto err;
63
64
9.04M
    bn_check_top(tmp);
65
9.04M
    if (a == b) {
66
4.14M
        if (!bn_sqr_fixed_top(tmp, a, ctx))
67
0
            goto err;
68
4.90M
    } else {
69
4.90M
        if (!bn_mul_fixed_top(tmp, a, b, ctx))
70
0
            goto err;
71
4.90M
    }
72
    /* reduce from aRR to aR */
73
9.04M
#ifdef MONT_WORD
74
9.04M
    if (!bn_from_montgomery_word(r, tmp, mont))
75
0
        goto err;
76
#else
77
    if (!BN_from_montgomery(r, tmp, mont, ctx))
78
        goto err;
79
#endif
80
9.04M
    ret = 1;
81
9.04M
err:
82
9.04M
    BN_CTX_end(ctx);
83
9.04M
    return ret;
84
9.04M
}
85
86
#ifdef MONT_WORD
87
static int bn_from_montgomery_word(BIGNUM *ret, BIGNUM *r, BN_MONT_CTX *mont)
88
10.4M
{
89
10.4M
    BIGNUM *n;
90
10.4M
    BN_ULONG *ap, *np, *rp, n0, v, carry;
91
10.4M
    int nl, max, i;
92
10.4M
    unsigned int rtop;
93
94
10.4M
    n = &(mont->N);
95
10.4M
    nl = n->top;
96
10.4M
    if (nl == 0) {
97
0
        ret->top = 0;
98
0
        return 1;
99
0
    }
100
101
10.4M
    max = (2 * nl); /* carry is stored separately */
102
10.4M
    if (bn_wexpand(r, max) == NULL)
103
0
        return 0;
104
105
10.4M
    r->neg ^= n->neg;
106
10.4M
    np = n->d;
107
10.4M
    rp = r->d;
108
109
    /* clear the top words of T */
110
258M
    for (rtop = r->top, i = 0; i < max; i++) {
111
248M
        v = (BN_ULONG)0 - ((i - rtop) >> (8 * sizeof(rtop) - 1));
112
248M
        rp[i] &= v;
113
248M
    }
114
115
10.4M
    r->top = max;
116
10.4M
    r->flags |= BN_FLG_FIXED_TOP;
117
10.4M
    n0 = mont->n0[0];
118
119
    /*
120
     * Add multiples of |n| to |r| until R = 2^(nl * BN_BITS2) divides it. On
121
     * input, we had |r| < |n| * R, so now |r| < 2 * |n| * R. Note that |r|
122
     * includes |carry| which is stored separately.
123
     */
124
134M
    for (carry = 0, i = 0; i < nl; i++, rp++) {
125
124M
        v = bn_mul_add_words(rp, np, nl, (rp[0] * n0) & BN_MASK2);
126
124M
        v = (v + carry + rp[nl]) & BN_MASK2;
127
124M
        carry |= (v != rp[nl]);
128
124M
        carry &= (v <= rp[nl]);
129
124M
        rp[nl] = v;
130
124M
    }
131
132
10.4M
    if (bn_wexpand(ret, nl) == NULL)
133
0
        return 0;
134
10.4M
    ret->top = nl;
135
10.4M
    ret->flags |= BN_FLG_FIXED_TOP;
136
10.4M
    ret->neg = r->neg;
137
138
10.4M
    rp = ret->d;
139
140
    /*
141
     * Shift |nl| words to divide by R. We have |ap| < 2 * |n|. Note that |ap|
142
     * includes |carry| which is stored separately.
143
     */
144
10.4M
    ap = &(r->d[nl]);
145
146
10.4M
    carry -= bn_sub_words(rp, ap, np, nl);
147
    /*
148
     * |carry| is -1 if |ap| - |np| underflowed or zero if it did not. Note
149
     * |carry| cannot be 1. That would imply the subtraction did not fit in
150
     * |nl| words, and we know at most one subtraction is needed.
151
     */
152
134M
    for (i = 0; i < nl; i++) {
153
124M
        rp[i] = (carry & ap[i]) | (~carry & rp[i]);
154
124M
        ap[i] = 0;
155
124M
    }
156
157
10.4M
    return 1;
158
10.4M
}
159
#endif /* MONT_WORD */
160
161
int BN_from_montgomery(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont,
162
    BN_CTX *ctx)
163
1.23M
{
164
1.23M
    int retn;
165
166
1.23M
    retn = bn_from_mont_fixed_top(ret, a, mont, ctx);
167
1.23M
    bn_correct_top(ret);
168
1.23M
    bn_check_top(ret);
169
170
1.23M
    return retn;
171
1.23M
}
172
173
int bn_from_mont_fixed_top(BIGNUM *ret, const BIGNUM *a, BN_MONT_CTX *mont,
174
    BN_CTX *ctx)
175
1.37M
{
176
1.37M
    int retn = 0;
177
1.37M
#ifdef MONT_WORD
178
1.37M
    BIGNUM *t;
179
180
1.37M
    BN_CTX_start(ctx);
181
1.37M
    if ((t = BN_CTX_get(ctx)) && BN_copy(t, a)) {
182
1.37M
        retn = bn_from_montgomery_word(ret, t, mont);
183
1.37M
    }
184
1.37M
    BN_CTX_end(ctx);
185
#else /* !MONT_WORD */
186
    BIGNUM *t1, *t2;
187
188
    BN_CTX_start(ctx);
189
    t1 = BN_CTX_get(ctx);
190
    t2 = BN_CTX_get(ctx);
191
    if (t2 == NULL)
192
        goto err;
193
194
    if (!BN_copy(t1, a))
195
        goto err;
196
    BN_mask_bits(t1, mont->ri);
197
198
    if (!BN_mul(t2, t1, &mont->Ni, ctx))
199
        goto err;
200
    BN_mask_bits(t2, mont->ri);
201
202
    if (!BN_mul(t1, t2, &mont->N, ctx))
203
        goto err;
204
    if (!BN_add(t2, a, t1))
205
        goto err;
206
    if (!BN_rshift(ret, t2, mont->ri))
207
        goto err;
208
209
    if (BN_ucmp(ret, &(mont->N)) >= 0) {
210
        if (!BN_usub(ret, ret, &(mont->N)))
211
            goto err;
212
    }
213
    retn = 1;
214
    bn_check_top(ret);
215
err:
216
    BN_CTX_end(ctx);
217
#endif /* MONT_WORD */
218
1.37M
    return retn;
219
1.37M
}
220
221
int bn_to_mont_fixed_top(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
222
    BN_CTX *ctx)
223
771k
{
224
771k
    return bn_mul_mont_fixed_top(r, a, &(mont->RR), mont, ctx);
225
771k
}
226
227
BN_MONT_CTX *BN_MONT_CTX_new(void)
228
2.75M
{
229
2.75M
    BN_MONT_CTX *ret;
230
231
2.75M
    if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL) {
232
0
        ERR_raise(ERR_LIB_BN, ERR_R_MALLOC_FAILURE);
233
0
        return NULL;
234
0
    }
235
236
2.75M
    BN_MONT_CTX_init(ret);
237
2.75M
    ret->flags = BN_FLG_MALLOCED;
238
2.75M
    return ret;
239
2.75M
}
240
241
void BN_MONT_CTX_init(BN_MONT_CTX *ctx)
242
2.75M
{
243
2.75M
    ctx->ri = 0;
244
2.75M
    bn_init(&ctx->RR);
245
2.75M
    bn_init(&ctx->N);
246
2.75M
    bn_init(&ctx->Ni);
247
2.75M
    ctx->n0[0] = ctx->n0[1] = 0;
248
2.75M
    ctx->flags = 0;
249
2.75M
}
250
251
void BN_MONT_CTX_free(BN_MONT_CTX *mont)
252
7.55M
{
253
7.55M
    if (mont == NULL)
254
4.80M
        return;
255
2.75M
    BN_clear_free(&mont->RR);
256
2.75M
    BN_clear_free(&mont->N);
257
2.75M
    BN_clear_free(&mont->Ni);
258
2.75M
    if (mont->flags & BN_FLG_MALLOCED)
259
2.75M
        OPENSSL_free(mont);
260
2.75M
}
261
262
int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx)
263
1.04M
{
264
1.04M
    int i, ret = 0;
265
1.04M
    BIGNUM *Ri, *R;
266
267
1.04M
    if (BN_is_zero(mod))
268
6
        return 0;
269
270
1.04M
    BN_CTX_start(ctx);
271
1.04M
    if ((Ri = BN_CTX_get(ctx)) == NULL)
272
0
        goto err;
273
1.04M
    R = &(mont->RR); /* grab RR as a temp */
274
1.04M
    if (!BN_copy(&(mont->N), mod))
275
0
        goto err; /* Set N */
276
1.04M
    if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0)
277
28.7k
        BN_set_flags(&(mont->N), BN_FLG_CONSTTIME);
278
1.04M
    mont->N.neg = 0;
279
280
1.04M
#ifdef MONT_WORD
281
1.04M
    {
282
1.04M
        BIGNUM tmod;
283
1.04M
        BN_ULONG buf[2];
284
285
1.04M
        bn_init(&tmod);
286
1.04M
        tmod.d = buf;
287
1.04M
        tmod.dmax = 2;
288
1.04M
        tmod.neg = 0;
289
290
1.04M
        if (BN_get_flags(mod, BN_FLG_CONSTTIME) != 0)
291
28.7k
            BN_set_flags(&tmod, BN_FLG_CONSTTIME);
292
293
1.04M
        mont->ri = (BN_num_bits(mod) + (BN_BITS2 - 1)) / BN_BITS2 * BN_BITS2;
294
295
#if defined(OPENSSL_BN_ASM_MONT) && (BN_BITS2 <= 32)
296
        /*
297
         * Only certain BN_BITS2<=32 platforms actually make use of n0[1],
298
         * and we could use the #else case (with a shorter R value) for the
299
         * others.  However, currently only the assembler files do know which
300
         * is which.
301
         */
302
303
        BN_zero(R);
304
        if (!(BN_set_bit(R, 2 * BN_BITS2)))
305
            goto err;
306
307
        tmod.top = 0;
308
        if ((buf[0] = mod->d[0]))
309
            tmod.top = 1;
310
        if ((buf[1] = mod->top > 1 ? mod->d[1] : 0))
311
            tmod.top = 2;
312
313
        if (BN_is_one(&tmod))
314
            BN_zero(Ri);
315
        else if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
316
            goto err;
317
        if (!BN_lshift(Ri, Ri, 2 * BN_BITS2))
318
            goto err; /* R*Ri */
319
        if (!BN_is_zero(Ri)) {
320
            if (!BN_sub_word(Ri, 1))
321
                goto err;
322
        } else { /* if N mod word size == 1 */
323
324
            if (bn_expand(Ri, (int)sizeof(BN_ULONG) * 2) == NULL)
325
                goto err;
326
            /* Ri-- (mod double word size) */
327
            Ri->neg = 0;
328
            Ri->d[0] = BN_MASK2;
329
            Ri->d[1] = BN_MASK2;
330
            Ri->top = 2;
331
        }
332
        if (!BN_div(Ri, NULL, Ri, &tmod, ctx))
333
            goto err;
334
        /*
335
         * Ni = (R*Ri-1)/N, keep only couple of least significant words:
336
         */
337
        mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0;
338
        mont->n0[1] = (Ri->top > 1) ? Ri->d[1] : 0;
339
#else
340
1.04M
        BN_zero(R);
341
1.04M
        if (!(BN_set_bit(R, BN_BITS2)))
342
0
            goto err; /* R */
343
344
1.04M
        buf[0] = mod->d[0]; /* tmod = N mod word size */
345
1.04M
        buf[1] = 0;
346
1.04M
        tmod.top = buf[0] != 0 ? 1 : 0;
347
        /* Ri = R^-1 mod N */
348
1.04M
        if (BN_is_one(&tmod))
349
90.5k
            BN_zero(Ri);
350
957k
        else if ((BN_mod_inverse(Ri, R, &tmod, ctx)) == NULL)
351
5.85k
            goto err;
352
1.04M
        if (!BN_lshift(Ri, Ri, BN_BITS2))
353
0
            goto err; /* R*Ri */
354
1.04M
        if (!BN_is_zero(Ri)) {
355
951k
            if (!BN_sub_word(Ri, 1))
356
0
                goto err;
357
951k
        } else { /* if N mod word size == 1 */
358
359
90.5k
            if (!BN_set_word(Ri, BN_MASK2))
360
0
                goto err; /* Ri-- (mod word size) */
361
90.5k
        }
362
1.04M
        if (!BN_div(Ri, NULL, Ri, &tmod, ctx))
363
0
            goto err;
364
        /*
365
         * Ni = (R*Ri-1)/N, keep only least significant word:
366
         */
367
1.04M
        mont->n0[0] = (Ri->top > 0) ? Ri->d[0] : 0;
368
1.04M
        mont->n0[1] = 0;
369
1.04M
#endif
370
1.04M
    }
371
#else /* !MONT_WORD */
372
    { /* bignum version */
373
        mont->ri = BN_num_bits(&mont->N);
374
        BN_zero(R);
375
        if (!BN_set_bit(R, mont->ri))
376
            goto err; /* R = 2^ri */
377
        /* Ri = R^-1 mod N */
378
        if ((BN_mod_inverse(Ri, R, &mont->N, ctx)) == NULL)
379
            goto err;
380
        if (!BN_lshift(Ri, Ri, mont->ri))
381
            goto err; /* R*Ri */
382
        if (!BN_sub_word(Ri, 1))
383
            goto err;
384
        /*
385
         * Ni = (R*Ri-1) / N
386
         */
387
        if (!BN_div(&(mont->Ni), NULL, Ri, &mont->N, ctx))
388
            goto err;
389
    }
390
#endif
391
392
    /* setup RR for conversions */
393
1.04M
    BN_zero(&(mont->RR));
394
1.04M
    if (!BN_set_bit(&(mont->RR), mont->ri * 2))
395
0
        goto err;
396
1.04M
    if (!BN_mod(&(mont->RR), &(mont->RR), &(mont->N), ctx))
397
0
        goto err;
398
399
1.34M
    for (i = mont->RR.top, ret = mont->N.top; i < ret; i++)
400
300k
        mont->RR.d[i] = 0;
401
1.04M
    mont->RR.top = ret;
402
1.04M
    mont->RR.flags |= BN_FLG_FIXED_TOP;
403
404
1.04M
    ret = 1;
405
1.04M
err:
406
1.04M
    BN_CTX_end(ctx);
407
1.04M
    return ret;
408
1.04M
}
409
410
BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from)
411
924k
{
412
924k
    if (to == from)
413
0
        return to;
414
415
924k
    if (!BN_copy(&(to->RR), &(from->RR)))
416
0
        return NULL;
417
924k
    if (!BN_copy(&(to->N), &(from->N)))
418
0
        return NULL;
419
924k
    if (!BN_copy(&(to->Ni), &(from->Ni)))
420
0
        return NULL;
421
924k
    to->ri = from->ri;
422
924k
    to->n0[0] = from->n0[0];
423
924k
    to->n0[1] = from->n0[1];
424
924k
    return to;
425
924k
}
426
427
BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_RWLOCK *lock,
428
    const BIGNUM *mod, BN_CTX *ctx)
429
113k
{
430
113k
    BN_MONT_CTX *ret;
431
432
113k
    if (!CRYPTO_THREAD_read_lock(lock))
433
0
        return NULL;
434
113k
    ret = *pmont;
435
113k
    CRYPTO_THREAD_unlock(lock);
436
113k
    if (ret)
437
22.8k
        return ret;
438
439
    /*
440
     * We don't want to serialize globally while doing our lazy-init math in
441
     * BN_MONT_CTX_set. That punishes threads that are doing independent
442
     * things. Instead, punish the case where more than one thread tries to
443
     * lazy-init the same 'pmont', by having each do the lazy-init math work
444
     * independently and only use the one from the thread that wins the race
445
     * (the losers throw away the work they've done).
446
     */
447
90.4k
    ret = BN_MONT_CTX_new();
448
90.4k
    if (ret == NULL)
449
0
        return NULL;
450
90.4k
    if (!BN_MONT_CTX_set(ret, mod, ctx)) {
451
3.38k
        BN_MONT_CTX_free(ret);
452
3.38k
        return NULL;
453
3.38k
    }
454
455
    /* The locked compare-and-set, after the local work is done. */
456
87.1k
    if (!CRYPTO_THREAD_write_lock(lock)) {
457
0
        BN_MONT_CTX_free(ret);
458
0
        return NULL;
459
0
    }
460
461
87.1k
    if (*pmont) {
462
0
        BN_MONT_CTX_free(ret);
463
0
        ret = *pmont;
464
0
    } else
465
87.1k
        *pmont = ret;
466
87.1k
    CRYPTO_THREAD_unlock(lock);
467
87.1k
    return ret;
468
87.1k
}