Address some -Wold-style-declaration warnings
[openssl.git] / crypto / ec / ecp_nistz256.c
1 /*
2  * Copyright 2014-2016 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  *                                                                            *
12  * Copyright 2014 Intel Corporation                                           *
13  *                                                                            *
14  * Licensed under the Apache License, Version 2.0 (the "License");            *
15  * you may not use this file except in compliance with the License.           *
16  * You may obtain a copy of the License at                                    *
17  *                                                                            *
18  *    http://www.apache.org/licenses/LICENSE-2.0                              *
19  *                                                                            *
20  * Unless required by applicable law or agreed to in writing, software        *
21  * distributed under the License is distributed on an "AS IS" BASIS,          *
22  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
23  * See the License for the specific language governing permissions and        *
24  * limitations under the License.                                             *
25  *                                                                            *
26  ******************************************************************************
27  *                                                                            *
28  * Developers and authors:                                                    *
29  * Shay Gueron (1, 2), and Vlad Krasnov (1)                                   *
30  * (1) Intel Corporation, Israel Development Center                           *
31  * (2) University of Haifa                                                    *
32  * Reference:                                                                 *
33  * S.Gueron and V.Krasnov, "Fast Prime Field Elliptic Curve Cryptography with *
34  *                          256 Bit Primes"                                   *
35  *                                                                            *
36  ******************************************************************************/
37
38 #include <string.h>
39
40 #include "internal/cryptlib.h"
41 #include "internal/bn_int.h"
42 #include "ec_lcl.h"
43
44 #if BN_BITS2 != 64
45 # define TOBN(hi,lo)    lo,hi
46 #else
47 # define TOBN(hi,lo)    ((BN_ULONG)hi<<32|lo)
48 #endif
49
50 #if defined(__GNUC__)
51 # define ALIGN32        __attribute((aligned(32)))
52 #elif defined(_MSC_VER)
53 # define ALIGN32        __declspec(align(32))
54 #else
55 # define ALIGN32
56 #endif
57
58 #define ALIGNPTR(p,N)   ((unsigned char *)p+N-(size_t)p%N)
59 #define P256_LIMBS      (256/BN_BITS2)
60
61 typedef unsigned short u16;
62
63 typedef struct {
64     BN_ULONG X[P256_LIMBS];
65     BN_ULONG Y[P256_LIMBS];
66     BN_ULONG Z[P256_LIMBS];
67 } P256_POINT;
68
69 typedef struct {
70     BN_ULONG X[P256_LIMBS];
71     BN_ULONG Y[P256_LIMBS];
72 } P256_POINT_AFFINE;
73
74 typedef P256_POINT_AFFINE PRECOMP256_ROW[64];
75
76 /* structure for precomputed multiples of the generator */
77 struct nistz256_pre_comp_st {
78     const EC_GROUP *group;      /* Parent EC_GROUP object */
79     size_t w;                   /* Window size */
80     /*
81      * Constant time access to the X and Y coordinates of the pre-computed,
82      * generator multiplies, in the Montgomery domain. Pre-calculated
83      * multiplies are stored in affine form.
84      */
85     PRECOMP256_ROW *precomp;
86     void *precomp_storage;
87     CRYPTO_REF_COUNT references;
88     CRYPTO_RWLOCK *lock;
89 };
90
91 /* Functions implemented in assembly */
92 /*
93  * Most of below mentioned functions *preserve* the property of inputs
94  * being fully reduced, i.e. being in [0, modulus) range. Simply put if
95  * inputs are fully reduced, then output is too. Note that reverse is
96  * not true, in sense that given partially reduced inputs output can be
97  * either, not unlikely reduced. And "most" in first sentence refers to
98  * the fact that given the calculations flow one can tolerate that
99  * addition, 1st function below, produces partially reduced result *if*
100  * multiplications by 2 and 3, which customarily use addition, fully
101  * reduce it. This effectively gives two options: a) addition produces
102  * fully reduced result [as long as inputs are, just like remaining
103  * functions]; b) addition is allowed to produce partially reduced
104  * result, but multiplications by 2 and 3 perform additional reduction
105  * step. Choice between the two can be platform-specific, but it was a)
106  * in all cases so far...
107  */
108 /* Modular add: res = a+b mod P   */
109 void ecp_nistz256_add(BN_ULONG res[P256_LIMBS],
110                       const BN_ULONG a[P256_LIMBS],
111                       const BN_ULONG b[P256_LIMBS]);
112 /* Modular mul by 2: res = 2*a mod P */
113 void ecp_nistz256_mul_by_2(BN_ULONG res[P256_LIMBS],
114                            const BN_ULONG a[P256_LIMBS]);
115 /* Modular mul by 3: res = 3*a mod P */
116 void ecp_nistz256_mul_by_3(BN_ULONG res[P256_LIMBS],
117                            const BN_ULONG a[P256_LIMBS]);
118
119 /* Modular div by 2: res = a/2 mod P */
120 void ecp_nistz256_div_by_2(BN_ULONG res[P256_LIMBS],
121                            const BN_ULONG a[P256_LIMBS]);
122 /* Modular sub: res = a-b mod P   */
123 void ecp_nistz256_sub(BN_ULONG res[P256_LIMBS],
124                       const BN_ULONG a[P256_LIMBS],
125                       const BN_ULONG b[P256_LIMBS]);
126 /* Modular neg: res = -a mod P    */
127 void ecp_nistz256_neg(BN_ULONG res[P256_LIMBS], const BN_ULONG a[P256_LIMBS]);
128 /* Montgomery mul: res = a*b*2^-256 mod P */
129 void ecp_nistz256_mul_mont(BN_ULONG res[P256_LIMBS],
130                            const BN_ULONG a[P256_LIMBS],
131                            const BN_ULONG b[P256_LIMBS]);
132 /* Montgomery sqr: res = a*a*2^-256 mod P */
133 void ecp_nistz256_sqr_mont(BN_ULONG res[P256_LIMBS],
134                            const BN_ULONG a[P256_LIMBS]);
135 /* Convert a number from Montgomery domain, by multiplying with 1 */
136 void ecp_nistz256_from_mont(BN_ULONG res[P256_LIMBS],
137                             const BN_ULONG in[P256_LIMBS]);
138 /* Convert a number to Montgomery domain, by multiplying with 2^512 mod P*/
139 void ecp_nistz256_to_mont(BN_ULONG res[P256_LIMBS],
140                           const BN_ULONG in[P256_LIMBS]);
141 /* Functions that perform constant time access to the precomputed tables */
142 void ecp_nistz256_scatter_w5(P256_POINT *val,
143                              const P256_POINT *in_t, int idx);
144 void ecp_nistz256_gather_w5(P256_POINT *val,
145                             const P256_POINT *in_t, int idx);
146 void ecp_nistz256_scatter_w7(P256_POINT_AFFINE *val,
147                              const P256_POINT_AFFINE *in_t, int idx);
148 void ecp_nistz256_gather_w7(P256_POINT_AFFINE *val,
149                             const P256_POINT_AFFINE *in_t, int idx);
150
151 /* One converted into the Montgomery domain */
152 static const BN_ULONG ONE[P256_LIMBS] = {
153     TOBN(0x00000000, 0x00000001), TOBN(0xffffffff, 0x00000000),
154     TOBN(0xffffffff, 0xffffffff), TOBN(0x00000000, 0xfffffffe)
155 };
156
157 static NISTZ256_PRE_COMP *ecp_nistz256_pre_comp_new(const EC_GROUP *group);
158
159 /* Precomputed tables for the default generator */
160 extern const PRECOMP256_ROW ecp_nistz256_precomputed[37];
161
162 /* Recode window to a signed digit, see ecp_nistputil.c for details */
163 static unsigned int _booth_recode_w5(unsigned int in)
164 {
165     unsigned int s, d;
166
167     s = ~((in >> 5) - 1);
168     d = (1 << 6) - in - 1;
169     d = (d & s) | (in & ~s);
170     d = (d >> 1) + (d & 1);
171
172     return (d << 1) + (s & 1);
173 }
174
175 static unsigned int _booth_recode_w7(unsigned int in)
176 {
177     unsigned int s, d;
178
179     s = ~((in >> 7) - 1);
180     d = (1 << 8) - in - 1;
181     d = (d & s) | (in & ~s);
182     d = (d >> 1) + (d & 1);
183
184     return (d << 1) + (s & 1);
185 }
186
187 static void copy_conditional(BN_ULONG dst[P256_LIMBS],
188                              const BN_ULONG src[P256_LIMBS], BN_ULONG move)
189 {
190     BN_ULONG mask1 = 0-move;
191     BN_ULONG mask2 = ~mask1;
192
193     dst[0] = (src[0] & mask1) ^ (dst[0] & mask2);
194     dst[1] = (src[1] & mask1) ^ (dst[1] & mask2);
195     dst[2] = (src[2] & mask1) ^ (dst[2] & mask2);
196     dst[3] = (src[3] & mask1) ^ (dst[3] & mask2);
197     if (P256_LIMBS == 8) {
198         dst[4] = (src[4] & mask1) ^ (dst[4] & mask2);
199         dst[5] = (src[5] & mask1) ^ (dst[5] & mask2);
200         dst[6] = (src[6] & mask1) ^ (dst[6] & mask2);
201         dst[7] = (src[7] & mask1) ^ (dst[7] & mask2);
202     }
203 }
204
205 static BN_ULONG is_zero(BN_ULONG in)
206 {
207     in |= (0 - in);
208     in = ~in;
209     in >>= BN_BITS2 - 1;
210     return in;
211 }
212
213 static BN_ULONG is_equal(const BN_ULONG a[P256_LIMBS],
214                          const BN_ULONG b[P256_LIMBS])
215 {
216     BN_ULONG res;
217
218     res = a[0] ^ b[0];
219     res |= a[1] ^ b[1];
220     res |= a[2] ^ b[2];
221     res |= a[3] ^ b[3];
222     if (P256_LIMBS == 8) {
223         res |= a[4] ^ b[4];
224         res |= a[5] ^ b[5];
225         res |= a[6] ^ b[6];
226         res |= a[7] ^ b[7];
227     }
228
229     return is_zero(res);
230 }
231
232 static BN_ULONG is_one(const BIGNUM *z)
233 {
234     BN_ULONG res = 0;
235     BN_ULONG *a = bn_get_words(z);
236
237     if (bn_get_top(z) == (P256_LIMBS - P256_LIMBS / 8)) {
238         res = a[0] ^ ONE[0];
239         res |= a[1] ^ ONE[1];
240         res |= a[2] ^ ONE[2];
241         res |= a[3] ^ ONE[3];
242         if (P256_LIMBS == 8) {
243             res |= a[4] ^ ONE[4];
244             res |= a[5] ^ ONE[5];
245             res |= a[6] ^ ONE[6];
246             /*
247              * no check for a[7] (being zero) on 32-bit platforms,
248              * because value of "one" takes only 7 limbs.
249              */
250         }
251         res = is_zero(res);
252     }
253
254     return res;
255 }
256
257 /*
258  * For reference, this macro is used only when new ecp_nistz256 assembly
259  * module is being developed.  For example, configure with
260  * -DECP_NISTZ256_REFERENCE_IMPLEMENTATION and implement only functions
261  * performing simplest arithmetic operations on 256-bit vectors. Then
262  * work on implementation of higher-level functions performing point
263  * operations. Then remove ECP_NISTZ256_REFERENCE_IMPLEMENTATION
264  * and never define it again. (The correct macro denoting presence of
265  * ecp_nistz256 module is ECP_NISTZ256_ASM.)
266  */
267 #ifndef ECP_NISTZ256_REFERENCE_IMPLEMENTATION
268 void ecp_nistz256_point_double(P256_POINT *r, const P256_POINT *a);
269 void ecp_nistz256_point_add(P256_POINT *r,
270                             const P256_POINT *a, const P256_POINT *b);
271 void ecp_nistz256_point_add_affine(P256_POINT *r,
272                                    const P256_POINT *a,
273                                    const P256_POINT_AFFINE *b);
274 #else
275 /* Point double: r = 2*a */
276 static void ecp_nistz256_point_double(P256_POINT *r, const P256_POINT *a)
277 {
278     BN_ULONG S[P256_LIMBS];
279     BN_ULONG M[P256_LIMBS];
280     BN_ULONG Zsqr[P256_LIMBS];
281     BN_ULONG tmp0[P256_LIMBS];
282
283     const BN_ULONG *in_x = a->X;
284     const BN_ULONG *in_y = a->Y;
285     const BN_ULONG *in_z = a->Z;
286
287     BN_ULONG *res_x = r->X;
288     BN_ULONG *res_y = r->Y;
289     BN_ULONG *res_z = r->Z;
290
291     ecp_nistz256_mul_by_2(S, in_y);
292
293     ecp_nistz256_sqr_mont(Zsqr, in_z);
294
295     ecp_nistz256_sqr_mont(S, S);
296
297     ecp_nistz256_mul_mont(res_z, in_z, in_y);
298     ecp_nistz256_mul_by_2(res_z, res_z);
299
300     ecp_nistz256_add(M, in_x, Zsqr);
301     ecp_nistz256_sub(Zsqr, in_x, Zsqr);
302
303     ecp_nistz256_sqr_mont(res_y, S);
304     ecp_nistz256_div_by_2(res_y, res_y);
305
306     ecp_nistz256_mul_mont(M, M, Zsqr);
307     ecp_nistz256_mul_by_3(M, M);
308
309     ecp_nistz256_mul_mont(S, S, in_x);
310     ecp_nistz256_mul_by_2(tmp0, S);
311
312     ecp_nistz256_sqr_mont(res_x, M);
313
314     ecp_nistz256_sub(res_x, res_x, tmp0);
315     ecp_nistz256_sub(S, S, res_x);
316
317     ecp_nistz256_mul_mont(S, S, M);
318     ecp_nistz256_sub(res_y, S, res_y);
319 }
320
321 /* Point addition: r = a+b */
322 static void ecp_nistz256_point_add(P256_POINT *r,
323                                    const P256_POINT *a, const P256_POINT *b)
324 {
325     BN_ULONG U2[P256_LIMBS], S2[P256_LIMBS];
326     BN_ULONG U1[P256_LIMBS], S1[P256_LIMBS];
327     BN_ULONG Z1sqr[P256_LIMBS];
328     BN_ULONG Z2sqr[P256_LIMBS];
329     BN_ULONG H[P256_LIMBS], R[P256_LIMBS];
330     BN_ULONG Hsqr[P256_LIMBS];
331     BN_ULONG Rsqr[P256_LIMBS];
332     BN_ULONG Hcub[P256_LIMBS];
333
334     BN_ULONG res_x[P256_LIMBS];
335     BN_ULONG res_y[P256_LIMBS];
336     BN_ULONG res_z[P256_LIMBS];
337
338     BN_ULONG in1infty, in2infty;
339
340     const BN_ULONG *in1_x = a->X;
341     const BN_ULONG *in1_y = a->Y;
342     const BN_ULONG *in1_z = a->Z;
343
344     const BN_ULONG *in2_x = b->X;
345     const BN_ULONG *in2_y = b->Y;
346     const BN_ULONG *in2_z = b->Z;
347
348     /*
349      * Infinity in encoded as (,,0)
350      */
351     in1infty = (in1_z[0] | in1_z[1] | in1_z[2] | in1_z[3]);
352     if (P256_LIMBS == 8)
353         in1infty |= (in1_z[4] | in1_z[5] | in1_z[6] | in1_z[7]);
354
355     in2infty = (in2_z[0] | in2_z[1] | in2_z[2] | in2_z[3]);
356     if (P256_LIMBS == 8)
357         in2infty |= (in2_z[4] | in2_z[5] | in2_z[6] | in2_z[7]);
358
359     in1infty = is_zero(in1infty);
360     in2infty = is_zero(in2infty);
361
362     ecp_nistz256_sqr_mont(Z2sqr, in2_z);        /* Z2^2 */
363     ecp_nistz256_sqr_mont(Z1sqr, in1_z);        /* Z1^2 */
364
365     ecp_nistz256_mul_mont(S1, Z2sqr, in2_z);    /* S1 = Z2^3 */
366     ecp_nistz256_mul_mont(S2, Z1sqr, in1_z);    /* S2 = Z1^3 */
367
368     ecp_nistz256_mul_mont(S1, S1, in1_y);       /* S1 = Y1*Z2^3 */
369     ecp_nistz256_mul_mont(S2, S2, in2_y);       /* S2 = Y2*Z1^3 */
370     ecp_nistz256_sub(R, S2, S1);                /* R = S2 - S1 */
371
372     ecp_nistz256_mul_mont(U1, in1_x, Z2sqr);    /* U1 = X1*Z2^2 */
373     ecp_nistz256_mul_mont(U2, in2_x, Z1sqr);    /* U2 = X2*Z1^2 */
374     ecp_nistz256_sub(H, U2, U1);                /* H = U2 - U1 */
375
376     /*
377      * This should not happen during sign/ecdh, so no constant time violation
378      */
379     if (is_equal(U1, U2) && !in1infty && !in2infty) {
380         if (is_equal(S1, S2)) {
381             ecp_nistz256_point_double(r, a);
382             return;
383         } else {
384             memset(r, 0, sizeof(*r));
385             return;
386         }
387     }
388
389     ecp_nistz256_sqr_mont(Rsqr, R);             /* R^2 */
390     ecp_nistz256_mul_mont(res_z, H, in1_z);     /* Z3 = H*Z1*Z2 */
391     ecp_nistz256_sqr_mont(Hsqr, H);             /* H^2 */
392     ecp_nistz256_mul_mont(res_z, res_z, in2_z); /* Z3 = H*Z1*Z2 */
393     ecp_nistz256_mul_mont(Hcub, Hsqr, H);       /* H^3 */
394
395     ecp_nistz256_mul_mont(U2, U1, Hsqr);        /* U1*H^2 */
396     ecp_nistz256_mul_by_2(Hsqr, U2);            /* 2*U1*H^2 */
397
398     ecp_nistz256_sub(res_x, Rsqr, Hsqr);
399     ecp_nistz256_sub(res_x, res_x, Hcub);
400
401     ecp_nistz256_sub(res_y, U2, res_x);
402
403     ecp_nistz256_mul_mont(S2, S1, Hcub);
404     ecp_nistz256_mul_mont(res_y, R, res_y);
405     ecp_nistz256_sub(res_y, res_y, S2);
406
407     copy_conditional(res_x, in2_x, in1infty);
408     copy_conditional(res_y, in2_y, in1infty);
409     copy_conditional(res_z, in2_z, in1infty);
410
411     copy_conditional(res_x, in1_x, in2infty);
412     copy_conditional(res_y, in1_y, in2infty);
413     copy_conditional(res_z, in1_z, in2infty);
414
415     memcpy(r->X, res_x, sizeof(res_x));
416     memcpy(r->Y, res_y, sizeof(res_y));
417     memcpy(r->Z, res_z, sizeof(res_z));
418 }
419
420 /* Point addition when b is known to be affine: r = a+b */
421 static void ecp_nistz256_point_add_affine(P256_POINT *r,
422                                           const P256_POINT *a,
423                                           const P256_POINT_AFFINE *b)
424 {
425     BN_ULONG U2[P256_LIMBS], S2[P256_LIMBS];
426     BN_ULONG Z1sqr[P256_LIMBS];
427     BN_ULONG H[P256_LIMBS], R[P256_LIMBS];
428     BN_ULONG Hsqr[P256_LIMBS];
429     BN_ULONG Rsqr[P256_LIMBS];
430     BN_ULONG Hcub[P256_LIMBS];
431
432     BN_ULONG res_x[P256_LIMBS];
433     BN_ULONG res_y[P256_LIMBS];
434     BN_ULONG res_z[P256_LIMBS];
435
436     BN_ULONG in1infty, in2infty;
437
438     const BN_ULONG *in1_x = a->X;
439     const BN_ULONG *in1_y = a->Y;
440     const BN_ULONG *in1_z = a->Z;
441
442     const BN_ULONG *in2_x = b->X;
443     const BN_ULONG *in2_y = b->Y;
444
445     /*
446      * Infinity in encoded as (,,0)
447      */
448     in1infty = (in1_z[0] | in1_z[1] | in1_z[2] | in1_z[3]);
449     if (P256_LIMBS == 8)
450         in1infty |= (in1_z[4] | in1_z[5] | in1_z[6] | in1_z[7]);
451
452     /*
453      * In affine representation we encode infinity as (0,0), which is
454      * not on the curve, so it is OK
455      */
456     in2infty = (in2_x[0] | in2_x[1] | in2_x[2] | in2_x[3] |
457                 in2_y[0] | in2_y[1] | in2_y[2] | in2_y[3]);
458     if (P256_LIMBS == 8)
459         in2infty |= (in2_x[4] | in2_x[5] | in2_x[6] | in2_x[7] |
460                      in2_y[4] | in2_y[5] | in2_y[6] | in2_y[7]);
461
462     in1infty = is_zero(in1infty);
463     in2infty = is_zero(in2infty);
464
465     ecp_nistz256_sqr_mont(Z1sqr, in1_z);        /* Z1^2 */
466
467     ecp_nistz256_mul_mont(U2, in2_x, Z1sqr);    /* U2 = X2*Z1^2 */
468     ecp_nistz256_sub(H, U2, in1_x);             /* H = U2 - U1 */
469
470     ecp_nistz256_mul_mont(S2, Z1sqr, in1_z);    /* S2 = Z1^3 */
471
472     ecp_nistz256_mul_mont(res_z, H, in1_z);     /* Z3 = H*Z1*Z2 */
473
474     ecp_nistz256_mul_mont(S2, S2, in2_y);       /* S2 = Y2*Z1^3 */
475     ecp_nistz256_sub(R, S2, in1_y);             /* R = S2 - S1 */
476
477     ecp_nistz256_sqr_mont(Hsqr, H);             /* H^2 */
478     ecp_nistz256_sqr_mont(Rsqr, R);             /* R^2 */
479     ecp_nistz256_mul_mont(Hcub, Hsqr, H);       /* H^3 */
480
481     ecp_nistz256_mul_mont(U2, in1_x, Hsqr);     /* U1*H^2 */
482     ecp_nistz256_mul_by_2(Hsqr, U2);            /* 2*U1*H^2 */
483
484     ecp_nistz256_sub(res_x, Rsqr, Hsqr);
485     ecp_nistz256_sub(res_x, res_x, Hcub);
486     ecp_nistz256_sub(H, U2, res_x);
487
488     ecp_nistz256_mul_mont(S2, in1_y, Hcub);
489     ecp_nistz256_mul_mont(H, H, R);
490     ecp_nistz256_sub(res_y, H, S2);
491
492     copy_conditional(res_x, in2_x, in1infty);
493     copy_conditional(res_x, in1_x, in2infty);
494
495     copy_conditional(res_y, in2_y, in1infty);
496     copy_conditional(res_y, in1_y, in2infty);
497
498     copy_conditional(res_z, ONE, in1infty);
499     copy_conditional(res_z, in1_z, in2infty);
500
501     memcpy(r->X, res_x, sizeof(res_x));
502     memcpy(r->Y, res_y, sizeof(res_y));
503     memcpy(r->Z, res_z, sizeof(res_z));
504 }
505 #endif
506
507 /* r = in^-1 mod p */
508 static void ecp_nistz256_mod_inverse(BN_ULONG r[P256_LIMBS],
509                                      const BN_ULONG in[P256_LIMBS])
510 {
511     /*
512      * The poly is ffffffff 00000001 00000000 00000000 00000000 ffffffff
513      * ffffffff ffffffff We use FLT and used poly-2 as exponent
514      */
515     BN_ULONG p2[P256_LIMBS];
516     BN_ULONG p4[P256_LIMBS];
517     BN_ULONG p8[P256_LIMBS];
518     BN_ULONG p16[P256_LIMBS];
519     BN_ULONG p32[P256_LIMBS];
520     BN_ULONG res[P256_LIMBS];
521     int i;
522
523     ecp_nistz256_sqr_mont(res, in);
524     ecp_nistz256_mul_mont(p2, res, in);         /* 3*p */
525
526     ecp_nistz256_sqr_mont(res, p2);
527     ecp_nistz256_sqr_mont(res, res);
528     ecp_nistz256_mul_mont(p4, res, p2);         /* f*p */
529
530     ecp_nistz256_sqr_mont(res, p4);
531     ecp_nistz256_sqr_mont(res, res);
532     ecp_nistz256_sqr_mont(res, res);
533     ecp_nistz256_sqr_mont(res, res);
534     ecp_nistz256_mul_mont(p8, res, p4);         /* ff*p */
535
536     ecp_nistz256_sqr_mont(res, p8);
537     for (i = 0; i < 7; i++)
538         ecp_nistz256_sqr_mont(res, res);
539     ecp_nistz256_mul_mont(p16, res, p8);        /* ffff*p */
540
541     ecp_nistz256_sqr_mont(res, p16);
542     for (i = 0; i < 15; i++)
543         ecp_nistz256_sqr_mont(res, res);
544     ecp_nistz256_mul_mont(p32, res, p16);       /* ffffffff*p */
545
546     ecp_nistz256_sqr_mont(res, p32);
547     for (i = 0; i < 31; i++)
548         ecp_nistz256_sqr_mont(res, res);
549     ecp_nistz256_mul_mont(res, res, in);
550
551     for (i = 0; i < 32 * 4; i++)
552         ecp_nistz256_sqr_mont(res, res);
553     ecp_nistz256_mul_mont(res, res, p32);
554
555     for (i = 0; i < 32; i++)
556         ecp_nistz256_sqr_mont(res, res);
557     ecp_nistz256_mul_mont(res, res, p32);
558
559     for (i = 0; i < 16; i++)
560         ecp_nistz256_sqr_mont(res, res);
561     ecp_nistz256_mul_mont(res, res, p16);
562
563     for (i = 0; i < 8; i++)
564         ecp_nistz256_sqr_mont(res, res);
565     ecp_nistz256_mul_mont(res, res, p8);
566
567     ecp_nistz256_sqr_mont(res, res);
568     ecp_nistz256_sqr_mont(res, res);
569     ecp_nistz256_sqr_mont(res, res);
570     ecp_nistz256_sqr_mont(res, res);
571     ecp_nistz256_mul_mont(res, res, p4);
572
573     ecp_nistz256_sqr_mont(res, res);
574     ecp_nistz256_sqr_mont(res, res);
575     ecp_nistz256_mul_mont(res, res, p2);
576
577     ecp_nistz256_sqr_mont(res, res);
578     ecp_nistz256_sqr_mont(res, res);
579     ecp_nistz256_mul_mont(res, res, in);
580
581     memcpy(r, res, sizeof(res));
582 }
583
584 /*
585  * ecp_nistz256_bignum_to_field_elem copies the contents of |in| to |out| and
586  * returns one if it fits. Otherwise it returns zero.
587  */
588 __owur static int ecp_nistz256_bignum_to_field_elem(BN_ULONG out[P256_LIMBS],
589                                                     const BIGNUM *in)
590 {
591     return bn_copy_words(out, in, P256_LIMBS);
592 }
593
594 /* r = sum(scalar[i]*point[i]) */
595 __owur static int ecp_nistz256_windowed_mul(const EC_GROUP *group,
596                                             P256_POINT *r,
597                                             const BIGNUM **scalar,
598                                             const EC_POINT **point,
599                                             size_t num, BN_CTX *ctx)
600 {
601     size_t i;
602     int j, ret = 0;
603     unsigned int idx;
604     unsigned char (*p_str)[33] = NULL;
605     const unsigned int window_size = 5;
606     const unsigned int mask = (1 << (window_size + 1)) - 1;
607     unsigned int wvalue;
608     P256_POINT *temp;           /* place for 5 temporary points */
609     const BIGNUM **scalars = NULL;
610     P256_POINT (*table)[16] = NULL;
611     void *table_storage = NULL;
612
613     if ((num * 16 + 6) > OPENSSL_MALLOC_MAX_NELEMS(P256_POINT)
614         || (table_storage =
615             OPENSSL_malloc((num * 16 + 5) * sizeof(P256_POINT) + 64)) == NULL
616         || (p_str =
617             OPENSSL_malloc(num * 33 * sizeof(unsigned char))) == NULL
618         || (scalars = OPENSSL_malloc(num * sizeof(BIGNUM *))) == NULL) {
619         ECerr(EC_F_ECP_NISTZ256_WINDOWED_MUL, ERR_R_MALLOC_FAILURE);
620         goto err;
621     }
622
623     table = (void *)ALIGNPTR(table_storage, 64);
624     temp = (P256_POINT *)(table + num);
625
626     for (i = 0; i < num; i++) {
627         P256_POINT *row = table[i];
628
629         /* This is an unusual input, we don't guarantee constant-timeness. */
630         if ((BN_num_bits(scalar[i]) > 256) || BN_is_negative(scalar[i])) {
631             BIGNUM *mod;
632
633             if ((mod = BN_CTX_get(ctx)) == NULL)
634                 goto err;
635             if (!BN_nnmod(mod, scalar[i], group->order, ctx)) {
636                 ECerr(EC_F_ECP_NISTZ256_WINDOWED_MUL, ERR_R_BN_LIB);
637                 goto err;
638             }
639             scalars[i] = mod;
640         } else
641             scalars[i] = scalar[i];
642
643         for (j = 0; j < bn_get_top(scalars[i]) * BN_BYTES; j += BN_BYTES) {
644             BN_ULONG d = bn_get_words(scalars[i])[j / BN_BYTES];
645
646             p_str[i][j + 0] = (unsigned char)d;
647             p_str[i][j + 1] = (unsigned char)(d >> 8);
648             p_str[i][j + 2] = (unsigned char)(d >> 16);
649             p_str[i][j + 3] = (unsigned char)(d >>= 24);
650             if (BN_BYTES == 8) {
651                 d >>= 8;
652                 p_str[i][j + 4] = (unsigned char)d;
653                 p_str[i][j + 5] = (unsigned char)(d >> 8);
654                 p_str[i][j + 6] = (unsigned char)(d >> 16);
655                 p_str[i][j + 7] = (unsigned char)(d >> 24);
656             }
657         }
658         for (; j < 33; j++)
659             p_str[i][j] = 0;
660
661         if (!ecp_nistz256_bignum_to_field_elem(temp[0].X, point[i]->X)
662             || !ecp_nistz256_bignum_to_field_elem(temp[0].Y, point[i]->Y)
663             || !ecp_nistz256_bignum_to_field_elem(temp[0].Z, point[i]->Z)) {
664             ECerr(EC_F_ECP_NISTZ256_WINDOWED_MUL,
665                   EC_R_COORDINATES_OUT_OF_RANGE);
666             goto err;
667         }
668
669         /*
670          * row[0] is implicitly (0,0,0) (the point at infinity), therefore it
671          * is not stored. All other values are actually stored with an offset
672          * of -1 in table.
673          */
674
675         ecp_nistz256_scatter_w5  (row, &temp[0], 1);
676         ecp_nistz256_point_double(&temp[1], &temp[0]);              /*1+1=2  */
677         ecp_nistz256_scatter_w5  (row, &temp[1], 2);
678         ecp_nistz256_point_add   (&temp[2], &temp[1], &temp[0]);    /*2+1=3  */
679         ecp_nistz256_scatter_w5  (row, &temp[2], 3);
680         ecp_nistz256_point_double(&temp[1], &temp[1]);              /*2*2=4  */
681         ecp_nistz256_scatter_w5  (row, &temp[1], 4);
682         ecp_nistz256_point_double(&temp[2], &temp[2]);              /*2*3=6  */
683         ecp_nistz256_scatter_w5  (row, &temp[2], 6);
684         ecp_nistz256_point_add   (&temp[3], &temp[1], &temp[0]);    /*4+1=5  */
685         ecp_nistz256_scatter_w5  (row, &temp[3], 5);
686         ecp_nistz256_point_add   (&temp[4], &temp[2], &temp[0]);    /*6+1=7  */
687         ecp_nistz256_scatter_w5  (row, &temp[4], 7);
688         ecp_nistz256_point_double(&temp[1], &temp[1]);              /*2*4=8  */
689         ecp_nistz256_scatter_w5  (row, &temp[1], 8);
690         ecp_nistz256_point_double(&temp[2], &temp[2]);              /*2*6=12 */
691         ecp_nistz256_scatter_w5  (row, &temp[2], 12);
692         ecp_nistz256_point_double(&temp[3], &temp[3]);              /*2*5=10 */
693         ecp_nistz256_scatter_w5  (row, &temp[3], 10);
694         ecp_nistz256_point_double(&temp[4], &temp[4]);              /*2*7=14 */
695         ecp_nistz256_scatter_w5  (row, &temp[4], 14);
696         ecp_nistz256_point_add   (&temp[2], &temp[2], &temp[0]);    /*12+1=13*/
697         ecp_nistz256_scatter_w5  (row, &temp[2], 13);
698         ecp_nistz256_point_add   (&temp[3], &temp[3], &temp[0]);    /*10+1=11*/
699         ecp_nistz256_scatter_w5  (row, &temp[3], 11);
700         ecp_nistz256_point_add   (&temp[4], &temp[4], &temp[0]);    /*14+1=15*/
701         ecp_nistz256_scatter_w5  (row, &temp[4], 15);
702         ecp_nistz256_point_add   (&temp[2], &temp[1], &temp[0]);    /*8+1=9  */
703         ecp_nistz256_scatter_w5  (row, &temp[2], 9);
704         ecp_nistz256_point_double(&temp[1], &temp[1]);              /*2*8=16 */
705         ecp_nistz256_scatter_w5  (row, &temp[1], 16);
706     }
707
708     idx = 255;
709
710     wvalue = p_str[0][(idx - 1) / 8];
711     wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
712
713     /*
714      * We gather to temp[0], because we know it's position relative
715      * to table
716      */
717     ecp_nistz256_gather_w5(&temp[0], table[0], _booth_recode_w5(wvalue) >> 1);
718     memcpy(r, &temp[0], sizeof(temp[0]));
719
720     while (idx >= 5) {
721         for (i = (idx == 255 ? 1 : 0); i < num; i++) {
722             unsigned int off = (idx - 1) / 8;
723
724             wvalue = p_str[i][off] | p_str[i][off + 1] << 8;
725             wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
726
727             wvalue = _booth_recode_w5(wvalue);
728
729             ecp_nistz256_gather_w5(&temp[0], table[i], wvalue >> 1);
730
731             ecp_nistz256_neg(temp[1].Y, temp[0].Y);
732             copy_conditional(temp[0].Y, temp[1].Y, (wvalue & 1));
733
734             ecp_nistz256_point_add(r, r, &temp[0]);
735         }
736
737         idx -= window_size;
738
739         ecp_nistz256_point_double(r, r);
740         ecp_nistz256_point_double(r, r);
741         ecp_nistz256_point_double(r, r);
742         ecp_nistz256_point_double(r, r);
743         ecp_nistz256_point_double(r, r);
744     }
745
746     /* Final window */
747     for (i = 0; i < num; i++) {
748         wvalue = p_str[i][0];
749         wvalue = (wvalue << 1) & mask;
750
751         wvalue = _booth_recode_w5(wvalue);
752
753         ecp_nistz256_gather_w5(&temp[0], table[i], wvalue >> 1);
754
755         ecp_nistz256_neg(temp[1].Y, temp[0].Y);
756         copy_conditional(temp[0].Y, temp[1].Y, wvalue & 1);
757
758         ecp_nistz256_point_add(r, r, &temp[0]);
759     }
760
761     ret = 1;
762  err:
763     OPENSSL_free(table_storage);
764     OPENSSL_free(p_str);
765     OPENSSL_free(scalars);
766     return ret;
767 }
768
769 /* Coordinates of G, for which we have precomputed tables */
770 static const BN_ULONG def_xG[P256_LIMBS] = {
771     TOBN(0x79e730d4, 0x18a9143c), TOBN(0x75ba95fc, 0x5fedb601),
772     TOBN(0x79fb732b, 0x77622510), TOBN(0x18905f76, 0xa53755c6)
773 };
774
775 static const BN_ULONG def_yG[P256_LIMBS] = {
776     TOBN(0xddf25357, 0xce95560a), TOBN(0x8b4ab8e4, 0xba19e45c),
777     TOBN(0xd2e88688, 0xdd21f325), TOBN(0x8571ff18, 0x25885d85)
778 };
779
780 /*
781  * ecp_nistz256_is_affine_G returns one if |generator| is the standard, P-256
782  * generator.
783  */
784 static int ecp_nistz256_is_affine_G(const EC_POINT *generator)
785 {
786     return (bn_get_top(generator->X) == P256_LIMBS) &&
787         (bn_get_top(generator->Y) == P256_LIMBS) &&
788         is_equal(bn_get_words(generator->X), def_xG) &&
789         is_equal(bn_get_words(generator->Y), def_yG) &&
790         is_one(generator->Z);
791 }
792
793 __owur static int ecp_nistz256_mult_precompute(EC_GROUP *group, BN_CTX *ctx)
794 {
795     /*
796      * We precompute a table for a Booth encoded exponent (wNAF) based
797      * computation. Each table holds 64 values for safe access, with an
798      * implicit value of infinity at index zero. We use window of size 7, and
799      * therefore require ceil(256/7) = 37 tables.
800      */
801     const BIGNUM *order;
802     EC_POINT *P = NULL, *T = NULL;
803     const EC_POINT *generator;
804     NISTZ256_PRE_COMP *pre_comp;
805     BN_CTX *new_ctx = NULL;
806     int i, j, k, ret = 0;
807     size_t w;
808
809     PRECOMP256_ROW *preComputedTable = NULL;
810     unsigned char *precomp_storage = NULL;
811
812     /* if there is an old NISTZ256_PRE_COMP object, throw it away */
813     EC_pre_comp_free(group);
814     generator = EC_GROUP_get0_generator(group);
815     if (generator == NULL) {
816         ECerr(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE, EC_R_UNDEFINED_GENERATOR);
817         return 0;
818     }
819
820     if (ecp_nistz256_is_affine_G(generator)) {
821         /*
822          * No need to calculate tables for the standard generator because we
823          * have them statically.
824          */
825         return 1;
826     }
827
828     if ((pre_comp = ecp_nistz256_pre_comp_new(group)) == NULL)
829         return 0;
830
831     if (ctx == NULL) {
832         ctx = new_ctx = BN_CTX_new();
833         if (ctx == NULL)
834             goto err;
835     }
836
837     BN_CTX_start(ctx);
838
839     order = EC_GROUP_get0_order(group);
840     if (order == NULL)
841         goto err;
842
843     if (BN_is_zero(order)) {
844         ECerr(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE, EC_R_UNKNOWN_ORDER);
845         goto err;
846     }
847
848     w = 7;
849
850     if ((precomp_storage =
851          OPENSSL_malloc(37 * 64 * sizeof(P256_POINT_AFFINE) + 64)) == NULL) {
852         ECerr(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE, ERR_R_MALLOC_FAILURE);
853         goto err;
854     }
855
856     preComputedTable = (void *)ALIGNPTR(precomp_storage, 64);
857
858     P = EC_POINT_new(group);
859     T = EC_POINT_new(group);
860     if (P == NULL || T == NULL)
861         goto err;
862
863     /*
864      * The zero entry is implicitly infinity, and we skip it, storing other
865      * values with -1 offset.
866      */
867     if (!EC_POINT_copy(T, generator))
868         goto err;
869
870     for (k = 0; k < 64; k++) {
871         if (!EC_POINT_copy(P, T))
872             goto err;
873         for (j = 0; j < 37; j++) {
874             P256_POINT_AFFINE temp;
875             /*
876              * It would be faster to use EC_POINTs_make_affine and
877              * make multiple points affine at the same time.
878              */
879             if (!EC_POINT_make_affine(group, P, ctx))
880                 goto err;
881             if (!ecp_nistz256_bignum_to_field_elem(temp.X, P->X) ||
882                 !ecp_nistz256_bignum_to_field_elem(temp.Y, P->Y)) {
883                 ECerr(EC_F_ECP_NISTZ256_MULT_PRECOMPUTE,
884                       EC_R_COORDINATES_OUT_OF_RANGE);
885                 goto err;
886             }
887             ecp_nistz256_scatter_w7(preComputedTable[j], &temp, k);
888             for (i = 0; i < 7; i++) {
889                 if (!EC_POINT_dbl(group, P, P, ctx))
890                     goto err;
891             }
892         }
893         if (!EC_POINT_add(group, T, T, generator, ctx))
894             goto err;
895     }
896
897     pre_comp->group = group;
898     pre_comp->w = w;
899     pre_comp->precomp = preComputedTable;
900     pre_comp->precomp_storage = precomp_storage;
901     precomp_storage = NULL;
902     SETPRECOMP(group, nistz256, pre_comp);
903     pre_comp = NULL;
904     ret = 1;
905
906  err:
907     if (ctx != NULL)
908         BN_CTX_end(ctx);
909     BN_CTX_free(new_ctx);
910
911     EC_nistz256_pre_comp_free(pre_comp);
912     OPENSSL_free(precomp_storage);
913     EC_POINT_free(P);
914     EC_POINT_free(T);
915     return ret;
916 }
917
918 /*
919  * Note that by default ECP_NISTZ256_AVX2 is undefined. While it's great
920  * code processing 4 points in parallel, corresponding serial operation
921  * is several times slower, because it uses 29x29=58-bit multiplication
922  * as opposite to 64x64=128-bit in integer-only scalar case. As result
923  * it doesn't provide *significant* performance improvement. Note that
924  * just defining ECP_NISTZ256_AVX2 is not sufficient to make it work,
925  * you'd need to compile even asm/ecp_nistz256-avx.pl module.
926  */
927 #if defined(ECP_NISTZ256_AVX2)
928 # if !(defined(__x86_64) || defined(__x86_64__) || \
929        defined(_M_AMD64) || defined(_MX64)) || \
930      !(defined(__GNUC__) || defined(_MSC_VER)) /* this is for ALIGN32 */
931 #  undef ECP_NISTZ256_AVX2
932 # else
933 /* Constant time access, loading four values, from four consecutive tables */
934 void ecp_nistz256_avx2_multi_gather_w7(void *result, const void *in,
935                                        int index0, int index1, int index2,
936                                        int index3);
937 void ecp_nistz256_avx2_transpose_convert(void *RESULTx4, const void *in);
938 void ecp_nistz256_avx2_convert_transpose_back(void *result, const void *Ax4);
939 void ecp_nistz256_avx2_point_add_affine_x4(void *RESULTx4, const void *Ax4,
940                                            const void *Bx4);
941 void ecp_nistz256_avx2_point_add_affines_x4(void *RESULTx4, const void *Ax4,
942                                             const void *Bx4);
943 void ecp_nistz256_avx2_to_mont(void *RESULTx4, const void *Ax4);
944 void ecp_nistz256_avx2_from_mont(void *RESULTx4, const void *Ax4);
945 void ecp_nistz256_avx2_set1(void *RESULTx4);
946 int ecp_nistz_avx2_eligible(void);
947
948 static void booth_recode_w7(unsigned char *sign,
949                             unsigned char *digit, unsigned char in)
950 {
951     unsigned char s, d;
952
953     s = ~((in >> 7) - 1);
954     d = (1 << 8) - in - 1;
955     d = (d & s) | (in & ~s);
956     d = (d >> 1) + (d & 1);
957
958     *sign = s & 1;
959     *digit = d;
960 }
961
962 /*
963  * ecp_nistz256_avx2_mul_g performs multiplication by G, using only the
964  * precomputed table. It does 4 affine point additions in parallel,
965  * significantly speeding up point multiplication for a fixed value.
966  */
967 static void ecp_nistz256_avx2_mul_g(P256_POINT *r,
968                                     unsigned char p_str[33],
969                                     const P256_POINT_AFFINE(*preComputedTable)[64])
970 {
971     const unsigned int window_size = 7;
972     const unsigned int mask = (1 << (window_size + 1)) - 1;
973     unsigned int wvalue;
974     /* Using 4 windows at a time */
975     unsigned char sign0, digit0;
976     unsigned char sign1, digit1;
977     unsigned char sign2, digit2;
978     unsigned char sign3, digit3;
979     unsigned int idx = 0;
980     BN_ULONG tmp[P256_LIMBS];
981     int i;
982
983     ALIGN32 BN_ULONG aX4[4 * 9 * 3] = { 0 };
984     ALIGN32 BN_ULONG bX4[4 * 9 * 2] = { 0 };
985     ALIGN32 P256_POINT_AFFINE point_arr[4];
986     ALIGN32 P256_POINT res_point_arr[4];
987
988     /* Initial four windows */
989     wvalue = *((u16 *) & p_str[0]);
990     wvalue = (wvalue << 1) & mask;
991     idx += window_size;
992     booth_recode_w7(&sign0, &digit0, wvalue);
993     wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
994     wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
995     idx += window_size;
996     booth_recode_w7(&sign1, &digit1, wvalue);
997     wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
998     wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
999     idx += window_size;
1000     booth_recode_w7(&sign2, &digit2, wvalue);
1001     wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
1002     wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
1003     idx += window_size;
1004     booth_recode_w7(&sign3, &digit3, wvalue);
1005
1006     ecp_nistz256_avx2_multi_gather_w7(point_arr, preComputedTable[0],
1007                                       digit0, digit1, digit2, digit3);
1008
1009     ecp_nistz256_neg(tmp, point_arr[0].Y);
1010     copy_conditional(point_arr[0].Y, tmp, sign0);
1011     ecp_nistz256_neg(tmp, point_arr[1].Y);
1012     copy_conditional(point_arr[1].Y, tmp, sign1);
1013     ecp_nistz256_neg(tmp, point_arr[2].Y);
1014     copy_conditional(point_arr[2].Y, tmp, sign2);
1015     ecp_nistz256_neg(tmp, point_arr[3].Y);
1016     copy_conditional(point_arr[3].Y, tmp, sign3);
1017
1018     ecp_nistz256_avx2_transpose_convert(aX4, point_arr);
1019     ecp_nistz256_avx2_to_mont(aX4, aX4);
1020     ecp_nistz256_avx2_to_mont(&aX4[4 * 9], &aX4[4 * 9]);
1021     ecp_nistz256_avx2_set1(&aX4[4 * 9 * 2]);
1022
1023     wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
1024     wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
1025     idx += window_size;
1026     booth_recode_w7(&sign0, &digit0, wvalue);
1027     wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
1028     wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
1029     idx += window_size;
1030     booth_recode_w7(&sign1, &digit1, wvalue);
1031     wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
1032     wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
1033     idx += window_size;
1034     booth_recode_w7(&sign2, &digit2, wvalue);
1035     wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
1036     wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
1037     idx += window_size;
1038     booth_recode_w7(&sign3, &digit3, wvalue);
1039
1040     ecp_nistz256_avx2_multi_gather_w7(point_arr, preComputedTable[4 * 1],
1041                                       digit0, digit1, digit2, digit3);
1042
1043     ecp_nistz256_neg(tmp, point_arr[0].Y);
1044     copy_conditional(point_arr[0].Y, tmp, sign0);
1045     ecp_nistz256_neg(tmp, point_arr[1].Y);
1046     copy_conditional(point_arr[1].Y, tmp, sign1);
1047     ecp_nistz256_neg(tmp, point_arr[2].Y);
1048     copy_conditional(point_arr[2].Y, tmp, sign2);
1049     ecp_nistz256_neg(tmp, point_arr[3].Y);
1050     copy_conditional(point_arr[3].Y, tmp, sign3);
1051
1052     ecp_nistz256_avx2_transpose_convert(bX4, point_arr);
1053     ecp_nistz256_avx2_to_mont(bX4, bX4);
1054     ecp_nistz256_avx2_to_mont(&bX4[4 * 9], &bX4[4 * 9]);
1055     /* Optimized when both inputs are affine */
1056     ecp_nistz256_avx2_point_add_affines_x4(aX4, aX4, bX4);
1057
1058     for (i = 2; i < 9; i++) {
1059         wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
1060         wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
1061         idx += window_size;
1062         booth_recode_w7(&sign0, &digit0, wvalue);
1063         wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
1064         wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
1065         idx += window_size;
1066         booth_recode_w7(&sign1, &digit1, wvalue);
1067         wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
1068         wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
1069         idx += window_size;
1070         booth_recode_w7(&sign2, &digit2, wvalue);
1071         wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
1072         wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
1073         idx += window_size;
1074         booth_recode_w7(&sign3, &digit3, wvalue);
1075
1076         ecp_nistz256_avx2_multi_gather_w7(point_arr,
1077                                           preComputedTable[4 * i],
1078                                           digit0, digit1, digit2, digit3);
1079
1080         ecp_nistz256_neg(tmp, point_arr[0].Y);
1081         copy_conditional(point_arr[0].Y, tmp, sign0);
1082         ecp_nistz256_neg(tmp, point_arr[1].Y);
1083         copy_conditional(point_arr[1].Y, tmp, sign1);
1084         ecp_nistz256_neg(tmp, point_arr[2].Y);
1085         copy_conditional(point_arr[2].Y, tmp, sign2);
1086         ecp_nistz256_neg(tmp, point_arr[3].Y);
1087         copy_conditional(point_arr[3].Y, tmp, sign3);
1088
1089         ecp_nistz256_avx2_transpose_convert(bX4, point_arr);
1090         ecp_nistz256_avx2_to_mont(bX4, bX4);
1091         ecp_nistz256_avx2_to_mont(&bX4[4 * 9], &bX4[4 * 9]);
1092
1093         ecp_nistz256_avx2_point_add_affine_x4(aX4, aX4, bX4);
1094     }
1095
1096     ecp_nistz256_avx2_from_mont(&aX4[4 * 9 * 0], &aX4[4 * 9 * 0]);
1097     ecp_nistz256_avx2_from_mont(&aX4[4 * 9 * 1], &aX4[4 * 9 * 1]);
1098     ecp_nistz256_avx2_from_mont(&aX4[4 * 9 * 2], &aX4[4 * 9 * 2]);
1099
1100     ecp_nistz256_avx2_convert_transpose_back(res_point_arr, aX4);
1101     /* Last window is performed serially */
1102     wvalue = *((u16 *) & p_str[(idx - 1) / 8]);
1103     wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
1104     booth_recode_w7(&sign0, &digit0, wvalue);
1105     ecp_nistz256_gather_w7((P256_POINT_AFFINE *)r,
1106                            preComputedTable[36], digit0);
1107     ecp_nistz256_neg(tmp, r->Y);
1108     copy_conditional(r->Y, tmp, sign0);
1109     memcpy(r->Z, ONE, sizeof(ONE));
1110     /* Sum the four windows */
1111     ecp_nistz256_point_add(r, r, &res_point_arr[0]);
1112     ecp_nistz256_point_add(r, r, &res_point_arr[1]);
1113     ecp_nistz256_point_add(r, r, &res_point_arr[2]);
1114     ecp_nistz256_point_add(r, r, &res_point_arr[3]);
1115 }
1116 # endif
1117 #endif
1118
1119 __owur static int ecp_nistz256_set_from_affine(EC_POINT *out, const EC_GROUP *group,
1120                                                const P256_POINT_AFFINE *in,
1121                                                BN_CTX *ctx)
1122 {
1123     BIGNUM *x, *y;
1124     BN_ULONG d_x[P256_LIMBS], d_y[P256_LIMBS];
1125     int ret = 0;
1126
1127     x = BN_new();
1128     if (x == NULL)
1129         return 0;
1130     y = BN_new();
1131     if (y == NULL) {
1132         BN_free(x);
1133         return 0;
1134     }
1135     memcpy(d_x, in->X, sizeof(d_x));
1136     bn_set_static_words(x, d_x, P256_LIMBS);
1137
1138     memcpy(d_y, in->Y, sizeof(d_y));
1139     bn_set_static_words(y, d_y, P256_LIMBS);
1140
1141     ret = EC_POINT_set_affine_coordinates_GFp(group, out, x, y, ctx);
1142
1143     BN_free(x);
1144     BN_free(y);
1145
1146     return ret;
1147 }
1148
1149 /* r = scalar*G + sum(scalars[i]*points[i]) */
1150 __owur static int ecp_nistz256_points_mul(const EC_GROUP *group,
1151                                           EC_POINT *r,
1152                                           const BIGNUM *scalar,
1153                                           size_t num,
1154                                           const EC_POINT *points[],
1155                                           const BIGNUM *scalars[], BN_CTX *ctx)
1156 {
1157     int i = 0, ret = 0, no_precomp_for_generator = 0, p_is_infinity = 0;
1158     size_t j;
1159     unsigned char p_str[33] = { 0 };
1160     const PRECOMP256_ROW *preComputedTable = NULL;
1161     const NISTZ256_PRE_COMP *pre_comp = NULL;
1162     const EC_POINT *generator = NULL;
1163     BN_CTX *new_ctx = NULL;
1164     const BIGNUM **new_scalars = NULL;
1165     const EC_POINT **new_points = NULL;
1166     unsigned int idx = 0;
1167     const unsigned int window_size = 7;
1168     const unsigned int mask = (1 << (window_size + 1)) - 1;
1169     unsigned int wvalue;
1170     ALIGN32 union {
1171         P256_POINT p;
1172         P256_POINT_AFFINE a;
1173     } t, p;
1174     BIGNUM *tmp_scalar;
1175
1176     if ((num + 1) == 0 || (num + 1) > OPENSSL_MALLOC_MAX_NELEMS(void *)) {
1177         ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, ERR_R_MALLOC_FAILURE);
1178         return 0;
1179     }
1180
1181     if (group->meth != r->meth) {
1182         ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, EC_R_INCOMPATIBLE_OBJECTS);
1183         return 0;
1184     }
1185
1186     if ((scalar == NULL) && (num == 0))
1187         return EC_POINT_set_to_infinity(group, r);
1188
1189     for (j = 0; j < num; j++) {
1190         if (group->meth != points[j]->meth) {
1191             ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, EC_R_INCOMPATIBLE_OBJECTS);
1192             return 0;
1193         }
1194     }
1195
1196     if (ctx == NULL) {
1197         ctx = new_ctx = BN_CTX_new();
1198         if (ctx == NULL)
1199             goto err;
1200     }
1201
1202     BN_CTX_start(ctx);
1203
1204     if (scalar) {
1205         generator = EC_GROUP_get0_generator(group);
1206         if (generator == NULL) {
1207             ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, EC_R_UNDEFINED_GENERATOR);
1208             goto err;
1209         }
1210
1211         /* look if we can use precomputed multiples of generator */
1212         pre_comp = group->pre_comp.nistz256;
1213
1214         if (pre_comp) {
1215             /*
1216              * If there is a precomputed table for the generator, check that
1217              * it was generated with the same generator.
1218              */
1219             EC_POINT *pre_comp_generator = EC_POINT_new(group);
1220             if (pre_comp_generator == NULL)
1221                 goto err;
1222
1223             if (!ecp_nistz256_set_from_affine(pre_comp_generator,
1224                                               group, pre_comp->precomp[0],
1225                                               ctx)) {
1226                 EC_POINT_free(pre_comp_generator);
1227                 goto err;
1228             }
1229
1230             if (0 == EC_POINT_cmp(group, generator, pre_comp_generator, ctx))
1231                 preComputedTable = (const PRECOMP256_ROW *)pre_comp->precomp;
1232
1233             EC_POINT_free(pre_comp_generator);
1234         }
1235
1236         if (preComputedTable == NULL && ecp_nistz256_is_affine_G(generator)) {
1237             /*
1238              * If there is no precomputed data, but the generator is the
1239              * default, a hardcoded table of precomputed data is used. This
1240              * is because applications, such as Apache, do not use
1241              * EC_KEY_precompute_mult.
1242              */
1243             preComputedTable = ecp_nistz256_precomputed;
1244         }
1245
1246         if (preComputedTable) {
1247             if ((BN_num_bits(scalar) > 256)
1248                 || BN_is_negative(scalar)) {
1249                 if ((tmp_scalar = BN_CTX_get(ctx)) == NULL)
1250                     goto err;
1251
1252                 if (!BN_nnmod(tmp_scalar, scalar, group->order, ctx)) {
1253                     ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, ERR_R_BN_LIB);
1254                     goto err;
1255                 }
1256                 scalar = tmp_scalar;
1257             }
1258
1259             for (i = 0; i < bn_get_top(scalar) * BN_BYTES; i += BN_BYTES) {
1260                 BN_ULONG d = bn_get_words(scalar)[i / BN_BYTES];
1261
1262                 p_str[i + 0] = (unsigned char)d;
1263                 p_str[i + 1] = (unsigned char)(d >> 8);
1264                 p_str[i + 2] = (unsigned char)(d >> 16);
1265                 p_str[i + 3] = (unsigned char)(d >>= 24);
1266                 if (BN_BYTES == 8) {
1267                     d >>= 8;
1268                     p_str[i + 4] = (unsigned char)d;
1269                     p_str[i + 5] = (unsigned char)(d >> 8);
1270                     p_str[i + 6] = (unsigned char)(d >> 16);
1271                     p_str[i + 7] = (unsigned char)(d >> 24);
1272                 }
1273             }
1274
1275             for (; i < 33; i++)
1276                 p_str[i] = 0;
1277
1278 #if defined(ECP_NISTZ256_AVX2)
1279             if (ecp_nistz_avx2_eligible()) {
1280                 ecp_nistz256_avx2_mul_g(&p.p, p_str, preComputedTable);
1281             } else
1282 #endif
1283             {
1284                 BN_ULONG infty;
1285
1286                 /* First window */
1287                 wvalue = (p_str[0] << 1) & mask;
1288                 idx += window_size;
1289
1290                 wvalue = _booth_recode_w7(wvalue);
1291
1292                 ecp_nistz256_gather_w7(&p.a, preComputedTable[0],
1293                                        wvalue >> 1);
1294
1295                 ecp_nistz256_neg(p.p.Z, p.p.Y);
1296                 copy_conditional(p.p.Y, p.p.Z, wvalue & 1);
1297
1298                 /*
1299                  * Since affine infinity is encoded as (0,0) and
1300                  * Jacobian ias (,,0), we need to harmonize them
1301                  * by assigning "one" or zero to Z.
1302                  */
1303                 infty = (p.p.X[0] | p.p.X[1] | p.p.X[2] | p.p.X[3] |
1304                          p.p.Y[0] | p.p.Y[1] | p.p.Y[2] | p.p.Y[3]);
1305                 if (P256_LIMBS == 8)
1306                     infty |= (p.p.X[4] | p.p.X[5] | p.p.X[6] | p.p.X[7] |
1307                               p.p.Y[4] | p.p.Y[5] | p.p.Y[6] | p.p.Y[7]);
1308
1309                 infty = 0 - is_zero(infty);
1310                 infty = ~infty;
1311
1312                 p.p.Z[0] = ONE[0] & infty;
1313                 p.p.Z[1] = ONE[1] & infty;
1314                 p.p.Z[2] = ONE[2] & infty;
1315                 p.p.Z[3] = ONE[3] & infty;
1316                 if (P256_LIMBS == 8) {
1317                     p.p.Z[4] = ONE[4] & infty;
1318                     p.p.Z[5] = ONE[5] & infty;
1319                     p.p.Z[6] = ONE[6] & infty;
1320                     p.p.Z[7] = ONE[7] & infty;
1321                 }
1322
1323                 for (i = 1; i < 37; i++) {
1324                     unsigned int off = (idx - 1) / 8;
1325                     wvalue = p_str[off] | p_str[off + 1] << 8;
1326                     wvalue = (wvalue >> ((idx - 1) % 8)) & mask;
1327                     idx += window_size;
1328
1329                     wvalue = _booth_recode_w7(wvalue);
1330
1331                     ecp_nistz256_gather_w7(&t.a,
1332                                            preComputedTable[i], wvalue >> 1);
1333
1334                     ecp_nistz256_neg(t.p.Z, t.a.Y);
1335                     copy_conditional(t.a.Y, t.p.Z, wvalue & 1);
1336
1337                     ecp_nistz256_point_add_affine(&p.p, &p.p, &t.a);
1338                 }
1339             }
1340         } else {
1341             p_is_infinity = 1;
1342             no_precomp_for_generator = 1;
1343         }
1344     } else
1345         p_is_infinity = 1;
1346
1347     if (no_precomp_for_generator) {
1348         /*
1349          * Without a precomputed table for the generator, it has to be
1350          * handled like a normal point.
1351          */
1352         new_scalars = OPENSSL_malloc((num + 1) * sizeof(BIGNUM *));
1353         if (new_scalars == NULL) {
1354             ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, ERR_R_MALLOC_FAILURE);
1355             goto err;
1356         }
1357
1358         new_points = OPENSSL_malloc((num + 1) * sizeof(EC_POINT *));
1359         if (new_points == NULL) {
1360             ECerr(EC_F_ECP_NISTZ256_POINTS_MUL, ERR_R_MALLOC_FAILURE);
1361             goto err;
1362         }
1363
1364         memcpy(new_scalars, scalars, num * sizeof(BIGNUM *));
1365         new_scalars[num] = scalar;
1366         memcpy(new_points, points, num * sizeof(EC_POINT *));
1367         new_points[num] = generator;
1368
1369         scalars = new_scalars;
1370         points = new_points;
1371         num++;
1372     }
1373
1374     if (num) {
1375         P256_POINT *out = &t.p;
1376         if (p_is_infinity)
1377             out = &p.p;
1378
1379         if (!ecp_nistz256_windowed_mul(group, out, scalars, points, num, ctx))
1380             goto err;
1381
1382         if (!p_is_infinity)
1383             ecp_nistz256_point_add(&p.p, &p.p, out);
1384     }
1385
1386     /* Not constant-time, but we're only operating on the public output. */
1387     if (!bn_set_words(r->X, p.p.X, P256_LIMBS) ||
1388         !bn_set_words(r->Y, p.p.Y, P256_LIMBS) ||
1389         !bn_set_words(r->Z, p.p.Z, P256_LIMBS)) {
1390         goto err;
1391     }
1392     r->Z_is_one = is_one(r->Z) & 1;
1393
1394     ret = 1;
1395
1396 err:
1397     if (ctx)
1398         BN_CTX_end(ctx);
1399     BN_CTX_free(new_ctx);
1400     OPENSSL_free(new_points);
1401     OPENSSL_free(new_scalars);
1402     return ret;
1403 }
1404
1405 __owur static int ecp_nistz256_get_affine(const EC_GROUP *group,
1406                                           const EC_POINT *point,
1407                                           BIGNUM *x, BIGNUM *y, BN_CTX *ctx)
1408 {
1409     BN_ULONG z_inv2[P256_LIMBS];
1410     BN_ULONG z_inv3[P256_LIMBS];
1411     BN_ULONG x_aff[P256_LIMBS];
1412     BN_ULONG y_aff[P256_LIMBS];
1413     BN_ULONG point_x[P256_LIMBS], point_y[P256_LIMBS], point_z[P256_LIMBS];
1414     BN_ULONG x_ret[P256_LIMBS], y_ret[P256_LIMBS];
1415
1416     if (EC_POINT_is_at_infinity(group, point)) {
1417         ECerr(EC_F_ECP_NISTZ256_GET_AFFINE, EC_R_POINT_AT_INFINITY);
1418         return 0;
1419     }
1420
1421     if (!ecp_nistz256_bignum_to_field_elem(point_x, point->X) ||
1422         !ecp_nistz256_bignum_to_field_elem(point_y, point->Y) ||
1423         !ecp_nistz256_bignum_to_field_elem(point_z, point->Z)) {
1424         ECerr(EC_F_ECP_NISTZ256_GET_AFFINE, EC_R_COORDINATES_OUT_OF_RANGE);
1425         return 0;
1426     }
1427
1428     ecp_nistz256_mod_inverse(z_inv3, point_z);
1429     ecp_nistz256_sqr_mont(z_inv2, z_inv3);
1430     ecp_nistz256_mul_mont(x_aff, z_inv2, point_x);
1431
1432     if (x != NULL) {
1433         ecp_nistz256_from_mont(x_ret, x_aff);
1434         if (!bn_set_words(x, x_ret, P256_LIMBS))
1435             return 0;
1436     }
1437
1438     if (y != NULL) {
1439         ecp_nistz256_mul_mont(z_inv3, z_inv3, z_inv2);
1440         ecp_nistz256_mul_mont(y_aff, z_inv3, point_y);
1441         ecp_nistz256_from_mont(y_ret, y_aff);
1442         if (!bn_set_words(y, y_ret, P256_LIMBS))
1443             return 0;
1444     }
1445
1446     return 1;
1447 }
1448
1449 static NISTZ256_PRE_COMP *ecp_nistz256_pre_comp_new(const EC_GROUP *group)
1450 {
1451     NISTZ256_PRE_COMP *ret = NULL;
1452
1453     if (!group)
1454         return NULL;
1455
1456     ret = OPENSSL_zalloc(sizeof(*ret));
1457
1458     if (ret == NULL) {
1459         ECerr(EC_F_ECP_NISTZ256_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
1460         return ret;
1461     }
1462
1463     ret->group = group;
1464     ret->w = 6;                 /* default */
1465     ret->references = 1;
1466
1467     ret->lock = CRYPTO_THREAD_lock_new();
1468     if (ret->lock == NULL) {
1469         ECerr(EC_F_ECP_NISTZ256_PRE_COMP_NEW, ERR_R_MALLOC_FAILURE);
1470         OPENSSL_free(ret);
1471         return NULL;
1472     }
1473     return ret;
1474 }
1475
1476 NISTZ256_PRE_COMP *EC_nistz256_pre_comp_dup(NISTZ256_PRE_COMP *p)
1477 {
1478     int i;
1479     if (p != NULL)
1480         CRYPTO_UP_REF(&p->references, &i, p->lock);
1481     return p;
1482 }
1483
1484 void EC_nistz256_pre_comp_free(NISTZ256_PRE_COMP *pre)
1485 {
1486     int i;
1487
1488     if (pre == NULL)
1489         return;
1490
1491     CRYPTO_DOWN_REF(&pre->references, &i, pre->lock);
1492     REF_PRINT_COUNT("EC_nistz256", x);
1493     if (i > 0)
1494         return;
1495     REF_ASSERT_ISNT(i < 0);
1496
1497     OPENSSL_free(pre->precomp_storage);
1498     CRYPTO_THREAD_lock_free(pre->lock);
1499     OPENSSL_free(pre);
1500 }
1501
1502
1503 static int ecp_nistz256_window_have_precompute_mult(const EC_GROUP *group)
1504 {
1505     /* There is a hard-coded table for the default generator. */
1506     const EC_POINT *generator = EC_GROUP_get0_generator(group);
1507
1508     if (generator != NULL && ecp_nistz256_is_affine_G(generator)) {
1509         /* There is a hard-coded table for the default generator. */
1510         return 1;
1511     }
1512
1513     return HAVEPRECOMP(group, nistz256);
1514 }
1515
1516 const EC_METHOD *EC_GFp_nistz256_method(void)
1517 {
1518     static const EC_METHOD ret = {
1519         EC_FLAGS_DEFAULT_OCT,
1520         NID_X9_62_prime_field,
1521         ec_GFp_mont_group_init,
1522         ec_GFp_mont_group_finish,
1523         ec_GFp_mont_group_clear_finish,
1524         ec_GFp_mont_group_copy,
1525         ec_GFp_mont_group_set_curve,
1526         ec_GFp_simple_group_get_curve,
1527         ec_GFp_simple_group_get_degree,
1528         ec_group_simple_order_bits,
1529         ec_GFp_simple_group_check_discriminant,
1530         ec_GFp_simple_point_init,
1531         ec_GFp_simple_point_finish,
1532         ec_GFp_simple_point_clear_finish,
1533         ec_GFp_simple_point_copy,
1534         ec_GFp_simple_point_set_to_infinity,
1535         ec_GFp_simple_set_Jprojective_coordinates_GFp,
1536         ec_GFp_simple_get_Jprojective_coordinates_GFp,
1537         ec_GFp_simple_point_set_affine_coordinates,
1538         ecp_nistz256_get_affine,
1539         0, 0, 0,
1540         ec_GFp_simple_add,
1541         ec_GFp_simple_dbl,
1542         ec_GFp_simple_invert,
1543         ec_GFp_simple_is_at_infinity,
1544         ec_GFp_simple_is_on_curve,
1545         ec_GFp_simple_cmp,
1546         ec_GFp_simple_make_affine,
1547         ec_GFp_simple_points_make_affine,
1548         ecp_nistz256_points_mul,                    /* mul */
1549         ecp_nistz256_mult_precompute,               /* precompute_mult */
1550         ecp_nistz256_window_have_precompute_mult,   /* have_precompute_mult */
1551         ec_GFp_mont_field_mul,
1552         ec_GFp_mont_field_sqr,
1553         0,                                          /* field_div */
1554         ec_GFp_mont_field_encode,
1555         ec_GFp_mont_field_decode,
1556         ec_GFp_mont_field_set_to_one,
1557         ec_key_simple_priv2oct,
1558         ec_key_simple_oct2priv,
1559         0, /* set private */
1560         ec_key_simple_generate_key,
1561         ec_key_simple_check_key,
1562         ec_key_simple_generate_public_key,
1563         0, /* keycopy */
1564         0, /* keyfinish */
1565         ecdh_simple_compute_key
1566     };
1567
1568     return &ret;
1569 }