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