Avoid an infinite loop in BN_GF2m_mod_inv
[openssl.git] / crypto / bn / bn_gf2m.c
1 /*
2  * Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 #include <assert.h>
12 #include <limits.h>
13 #include <stdio.h>
14 #include "internal/cryptlib.h"
15 #include "bn_local.h"
16
17 #ifndef OPENSSL_NO_EC2M
18
19 /*
20  * Maximum number of iterations before BN_GF2m_mod_solve_quad_arr should
21  * fail.
22  */
23 # define MAX_ITERATIONS 50
24
25 # define SQR_nibble(w)   ((((w) & 8) << 3) \
26                        |  (((w) & 4) << 2) \
27                        |  (((w) & 2) << 1) \
28                        |   ((w) & 1))
29
30
31 /* Platform-specific macros to accelerate squaring. */
32 # if defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG)
33 #  define SQR1(w) \
34     SQR_nibble((w) >> 60) << 56 | SQR_nibble((w) >> 56) << 48 | \
35     SQR_nibble((w) >> 52) << 40 | SQR_nibble((w) >> 48) << 32 | \
36     SQR_nibble((w) >> 44) << 24 | SQR_nibble((w) >> 40) << 16 | \
37     SQR_nibble((w) >> 36) <<  8 | SQR_nibble((w) >> 32)
38 #  define SQR0(w) \
39     SQR_nibble((w) >> 28) << 56 | SQR_nibble((w) >> 24) << 48 | \
40     SQR_nibble((w) >> 20) << 40 | SQR_nibble((w) >> 16) << 32 | \
41     SQR_nibble((w) >> 12) << 24 | SQR_nibble((w) >>  8) << 16 | \
42     SQR_nibble((w) >>  4) <<  8 | SQR_nibble((w)      )
43 # endif
44 # ifdef THIRTY_TWO_BIT
45 #  define SQR1(w) \
46     SQR_nibble((w) >> 28) << 24 | SQR_nibble((w) >> 24) << 16 | \
47     SQR_nibble((w) >> 20) <<  8 | SQR_nibble((w) >> 16)
48 #  define SQR0(w) \
49     SQR_nibble((w) >> 12) << 24 | SQR_nibble((w) >>  8) << 16 | \
50     SQR_nibble((w) >>  4) <<  8 | SQR_nibble((w)      )
51 # endif
52
53 # if !defined(OPENSSL_BN_ASM_GF2m)
54 /*
55  * Product of two polynomials a, b each with degree < BN_BITS2 - 1, result is
56  * a polynomial r with degree < 2 * BN_BITS - 1 The caller MUST ensure that
57  * the variables have the right amount of space allocated.
58  */
59 #  ifdef THIRTY_TWO_BIT
60 static void bn_GF2m_mul_1x1(BN_ULONG *r1, BN_ULONG *r0, const BN_ULONG a,
61                             const BN_ULONG b)
62 {
63     register BN_ULONG h, l, s;
64     BN_ULONG tab[8], top2b = a >> 30;
65     register BN_ULONG a1, a2, a4;
66
67     a1 = a & (0x3FFFFFFF);
68     a2 = a1 << 1;
69     a4 = a2 << 1;
70
71     tab[0] = 0;
72     tab[1] = a1;
73     tab[2] = a2;
74     tab[3] = a1 ^ a2;
75     tab[4] = a4;
76     tab[5] = a1 ^ a4;
77     tab[6] = a2 ^ a4;
78     tab[7] = a1 ^ a2 ^ a4;
79
80     s = tab[b & 0x7];
81     l = s;
82     s = tab[b >> 3 & 0x7];
83     l ^= s << 3;
84     h = s >> 29;
85     s = tab[b >> 6 & 0x7];
86     l ^= s << 6;
87     h ^= s >> 26;
88     s = tab[b >> 9 & 0x7];
89     l ^= s << 9;
90     h ^= s >> 23;
91     s = tab[b >> 12 & 0x7];
92     l ^= s << 12;
93     h ^= s >> 20;
94     s = tab[b >> 15 & 0x7];
95     l ^= s << 15;
96     h ^= s >> 17;
97     s = tab[b >> 18 & 0x7];
98     l ^= s << 18;
99     h ^= s >> 14;
100     s = tab[b >> 21 & 0x7];
101     l ^= s << 21;
102     h ^= s >> 11;
103     s = tab[b >> 24 & 0x7];
104     l ^= s << 24;
105     h ^= s >> 8;
106     s = tab[b >> 27 & 0x7];
107     l ^= s << 27;
108     h ^= s >> 5;
109     s = tab[b >> 30];
110     l ^= s << 30;
111     h ^= s >> 2;
112
113     /* compensate for the top two bits of a */
114
115     if (top2b & 01) {
116         l ^= b << 30;
117         h ^= b >> 2;
118     }
119     if (top2b & 02) {
120         l ^= b << 31;
121         h ^= b >> 1;
122     }
123
124     *r1 = h;
125     *r0 = l;
126 }
127 #  endif
128 #  if defined(SIXTY_FOUR_BIT) || defined(SIXTY_FOUR_BIT_LONG)
129 static void bn_GF2m_mul_1x1(BN_ULONG *r1, BN_ULONG *r0, const BN_ULONG a,
130                             const BN_ULONG b)
131 {
132     register BN_ULONG h, l, s;
133     BN_ULONG tab[16], top3b = a >> 61;
134     register BN_ULONG a1, a2, a4, a8;
135
136     a1 = a & (0x1FFFFFFFFFFFFFFFULL);
137     a2 = a1 << 1;
138     a4 = a2 << 1;
139     a8 = a4 << 1;
140
141     tab[0] = 0;
142     tab[1] = a1;
143     tab[2] = a2;
144     tab[3] = a1 ^ a2;
145     tab[4] = a4;
146     tab[5] = a1 ^ a4;
147     tab[6] = a2 ^ a4;
148     tab[7] = a1 ^ a2 ^ a4;
149     tab[8] = a8;
150     tab[9] = a1 ^ a8;
151     tab[10] = a2 ^ a8;
152     tab[11] = a1 ^ a2 ^ a8;
153     tab[12] = a4 ^ a8;
154     tab[13] = a1 ^ a4 ^ a8;
155     tab[14] = a2 ^ a4 ^ a8;
156     tab[15] = a1 ^ a2 ^ a4 ^ a8;
157
158     s = tab[b & 0xF];
159     l = s;
160     s = tab[b >> 4 & 0xF];
161     l ^= s << 4;
162     h = s >> 60;
163     s = tab[b >> 8 & 0xF];
164     l ^= s << 8;
165     h ^= s >> 56;
166     s = tab[b >> 12 & 0xF];
167     l ^= s << 12;
168     h ^= s >> 52;
169     s = tab[b >> 16 & 0xF];
170     l ^= s << 16;
171     h ^= s >> 48;
172     s = tab[b >> 20 & 0xF];
173     l ^= s << 20;
174     h ^= s >> 44;
175     s = tab[b >> 24 & 0xF];
176     l ^= s << 24;
177     h ^= s >> 40;
178     s = tab[b >> 28 & 0xF];
179     l ^= s << 28;
180     h ^= s >> 36;
181     s = tab[b >> 32 & 0xF];
182     l ^= s << 32;
183     h ^= s >> 32;
184     s = tab[b >> 36 & 0xF];
185     l ^= s << 36;
186     h ^= s >> 28;
187     s = tab[b >> 40 & 0xF];
188     l ^= s << 40;
189     h ^= s >> 24;
190     s = tab[b >> 44 & 0xF];
191     l ^= s << 44;
192     h ^= s >> 20;
193     s = tab[b >> 48 & 0xF];
194     l ^= s << 48;
195     h ^= s >> 16;
196     s = tab[b >> 52 & 0xF];
197     l ^= s << 52;
198     h ^= s >> 12;
199     s = tab[b >> 56 & 0xF];
200     l ^= s << 56;
201     h ^= s >> 8;
202     s = tab[b >> 60];
203     l ^= s << 60;
204     h ^= s >> 4;
205
206     /* compensate for the top three bits of a */
207
208     if (top3b & 01) {
209         l ^= b << 61;
210         h ^= b >> 3;
211     }
212     if (top3b & 02) {
213         l ^= b << 62;
214         h ^= b >> 2;
215     }
216     if (top3b & 04) {
217         l ^= b << 63;
218         h ^= b >> 1;
219     }
220
221     *r1 = h;
222     *r0 = l;
223 }
224 #  endif
225
226 /*
227  * Product of two polynomials a, b each with degree < 2 * BN_BITS2 - 1,
228  * result is a polynomial r with degree < 4 * BN_BITS2 - 1 The caller MUST
229  * ensure that the variables have the right amount of space allocated.
230  */
231 static void bn_GF2m_mul_2x2(BN_ULONG *r, const BN_ULONG a1, const BN_ULONG a0,
232                             const BN_ULONG b1, const BN_ULONG b0)
233 {
234     BN_ULONG m1, m0;
235     /* r[3] = h1, r[2] = h0; r[1] = l1; r[0] = l0 */
236     bn_GF2m_mul_1x1(r + 3, r + 2, a1, b1);
237     bn_GF2m_mul_1x1(r + 1, r, a0, b0);
238     bn_GF2m_mul_1x1(&m1, &m0, a0 ^ a1, b0 ^ b1);
239     /* Correction on m1 ^= l1 ^ h1; m0 ^= l0 ^ h0; */
240     r[2] ^= m1 ^ r[1] ^ r[3];   /* h0 ^= m1 ^ l1 ^ h1; */
241     r[1] = r[3] ^ r[2] ^ r[0] ^ m1 ^ m0; /* l1 ^= l0 ^ h0 ^ m0; */
242 }
243 # else
244 void bn_GF2m_mul_2x2(BN_ULONG *r, BN_ULONG a1, BN_ULONG a0, BN_ULONG b1,
245                      BN_ULONG b0);
246 # endif
247
248 /*
249  * Add polynomials a and b and store result in r; r could be a or b, a and b
250  * could be equal; r is the bitwise XOR of a and b.
251  */
252 int BN_GF2m_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b)
253 {
254     int i;
255     const BIGNUM *at, *bt;
256
257     bn_check_top(a);
258     bn_check_top(b);
259
260     if (a->top < b->top) {
261         at = b;
262         bt = a;
263     } else {
264         at = a;
265         bt = b;
266     }
267
268     if (bn_wexpand(r, at->top) == NULL)
269         return 0;
270
271     for (i = 0; i < bt->top; i++) {
272         r->d[i] = at->d[i] ^ bt->d[i];
273     }
274     for (; i < at->top; i++) {
275         r->d[i] = at->d[i];
276     }
277
278     r->top = at->top;
279     bn_correct_top(r);
280
281     return 1;
282 }
283
284 /*-
285  * Some functions allow for representation of the irreducible polynomials
286  * as an int[], say p.  The irreducible f(t) is then of the form:
287  *     t^p[0] + t^p[1] + ... + t^p[k]
288  * where m = p[0] > p[1] > ... > p[k] = 0.
289  */
290
291 /* Performs modular reduction of a and store result in r.  r could be a. */
292 int BN_GF2m_mod_arr(BIGNUM *r, const BIGNUM *a, const int p[])
293 {
294     int j, k;
295     int n, dN, d0, d1;
296     BN_ULONG zz, *z;
297
298     bn_check_top(a);
299
300     if (p[0] == 0) {
301         /* reduction mod 1 => return 0 */
302         BN_zero(r);
303         return 1;
304     }
305
306     /*
307      * Since the algorithm does reduction in the r value, if a != r, copy the
308      * contents of a into r so we can do reduction in r.
309      */
310     if (a != r) {
311         if (!bn_wexpand(r, a->top))
312             return 0;
313         for (j = 0; j < a->top; j++) {
314             r->d[j] = a->d[j];
315         }
316         r->top = a->top;
317     }
318     z = r->d;
319
320     /* start reduction */
321     dN = p[0] / BN_BITS2;
322     for (j = r->top - 1; j > dN;) {
323         zz = z[j];
324         if (z[j] == 0) {
325             j--;
326             continue;
327         }
328         z[j] = 0;
329
330         for (k = 1; p[k] != 0; k++) {
331             /* reducing component t^p[k] */
332             n = p[0] - p[k];
333             d0 = n % BN_BITS2;
334             d1 = BN_BITS2 - d0;
335             n /= BN_BITS2;
336             z[j - n] ^= (zz >> d0);
337             if (d0)
338                 z[j - n - 1] ^= (zz << d1);
339         }
340
341         /* reducing component t^0 */
342         n = dN;
343         d0 = p[0] % BN_BITS2;
344         d1 = BN_BITS2 - d0;
345         z[j - n] ^= (zz >> d0);
346         if (d0)
347             z[j - n - 1] ^= (zz << d1);
348     }
349
350     /* final round of reduction */
351     while (j == dN) {
352
353         d0 = p[0] % BN_BITS2;
354         zz = z[dN] >> d0;
355         if (zz == 0)
356             break;
357         d1 = BN_BITS2 - d0;
358
359         /* clear up the top d1 bits */
360         if (d0)
361             z[dN] = (z[dN] << d1) >> d1;
362         else
363             z[dN] = 0;
364         z[0] ^= zz;             /* reduction t^0 component */
365
366         for (k = 1; p[k] != 0; k++) {
367             BN_ULONG tmp_ulong;
368
369             /* reducing component t^p[k] */
370             n = p[k] / BN_BITS2;
371             d0 = p[k] % BN_BITS2;
372             d1 = BN_BITS2 - d0;
373             z[n] ^= (zz << d0);
374             if (d0 && (tmp_ulong = zz >> d1))
375                 z[n + 1] ^= tmp_ulong;
376         }
377
378     }
379
380     bn_correct_top(r);
381     return 1;
382 }
383
384 /*
385  * Performs modular reduction of a by p and store result in r.  r could be a.
386  * This function calls down to the BN_GF2m_mod_arr implementation; this wrapper
387  * function is only provided for convenience; for best performance, use the
388  * BN_GF2m_mod_arr function.
389  */
390 int BN_GF2m_mod(BIGNUM *r, const BIGNUM *a, const BIGNUM *p)
391 {
392     int ret = 0;
393     int arr[6];
394     bn_check_top(a);
395     bn_check_top(p);
396     ret = BN_GF2m_poly2arr(p, arr, OSSL_NELEM(arr));
397     if (!ret || ret > (int)OSSL_NELEM(arr)) {
398         ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH);
399         return 0;
400     }
401     ret = BN_GF2m_mod_arr(r, a, arr);
402     bn_check_top(r);
403     return ret;
404 }
405
406 /*
407  * Compute the product of two polynomials a and b, reduce modulo p, and store
408  * the result in r.  r could be a or b; a could be b.
409  */
410 int BN_GF2m_mod_mul_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
411                         const int p[], BN_CTX *ctx)
412 {
413     int zlen, i, j, k, ret = 0;
414     BIGNUM *s;
415     BN_ULONG x1, x0, y1, y0, zz[4];
416
417     bn_check_top(a);
418     bn_check_top(b);
419
420     if (a == b) {
421         return BN_GF2m_mod_sqr_arr(r, a, p, ctx);
422     }
423
424     BN_CTX_start(ctx);
425     if ((s = BN_CTX_get(ctx)) == NULL)
426         goto err;
427
428     zlen = a->top + b->top + 4;
429     if (!bn_wexpand(s, zlen))
430         goto err;
431     s->top = zlen;
432
433     for (i = 0; i < zlen; i++)
434         s->d[i] = 0;
435
436     for (j = 0; j < b->top; j += 2) {
437         y0 = b->d[j];
438         y1 = ((j + 1) == b->top) ? 0 : b->d[j + 1];
439         for (i = 0; i < a->top; i += 2) {
440             x0 = a->d[i];
441             x1 = ((i + 1) == a->top) ? 0 : a->d[i + 1];
442             bn_GF2m_mul_2x2(zz, x1, x0, y1, y0);
443             for (k = 0; k < 4; k++)
444                 s->d[i + j + k] ^= zz[k];
445         }
446     }
447
448     bn_correct_top(s);
449     if (BN_GF2m_mod_arr(r, s, p))
450         ret = 1;
451     bn_check_top(r);
452
453  err:
454     BN_CTX_end(ctx);
455     return ret;
456 }
457
458 /*
459  * Compute the product of two polynomials a and b, reduce modulo p, and store
460  * the result in r.  r could be a or b; a could equal b. This function calls
461  * down to the BN_GF2m_mod_mul_arr implementation; this wrapper function is
462  * only provided for convenience; for best performance, use the
463  * BN_GF2m_mod_mul_arr function.
464  */
465 int BN_GF2m_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
466                     const BIGNUM *p, BN_CTX *ctx)
467 {
468     int ret = 0;
469     const int max = BN_num_bits(p) + 1;
470     int *arr;
471
472     bn_check_top(a);
473     bn_check_top(b);
474     bn_check_top(p);
475
476     arr = OPENSSL_malloc(sizeof(*arr) * max);
477     if (arr == NULL)
478         return 0;
479     ret = BN_GF2m_poly2arr(p, arr, max);
480     if (!ret || ret > max) {
481         ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH);
482         goto err;
483     }
484     ret = BN_GF2m_mod_mul_arr(r, a, b, arr, ctx);
485     bn_check_top(r);
486  err:
487     OPENSSL_free(arr);
488     return ret;
489 }
490
491 /* Square a, reduce the result mod p, and store it in a.  r could be a. */
492 int BN_GF2m_mod_sqr_arr(BIGNUM *r, const BIGNUM *a, const int p[],
493                         BN_CTX *ctx)
494 {
495     int i, ret = 0;
496     BIGNUM *s;
497
498     bn_check_top(a);
499     BN_CTX_start(ctx);
500     if ((s = BN_CTX_get(ctx)) == NULL)
501         goto err;
502     if (!bn_wexpand(s, 2 * a->top))
503         goto err;
504
505     for (i = a->top - 1; i >= 0; i--) {
506         s->d[2 * i + 1] = SQR1(a->d[i]);
507         s->d[2 * i] = SQR0(a->d[i]);
508     }
509
510     s->top = 2 * a->top;
511     bn_correct_top(s);
512     if (!BN_GF2m_mod_arr(r, s, p))
513         goto err;
514     bn_check_top(r);
515     ret = 1;
516  err:
517     BN_CTX_end(ctx);
518     return ret;
519 }
520
521 /*
522  * Square a, reduce the result mod p, and store it in a.  r could be a. This
523  * function calls down to the BN_GF2m_mod_sqr_arr implementation; this
524  * wrapper function is only provided for convenience; for best performance,
525  * use the BN_GF2m_mod_sqr_arr function.
526  */
527 int BN_GF2m_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
528 {
529     int ret = 0;
530     const int max = BN_num_bits(p) + 1;
531     int *arr;
532
533     bn_check_top(a);
534     bn_check_top(p);
535
536     arr = OPENSSL_malloc(sizeof(*arr) * max);
537     if (arr == NULL)
538         return 0;
539     ret = BN_GF2m_poly2arr(p, arr, max);
540     if (!ret || ret > max) {
541         ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH);
542         goto err;
543     }
544     ret = BN_GF2m_mod_sqr_arr(r, a, arr, ctx);
545     bn_check_top(r);
546  err:
547     OPENSSL_free(arr);
548     return ret;
549 }
550
551 /*
552  * Invert a, reduce modulo p, and store the result in r. r could be a. Uses
553  * Modified Almost Inverse Algorithm (Algorithm 10) from Hankerson, D.,
554  * Hernandez, J.L., and Menezes, A.  "Software Implementation of Elliptic
555  * Curve Cryptography Over Binary Fields".
556  */
557 static int BN_GF2m_mod_inv_vartime(BIGNUM *r, const BIGNUM *a,
558                                    const BIGNUM *p, BN_CTX *ctx)
559 {
560     BIGNUM *b, *c = NULL, *u = NULL, *v = NULL, *tmp;
561     int ret = 0;
562
563     bn_check_top(a);
564     bn_check_top(p);
565
566     BN_CTX_start(ctx);
567
568     b = BN_CTX_get(ctx);
569     c = BN_CTX_get(ctx);
570     u = BN_CTX_get(ctx);
571     v = BN_CTX_get(ctx);
572     if (v == NULL)
573         goto err;
574
575     if (!BN_GF2m_mod(u, a, p))
576         goto err;
577     if (BN_is_zero(u))
578         goto err;
579
580     if (!BN_copy(v, p))
581         goto err;
582 # if 0
583     if (!BN_one(b))
584         goto err;
585
586     while (1) {
587         while (!BN_is_odd(u)) {
588             if (BN_is_zero(u))
589                 goto err;
590             if (!BN_rshift1(u, u))
591                 goto err;
592             if (BN_is_odd(b)) {
593                 if (!BN_GF2m_add(b, b, p))
594                     goto err;
595             }
596             if (!BN_rshift1(b, b))
597                 goto err;
598         }
599
600         if (BN_abs_is_word(u, 1))
601             break;
602
603         if (BN_num_bits(u) < BN_num_bits(v)) {
604             tmp = u;
605             u = v;
606             v = tmp;
607             tmp = b;
608             b = c;
609             c = tmp;
610         }
611
612         if (!BN_GF2m_add(u, u, v))
613             goto err;
614         if (!BN_GF2m_add(b, b, c))
615             goto err;
616     }
617 # else
618     {
619         int i;
620         int ubits = BN_num_bits(u);
621         int vbits = BN_num_bits(v); /* v is copy of p */
622         int top = p->top;
623         BN_ULONG *udp, *bdp, *vdp, *cdp;
624
625         if (!bn_wexpand(u, top))
626             goto err;
627         udp = u->d;
628         for (i = u->top; i < top; i++)
629             udp[i] = 0;
630         u->top = top;
631         if (!bn_wexpand(b, top))
632           goto err;
633         bdp = b->d;
634         bdp[0] = 1;
635         for (i = 1; i < top; i++)
636             bdp[i] = 0;
637         b->top = top;
638         if (!bn_wexpand(c, top))
639           goto err;
640         cdp = c->d;
641         for (i = 0; i < top; i++)
642             cdp[i] = 0;
643         c->top = top;
644         vdp = v->d;             /* It pays off to "cache" *->d pointers,
645                                  * because it allows optimizer to be more
646                                  * aggressive. But we don't have to "cache"
647                                  * p->d, because *p is declared 'const'... */
648         while (1) {
649             while (ubits && !(udp[0] & 1)) {
650                 BN_ULONG u0, u1, b0, b1, mask;
651
652                 u0 = udp[0];
653                 b0 = bdp[0];
654                 mask = (BN_ULONG)0 - (b0 & 1);
655                 b0 ^= p->d[0] & mask;
656                 for (i = 0; i < top - 1; i++) {
657                     u1 = udp[i + 1];
658                     udp[i] = ((u0 >> 1) | (u1 << (BN_BITS2 - 1))) & BN_MASK2;
659                     u0 = u1;
660                     b1 = bdp[i + 1] ^ (p->d[i + 1] & mask);
661                     bdp[i] = ((b0 >> 1) | (b1 << (BN_BITS2 - 1))) & BN_MASK2;
662                     b0 = b1;
663                 }
664                 udp[i] = u0 >> 1;
665                 bdp[i] = b0 >> 1;
666                 ubits--;
667             }
668
669             if (ubits <= BN_BITS2) {
670                 if (udp[0] == 0) /* poly was reducible */
671                     goto err;
672                 if (udp[0] == 1)
673                     break;
674             }
675
676             if (ubits < vbits) {
677                 i = ubits;
678                 ubits = vbits;
679                 vbits = i;
680                 tmp = u;
681                 u = v;
682                 v = tmp;
683                 tmp = b;
684                 b = c;
685                 c = tmp;
686                 udp = vdp;
687                 vdp = v->d;
688                 bdp = cdp;
689                 cdp = c->d;
690             }
691             for (i = 0; i < top; i++) {
692                 udp[i] ^= vdp[i];
693                 bdp[i] ^= cdp[i];
694             }
695             if (ubits == vbits) {
696                 BN_ULONG ul;
697                 int utop = (ubits - 1) / BN_BITS2;
698
699                 while ((ul = udp[utop]) == 0 && utop)
700                     utop--;
701                 ubits = utop * BN_BITS2 + BN_num_bits_word(ul);
702             }
703         }
704         bn_correct_top(b);
705     }
706 # endif
707
708     if (!BN_copy(r, b))
709         goto err;
710     bn_check_top(r);
711     ret = 1;
712
713  err:
714 # ifdef BN_DEBUG
715     /* BN_CTX_end would complain about the expanded form */
716     bn_correct_top(c);
717     bn_correct_top(u);
718     bn_correct_top(v);
719 # endif
720     BN_CTX_end(ctx);
721     return ret;
722 }
723
724 /*-
725  * Wrapper for BN_GF2m_mod_inv_vartime that blinds the input before calling.
726  * This is not constant time.
727  * But it does eliminate first order deduction on the input.
728  */
729 int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
730 {
731     BIGNUM *b = NULL;
732     int ret = 0;
733     int numbits;
734
735     BN_CTX_start(ctx);
736     if ((b = BN_CTX_get(ctx)) == NULL)
737         goto err;
738
739     /* Fail on a non-sensical input p value */
740     numbits = BN_num_bits(p);
741     if (numbits <= 1)
742         goto err;
743
744     /* generate blinding value */
745     do {
746         if (!BN_priv_rand_ex(b, numbits - 1,
747                              BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY, 0, ctx))
748             goto err;
749     } while (BN_is_zero(b));
750
751     /* r := a * b */
752     if (!BN_GF2m_mod_mul(r, a, b, p, ctx))
753         goto err;
754
755     /* r := 1/(a * b) */
756     if (!BN_GF2m_mod_inv_vartime(r, r, p, ctx))
757         goto err;
758
759     /* r := b/(a * b) = 1/a */
760     if (!BN_GF2m_mod_mul(r, r, b, p, ctx))
761         goto err;
762
763     ret = 1;
764
765  err:
766     BN_CTX_end(ctx);
767     return ret;
768 }
769
770 /*
771  * Invert xx, reduce modulo p, and store the result in r. r could be xx.
772  * This function calls down to the BN_GF2m_mod_inv implementation; this
773  * wrapper function is only provided for convenience; for best performance,
774  * use the BN_GF2m_mod_inv function.
775  */
776 int BN_GF2m_mod_inv_arr(BIGNUM *r, const BIGNUM *xx, const int p[],
777                         BN_CTX *ctx)
778 {
779     BIGNUM *field;
780     int ret = 0;
781
782     bn_check_top(xx);
783     BN_CTX_start(ctx);
784     if ((field = BN_CTX_get(ctx)) == NULL)
785         goto err;
786     if (!BN_GF2m_arr2poly(p, field))
787         goto err;
788
789     ret = BN_GF2m_mod_inv(r, xx, field, ctx);
790     bn_check_top(r);
791
792  err:
793     BN_CTX_end(ctx);
794     return ret;
795 }
796
797 /*
798  * Divide y by x, reduce modulo p, and store the result in r. r could be x
799  * or y, x could equal y.
800  */
801 int BN_GF2m_mod_div(BIGNUM *r, const BIGNUM *y, const BIGNUM *x,
802                     const BIGNUM *p, BN_CTX *ctx)
803 {
804     BIGNUM *xinv = NULL;
805     int ret = 0;
806
807     bn_check_top(y);
808     bn_check_top(x);
809     bn_check_top(p);
810
811     BN_CTX_start(ctx);
812     xinv = BN_CTX_get(ctx);
813     if (xinv == NULL)
814         goto err;
815
816     if (!BN_GF2m_mod_inv(xinv, x, p, ctx))
817         goto err;
818     if (!BN_GF2m_mod_mul(r, y, xinv, p, ctx))
819         goto err;
820     bn_check_top(r);
821     ret = 1;
822
823  err:
824     BN_CTX_end(ctx);
825     return ret;
826 }
827
828 /*
829  * Divide yy by xx, reduce modulo p, and store the result in r. r could be xx
830  * * or yy, xx could equal yy. This function calls down to the
831  * BN_GF2m_mod_div implementation; this wrapper function is only provided for
832  * convenience; for best performance, use the BN_GF2m_mod_div function.
833  */
834 int BN_GF2m_mod_div_arr(BIGNUM *r, const BIGNUM *yy, const BIGNUM *xx,
835                         const int p[], BN_CTX *ctx)
836 {
837     BIGNUM *field;
838     int ret = 0;
839
840     bn_check_top(yy);
841     bn_check_top(xx);
842
843     BN_CTX_start(ctx);
844     if ((field = BN_CTX_get(ctx)) == NULL)
845         goto err;
846     if (!BN_GF2m_arr2poly(p, field))
847         goto err;
848
849     ret = BN_GF2m_mod_div(r, yy, xx, field, ctx);
850     bn_check_top(r);
851
852  err:
853     BN_CTX_end(ctx);
854     return ret;
855 }
856
857 /*
858  * Compute the bth power of a, reduce modulo p, and store the result in r.  r
859  * could be a. Uses simple square-and-multiply algorithm A.5.1 from IEEE
860  * P1363.
861  */
862 int BN_GF2m_mod_exp_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
863                         const int p[], BN_CTX *ctx)
864 {
865     int ret = 0, i, n;
866     BIGNUM *u;
867
868     bn_check_top(a);
869     bn_check_top(b);
870
871     if (BN_is_zero(b))
872         return BN_one(r);
873
874     if (BN_abs_is_word(b, 1))
875         return (BN_copy(r, a) != NULL);
876
877     BN_CTX_start(ctx);
878     if ((u = BN_CTX_get(ctx)) == NULL)
879         goto err;
880
881     if (!BN_GF2m_mod_arr(u, a, p))
882         goto err;
883
884     n = BN_num_bits(b) - 1;
885     for (i = n - 1; i >= 0; i--) {
886         if (!BN_GF2m_mod_sqr_arr(u, u, p, ctx))
887             goto err;
888         if (BN_is_bit_set(b, i)) {
889             if (!BN_GF2m_mod_mul_arr(u, u, a, p, ctx))
890                 goto err;
891         }
892     }
893     if (!BN_copy(r, u))
894         goto err;
895     bn_check_top(r);
896     ret = 1;
897  err:
898     BN_CTX_end(ctx);
899     return ret;
900 }
901
902 /*
903  * Compute the bth power of a, reduce modulo p, and store the result in r.  r
904  * could be a. This function calls down to the BN_GF2m_mod_exp_arr
905  * implementation; this wrapper function is only provided for convenience;
906  * for best performance, use the BN_GF2m_mod_exp_arr function.
907  */
908 int BN_GF2m_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
909                     const BIGNUM *p, BN_CTX *ctx)
910 {
911     int ret = 0;
912     const int max = BN_num_bits(p) + 1;
913     int *arr;
914
915     bn_check_top(a);
916     bn_check_top(b);
917     bn_check_top(p);
918
919     arr = OPENSSL_malloc(sizeof(*arr) * max);
920     if (arr == NULL)
921         return 0;
922     ret = BN_GF2m_poly2arr(p, arr, max);
923     if (!ret || ret > max) {
924         ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH);
925         goto err;
926     }
927     ret = BN_GF2m_mod_exp_arr(r, a, b, arr, ctx);
928     bn_check_top(r);
929  err:
930     OPENSSL_free(arr);
931     return ret;
932 }
933
934 /*
935  * Compute the square root of a, reduce modulo p, and store the result in r.
936  * r could be a. Uses exponentiation as in algorithm A.4.1 from IEEE P1363.
937  */
938 int BN_GF2m_mod_sqrt_arr(BIGNUM *r, const BIGNUM *a, const int p[],
939                          BN_CTX *ctx)
940 {
941     int ret = 0;
942     BIGNUM *u;
943
944     bn_check_top(a);
945
946     if (p[0] == 0) {
947         /* reduction mod 1 => return 0 */
948         BN_zero(r);
949         return 1;
950     }
951
952     BN_CTX_start(ctx);
953     if ((u = BN_CTX_get(ctx)) == NULL)
954         goto err;
955
956     if (!BN_set_bit(u, p[0] - 1))
957         goto err;
958     ret = BN_GF2m_mod_exp_arr(r, a, u, p, ctx);
959     bn_check_top(r);
960
961  err:
962     BN_CTX_end(ctx);
963     return ret;
964 }
965
966 /*
967  * Compute the square root of a, reduce modulo p, and store the result in r.
968  * r could be a. This function calls down to the BN_GF2m_mod_sqrt_arr
969  * implementation; this wrapper function is only provided for convenience;
970  * for best performance, use the BN_GF2m_mod_sqrt_arr function.
971  */
972 int BN_GF2m_mod_sqrt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
973 {
974     int ret = 0;
975     const int max = BN_num_bits(p) + 1;
976     int *arr;
977
978     bn_check_top(a);
979     bn_check_top(p);
980
981     arr = OPENSSL_malloc(sizeof(*arr) * max);
982     if (arr == NULL)
983         return 0;
984     ret = BN_GF2m_poly2arr(p, arr, max);
985     if (!ret || ret > max) {
986         ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH);
987         goto err;
988     }
989     ret = BN_GF2m_mod_sqrt_arr(r, a, arr, ctx);
990     bn_check_top(r);
991  err:
992     OPENSSL_free(arr);
993     return ret;
994 }
995
996 /*
997  * Find r such that r^2 + r = a mod p.  r could be a. If no r exists returns
998  * 0. Uses algorithms A.4.7 and A.4.6 from IEEE P1363.
999  */
1000 int BN_GF2m_mod_solve_quad_arr(BIGNUM *r, const BIGNUM *a_, const int p[],
1001                                BN_CTX *ctx)
1002 {
1003     int ret = 0, count = 0, j;
1004     BIGNUM *a, *z, *rho, *w, *w2, *tmp;
1005
1006     bn_check_top(a_);
1007
1008     if (p[0] == 0) {
1009         /* reduction mod 1 => return 0 */
1010         BN_zero(r);
1011         return 1;
1012     }
1013
1014     BN_CTX_start(ctx);
1015     a = BN_CTX_get(ctx);
1016     z = BN_CTX_get(ctx);
1017     w = BN_CTX_get(ctx);
1018     if (w == NULL)
1019         goto err;
1020
1021     if (!BN_GF2m_mod_arr(a, a_, p))
1022         goto err;
1023
1024     if (BN_is_zero(a)) {
1025         BN_zero(r);
1026         ret = 1;
1027         goto err;
1028     }
1029
1030     if (p[0] & 0x1) {           /* m is odd */
1031         /* compute half-trace of a */
1032         if (!BN_copy(z, a))
1033             goto err;
1034         for (j = 1; j <= (p[0] - 1) / 2; j++) {
1035             if (!BN_GF2m_mod_sqr_arr(z, z, p, ctx))
1036                 goto err;
1037             if (!BN_GF2m_mod_sqr_arr(z, z, p, ctx))
1038                 goto err;
1039             if (!BN_GF2m_add(z, z, a))
1040                 goto err;
1041         }
1042
1043     } else {                    /* m is even */
1044
1045         rho = BN_CTX_get(ctx);
1046         w2 = BN_CTX_get(ctx);
1047         tmp = BN_CTX_get(ctx);
1048         if (tmp == NULL)
1049             goto err;
1050         do {
1051             if (!BN_priv_rand_ex(rho, p[0], BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY,
1052                                  0, ctx))
1053                 goto err;
1054             if (!BN_GF2m_mod_arr(rho, rho, p))
1055                 goto err;
1056             BN_zero(z);
1057             if (!BN_copy(w, rho))
1058                 goto err;
1059             for (j = 1; j <= p[0] - 1; j++) {
1060                 if (!BN_GF2m_mod_sqr_arr(z, z, p, ctx))
1061                     goto err;
1062                 if (!BN_GF2m_mod_sqr_arr(w2, w, p, ctx))
1063                     goto err;
1064                 if (!BN_GF2m_mod_mul_arr(tmp, w2, a, p, ctx))
1065                     goto err;
1066                 if (!BN_GF2m_add(z, z, tmp))
1067                     goto err;
1068                 if (!BN_GF2m_add(w, w2, rho))
1069                     goto err;
1070             }
1071             count++;
1072         } while (BN_is_zero(w) && (count < MAX_ITERATIONS));
1073         if (BN_is_zero(w)) {
1074             ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS);
1075             goto err;
1076         }
1077     }
1078
1079     if (!BN_GF2m_mod_sqr_arr(w, z, p, ctx))
1080         goto err;
1081     if (!BN_GF2m_add(w, z, w))
1082         goto err;
1083     if (BN_GF2m_cmp(w, a)) {
1084         ERR_raise(ERR_LIB_BN, BN_R_NO_SOLUTION);
1085         goto err;
1086     }
1087
1088     if (!BN_copy(r, z))
1089         goto err;
1090     bn_check_top(r);
1091
1092     ret = 1;
1093
1094  err:
1095     BN_CTX_end(ctx);
1096     return ret;
1097 }
1098
1099 /*
1100  * Find r such that r^2 + r = a mod p.  r could be a. If no r exists returns
1101  * 0. This function calls down to the BN_GF2m_mod_solve_quad_arr
1102  * implementation; this wrapper function is only provided for convenience;
1103  * for best performance, use the BN_GF2m_mod_solve_quad_arr function.
1104  */
1105 int BN_GF2m_mod_solve_quad(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
1106                            BN_CTX *ctx)
1107 {
1108     int ret = 0;
1109     const int max = BN_num_bits(p) + 1;
1110     int *arr;
1111
1112     bn_check_top(a);
1113     bn_check_top(p);
1114
1115     arr = OPENSSL_malloc(sizeof(*arr) * max);
1116     if (arr == NULL)
1117         goto err;
1118     ret = BN_GF2m_poly2arr(p, arr, max);
1119     if (!ret || ret > max) {
1120         ERR_raise(ERR_LIB_BN, BN_R_INVALID_LENGTH);
1121         goto err;
1122     }
1123     ret = BN_GF2m_mod_solve_quad_arr(r, a, arr, ctx);
1124     bn_check_top(r);
1125  err:
1126     OPENSSL_free(arr);
1127     return ret;
1128 }
1129
1130 /*
1131  * Convert the bit-string representation of a polynomial ( \sum_{i=0}^n a_i *
1132  * x^i) into an array of integers corresponding to the bits with non-zero
1133  * coefficient.  Array is terminated with -1. Up to max elements of the array
1134  * will be filled.  Return value is total number of array elements that would
1135  * be filled if array was large enough.
1136  */
1137 int BN_GF2m_poly2arr(const BIGNUM *a, int p[], int max)
1138 {
1139     int i, j, k = 0;
1140     BN_ULONG mask;
1141
1142     if (BN_is_zero(a))
1143         return 0;
1144
1145     for (i = a->top - 1; i >= 0; i--) {
1146         if (!a->d[i])
1147             /* skip word if a->d[i] == 0 */
1148             continue;
1149         mask = BN_TBIT;
1150         for (j = BN_BITS2 - 1; j >= 0; j--) {
1151             if (a->d[i] & mask) {
1152                 if (k < max)
1153                     p[k] = BN_BITS2 * i + j;
1154                 k++;
1155             }
1156             mask >>= 1;
1157         }
1158     }
1159
1160     if (k < max) {
1161         p[k] = -1;
1162         k++;
1163     }
1164
1165     return k;
1166 }
1167
1168 /*
1169  * Convert the coefficient array representation of a polynomial to a
1170  * bit-string.  The array must be terminated by -1.
1171  */
1172 int BN_GF2m_arr2poly(const int p[], BIGNUM *a)
1173 {
1174     int i;
1175
1176     bn_check_top(a);
1177     BN_zero(a);
1178     for (i = 0; p[i] != -1; i++) {
1179         if (BN_set_bit(a, p[i]) == 0)
1180             return 0;
1181     }
1182     bn_check_top(a);
1183
1184     return 1;
1185 }
1186
1187 #endif