xref: /src/crypto/openssl/crypto/bn/bn_lib.c (revision f25b8c9fb4f58cf61adb47d7570abe7caa6d385d)
1 /*
2  * Copyright 1995-2024 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <assert.h>
11 #include <limits.h>
12 #include "internal/cryptlib.h"
13 #include "internal/endian.h"
14 #include "bn_local.h"
15 #include <openssl/opensslconf.h>
16 #include "internal/constant_time.h"
17 
18 /* This stuff appears to be completely unused, so is deprecated */
19 #ifndef OPENSSL_NO_DEPRECATED_0_9_8
20 /*-
21  * For a 32 bit machine
22  * 2 -   4 ==  128
23  * 3 -   8 ==  256
24  * 4 -  16 ==  512
25  * 5 -  32 == 1024
26  * 6 -  64 == 2048
27  * 7 - 128 == 4096
28  * 8 - 256 == 8192
29  */
30 static int bn_limit_bits = 0;
31 static int bn_limit_num = 8; /* (1<<bn_limit_bits) */
32 static int bn_limit_bits_low = 0;
33 static int bn_limit_num_low = 8; /* (1<<bn_limit_bits_low) */
34 static int bn_limit_bits_high = 0;
35 static int bn_limit_num_high = 8; /* (1<<bn_limit_bits_high) */
36 static int bn_limit_bits_mont = 0;
37 static int bn_limit_num_mont = 8; /* (1<<bn_limit_bits_mont) */
38 
BN_set_params(int mult,int high,int low,int mont)39 void BN_set_params(int mult, int high, int low, int mont)
40 {
41     if (mult >= 0) {
42         if (mult > (int)(sizeof(int) * 8) - 1)
43             mult = sizeof(int) * 8 - 1;
44         bn_limit_bits = mult;
45         bn_limit_num = 1 << mult;
46     }
47     if (high >= 0) {
48         if (high > (int)(sizeof(int) * 8) - 1)
49             high = sizeof(int) * 8 - 1;
50         bn_limit_bits_high = high;
51         bn_limit_num_high = 1 << high;
52     }
53     if (low >= 0) {
54         if (low > (int)(sizeof(int) * 8) - 1)
55             low = sizeof(int) * 8 - 1;
56         bn_limit_bits_low = low;
57         bn_limit_num_low = 1 << low;
58     }
59     if (mont >= 0) {
60         if (mont > (int)(sizeof(int) * 8) - 1)
61             mont = sizeof(int) * 8 - 1;
62         bn_limit_bits_mont = mont;
63         bn_limit_num_mont = 1 << mont;
64     }
65 }
66 
BN_get_params(int which)67 int BN_get_params(int which)
68 {
69     if (which == 0)
70         return bn_limit_bits;
71     else if (which == 1)
72         return bn_limit_bits_high;
73     else if (which == 2)
74         return bn_limit_bits_low;
75     else if (which == 3)
76         return bn_limit_bits_mont;
77     else
78         return 0;
79 }
80 #endif
81 
BN_value_one(void)82 const BIGNUM *BN_value_one(void)
83 {
84     static const BN_ULONG data_one = 1L;
85     static const BIGNUM const_one = {
86         (BN_ULONG *)&data_one, 1, 1, 0, BN_FLG_STATIC_DATA
87     };
88 
89     return &const_one;
90 }
91 
92 /*
93  * Old Visual Studio ARM compiler miscompiles BN_num_bits_word()
94  * https://mta.openssl.org/pipermail/openssl-users/2018-August/008465.html
95  */
96 #if defined(_MSC_VER) && defined(_ARM_) && defined(_WIN32_WCE) \
97     && _MSC_VER >= 1400 && _MSC_VER < 1501
98 #define MS_BROKEN_BN_num_bits_word
99 #pragma optimize("", off)
100 #endif
BN_num_bits_word(BN_ULONG l)101 int BN_num_bits_word(BN_ULONG l)
102 {
103     BN_ULONG x, mask;
104     int bits = (l != 0);
105 
106 #if BN_BITS2 > 32
107     x = l >> 32;
108     mask = (0 - x) & BN_MASK2;
109     mask = (0 - (mask >> (BN_BITS2 - 1)));
110     bits += 32 & mask;
111     l ^= (x ^ l) & mask;
112 #endif
113 
114     x = l >> 16;
115     mask = (0 - x) & BN_MASK2;
116     mask = (0 - (mask >> (BN_BITS2 - 1)));
117     bits += 16 & mask;
118     l ^= (x ^ l) & mask;
119 
120     x = l >> 8;
121     mask = (0 - x) & BN_MASK2;
122     mask = (0 - (mask >> (BN_BITS2 - 1)));
123     bits += 8 & mask;
124     l ^= (x ^ l) & mask;
125 
126     x = l >> 4;
127     mask = (0 - x) & BN_MASK2;
128     mask = (0 - (mask >> (BN_BITS2 - 1)));
129     bits += 4 & mask;
130     l ^= (x ^ l) & mask;
131 
132     x = l >> 2;
133     mask = (0 - x) & BN_MASK2;
134     mask = (0 - (mask >> (BN_BITS2 - 1)));
135     bits += 2 & mask;
136     l ^= (x ^ l) & mask;
137 
138     x = l >> 1;
139     mask = (0 - x) & BN_MASK2;
140     mask = (0 - (mask >> (BN_BITS2 - 1)));
141     bits += 1 & mask;
142 
143     return bits;
144 }
145 #ifdef MS_BROKEN_BN_num_bits_word
146 #pragma optimize("", on)
147 #endif
148 
149 /*
150  * This function still leaks `a->dmax`: it's caller's responsibility to
151  * expand the input `a` in advance to a public length.
152  */
bn_num_bits_consttime(const BIGNUM * a)153 static ossl_inline int bn_num_bits_consttime(const BIGNUM *a)
154 {
155     int j, ret;
156     unsigned int mask, past_i;
157     int i = a->top - 1;
158     bn_check_top(a);
159 
160     for (j = 0, past_i = 0, ret = 0; j < a->dmax; j++) {
161         mask = constant_time_eq_int(i, j); /* 0xff..ff if i==j, 0x0 otherwise */
162 
163         ret += BN_BITS2 & (~mask & ~past_i);
164         ret += BN_num_bits_word(a->d[j]) & mask;
165 
166         past_i |= mask; /* past_i will become 0xff..ff after i==j */
167     }
168 
169     /*
170      * if BN_is_zero(a) => i is -1 and ret contains garbage, so we mask the
171      * final result.
172      */
173     mask = ~(constant_time_eq_int(i, ((int)-1)));
174 
175     return ret & mask;
176 }
177 
BN_num_bits(const BIGNUM * a)178 int BN_num_bits(const BIGNUM *a)
179 {
180     int i = a->top - 1;
181     bn_check_top(a);
182 
183     if (a->flags & BN_FLG_CONSTTIME) {
184         /*
185          * We assume that BIGNUMs flagged as CONSTTIME have also been expanded
186          * so that a->dmax is not leaking secret information.
187          *
188          * In other words, it's the caller's responsibility to ensure `a` has
189          * been preallocated in advance to a public length if we hit this
190          * branch.
191          *
192          */
193         return bn_num_bits_consttime(a);
194     }
195 
196     if (BN_is_zero(a))
197         return 0;
198 
199     return ((i * BN_BITS2) + BN_num_bits_word(a->d[i]));
200 }
201 
bn_free_d(BIGNUM * a,int clear)202 static void bn_free_d(BIGNUM *a, int clear)
203 {
204     if (BN_get_flags(a, BN_FLG_SECURE))
205         OPENSSL_secure_clear_free(a->d, a->dmax * sizeof(a->d[0]));
206     else if (clear != 0)
207         OPENSSL_clear_free(a->d, a->dmax * sizeof(a->d[0]));
208     else
209         OPENSSL_free(a->d);
210 }
211 
BN_clear_free(BIGNUM * a)212 void BN_clear_free(BIGNUM *a)
213 {
214     if (a == NULL)
215         return;
216     if (a->d != NULL && !BN_get_flags(a, BN_FLG_STATIC_DATA))
217         bn_free_d(a, 1);
218     if (BN_get_flags(a, BN_FLG_MALLOCED)) {
219         OPENSSL_cleanse(a, sizeof(*a));
220         OPENSSL_free(a);
221     }
222 }
223 
BN_free(BIGNUM * a)224 void BN_free(BIGNUM *a)
225 {
226     if (a == NULL)
227         return;
228     if (!BN_get_flags(a, BN_FLG_STATIC_DATA))
229         bn_free_d(a, 0);
230     if (a->flags & BN_FLG_MALLOCED)
231         OPENSSL_free(a);
232 }
233 
bn_init(BIGNUM * a)234 void bn_init(BIGNUM *a)
235 {
236     static BIGNUM nilbn;
237 
238     *a = nilbn;
239     bn_check_top(a);
240 }
241 
BN_new(void)242 BIGNUM *BN_new(void)
243 {
244     BIGNUM *ret;
245 
246     if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL)
247         return NULL;
248     ret->flags = BN_FLG_MALLOCED;
249     bn_check_top(ret);
250     return ret;
251 }
252 
BN_secure_new(void)253 BIGNUM *BN_secure_new(void)
254 {
255     BIGNUM *ret = BN_new();
256 
257     if (ret != NULL)
258         ret->flags |= BN_FLG_SECURE;
259     return ret;
260 }
261 
262 /* This is used by bn_expand2() */
263 /* The caller MUST check that words > b->dmax before calling this */
bn_expand_internal(const BIGNUM * b,int words)264 static BN_ULONG *bn_expand_internal(const BIGNUM *b, int words)
265 {
266     BN_ULONG *a = NULL;
267 
268     if (words > (INT_MAX / (4 * BN_BITS2))) {
269         ERR_raise(ERR_LIB_BN, BN_R_BIGNUM_TOO_LONG);
270         return NULL;
271     }
272     if (BN_get_flags(b, BN_FLG_STATIC_DATA)) {
273         ERR_raise(ERR_LIB_BN, BN_R_EXPAND_ON_STATIC_BIGNUM_DATA);
274         return NULL;
275     }
276     if (BN_get_flags(b, BN_FLG_SECURE))
277         a = OPENSSL_secure_zalloc(words * sizeof(*a));
278     else
279         a = OPENSSL_zalloc(words * sizeof(*a));
280     if (a == NULL)
281         return NULL;
282 
283     assert(b->top <= words);
284     if (b->top > 0)
285         memcpy(a, b->d, sizeof(*a) * b->top);
286 
287     return a;
288 }
289 
290 /*
291  * This is an internal function that should not be used in applications. It
292  * ensures that 'b' has enough room for a 'words' word number and initialises
293  * any unused part of b->d with leading zeros. It is mostly used by the
294  * various BIGNUM routines. If there is an error, NULL is returned. If not,
295  * 'b' is returned.
296  */
297 
bn_expand2(BIGNUM * b,int words)298 BIGNUM *bn_expand2(BIGNUM *b, int words)
299 {
300     if (words > b->dmax) {
301         BN_ULONG *a = bn_expand_internal(b, words);
302         if (!a)
303             return NULL;
304         if (b->d != NULL)
305             bn_free_d(b, 1);
306         b->d = a;
307         b->dmax = words;
308     }
309 
310     return b;
311 }
312 
BN_dup(const BIGNUM * a)313 BIGNUM *BN_dup(const BIGNUM *a)
314 {
315     BIGNUM *t;
316 
317     if (a == NULL)
318         return NULL;
319     bn_check_top(a);
320 
321     t = BN_get_flags(a, BN_FLG_SECURE) ? BN_secure_new() : BN_new();
322     if (t == NULL)
323         return NULL;
324     if (!BN_copy(t, a)) {
325         BN_free(t);
326         return NULL;
327     }
328     bn_check_top(t);
329     return t;
330 }
331 
BN_copy(BIGNUM * a,const BIGNUM * b)332 BIGNUM *BN_copy(BIGNUM *a, const BIGNUM *b)
333 {
334     int bn_words;
335 
336     bn_check_top(b);
337 
338     bn_words = BN_get_flags(b, BN_FLG_CONSTTIME) ? b->dmax : b->top;
339 
340     if (a == b)
341         return a;
342     if (bn_wexpand(a, bn_words) == NULL)
343         return NULL;
344 
345     if (b->top > 0)
346         memcpy(a->d, b->d, sizeof(b->d[0]) * bn_words);
347 
348     a->neg = b->neg;
349     a->top = b->top;
350     a->flags |= b->flags & BN_FLG_FIXED_TOP;
351     bn_check_top(a);
352     return a;
353 }
354 
355 #define FLAGS_DATA(flags) ((flags) & (BN_FLG_STATIC_DATA | BN_FLG_CONSTTIME | BN_FLG_SECURE | BN_FLG_FIXED_TOP))
356 #define FLAGS_STRUCT(flags) ((flags) & (BN_FLG_MALLOCED))
357 
BN_swap(BIGNUM * a,BIGNUM * b)358 void BN_swap(BIGNUM *a, BIGNUM *b)
359 {
360     int flags_old_a, flags_old_b;
361     BN_ULONG *tmp_d;
362     int tmp_top, tmp_dmax, tmp_neg;
363 
364     bn_check_top(a);
365     bn_check_top(b);
366 
367     flags_old_a = a->flags;
368     flags_old_b = b->flags;
369 
370     tmp_d = a->d;
371     tmp_top = a->top;
372     tmp_dmax = a->dmax;
373     tmp_neg = a->neg;
374 
375     a->d = b->d;
376     a->top = b->top;
377     a->dmax = b->dmax;
378     a->neg = b->neg;
379 
380     b->d = tmp_d;
381     b->top = tmp_top;
382     b->dmax = tmp_dmax;
383     b->neg = tmp_neg;
384 
385     a->flags = FLAGS_STRUCT(flags_old_a) | FLAGS_DATA(flags_old_b);
386     b->flags = FLAGS_STRUCT(flags_old_b) | FLAGS_DATA(flags_old_a);
387     bn_check_top(a);
388     bn_check_top(b);
389 }
390 
BN_clear(BIGNUM * a)391 void BN_clear(BIGNUM *a)
392 {
393     if (a == NULL)
394         return;
395     bn_check_top(a);
396     if (a->d != NULL)
397         OPENSSL_cleanse(a->d, sizeof(*a->d) * a->dmax);
398     a->neg = 0;
399     a->top = 0;
400     a->flags &= ~BN_FLG_FIXED_TOP;
401 }
402 
BN_get_word(const BIGNUM * a)403 BN_ULONG BN_get_word(const BIGNUM *a)
404 {
405     if (a->top > 1)
406         return BN_MASK2;
407     else if (a->top == 1)
408         return a->d[0];
409     /* a->top == 0 */
410     return 0;
411 }
412 
BN_set_word(BIGNUM * a,BN_ULONG w)413 int BN_set_word(BIGNUM *a, BN_ULONG w)
414 {
415     bn_check_top(a);
416     if (bn_expand(a, (int)sizeof(BN_ULONG) * 8) == NULL)
417         return 0;
418     a->neg = 0;
419     a->d[0] = w;
420     a->top = (w ? 1 : 0);
421     a->flags &= ~BN_FLG_FIXED_TOP;
422     bn_check_top(a);
423     return 1;
424 }
425 
426 typedef enum { BIG,
427     LITTLE } endianness_t;
428 typedef enum { SIGNED,
429     UNSIGNED } signedness_t;
430 
bin2bn(const unsigned char * s,int len,BIGNUM * ret,endianness_t endianness,signedness_t signedness)431 static BIGNUM *bin2bn(const unsigned char *s, int len, BIGNUM *ret,
432     endianness_t endianness, signedness_t signedness)
433 {
434     int inc;
435     const unsigned char *s2;
436     int inc2;
437     int neg = 0, xor = 0, carry = 0;
438     unsigned int i;
439     unsigned int n;
440     BIGNUM *bn = NULL;
441 
442     /* Negative length is not acceptable */
443     if (len < 0)
444         return NULL;
445 
446     if (ret == NULL)
447         ret = bn = BN_new();
448     if (ret == NULL)
449         return NULL;
450     bn_check_top(ret);
451 
452     /*
453      * If the input has no bits, the number is considered zero.
454      * This makes calls with s==NULL and len==0 safe.
455      */
456     if (len == 0) {
457         BN_clear(ret);
458         return ret;
459     }
460 
461     /*
462      * The loop that does the work iterates from least to most
463      * significant BIGNUM chunk, so we adapt parameters to transfer
464      * input bytes accordingly.
465      */
466     if (endianness == LITTLE) {
467         s2 = s + len - 1;
468         inc2 = -1;
469         inc = 1;
470     } else {
471         s2 = s;
472         inc2 = 1;
473         inc = -1;
474         s += len - 1;
475     }
476 
477     /* Take note of the signedness of the input bytes*/
478     if (signedness == SIGNED) {
479         neg = !!(*s2 & 0x80);
480         xor = neg ? 0xff : 0x00;
481         carry = neg;
482     }
483 
484     /*
485      * Skip leading sign extensions (the value of |xor|).
486      * This is the only spot where |s2| and |inc2| are used.
487      */
488     for (; len > 0 && *s2 == xor; s2 += inc2, len--)
489         continue;
490 
491     /*
492      * If there was a set of 0xff, we backtrack one byte unless the next
493      * one has a sign bit, as the last 0xff is then part of the actual
494      * number, rather then a mere sign extension.
495      */
496     if (xor == 0xff) {
497         if (len == 0 || !(*s2 & 0x80))
498             len++;
499     }
500     /* If it was all zeros, we're done */
501     if (len == 0) {
502         ret->top = 0;
503         return ret;
504     }
505     n = ((len - 1) / BN_BYTES) + 1; /* Number of resulting bignum chunks */
506     if (bn_wexpand(ret, (int)n) == NULL) {
507         BN_free(bn);
508         return NULL;
509     }
510     ret->top = n;
511     ret->neg = neg;
512     for (i = 0; n-- > 0; i++) {
513         BN_ULONG l = 0; /* Accumulator */
514         unsigned int m = 0; /* Offset in a bignum chunk, in bits */
515 
516         for (; len > 0 && m < BN_BYTES * 8; len--, s += inc, m += 8) {
517             BN_ULONG byte_xored = *s ^ xor;
518             BN_ULONG byte = (byte_xored + carry) & 0xff;
519 
520             carry = byte_xored > byte; /* Implicit 1 or 0 */
521             l |= (byte << m);
522         }
523         ret->d[i] = l;
524     }
525     /*
526      * need to call this due to clear byte at top if avoiding having the top
527      * bit set (-ve number)
528      */
529     bn_correct_top(ret);
530     return ret;
531 }
532 
BN_bin2bn(const unsigned char * s,int len,BIGNUM * ret)533 BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret)
534 {
535     return bin2bn(s, len, ret, BIG, UNSIGNED);
536 }
537 
BN_signed_bin2bn(const unsigned char * s,int len,BIGNUM * ret)538 BIGNUM *BN_signed_bin2bn(const unsigned char *s, int len, BIGNUM *ret)
539 {
540     return bin2bn(s, len, ret, BIG, SIGNED);
541 }
542 
bn2binpad(const BIGNUM * a,unsigned char * to,int tolen,endianness_t endianness,signedness_t signedness)543 static int bn2binpad(const BIGNUM *a, unsigned char *to, int tolen,
544     endianness_t endianness, signedness_t signedness)
545 {
546     int inc;
547     int n, n8;
548     int xor = 0, carry = 0, ext = 0;
549     size_t i, lasti, j, atop, mask;
550     BN_ULONG l;
551 
552     /*
553      * In case |a| is fixed-top, BN_num_bits can return bogus length,
554      * but it's assumed that fixed-top inputs ought to be "nominated"
555      * even for padded output, so it works out...
556      */
557     n8 = BN_num_bits(a);
558     n = (n8 + 7) / 8; /* This is what BN_num_bytes() does */
559 
560     /* Take note of the signedness of the bignum */
561     if (signedness == SIGNED) {
562         xor = a->neg ? 0xff : 0x00;
563         carry = a->neg;
564 
565         /*
566          * if |n * 8 == n|, then the MSbit is set, otherwise unset.
567          * We must compensate with one extra byte if that doesn't
568          * correspond to the signedness of the bignum with regards
569          * to 2's complement.
570          */
571         ext = (n * 8 == n8)
572             ? !a->neg /* MSbit set on nonnegative bignum */
573             : a->neg; /* MSbit unset on negative bignum */
574     }
575 
576     if (tolen == -1) {
577         tolen = n + ext;
578     } else if (tolen < n + ext) { /* uncommon/unlike case */
579         BIGNUM temp = *a;
580 
581         bn_correct_top(&temp);
582         n8 = BN_num_bits(&temp);
583         n = (n8 + 7) / 8; /* This is what BN_num_bytes() does */
584         if (tolen < n + ext)
585             return -1;
586     }
587 
588     /* Swipe through whole available data and don't give away padded zero. */
589     atop = a->dmax * BN_BYTES;
590     if (atop == 0) {
591         if (tolen != 0)
592             memset(to, '\0', tolen);
593         return tolen;
594     }
595 
596     /*
597      * The loop that does the work iterates from least significant
598      * to most significant BIGNUM limb, so we adapt parameters to
599      * transfer output bytes accordingly.
600      */
601     if (endianness == LITTLE) {
602         inc = 1;
603     } else {
604         inc = -1;
605         to += tolen - 1; /* Move to the last byte, not beyond */
606     }
607 
608     lasti = atop - 1;
609     atop = a->top * BN_BYTES;
610     for (i = 0, j = 0; j < (size_t)tolen; j++) {
611         unsigned char byte, byte_xored;
612 
613         l = a->d[i / BN_BYTES];
614         mask = 0 - ((j - atop) >> (8 * sizeof(i) - 1));
615         byte = (unsigned char)(l >> (8 * (i % BN_BYTES)) & mask);
616         byte_xored = byte ^ xor;
617         *to = (unsigned char)(byte_xored + carry);
618         carry = byte_xored > *to; /* Implicit 1 or 0 */
619         to += inc;
620         i += (i - lasti) >> (8 * sizeof(i) - 1); /* stay on last limb */
621     }
622 
623     return tolen;
624 }
625 
BN_bn2binpad(const BIGNUM * a,unsigned char * to,int tolen)626 int BN_bn2binpad(const BIGNUM *a, unsigned char *to, int tolen)
627 {
628     if (tolen < 0)
629         return -1;
630     return bn2binpad(a, to, tolen, BIG, UNSIGNED);
631 }
632 
BN_signed_bn2bin(const BIGNUM * a,unsigned char * to,int tolen)633 int BN_signed_bn2bin(const BIGNUM *a, unsigned char *to, int tolen)
634 {
635     if (tolen < 0)
636         return -1;
637     return bn2binpad(a, to, tolen, BIG, SIGNED);
638 }
639 
BN_bn2bin(const BIGNUM * a,unsigned char * to)640 int BN_bn2bin(const BIGNUM *a, unsigned char *to)
641 {
642     return bn2binpad(a, to, -1, BIG, UNSIGNED);
643 }
644 
BN_lebin2bn(const unsigned char * s,int len,BIGNUM * ret)645 BIGNUM *BN_lebin2bn(const unsigned char *s, int len, BIGNUM *ret)
646 {
647     return bin2bn(s, len, ret, LITTLE, UNSIGNED);
648 }
649 
BN_signed_lebin2bn(const unsigned char * s,int len,BIGNUM * ret)650 BIGNUM *BN_signed_lebin2bn(const unsigned char *s, int len, BIGNUM *ret)
651 {
652     return bin2bn(s, len, ret, LITTLE, SIGNED);
653 }
654 
BN_bn2lebinpad(const BIGNUM * a,unsigned char * to,int tolen)655 int BN_bn2lebinpad(const BIGNUM *a, unsigned char *to, int tolen)
656 {
657     if (tolen < 0)
658         return -1;
659     return bn2binpad(a, to, tolen, LITTLE, UNSIGNED);
660 }
661 
BN_signed_bn2lebin(const BIGNUM * a,unsigned char * to,int tolen)662 int BN_signed_bn2lebin(const BIGNUM *a, unsigned char *to, int tolen)
663 {
664     if (tolen < 0)
665         return -1;
666     return bn2binpad(a, to, tolen, LITTLE, SIGNED);
667 }
668 
BN_native2bn(const unsigned char * s,int len,BIGNUM * ret)669 BIGNUM *BN_native2bn(const unsigned char *s, int len, BIGNUM *ret)
670 {
671     DECLARE_IS_ENDIAN;
672 
673     if (IS_LITTLE_ENDIAN)
674         return BN_lebin2bn(s, len, ret);
675     return BN_bin2bn(s, len, ret);
676 }
677 
BN_signed_native2bn(const unsigned char * s,int len,BIGNUM * ret)678 BIGNUM *BN_signed_native2bn(const unsigned char *s, int len, BIGNUM *ret)
679 {
680     DECLARE_IS_ENDIAN;
681 
682     if (IS_LITTLE_ENDIAN)
683         return BN_signed_lebin2bn(s, len, ret);
684     return BN_signed_bin2bn(s, len, ret);
685 }
686 
BN_bn2nativepad(const BIGNUM * a,unsigned char * to,int tolen)687 int BN_bn2nativepad(const BIGNUM *a, unsigned char *to, int tolen)
688 {
689     DECLARE_IS_ENDIAN;
690 
691     if (IS_LITTLE_ENDIAN)
692         return BN_bn2lebinpad(a, to, tolen);
693     return BN_bn2binpad(a, to, tolen);
694 }
695 
BN_signed_bn2native(const BIGNUM * a,unsigned char * to,int tolen)696 int BN_signed_bn2native(const BIGNUM *a, unsigned char *to, int tolen)
697 {
698     DECLARE_IS_ENDIAN;
699 
700     if (IS_LITTLE_ENDIAN)
701         return BN_signed_bn2lebin(a, to, tolen);
702     return BN_signed_bn2bin(a, to, tolen);
703 }
704 
BN_ucmp(const BIGNUM * a,const BIGNUM * b)705 int BN_ucmp(const BIGNUM *a, const BIGNUM *b)
706 {
707     int i;
708     BN_ULONG t1, t2, *ap, *bp;
709 
710     ap = a->d;
711     bp = b->d;
712 
713     if (BN_get_flags(a, BN_FLG_CONSTTIME)
714         && a->top == b->top) {
715         int res = 0;
716 
717         for (i = 0; i < b->top; i++) {
718             res = constant_time_select_int(constant_time_lt_bn(ap[i], bp[i]),
719                 -1, res);
720             res = constant_time_select_int(constant_time_lt_bn(bp[i], ap[i]),
721                 1, res);
722         }
723         return res;
724     }
725 
726     bn_check_top(a);
727     bn_check_top(b);
728 
729     i = a->top - b->top;
730     if (i != 0)
731         return i;
732 
733     for (i = a->top - 1; i >= 0; i--) {
734         t1 = ap[i];
735         t2 = bp[i];
736         if (t1 != t2)
737             return ((t1 > t2) ? 1 : -1);
738     }
739     return 0;
740 }
741 
BN_cmp(const BIGNUM * a,const BIGNUM * b)742 int BN_cmp(const BIGNUM *a, const BIGNUM *b)
743 {
744     int i;
745     int gt, lt;
746     BN_ULONG t1, t2;
747 
748     if ((a == NULL) || (b == NULL)) {
749         if (a != NULL)
750             return -1;
751         else if (b != NULL)
752             return 1;
753         else
754             return 0;
755     }
756 
757     bn_check_top(a);
758     bn_check_top(b);
759 
760     if (a->neg != b->neg) {
761         if (a->neg)
762             return -1;
763         else
764             return 1;
765     }
766     if (a->neg == 0) {
767         gt = 1;
768         lt = -1;
769     } else {
770         gt = -1;
771         lt = 1;
772     }
773 
774     if (a->top > b->top)
775         return gt;
776     if (a->top < b->top)
777         return lt;
778     for (i = a->top - 1; i >= 0; i--) {
779         t1 = a->d[i];
780         t2 = b->d[i];
781         if (t1 > t2)
782             return gt;
783         if (t1 < t2)
784             return lt;
785     }
786     return 0;
787 }
788 
BN_set_bit(BIGNUM * a,int n)789 int BN_set_bit(BIGNUM *a, int n)
790 {
791     int i, j, k;
792 
793     if (n < 0)
794         return 0;
795 
796     i = n / BN_BITS2;
797     j = n % BN_BITS2;
798     if (a->top <= i) {
799         if (bn_wexpand(a, i + 1) == NULL)
800             return 0;
801         for (k = a->top; k < i + 1; k++)
802             a->d[k] = 0;
803         a->top = i + 1;
804         a->flags &= ~BN_FLG_FIXED_TOP;
805     }
806 
807     a->d[i] |= (((BN_ULONG)1) << j);
808     bn_check_top(a);
809     return 1;
810 }
811 
BN_clear_bit(BIGNUM * a,int n)812 int BN_clear_bit(BIGNUM *a, int n)
813 {
814     int i, j;
815 
816     bn_check_top(a);
817     if (n < 0)
818         return 0;
819 
820     i = n / BN_BITS2;
821     j = n % BN_BITS2;
822     if (a->top <= i)
823         return 0;
824 
825     a->d[i] &= (~(((BN_ULONG)1) << j));
826     bn_correct_top(a);
827     return 1;
828 }
829 
BN_is_bit_set(const BIGNUM * a,int n)830 int BN_is_bit_set(const BIGNUM *a, int n)
831 {
832     int i, j;
833 
834     bn_check_top(a);
835     if (n < 0)
836         return 0;
837     i = n / BN_BITS2;
838     j = n % BN_BITS2;
839     if (a->top <= i)
840         return 0;
841     return (int)(((a->d[i]) >> j) & ((BN_ULONG)1));
842 }
843 
ossl_bn_mask_bits_fixed_top(BIGNUM * a,int n)844 int ossl_bn_mask_bits_fixed_top(BIGNUM *a, int n)
845 {
846     int b, w;
847 
848     if (n < 0)
849         return 0;
850 
851     w = n / BN_BITS2;
852     b = n % BN_BITS2;
853     if (w >= a->top)
854         return 0;
855     if (b == 0)
856         a->top = w;
857     else {
858         a->top = w + 1;
859         a->d[w] &= ~(BN_MASK2 << b);
860     }
861     a->flags |= BN_FLG_FIXED_TOP;
862     return 1;
863 }
864 
BN_mask_bits(BIGNUM * a,int n)865 int BN_mask_bits(BIGNUM *a, int n)
866 {
867     int ret;
868 
869     bn_check_top(a);
870     ret = ossl_bn_mask_bits_fixed_top(a, n);
871     if (ret)
872         bn_correct_top(a);
873     return ret;
874 }
875 
BN_set_negative(BIGNUM * a,int b)876 void BN_set_negative(BIGNUM *a, int b)
877 {
878     if (b && !BN_is_zero(a))
879         a->neg = 1;
880     else
881         a->neg = 0;
882 }
883 
bn_cmp_words(const BN_ULONG * a,const BN_ULONG * b,int n)884 int bn_cmp_words(const BN_ULONG *a, const BN_ULONG *b, int n)
885 {
886     int i;
887     BN_ULONG aa, bb;
888 
889     if (n == 0)
890         return 0;
891 
892     aa = a[n - 1];
893     bb = b[n - 1];
894     if (aa != bb)
895         return ((aa > bb) ? 1 : -1);
896     for (i = n - 2; i >= 0; i--) {
897         aa = a[i];
898         bb = b[i];
899         if (aa != bb)
900             return ((aa > bb) ? 1 : -1);
901     }
902     return 0;
903 }
904 
905 /*
906  * Here follows a specialised variants of bn_cmp_words().  It has the
907  * capability of performing the operation on arrays of different sizes. The
908  * sizes of those arrays is expressed through cl, which is the common length
909  * ( basically, min(len(a),len(b)) ), and dl, which is the delta between the
910  * two lengths, calculated as len(a)-len(b). All lengths are the number of
911  * BN_ULONGs...
912  */
913 
bn_cmp_part_words(const BN_ULONG * a,const BN_ULONG * b,int cl,int dl)914 int bn_cmp_part_words(const BN_ULONG *a, const BN_ULONG *b, int cl, int dl)
915 {
916     int n, i;
917     n = cl - 1;
918 
919     if (dl < 0) {
920         for (i = dl; i < 0; i++) {
921             if (b[n - i] != 0)
922                 return -1; /* a < b */
923         }
924     }
925     if (dl > 0) {
926         for (i = dl; i > 0; i--) {
927             if (a[n + i] != 0)
928                 return 1; /* a > b */
929         }
930     }
931     return bn_cmp_words(a, b, cl);
932 }
933 
934 /*-
935  * Constant-time conditional swap of a and b.
936  * a and b are swapped if condition is not 0.
937  * nwords is the number of words to swap.
938  * Assumes that at least nwords are allocated in both a and b.
939  * Assumes that no more than nwords are used by either a or b.
940  */
BN_consttime_swap(BN_ULONG condition,BIGNUM * a,BIGNUM * b,int nwords)941 void BN_consttime_swap(BN_ULONG condition, BIGNUM *a, BIGNUM *b, int nwords)
942 {
943     BN_ULONG t;
944     int i;
945 
946     bn_wcheck_size(a, nwords);
947     bn_wcheck_size(b, nwords);
948 
949     condition = ((~condition & ((condition - 1))) >> (BN_BITS2 - 1)) - 1;
950 
951     t = (a->top ^ b->top) & condition;
952     a->top ^= t;
953     b->top ^= t;
954 
955     t = (a->neg ^ b->neg) & condition;
956     a->neg ^= t;
957     b->neg ^= t;
958 
959     /*-
960      * BN_FLG_STATIC_DATA: indicates that data may not be written to. Intention
961      * is actually to treat it as it's read-only data, and some (if not most)
962      * of it does reside in read-only segment. In other words observation of
963      * BN_FLG_STATIC_DATA in BN_consttime_swap should be treated as fatal
964      * condition. It would either cause SEGV or effectively cause data
965      * corruption.
966      *
967      * BN_FLG_MALLOCED: refers to BN structure itself, and hence must be
968      * preserved.
969      *
970      * BN_FLG_SECURE: must be preserved, because it determines how x->d was
971      * allocated and hence how to free it.
972      *
973      * BN_FLG_CONSTTIME: sufficient to mask and swap
974      *
975      * BN_FLG_FIXED_TOP: indicates that we haven't called bn_correct_top() on
976      * the data, so the d array may be padded with additional 0 values (i.e.
977      * top could be greater than the minimal value that it could be). We should
978      * be swapping it
979      */
980 
981 #define BN_CONSTTIME_SWAP_FLAGS (BN_FLG_CONSTTIME | BN_FLG_FIXED_TOP)
982 
983     t = ((a->flags ^ b->flags) & BN_CONSTTIME_SWAP_FLAGS) & condition;
984     a->flags ^= t;
985     b->flags ^= t;
986 
987     /* conditionally swap the data */
988     for (i = 0; i < nwords; i++) {
989         t = (a->d[i] ^ b->d[i]) & condition;
990         a->d[i] ^= t;
991         b->d[i] ^= t;
992     }
993 }
994 
995 #undef BN_CONSTTIME_SWAP_FLAGS
996 
997 /* Bits of security, see SP800-57 */
998 
BN_security_bits(int L,int N)999 int BN_security_bits(int L, int N)
1000 {
1001     int secbits, bits;
1002     if (L >= 15360)
1003         secbits = 256;
1004     else if (L >= 7680)
1005         secbits = 192;
1006     else if (L >= 3072)
1007         secbits = 128;
1008     else if (L >= 2048)
1009         secbits = 112;
1010     else if (L >= 1024)
1011         secbits = 80;
1012     else
1013         return 0;
1014     if (N == -1)
1015         return secbits;
1016     bits = N / 2;
1017     if (bits < 80)
1018         return 0;
1019     return bits >= secbits ? secbits : bits;
1020 }
1021 
BN_zero_ex(BIGNUM * a)1022 void BN_zero_ex(BIGNUM *a)
1023 {
1024     a->neg = 0;
1025     a->top = 0;
1026     a->flags &= ~BN_FLG_FIXED_TOP;
1027 }
1028 
BN_abs_is_word(const BIGNUM * a,const BN_ULONG w)1029 int BN_abs_is_word(const BIGNUM *a, const BN_ULONG w)
1030 {
1031     return ((a->top == 1) && (a->d[0] == w)) || ((w == 0) && (a->top == 0));
1032 }
1033 
BN_is_zero(const BIGNUM * a)1034 int BN_is_zero(const BIGNUM *a)
1035 {
1036     return a->top == 0;
1037 }
1038 
BN_is_one(const BIGNUM * a)1039 int BN_is_one(const BIGNUM *a)
1040 {
1041     return BN_abs_is_word(a, 1) && !a->neg;
1042 }
1043 
BN_is_word(const BIGNUM * a,const BN_ULONG w)1044 int BN_is_word(const BIGNUM *a, const BN_ULONG w)
1045 {
1046     return BN_abs_is_word(a, w) && (!w || !a->neg);
1047 }
1048 
ossl_bn_is_word_fixed_top(const BIGNUM * a,const BN_ULONG w)1049 int ossl_bn_is_word_fixed_top(const BIGNUM *a, const BN_ULONG w)
1050 {
1051     int res, i;
1052     const BN_ULONG *ap = a->d;
1053 
1054     if (a->neg || a->top == 0)
1055         return 0;
1056 
1057     res = constant_time_select_int(constant_time_eq_bn(ap[0], w), 1, 0);
1058 
1059     for (i = 1; i < a->top; i++)
1060         res = constant_time_select_int(constant_time_is_zero_bn(ap[i]),
1061             res, 0);
1062     return res;
1063 }
1064 
BN_is_odd(const BIGNUM * a)1065 int BN_is_odd(const BIGNUM *a)
1066 {
1067     return (a->top > 0) && (a->d[0] & 1);
1068 }
1069 
BN_is_negative(const BIGNUM * a)1070 int BN_is_negative(const BIGNUM *a)
1071 {
1072     return (a->neg != 0);
1073 }
1074 
BN_to_montgomery(BIGNUM * r,const BIGNUM * a,BN_MONT_CTX * mont,BN_CTX * ctx)1075 int BN_to_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
1076     BN_CTX *ctx)
1077 {
1078     return BN_mod_mul_montgomery(r, a, &(mont->RR), mont, ctx);
1079 }
1080 
BN_with_flags(BIGNUM * dest,const BIGNUM * b,int flags)1081 void BN_with_flags(BIGNUM *dest, const BIGNUM *b, int flags)
1082 {
1083     dest->d = b->d;
1084     dest->top = b->top;
1085     dest->dmax = b->dmax;
1086     dest->neg = b->neg;
1087     dest->flags = ((dest->flags & BN_FLG_MALLOCED)
1088         | (b->flags & ~BN_FLG_MALLOCED)
1089         | BN_FLG_STATIC_DATA | flags);
1090 }
1091 
BN_GENCB_new(void)1092 BN_GENCB *BN_GENCB_new(void)
1093 {
1094     BN_GENCB *ret;
1095 
1096     if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL)
1097         return NULL;
1098 
1099     return ret;
1100 }
1101 
BN_GENCB_free(BN_GENCB * cb)1102 void BN_GENCB_free(BN_GENCB *cb)
1103 {
1104     if (cb == NULL)
1105         return;
1106     OPENSSL_free(cb);
1107 }
1108 
BN_set_flags(BIGNUM * b,int n)1109 void BN_set_flags(BIGNUM *b, int n)
1110 {
1111     b->flags |= n;
1112 }
1113 
BN_get_flags(const BIGNUM * b,int n)1114 int BN_get_flags(const BIGNUM *b, int n)
1115 {
1116     return b->flags & n;
1117 }
1118 
1119 /* Populate a BN_GENCB structure with an "old"-style callback */
BN_GENCB_set_old(BN_GENCB * gencb,void (* callback)(int,int,void *),void * cb_arg)1120 void BN_GENCB_set_old(BN_GENCB *gencb, void (*callback)(int, int, void *),
1121     void *cb_arg)
1122 {
1123     BN_GENCB *tmp_gencb = gencb;
1124     tmp_gencb->ver = 1;
1125     tmp_gencb->arg = cb_arg;
1126     tmp_gencb->cb.cb_1 = callback;
1127 }
1128 
1129 /* Populate a BN_GENCB structure with a "new"-style callback */
BN_GENCB_set(BN_GENCB * gencb,int (* callback)(int,int,BN_GENCB *),void * cb_arg)1130 void BN_GENCB_set(BN_GENCB *gencb, int (*callback)(int, int, BN_GENCB *),
1131     void *cb_arg)
1132 {
1133     BN_GENCB *tmp_gencb = gencb;
1134     tmp_gencb->ver = 2;
1135     tmp_gencb->arg = cb_arg;
1136     tmp_gencb->cb.cb_2 = callback;
1137 }
1138 
BN_GENCB_get_arg(BN_GENCB * cb)1139 void *BN_GENCB_get_arg(BN_GENCB *cb)
1140 {
1141     return cb->arg;
1142 }
1143 
bn_wexpand(BIGNUM * a,int words)1144 BIGNUM *bn_wexpand(BIGNUM *a, int words)
1145 {
1146     return (words <= a->dmax) ? a : bn_expand2(a, words);
1147 }
1148 
bn_correct_top_consttime(BIGNUM * a)1149 void bn_correct_top_consttime(BIGNUM *a)
1150 {
1151     int j, atop;
1152     BN_ULONG limb;
1153     unsigned int mask;
1154 
1155     for (j = 0, atop = 0; j < a->dmax; j++) {
1156         limb = a->d[j];
1157         limb |= 0 - limb;
1158         limb >>= BN_BITS2 - 1;
1159         limb = 0 - limb;
1160         mask = (unsigned int)limb;
1161         mask &= constant_time_msb(j - a->top);
1162         atop = constant_time_select_int(mask, j + 1, atop);
1163     }
1164 
1165     mask = constant_time_eq_int(atop, 0);
1166     a->top = atop;
1167     a->neg = constant_time_select_int(mask, 0, a->neg);
1168     a->flags &= ~BN_FLG_FIXED_TOP;
1169 }
1170 
bn_correct_top(BIGNUM * a)1171 void bn_correct_top(BIGNUM *a)
1172 {
1173     BN_ULONG *ftl;
1174     int tmp_top = a->top;
1175 
1176     if (tmp_top > 0) {
1177         for (ftl = &(a->d[tmp_top]); tmp_top > 0; tmp_top--) {
1178             ftl--;
1179             if (*ftl != 0)
1180                 break;
1181         }
1182         a->top = tmp_top;
1183     }
1184     if (a->top == 0)
1185         a->neg = 0;
1186     a->flags &= ~BN_FLG_FIXED_TOP;
1187     bn_pollute(a);
1188 }
1189