1 /* Copyright (c) 2015, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 /* A 64-bit implementation of the NIST P-256 elliptic curve point
16  * multiplication
17  *
18  * OpenSSL integration was taken from Emilia Kasper's work in ecp_nistp224.c.
19  * Otherwise based on Emilia's P224 work, which was inspired by my curve25519
20  * work which got its smarts from Daniel J. Bernstein's work on the same. */
21 
22 #include <openssl/base.h>
23 
24 #if defined(OPENSSL_64_BIT) && !defined(OPENSSL_WINDOWS)
25 
26 #include <openssl/bn.h>
27 #include <openssl/ec.h>
28 #include <openssl/err.h>
29 #include <openssl/mem.h>
30 
31 #include <string.h>
32 
33 #include "internal.h"
34 #include "../internal.h"
35 
36 
37 typedef uint8_t u8;
38 typedef uint64_t u64;
39 typedef int64_t s64;
40 
41 /* The underlying field. P256 operates over GF(2^256-2^224+2^192+2^96-1). We
42  * can serialise an element of this field into 32 bytes. We call this an
43  * felem_bytearray. */
44 typedef u8 felem_bytearray[32];
45 
46 /* The representation of field elements.
47  * ------------------------------------
48  *
49  * We represent field elements with either four 128-bit values, eight 128-bit
50  * values, or four 64-bit values. The field element represented is:
51  *   v[0]*2^0 + v[1]*2^64 + v[2]*2^128 + v[3]*2^192  (mod p)
52  * or:
53  *   v[0]*2^0 + v[1]*2^64 + v[2]*2^128 + ... + v[8]*2^512  (mod p)
54  *
55  * 128-bit values are called 'limbs'. Since the limbs are spaced only 64 bits
56  * apart, but are 128-bits wide, the most significant bits of each limb overlap
57  * with the least significant bits of the next.
58  *
59  * A field element with four limbs is an 'felem'. One with eight limbs is a
60  * 'longfelem'
61  *
62  * A field element with four, 64-bit values is called a 'smallfelem'. Small
63  * values are used as intermediate values before multiplication. */
64 
65 #define NLIMBS 4
66 
67 typedef uint128_t limb;
68 typedef limb felem[NLIMBS];
69 typedef limb longfelem[NLIMBS * 2];
70 typedef u64 smallfelem[NLIMBS];
71 
72 /* This is the value of the prime as four 64-bit words, little-endian. */
73 static const u64 kPrime[4] = {0xfffffffffffffffful, 0xffffffff, 0,
74                               0xffffffff00000001ul};
75 static const u64 bottom63bits = 0x7ffffffffffffffful;
76 
77 /* bin32_to_felem takes a little-endian byte array and converts it into felem
78  * form. This assumes that the CPU is little-endian. */
bin32_to_felem(felem out,const u8 in[32])79 static void bin32_to_felem(felem out, const u8 in[32]) {
80   out[0] = *((const u64 *)&in[0]);
81   out[1] = *((const u64 *)&in[8]);
82   out[2] = *((const u64 *)&in[16]);
83   out[3] = *((const u64 *)&in[24]);
84 }
85 
86 /* smallfelem_to_bin32 takes a smallfelem and serialises into a little endian,
87  * 32 byte array. This assumes that the CPU is little-endian. */
smallfelem_to_bin32(u8 out[32],const smallfelem in)88 static void smallfelem_to_bin32(u8 out[32], const smallfelem in) {
89   *((u64 *)&out[0]) = in[0];
90   *((u64 *)&out[8]) = in[1];
91   *((u64 *)&out[16]) = in[2];
92   *((u64 *)&out[24]) = in[3];
93 }
94 
95 /* To preserve endianness when using BN_bn2bin and BN_bin2bn. */
flip_endian(u8 * out,const u8 * in,size_t len)96 static void flip_endian(u8 *out, const u8 *in, size_t len) {
97   for (size_t i = 0; i < len; ++i) {
98     out[i] = in[len - 1 - i];
99   }
100 }
101 
102 /* BN_to_felem converts an OpenSSL BIGNUM into an felem. */
BN_to_felem(felem out,const BIGNUM * bn)103 static int BN_to_felem(felem out, const BIGNUM *bn) {
104   if (BN_is_negative(bn)) {
105     OPENSSL_PUT_ERROR(EC, EC_R_BIGNUM_OUT_OF_RANGE);
106     return 0;
107   }
108 
109   felem_bytearray b_out;
110   /* BN_bn2bin eats leading zeroes */
111   OPENSSL_memset(b_out, 0, sizeof(b_out));
112   size_t num_bytes = BN_num_bytes(bn);
113   if (num_bytes > sizeof(b_out)) {
114     OPENSSL_PUT_ERROR(EC, EC_R_BIGNUM_OUT_OF_RANGE);
115     return 0;
116   }
117 
118   felem_bytearray b_in;
119   num_bytes = BN_bn2bin(bn, b_in);
120   flip_endian(b_out, b_in, num_bytes);
121   bin32_to_felem(out, b_out);
122   return 1;
123 }
124 
125 /* felem_to_BN converts an felem into an OpenSSL BIGNUM. */
smallfelem_to_BN(BIGNUM * out,const smallfelem in)126 static BIGNUM *smallfelem_to_BN(BIGNUM *out, const smallfelem in) {
127   felem_bytearray b_in, b_out;
128   smallfelem_to_bin32(b_in, in);
129   flip_endian(b_out, b_in, sizeof(b_out));
130   return BN_bin2bn(b_out, sizeof(b_out), out);
131 }
132 
133 /* Field operations. */
134 
felem_assign(felem out,const felem in)135 static void felem_assign(felem out, const felem in) {
136   out[0] = in[0];
137   out[1] = in[1];
138   out[2] = in[2];
139   out[3] = in[3];
140 }
141 
142 /* felem_sum sets out = out + in. */
felem_sum(felem out,const felem in)143 static void felem_sum(felem out, const felem in) {
144   out[0] += in[0];
145   out[1] += in[1];
146   out[2] += in[2];
147   out[3] += in[3];
148 }
149 
150 /* felem_small_sum sets out = out + in. */
felem_small_sum(felem out,const smallfelem in)151 static void felem_small_sum(felem out, const smallfelem in) {
152   out[0] += in[0];
153   out[1] += in[1];
154   out[2] += in[2];
155   out[3] += in[3];
156 }
157 
158 /* felem_scalar sets out = out * scalar */
felem_scalar(felem out,const u64 scalar)159 static void felem_scalar(felem out, const u64 scalar) {
160   out[0] *= scalar;
161   out[1] *= scalar;
162   out[2] *= scalar;
163   out[3] *= scalar;
164 }
165 
166 /* longfelem_scalar sets out = out * scalar */
longfelem_scalar(longfelem out,const u64 scalar)167 static void longfelem_scalar(longfelem out, const u64 scalar) {
168   out[0] *= scalar;
169   out[1] *= scalar;
170   out[2] *= scalar;
171   out[3] *= scalar;
172   out[4] *= scalar;
173   out[5] *= scalar;
174   out[6] *= scalar;
175   out[7] *= scalar;
176 }
177 
178 #define two105m41m9 ((((limb)1) << 105) - (((limb)1) << 41) - (((limb)1) << 9))
179 #define two105 (((limb)1) << 105)
180 #define two105m41p9 ((((limb)1) << 105) - (((limb)1) << 41) + (((limb)1) << 9))
181 
182 /* zero105 is 0 mod p */
183 static const felem zero105 = {two105m41m9, two105, two105m41p9, two105m41p9};
184 
185 /* smallfelem_neg sets |out| to |-small|
186  * On exit:
187  *   out[i] < out[i] + 2^105 */
smallfelem_neg(felem out,const smallfelem small)188 static void smallfelem_neg(felem out, const smallfelem small) {
189   /* In order to prevent underflow, we subtract from 0 mod p. */
190   out[0] = zero105[0] - small[0];
191   out[1] = zero105[1] - small[1];
192   out[2] = zero105[2] - small[2];
193   out[3] = zero105[3] - small[3];
194 }
195 
196 /* felem_diff subtracts |in| from |out|
197  * On entry:
198  *   in[i] < 2^104
199  * On exit:
200  *   out[i] < out[i] + 2^105. */
felem_diff(felem out,const felem in)201 static void felem_diff(felem out, const felem in) {
202   /* In order to prevent underflow, we add 0 mod p before subtracting. */
203   out[0] += zero105[0];
204   out[1] += zero105[1];
205   out[2] += zero105[2];
206   out[3] += zero105[3];
207 
208   out[0] -= in[0];
209   out[1] -= in[1];
210   out[2] -= in[2];
211   out[3] -= in[3];
212 }
213 
214 #define two107m43m11 \
215   ((((limb)1) << 107) - (((limb)1) << 43) - (((limb)1) << 11))
216 #define two107 (((limb)1) << 107)
217 #define two107m43p11 \
218   ((((limb)1) << 107) - (((limb)1) << 43) + (((limb)1) << 11))
219 
220 /* zero107 is 0 mod p */
221 static const felem zero107 = {two107m43m11, two107, two107m43p11, two107m43p11};
222 
223 /* An alternative felem_diff for larger inputs |in|
224  * felem_diff_zero107 subtracts |in| from |out|
225  * On entry:
226  *   in[i] < 2^106
227  * On exit:
228  *   out[i] < out[i] + 2^107. */
felem_diff_zero107(felem out,const felem in)229 static void felem_diff_zero107(felem out, const felem in) {
230   /* In order to prevent underflow, we add 0 mod p before subtracting. */
231   out[0] += zero107[0];
232   out[1] += zero107[1];
233   out[2] += zero107[2];
234   out[3] += zero107[3];
235 
236   out[0] -= in[0];
237   out[1] -= in[1];
238   out[2] -= in[2];
239   out[3] -= in[3];
240 }
241 
242 /* longfelem_diff subtracts |in| from |out|
243  * On entry:
244  *   in[i] < 7*2^67
245  * On exit:
246  *   out[i] < out[i] + 2^70 + 2^40. */
longfelem_diff(longfelem out,const longfelem in)247 static void longfelem_diff(longfelem out, const longfelem in) {
248   static const limb two70m8p6 =
249       (((limb)1) << 70) - (((limb)1) << 8) + (((limb)1) << 6);
250   static const limb two70p40 = (((limb)1) << 70) + (((limb)1) << 40);
251   static const limb two70 = (((limb)1) << 70);
252   static const limb two70m40m38p6 = (((limb)1) << 70) - (((limb)1) << 40) -
253                                     (((limb)1) << 38) + (((limb)1) << 6);
254   static const limb two70m6 = (((limb)1) << 70) - (((limb)1) << 6);
255 
256   /* add 0 mod p to avoid underflow */
257   out[0] += two70m8p6;
258   out[1] += two70p40;
259   out[2] += two70;
260   out[3] += two70m40m38p6;
261   out[4] += two70m6;
262   out[5] += two70m6;
263   out[6] += two70m6;
264   out[7] += two70m6;
265 
266   /* in[i] < 7*2^67 < 2^70 - 2^40 - 2^38 + 2^6 */
267   out[0] -= in[0];
268   out[1] -= in[1];
269   out[2] -= in[2];
270   out[3] -= in[3];
271   out[4] -= in[4];
272   out[5] -= in[5];
273   out[6] -= in[6];
274   out[7] -= in[7];
275 }
276 
277 #define two64m0 ((((limb)1) << 64) - 1)
278 #define two110p32m0 ((((limb)1) << 110) + (((limb)1) << 32) - 1)
279 #define two64m46 ((((limb)1) << 64) - (((limb)1) << 46))
280 #define two64m32 ((((limb)1) << 64) - (((limb)1) << 32))
281 
282 /* zero110 is 0 mod p. */
283 static const felem zero110 = {two64m0, two110p32m0, two64m46, two64m32};
284 
285 /* felem_shrink converts an felem into a smallfelem. The result isn't quite
286  * minimal as the value may be greater than p.
287  *
288  * On entry:
289  *   in[i] < 2^109
290  * On exit:
291  *   out[i] < 2^64. */
felem_shrink(smallfelem out,const felem in)292 static void felem_shrink(smallfelem out, const felem in) {
293   felem tmp;
294   u64 a, b, mask;
295   s64 high, low;
296   static const u64 kPrime3Test = 0x7fffffff00000001ul; /* 2^63 - 2^32 + 1 */
297 
298   /* Carry 2->3 */
299   tmp[3] = zero110[3] + in[3] + ((u64)(in[2] >> 64));
300   /* tmp[3] < 2^110 */
301 
302   tmp[2] = zero110[2] + (u64)in[2];
303   tmp[0] = zero110[0] + in[0];
304   tmp[1] = zero110[1] + in[1];
305   /* tmp[0] < 2**110, tmp[1] < 2^111, tmp[2] < 2**65 */
306 
307   /* We perform two partial reductions where we eliminate the high-word of
308    * tmp[3]. We don't update the other words till the end. */
309   a = tmp[3] >> 64; /* a < 2^46 */
310   tmp[3] = (u64)tmp[3];
311   tmp[3] -= a;
312   tmp[3] += ((limb)a) << 32;
313   /* tmp[3] < 2^79 */
314 
315   b = a;
316   a = tmp[3] >> 64; /* a < 2^15 */
317   b += a;           /* b < 2^46 + 2^15 < 2^47 */
318   tmp[3] = (u64)tmp[3];
319   tmp[3] -= a;
320   tmp[3] += ((limb)a) << 32;
321   /* tmp[3] < 2^64 + 2^47 */
322 
323   /* This adjusts the other two words to complete the two partial
324    * reductions. */
325   tmp[0] += b;
326   tmp[1] -= (((limb)b) << 32);
327 
328   /* In order to make space in tmp[3] for the carry from 2 -> 3, we
329    * conditionally subtract kPrime if tmp[3] is large enough. */
330   high = tmp[3] >> 64;
331   /* As tmp[3] < 2^65, high is either 1 or 0 */
332   high = ~(high - 1);
333   /* high is:
334    *   all ones   if the high word of tmp[3] is 1
335    *   all zeros  if the high word of tmp[3] if 0 */
336   low = tmp[3];
337   mask = low >> 63;
338   /* mask is:
339    *   all ones   if the MSB of low is 1
340    *   all zeros  if the MSB of low if 0 */
341   low &= bottom63bits;
342   low -= kPrime3Test;
343   /* if low was greater than kPrime3Test then the MSB is zero */
344   low = ~low;
345   low >>= 63;
346   /* low is:
347    *   all ones   if low was > kPrime3Test
348    *   all zeros  if low was <= kPrime3Test */
349   mask = (mask & low) | high;
350   tmp[0] -= mask & kPrime[0];
351   tmp[1] -= mask & kPrime[1];
352   /* kPrime[2] is zero, so omitted */
353   tmp[3] -= mask & kPrime[3];
354   /* tmp[3] < 2**64 - 2**32 + 1 */
355 
356   tmp[1] += ((u64)(tmp[0] >> 64));
357   tmp[0] = (u64)tmp[0];
358   tmp[2] += ((u64)(tmp[1] >> 64));
359   tmp[1] = (u64)tmp[1];
360   tmp[3] += ((u64)(tmp[2] >> 64));
361   tmp[2] = (u64)tmp[2];
362   /* tmp[i] < 2^64 */
363 
364   out[0] = tmp[0];
365   out[1] = tmp[1];
366   out[2] = tmp[2];
367   out[3] = tmp[3];
368 }
369 
370 /* smallfelem_expand converts a smallfelem to an felem */
smallfelem_expand(felem out,const smallfelem in)371 static void smallfelem_expand(felem out, const smallfelem in) {
372   out[0] = in[0];
373   out[1] = in[1];
374   out[2] = in[2];
375   out[3] = in[3];
376 }
377 
378 /* smallfelem_square sets |out| = |small|^2
379  * On entry:
380  *   small[i] < 2^64
381  * On exit:
382  *   out[i] < 7 * 2^64 < 2^67 */
smallfelem_square(longfelem out,const smallfelem small)383 static void smallfelem_square(longfelem out, const smallfelem small) {
384   limb a;
385   u64 high, low;
386 
387   a = ((uint128_t)small[0]) * small[0];
388   low = a;
389   high = a >> 64;
390   out[0] = low;
391   out[1] = high;
392 
393   a = ((uint128_t)small[0]) * small[1];
394   low = a;
395   high = a >> 64;
396   out[1] += low;
397   out[1] += low;
398   out[2] = high;
399 
400   a = ((uint128_t)small[0]) * small[2];
401   low = a;
402   high = a >> 64;
403   out[2] += low;
404   out[2] *= 2;
405   out[3] = high;
406 
407   a = ((uint128_t)small[0]) * small[3];
408   low = a;
409   high = a >> 64;
410   out[3] += low;
411   out[4] = high;
412 
413   a = ((uint128_t)small[1]) * small[2];
414   low = a;
415   high = a >> 64;
416   out[3] += low;
417   out[3] *= 2;
418   out[4] += high;
419 
420   a = ((uint128_t)small[1]) * small[1];
421   low = a;
422   high = a >> 64;
423   out[2] += low;
424   out[3] += high;
425 
426   a = ((uint128_t)small[1]) * small[3];
427   low = a;
428   high = a >> 64;
429   out[4] += low;
430   out[4] *= 2;
431   out[5] = high;
432 
433   a = ((uint128_t)small[2]) * small[3];
434   low = a;
435   high = a >> 64;
436   out[5] += low;
437   out[5] *= 2;
438   out[6] = high;
439   out[6] += high;
440 
441   a = ((uint128_t)small[2]) * small[2];
442   low = a;
443   high = a >> 64;
444   out[4] += low;
445   out[5] += high;
446 
447   a = ((uint128_t)small[3]) * small[3];
448   low = a;
449   high = a >> 64;
450   out[6] += low;
451   out[7] = high;
452 }
453 
454 /*felem_square sets |out| = |in|^2
455  * On entry:
456  *   in[i] < 2^109
457  * On exit:
458  *   out[i] < 7 * 2^64 < 2^67. */
felem_square(longfelem out,const felem in)459 static void felem_square(longfelem out, const felem in) {
460   u64 small[4];
461   felem_shrink(small, in);
462   smallfelem_square(out, small);
463 }
464 
465 /* smallfelem_mul sets |out| = |small1| * |small2|
466  * On entry:
467  *   small1[i] < 2^64
468  *   small2[i] < 2^64
469  * On exit:
470  *   out[i] < 7 * 2^64 < 2^67. */
smallfelem_mul(longfelem out,const smallfelem small1,const smallfelem small2)471 static void smallfelem_mul(longfelem out, const smallfelem small1,
472                            const smallfelem small2) {
473   limb a;
474   u64 high, low;
475 
476   a = ((uint128_t)small1[0]) * small2[0];
477   low = a;
478   high = a >> 64;
479   out[0] = low;
480   out[1] = high;
481 
482   a = ((uint128_t)small1[0]) * small2[1];
483   low = a;
484   high = a >> 64;
485   out[1] += low;
486   out[2] = high;
487 
488   a = ((uint128_t)small1[1]) * small2[0];
489   low = a;
490   high = a >> 64;
491   out[1] += low;
492   out[2] += high;
493 
494   a = ((uint128_t)small1[0]) * small2[2];
495   low = a;
496   high = a >> 64;
497   out[2] += low;
498   out[3] = high;
499 
500   a = ((uint128_t)small1[1]) * small2[1];
501   low = a;
502   high = a >> 64;
503   out[2] += low;
504   out[3] += high;
505 
506   a = ((uint128_t)small1[2]) * small2[0];
507   low = a;
508   high = a >> 64;
509   out[2] += low;
510   out[3] += high;
511 
512   a = ((uint128_t)small1[0]) * small2[3];
513   low = a;
514   high = a >> 64;
515   out[3] += low;
516   out[4] = high;
517 
518   a = ((uint128_t)small1[1]) * small2[2];
519   low = a;
520   high = a >> 64;
521   out[3] += low;
522   out[4] += high;
523 
524   a = ((uint128_t)small1[2]) * small2[1];
525   low = a;
526   high = a >> 64;
527   out[3] += low;
528   out[4] += high;
529 
530   a = ((uint128_t)small1[3]) * small2[0];
531   low = a;
532   high = a >> 64;
533   out[3] += low;
534   out[4] += high;
535 
536   a = ((uint128_t)small1[1]) * small2[3];
537   low = a;
538   high = a >> 64;
539   out[4] += low;
540   out[5] = high;
541 
542   a = ((uint128_t)small1[2]) * small2[2];
543   low = a;
544   high = a >> 64;
545   out[4] += low;
546   out[5] += high;
547 
548   a = ((uint128_t)small1[3]) * small2[1];
549   low = a;
550   high = a >> 64;
551   out[4] += low;
552   out[5] += high;
553 
554   a = ((uint128_t)small1[2]) * small2[3];
555   low = a;
556   high = a >> 64;
557   out[5] += low;
558   out[6] = high;
559 
560   a = ((uint128_t)small1[3]) * small2[2];
561   low = a;
562   high = a >> 64;
563   out[5] += low;
564   out[6] += high;
565 
566   a = ((uint128_t)small1[3]) * small2[3];
567   low = a;
568   high = a >> 64;
569   out[6] += low;
570   out[7] = high;
571 }
572 
573 /* felem_mul sets |out| = |in1| * |in2|
574  * On entry:
575  *   in1[i] < 2^109
576  *   in2[i] < 2^109
577  * On exit:
578  *   out[i] < 7 * 2^64 < 2^67 */
felem_mul(longfelem out,const felem in1,const felem in2)579 static void felem_mul(longfelem out, const felem in1, const felem in2) {
580   smallfelem small1, small2;
581   felem_shrink(small1, in1);
582   felem_shrink(small2, in2);
583   smallfelem_mul(out, small1, small2);
584 }
585 
586 /* felem_small_mul sets |out| = |small1| * |in2|
587  * On entry:
588  *   small1[i] < 2^64
589  *   in2[i] < 2^109
590  * On exit:
591  *   out[i] < 7 * 2^64 < 2^67 */
felem_small_mul(longfelem out,const smallfelem small1,const felem in2)592 static void felem_small_mul(longfelem out, const smallfelem small1,
593                             const felem in2) {
594   smallfelem small2;
595   felem_shrink(small2, in2);
596   smallfelem_mul(out, small1, small2);
597 }
598 
599 #define two100m36m4 ((((limb)1) << 100) - (((limb)1) << 36) - (((limb)1) << 4))
600 #define two100 (((limb)1) << 100)
601 #define two100m36p4 ((((limb)1) << 100) - (((limb)1) << 36) + (((limb)1) << 4))
602 
603 /* zero100 is 0 mod p */
604 static const felem zero100 = {two100m36m4, two100, two100m36p4, two100m36p4};
605 
606 /* Internal function for the different flavours of felem_reduce.
607  * felem_reduce_ reduces the higher coefficients in[4]-in[7].
608  * On entry:
609  *   out[0] >= in[6] + 2^32*in[6] + in[7] + 2^32*in[7]
610  *   out[1] >= in[7] + 2^32*in[4]
611  *   out[2] >= in[5] + 2^32*in[5]
612  *   out[3] >= in[4] + 2^32*in[5] + 2^32*in[6]
613  * On exit:
614  *   out[0] <= out[0] + in[4] + 2^32*in[5]
615  *   out[1] <= out[1] + in[5] + 2^33*in[6]
616  *   out[2] <= out[2] + in[7] + 2*in[6] + 2^33*in[7]
617  *   out[3] <= out[3] + 2^32*in[4] + 3*in[7] */
felem_reduce_(felem out,const longfelem in)618 static void felem_reduce_(felem out, const longfelem in) {
619   int128_t c;
620   /* combine common terms from below */
621   c = in[4] + (in[5] << 32);
622   out[0] += c;
623   out[3] -= c;
624 
625   c = in[5] - in[7];
626   out[1] += c;
627   out[2] -= c;
628 
629   /* the remaining terms */
630   /* 256: [(0,1),(96,-1),(192,-1),(224,1)] */
631   out[1] -= (in[4] << 32);
632   out[3] += (in[4] << 32);
633 
634   /* 320: [(32,1),(64,1),(128,-1),(160,-1),(224,-1)] */
635   out[2] -= (in[5] << 32);
636 
637   /* 384: [(0,-1),(32,-1),(96,2),(128,2),(224,-1)] */
638   out[0] -= in[6];
639   out[0] -= (in[6] << 32);
640   out[1] += (in[6] << 33);
641   out[2] += (in[6] * 2);
642   out[3] -= (in[6] << 32);
643 
644   /* 448: [(0,-1),(32,-1),(64,-1),(128,1),(160,2),(192,3)] */
645   out[0] -= in[7];
646   out[0] -= (in[7] << 32);
647   out[2] += (in[7] << 33);
648   out[3] += (in[7] * 3);
649 }
650 
651 /* felem_reduce converts a longfelem into an felem.
652  * To be called directly after felem_square or felem_mul.
653  * On entry:
654  *   in[0] < 2^64, in[1] < 3*2^64, in[2] < 5*2^64, in[3] < 7*2^64
655  *   in[4] < 7*2^64, in[5] < 5*2^64, in[6] < 3*2^64, in[7] < 2*64
656  * On exit:
657  *   out[i] < 2^101 */
felem_reduce(felem out,const longfelem in)658 static void felem_reduce(felem out, const longfelem in) {
659   out[0] = zero100[0] + in[0];
660   out[1] = zero100[1] + in[1];
661   out[2] = zero100[2] + in[2];
662   out[3] = zero100[3] + in[3];
663 
664   felem_reduce_(out, in);
665 
666   /* out[0] > 2^100 - 2^36 - 2^4 - 3*2^64 - 3*2^96 - 2^64 - 2^96 > 0
667    * out[1] > 2^100 - 2^64 - 7*2^96 > 0
668    * out[2] > 2^100 - 2^36 + 2^4 - 5*2^64 - 5*2^96 > 0
669    * out[3] > 2^100 - 2^36 + 2^4 - 7*2^64 - 5*2^96 - 3*2^96 > 0
670    *
671    * out[0] < 2^100 + 2^64 + 7*2^64 + 5*2^96 < 2^101
672    * out[1] < 2^100 + 3*2^64 + 5*2^64 + 3*2^97 < 2^101
673    * out[2] < 2^100 + 5*2^64 + 2^64 + 3*2^65 + 2^97 < 2^101
674    * out[3] < 2^100 + 7*2^64 + 7*2^96 + 3*2^64 < 2^101 */
675 }
676 
677 /* felem_reduce_zero105 converts a larger longfelem into an felem.
678  * On entry:
679  *   in[0] < 2^71
680  * On exit:
681  *   out[i] < 2^106 */
felem_reduce_zero105(felem out,const longfelem in)682 static void felem_reduce_zero105(felem out, const longfelem in) {
683     out[0] = zero105[0] + in[0];
684     out[1] = zero105[1] + in[1];
685     out[2] = zero105[2] + in[2];
686     out[3] = zero105[3] + in[3];
687 
688     felem_reduce_(out, in);
689 
690     /* out[0] > 2^105 - 2^41 - 2^9 - 2^71 - 2^103 - 2^71 - 2^103 > 0
691      * out[1] > 2^105 - 2^71 - 2^103 > 0
692      * out[2] > 2^105 - 2^41 + 2^9 - 2^71 - 2^103 > 0
693      * out[3] > 2^105 - 2^41 + 2^9 - 2^71 - 2^103 - 2^103 > 0
694      *
695      * out[0] < 2^105 + 2^71 + 2^71 + 2^103 < 2^106
696      * out[1] < 2^105 + 2^71 + 2^71 + 2^103 < 2^106
697      * out[2] < 2^105 + 2^71 + 2^71 + 2^71 + 2^103 < 2^106
698      * out[3] < 2^105 + 2^71 + 2^103 + 2^71 < 2^106 */
699 }
700 
701 /* subtract_u64 sets *result = *result - v and *carry to one if the
702  * subtraction underflowed. */
subtract_u64(u64 * result,u64 * carry,u64 v)703 static void subtract_u64(u64 *result, u64 *carry, u64 v) {
704   uint128_t r = *result;
705   r -= v;
706   *carry = (r >> 64) & 1;
707   *result = (u64)r;
708 }
709 
710 /* felem_contract converts |in| to its unique, minimal representation. On
711  * entry: in[i] < 2^109. */
felem_contract(smallfelem out,const felem in)712 static void felem_contract(smallfelem out, const felem in) {
713   u64 all_equal_so_far = 0, result = 0;
714 
715   felem_shrink(out, in);
716   /* small is minimal except that the value might be > p */
717 
718   all_equal_so_far--;
719   /* We are doing a constant time test if out >= kPrime. We need to compare
720    * each u64, from most-significant to least significant. For each one, if
721    * all words so far have been equal (m is all ones) then a non-equal
722    * result is the answer. Otherwise we continue. */
723   for (size_t i = 3; i < 4; i--) {
724     u64 equal;
725     uint128_t a = ((uint128_t)kPrime[i]) - out[i];
726     /* if out[i] > kPrime[i] then a will underflow and the high 64-bits
727      * will all be set. */
728     result |= all_equal_so_far & ((u64)(a >> 64));
729 
730     /* if kPrime[i] == out[i] then |equal| will be all zeros and the
731      * decrement will make it all ones. */
732     equal = kPrime[i] ^ out[i];
733     equal--;
734     equal &= equal << 32;
735     equal &= equal << 16;
736     equal &= equal << 8;
737     equal &= equal << 4;
738     equal &= equal << 2;
739     equal &= equal << 1;
740     equal = ((s64)equal) >> 63;
741 
742     all_equal_so_far &= equal;
743   }
744 
745   /* if all_equal_so_far is still all ones then the two values are equal
746    * and so out >= kPrime is true. */
747   result |= all_equal_so_far;
748 
749   /* if out >= kPrime then we subtract kPrime. */
750   u64 carry;
751   subtract_u64(&out[0], &carry, result & kPrime[0]);
752   subtract_u64(&out[1], &carry, carry);
753   subtract_u64(&out[2], &carry, carry);
754   subtract_u64(&out[3], &carry, carry);
755 
756   subtract_u64(&out[1], &carry, result & kPrime[1]);
757   subtract_u64(&out[2], &carry, carry);
758   subtract_u64(&out[3], &carry, carry);
759 
760   subtract_u64(&out[2], &carry, result & kPrime[2]);
761   subtract_u64(&out[3], &carry, carry);
762 
763   subtract_u64(&out[3], &carry, result & kPrime[3]);
764 }
765 
766 /* felem_is_zero returns a limb with all bits set if |in| == 0 (mod p) and 0
767  * otherwise.
768  * On entry:
769  *   small[i] < 2^64 */
smallfelem_is_zero(const smallfelem small)770 static limb smallfelem_is_zero(const smallfelem small) {
771   limb result;
772   u64 is_p;
773 
774   u64 is_zero = small[0] | small[1] | small[2] | small[3];
775   is_zero--;
776   is_zero &= is_zero << 32;
777   is_zero &= is_zero << 16;
778   is_zero &= is_zero << 8;
779   is_zero &= is_zero << 4;
780   is_zero &= is_zero << 2;
781   is_zero &= is_zero << 1;
782   is_zero = ((s64)is_zero) >> 63;
783 
784   is_p = (small[0] ^ kPrime[0]) | (small[1] ^ kPrime[1]) |
785          (small[2] ^ kPrime[2]) | (small[3] ^ kPrime[3]);
786   is_p--;
787   is_p &= is_p << 32;
788   is_p &= is_p << 16;
789   is_p &= is_p << 8;
790   is_p &= is_p << 4;
791   is_p &= is_p << 2;
792   is_p &= is_p << 1;
793   is_p = ((s64)is_p) >> 63;
794 
795   is_zero |= is_p;
796 
797   result = is_zero;
798   result |= ((limb)is_zero) << 64;
799   return result;
800 }
801 
802 /* felem_inv calculates |out| = |in|^{-1}
803  *
804  * Based on Fermat's Little Theorem:
805  *   a^p = a (mod p)
806  *   a^{p-1} = 1 (mod p)
807  *   a^{p-2} = a^{-1} (mod p) */
felem_inv(felem out,const felem in)808 static void felem_inv(felem out, const felem in) {
809   felem ftmp, ftmp2;
810   /* each e_I will hold |in|^{2^I - 1} */
811   felem e2, e4, e8, e16, e32, e64;
812   longfelem tmp;
813 
814   felem_square(tmp, in);
815   felem_reduce(ftmp, tmp); /* 2^1 */
816   felem_mul(tmp, in, ftmp);
817   felem_reduce(ftmp, tmp); /* 2^2 - 2^0 */
818   felem_assign(e2, ftmp);
819   felem_square(tmp, ftmp);
820   felem_reduce(ftmp, tmp); /* 2^3 - 2^1 */
821   felem_square(tmp, ftmp);
822   felem_reduce(ftmp, tmp); /* 2^4 - 2^2 */
823   felem_mul(tmp, ftmp, e2);
824   felem_reduce(ftmp, tmp); /* 2^4 - 2^0 */
825   felem_assign(e4, ftmp);
826   felem_square(tmp, ftmp);
827   felem_reduce(ftmp, tmp); /* 2^5 - 2^1 */
828   felem_square(tmp, ftmp);
829   felem_reduce(ftmp, tmp); /* 2^6 - 2^2 */
830   felem_square(tmp, ftmp);
831   felem_reduce(ftmp, tmp); /* 2^7 - 2^3 */
832   felem_square(tmp, ftmp);
833   felem_reduce(ftmp, tmp); /* 2^8 - 2^4 */
834   felem_mul(tmp, ftmp, e4);
835   felem_reduce(ftmp, tmp); /* 2^8 - 2^0 */
836   felem_assign(e8, ftmp);
837   for (size_t i = 0; i < 8; i++) {
838     felem_square(tmp, ftmp);
839     felem_reduce(ftmp, tmp);
840   } /* 2^16 - 2^8 */
841   felem_mul(tmp, ftmp, e8);
842   felem_reduce(ftmp, tmp); /* 2^16 - 2^0 */
843   felem_assign(e16, ftmp);
844   for (size_t i = 0; i < 16; i++) {
845     felem_square(tmp, ftmp);
846     felem_reduce(ftmp, tmp);
847   } /* 2^32 - 2^16 */
848   felem_mul(tmp, ftmp, e16);
849   felem_reduce(ftmp, tmp); /* 2^32 - 2^0 */
850   felem_assign(e32, ftmp);
851   for (size_t i = 0; i < 32; i++) {
852     felem_square(tmp, ftmp);
853     felem_reduce(ftmp, tmp);
854   } /* 2^64 - 2^32 */
855   felem_assign(e64, ftmp);
856   felem_mul(tmp, ftmp, in);
857   felem_reduce(ftmp, tmp); /* 2^64 - 2^32 + 2^0 */
858   for (size_t i = 0; i < 192; i++) {
859     felem_square(tmp, ftmp);
860     felem_reduce(ftmp, tmp);
861   } /* 2^256 - 2^224 + 2^192 */
862 
863   felem_mul(tmp, e64, e32);
864   felem_reduce(ftmp2, tmp); /* 2^64 - 2^0 */
865   for (size_t i = 0; i < 16; i++) {
866     felem_square(tmp, ftmp2);
867     felem_reduce(ftmp2, tmp);
868   } /* 2^80 - 2^16 */
869   felem_mul(tmp, ftmp2, e16);
870   felem_reduce(ftmp2, tmp); /* 2^80 - 2^0 */
871   for (size_t i = 0; i < 8; i++) {
872     felem_square(tmp, ftmp2);
873     felem_reduce(ftmp2, tmp);
874   } /* 2^88 - 2^8 */
875   felem_mul(tmp, ftmp2, e8);
876   felem_reduce(ftmp2, tmp); /* 2^88 - 2^0 */
877   for (size_t i = 0; i < 4; i++) {
878     felem_square(tmp, ftmp2);
879     felem_reduce(ftmp2, tmp);
880   } /* 2^92 - 2^4 */
881   felem_mul(tmp, ftmp2, e4);
882   felem_reduce(ftmp2, tmp); /* 2^92 - 2^0 */
883   felem_square(tmp, ftmp2);
884   felem_reduce(ftmp2, tmp); /* 2^93 - 2^1 */
885   felem_square(tmp, ftmp2);
886   felem_reduce(ftmp2, tmp); /* 2^94 - 2^2 */
887   felem_mul(tmp, ftmp2, e2);
888   felem_reduce(ftmp2, tmp); /* 2^94 - 2^0 */
889   felem_square(tmp, ftmp2);
890   felem_reduce(ftmp2, tmp); /* 2^95 - 2^1 */
891   felem_square(tmp, ftmp2);
892   felem_reduce(ftmp2, tmp); /* 2^96 - 2^2 */
893   felem_mul(tmp, ftmp2, in);
894   felem_reduce(ftmp2, tmp); /* 2^96 - 3 */
895 
896   felem_mul(tmp, ftmp2, ftmp);
897   felem_reduce(out, tmp); /* 2^256 - 2^224 + 2^192 + 2^96 - 3 */
898 }
899 
900 /* Group operations
901  * ----------------
902  *
903  * Building on top of the field operations we have the operations on the
904  * elliptic curve group itself. Points on the curve are represented in Jacobian
905  * coordinates. */
906 
907 /* point_double calculates 2*(x_in, y_in, z_in)
908  *
909  * The method is taken from:
910  *   http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
911  *
912  * Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed.
913  * while x_out == y_in is not (maybe this works, but it's not tested). */
point_double(felem x_out,felem y_out,felem z_out,const felem x_in,const felem y_in,const felem z_in)914 static void point_double(felem x_out, felem y_out, felem z_out,
915                          const felem x_in, const felem y_in, const felem z_in) {
916   longfelem tmp, tmp2;
917   felem delta, gamma, beta, alpha, ftmp, ftmp2;
918   smallfelem small1, small2;
919 
920   felem_assign(ftmp, x_in);
921   /* ftmp[i] < 2^106 */
922   felem_assign(ftmp2, x_in);
923   /* ftmp2[i] < 2^106 */
924 
925   /* delta = z^2 */
926   felem_square(tmp, z_in);
927   felem_reduce(delta, tmp);
928   /* delta[i] < 2^101 */
929 
930   /* gamma = y^2 */
931   felem_square(tmp, y_in);
932   felem_reduce(gamma, tmp);
933   /* gamma[i] < 2^101 */
934   felem_shrink(small1, gamma);
935 
936   /* beta = x*gamma */
937   felem_small_mul(tmp, small1, x_in);
938   felem_reduce(beta, tmp);
939   /* beta[i] < 2^101 */
940 
941   /* alpha = 3*(x-delta)*(x+delta) */
942   felem_diff(ftmp, delta);
943   /* ftmp[i] < 2^105 + 2^106 < 2^107 */
944   felem_sum(ftmp2, delta);
945   /* ftmp2[i] < 2^105 + 2^106 < 2^107 */
946   felem_scalar(ftmp2, 3);
947   /* ftmp2[i] < 3 * 2^107 < 2^109 */
948   felem_mul(tmp, ftmp, ftmp2);
949   felem_reduce(alpha, tmp);
950   /* alpha[i] < 2^101 */
951   felem_shrink(small2, alpha);
952 
953   /* x' = alpha^2 - 8*beta */
954   smallfelem_square(tmp, small2);
955   felem_reduce(x_out, tmp);
956   felem_assign(ftmp, beta);
957   felem_scalar(ftmp, 8);
958   /* ftmp[i] < 8 * 2^101 = 2^104 */
959   felem_diff(x_out, ftmp);
960   /* x_out[i] < 2^105 + 2^101 < 2^106 */
961 
962   /* z' = (y + z)^2 - gamma - delta */
963   felem_sum(delta, gamma);
964   /* delta[i] < 2^101 + 2^101 = 2^102 */
965   felem_assign(ftmp, y_in);
966   felem_sum(ftmp, z_in);
967   /* ftmp[i] < 2^106 + 2^106 = 2^107 */
968   felem_square(tmp, ftmp);
969   felem_reduce(z_out, tmp);
970   felem_diff(z_out, delta);
971   /* z_out[i] < 2^105 + 2^101 < 2^106 */
972 
973   /* y' = alpha*(4*beta - x') - 8*gamma^2 */
974   felem_scalar(beta, 4);
975   /* beta[i] < 4 * 2^101 = 2^103 */
976   felem_diff_zero107(beta, x_out);
977   /* beta[i] < 2^107 + 2^103 < 2^108 */
978   felem_small_mul(tmp, small2, beta);
979   /* tmp[i] < 7 * 2^64 < 2^67 */
980   smallfelem_square(tmp2, small1);
981   /* tmp2[i] < 7 * 2^64 */
982   longfelem_scalar(tmp2, 8);
983   /* tmp2[i] < 8 * 7 * 2^64 = 7 * 2^67 */
984   longfelem_diff(tmp, tmp2);
985   /* tmp[i] < 2^67 + 2^70 + 2^40 < 2^71 */
986   felem_reduce_zero105(y_out, tmp);
987   /* y_out[i] < 2^106 */
988 }
989 
990 /* point_double_small is the same as point_double, except that it operates on
991  * smallfelems. */
point_double_small(smallfelem x_out,smallfelem y_out,smallfelem z_out,const smallfelem x_in,const smallfelem y_in,const smallfelem z_in)992 static void point_double_small(smallfelem x_out, smallfelem y_out,
993                                smallfelem z_out, const smallfelem x_in,
994                                const smallfelem y_in, const smallfelem z_in) {
995   felem felem_x_out, felem_y_out, felem_z_out;
996   felem felem_x_in, felem_y_in, felem_z_in;
997 
998   smallfelem_expand(felem_x_in, x_in);
999   smallfelem_expand(felem_y_in, y_in);
1000   smallfelem_expand(felem_z_in, z_in);
1001   point_double(felem_x_out, felem_y_out, felem_z_out, felem_x_in, felem_y_in,
1002                felem_z_in);
1003   felem_shrink(x_out, felem_x_out);
1004   felem_shrink(y_out, felem_y_out);
1005   felem_shrink(z_out, felem_z_out);
1006 }
1007 
1008 /* copy_conditional copies in to out iff mask is all ones. */
copy_conditional(felem out,const felem in,limb mask)1009 static void copy_conditional(felem out, const felem in, limb mask) {
1010   for (size_t i = 0; i < NLIMBS; ++i) {
1011     const limb tmp = mask & (in[i] ^ out[i]);
1012     out[i] ^= tmp;
1013   }
1014 }
1015 
1016 /* copy_small_conditional copies in to out iff mask is all ones. */
copy_small_conditional(felem out,const smallfelem in,limb mask)1017 static void copy_small_conditional(felem out, const smallfelem in, limb mask) {
1018   const u64 mask64 = mask;
1019   for (size_t i = 0; i < NLIMBS; ++i) {
1020     out[i] = ((limb)(in[i] & mask64)) | (out[i] & ~mask);
1021   }
1022 }
1023 
1024 /* point_add calcuates (x1, y1, z1) + (x2, y2, z2)
1025  *
1026  * The method is taken from:
1027  *   http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl,
1028  * adapted for mixed addition (z2 = 1, or z2 = 0 for the point at infinity).
1029  *
1030  * This function includes a branch for checking whether the two input points
1031  * are equal, (while not equal to the point at infinity). This case never
1032  * happens during single point multiplication, so there is no timing leak for
1033  * ECDH or ECDSA signing. */
point_add(felem x3,felem y3,felem z3,const felem x1,const felem y1,const felem z1,const int mixed,const smallfelem x2,const smallfelem y2,const smallfelem z2)1034 static void point_add(felem x3, felem y3, felem z3, const felem x1,
1035                       const felem y1, const felem z1, const int mixed,
1036                       const smallfelem x2, const smallfelem y2,
1037                       const smallfelem z2) {
1038   felem ftmp, ftmp2, ftmp3, ftmp4, ftmp5, ftmp6, x_out, y_out, z_out;
1039   longfelem tmp, tmp2;
1040   smallfelem small1, small2, small3, small4, small5;
1041   limb x_equal, y_equal, z1_is_zero, z2_is_zero;
1042 
1043   felem_shrink(small3, z1);
1044 
1045   z1_is_zero = smallfelem_is_zero(small3);
1046   z2_is_zero = smallfelem_is_zero(z2);
1047 
1048   /* ftmp = z1z1 = z1**2 */
1049   smallfelem_square(tmp, small3);
1050   felem_reduce(ftmp, tmp);
1051   /* ftmp[i] < 2^101 */
1052   felem_shrink(small1, ftmp);
1053 
1054   if (!mixed) {
1055     /* ftmp2 = z2z2 = z2**2 */
1056     smallfelem_square(tmp, z2);
1057     felem_reduce(ftmp2, tmp);
1058     /* ftmp2[i] < 2^101 */
1059     felem_shrink(small2, ftmp2);
1060 
1061     felem_shrink(small5, x1);
1062 
1063     /* u1 = ftmp3 = x1*z2z2 */
1064     smallfelem_mul(tmp, small5, small2);
1065     felem_reduce(ftmp3, tmp);
1066     /* ftmp3[i] < 2^101 */
1067 
1068     /* ftmp5 = z1 + z2 */
1069     felem_assign(ftmp5, z1);
1070     felem_small_sum(ftmp5, z2);
1071     /* ftmp5[i] < 2^107 */
1072 
1073     /* ftmp5 = (z1 + z2)**2 - (z1z1 + z2z2) = 2z1z2 */
1074     felem_square(tmp, ftmp5);
1075     felem_reduce(ftmp5, tmp);
1076     /* ftmp2 = z2z2 + z1z1 */
1077     felem_sum(ftmp2, ftmp);
1078     /* ftmp2[i] < 2^101 + 2^101 = 2^102 */
1079     felem_diff(ftmp5, ftmp2);
1080     /* ftmp5[i] < 2^105 + 2^101 < 2^106 */
1081 
1082     /* ftmp2 = z2 * z2z2 */
1083     smallfelem_mul(tmp, small2, z2);
1084     felem_reduce(ftmp2, tmp);
1085 
1086     /* s1 = ftmp2 = y1 * z2**3 */
1087     felem_mul(tmp, y1, ftmp2);
1088     felem_reduce(ftmp6, tmp);
1089     /* ftmp6[i] < 2^101 */
1090   } else {
1091     /* We'll assume z2 = 1 (special case z2 = 0 is handled later). */
1092 
1093     /* u1 = ftmp3 = x1*z2z2 */
1094     felem_assign(ftmp3, x1);
1095     /* ftmp3[i] < 2^106 */
1096 
1097     /* ftmp5 = 2z1z2 */
1098     felem_assign(ftmp5, z1);
1099     felem_scalar(ftmp5, 2);
1100     /* ftmp5[i] < 2*2^106 = 2^107 */
1101 
1102     /* s1 = ftmp2 = y1 * z2**3 */
1103     felem_assign(ftmp6, y1);
1104     /* ftmp6[i] < 2^106 */
1105   }
1106 
1107   /* u2 = x2*z1z1 */
1108   smallfelem_mul(tmp, x2, small1);
1109   felem_reduce(ftmp4, tmp);
1110 
1111   /* h = ftmp4 = u2 - u1 */
1112   felem_diff_zero107(ftmp4, ftmp3);
1113   /* ftmp4[i] < 2^107 + 2^101 < 2^108 */
1114   felem_shrink(small4, ftmp4);
1115 
1116   x_equal = smallfelem_is_zero(small4);
1117 
1118   /* z_out = ftmp5 * h */
1119   felem_small_mul(tmp, small4, ftmp5);
1120   felem_reduce(z_out, tmp);
1121   /* z_out[i] < 2^101 */
1122 
1123   /* ftmp = z1 * z1z1 */
1124   smallfelem_mul(tmp, small1, small3);
1125   felem_reduce(ftmp, tmp);
1126 
1127   /* s2 = tmp = y2 * z1**3 */
1128   felem_small_mul(tmp, y2, ftmp);
1129   felem_reduce(ftmp5, tmp);
1130 
1131   /* r = ftmp5 = (s2 - s1)*2 */
1132   felem_diff_zero107(ftmp5, ftmp6);
1133   /* ftmp5[i] < 2^107 + 2^107 = 2^108 */
1134   felem_scalar(ftmp5, 2);
1135   /* ftmp5[i] < 2^109 */
1136   felem_shrink(small1, ftmp5);
1137   y_equal = smallfelem_is_zero(small1);
1138 
1139   if (x_equal && y_equal && !z1_is_zero && !z2_is_zero) {
1140     point_double(x3, y3, z3, x1, y1, z1);
1141     return;
1142   }
1143 
1144   /* I = ftmp = (2h)**2 */
1145   felem_assign(ftmp, ftmp4);
1146   felem_scalar(ftmp, 2);
1147   /* ftmp[i] < 2*2^108 = 2^109 */
1148   felem_square(tmp, ftmp);
1149   felem_reduce(ftmp, tmp);
1150 
1151   /* J = ftmp2 = h * I */
1152   felem_mul(tmp, ftmp4, ftmp);
1153   felem_reduce(ftmp2, tmp);
1154 
1155   /* V = ftmp4 = U1 * I */
1156   felem_mul(tmp, ftmp3, ftmp);
1157   felem_reduce(ftmp4, tmp);
1158 
1159   /* x_out = r**2 - J - 2V */
1160   smallfelem_square(tmp, small1);
1161   felem_reduce(x_out, tmp);
1162   felem_assign(ftmp3, ftmp4);
1163   felem_scalar(ftmp4, 2);
1164   felem_sum(ftmp4, ftmp2);
1165   /* ftmp4[i] < 2*2^101 + 2^101 < 2^103 */
1166   felem_diff(x_out, ftmp4);
1167   /* x_out[i] < 2^105 + 2^101 */
1168 
1169   /* y_out = r(V-x_out) - 2 * s1 * J */
1170   felem_diff_zero107(ftmp3, x_out);
1171   /* ftmp3[i] < 2^107 + 2^101 < 2^108 */
1172   felem_small_mul(tmp, small1, ftmp3);
1173   felem_mul(tmp2, ftmp6, ftmp2);
1174   longfelem_scalar(tmp2, 2);
1175   /* tmp2[i] < 2*2^67 = 2^68 */
1176   longfelem_diff(tmp, tmp2);
1177   /* tmp[i] < 2^67 + 2^70 + 2^40 < 2^71 */
1178   felem_reduce_zero105(y_out, tmp);
1179   /* y_out[i] < 2^106 */
1180 
1181   copy_small_conditional(x_out, x2, z1_is_zero);
1182   copy_conditional(x_out, x1, z2_is_zero);
1183   copy_small_conditional(y_out, y2, z1_is_zero);
1184   copy_conditional(y_out, y1, z2_is_zero);
1185   copy_small_conditional(z_out, z2, z1_is_zero);
1186   copy_conditional(z_out, z1, z2_is_zero);
1187   felem_assign(x3, x_out);
1188   felem_assign(y3, y_out);
1189   felem_assign(z3, z_out);
1190 }
1191 
1192 /* point_add_small is the same as point_add, except that it operates on
1193  * smallfelems. */
point_add_small(smallfelem x3,smallfelem y3,smallfelem z3,smallfelem x1,smallfelem y1,smallfelem z1,smallfelem x2,smallfelem y2,smallfelem z2)1194 static void point_add_small(smallfelem x3, smallfelem y3, smallfelem z3,
1195                             smallfelem x1, smallfelem y1, smallfelem z1,
1196                             smallfelem x2, smallfelem y2, smallfelem z2) {
1197   felem felem_x3, felem_y3, felem_z3;
1198   felem felem_x1, felem_y1, felem_z1;
1199   smallfelem_expand(felem_x1, x1);
1200   smallfelem_expand(felem_y1, y1);
1201   smallfelem_expand(felem_z1, z1);
1202   point_add(felem_x3, felem_y3, felem_z3, felem_x1, felem_y1, felem_z1, 0, x2,
1203             y2, z2);
1204   felem_shrink(x3, felem_x3);
1205   felem_shrink(y3, felem_y3);
1206   felem_shrink(z3, felem_z3);
1207 }
1208 
1209 /* Base point pre computation
1210  * --------------------------
1211  *
1212  * Two different sorts of precomputed tables are used in the following code.
1213  * Each contain various points on the curve, where each point is three field
1214  * elements (x, y, z).
1215  *
1216  * For the base point table, z is usually 1 (0 for the point at infinity).
1217  * This table has 2 * 16 elements, starting with the following:
1218  * index | bits    | point
1219  * ------+---------+------------------------------
1220  *     0 | 0 0 0 0 | 0G
1221  *     1 | 0 0 0 1 | 1G
1222  *     2 | 0 0 1 0 | 2^64G
1223  *     3 | 0 0 1 1 | (2^64 + 1)G
1224  *     4 | 0 1 0 0 | 2^128G
1225  *     5 | 0 1 0 1 | (2^128 + 1)G
1226  *     6 | 0 1 1 0 | (2^128 + 2^64)G
1227  *     7 | 0 1 1 1 | (2^128 + 2^64 + 1)G
1228  *     8 | 1 0 0 0 | 2^192G
1229  *     9 | 1 0 0 1 | (2^192 + 1)G
1230  *    10 | 1 0 1 0 | (2^192 + 2^64)G
1231  *    11 | 1 0 1 1 | (2^192 + 2^64 + 1)G
1232  *    12 | 1 1 0 0 | (2^192 + 2^128)G
1233  *    13 | 1 1 0 1 | (2^192 + 2^128 + 1)G
1234  *    14 | 1 1 1 0 | (2^192 + 2^128 + 2^64)G
1235  *    15 | 1 1 1 1 | (2^192 + 2^128 + 2^64 + 1)G
1236  * followed by a copy of this with each element multiplied by 2^32.
1237  *
1238  * The reason for this is so that we can clock bits into four different
1239  * locations when doing simple scalar multiplies against the base point,
1240  * and then another four locations using the second 16 elements.
1241  *
1242  * Tables for other points have table[i] = iG for i in 0 .. 16. */
1243 
1244 /* g_pre_comp is the table of precomputed base points */
1245 static const smallfelem g_pre_comp[2][16][3] = {
1246     {{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
1247      {{0xf4a13945d898c296, 0x77037d812deb33a0, 0xf8bce6e563a440f2,
1248        0x6b17d1f2e12c4247},
1249       {0xcbb6406837bf51f5, 0x2bce33576b315ece, 0x8ee7eb4a7c0f9e16,
1250        0x4fe342e2fe1a7f9b},
1251       {1, 0, 0, 0}},
1252      {{0x90e75cb48e14db63, 0x29493baaad651f7e, 0x8492592e326e25de,
1253        0x0fa822bc2811aaa5},
1254       {0xe41124545f462ee7, 0x34b1a65050fe82f5, 0x6f4ad4bcb3df188b,
1255        0xbff44ae8f5dba80d},
1256       {1, 0, 0, 0}},
1257      {{0x93391ce2097992af, 0xe96c98fd0d35f1fa, 0xb257c0de95e02789,
1258        0x300a4bbc89d6726f},
1259       {0xaa54a291c08127a0, 0x5bb1eeada9d806a5, 0x7f1ddb25ff1e3c6f,
1260        0x72aac7e0d09b4644},
1261       {1, 0, 0, 0}},
1262      {{0x57c84fc9d789bd85, 0xfc35ff7dc297eac3, 0xfb982fd588c6766e,
1263        0x447d739beedb5e67},
1264       {0x0c7e33c972e25b32, 0x3d349b95a7fae500, 0xe12e9d953a4aaff7,
1265        0x2d4825ab834131ee},
1266       {1, 0, 0, 0}},
1267      {{0x13949c932a1d367f, 0xef7fbd2b1a0a11b7, 0xddc6068bb91dfc60,
1268        0xef9519328a9c72ff},
1269       {0x196035a77376d8a8, 0x23183b0895ca1740, 0xc1ee9807022c219c,
1270        0x611e9fc37dbb2c9b},
1271       {1, 0, 0, 0}},
1272      {{0xcae2b1920b57f4bc, 0x2936df5ec6c9bc36, 0x7dea6482e11238bf,
1273        0x550663797b51f5d8},
1274       {0x44ffe216348a964c, 0x9fb3d576dbdefbe1, 0x0afa40018d9d50e5,
1275        0x157164848aecb851},
1276       {1, 0, 0, 0}},
1277      {{0xe48ecafffc5cde01, 0x7ccd84e70d715f26, 0xa2e8f483f43e4391,
1278        0xeb5d7745b21141ea},
1279       {0xcac917e2731a3479, 0x85f22cfe2844b645, 0x0990e6a158006cee,
1280        0xeafd72ebdbecc17b},
1281       {1, 0, 0, 0}},
1282      {{0x6cf20ffb313728be, 0x96439591a3c6b94a, 0x2736ff8344315fc5,
1283        0xa6d39677a7849276},
1284       {0xf2bab833c357f5f4, 0x824a920c2284059b, 0x66b8babd2d27ecdf,
1285        0x674f84749b0b8816},
1286       {1, 0, 0, 0}},
1287      {{0x2df48c04677c8a3e, 0x74e02f080203a56b, 0x31855f7db8c7fedb,
1288        0x4e769e7672c9ddad},
1289       {0xa4c36165b824bbb0, 0xfb9ae16f3b9122a5, 0x1ec0057206947281,
1290        0x42b99082de830663},
1291       {1, 0, 0, 0}},
1292      {{0x6ef95150dda868b9, 0xd1f89e799c0ce131, 0x7fdc1ca008a1c478,
1293        0x78878ef61c6ce04d},
1294       {0x9c62b9121fe0d976, 0x6ace570ebde08d4f, 0xde53142c12309def,
1295        0xb6cb3f5d7b72c321},
1296       {1, 0, 0, 0}},
1297      {{0x7f991ed2c31a3573, 0x5b82dd5bd54fb496, 0x595c5220812ffcae,
1298        0x0c88bc4d716b1287},
1299       {0x3a57bf635f48aca8, 0x7c8181f4df2564f3, 0x18d1b5b39c04e6aa,
1300        0xdd5ddea3f3901dc6},
1301       {1, 0, 0, 0}},
1302      {{0xe96a79fb3e72ad0c, 0x43a0a28c42ba792f, 0xefe0a423083e49f3,
1303        0x68f344af6b317466},
1304       {0xcdfe17db3fb24d4a, 0x668bfc2271f5c626, 0x604ed93c24d67ff3,
1305        0x31b9c405f8540a20},
1306       {1, 0, 0, 0}},
1307      {{0xd36b4789a2582e7f, 0x0d1a10144ec39c28, 0x663c62c3edbad7a0,
1308        0x4052bf4b6f461db9},
1309       {0x235a27c3188d25eb, 0xe724f33999bfcc5b, 0x862be6bd71d70cc8,
1310        0xfecf4d5190b0fc61},
1311       {1, 0, 0, 0}},
1312      {{0x74346c10a1d4cfac, 0xafdf5cc08526a7a4, 0x123202a8f62bff7a,
1313        0x1eddbae2c802e41a},
1314       {0x8fa0af2dd603f844, 0x36e06b7e4c701917, 0x0c45f45273db33a0,
1315        0x43104d86560ebcfc},
1316       {1, 0, 0, 0}},
1317      {{0x9615b5110d1d78e5, 0x66b0de3225c4744b, 0x0a4a46fb6aaf363a,
1318        0xb48e26b484f7a21c},
1319       {0x06ebb0f621a01b2d, 0xc004e4048b7b0f98, 0x64131bcdfed6f668,
1320        0xfac015404d4d3dab},
1321       {1, 0, 0, 0}}},
1322     {{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}},
1323      {{0x3a5a9e22185a5943, 0x1ab919365c65dfb6, 0x21656b32262c71da,
1324        0x7fe36b40af22af89},
1325       {0xd50d152c699ca101, 0x74b3d5867b8af212, 0x9f09f40407dca6f1,
1326        0xe697d45825b63624},
1327       {1, 0, 0, 0}},
1328      {{0xa84aa9397512218e, 0xe9a521b074ca0141, 0x57880b3a18a2e902,
1329        0x4a5b506612a677a6},
1330       {0x0beada7a4c4f3840, 0x626db15419e26d9d, 0xc42604fbe1627d40,
1331        0xeb13461ceac089f1},
1332       {1, 0, 0, 0}},
1333      {{0xf9faed0927a43281, 0x5e52c4144103ecbc, 0xc342967aa815c857,
1334        0x0781b8291c6a220a},
1335       {0x5a8343ceeac55f80, 0x88f80eeee54a05e3, 0x97b2a14f12916434,
1336        0x690cde8df0151593},
1337       {1, 0, 0, 0}},
1338      {{0xaee9c75df7f82f2a, 0x9e4c35874afdf43a, 0xf5622df437371326,
1339        0x8a535f566ec73617},
1340       {0xc5f9a0ac223094b7, 0xcde533864c8c7669, 0x37e02819085a92bf,
1341        0x0455c08468b08bd7},
1342       {1, 0, 0, 0}},
1343      {{0x0c0a6e2c9477b5d9, 0xf9a4bf62876dc444, 0x5050a949b6cdc279,
1344        0x06bada7ab77f8276},
1345       {0xc8b4aed1ea48dac9, 0xdebd8a4b7ea1070f, 0x427d49101366eb70,
1346        0x5b476dfd0e6cb18a},
1347       {1, 0, 0, 0}},
1348      {{0x7c5c3e44278c340a, 0x4d54606812d66f3b, 0x29a751b1ae23c5d8,
1349        0x3e29864e8a2ec908},
1350       {0x142d2a6626dbb850, 0xad1744c4765bd780, 0x1f150e68e322d1ed,
1351        0x239b90ea3dc31e7e},
1352       {1, 0, 0, 0}},
1353      {{0x78c416527a53322a, 0x305dde6709776f8e, 0xdbcab759f8862ed4,
1354        0x820f4dd949f72ff7},
1355       {0x6cc544a62b5debd4, 0x75be5d937b4e8cc4, 0x1b481b1b215c14d3,
1356        0x140406ec783a05ec},
1357       {1, 0, 0, 0}},
1358      {{0x6a703f10e895df07, 0xfd75f3fa01876bd8, 0xeb5b06e70ce08ffe,
1359        0x68f6b8542783dfee},
1360       {0x90c76f8a78712655, 0xcf5293d2f310bf7f, 0xfbc8044dfda45028,
1361        0xcbe1feba92e40ce6},
1362       {1, 0, 0, 0}},
1363      {{0xe998ceea4396e4c1, 0xfc82ef0b6acea274, 0x230f729f2250e927,
1364        0xd0b2f94d2f420109},
1365       {0x4305adddb38d4966, 0x10b838f8624c3b45, 0x7db2636658954e7a,
1366        0x971459828b0719e5},
1367       {1, 0, 0, 0}},
1368      {{0x4bd6b72623369fc9, 0x57f2929e53d0b876, 0xc2d5cba4f2340687,
1369        0x961610004a866aba},
1370       {0x49997bcd2e407a5e, 0x69ab197d92ddcb24, 0x2cf1f2438fe5131c,
1371        0x7acb9fadcee75e44},
1372       {1, 0, 0, 0}},
1373      {{0x254e839423d2d4c0, 0xf57f0c917aea685b, 0xa60d880f6f75aaea,
1374        0x24eb9acca333bf5b},
1375       {0xe3de4ccb1cda5dea, 0xfeef9341c51a6b4f, 0x743125f88bac4c4d,
1376        0x69f891c5acd079cc},
1377       {1, 0, 0, 0}},
1378      {{0xeee44b35702476b5, 0x7ed031a0e45c2258, 0xb422d1e7bd6f8514,
1379        0xe51f547c5972a107},
1380       {0xa25bcd6fc9cf343d, 0x8ca922ee097c184e, 0xa62f98b3a9fe9a06,
1381        0x1c309a2b25bb1387},
1382       {1, 0, 0, 0}},
1383      {{0x9295dbeb1967c459, 0xb00148833472c98e, 0xc504977708011828,
1384        0x20b87b8aa2c4e503},
1385       {0x3063175de057c277, 0x1bd539338fe582dd, 0x0d11adef5f69a044,
1386        0xf5c6fa49919776be},
1387       {1, 0, 0, 0}},
1388      {{0x8c944e760fd59e11, 0x3876cba1102fad5f, 0xa454c3fad83faa56,
1389        0x1ed7d1b9332010b9},
1390       {0xa1011a270024b889, 0x05e4d0dcac0cd344, 0x52b520f0eb6a2a24,
1391        0x3a2b03f03217257a},
1392       {1, 0, 0, 0}},
1393      {{0xf20fc2afdf1d043d, 0xf330240db58d5a62, 0xfc7d229ca0058c3b,
1394        0x15fee545c78dd9f6},
1395       {0x501e82885bc98cda, 0x41ef80e5d046ac04, 0x557d9f49461210fb,
1396        0x4ab5b6b2b8753f81},
1397       {1, 0, 0, 0}}}};
1398 
1399 /* select_point selects the |idx|th point from a precomputation table and
1400  * copies it to out. */
select_point(const u64 idx,size_t size,const smallfelem pre_comp[][3],smallfelem out[3])1401 static void select_point(const u64 idx, size_t size,
1402                          const smallfelem pre_comp[/*size*/][3],
1403                          smallfelem out[3]) {
1404   u64 *outlimbs = &out[0][0];
1405   OPENSSL_memset(outlimbs, 0, 3 * sizeof(smallfelem));
1406 
1407   for (size_t i = 0; i < size; i++) {
1408     const u64 *inlimbs = (const u64 *)&pre_comp[i][0][0];
1409     u64 mask = i ^ idx;
1410     mask |= mask >> 4;
1411     mask |= mask >> 2;
1412     mask |= mask >> 1;
1413     mask &= 1;
1414     mask--;
1415     for (size_t j = 0; j < NLIMBS * 3; j++) {
1416       outlimbs[j] |= inlimbs[j] & mask;
1417     }
1418   }
1419 }
1420 
1421 /* get_bit returns the |i|th bit in |in| */
get_bit(const felem_bytearray in,int i)1422 static char get_bit(const felem_bytearray in, int i) {
1423   if (i < 0 || i >= 256) {
1424     return 0;
1425   }
1426   return (in[i >> 3] >> (i & 7)) & 1;
1427 }
1428 
1429 /* Interleaved point multiplication using precomputed point multiples: The
1430  * small point multiples 0*P, 1*P, ..., 17*P are in p_pre_comp, the scalar
1431  * in p_scalar, if non-NULL. If g_scalar is non-NULL, we also add this multiple
1432  * of the generator, using certain (large) precomputed multiples in g_pre_comp.
1433  * Output point (X, Y, Z) is stored in x_out, y_out, z_out. */
batch_mul(felem x_out,felem y_out,felem z_out,const u8 * p_scalar,const u8 * g_scalar,const smallfelem p_pre_comp[17][3])1434 static void batch_mul(felem x_out, felem y_out, felem z_out, const u8 *p_scalar,
1435                       const u8 *g_scalar, const smallfelem p_pre_comp[17][3]) {
1436   felem nq[3], ftmp;
1437   smallfelem tmp[3];
1438   u64 bits;
1439   u8 sign, digit;
1440 
1441   /* set nq to the point at infinity */
1442   OPENSSL_memset(nq, 0, 3 * sizeof(felem));
1443 
1444   /* Loop over both scalars msb-to-lsb, interleaving additions of multiples
1445    * of the generator (two in each of the last 32 rounds) and additions of p
1446    * (every 5th round). */
1447 
1448   int skip = 1; /* save two point operations in the first round */
1449   size_t i = p_scalar != NULL ? 255 : 31;
1450   for (;;) {
1451     /* double */
1452     if (!skip) {
1453       point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]);
1454     }
1455 
1456     /* add multiples of the generator */
1457     if (g_scalar != NULL && i <= 31) {
1458       /* first, look 32 bits upwards */
1459       bits = get_bit(g_scalar, i + 224) << 3;
1460       bits |= get_bit(g_scalar, i + 160) << 2;
1461       bits |= get_bit(g_scalar, i + 96) << 1;
1462       bits |= get_bit(g_scalar, i + 32);
1463       /* select the point to add, in constant time */
1464       select_point(bits, 16, g_pre_comp[1], tmp);
1465 
1466       if (!skip) {
1467         point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */,
1468                   tmp[0], tmp[1], tmp[2]);
1469       } else {
1470         smallfelem_expand(nq[0], tmp[0]);
1471         smallfelem_expand(nq[1], tmp[1]);
1472         smallfelem_expand(nq[2], tmp[2]);
1473         skip = 0;
1474       }
1475 
1476       /* second, look at the current position */
1477       bits = get_bit(g_scalar, i + 192) << 3;
1478       bits |= get_bit(g_scalar, i + 128) << 2;
1479       bits |= get_bit(g_scalar, i + 64) << 1;
1480       bits |= get_bit(g_scalar, i);
1481       /* select the point to add, in constant time */
1482       select_point(bits, 16, g_pre_comp[0], tmp);
1483       point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, tmp[0],
1484                 tmp[1], tmp[2]);
1485     }
1486 
1487     /* do other additions every 5 doublings */
1488     if (p_scalar != NULL && i % 5 == 0) {
1489       bits = get_bit(p_scalar, i + 4) << 5;
1490       bits |= get_bit(p_scalar, i + 3) << 4;
1491       bits |= get_bit(p_scalar, i + 2) << 3;
1492       bits |= get_bit(p_scalar, i + 1) << 2;
1493       bits |= get_bit(p_scalar, i) << 1;
1494       bits |= get_bit(p_scalar, i - 1);
1495       ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits);
1496 
1497       /* select the point to add or subtract, in constant time. */
1498       select_point(digit, 17, p_pre_comp, tmp);
1499       smallfelem_neg(ftmp, tmp[1]); /* (X, -Y, Z) is the negative
1500                                      * point */
1501       copy_small_conditional(ftmp, tmp[1], (((limb)sign) - 1));
1502       felem_contract(tmp[1], ftmp);
1503 
1504       if (!skip) {
1505         point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 0 /* mixed */,
1506                   tmp[0], tmp[1], tmp[2]);
1507       } else {
1508         smallfelem_expand(nq[0], tmp[0]);
1509         smallfelem_expand(nq[1], tmp[1]);
1510         smallfelem_expand(nq[2], tmp[2]);
1511         skip = 0;
1512       }
1513     }
1514 
1515     if (i == 0) {
1516       break;
1517     }
1518     --i;
1519   }
1520   felem_assign(x_out, nq[0]);
1521   felem_assign(y_out, nq[1]);
1522   felem_assign(z_out, nq[2]);
1523 }
1524 
1525 /******************************************************************************/
1526 /*
1527  * OPENSSL EC_METHOD FUNCTIONS
1528  */
1529 
1530 /* Takes the Jacobian coordinates (X, Y, Z) of a point and returns (X', Y') =
1531  * (X/Z^2, Y/Z^3). */
ec_GFp_nistp256_point_get_affine_coordinates(const EC_GROUP * group,const EC_POINT * point,BIGNUM * x,BIGNUM * y,BN_CTX * ctx)1532 static int ec_GFp_nistp256_point_get_affine_coordinates(const EC_GROUP *group,
1533                                                         const EC_POINT *point,
1534                                                         BIGNUM *x, BIGNUM *y,
1535                                                         BN_CTX *ctx) {
1536   felem z1, z2, x_in, y_in;
1537   smallfelem x_out, y_out;
1538   longfelem tmp;
1539 
1540   if (EC_POINT_is_at_infinity(group, point)) {
1541     OPENSSL_PUT_ERROR(EC, EC_R_POINT_AT_INFINITY);
1542     return 0;
1543   }
1544   if (!BN_to_felem(x_in, &point->X) ||
1545       !BN_to_felem(y_in, &point->Y) ||
1546       !BN_to_felem(z1, &point->Z)) {
1547     return 0;
1548   }
1549   felem_inv(z2, z1);
1550   felem_square(tmp, z2);
1551   felem_reduce(z1, tmp);
1552 
1553   if (x != NULL) {
1554     felem_mul(tmp, x_in, z1);
1555     felem_reduce(x_in, tmp);
1556     felem_contract(x_out, x_in);
1557     if (!smallfelem_to_BN(x, x_out)) {
1558       OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB);
1559       return 0;
1560     }
1561   }
1562 
1563   if (y != NULL) {
1564     felem_mul(tmp, z1, z2);
1565     felem_reduce(z1, tmp);
1566     felem_mul(tmp, y_in, z1);
1567     felem_reduce(y_in, tmp);
1568     felem_contract(y_out, y_in);
1569     if (!smallfelem_to_BN(y, y_out)) {
1570       OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB);
1571       return 0;
1572     }
1573   }
1574 
1575   return 1;
1576 }
1577 
ec_GFp_nistp256_points_mul(const EC_GROUP * group,EC_POINT * r,const BIGNUM * g_scalar,const EC_POINT * p,const BIGNUM * p_scalar,BN_CTX * ctx)1578 static int ec_GFp_nistp256_points_mul(const EC_GROUP *group, EC_POINT *r,
1579                                       const BIGNUM *g_scalar, const EC_POINT *p,
1580                                       const BIGNUM *p_scalar, BN_CTX *ctx) {
1581   int ret = 0;
1582   BN_CTX *new_ctx = NULL;
1583   BIGNUM *x, *y, *z, *tmp_scalar;
1584   felem_bytearray g_secret, p_secret;
1585   smallfelem p_pre_comp[17][3];
1586   felem_bytearray tmp;
1587   smallfelem x_in, y_in, z_in;
1588   felem x_out, y_out, z_out;
1589 
1590   if (ctx == NULL) {
1591     ctx = new_ctx = BN_CTX_new();
1592     if (ctx == NULL) {
1593       return 0;
1594     }
1595   }
1596 
1597   BN_CTX_start(ctx);
1598   if ((x = BN_CTX_get(ctx)) == NULL ||
1599       (y = BN_CTX_get(ctx)) == NULL ||
1600       (z = BN_CTX_get(ctx)) == NULL ||
1601       (tmp_scalar = BN_CTX_get(ctx)) == NULL) {
1602     goto err;
1603   }
1604 
1605   if (p != NULL && p_scalar != NULL) {
1606     /* We treat NULL scalars as 0, and NULL points as points at infinity, i.e.,
1607      * they contribute nothing to the linear combination. */
1608     OPENSSL_memset(&p_secret, 0, sizeof(p_secret));
1609     OPENSSL_memset(&p_pre_comp, 0, sizeof(p_pre_comp));
1610     size_t num_bytes;
1611     /* Reduce g_scalar to 0 <= g_scalar < 2^256. */
1612     if (BN_num_bits(p_scalar) > 256 || BN_is_negative(p_scalar)) {
1613       /* This is an unusual input, and we don't guarantee constant-timeness. */
1614       if (!BN_nnmod(tmp_scalar, p_scalar, &group->order, ctx)) {
1615         OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB);
1616         goto err;
1617       }
1618       num_bytes = BN_bn2bin(tmp_scalar, tmp);
1619     } else {
1620       num_bytes = BN_bn2bin(p_scalar, tmp);
1621     }
1622     flip_endian(p_secret, tmp, num_bytes);
1623     /* Precompute multiples. */
1624     if (!BN_to_felem(x_out, &p->X) ||
1625         !BN_to_felem(y_out, &p->Y) ||
1626         !BN_to_felem(z_out, &p->Z)) {
1627       goto err;
1628     }
1629     felem_shrink(p_pre_comp[1][0], x_out);
1630     felem_shrink(p_pre_comp[1][1], y_out);
1631     felem_shrink(p_pre_comp[1][2], z_out);
1632     for (size_t j = 2; j <= 16; ++j) {
1633       if (j & 1) {
1634         point_add_small(p_pre_comp[j][0], p_pre_comp[j][1],
1635                         p_pre_comp[j][2], p_pre_comp[1][0],
1636                         p_pre_comp[1][1], p_pre_comp[1][2],
1637                         p_pre_comp[j - 1][0], p_pre_comp[j - 1][1],
1638                         p_pre_comp[j - 1][2]);
1639       } else {
1640         point_double_small(p_pre_comp[j][0], p_pre_comp[j][1],
1641                            p_pre_comp[j][2], p_pre_comp[j / 2][0],
1642                            p_pre_comp[j / 2][1], p_pre_comp[j / 2][2]);
1643       }
1644     }
1645   }
1646 
1647   if (g_scalar != NULL) {
1648     size_t num_bytes;
1649 
1650     OPENSSL_memset(g_secret, 0, sizeof(g_secret));
1651     /* reduce g_scalar to 0 <= g_scalar < 2^256 */
1652     if (BN_num_bits(g_scalar) > 256 || BN_is_negative(g_scalar)) {
1653       /* this is an unusual input, and we don't guarantee
1654        * constant-timeness. */
1655       if (!BN_nnmod(tmp_scalar, g_scalar, &group->order, ctx)) {
1656         OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB);
1657         goto err;
1658       }
1659       num_bytes = BN_bn2bin(tmp_scalar, tmp);
1660     } else {
1661       num_bytes = BN_bn2bin(g_scalar, tmp);
1662     }
1663     flip_endian(g_secret, tmp, num_bytes);
1664   }
1665   batch_mul(x_out, y_out, z_out,
1666             (p != NULL && p_scalar != NULL) ? p_secret : NULL,
1667             g_scalar != NULL ? g_secret : NULL,
1668             (const smallfelem(*)[3]) &p_pre_comp);
1669 
1670   /* reduce the output to its unique minimal representation */
1671   felem_contract(x_in, x_out);
1672   felem_contract(y_in, y_out);
1673   felem_contract(z_in, z_out);
1674   if (!smallfelem_to_BN(x, x_in) ||
1675       !smallfelem_to_BN(y, y_in) ||
1676       !smallfelem_to_BN(z, z_in)) {
1677     OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB);
1678     goto err;
1679   }
1680   ret = ec_point_set_Jprojective_coordinates_GFp(group, r, x, y, z, ctx);
1681 
1682 err:
1683   BN_CTX_end(ctx);
1684   BN_CTX_free(new_ctx);
1685   return ret;
1686 }
1687 
1688 const EC_METHOD EC_GFp_nistp256_method = {
1689     ec_GFp_simple_group_init,
1690     ec_GFp_simple_group_finish,
1691     ec_GFp_simple_group_copy,
1692     ec_GFp_simple_group_set_curve,
1693     ec_GFp_nistp256_point_get_affine_coordinates,
1694     ec_GFp_nistp256_points_mul,
1695     ec_GFp_simple_field_mul,
1696     ec_GFp_simple_field_sqr,
1697     NULL /* field_encode */,
1698     NULL /* field_decode */,
1699 };
1700 
1701 #endif  /* 64_BIT && !WINDOWS */
1702