xref: /dragonfly/crypto/libressl/crypto/bn/bn_lcl.h (revision e5a92d33)
1 /* $OpenBSD: bn_lcl.h,v 1.30 2018/11/05 23:52:47 tb Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2000 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 
112 #ifndef HEADER_BN_LCL_H
113 #define HEADER_BN_LCL_H
114 
115 #include <openssl/opensslconf.h>
116 
117 #include <openssl/bn.h>
118 
119 __BEGIN_HIDDEN_DECLS
120 
121 /*
122  * BN_window_bits_for_exponent_size -- macro for sliding window mod_exp functions
123  *
124  *
125  * For window size 'w' (w >= 2) and a random 'b' bits exponent,
126  * the number of multiplications is a constant plus on average
127  *
128  *    2^(w-1) + (b-w)/(w+1);
129  *
130  * here  2^(w-1)  is for precomputing the table (we actually need
131  * entries only for windows that have the lowest bit set), and
132  * (b-w)/(w+1)  is an approximation for the expected number of
133  * w-bit windows, not counting the first one.
134  *
135  * Thus we should use
136  *
137  *    w >= 6  if        b > 671
138  *     w = 5  if  671 > b > 239
139  *     w = 4  if  239 > b >  79
140  *     w = 3  if   79 > b >  23
141  *    w <= 2  if   23 > b
142  *
143  * (with draws in between).  Very small exponents are often selected
144  * with low Hamming weight, so we use  w = 1  for b <= 23.
145  */
146 #define BN_window_bits_for_exponent_size(b) \
147 		((b) > 671 ? 6 : \
148 		 (b) > 239 ? 5 : \
149 		 (b) >  79 ? 4 : \
150 		 (b) >  23 ? 3 : 1)
151 
152 
153 /* BN_mod_exp_mont_consttime is based on the assumption that the
154  * L1 data cache line width of the target processor is at least
155  * the following value.
156  */
157 #define MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH	( 64 )
158 #define MOD_EXP_CTIME_MIN_CACHE_LINE_MASK	(MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - 1)
159 
160 /* Window sizes optimized for fixed window size modular exponentiation
161  * algorithm (BN_mod_exp_mont_consttime).
162  *
163  * To achieve the security goals of BN_mode_exp_mont_consttime, the
164  * maximum size of the window must not exceed
165  * log_2(MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH).
166  *
167  * Window size thresholds are defined for cache line sizes of 32 and 64,
168  * cache line sizes where log_2(32)=5 and log_2(64)=6 respectively. A
169  * window size of 7 should only be used on processors that have a 128
170  * byte or greater cache line size.
171  */
172 #if MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 64
173 
174 #  define BN_window_bits_for_ctime_exponent_size(b) \
175 		((b) > 937 ? 6 : \
176 		 (b) > 306 ? 5 : \
177 		 (b) >  89 ? 4 : \
178 		 (b) >  22 ? 3 : 1)
179 #  define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE	(6)
180 
181 #elif MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH == 32
182 
183 #  define BN_window_bits_for_ctime_exponent_size(b) \
184 		((b) > 306 ? 5 : \
185 		 (b) >  89 ? 4 : \
186 		 (b) >  22 ? 3 : 1)
187 #  define BN_MAX_WINDOW_BITS_FOR_CTIME_EXPONENT_SIZE	(5)
188 
189 #endif
190 
191 
192 /* Pentium pro 16,16,16,32,64 */
193 /* Alpha       16,16,16,16.64 */
194 #define BN_MULL_SIZE_NORMAL			(16) /* 32 */
195 #define BN_MUL_RECURSIVE_SIZE_NORMAL		(16) /* 32 less than */
196 #define BN_SQR_RECURSIVE_SIZE_NORMAL		(16) /* 32 */
197 #define BN_MUL_LOW_RECURSIVE_SIZE_NORMAL	(32) /* 32 */
198 #define BN_MONT_CTX_SET_SIZE_WORD		(64) /* 32 */
199 
200 #if !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
201 /*
202  * BN_UMULT_HIGH section.
203  *
204  * No, I'm not trying to overwhelm you when stating that the
205  * product of N-bit numbers is 2*N bits wide:-) No, I don't expect
206  * you to be impressed when I say that if the compiler doesn't
207  * support 2*N integer type, then you have to replace every N*N
208  * multiplication with 4 (N/2)*(N/2) accompanied by some shifts
209  * and additions which unavoidably results in severe performance
210  * penalties. Of course provided that the hardware is capable of
211  * producing 2*N result... That's when you normally start
212  * considering assembler implementation. However! It should be
213  * pointed out that some CPUs (most notably Alpha, PowerPC and
214  * upcoming IA-64 family:-) provide *separate* instruction
215  * calculating the upper half of the product placing the result
216  * into a general purpose register. Now *if* the compiler supports
217  * inline assembler, then it's not impossible to implement the
218  * "bignum" routines (and have the compiler optimize 'em)
219  * exhibiting "native" performance in C. That's what BN_UMULT_HIGH
220  * macro is about:-)
221  *
222  *					<appro@fy.chalmers.se>
223  */
224 # if defined(__alpha)
225 #  if defined(__GNUC__) && __GNUC__>=2
226 #   define BN_UMULT_HIGH(a,b)	({	\
227 	BN_ULONG ret;		\
228 	asm ("umulh	%1,%2,%0"	\
229 	     : "=r"(ret)		\
230 	     : "r"(a), "r"(b));		\
231 	ret;			})
232 #  endif	/* compiler */
233 # elif defined(_ARCH_PPC) && defined(_LP64)
234 #  if defined(__GNUC__) && __GNUC__>=2
235 #   define BN_UMULT_HIGH(a,b)	({	\
236 	BN_ULONG ret;		\
237 	asm ("mulhdu	%0,%1,%2"	\
238 	     : "=r"(ret)		\
239 	     : "r"(a), "r"(b));		\
240 	ret;			})
241 #  endif	/* compiler */
242 # elif (defined(__x86_64) || defined(__x86_64__)) && defined(_LP64)
243 #  if defined(__GNUC__) && __GNUC__>=2
244 #   define BN_UMULT_HIGH(a,b)	({	\
245 	BN_ULONG ret,discard;	\
246 	asm ("mulq	%3"		\
247 	     : "=a"(discard),"=d"(ret)	\
248 	     : "a"(a), "g"(b)		\
249 	     : "cc");			\
250 	ret;			})
251 #   define BN_UMULT_LOHI(low,high,a,b)	\
252 	asm ("mulq	%3"		\
253 		: "=a"(low),"=d"(high)	\
254 		: "a"(a),"g"(b)		\
255 		: "cc");
256 #  endif
257 # elif defined(__mips) && defined(_LP64)
258 #  if defined(__GNUC__) && __GNUC__>=2
259 #   if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) /* "h" constraint is no more since 4.4 */
260 #     define BN_UMULT_HIGH(a,b)		 (((__uint128_t)(a)*(b))>>64)
261 #     define BN_UMULT_LOHI(low,high,a,b) ({	\
262 	__uint128_t ret=(__uint128_t)(a)*(b);	\
263 	(high)=ret>>64; (low)=ret;	 })
264 #   else
265 #     define BN_UMULT_HIGH(a,b)	({	\
266 	BN_ULONG ret;		\
267 	asm ("dmultu	%1,%2"		\
268 	     : "=h"(ret)		\
269 	     : "r"(a), "r"(b) : "l");	\
270 	ret;			})
271 #     define BN_UMULT_LOHI(low,high,a,b)\
272 	asm ("dmultu	%2,%3"		\
273 	     : "=l"(low),"=h"(high)	\
274 	     : "r"(a), "r"(b));
275 #    endif
276 #  endif
277 # endif		/* cpu */
278 #endif		/* OPENSSL_NO_ASM */
279 
280 /*************************************************************
281  * Using the long long type
282  */
283 #define Lw(t)    (((BN_ULONG)(t))&BN_MASK2)
284 #define Hw(t)    (((BN_ULONG)((t)>>BN_BITS2))&BN_MASK2)
285 
286 #ifdef BN_DEBUG_RAND
287 #define bn_clear_top2max(a) \
288 	{ \
289 	int      ind = (a)->dmax - (a)->top; \
290 	BN_ULONG *ftl = &(a)->d[(a)->top-1]; \
291 	for (; ind != 0; ind--) \
292 		*(++ftl) = 0x0; \
293 	}
294 #else
295 #define bn_clear_top2max(a)
296 #endif
297 
298 #ifdef BN_LLONG
299 #define mul_add(r,a,w,c) { \
300 	BN_ULLONG t; \
301 	t=(BN_ULLONG)w * (a) + (r) + (c); \
302 	(r)= Lw(t); \
303 	(c)= Hw(t); \
304 	}
305 
306 #define mul(r,a,w,c) { \
307 	BN_ULLONG t; \
308 	t=(BN_ULLONG)w * (a) + (c); \
309 	(r)= Lw(t); \
310 	(c)= Hw(t); \
311 	}
312 
313 #define sqr(r0,r1,a) { \
314 	BN_ULLONG t; \
315 	t=(BN_ULLONG)(a)*(a); \
316 	(r0)=Lw(t); \
317 	(r1)=Hw(t); \
318 	}
319 
320 #elif defined(BN_UMULT_LOHI)
321 #define mul_add(r,a,w,c) {		\
322 	BN_ULONG high,low,ret,tmp=(a);	\
323 	ret =  (r);			\
324 	BN_UMULT_LOHI(low,high,w,tmp);	\
325 	ret += (c);			\
326 	(c) =  (ret<(c))?1:0;		\
327 	(c) += high;			\
328 	ret += low;			\
329 	(c) += (ret<low)?1:0;		\
330 	(r) =  ret;			\
331 	}
332 
333 #define mul(r,a,w,c)	{		\
334 	BN_ULONG high,low,ret,ta=(a);	\
335 	BN_UMULT_LOHI(low,high,w,ta);	\
336 	ret =  low + (c);		\
337 	(c) =  high;			\
338 	(c) += (ret<low)?1:0;		\
339 	(r) =  ret;			\
340 	}
341 
342 #define sqr(r0,r1,a)	{		\
343 	BN_ULONG tmp=(a);		\
344 	BN_UMULT_LOHI(r0,r1,tmp,tmp);	\
345 	}
346 
347 #elif defined(BN_UMULT_HIGH)
348 #define mul_add(r,a,w,c) {		\
349 	BN_ULONG high,low,ret,tmp=(a);	\
350 	ret =  (r);			\
351 	high=  BN_UMULT_HIGH(w,tmp);	\
352 	ret += (c);			\
353 	low =  (w) * tmp;		\
354 	(c) =  (ret<(c))?1:0;		\
355 	(c) += high;			\
356 	ret += low;			\
357 	(c) += (ret<low)?1:0;		\
358 	(r) =  ret;			\
359 	}
360 
361 #define mul(r,a,w,c)	{		\
362 	BN_ULONG high,low,ret,ta=(a);	\
363 	low =  (w) * ta;		\
364 	high=  BN_UMULT_HIGH(w,ta);	\
365 	ret =  low + (c);		\
366 	(c) =  high;			\
367 	(c) += (ret<low)?1:0;		\
368 	(r) =  ret;			\
369 	}
370 
371 #define sqr(r0,r1,a)	{		\
372 	BN_ULONG tmp=(a);		\
373 	(r0) = tmp * tmp;		\
374 	(r1) = BN_UMULT_HIGH(tmp,tmp);	\
375 	}
376 
377 #else
378 /*************************************************************
379  * No long long type
380  */
381 
382 #define LBITS(a)	((a)&BN_MASK2l)
383 #define HBITS(a)	(((a)>>BN_BITS4)&BN_MASK2l)
384 #define	L2HBITS(a)	(((a)<<BN_BITS4)&BN_MASK2)
385 
386 #define mul64(l,h,bl,bh) \
387 	{ \
388 	BN_ULONG m,m1,lt,ht; \
389  \
390 	lt=l; \
391 	ht=h; \
392 	m =(bh)*(lt); \
393 	lt=(bl)*(lt); \
394 	m1=(bl)*(ht); \
395 	ht =(bh)*(ht); \
396 	m=(m+m1)&BN_MASK2; if (m < m1) ht+=L2HBITS((BN_ULONG)1); \
397 	ht+=HBITS(m); \
398 	m1=L2HBITS(m); \
399 	lt=(lt+m1)&BN_MASK2; if (lt < m1) ht++; \
400 	(l)=lt; \
401 	(h)=ht; \
402 	}
403 
404 #define sqr64(lo,ho,in) \
405 	{ \
406 	BN_ULONG l,h,m; \
407  \
408 	h=(in); \
409 	l=LBITS(h); \
410 	h=HBITS(h); \
411 	m =(l)*(h); \
412 	l*=l; \
413 	h*=h; \
414 	h+=(m&BN_MASK2h1)>>(BN_BITS4-1); \
415 	m =(m&BN_MASK2l)<<(BN_BITS4+1); \
416 	l=(l+m)&BN_MASK2; if (l < m) h++; \
417 	(lo)=l; \
418 	(ho)=h; \
419 	}
420 
421 #define mul_add(r,a,bl,bh,c) { \
422 	BN_ULONG l,h; \
423  \
424 	h= (a); \
425 	l=LBITS(h); \
426 	h=HBITS(h); \
427 	mul64(l,h,(bl),(bh)); \
428  \
429 	/* non-multiply part */ \
430 	l=(l+(c))&BN_MASK2; if (l < (c)) h++; \
431 	(c)=(r); \
432 	l=(l+(c))&BN_MASK2; if (l < (c)) h++; \
433 	(c)=h&BN_MASK2; \
434 	(r)=l; \
435 	}
436 
437 #define mul(r,a,bl,bh,c) { \
438 	BN_ULONG l,h; \
439  \
440 	h= (a); \
441 	l=LBITS(h); \
442 	h=HBITS(h); \
443 	mul64(l,h,(bl),(bh)); \
444  \
445 	/* non-multiply part */ \
446 	l+=(c); if ((l&BN_MASK2) < (c)) h++; \
447 	(c)=h&BN_MASK2; \
448 	(r)=l&BN_MASK2; \
449 	}
450 #endif /* !BN_LLONG */
451 
452 void bn_mul_normal(BN_ULONG *r, BN_ULONG *a, int na, BN_ULONG *b, int nb);
453 void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b);
454 void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b);
455 void bn_sqr_normal(BN_ULONG *r, const BN_ULONG *a, int n, BN_ULONG *tmp);
456 void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a);
457 void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a);
458 int bn_cmp_words(const BN_ULONG *a, const BN_ULONG *b, int n);
459 int bn_cmp_part_words(const BN_ULONG *a, const BN_ULONG *b,
460     int cl, int dl);
461 void bn_mul_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2,
462     int dna, int dnb, BN_ULONG *t);
463 void bn_mul_part_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b,
464     int n, int tna, int tnb, BN_ULONG *t);
465 void bn_sqr_recursive(BN_ULONG *r, const BN_ULONG *a, int n2, BN_ULONG *t);
466 void bn_mul_low_normal(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n);
467 void bn_mul_low_recursive(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n2,
468     BN_ULONG *t);
469 void bn_mul_high(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, BN_ULONG *l, int n2,
470     BN_ULONG *t);
471 BN_ULONG bn_add_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
472     int cl, int dl);
473 BN_ULONG bn_sub_part_words(BN_ULONG *r, const BN_ULONG *a, const BN_ULONG *b,
474     int cl, int dl);
475 int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num);
476 
477 #define bn_wexpand(a,words) (((words) <= (a)->dmax)?(a):bn_expand2((a),(words)))
478 BIGNUM *bn_expand2(BIGNUM *a, int words);
479 BIGNUM *bn_expand(BIGNUM *a, int bits);
480 
481 BIGNUM *bn_dup_expand(const BIGNUM *a, int words); /* unused */
482 
483 /* Bignum consistency macros
484  * There is one "API" macro, bn_fix_top(), for stripping leading zeroes from
485  * bignum data after direct manipulations on the data. There is also an
486  * "internal" macro, bn_check_top(), for verifying that there are no leading
487  * zeroes. Unfortunately, some auditing is required due to the fact that
488  * bn_fix_top() has become an overabused duct-tape because bignum data is
489  * occasionally passed around in an inconsistent state. So the following
490  * changes have been made to sort this out;
491  * - bn_fix_top()s implementation has been moved to bn_correct_top()
492  * - if BN_DEBUG isn't defined, bn_fix_top() maps to bn_correct_top(), and
493  *   bn_check_top() is as before.
494  * - if BN_DEBUG *is* defined;
495  *   - bn_check_top() tries to pollute unused words even if the bignum 'top' is
496  *     consistent. (ed: only if BN_DEBUG_RAND is defined)
497  *   - bn_fix_top() maps to bn_check_top() rather than "fixing" anything.
498  * The idea is to have debug builds flag up inconsistent bignums when they
499  * occur. If that occurs in a bn_fix_top(), we examine the code in question; if
500  * the use of bn_fix_top() was appropriate (ie. it follows directly after code
501  * that manipulates the bignum) it is converted to bn_correct_top(), and if it
502  * was not appropriate, we convert it permanently to bn_check_top() and track
503  * down the cause of the bug. Eventually, no internal code should be using the
504  * bn_fix_top() macro. External applications and libraries should try this with
505  * their own code too, both in terms of building against the openssl headers
506  * with BN_DEBUG defined *and* linking with a version of OpenSSL built with it
507  * defined. This not only improves external code, it provides more test
508  * coverage for openssl's own code.
509  */
510 
511 #ifdef BN_DEBUG
512 
513 /* We only need assert() when debugging */
514 #include <assert.h>
515 
516 #ifdef BN_DEBUG_RAND
517 #define bn_pollute(a) \
518 	do { \
519 		const BIGNUM *_bnum1 = (a); \
520 		if(_bnum1->top < _bnum1->dmax) { \
521 			unsigned char _tmp_char; \
522 			/* We cast away const without the compiler knowing, any \
523 			 * *genuinely* constant variables that aren't mutable \
524 			 * wouldn't be constructed with top!=dmax. */ \
525 			BN_ULONG *_not_const; \
526 			memcpy(&_not_const, &_bnum1->d, sizeof(BN_ULONG*)); \
527 			arc4random_buf(&_tmp_char, 1); \
528 			memset((unsigned char *)(_not_const + _bnum1->top), _tmp_char, \
529 				(_bnum1->dmax - _bnum1->top) * sizeof(BN_ULONG)); \
530 		} \
531 	} while(0)
532 #else
533 #define bn_pollute(a)
534 #endif
535 
536 #define bn_check_top(a) \
537 	do { \
538 		const BIGNUM *_bnum2 = (a); \
539 		if (_bnum2 != NULL) { \
540 			assert((_bnum2->top == 0) || \
541 				(_bnum2->d[_bnum2->top - 1] != 0)); \
542 			bn_pollute(_bnum2); \
543 		} \
544 	} while(0)
545 
546 #define bn_fix_top(a)		bn_check_top(a)
547 
548 #define bn_check_size(bn, bits) bn_wcheck_size(bn, ((bits+BN_BITS2-1))/BN_BITS2)
549 #define bn_wcheck_size(bn, words) \
550 	do { \
551 		const BIGNUM *_bnum2 = (bn); \
552 		assert(words <= (_bnum2)->dmax && words >= (_bnum2)->top); \
553 	} while(0)
554 
555 #else /* !BN_DEBUG */
556 
557 #define bn_pollute(a)
558 #define bn_check_top(a)
559 #define bn_fix_top(a)		bn_correct_top(a)
560 #define bn_check_size(bn, bits)
561 #define bn_wcheck_size(bn, words)
562 
563 #endif
564 
565 #define bn_correct_top(a) \
566         { \
567         BN_ULONG *ftl; \
568 	int tmp_top = (a)->top; \
569 	if (tmp_top > 0) \
570 		{ \
571 		for (ftl= &((a)->d[tmp_top-1]); tmp_top > 0; tmp_top--) \
572 			if (*(ftl--)) break; \
573 		(a)->top = tmp_top; \
574 		} \
575 	bn_pollute(a); \
576 	}
577 
578 BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w);
579 BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w);
580 void     bn_sqr_words(BN_ULONG *rp, const BN_ULONG *ap, int num);
581 BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d);
582 BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, int num);
583 BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, int num);
584 
585 int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom);
586 int bn_rand_interval(BIGNUM *rnd, const BIGNUM *lower_inc, const BIGNUM *upper_exc);
587 
588 /* Explicitly const time / non-const time versions for internal use */
589 int BN_mod_exp_ct(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
590     const BIGNUM *m, BN_CTX *ctx);
591 int BN_mod_exp_nonct(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
592     const BIGNUM *m, BN_CTX *ctx);
593 int BN_mod_exp_mont_ct(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
594     const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
595 int BN_mod_exp_mont_nonct(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
596     const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
597 int BN_div_nonct(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d,
598     BN_CTX *ctx);
599 int BN_div_ct(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d,
600     BN_CTX *ctx);
601 #define BN_mod_ct(rem,m,d,ctx) BN_div_ct(NULL,(rem),(m),(d),(ctx))
602 #define BN_mod_nonct(rem,m,d,ctx) BN_div_nonct(NULL,(rem),(m),(d),(ctx))
603 BIGNUM *BN_mod_inverse_ct(BIGNUM *ret, const BIGNUM *a, const BIGNUM *n,
604     BN_CTX *ctx);
605 BIGNUM *BN_mod_inverse_nonct(BIGNUM *ret, const BIGNUM *a, const BIGNUM *n,
606     BN_CTX *ctx);
607 int	BN_gcd_ct(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
608 int	BN_gcd_nonct(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
609 
610 int	BN_swap_ct(BN_ULONG swap, BIGNUM *a, BIGNUM *b, size_t nwords);
611 
612 __END_HIDDEN_DECLS
613 #endif
614