xref: /freebsd/crypto/openssl/crypto/bn/bn_lib.c (revision 78e936b2d0b5e6554425009199be31e76bc67c10)
1 /*
2  * Copyright 1995-2026 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     /*
711      * As it is a public API function, we should handle NULL parameters in
712      * some way. The function can’t return an error, so let’s define that NULL
713      * is less than any BIGNUM.
714      */
715     if (!ossl_assert(a != NULL && b != NULL))
716         return (b == NULL) - (a == NULL);
717 
718     ap = a->d;
719     bp = b->d;
720 
721     if (BN_get_flags(a, BN_FLG_CONSTTIME)
722         || BN_get_flags(b, BN_FLG_CONSTTIME)) {
723         int res = 0;
724         int min_top = a->top < b->top ? a->top : b->top;
725 
726         for (i = 0; i < min_top; i++) {
727             res = constant_time_select_int(constant_time_lt_bn(ap[i], bp[i]),
728                 -1, res);
729             res = constant_time_select_int(constant_time_lt_bn(bp[i], ap[i]),
730                 1, res);
731         }
732 
733         for (i = min_top; i < a->top; ++i)
734             res = constant_time_select_int((int)constant_time_is_zero_bn(ap[i]),
735                 res, 1);
736 
737         for (i = min_top; i < b->top; ++i)
738             res = constant_time_select_int((int)constant_time_is_zero_bn(bp[i]),
739                 res, -1);
740 
741         return res;
742     }
743 
744     bn_check_top(a);
745     bn_check_top(b);
746 
747     i = a->top - b->top;
748     if (i != 0)
749         return i;
750 
751     for (i = a->top - 1; i >= 0; i--) {
752         t1 = ap[i];
753         t2 = bp[i];
754         if (t1 != t2)
755             return ((t1 > t2) ? 1 : -1);
756     }
757     return 0;
758 }
759 
BN_cmp(const BIGNUM * a,const BIGNUM * b)760 int BN_cmp(const BIGNUM *a, const BIGNUM *b)
761 {
762     int i;
763     int gt, lt;
764     BN_ULONG t1, t2;
765 
766     if ((a == NULL) || (b == NULL)) {
767         if (a != NULL)
768             return -1;
769         else if (b != NULL)
770             return 1;
771         else
772             return 0;
773     }
774 
775     bn_check_top(a);
776     bn_check_top(b);
777 
778     if (a->neg != b->neg) {
779         if (a->neg)
780             return -1;
781         else
782             return 1;
783     }
784     if (a->neg == 0) {
785         gt = 1;
786         lt = -1;
787     } else {
788         gt = -1;
789         lt = 1;
790     }
791 
792     if (a->top > b->top)
793         return gt;
794     if (a->top < b->top)
795         return lt;
796     for (i = a->top - 1; i >= 0; i--) {
797         t1 = a->d[i];
798         t2 = b->d[i];
799         if (t1 > t2)
800             return gt;
801         if (t1 < t2)
802             return lt;
803     }
804     return 0;
805 }
806 
BN_set_bit(BIGNUM * a,int n)807 int BN_set_bit(BIGNUM *a, int n)
808 {
809     int i, j, k;
810 
811     if (n < 0)
812         return 0;
813 
814     i = n / BN_BITS2;
815     j = n % BN_BITS2;
816     if (a->top <= i) {
817         if (bn_wexpand(a, i + 1) == NULL)
818             return 0;
819         for (k = a->top; k < i + 1; k++)
820             a->d[k] = 0;
821         a->top = i + 1;
822         a->flags &= ~BN_FLG_FIXED_TOP;
823     }
824 
825     a->d[i] |= (((BN_ULONG)1) << j);
826     bn_check_top(a);
827     return 1;
828 }
829 
BN_clear_bit(BIGNUM * a,int n)830 int BN_clear_bit(BIGNUM *a, int n)
831 {
832     int i, j;
833 
834     bn_check_top(a);
835     if (n < 0)
836         return 0;
837 
838     i = n / BN_BITS2;
839     j = n % BN_BITS2;
840     if (a->top <= i)
841         return 0;
842 
843     a->d[i] &= (~(((BN_ULONG)1) << j));
844     bn_correct_top(a);
845     return 1;
846 }
847 
BN_is_bit_set(const BIGNUM * a,int n)848 int BN_is_bit_set(const BIGNUM *a, int n)
849 {
850     int i, j;
851 
852     bn_check_top(a);
853     if (n < 0)
854         return 0;
855     i = n / BN_BITS2;
856     j = n % BN_BITS2;
857     if (a->top <= i)
858         return 0;
859     return (int)(((a->d[i]) >> j) & ((BN_ULONG)1));
860 }
861 
ossl_bn_mask_bits_fixed_top(BIGNUM * a,int n)862 int ossl_bn_mask_bits_fixed_top(BIGNUM *a, int n)
863 {
864     int b, w;
865 
866     if (n < 0)
867         return 0;
868 
869     w = n / BN_BITS2;
870     b = n % BN_BITS2;
871     if (w >= a->top)
872         return 0;
873     if (b == 0)
874         a->top = w;
875     else {
876         a->top = w + 1;
877         a->d[w] &= ~(BN_MASK2 << b);
878     }
879     a->flags |= BN_FLG_FIXED_TOP;
880     return 1;
881 }
882 
BN_mask_bits(BIGNUM * a,int n)883 int BN_mask_bits(BIGNUM *a, int n)
884 {
885     int ret;
886 
887     bn_check_top(a);
888     ret = ossl_bn_mask_bits_fixed_top(a, n);
889     if (ret)
890         bn_correct_top(a);
891     return ret;
892 }
893 
BN_set_negative(BIGNUM * a,int b)894 void BN_set_negative(BIGNUM *a, int b)
895 {
896     if (b && !BN_is_zero(a))
897         a->neg = 1;
898     else
899         a->neg = 0;
900 }
901 
bn_cmp_words(const BN_ULONG * a,const BN_ULONG * b,int n)902 int bn_cmp_words(const BN_ULONG *a, const BN_ULONG *b, int n)
903 {
904     int i;
905     BN_ULONG aa, bb;
906 
907     if (n == 0)
908         return 0;
909 
910     aa = a[n - 1];
911     bb = b[n - 1];
912     if (aa != bb)
913         return ((aa > bb) ? 1 : -1);
914     for (i = n - 2; i >= 0; i--) {
915         aa = a[i];
916         bb = b[i];
917         if (aa != bb)
918             return ((aa > bb) ? 1 : -1);
919     }
920     return 0;
921 }
922 
923 /*
924  * Here follows a specialised variants of bn_cmp_words().  It has the
925  * capability of performing the operation on arrays of different sizes. The
926  * sizes of those arrays is expressed through cl, which is the common length
927  * ( basically, min(len(a),len(b)) ), and dl, which is the delta between the
928  * two lengths, calculated as len(a)-len(b). All lengths are the number of
929  * BN_ULONGs...
930  */
931 
bn_cmp_part_words(const BN_ULONG * a,const BN_ULONG * b,int cl,int dl)932 int bn_cmp_part_words(const BN_ULONG *a, const BN_ULONG *b, int cl, int dl)
933 {
934     int n, i;
935     n = cl - 1;
936 
937     if (dl < 0) {
938         for (i = dl; i < 0; i++) {
939             if (b[n - i] != 0)
940                 return -1; /* a < b */
941         }
942     }
943     if (dl > 0) {
944         for (i = dl; i > 0; i--) {
945             if (a[n + i] != 0)
946                 return 1; /* a > b */
947         }
948     }
949     return bn_cmp_words(a, b, cl);
950 }
951 
952 /*-
953  * Constant-time conditional swap of a and b.
954  * a and b are swapped if condition is not 0.
955  * nwords is the number of words to swap.
956  * Assumes that at least nwords are allocated in both a and b.
957  * Assumes that no more than nwords are used by either a or b.
958  */
BN_consttime_swap(BN_ULONG condition,BIGNUM * a,BIGNUM * b,int nwords)959 void BN_consttime_swap(BN_ULONG condition, BIGNUM *a, BIGNUM *b, int nwords)
960 {
961     BN_ULONG t;
962     int i;
963 
964     bn_wcheck_size(a, nwords);
965     bn_wcheck_size(b, nwords);
966 
967     condition = ((~condition & ((condition - 1))) >> (BN_BITS2 - 1)) - 1;
968 
969     t = (a->top ^ b->top) & value_barrier_bn(condition);
970     a->top ^= t;
971     b->top ^= t;
972 
973     t = (a->neg ^ b->neg) & value_barrier_bn(condition);
974     a->neg ^= t;
975     b->neg ^= t;
976 
977     /*-
978      * BN_FLG_STATIC_DATA: indicates that data may not be written to. Intention
979      * is actually to treat it as it's read-only data, and some (if not most)
980      * of it does reside in read-only segment. In other words observation of
981      * BN_FLG_STATIC_DATA in BN_consttime_swap should be treated as fatal
982      * condition. It would either cause SEGV or effectively cause data
983      * corruption.
984      *
985      * BN_FLG_MALLOCED: refers to BN structure itself, and hence must be
986      * preserved.
987      *
988      * BN_FLG_SECURE: must be preserved, because it determines how x->d was
989      * allocated and hence how to free it.
990      *
991      * BN_FLG_CONSTTIME: sufficient to mask and swap
992      *
993      * BN_FLG_FIXED_TOP: indicates that we haven't called bn_correct_top() on
994      * the data, so the d array may be padded with additional 0 values (i.e.
995      * top could be greater than the minimal value that it could be). We should
996      * be swapping it
997      */
998 
999 #define BN_CONSTTIME_SWAP_FLAGS (BN_FLG_CONSTTIME | BN_FLG_FIXED_TOP)
1000 
1001     t = ((a->flags ^ b->flags) & BN_CONSTTIME_SWAP_FLAGS) & value_barrier_bn(condition);
1002     a->flags ^= t;
1003     b->flags ^= t;
1004 
1005     /* conditionally swap the data */
1006     for (i = 0; i < nwords; i++) {
1007         t = (a->d[i] ^ b->d[i]) & value_barrier_bn(condition);
1008         a->d[i] ^= t;
1009         b->d[i] ^= t;
1010     }
1011 }
1012 
1013 #undef BN_CONSTTIME_SWAP_FLAGS
1014 
1015 /* Bits of security, see SP800-57 */
1016 
BN_security_bits(int L,int N)1017 int BN_security_bits(int L, int N)
1018 {
1019     int secbits, bits;
1020     if (L >= 15360)
1021         secbits = 256;
1022     else if (L >= 7680)
1023         secbits = 192;
1024     else if (L >= 3072)
1025         secbits = 128;
1026     else if (L >= 2048)
1027         secbits = 112;
1028     else if (L >= 1024)
1029         secbits = 80;
1030     else
1031         return 0;
1032     if (N == -1)
1033         return secbits;
1034     bits = N / 2;
1035     if (bits < 80)
1036         return 0;
1037     return bits >= secbits ? secbits : bits;
1038 }
1039 
BN_zero_ex(BIGNUM * a)1040 void BN_zero_ex(BIGNUM *a)
1041 {
1042     a->neg = 0;
1043     a->top = 0;
1044     a->flags &= ~BN_FLG_FIXED_TOP;
1045 }
1046 
BN_abs_is_word(const BIGNUM * a,const BN_ULONG w)1047 int BN_abs_is_word(const BIGNUM *a, const BN_ULONG w)
1048 {
1049     return ((a->top == 1) && (a->d[0] == w)) || ((w == 0) && (a->top == 0));
1050 }
1051 
BN_is_zero(const BIGNUM * a)1052 int BN_is_zero(const BIGNUM *a)
1053 {
1054     return a->top == 0;
1055 }
1056 
BN_is_one(const BIGNUM * a)1057 int BN_is_one(const BIGNUM *a)
1058 {
1059     return BN_abs_is_word(a, 1) && !a->neg;
1060 }
1061 
BN_is_word(const BIGNUM * a,const BN_ULONG w)1062 int BN_is_word(const BIGNUM *a, const BN_ULONG w)
1063 {
1064     return BN_abs_is_word(a, w) && (!w || !a->neg);
1065 }
1066 
ossl_bn_is_word_fixed_top(const BIGNUM * a,const BN_ULONG w)1067 int ossl_bn_is_word_fixed_top(const BIGNUM *a, const BN_ULONG w)
1068 {
1069     int res, i;
1070     const BN_ULONG *ap = a->d;
1071 
1072     if (a->neg || a->top == 0)
1073         return 0;
1074 
1075     res = constant_time_select_int(constant_time_eq_bn(ap[0], w), 1, 0);
1076 
1077     for (i = 1; i < a->top; i++)
1078         res = constant_time_select_int(constant_time_is_zero_bn(ap[i]),
1079             res, 0);
1080     return res;
1081 }
1082 
BN_is_odd(const BIGNUM * a)1083 int BN_is_odd(const BIGNUM *a)
1084 {
1085     return (a->top > 0) && (a->d[0] & 1);
1086 }
1087 
BN_is_negative(const BIGNUM * a)1088 int BN_is_negative(const BIGNUM *a)
1089 {
1090     return (a->neg != 0);
1091 }
1092 
BN_to_montgomery(BIGNUM * r,const BIGNUM * a,BN_MONT_CTX * mont,BN_CTX * ctx)1093 int BN_to_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
1094     BN_CTX *ctx)
1095 {
1096     return BN_mod_mul_montgomery(r, a, &(mont->RR), mont, ctx);
1097 }
1098 
BN_with_flags(BIGNUM * dest,const BIGNUM * b,int flags)1099 void BN_with_flags(BIGNUM *dest, const BIGNUM *b, int flags)
1100 {
1101     dest->d = b->d;
1102     dest->top = b->top;
1103     dest->dmax = b->dmax;
1104     dest->neg = b->neg;
1105     dest->flags = ((dest->flags & BN_FLG_MALLOCED)
1106         | (b->flags & ~BN_FLG_MALLOCED)
1107         | BN_FLG_STATIC_DATA | flags);
1108 }
1109 
BN_GENCB_new(void)1110 BN_GENCB *BN_GENCB_new(void)
1111 {
1112     BN_GENCB *ret;
1113 
1114     if ((ret = OPENSSL_malloc(sizeof(*ret))) == NULL)
1115         return NULL;
1116 
1117     return ret;
1118 }
1119 
BN_GENCB_free(BN_GENCB * cb)1120 void BN_GENCB_free(BN_GENCB *cb)
1121 {
1122     if (cb == NULL)
1123         return;
1124     OPENSSL_free(cb);
1125 }
1126 
BN_set_flags(BIGNUM * b,int n)1127 void BN_set_flags(BIGNUM *b, int n)
1128 {
1129     b->flags |= n;
1130 }
1131 
BN_get_flags(const BIGNUM * b,int n)1132 int BN_get_flags(const BIGNUM *b, int n)
1133 {
1134     return b->flags & n;
1135 }
1136 
1137 /* 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)1138 void BN_GENCB_set_old(BN_GENCB *gencb, void (*callback)(int, int, void *),
1139     void *cb_arg)
1140 {
1141     BN_GENCB *tmp_gencb = gencb;
1142     tmp_gencb->ver = 1;
1143     tmp_gencb->arg = cb_arg;
1144     tmp_gencb->cb.cb_1 = callback;
1145 }
1146 
1147 /* 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)1148 void BN_GENCB_set(BN_GENCB *gencb, int (*callback)(int, int, BN_GENCB *),
1149     void *cb_arg)
1150 {
1151     BN_GENCB *tmp_gencb = gencb;
1152     tmp_gencb->ver = 2;
1153     tmp_gencb->arg = cb_arg;
1154     tmp_gencb->cb.cb_2 = callback;
1155 }
1156 
BN_GENCB_get_arg(BN_GENCB * cb)1157 void *BN_GENCB_get_arg(BN_GENCB *cb)
1158 {
1159     return cb->arg;
1160 }
1161 
bn_wexpand(BIGNUM * a,int words)1162 BIGNUM *bn_wexpand(BIGNUM *a, int words)
1163 {
1164     return (words <= a->dmax) ? a : bn_expand2(a, words);
1165 }
1166 
bn_correct_top_consttime(BIGNUM * a)1167 void bn_correct_top_consttime(BIGNUM *a)
1168 {
1169     int j, atop;
1170     BN_ULONG limb;
1171     unsigned int mask;
1172 
1173     for (j = 0, atop = 0; j < a->dmax; j++) {
1174         limb = a->d[j];
1175         limb |= 0 - limb;
1176         limb >>= BN_BITS2 - 1;
1177         limb = 0 - limb;
1178         mask = (unsigned int)limb;
1179         mask &= constant_time_msb(j - a->top);
1180         atop = constant_time_select_int(mask, j + 1, atop);
1181     }
1182 
1183     mask = constant_time_eq_int(atop, 0);
1184     a->top = atop;
1185     a->neg = constant_time_select_int(mask, 0, a->neg);
1186     a->flags &= ~BN_FLG_FIXED_TOP;
1187 }
1188 
bn_correct_top(BIGNUM * a)1189 void bn_correct_top(BIGNUM *a)
1190 {
1191     BN_ULONG *ftl;
1192     int tmp_top = a->top;
1193 
1194     if (tmp_top > 0) {
1195         for (ftl = &(a->d[tmp_top]); tmp_top > 0; tmp_top--) {
1196             ftl--;
1197             if (*ftl != 0)
1198                 break;
1199         }
1200         a->top = tmp_top;
1201     }
1202     if (a->top == 0)
1203         a->neg = 0;
1204     a->flags &= ~BN_FLG_FIXED_TOP;
1205     bn_pollute(a);
1206 }
1207