xref: /kernel/linux/linux-5.10/crypto/ecc.c (revision 8c2ecf20)
1/*
2 * Copyright (c) 2013, 2014 Kenneth MacKay. All rights reserved.
3 * Copyright (c) 2019 Vitaly Chikunov <vt@altlinux.org>
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met:
8 *  * Redistributions of source code must retain the above copyright
9 *   notice, this list of conditions and the following disclaimer.
10 *  * Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
15 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
16 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
17 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
18 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
19 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
20 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
24 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include <linux/module.h>
28#include <linux/random.h>
29#include <linux/slab.h>
30#include <linux/swab.h>
31#include <linux/fips.h>
32#include <crypto/ecdh.h>
33#include <crypto/rng.h>
34#include <asm/unaligned.h>
35#include <linux/ratelimit.h>
36
37#include "ecc.h"
38#include "ecc_curve_defs.h"
39
40typedef struct {
41	u64 m_low;
42	u64 m_high;
43} uint128_t;
44
45const struct ecc_curve *ecc_get_curve(unsigned int curve_id)
46{
47	switch (curve_id) {
48	/* In FIPS mode only allow P256 and higher */
49	case ECC_CURVE_NIST_P192:
50		return fips_enabled ? NULL : &nist_p192;
51	case ECC_CURVE_NIST_P256:
52		return &nist_p256;
53	case ECC_CURVE_NIST_P384:
54		return &nist_p384;
55	default:
56		return NULL;
57	}
58}
59EXPORT_SYMBOL(ecc_get_curve);
60
61static u64 *ecc_alloc_digits_space(unsigned int ndigits)
62{
63	size_t len = ndigits * sizeof(u64);
64
65	if (!len)
66		return NULL;
67
68	return kmalloc(len, GFP_KERNEL);
69}
70
71static void ecc_free_digits_space(u64 *space)
72{
73	kfree_sensitive(space);
74}
75
76static struct ecc_point *ecc_alloc_point(unsigned int ndigits)
77{
78	struct ecc_point *p = kmalloc(sizeof(*p), GFP_KERNEL);
79
80	if (!p)
81		return NULL;
82
83	p->x = ecc_alloc_digits_space(ndigits);
84	if (!p->x)
85		goto err_alloc_x;
86
87	p->y = ecc_alloc_digits_space(ndigits);
88	if (!p->y)
89		goto err_alloc_y;
90
91	p->ndigits = ndigits;
92
93	return p;
94
95err_alloc_y:
96	ecc_free_digits_space(p->x);
97err_alloc_x:
98	kfree(p);
99	return NULL;
100}
101
102static void ecc_free_point(struct ecc_point *p)
103{
104	if (!p)
105		return;
106
107	kfree_sensitive(p->x);
108	kfree_sensitive(p->y);
109	kfree_sensitive(p);
110}
111
112static void vli_clear(u64 *vli, unsigned int ndigits)
113{
114	int i;
115
116	for (i = 0; i < ndigits; i++)
117		vli[i] = 0;
118}
119
120/* Returns true if vli == 0, false otherwise. */
121bool vli_is_zero(const u64 *vli, unsigned int ndigits)
122{
123	int i;
124
125	for (i = 0; i < ndigits; i++) {
126		if (vli[i])
127			return false;
128	}
129
130	return true;
131}
132EXPORT_SYMBOL(vli_is_zero);
133
134/* Returns nonzero if bit bit of vli is set. */
135static u64 vli_test_bit(const u64 *vli, unsigned int bit)
136{
137	return (vli[bit / 64] & ((u64)1 << (bit % 64)));
138}
139
140static bool vli_is_negative(const u64 *vli, unsigned int ndigits)
141{
142	return vli_test_bit(vli, ndigits * 64 - 1);
143}
144
145/* Counts the number of 64-bit "digits" in vli. */
146static unsigned int vli_num_digits(const u64 *vli, unsigned int ndigits)
147{
148	int i;
149
150	/* Search from the end until we find a non-zero digit.
151	 * We do it in reverse because we expect that most digits will
152	 * be nonzero.
153	 */
154	for (i = ndigits - 1; i >= 0 && vli[i] == 0; i--);
155
156	return (i + 1);
157}
158
159/* Counts the number of bits required for vli. */
160static unsigned int vli_num_bits(const u64 *vli, unsigned int ndigits)
161{
162	unsigned int i, num_digits;
163	u64 digit;
164
165	num_digits = vli_num_digits(vli, ndigits);
166	if (num_digits == 0)
167		return 0;
168
169	digit = vli[num_digits - 1];
170	for (i = 0; digit; i++)
171		digit >>= 1;
172
173	return ((num_digits - 1) * 64 + i);
174}
175
176/* Set dest from unaligned bit string src. */
177void vli_from_be64(u64 *dest, const void *src, unsigned int ndigits)
178{
179	int i;
180	const u64 *from = src;
181
182	for (i = 0; i < ndigits; i++)
183		dest[i] = get_unaligned_be64(&from[ndigits - 1 - i]);
184}
185EXPORT_SYMBOL(vli_from_be64);
186
187void vli_from_le64(u64 *dest, const void *src, unsigned int ndigits)
188{
189	int i;
190	const u64 *from = src;
191
192	for (i = 0; i < ndigits; i++)
193		dest[i] = get_unaligned_le64(&from[i]);
194}
195EXPORT_SYMBOL(vli_from_le64);
196
197/* Sets dest = src. */
198static void vli_set(u64 *dest, const u64 *src, unsigned int ndigits)
199{
200	int i;
201
202	for (i = 0; i < ndigits; i++)
203		dest[i] = src[i];
204}
205
206/* Returns sign of left - right. */
207int vli_cmp(const u64 *left, const u64 *right, unsigned int ndigits)
208{
209	int i;
210
211	for (i = ndigits - 1; i >= 0; i--) {
212		if (left[i] > right[i])
213			return 1;
214		else if (left[i] < right[i])
215			return -1;
216	}
217
218	return 0;
219}
220EXPORT_SYMBOL(vli_cmp);
221
222/* Computes result = in << c, returning carry. Can modify in place
223 * (if result == in). 0 < shift < 64.
224 */
225static u64 vli_lshift(u64 *result, const u64 *in, unsigned int shift,
226		      unsigned int ndigits)
227{
228	u64 carry = 0;
229	int i;
230
231	for (i = 0; i < ndigits; i++) {
232		u64 temp = in[i];
233
234		result[i] = (temp << shift) | carry;
235		carry = temp >> (64 - shift);
236	}
237
238	return carry;
239}
240
241/* Computes vli = vli >> 1. */
242static void vli_rshift1(u64 *vli, unsigned int ndigits)
243{
244	u64 *end = vli;
245	u64 carry = 0;
246
247	vli += ndigits;
248
249	while (vli-- > end) {
250		u64 temp = *vli;
251		*vli = (temp >> 1) | carry;
252		carry = temp << 63;
253	}
254}
255
256/* Computes result = left + right, returning carry. Can modify in place. */
257static u64 vli_add(u64 *result, const u64 *left, const u64 *right,
258		   unsigned int ndigits)
259{
260	u64 carry = 0;
261	int i;
262
263	for (i = 0; i < ndigits; i++) {
264		u64 sum;
265
266		sum = left[i] + right[i] + carry;
267		if (sum != left[i])
268			carry = (sum < left[i]);
269
270		result[i] = sum;
271	}
272
273	return carry;
274}
275
276/* Computes result = left + right, returning carry. Can modify in place. */
277static u64 vli_uadd(u64 *result, const u64 *left, u64 right,
278		    unsigned int ndigits)
279{
280	u64 carry = right;
281	int i;
282
283	for (i = 0; i < ndigits; i++) {
284		u64 sum;
285
286		sum = left[i] + carry;
287		if (sum != left[i])
288			carry = (sum < left[i]);
289		else
290			carry = !!carry;
291
292		result[i] = sum;
293	}
294
295	return carry;
296}
297
298/* Computes result = left - right, returning borrow. Can modify in place. */
299u64 vli_sub(u64 *result, const u64 *left, const u64 *right,
300		   unsigned int ndigits)
301{
302	u64 borrow = 0;
303	int i;
304
305	for (i = 0; i < ndigits; i++) {
306		u64 diff;
307
308		diff = left[i] - right[i] - borrow;
309		if (diff != left[i])
310			borrow = (diff > left[i]);
311
312		result[i] = diff;
313	}
314
315	return borrow;
316}
317EXPORT_SYMBOL(vli_sub);
318
319/* Computes result = left - right, returning borrow. Can modify in place. */
320static u64 vli_usub(u64 *result, const u64 *left, u64 right,
321	     unsigned int ndigits)
322{
323	u64 borrow = right;
324	int i;
325
326	for (i = 0; i < ndigits; i++) {
327		u64 diff;
328
329		diff = left[i] - borrow;
330		if (diff != left[i])
331			borrow = (diff > left[i]);
332
333		result[i] = diff;
334	}
335
336	return borrow;
337}
338
339static uint128_t mul_64_64(u64 left, u64 right)
340{
341	uint128_t result;
342#if defined(CONFIG_ARCH_SUPPORTS_INT128)
343	unsigned __int128 m = (unsigned __int128)left * right;
344
345	result.m_low  = m;
346	result.m_high = m >> 64;
347#else
348	u64 a0 = left & 0xffffffffull;
349	u64 a1 = left >> 32;
350	u64 b0 = right & 0xffffffffull;
351	u64 b1 = right >> 32;
352	u64 m0 = a0 * b0;
353	u64 m1 = a0 * b1;
354	u64 m2 = a1 * b0;
355	u64 m3 = a1 * b1;
356
357	m2 += (m0 >> 32);
358	m2 += m1;
359
360	/* Overflow */
361	if (m2 < m1)
362		m3 += 0x100000000ull;
363
364	result.m_low = (m0 & 0xffffffffull) | (m2 << 32);
365	result.m_high = m3 + (m2 >> 32);
366#endif
367	return result;
368}
369
370static uint128_t add_128_128(uint128_t a, uint128_t b)
371{
372	uint128_t result;
373
374	result.m_low = a.m_low + b.m_low;
375	result.m_high = a.m_high + b.m_high + (result.m_low < a.m_low);
376
377	return result;
378}
379
380static void vli_mult(u64 *result, const u64 *left, const u64 *right,
381		     unsigned int ndigits)
382{
383	uint128_t r01 = { 0, 0 };
384	u64 r2 = 0;
385	unsigned int i, k;
386
387	/* Compute each digit of result in sequence, maintaining the
388	 * carries.
389	 */
390	for (k = 0; k < ndigits * 2 - 1; k++) {
391		unsigned int min;
392
393		if (k < ndigits)
394			min = 0;
395		else
396			min = (k + 1) - ndigits;
397
398		for (i = min; i <= k && i < ndigits; i++) {
399			uint128_t product;
400
401			product = mul_64_64(left[i], right[k - i]);
402
403			r01 = add_128_128(r01, product);
404			r2 += (r01.m_high < product.m_high);
405		}
406
407		result[k] = r01.m_low;
408		r01.m_low = r01.m_high;
409		r01.m_high = r2;
410		r2 = 0;
411	}
412
413	result[ndigits * 2 - 1] = r01.m_low;
414}
415
416/* Compute product = left * right, for a small right value. */
417static void vli_umult(u64 *result, const u64 *left, u32 right,
418		      unsigned int ndigits)
419{
420	uint128_t r01 = { 0 };
421	unsigned int k;
422
423	for (k = 0; k < ndigits; k++) {
424		uint128_t product;
425
426		product = mul_64_64(left[k], right);
427		r01 = add_128_128(r01, product);
428		/* no carry */
429		result[k] = r01.m_low;
430		r01.m_low = r01.m_high;
431		r01.m_high = 0;
432	}
433	result[k] = r01.m_low;
434	for (++k; k < ndigits * 2; k++)
435		result[k] = 0;
436}
437
438static void vli_square(u64 *result, const u64 *left, unsigned int ndigits)
439{
440	uint128_t r01 = { 0, 0 };
441	u64 r2 = 0;
442	int i, k;
443
444	for (k = 0; k < ndigits * 2 - 1; k++) {
445		unsigned int min;
446
447		if (k < ndigits)
448			min = 0;
449		else
450			min = (k + 1) - ndigits;
451
452		for (i = min; i <= k && i <= k - i; i++) {
453			uint128_t product;
454
455			product = mul_64_64(left[i], left[k - i]);
456
457			if (i < k - i) {
458				r2 += product.m_high >> 63;
459				product.m_high = (product.m_high << 1) |
460						 (product.m_low >> 63);
461				product.m_low <<= 1;
462			}
463
464			r01 = add_128_128(r01, product);
465			r2 += (r01.m_high < product.m_high);
466		}
467
468		result[k] = r01.m_low;
469		r01.m_low = r01.m_high;
470		r01.m_high = r2;
471		r2 = 0;
472	}
473
474	result[ndigits * 2 - 1] = r01.m_low;
475}
476
477/* Computes result = (left + right) % mod.
478 * Assumes that left < mod and right < mod, result != mod.
479 */
480static void vli_mod_add(u64 *result, const u64 *left, const u64 *right,
481			const u64 *mod, unsigned int ndigits)
482{
483	u64 carry;
484
485	carry = vli_add(result, left, right, ndigits);
486
487	/* result > mod (result = mod + remainder), so subtract mod to
488	 * get remainder.
489	 */
490	if (carry || vli_cmp(result, mod, ndigits) >= 0)
491		vli_sub(result, result, mod, ndigits);
492}
493
494/* Computes result = (left - right) % mod.
495 * Assumes that left < mod and right < mod, result != mod.
496 */
497static void vli_mod_sub(u64 *result, const u64 *left, const u64 *right,
498			const u64 *mod, unsigned int ndigits)
499{
500	u64 borrow = vli_sub(result, left, right, ndigits);
501
502	/* In this case, p_result == -diff == (max int) - diff.
503	 * Since -x % d == d - x, we can get the correct result from
504	 * result + mod (with overflow).
505	 */
506	if (borrow)
507		vli_add(result, result, mod, ndigits);
508}
509
510/*
511 * Computes result = product % mod
512 * for special form moduli: p = 2^k-c, for small c (note the minus sign)
513 *
514 * References:
515 * R. Crandall, C. Pomerance. Prime Numbers: A Computational Perspective.
516 * 9 Fast Algorithms for Large-Integer Arithmetic. 9.2.3 Moduli of special form
517 * Algorithm 9.2.13 (Fast mod operation for special-form moduli).
518 */
519static void vli_mmod_special(u64 *result, const u64 *product,
520			      const u64 *mod, unsigned int ndigits)
521{
522	u64 c = -mod[0];
523	u64 t[ECC_MAX_DIGITS * 2];
524	u64 r[ECC_MAX_DIGITS * 2];
525
526	vli_set(r, product, ndigits * 2);
527	while (!vli_is_zero(r + ndigits, ndigits)) {
528		vli_umult(t, r + ndigits, c, ndigits);
529		vli_clear(r + ndigits, ndigits);
530		vli_add(r, r, t, ndigits * 2);
531	}
532	vli_set(t, mod, ndigits);
533	vli_clear(t + ndigits, ndigits);
534	while (vli_cmp(r, t, ndigits * 2) >= 0)
535		vli_sub(r, r, t, ndigits * 2);
536	vli_set(result, r, ndigits);
537}
538
539/*
540 * Computes result = product % mod
541 * for special form moduli: p = 2^{k-1}+c, for small c (note the plus sign)
542 * where k-1 does not fit into qword boundary by -1 bit (such as 255).
543
544 * References (loosely based on):
545 * A. Menezes, P. van Oorschot, S. Vanstone. Handbook of Applied Cryptography.
546 * 14.3.4 Reduction methods for moduli of special form. Algorithm 14.47.
547 * URL: http://cacr.uwaterloo.ca/hac/about/chap14.pdf
548 *
549 * H. Cohen, G. Frey, R. Avanzi, C. Doche, T. Lange, K. Nguyen, F. Vercauteren.
550 * Handbook of Elliptic and Hyperelliptic Curve Cryptography.
551 * Algorithm 10.25 Fast reduction for special form moduli
552 */
553static void vli_mmod_special2(u64 *result, const u64 *product,
554			       const u64 *mod, unsigned int ndigits)
555{
556	u64 c2 = mod[0] * 2;
557	u64 q[ECC_MAX_DIGITS];
558	u64 r[ECC_MAX_DIGITS * 2];
559	u64 m[ECC_MAX_DIGITS * 2]; /* expanded mod */
560	int carry; /* last bit that doesn't fit into q */
561	int i;
562
563	vli_set(m, mod, ndigits);
564	vli_clear(m + ndigits, ndigits);
565
566	vli_set(r, product, ndigits);
567	/* q and carry are top bits */
568	vli_set(q, product + ndigits, ndigits);
569	vli_clear(r + ndigits, ndigits);
570	carry = vli_is_negative(r, ndigits);
571	if (carry)
572		r[ndigits - 1] &= (1ull << 63) - 1;
573	for (i = 1; carry || !vli_is_zero(q, ndigits); i++) {
574		u64 qc[ECC_MAX_DIGITS * 2];
575
576		vli_umult(qc, q, c2, ndigits);
577		if (carry)
578			vli_uadd(qc, qc, mod[0], ndigits * 2);
579		vli_set(q, qc + ndigits, ndigits);
580		vli_clear(qc + ndigits, ndigits);
581		carry = vli_is_negative(qc, ndigits);
582		if (carry)
583			qc[ndigits - 1] &= (1ull << 63) - 1;
584		if (i & 1)
585			vli_sub(r, r, qc, ndigits * 2);
586		else
587			vli_add(r, r, qc, ndigits * 2);
588	}
589	while (vli_is_negative(r, ndigits * 2))
590		vli_add(r, r, m, ndigits * 2);
591	while (vli_cmp(r, m, ndigits * 2) >= 0)
592		vli_sub(r, r, m, ndigits * 2);
593
594	vli_set(result, r, ndigits);
595}
596
597/*
598 * Computes result = product % mod, where product is 2N words long.
599 * Reference: Ken MacKay's micro-ecc.
600 * Currently only designed to work for curve_p or curve_n.
601 */
602static void vli_mmod_slow(u64 *result, u64 *product, const u64 *mod,
603			  unsigned int ndigits)
604{
605	u64 mod_m[2 * ECC_MAX_DIGITS];
606	u64 tmp[2 * ECC_MAX_DIGITS];
607	u64 *v[2] = { tmp, product };
608	u64 carry = 0;
609	unsigned int i;
610	/* Shift mod so its highest set bit is at the maximum position. */
611	int shift = (ndigits * 2 * 64) - vli_num_bits(mod, ndigits);
612	int word_shift = shift / 64;
613	int bit_shift = shift % 64;
614
615	vli_clear(mod_m, word_shift);
616	if (bit_shift > 0) {
617		for (i = 0; i < ndigits; ++i) {
618			mod_m[word_shift + i] = (mod[i] << bit_shift) | carry;
619			carry = mod[i] >> (64 - bit_shift);
620		}
621	} else
622		vli_set(mod_m + word_shift, mod, ndigits);
623
624	for (i = 1; shift >= 0; --shift) {
625		u64 borrow = 0;
626		unsigned int j;
627
628		for (j = 0; j < ndigits * 2; ++j) {
629			u64 diff = v[i][j] - mod_m[j] - borrow;
630
631			if (diff != v[i][j])
632				borrow = (diff > v[i][j]);
633			v[1 - i][j] = diff;
634		}
635		i = !(i ^ borrow); /* Swap the index if there was no borrow */
636		vli_rshift1(mod_m, ndigits);
637		mod_m[ndigits - 1] |= mod_m[ndigits] << (64 - 1);
638		vli_rshift1(mod_m + ndigits, ndigits);
639	}
640	vli_set(result, v[i], ndigits);
641}
642
643/* Computes result = product % mod using Barrett's reduction with precomputed
644 * value mu appended to the mod after ndigits, mu = (2^{2w} / mod) and have
645 * length ndigits + 1, where mu * (2^w - 1) should not overflow ndigits
646 * boundary.
647 *
648 * Reference:
649 * R. Brent, P. Zimmermann. Modern Computer Arithmetic. 2010.
650 * 2.4.1 Barrett's algorithm. Algorithm 2.5.
651 */
652static void vli_mmod_barrett(u64 *result, u64 *product, const u64 *mod,
653			     unsigned int ndigits)
654{
655	u64 q[ECC_MAX_DIGITS * 2];
656	u64 r[ECC_MAX_DIGITS * 2];
657	const u64 *mu = mod + ndigits;
658
659	vli_mult(q, product + ndigits, mu, ndigits);
660	if (mu[ndigits])
661		vli_add(q + ndigits, q + ndigits, product + ndigits, ndigits);
662	vli_mult(r, mod, q + ndigits, ndigits);
663	vli_sub(r, product, r, ndigits * 2);
664	while (!vli_is_zero(r + ndigits, ndigits) ||
665	       vli_cmp(r, mod, ndigits) != -1) {
666		u64 carry;
667
668		carry = vli_sub(r, r, mod, ndigits);
669		vli_usub(r + ndigits, r + ndigits, carry, ndigits);
670	}
671	vli_set(result, r, ndigits);
672}
673
674/* Computes p_result = p_product % curve_p.
675 * See algorithm 5 and 6 from
676 * http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf
677 */
678static void vli_mmod_fast_192(u64 *result, const u64 *product,
679			      const u64 *curve_prime, u64 *tmp)
680{
681	const unsigned int ndigits = 3;
682	int carry;
683
684	vli_set(result, product, ndigits);
685
686	vli_set(tmp, &product[3], ndigits);
687	carry = vli_add(result, result, tmp, ndigits);
688
689	tmp[0] = 0;
690	tmp[1] = product[3];
691	tmp[2] = product[4];
692	carry += vli_add(result, result, tmp, ndigits);
693
694	tmp[0] = tmp[1] = product[5];
695	tmp[2] = 0;
696	carry += vli_add(result, result, tmp, ndigits);
697
698	while (carry || vli_cmp(curve_prime, result, ndigits) != 1)
699		carry -= vli_sub(result, result, curve_prime, ndigits);
700}
701
702/* Computes result = product % curve_prime
703 * from http://www.nsa.gov/ia/_files/nist-routines.pdf
704 */
705static void vli_mmod_fast_256(u64 *result, const u64 *product,
706			      const u64 *curve_prime, u64 *tmp)
707{
708	int carry;
709	const unsigned int ndigits = 4;
710
711	/* t */
712	vli_set(result, product, ndigits);
713
714	/* s1 */
715	tmp[0] = 0;
716	tmp[1] = product[5] & 0xffffffff00000000ull;
717	tmp[2] = product[6];
718	tmp[3] = product[7];
719	carry = vli_lshift(tmp, tmp, 1, ndigits);
720	carry += vli_add(result, result, tmp, ndigits);
721
722	/* s2 */
723	tmp[1] = product[6] << 32;
724	tmp[2] = (product[6] >> 32) | (product[7] << 32);
725	tmp[3] = product[7] >> 32;
726	carry += vli_lshift(tmp, tmp, 1, ndigits);
727	carry += vli_add(result, result, tmp, ndigits);
728
729	/* s3 */
730	tmp[0] = product[4];
731	tmp[1] = product[5] & 0xffffffff;
732	tmp[2] = 0;
733	tmp[3] = product[7];
734	carry += vli_add(result, result, tmp, ndigits);
735
736	/* s4 */
737	tmp[0] = (product[4] >> 32) | (product[5] << 32);
738	tmp[1] = (product[5] >> 32) | (product[6] & 0xffffffff00000000ull);
739	tmp[2] = product[7];
740	tmp[3] = (product[6] >> 32) | (product[4] << 32);
741	carry += vli_add(result, result, tmp, ndigits);
742
743	/* d1 */
744	tmp[0] = (product[5] >> 32) | (product[6] << 32);
745	tmp[1] = (product[6] >> 32);
746	tmp[2] = 0;
747	tmp[3] = (product[4] & 0xffffffff) | (product[5] << 32);
748	carry -= vli_sub(result, result, tmp, ndigits);
749
750	/* d2 */
751	tmp[0] = product[6];
752	tmp[1] = product[7];
753	tmp[2] = 0;
754	tmp[3] = (product[4] >> 32) | (product[5] & 0xffffffff00000000ull);
755	carry -= vli_sub(result, result, tmp, ndigits);
756
757	/* d3 */
758	tmp[0] = (product[6] >> 32) | (product[7] << 32);
759	tmp[1] = (product[7] >> 32) | (product[4] << 32);
760	tmp[2] = (product[4] >> 32) | (product[5] << 32);
761	tmp[3] = (product[6] << 32);
762	carry -= vli_sub(result, result, tmp, ndigits);
763
764	/* d4 */
765	tmp[0] = product[7];
766	tmp[1] = product[4] & 0xffffffff00000000ull;
767	tmp[2] = product[5];
768	tmp[3] = product[6] & 0xffffffff00000000ull;
769	carry -= vli_sub(result, result, tmp, ndigits);
770
771	if (carry < 0) {
772		do {
773			carry += vli_add(result, result, curve_prime, ndigits);
774		} while (carry < 0);
775	} else {
776		while (carry || vli_cmp(curve_prime, result, ndigits) != 1)
777			carry -= vli_sub(result, result, curve_prime, ndigits);
778	}
779}
780
781#define SL32OR32(x32, y32) (((u64)x32 << 32) | y32)
782#define AND64H(x64)  (x64 & 0xffFFffFF00000000ull)
783#define AND64L(x64)  (x64 & 0x00000000ffFFffFFull)
784
785/* Computes result = product % curve_prime
786 * from "Mathematical routines for the NIST prime elliptic curves"
787 */
788static void vli_mmod_fast_384(u64 *result, const u64 *product,
789				const u64 *curve_prime, u64 *tmp)
790{
791	int carry;
792	const unsigned int ndigits = 6;
793
794	/* t */
795	vli_set(result, product, ndigits);
796
797	/* s1 */
798	tmp[0] = 0;		// 0 || 0
799	tmp[1] = 0;		// 0 || 0
800	tmp[2] = SL32OR32(product[11], (product[10]>>32));	//a22||a21
801	tmp[3] = product[11]>>32;	// 0 ||a23
802	tmp[4] = 0;		// 0 || 0
803	tmp[5] = 0;		// 0 || 0
804	carry = vli_lshift(tmp, tmp, 1, ndigits);
805	carry += vli_add(result, result, tmp, ndigits);
806
807	/* s2 */
808	tmp[0] = product[6];	//a13||a12
809	tmp[1] = product[7];	//a15||a14
810	tmp[2] = product[8];	//a17||a16
811	tmp[3] = product[9];	//a19||a18
812	tmp[4] = product[10];	//a21||a20
813	tmp[5] = product[11];	//a23||a22
814	carry += vli_add(result, result, tmp, ndigits);
815
816	/* s3 */
817	tmp[0] = SL32OR32(product[11], (product[10]>>32));	//a22||a21
818	tmp[1] = SL32OR32(product[6], (product[11]>>32));	//a12||a23
819	tmp[2] = SL32OR32(product[7], (product[6])>>32);	//a14||a13
820	tmp[3] = SL32OR32(product[8], (product[7]>>32));	//a16||a15
821	tmp[4] = SL32OR32(product[9], (product[8]>>32));	//a18||a17
822	tmp[5] = SL32OR32(product[10], (product[9]>>32));	//a20||a19
823	carry += vli_add(result, result, tmp, ndigits);
824
825	/* s4 */
826	tmp[0] = AND64H(product[11]);	//a23|| 0
827	tmp[1] = (product[10]<<32);	//a20|| 0
828	tmp[2] = product[6];	//a13||a12
829	tmp[3] = product[7];	//a15||a14
830	tmp[4] = product[8];	//a17||a16
831	tmp[5] = product[9];	//a19||a18
832	carry += vli_add(result, result, tmp, ndigits);
833
834	/* s5 */
835	tmp[0] = 0;		//  0|| 0
836	tmp[1] = 0;		//  0|| 0
837	tmp[2] = product[10];	//a21||a20
838	tmp[3] = product[11];	//a23||a22
839	tmp[4] = 0;		//  0|| 0
840	tmp[5] = 0;		//  0|| 0
841	carry += vli_add(result, result, tmp, ndigits);
842
843	/* s6 */
844	tmp[0] = AND64L(product[10]);	// 0 ||a20
845	tmp[1] = AND64H(product[10]);	//a21|| 0
846	tmp[2] = product[11];	//a23||a22
847	tmp[3] = 0;		// 0 || 0
848	tmp[4] = 0;		// 0 || 0
849	tmp[5] = 0;		// 0 || 0
850	carry += vli_add(result, result, tmp, ndigits);
851
852	/* d1 */
853	tmp[0] = SL32OR32(product[6], (product[11]>>32));	//a12||a23
854	tmp[1] = SL32OR32(product[7], (product[6]>>32));	//a14||a13
855	tmp[2] = SL32OR32(product[8], (product[7]>>32));	//a16||a15
856	tmp[3] = SL32OR32(product[9], (product[8]>>32));	//a18||a17
857	tmp[4] = SL32OR32(product[10], (product[9]>>32));	//a20||a19
858	tmp[5] = SL32OR32(product[11], (product[10]>>32));	//a22||a21
859	carry -= vli_sub(result, result, tmp, ndigits);
860
861	/* d2 */
862	tmp[0] = (product[10]<<32);	//a20|| 0
863	tmp[1] = SL32OR32(product[11], (product[10]>>32));	//a22||a21
864	tmp[2] = (product[11]>>32);	// 0 ||a23
865	tmp[3] = 0;		// 0 || 0
866	tmp[4] = 0;		// 0 || 0
867	tmp[5] = 0;		// 0 || 0
868	carry -= vli_sub(result, result, tmp, ndigits);
869
870	/* d3 */
871	tmp[0] = 0;		// 0 || 0
872	tmp[1] = AND64H(product[11]);	//a23|| 0
873	tmp[2] = product[11]>>32;	// 0 ||a23
874	tmp[3] = 0;		// 0 || 0
875	tmp[4] = 0;		// 0 || 0
876	tmp[5] = 0;		// 0 || 0
877	carry -= vli_sub(result, result, tmp, ndigits);
878
879	if (carry < 0) {
880		do {
881			carry += vli_add(result, result, curve_prime, ndigits);
882		} while (carry < 0);
883	} else {
884		while (carry || vli_cmp(curve_prime, result, ndigits) != 1)
885			carry -= vli_sub(result, result, curve_prime, ndigits);
886	}
887
888}
889
890#undef SL32OR32
891#undef AND64H
892#undef AND64L
893
894/* Computes result = product % curve_prime for different curve_primes.
895 *
896 * Note that curve_primes are distinguished just by heuristic check and
897 * not by complete conformance check.
898 */
899static bool vli_mmod_fast(u64 *result, u64 *product,
900			  const struct ecc_curve *curve)
901{
902	u64 tmp[2 * ECC_MAX_DIGITS];
903	const u64 *curve_prime = curve->p;
904	const unsigned int ndigits = curve->g.ndigits;
905
906	/* All NIST curves have name prefix 'nist_' */
907	if (strncmp(curve->name, "nist_", 5) != 0) {
908		/* Try to handle Pseudo-Marsenne primes. */
909		if (curve_prime[ndigits - 1] == -1ull) {
910			vli_mmod_special(result, product, curve_prime,
911					 ndigits);
912			return true;
913		} else if (curve_prime[ndigits - 1] == 1ull << 63 &&
914			   curve_prime[ndigits - 2] == 0) {
915			vli_mmod_special2(result, product, curve_prime,
916					  ndigits);
917			return true;
918		}
919		vli_mmod_barrett(result, product, curve_prime, ndigits);
920		return true;
921	}
922
923	switch (ndigits) {
924	case 3:
925		vli_mmod_fast_192(result, product, curve_prime, tmp);
926		break;
927	case 4:
928		vli_mmod_fast_256(result, product, curve_prime, tmp);
929		break;
930	case 6:
931		vli_mmod_fast_384(result, product, curve_prime, tmp);
932		break;
933	default:
934		pr_err_ratelimited("ecc: unsupported digits size!\n");
935		return false;
936	}
937
938	return true;
939}
940
941/* Computes result = (left * right) % mod.
942 * Assumes that mod is big enough curve order.
943 */
944void vli_mod_mult_slow(u64 *result, const u64 *left, const u64 *right,
945		       const u64 *mod, unsigned int ndigits)
946{
947	u64 product[ECC_MAX_DIGITS * 2];
948
949	vli_mult(product, left, right, ndigits);
950	vli_mmod_slow(result, product, mod, ndigits);
951}
952EXPORT_SYMBOL(vli_mod_mult_slow);
953
954/* Computes result = (left * right) % curve_prime. */
955static void vli_mod_mult_fast(u64 *result, const u64 *left, const u64 *right,
956			      const struct ecc_curve *curve)
957{
958	u64 product[2 * ECC_MAX_DIGITS];
959
960	vli_mult(product, left, right, curve->g.ndigits);
961	vli_mmod_fast(result, product, curve);
962}
963
964/* Computes result = left^2 % curve_prime. */
965static void vli_mod_square_fast(u64 *result, const u64 *left,
966				const struct ecc_curve *curve)
967{
968	u64 product[2 * ECC_MAX_DIGITS];
969
970	vli_square(product, left, curve->g.ndigits);
971	vli_mmod_fast(result, product, curve);
972}
973
974#define EVEN(vli) (!(vli[0] & 1))
975/* Computes result = (1 / p_input) % mod. All VLIs are the same size.
976 * See "From Euclid's GCD to Montgomery Multiplication to the Great Divide"
977 * https://labs.oracle.com/techrep/2001/smli_tr-2001-95.pdf
978 */
979void vli_mod_inv(u64 *result, const u64 *input, const u64 *mod,
980			unsigned int ndigits)
981{
982	u64 a[ECC_MAX_DIGITS], b[ECC_MAX_DIGITS];
983	u64 u[ECC_MAX_DIGITS], v[ECC_MAX_DIGITS];
984	u64 carry;
985	int cmp_result;
986
987	if (vli_is_zero(input, ndigits)) {
988		vli_clear(result, ndigits);
989		return;
990	}
991
992	vli_set(a, input, ndigits);
993	vli_set(b, mod, ndigits);
994	vli_clear(u, ndigits);
995	u[0] = 1;
996	vli_clear(v, ndigits);
997
998	while ((cmp_result = vli_cmp(a, b, ndigits)) != 0) {
999		carry = 0;
1000
1001		if (EVEN(a)) {
1002			vli_rshift1(a, ndigits);
1003
1004			if (!EVEN(u))
1005				carry = vli_add(u, u, mod, ndigits);
1006
1007			vli_rshift1(u, ndigits);
1008			if (carry)
1009				u[ndigits - 1] |= 0x8000000000000000ull;
1010		} else if (EVEN(b)) {
1011			vli_rshift1(b, ndigits);
1012
1013			if (!EVEN(v))
1014				carry = vli_add(v, v, mod, ndigits);
1015
1016			vli_rshift1(v, ndigits);
1017			if (carry)
1018				v[ndigits - 1] |= 0x8000000000000000ull;
1019		} else if (cmp_result > 0) {
1020			vli_sub(a, a, b, ndigits);
1021			vli_rshift1(a, ndigits);
1022
1023			if (vli_cmp(u, v, ndigits) < 0)
1024				vli_add(u, u, mod, ndigits);
1025
1026			vli_sub(u, u, v, ndigits);
1027			if (!EVEN(u))
1028				carry = vli_add(u, u, mod, ndigits);
1029
1030			vli_rshift1(u, ndigits);
1031			if (carry)
1032				u[ndigits - 1] |= 0x8000000000000000ull;
1033		} else {
1034			vli_sub(b, b, a, ndigits);
1035			vli_rshift1(b, ndigits);
1036
1037			if (vli_cmp(v, u, ndigits) < 0)
1038				vli_add(v, v, mod, ndigits);
1039
1040			vli_sub(v, v, u, ndigits);
1041			if (!EVEN(v))
1042				carry = vli_add(v, v, mod, ndigits);
1043
1044			vli_rshift1(v, ndigits);
1045			if (carry)
1046				v[ndigits - 1] |= 0x8000000000000000ull;
1047		}
1048	}
1049
1050	vli_set(result, u, ndigits);
1051}
1052EXPORT_SYMBOL(vli_mod_inv);
1053
1054/* ------ Point operations ------ */
1055
1056/* Returns true if p_point is the point at infinity, false otherwise. */
1057static bool ecc_point_is_zero(const struct ecc_point *point)
1058{
1059	return (vli_is_zero(point->x, point->ndigits) &&
1060		vli_is_zero(point->y, point->ndigits));
1061}
1062
1063/* Point multiplication algorithm using Montgomery's ladder with co-Z
1064 * coordinates. From https://eprint.iacr.org/2011/338.pdf
1065 */
1066
1067/* Double in place */
1068static void ecc_point_double_jacobian(u64 *x1, u64 *y1, u64 *z1,
1069					const struct ecc_curve *curve)
1070{
1071	/* t1 = x, t2 = y, t3 = z */
1072	u64 t4[ECC_MAX_DIGITS];
1073	u64 t5[ECC_MAX_DIGITS];
1074	const u64 *curve_prime = curve->p;
1075	const unsigned int ndigits = curve->g.ndigits;
1076
1077	if (vli_is_zero(z1, ndigits))
1078		return;
1079
1080	/* t4 = y1^2 */
1081	vli_mod_square_fast(t4, y1, curve);
1082	/* t5 = x1*y1^2 = A */
1083	vli_mod_mult_fast(t5, x1, t4, curve);
1084	/* t4 = y1^4 */
1085	vli_mod_square_fast(t4, t4, curve);
1086	/* t2 = y1*z1 = z3 */
1087	vli_mod_mult_fast(y1, y1, z1, curve);
1088	/* t3 = z1^2 */
1089	vli_mod_square_fast(z1, z1, curve);
1090
1091	/* t1 = x1 + z1^2 */
1092	vli_mod_add(x1, x1, z1, curve_prime, ndigits);
1093	/* t3 = 2*z1^2 */
1094	vli_mod_add(z1, z1, z1, curve_prime, ndigits);
1095	/* t3 = x1 - z1^2 */
1096	vli_mod_sub(z1, x1, z1, curve_prime, ndigits);
1097	/* t1 = x1^2 - z1^4 */
1098	vli_mod_mult_fast(x1, x1, z1, curve);
1099
1100	/* t3 = 2*(x1^2 - z1^4) */
1101	vli_mod_add(z1, x1, x1, curve_prime, ndigits);
1102	/* t1 = 3*(x1^2 - z1^4) */
1103	vli_mod_add(x1, x1, z1, curve_prime, ndigits);
1104	if (vli_test_bit(x1, 0)) {
1105		u64 carry = vli_add(x1, x1, curve_prime, ndigits);
1106
1107		vli_rshift1(x1, ndigits);
1108		x1[ndigits - 1] |= carry << 63;
1109	} else {
1110		vli_rshift1(x1, ndigits);
1111	}
1112	/* t1 = 3/2*(x1^2 - z1^4) = B */
1113
1114	/* t3 = B^2 */
1115	vli_mod_square_fast(z1, x1, curve);
1116	/* t3 = B^2 - A */
1117	vli_mod_sub(z1, z1, t5, curve_prime, ndigits);
1118	/* t3 = B^2 - 2A = x3 */
1119	vli_mod_sub(z1, z1, t5, curve_prime, ndigits);
1120	/* t5 = A - x3 */
1121	vli_mod_sub(t5, t5, z1, curve_prime, ndigits);
1122	/* t1 = B * (A - x3) */
1123	vli_mod_mult_fast(x1, x1, t5, curve);
1124	/* t4 = B * (A - x3) - y1^4 = y3 */
1125	vli_mod_sub(t4, x1, t4, curve_prime, ndigits);
1126
1127	vli_set(x1, z1, ndigits);
1128	vli_set(z1, y1, ndigits);
1129	vli_set(y1, t4, ndigits);
1130}
1131
1132/* Modify (x1, y1) => (x1 * z^2, y1 * z^3) */
1133static void apply_z(u64 *x1, u64 *y1, u64 *z, const struct ecc_curve *curve)
1134{
1135	u64 t1[ECC_MAX_DIGITS];
1136
1137	vli_mod_square_fast(t1, z, curve);		/* z^2 */
1138	vli_mod_mult_fast(x1, x1, t1, curve);	/* x1 * z^2 */
1139	vli_mod_mult_fast(t1, t1, z, curve);	/* z^3 */
1140	vli_mod_mult_fast(y1, y1, t1, curve);	/* y1 * z^3 */
1141}
1142
1143/* P = (x1, y1) => 2P, (x2, y2) => P' */
1144static void xycz_initial_double(u64 *x1, u64 *y1, u64 *x2, u64 *y2,
1145				u64 *p_initial_z, const struct ecc_curve *curve)
1146{
1147	u64 z[ECC_MAX_DIGITS];
1148	const unsigned int ndigits = curve->g.ndigits;
1149
1150	vli_set(x2, x1, ndigits);
1151	vli_set(y2, y1, ndigits);
1152
1153	vli_clear(z, ndigits);
1154	z[0] = 1;
1155
1156	if (p_initial_z)
1157		vli_set(z, p_initial_z, ndigits);
1158
1159	apply_z(x1, y1, z, curve);
1160
1161	ecc_point_double_jacobian(x1, y1, z, curve);
1162
1163	apply_z(x2, y2, z, curve);
1164}
1165
1166/* Input P = (x1, y1, Z), Q = (x2, y2, Z)
1167 * Output P' = (x1', y1', Z3), P + Q = (x3, y3, Z3)
1168 * or P => P', Q => P + Q
1169 */
1170static void xycz_add(u64 *x1, u64 *y1, u64 *x2, u64 *y2,
1171			const struct ecc_curve *curve)
1172{
1173	/* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
1174	u64 t5[ECC_MAX_DIGITS];
1175	const u64 *curve_prime = curve->p;
1176	const unsigned int ndigits = curve->g.ndigits;
1177
1178	/* t5 = x2 - x1 */
1179	vli_mod_sub(t5, x2, x1, curve_prime, ndigits);
1180	/* t5 = (x2 - x1)^2 = A */
1181	vli_mod_square_fast(t5, t5, curve);
1182	/* t1 = x1*A = B */
1183	vli_mod_mult_fast(x1, x1, t5, curve);
1184	/* t3 = x2*A = C */
1185	vli_mod_mult_fast(x2, x2, t5, curve);
1186	/* t4 = y2 - y1 */
1187	vli_mod_sub(y2, y2, y1, curve_prime, ndigits);
1188	/* t5 = (y2 - y1)^2 = D */
1189	vli_mod_square_fast(t5, y2, curve);
1190
1191	/* t5 = D - B */
1192	vli_mod_sub(t5, t5, x1, curve_prime, ndigits);
1193	/* t5 = D - B - C = x3 */
1194	vli_mod_sub(t5, t5, x2, curve_prime, ndigits);
1195	/* t3 = C - B */
1196	vli_mod_sub(x2, x2, x1, curve_prime, ndigits);
1197	/* t2 = y1*(C - B) */
1198	vli_mod_mult_fast(y1, y1, x2, curve);
1199	/* t3 = B - x3 */
1200	vli_mod_sub(x2, x1, t5, curve_prime, ndigits);
1201	/* t4 = (y2 - y1)*(B - x3) */
1202	vli_mod_mult_fast(y2, y2, x2, curve);
1203	/* t4 = y3 */
1204	vli_mod_sub(y2, y2, y1, curve_prime, ndigits);
1205
1206	vli_set(x2, t5, ndigits);
1207}
1208
1209/* Input P = (x1, y1, Z), Q = (x2, y2, Z)
1210 * Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
1211 * or P => P - Q, Q => P + Q
1212 */
1213static void xycz_add_c(u64 *x1, u64 *y1, u64 *x2, u64 *y2,
1214			const struct ecc_curve *curve)
1215{
1216	/* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
1217	u64 t5[ECC_MAX_DIGITS];
1218	u64 t6[ECC_MAX_DIGITS];
1219	u64 t7[ECC_MAX_DIGITS];
1220	const u64 *curve_prime = curve->p;
1221	const unsigned int ndigits = curve->g.ndigits;
1222
1223	/* t5 = x2 - x1 */
1224	vli_mod_sub(t5, x2, x1, curve_prime, ndigits);
1225	/* t5 = (x2 - x1)^2 = A */
1226	vli_mod_square_fast(t5, t5, curve);
1227	/* t1 = x1*A = B */
1228	vli_mod_mult_fast(x1, x1, t5, curve);
1229	/* t3 = x2*A = C */
1230	vli_mod_mult_fast(x2, x2, t5, curve);
1231	/* t4 = y2 + y1 */
1232	vli_mod_add(t5, y2, y1, curve_prime, ndigits);
1233	/* t4 = y2 - y1 */
1234	vli_mod_sub(y2, y2, y1, curve_prime, ndigits);
1235
1236	/* t6 = C - B */
1237	vli_mod_sub(t6, x2, x1, curve_prime, ndigits);
1238	/* t2 = y1 * (C - B) */
1239	vli_mod_mult_fast(y1, y1, t6, curve);
1240	/* t6 = B + C */
1241	vli_mod_add(t6, x1, x2, curve_prime, ndigits);
1242	/* t3 = (y2 - y1)^2 */
1243	vli_mod_square_fast(x2, y2, curve);
1244	/* t3 = x3 */
1245	vli_mod_sub(x2, x2, t6, curve_prime, ndigits);
1246
1247	/* t7 = B - x3 */
1248	vli_mod_sub(t7, x1, x2, curve_prime, ndigits);
1249	/* t4 = (y2 - y1)*(B - x3) */
1250	vli_mod_mult_fast(y2, y2, t7, curve);
1251	/* t4 = y3 */
1252	vli_mod_sub(y2, y2, y1, curve_prime, ndigits);
1253
1254	/* t7 = (y2 + y1)^2 = F */
1255	vli_mod_square_fast(t7, t5, curve);
1256	/* t7 = x3' */
1257	vli_mod_sub(t7, t7, t6, curve_prime, ndigits);
1258	/* t6 = x3' - B */
1259	vli_mod_sub(t6, t7, x1, curve_prime, ndigits);
1260	/* t6 = (y2 + y1)*(x3' - B) */
1261	vli_mod_mult_fast(t6, t6, t5, curve);
1262	/* t2 = y3' */
1263	vli_mod_sub(y1, t6, y1, curve_prime, ndigits);
1264
1265	vli_set(x1, t7, ndigits);
1266}
1267
1268static void ecc_point_mult(struct ecc_point *result,
1269			   const struct ecc_point *point, const u64 *scalar,
1270			   u64 *initial_z, const struct ecc_curve *curve,
1271			   unsigned int ndigits)
1272{
1273	/* R0 and R1 */
1274	u64 rx[2][ECC_MAX_DIGITS];
1275	u64 ry[2][ECC_MAX_DIGITS];
1276	u64 z[ECC_MAX_DIGITS];
1277	u64 sk[2][ECC_MAX_DIGITS];
1278	u64 *curve_prime = curve->p;
1279	int i, nb;
1280	int num_bits;
1281	int carry;
1282
1283	carry = vli_add(sk[0], scalar, curve->n, ndigits);
1284	vli_add(sk[1], sk[0], curve->n, ndigits);
1285	scalar = sk[!carry];
1286	num_bits = sizeof(u64) * ndigits * 8 + 1;
1287
1288	vli_set(rx[1], point->x, ndigits);
1289	vli_set(ry[1], point->y, ndigits);
1290
1291	xycz_initial_double(rx[1], ry[1], rx[0], ry[0], initial_z, curve);
1292
1293	for (i = num_bits - 2; i > 0; i--) {
1294		nb = !vli_test_bit(scalar, i);
1295		xycz_add_c(rx[1 - nb], ry[1 - nb], rx[nb], ry[nb], curve);
1296		xycz_add(rx[nb], ry[nb], rx[1 - nb], ry[1 - nb], curve);
1297	}
1298
1299	nb = !vli_test_bit(scalar, 0);
1300	xycz_add_c(rx[1 - nb], ry[1 - nb], rx[nb], ry[nb], curve);
1301
1302	/* Find final 1/Z value. */
1303	/* X1 - X0 */
1304	vli_mod_sub(z, rx[1], rx[0], curve_prime, ndigits);
1305	/* Yb * (X1 - X0) */
1306	vli_mod_mult_fast(z, z, ry[1 - nb], curve);
1307	/* xP * Yb * (X1 - X0) */
1308	vli_mod_mult_fast(z, z, point->x, curve);
1309
1310	/* 1 / (xP * Yb * (X1 - X0)) */
1311	vli_mod_inv(z, z, curve_prime, point->ndigits);
1312
1313	/* yP / (xP * Yb * (X1 - X0)) */
1314	vli_mod_mult_fast(z, z, point->y, curve);
1315	/* Xb * yP / (xP * Yb * (X1 - X0)) */
1316	vli_mod_mult_fast(z, z, rx[1 - nb], curve);
1317	/* End 1/Z calculation */
1318
1319	xycz_add(rx[nb], ry[nb], rx[1 - nb], ry[1 - nb], curve);
1320
1321	apply_z(rx[0], ry[0], z, curve);
1322
1323	vli_set(result->x, rx[0], ndigits);
1324	vli_set(result->y, ry[0], ndigits);
1325}
1326
1327/* Computes R = P + Q mod p */
1328static void ecc_point_add(const struct ecc_point *result,
1329		   const struct ecc_point *p, const struct ecc_point *q,
1330		   const struct ecc_curve *curve)
1331{
1332	u64 z[ECC_MAX_DIGITS];
1333	u64 px[ECC_MAX_DIGITS];
1334	u64 py[ECC_MAX_DIGITS];
1335	unsigned int ndigits = curve->g.ndigits;
1336
1337	vli_set(result->x, q->x, ndigits);
1338	vli_set(result->y, q->y, ndigits);
1339	vli_mod_sub(z, result->x, p->x, curve->p, ndigits);
1340	vli_set(px, p->x, ndigits);
1341	vli_set(py, p->y, ndigits);
1342	xycz_add(px, py, result->x, result->y, curve);
1343	vli_mod_inv(z, z, curve->p, ndigits);
1344	apply_z(result->x, result->y, z, curve);
1345}
1346
1347/* Computes R = u1P + u2Q mod p using Shamir's trick.
1348 * Based on: Kenneth MacKay's micro-ecc (2014).
1349 */
1350void ecc_point_mult_shamir(const struct ecc_point *result,
1351			   const u64 *u1, const struct ecc_point *p,
1352			   const u64 *u2, const struct ecc_point *q,
1353			   const struct ecc_curve *curve)
1354{
1355	u64 z[ECC_MAX_DIGITS];
1356	u64 sump[2][ECC_MAX_DIGITS];
1357	u64 *rx = result->x;
1358	u64 *ry = result->y;
1359	unsigned int ndigits = curve->g.ndigits;
1360	unsigned int num_bits;
1361	struct ecc_point sum = ECC_POINT_INIT(sump[0], sump[1], ndigits);
1362	const struct ecc_point *points[4];
1363	const struct ecc_point *point;
1364	unsigned int idx;
1365	int i;
1366
1367	ecc_point_add(&sum, p, q, curve);
1368	points[0] = NULL;
1369	points[1] = p;
1370	points[2] = q;
1371	points[3] = &sum;
1372
1373	num_bits = max(vli_num_bits(u1, ndigits), vli_num_bits(u2, ndigits));
1374	i = num_bits - 1;
1375	idx = (!!vli_test_bit(u1, i)) | ((!!vli_test_bit(u2, i)) << 1);
1376	point = points[idx];
1377
1378	vli_set(rx, point->x, ndigits);
1379	vli_set(ry, point->y, ndigits);
1380	vli_clear(z + 1, ndigits - 1);
1381	z[0] = 1;
1382
1383	for (--i; i >= 0; i--) {
1384		ecc_point_double_jacobian(rx, ry, z, curve);
1385		idx = (!!vli_test_bit(u1, i)) | ((!!vli_test_bit(u2, i)) << 1);
1386		point = points[idx];
1387		if (point) {
1388			u64 tx[ECC_MAX_DIGITS];
1389			u64 ty[ECC_MAX_DIGITS];
1390			u64 tz[ECC_MAX_DIGITS];
1391
1392			vli_set(tx, point->x, ndigits);
1393			vli_set(ty, point->y, ndigits);
1394			apply_z(tx, ty, z, curve);
1395			vli_mod_sub(tz, rx, tx, curve->p, ndigits);
1396			xycz_add(tx, ty, rx, ry, curve);
1397			vli_mod_mult_fast(z, z, tz, curve);
1398		}
1399	}
1400	vli_mod_inv(z, z, curve->p, ndigits);
1401	apply_z(rx, ry, z, curve);
1402}
1403EXPORT_SYMBOL(ecc_point_mult_shamir);
1404
1405static int __ecc_is_key_valid(const struct ecc_curve *curve,
1406			      const u64 *private_key, unsigned int ndigits)
1407{
1408	u64 one[ECC_MAX_DIGITS] = { 1, };
1409	u64 res[ECC_MAX_DIGITS];
1410
1411	if (!private_key)
1412		return -EINVAL;
1413
1414	if (curve->g.ndigits != ndigits)
1415		return -EINVAL;
1416
1417	/* Make sure the private key is in the range [2, n-3]. */
1418	if (vli_cmp(one, private_key, ndigits) != -1)
1419		return -EINVAL;
1420	vli_sub(res, curve->n, one, ndigits);
1421	vli_sub(res, res, one, ndigits);
1422	if (vli_cmp(res, private_key, ndigits) != 1)
1423		return -EINVAL;
1424
1425	return 0;
1426}
1427
1428int ecc_is_key_valid(unsigned int curve_id, unsigned int ndigits,
1429		     const u64 *private_key, unsigned int private_key_len)
1430{
1431	int nbytes;
1432	const struct ecc_curve *curve = ecc_get_curve(curve_id);
1433
1434	nbytes = ndigits << ECC_DIGITS_TO_BYTES_SHIFT;
1435
1436	if (private_key_len != nbytes)
1437		return -EINVAL;
1438
1439	return __ecc_is_key_valid(curve, private_key, ndigits);
1440}
1441EXPORT_SYMBOL(ecc_is_key_valid);
1442
1443/*
1444 * ECC private keys are generated using the method of extra random bits,
1445 * equivalent to that described in FIPS 186-4, Appendix B.4.1.
1446 *
1447 * d = (c mod(n–1)) + 1    where c is a string of random bits, 64 bits longer
1448 *                         than requested
1449 * 0 <= c mod(n-1) <= n-2  and implies that
1450 * 1 <= d <= n-1
1451 *
1452 * This method generates a private key uniformly distributed in the range
1453 * [1, n-1].
1454 */
1455int ecc_gen_privkey(unsigned int curve_id, unsigned int ndigits, u64 *privkey)
1456{
1457	const struct ecc_curve *curve = ecc_get_curve(curve_id);
1458	u64 priv[ECC_MAX_DIGITS];
1459	unsigned int nbytes = ndigits << ECC_DIGITS_TO_BYTES_SHIFT;
1460	unsigned int nbits = vli_num_bits(curve->n, ndigits);
1461	int err;
1462
1463	/* Check that N is included in Table 1 of FIPS 186-4, section 6.1.1 */
1464	if (nbits < 160 || ndigits > ARRAY_SIZE(priv))
1465		return -EINVAL;
1466
1467	/*
1468	 * FIPS 186-4 recommends that the private key should be obtained from a
1469	 * RBG with a security strength equal to or greater than the security
1470	 * strength associated with N.
1471	 *
1472	 * The maximum security strength identified by NIST SP800-57pt1r4 for
1473	 * ECC is 256 (N >= 512).
1474	 *
1475	 * This condition is met by the default RNG because it selects a favored
1476	 * DRBG with a security strength of 256.
1477	 */
1478	if (crypto_get_default_rng())
1479		return -EFAULT;
1480
1481	err = crypto_rng_get_bytes(crypto_default_rng, (u8 *)priv, nbytes);
1482	crypto_put_default_rng();
1483	if (err)
1484		return err;
1485
1486	/* Make sure the private key is in the valid range. */
1487	if (__ecc_is_key_valid(curve, priv, ndigits))
1488		return -EINVAL;
1489
1490	ecc_swap_digits(priv, privkey, ndigits);
1491
1492	return 0;
1493}
1494EXPORT_SYMBOL(ecc_gen_privkey);
1495
1496int ecc_make_pub_key(unsigned int curve_id, unsigned int ndigits,
1497		     const u64 *private_key, u64 *public_key)
1498{
1499	int ret = 0;
1500	struct ecc_point *pk;
1501	u64 priv[ECC_MAX_DIGITS];
1502	const struct ecc_curve *curve = ecc_get_curve(curve_id);
1503
1504	if (!private_key || !curve || ndigits > ARRAY_SIZE(priv)) {
1505		ret = -EINVAL;
1506		goto out;
1507	}
1508
1509	ecc_swap_digits(private_key, priv, ndigits);
1510
1511	pk = ecc_alloc_point(ndigits);
1512	if (!pk) {
1513		ret = -ENOMEM;
1514		goto out;
1515	}
1516
1517	ecc_point_mult(pk, &curve->g, priv, NULL, curve, ndigits);
1518
1519	/* SP800-56A rev 3 5.6.2.1.3 key check */
1520	if (ecc_is_pubkey_valid_full(curve, pk)) {
1521		ret = -EAGAIN;
1522		goto err_free_point;
1523	}
1524
1525	ecc_swap_digits(pk->x, public_key, ndigits);
1526	ecc_swap_digits(pk->y, &public_key[ndigits], ndigits);
1527
1528err_free_point:
1529	ecc_free_point(pk);
1530out:
1531	return ret;
1532}
1533EXPORT_SYMBOL(ecc_make_pub_key);
1534
1535/* SP800-56A section 5.6.2.3.4 partial verification: ephemeral keys only */
1536int ecc_is_pubkey_valid_partial(const struct ecc_curve *curve,
1537				struct ecc_point *pk)
1538{
1539	u64 yy[ECC_MAX_DIGITS], xxx[ECC_MAX_DIGITS], w[ECC_MAX_DIGITS];
1540
1541	if (WARN_ON(pk->ndigits != curve->g.ndigits))
1542		return -EINVAL;
1543
1544	/* Check 1: Verify key is not the zero point. */
1545	if (ecc_point_is_zero(pk))
1546		return -EINVAL;
1547
1548	/* Check 2: Verify key is in the range [1, p-1]. */
1549	if (vli_cmp(curve->p, pk->x, pk->ndigits) != 1)
1550		return -EINVAL;
1551	if (vli_cmp(curve->p, pk->y, pk->ndigits) != 1)
1552		return -EINVAL;
1553
1554	/* Check 3: Verify that y^2 == (x^3 + a·x + b) mod p */
1555	vli_mod_square_fast(yy, pk->y, curve); /* y^2 */
1556	vli_mod_square_fast(xxx, pk->x, curve); /* x^2 */
1557	vli_mod_mult_fast(xxx, xxx, pk->x, curve); /* x^3 */
1558	vli_mod_mult_fast(w, curve->a, pk->x, curve); /* a·x */
1559	vli_mod_add(w, w, curve->b, curve->p, pk->ndigits); /* a·x + b */
1560	vli_mod_add(w, w, xxx, curve->p, pk->ndigits); /* x^3 + a·x + b */
1561	if (vli_cmp(yy, w, pk->ndigits) != 0) /* Equation */
1562		return -EINVAL;
1563
1564	return 0;
1565}
1566EXPORT_SYMBOL(ecc_is_pubkey_valid_partial);
1567
1568/* SP800-56A section 5.6.2.3.3 full verification */
1569int ecc_is_pubkey_valid_full(const struct ecc_curve *curve,
1570			     struct ecc_point *pk)
1571{
1572	struct ecc_point *nQ;
1573
1574	/* Checks 1 through 3 */
1575	int ret = ecc_is_pubkey_valid_partial(curve, pk);
1576
1577	if (ret)
1578		return ret;
1579
1580	/* Check 4: Verify that nQ is the zero point. */
1581	nQ = ecc_alloc_point(pk->ndigits);
1582	if (!nQ)
1583		return -ENOMEM;
1584
1585	ecc_point_mult(nQ, pk, curve->n, NULL, curve, pk->ndigits);
1586	if (!ecc_point_is_zero(nQ))
1587		ret = -EINVAL;
1588
1589	ecc_free_point(nQ);
1590
1591	return ret;
1592}
1593EXPORT_SYMBOL(ecc_is_pubkey_valid_full);
1594
1595int crypto_ecdh_shared_secret(unsigned int curve_id, unsigned int ndigits,
1596			      const u64 *private_key, const u64 *public_key,
1597			      u64 *secret)
1598{
1599	int ret = 0;
1600	struct ecc_point *product, *pk;
1601	u64 priv[ECC_MAX_DIGITS];
1602	u64 rand_z[ECC_MAX_DIGITS];
1603	unsigned int nbytes;
1604	const struct ecc_curve *curve = ecc_get_curve(curve_id);
1605
1606	if (!private_key || !public_key || !curve ||
1607	    ndigits > ARRAY_SIZE(priv) || ndigits > ARRAY_SIZE(rand_z)) {
1608		ret = -EINVAL;
1609		goto out;
1610	}
1611
1612	nbytes = ndigits << ECC_DIGITS_TO_BYTES_SHIFT;
1613
1614	get_random_bytes(rand_z, nbytes);
1615
1616	pk = ecc_alloc_point(ndigits);
1617	if (!pk) {
1618		ret = -ENOMEM;
1619		goto out;
1620	}
1621
1622	ecc_swap_digits(public_key, pk->x, ndigits);
1623	ecc_swap_digits(&public_key[ndigits], pk->y, ndigits);
1624	ret = ecc_is_pubkey_valid_partial(curve, pk);
1625	if (ret)
1626		goto err_alloc_product;
1627
1628	ecc_swap_digits(private_key, priv, ndigits);
1629
1630	product = ecc_alloc_point(ndigits);
1631	if (!product) {
1632		ret = -ENOMEM;
1633		goto err_alloc_product;
1634	}
1635
1636	ecc_point_mult(product, pk, priv, rand_z, curve, ndigits);
1637
1638	if (ecc_point_is_zero(product)) {
1639		ret = -EFAULT;
1640		goto err_validity;
1641	}
1642
1643	ecc_swap_digits(product->x, secret, ndigits);
1644
1645err_validity:
1646	memzero_explicit(priv, sizeof(priv));
1647	memzero_explicit(rand_z, sizeof(rand_z));
1648	ecc_free_point(product);
1649err_alloc_product:
1650	ecc_free_point(pk);
1651out:
1652	return ret;
1653}
1654EXPORT_SYMBOL(crypto_ecdh_shared_secret);
1655
1656MODULE_LICENSE("Dual BSD/GPL");
1657