• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.] */
56 
57 #include <openssl/bn.h>
58 
59 #include <assert.h>
60 #include <stdlib.h>
61 #include <string.h>
62 
63 #include <openssl/err.h>
64 #include <openssl/mem.h>
65 #include <openssl/type_check.h>
66 
67 #include "internal.h"
68 #include "../../internal.h"
69 
70 
71 #define BN_MUL_RECURSIVE_SIZE_NORMAL 16
72 #define BN_SQR_RECURSIVE_SIZE_NORMAL BN_MUL_RECURSIVE_SIZE_NORMAL
73 
74 
bn_abs_sub_words(BN_ULONG * r,const BN_ULONG * a,const BN_ULONG * b,size_t num,BN_ULONG * tmp)75 static void bn_abs_sub_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
76                              size_t num, BN_ULONG *tmp) {
77   BN_ULONG borrow = bn_sub_words(tmp, a, b, num);
78   bn_sub_words(r, b, a, num);
79   bn_select_words(r, 0 - borrow, r /* tmp < 0 */, tmp /* tmp >= 0 */, num);
80 }
81 
bn_mul_normal(BN_ULONG * r,const BN_ULONG * a,size_t na,const BN_ULONG * b,size_t nb)82 static void bn_mul_normal(BN_ULONG *r, const BN_ULONG *a, size_t na,
83                           const BN_ULONG *b, size_t nb) {
84   if (na < nb) {
85     size_t itmp = na;
86     na = nb;
87     nb = itmp;
88     const BN_ULONG *ltmp = a;
89     a = b;
90     b = ltmp;
91   }
92   BN_ULONG *rr = &(r[na]);
93   if (nb == 0) {
94     OPENSSL_memset(r, 0, na * sizeof(BN_ULONG));
95     return;
96   }
97   rr[0] = bn_mul_words(r, a, na, b[0]);
98 
99   for (;;) {
100     if (--nb == 0) {
101       return;
102     }
103     rr[1] = bn_mul_add_words(&(r[1]), a, na, b[1]);
104     if (--nb == 0) {
105       return;
106     }
107     rr[2] = bn_mul_add_words(&(r[2]), a, na, b[2]);
108     if (--nb == 0) {
109       return;
110     }
111     rr[3] = bn_mul_add_words(&(r[3]), a, na, b[3]);
112     if (--nb == 0) {
113       return;
114     }
115     rr[4] = bn_mul_add_words(&(r[4]), a, na, b[4]);
116     rr += 4;
117     r += 4;
118     b += 4;
119   }
120 }
121 
122 // bn_sub_part_words sets |r| to |a| - |b|. It returns the borrow bit, which is
123 // one if the operation underflowed and zero otherwise. |cl| is the common
124 // length, that is, the shorter of len(a) or len(b). |dl| is the delta length,
125 // that is, len(a) - len(b). |r|'s length matches the larger of |a| and |b|, or
126 // cl + abs(dl).
127 //
128 // TODO(davidben): Make this take |size_t|. The |cl| + |dl| calling convention
129 // is confusing.
bn_sub_part_words(BN_ULONG * r,const BN_ULONG * a,const BN_ULONG * b,int cl,int dl)130 static BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a,
131                                   const BN_ULONG *b, int cl, int dl) {
132   assert(cl >= 0);
133   BN_ULONG borrow = bn_sub_words(r, a, b, cl);
134   if (dl == 0) {
135     return borrow;
136   }
137 
138   r += cl;
139   a += cl;
140   b += cl;
141 
142   if (dl < 0) {
143     // |a| is shorter than |b|. Complete the subtraction as if the excess words
144     // in |a| were zeros.
145     dl = -dl;
146     for (int i = 0; i < dl; i++) {
147       r[i] = 0u - b[i] - borrow;
148       borrow |= r[i] != 0;
149     }
150   } else {
151     // |b| is shorter than |a|. Complete the subtraction as if the excess words
152     // in |b| were zeros.
153     for (int i = 0; i < dl; i++) {
154       // |r| and |a| may alias, so use a temporary.
155       BN_ULONG tmp = a[i];
156       r[i] = a[i] - borrow;
157       borrow = tmp < r[i];
158     }
159   }
160 
161   return borrow;
162 }
163 
164 // bn_abs_sub_part_words computes |r| = |a| - |b|, storing the absolute value
165 // and returning a mask of all ones if the result was negative and all zeros if
166 // the result was positive. |cl| and |dl| follow the |bn_sub_part_words| calling
167 // convention.
168 //
169 // TODO(davidben): Make this take |size_t|. The |cl| + |dl| calling convention
170 // is confusing.
bn_abs_sub_part_words(BN_ULONG * r,const BN_ULONG * a,const BN_ULONG * b,int cl,int dl,BN_ULONG * tmp)171 static BN_ULONG bn_abs_sub_part_words(BN_ULONG *r, const BN_ULONG *a,
172                                       const BN_ULONG *b, int cl, int dl,
173                                       BN_ULONG *tmp) {
174   BN_ULONG borrow = bn_sub_part_words(tmp, a, b, cl, dl);
175   bn_sub_part_words(r, b, a, cl, -dl);
176   int r_len = cl + (dl < 0 ? -dl : dl);
177   borrow = 0 - borrow;
178   bn_select_words(r, borrow, r /* tmp < 0 */, tmp /* tmp >= 0 */, r_len);
179   return borrow;
180 }
181 
bn_abs_sub_consttime(BIGNUM * r,const BIGNUM * a,const BIGNUM * b,BN_CTX * ctx)182 int bn_abs_sub_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
183                          BN_CTX *ctx) {
184   int cl = a->width < b->width ? a->width : b->width;
185   int dl = a->width - b->width;
186   int r_len = a->width < b->width ? b->width : a->width;
187   BN_CTX_start(ctx);
188   BIGNUM *tmp = BN_CTX_get(ctx);
189   int ok = tmp != NULL &&
190            bn_wexpand(r, r_len) &&
191            bn_wexpand(tmp, r_len);
192   if (ok) {
193     bn_abs_sub_part_words(r->d, a->d, b->d, cl, dl, tmp->d);
194     r->width = r_len;
195   }
196   BN_CTX_end(ctx);
197   return ok;
198 }
199 
200 // Karatsuba recursive multiplication algorithm
201 // (cf. Knuth, The Art of Computer Programming, Vol. 2)
202 
203 // bn_mul_recursive sets |r| to |a| * |b|, using |t| as scratch space. |r| has
204 // length 2*|n2|, |a| has length |n2| + |dna|, |b| has length |n2| + |dnb|, and
205 // |t| has length 4*|n2|. |n2| must be a power of two. Finally, we must have
206 // -|BN_MUL_RECURSIVE_SIZE_NORMAL|/2 <= |dna| <= 0 and
207 // -|BN_MUL_RECURSIVE_SIZE_NORMAL|/2 <= |dnb| <= 0.
208 //
209 // TODO(davidben): Simplify and |size_t| the calling convention around lengths
210 // here.
bn_mul_recursive(BN_ULONG * r,const BN_ULONG * a,const BN_ULONG * b,int n2,int dna,int dnb,BN_ULONG * t)211 static void bn_mul_recursive(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
212                              int n2, int dna, int dnb, BN_ULONG *t) {
213   // |n2| is a power of two.
214   assert(n2 != 0 && (n2 & (n2 - 1)) == 0);
215   // Check |dna| and |dnb| are in range.
216   assert(-BN_MUL_RECURSIVE_SIZE_NORMAL/2 <= dna && dna <= 0);
217   assert(-BN_MUL_RECURSIVE_SIZE_NORMAL/2 <= dnb && dnb <= 0);
218 
219   // Only call bn_mul_comba 8 if n2 == 8 and the
220   // two arrays are complete [steve]
221   if (n2 == 8 && dna == 0 && dnb == 0) {
222     bn_mul_comba8(r, a, b);
223     return;
224   }
225 
226   // Else do normal multiply
227   if (n2 < BN_MUL_RECURSIVE_SIZE_NORMAL) {
228     bn_mul_normal(r, a, n2 + dna, b, n2 + dnb);
229     if (dna + dnb < 0) {
230       OPENSSL_memset(&r[2 * n2 + dna + dnb], 0,
231                      sizeof(BN_ULONG) * -(dna + dnb));
232     }
233     return;
234   }
235 
236   // Split |a| and |b| into a0,a1 and b0,b1, where a0 and b0 have size |n|.
237   // Split |t| into t0,t1,t2,t3, each of size |n|, with the remaining 4*|n| used
238   // for recursive calls.
239   // Split |r| into r0,r1,r2,r3. We must contribute a0*b0 to r0,r1, a0*a1+b0*b1
240   // to r1,r2, and a1*b1 to r2,r3. The middle term we will compute as:
241   //
242   //   a0*a1 + b0*b1 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0
243   //
244   // Note that we know |n| >= |BN_MUL_RECURSIVE_SIZE_NORMAL|/2 above, so
245   // |tna| and |tnb| are non-negative.
246   int n = n2 / 2, tna = n + dna, tnb = n + dnb;
247 
248   // t0 = a0 - a1 and t1 = b1 - b0. The result will be multiplied, so we XOR
249   // their sign masks, giving the sign of (a0 - a1)*(b1 - b0). t0 and t1
250   // themselves store the absolute value.
251   BN_ULONG neg = bn_abs_sub_part_words(t, a, &a[n], tna, n - tna, &t[n2]);
252   neg ^= bn_abs_sub_part_words(&t[n], &b[n], b, tnb, tnb - n, &t[n2]);
253 
254   // Compute:
255   // t2,t3 = t0 * t1 = |(a0 - a1)*(b1 - b0)|
256   // r0,r1 = a0 * b0
257   // r2,r3 = a1 * b1
258   if (n == 4 && dna == 0 && dnb == 0) {
259     bn_mul_comba4(&t[n2], t, &t[n]);
260 
261     bn_mul_comba4(r, a, b);
262     bn_mul_comba4(&r[n2], &a[n], &b[n]);
263   } else if (n == 8 && dna == 0 && dnb == 0) {
264     bn_mul_comba8(&t[n2], t, &t[n]);
265 
266     bn_mul_comba8(r, a, b);
267     bn_mul_comba8(&r[n2], &a[n], &b[n]);
268   } else {
269     BN_ULONG *p = &t[n2 * 2];
270     bn_mul_recursive(&t[n2], t, &t[n], n, 0, 0, p);
271     bn_mul_recursive(r, a, b, n, 0, 0, p);
272     bn_mul_recursive(&r[n2], &a[n], &b[n], n, dna, dnb, p);
273   }
274 
275   // t0,t1,c = r0,r1 + r2,r3 = a0*b0 + a1*b1
276   BN_ULONG c = bn_add_words(t, r, &r[n2], n2);
277 
278   // t2,t3,c = t0,t1,c + neg*t2,t3 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0.
279   // The second term is stored as the absolute value, so we do this with a
280   // constant-time select.
281   BN_ULONG c_neg = c - bn_sub_words(&t[n2 * 2], t, &t[n2], n2);
282   BN_ULONG c_pos = c + bn_add_words(&t[n2], t, &t[n2], n2);
283   bn_select_words(&t[n2], neg, &t[n2 * 2], &t[n2], n2);
284   OPENSSL_STATIC_ASSERT(sizeof(BN_ULONG) <= sizeof(crypto_word_t),
285                         "crypto_word_t is too small");
286   c = constant_time_select_w(neg, c_neg, c_pos);
287 
288   // We now have our three components. Add them together.
289   // r1,r2,c = r1,r2 + t2,t3,c
290   c += bn_add_words(&r[n], &r[n], &t[n2], n2);
291 
292   // Propagate the carry bit to the end.
293   for (int i = n + n2; i < n2 + n2; i++) {
294     BN_ULONG old = r[i];
295     r[i] = old + c;
296     c = r[i] < old;
297   }
298 
299   // The product should fit without carries.
300   assert(c == 0);
301 }
302 
303 // bn_mul_part_recursive sets |r| to |a| * |b|, using |t| as scratch space. |r|
304 // has length 4*|n|, |a| has length |n| + |tna|, |b| has length |n| + |tnb|, and
305 // |t| has length 8*|n|. |n| must be a power of two. Additionally, we must have
306 // 0 <= tna < n and 0 <= tnb < n, and |tna| and |tnb| must differ by at most
307 // one.
308 //
309 // TODO(davidben): Make this take |size_t| and perhaps the actual lengths of |a|
310 // and |b|.
bn_mul_part_recursive(BN_ULONG * r,const BN_ULONG * a,const BN_ULONG * b,int n,int tna,int tnb,BN_ULONG * t)311 static void bn_mul_part_recursive(BN_ULONG *r, const BN_ULONG *a,
312                                   const BN_ULONG *b, int n, int tna, int tnb,
313                                   BN_ULONG *t) {
314   // |n| is a power of two.
315   assert(n != 0 && (n & (n - 1)) == 0);
316   // Check |tna| and |tnb| are in range.
317   assert(0 <= tna && tna < n);
318   assert(0 <= tnb && tnb < n);
319   assert(-1 <= tna - tnb && tna - tnb <= 1);
320 
321   int n2 = n * 2;
322   if (n < 8) {
323     bn_mul_normal(r, a, n + tna, b, n + tnb);
324     OPENSSL_memset(r + n2 + tna + tnb, 0, n2 - tna - tnb);
325     return;
326   }
327 
328   // Split |a| and |b| into a0,a1 and b0,b1, where a0 and b0 have size |n|. |a1|
329   // and |b1| have size |tna| and |tnb|, respectively.
330   // Split |t| into t0,t1,t2,t3, each of size |n|, with the remaining 4*|n| used
331   // for recursive calls.
332   // Split |r| into r0,r1,r2,r3. We must contribute a0*b0 to r0,r1, a0*a1+b0*b1
333   // to r1,r2, and a1*b1 to r2,r3. The middle term we will compute as:
334   //
335   //   a0*a1 + b0*b1 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0
336 
337   // t0 = a0 - a1 and t1 = b1 - b0. The result will be multiplied, so we XOR
338   // their sign masks, giving the sign of (a0 - a1)*(b1 - b0). t0 and t1
339   // themselves store the absolute value.
340   BN_ULONG neg = bn_abs_sub_part_words(t, a, &a[n], tna, n - tna, &t[n2]);
341   neg ^= bn_abs_sub_part_words(&t[n], &b[n], b, tnb, tnb - n, &t[n2]);
342 
343   // Compute:
344   // t2,t3 = t0 * t1 = |(a0 - a1)*(b1 - b0)|
345   // r0,r1 = a0 * b0
346   // r2,r3 = a1 * b1
347   if (n == 8) {
348     bn_mul_comba8(&t[n2], t, &t[n]);
349     bn_mul_comba8(r, a, b);
350 
351     bn_mul_normal(&r[n2], &a[n], tna, &b[n], tnb);
352     // |bn_mul_normal| only writes |tna| + |tna| words. Zero the rest.
353     OPENSSL_memset(&r[n2 + tna + tnb], 0, sizeof(BN_ULONG) * (n2 - tna - tnb));
354   } else {
355     BN_ULONG *p = &t[n2 * 2];
356     bn_mul_recursive(&t[n2], t, &t[n], n, 0, 0, p);
357     bn_mul_recursive(r, a, b, n, 0, 0, p);
358 
359     OPENSSL_memset(&r[n2], 0, sizeof(BN_ULONG) * n2);
360     if (tna < BN_MUL_RECURSIVE_SIZE_NORMAL &&
361         tnb < BN_MUL_RECURSIVE_SIZE_NORMAL) {
362       bn_mul_normal(&r[n2], &a[n], tna, &b[n], tnb);
363     } else {
364       int i = n;
365       for (;;) {
366         i /= 2;
367         if (i < tna || i < tnb) {
368           // E.g., n == 16, i == 8 and tna == 11. |tna| and |tnb| are within one
369           // of each other, so if |tna| is larger and tna > i, then we know
370           // tnb >= i, and this call is valid.
371           bn_mul_part_recursive(&r[n2], &a[n], &b[n], i, tna - i, tnb - i, p);
372           break;
373         }
374         if (i == tna || i == tnb) {
375           // If there is only a bottom half to the number, just do it. We know
376           // the larger of |tna - i| and |tnb - i| is zero. The other is zero or
377           // -1 by because of |tna| and |tnb| differ by at most one.
378           bn_mul_recursive(&r[n2], &a[n], &b[n], i, tna - i, tnb - i, p);
379           break;
380         }
381 
382         // This loop will eventually terminate when |i| falls below
383         // |BN_MUL_RECURSIVE_SIZE_NORMAL| because we know one of |tna| and |tnb|
384         // exceeds that.
385       }
386     }
387   }
388 
389   // t0,t1,c = r0,r1 + r2,r3 = a0*b0 + a1*b1
390   BN_ULONG c = bn_add_words(t, r, &r[n2], n2);
391 
392   // t2,t3,c = t0,t1,c + neg*t2,t3 = (a0 - a1)*(b1 - b0) + a1*b1 + a0*b0.
393   // The second term is stored as the absolute value, so we do this with a
394   // constant-time select.
395   BN_ULONG c_neg = c - bn_sub_words(&t[n2 * 2], t, &t[n2], n2);
396   BN_ULONG c_pos = c + bn_add_words(&t[n2], t, &t[n2], n2);
397   bn_select_words(&t[n2], neg, &t[n2 * 2], &t[n2], n2);
398   OPENSSL_STATIC_ASSERT(sizeof(BN_ULONG) <= sizeof(crypto_word_t),
399                         "crypto_word_t is too small");
400   c = constant_time_select_w(neg, c_neg, c_pos);
401 
402   // We now have our three components. Add them together.
403   // r1,r2,c = r1,r2 + t2,t3,c
404   c += bn_add_words(&r[n], &r[n], &t[n2], n2);
405 
406   // Propagate the carry bit to the end.
407   for (int i = n + n2; i < n2 + n2; i++) {
408     BN_ULONG old = r[i];
409     r[i] = old + c;
410     c = r[i] < old;
411   }
412 
413   // The product should fit without carries.
414   assert(c == 0);
415 }
416 
417 // bn_mul_impl implements |BN_mul| and |bn_mul_consttime|. Note this function
418 // breaks |BIGNUM| invariants and may return a negative zero. This is handled by
419 // the callers.
bn_mul_impl(BIGNUM * r,const BIGNUM * a,const BIGNUM * b,BN_CTX * ctx)420 static int bn_mul_impl(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
421                        BN_CTX *ctx) {
422   int al = a->width;
423   int bl = b->width;
424   if (al == 0 || bl == 0) {
425     BN_zero(r);
426     return 1;
427   }
428 
429   int ret = 0;
430   BIGNUM *rr;
431   BN_CTX_start(ctx);
432   if (r == a || r == b) {
433     rr = BN_CTX_get(ctx);
434     if (rr == NULL) {
435       goto err;
436     }
437   } else {
438     rr = r;
439   }
440   rr->neg = a->neg ^ b->neg;
441 
442   int i = al - bl;
443   if (i == 0) {
444     if (al == 8) {
445       if (!bn_wexpand(rr, 16)) {
446         goto err;
447       }
448       rr->width = 16;
449       bn_mul_comba8(rr->d, a->d, b->d);
450       goto end;
451     }
452   }
453 
454   int top = al + bl;
455   static const int kMulNormalSize = 16;
456   if (al >= kMulNormalSize && bl >= kMulNormalSize) {
457     if (-1 <= i && i <= 1) {
458       // Find the largest power of two less than or equal to the larger length.
459       int j;
460       if (i >= 0) {
461         j = BN_num_bits_word((BN_ULONG)al);
462       } else {
463         j = BN_num_bits_word((BN_ULONG)bl);
464       }
465       j = 1 << (j - 1);
466       assert(j <= al || j <= bl);
467       BIGNUM *t = BN_CTX_get(ctx);
468       if (t == NULL) {
469         goto err;
470       }
471       if (al > j || bl > j) {
472         // We know |al| and |bl| are at most one from each other, so if al > j,
473         // bl >= j, and vice versa. Thus we can use |bn_mul_part_recursive|.
474         //
475         // TODO(davidben): This codepath is almost unused in standard
476         // algorithms. Is this optimization necessary? See notes in
477         // https://boringssl-review.googlesource.com/q/I0bd604e2cd6a75c266f64476c23a730ca1721ea6
478         assert(al >= j && bl >= j);
479         if (!bn_wexpand(t, j * 8) ||
480             !bn_wexpand(rr, j * 4)) {
481           goto err;
482         }
483         bn_mul_part_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d);
484       } else {
485         // al <= j && bl <= j. Additionally, we know j <= al or j <= bl, so one
486         // of al - j or bl - j is zero. The other, by the bound on |i| above, is
487         // zero or -1. Thus, we can use |bn_mul_recursive|.
488         if (!bn_wexpand(t, j * 4) ||
489             !bn_wexpand(rr, j * 2)) {
490           goto err;
491         }
492         bn_mul_recursive(rr->d, a->d, b->d, j, al - j, bl - j, t->d);
493       }
494       rr->width = top;
495       goto end;
496     }
497   }
498 
499   if (!bn_wexpand(rr, top)) {
500     goto err;
501   }
502   rr->width = top;
503   bn_mul_normal(rr->d, a->d, al, b->d, bl);
504 
505 end:
506   if (r != rr && !BN_copy(r, rr)) {
507     goto err;
508   }
509   ret = 1;
510 
511 err:
512   BN_CTX_end(ctx);
513   return ret;
514 }
515 
BN_mul(BIGNUM * r,const BIGNUM * a,const BIGNUM * b,BN_CTX * ctx)516 int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) {
517   if (!bn_mul_impl(r, a, b, ctx)) {
518     return 0;
519   }
520 
521   // This additionally fixes any negative zeros created by |bn_mul_impl|.
522   bn_set_minimal_width(r);
523   return 1;
524 }
525 
bn_mul_consttime(BIGNUM * r,const BIGNUM * a,const BIGNUM * b,BN_CTX * ctx)526 int bn_mul_consttime(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx) {
527   // Prevent negative zeros.
528   if (a->neg || b->neg) {
529     OPENSSL_PUT_ERROR(BN, BN_R_NEGATIVE_NUMBER);
530     return 0;
531   }
532 
533   return bn_mul_impl(r, a, b, ctx);
534 }
535 
bn_mul_small(BN_ULONG * r,size_t num_r,const BN_ULONG * a,size_t num_a,const BN_ULONG * b,size_t num_b)536 void bn_mul_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a,
537                   const BN_ULONG *b, size_t num_b) {
538   if (num_r != num_a + num_b) {
539     abort();
540   }
541   // TODO(davidben): Should this call |bn_mul_comba4| too? |BN_mul| does not
542   // hit that code.
543   if (num_a == 8 && num_b == 8) {
544     bn_mul_comba8(r, a, b);
545   } else {
546     bn_mul_normal(r, a, num_a, b, num_b);
547   }
548 }
549 
550 // tmp must have 2*n words
bn_sqr_normal(BN_ULONG * r,const BN_ULONG * a,size_t n,BN_ULONG * tmp)551 static void bn_sqr_normal(BN_ULONG *r, const BN_ULONG *a, size_t n,
552                           BN_ULONG *tmp) {
553   if (n == 0) {
554     return;
555   }
556 
557   size_t max = n * 2;
558   const BN_ULONG *ap = a;
559   BN_ULONG *rp = r;
560   rp[0] = rp[max - 1] = 0;
561   rp++;
562 
563   // Compute the contribution of a[i] * a[j] for all i < j.
564   if (n > 1) {
565     ap++;
566     rp[n - 1] = bn_mul_words(rp, ap, n - 1, ap[-1]);
567     rp += 2;
568   }
569   if (n > 2) {
570     for (size_t i = n - 2; i > 0; i--) {
571       ap++;
572       rp[i] = bn_mul_add_words(rp, ap, i, ap[-1]);
573       rp += 2;
574     }
575   }
576 
577   // The final result fits in |max| words, so none of the following operations
578   // will overflow.
579 
580   // Double |r|, giving the contribution of a[i] * a[j] for all i != j.
581   bn_add_words(r, r, r, max);
582 
583   // Add in the contribution of a[i] * a[i] for all i.
584   bn_sqr_words(tmp, a, n);
585   bn_add_words(r, r, tmp, max);
586 }
587 
588 // bn_sqr_recursive sets |r| to |a|^2, using |t| as scratch space. |r| has
589 // length 2*|n2|, |a| has length |n2|, and |t| has length 4*|n2|. |n2| must be
590 // a power of two.
bn_sqr_recursive(BN_ULONG * r,const BN_ULONG * a,size_t n2,BN_ULONG * t)591 static void bn_sqr_recursive(BN_ULONG *r, const BN_ULONG *a, size_t n2,
592                              BN_ULONG *t) {
593   // |n2| is a power of two.
594   assert(n2 != 0 && (n2 & (n2 - 1)) == 0);
595 
596   if (n2 == 4) {
597     bn_sqr_comba4(r, a);
598     return;
599   }
600   if (n2 == 8) {
601     bn_sqr_comba8(r, a);
602     return;
603   }
604   if (n2 < BN_SQR_RECURSIVE_SIZE_NORMAL) {
605     bn_sqr_normal(r, a, n2, t);
606     return;
607   }
608 
609   // Split |a| into a0,a1, each of size |n|.
610   // Split |t| into t0,t1,t2,t3, each of size |n|, with the remaining 4*|n| used
611   // for recursive calls.
612   // Split |r| into r0,r1,r2,r3. We must contribute a0^2 to r0,r1, 2*a0*a1 to
613   // r1,r2, and a1^2 to r2,r3.
614   size_t n = n2 / 2;
615   BN_ULONG *t_recursive = &t[n2 * 2];
616 
617   // t0 = |a0 - a1|.
618   bn_abs_sub_words(t, a, &a[n], n, &t[n]);
619   // t2,t3 = t0^2 = |a0 - a1|^2 = a0^2 - 2*a0*a1 + a1^2
620   bn_sqr_recursive(&t[n2], t, n, t_recursive);
621 
622   // r0,r1 = a0^2
623   bn_sqr_recursive(r, a, n, t_recursive);
624 
625   // r2,r3 = a1^2
626   bn_sqr_recursive(&r[n2], &a[n], n, t_recursive);
627 
628   // t0,t1,c = r0,r1 + r2,r3 = a0^2 + a1^2
629   BN_ULONG c = bn_add_words(t, r, &r[n2], n2);
630   // t2,t3,c = t0,t1,c - t2,t3 = 2*a0*a1
631   c -= bn_sub_words(&t[n2], t, &t[n2], n2);
632 
633   // We now have our three components. Add them together.
634   // r1,r2,c = r1,r2 + t2,t3,c
635   c += bn_add_words(&r[n], &r[n], &t[n2], n2);
636 
637   // Propagate the carry bit to the end.
638   for (size_t i = n + n2; i < n2 + n2; i++) {
639     BN_ULONG old = r[i];
640     r[i] = old + c;
641     c = r[i] < old;
642   }
643 
644   // The square should fit without carries.
645   assert(c == 0);
646 }
647 
BN_mul_word(BIGNUM * bn,BN_ULONG w)648 int BN_mul_word(BIGNUM *bn, BN_ULONG w) {
649   if (!bn->width) {
650     return 1;
651   }
652 
653   if (w == 0) {
654     BN_zero(bn);
655     return 1;
656   }
657 
658   BN_ULONG ll = bn_mul_words(bn->d, bn->d, bn->width, w);
659   if (ll) {
660     if (!bn_wexpand(bn, bn->width + 1)) {
661       return 0;
662     }
663     bn->d[bn->width++] = ll;
664   }
665 
666   return 1;
667 }
668 
bn_sqr_consttime(BIGNUM * r,const BIGNUM * a,BN_CTX * ctx)669 int bn_sqr_consttime(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) {
670   int al = a->width;
671   if (al <= 0) {
672     r->width = 0;
673     r->neg = 0;
674     return 1;
675   }
676 
677   int ret = 0;
678   BN_CTX_start(ctx);
679   BIGNUM *rr = (a != r) ? r : BN_CTX_get(ctx);
680   BIGNUM *tmp = BN_CTX_get(ctx);
681   if (!rr || !tmp) {
682     goto err;
683   }
684 
685   int max = 2 * al;  // Non-zero (from above)
686   if (!bn_wexpand(rr, max)) {
687     goto err;
688   }
689 
690   if (al == 4) {
691     bn_sqr_comba4(rr->d, a->d);
692   } else if (al == 8) {
693     bn_sqr_comba8(rr->d, a->d);
694   } else {
695     if (al < BN_SQR_RECURSIVE_SIZE_NORMAL) {
696       BN_ULONG t[BN_SQR_RECURSIVE_SIZE_NORMAL * 2];
697       bn_sqr_normal(rr->d, a->d, al, t);
698     } else {
699       // If |al| is a power of two, we can use |bn_sqr_recursive|.
700       if (al != 0 && (al & (al - 1)) == 0) {
701         if (!bn_wexpand(tmp, al * 4)) {
702           goto err;
703         }
704         bn_sqr_recursive(rr->d, a->d, al, tmp->d);
705       } else {
706         if (!bn_wexpand(tmp, max)) {
707           goto err;
708         }
709         bn_sqr_normal(rr->d, a->d, al, tmp->d);
710       }
711     }
712   }
713 
714   rr->neg = 0;
715   rr->width = max;
716 
717   if (rr != r && !BN_copy(r, rr)) {
718     goto err;
719   }
720   ret = 1;
721 
722 err:
723   BN_CTX_end(ctx);
724   return ret;
725 }
726 
BN_sqr(BIGNUM * r,const BIGNUM * a,BN_CTX * ctx)727 int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) {
728   if (!bn_sqr_consttime(r, a, ctx)) {
729     return 0;
730   }
731 
732   bn_set_minimal_width(r);
733   return 1;
734 }
735 
bn_sqr_small(BN_ULONG * r,size_t num_r,const BN_ULONG * a,size_t num_a)736 void bn_sqr_small(BN_ULONG *r, size_t num_r, const BN_ULONG *a, size_t num_a) {
737   if (num_r != 2 * num_a || num_a > BN_SMALL_MAX_WORDS) {
738     abort();
739   }
740   if (num_a == 4) {
741     bn_sqr_comba4(r, a);
742   } else if (num_a == 8) {
743     bn_sqr_comba8(r, a);
744   } else {
745     BN_ULONG tmp[2 * BN_SMALL_MAX_WORDS];
746     bn_sqr_normal(r, a, num_a, tmp);
747     OPENSSL_cleanse(tmp, 2 * num_a * sizeof(BN_ULONG));
748   }
749 }
750