bn_exp.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  1. /* crypto/bn/bn_exp.c */
  2. /* Copyright (C) 1995-1998 Eric Young ([email protected])
  3. * All rights reserved.
  4. *
  5. * This package is an SSL implementation written
  6. * by Eric Young ([email protected]).
  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 ([email protected]).
  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 ([email protected])"
  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 ([email protected])"
  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-2018 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. * [email protected].
  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. * ([email protected]). This product includes software written by Tim
  108. * Hudson ([email protected]).
  109. *
  110. */
  111. #include "cryptlib.h"
  112. #include "constant_time_locl.h"
  113. #include "bn_lcl.h"
  114. #include <stdlib.h>
  115. #ifdef _WIN32
  116. # include <malloc.h>
  117. # ifndef alloca
  118. # define alloca _alloca
  119. # endif
  120. #elif defined(__GNUC__)
  121. # ifndef alloca
  122. # define alloca(s) __builtin_alloca((s))
  123. # endif
  124. #elif defined(__sun)
  125. # include <alloca.h>
  126. #endif
  127. #include "rsaz_exp.h"
  128. #undef SPARC_T4_MONT
  129. #if defined(OPENSSL_BN_ASM_MONT) && (defined(__sparc__) || defined(__sparc))
  130. # include "sparc_arch.h"
  131. extern unsigned int OPENSSL_sparcv9cap_P[];
  132. # define SPARC_T4_MONT
  133. #endif
  134. /* maximum precomputation table size for *variable* sliding windows */
  135. #define TABLE_SIZE 32
  136. /* this one works - simple but works */
  137. int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx)
  138. {
  139. int i, bits, ret = 0;
  140. BIGNUM *v, *rr;
  141. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
  142. || BN_get_flags(a, BN_FLG_CONSTTIME) != 0) {
  143. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  144. BNerr(BN_F_BN_EXP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  145. return 0;
  146. }
  147. BN_CTX_start(ctx);
  148. if ((r == a) || (r == p))
  149. rr = BN_CTX_get(ctx);
  150. else
  151. rr = r;
  152. v = BN_CTX_get(ctx);
  153. if (rr == NULL || v == NULL)
  154. goto err;
  155. if (BN_copy(v, a) == NULL)
  156. goto err;
  157. bits = BN_num_bits(p);
  158. if (BN_is_odd(p)) {
  159. if (BN_copy(rr, a) == NULL)
  160. goto err;
  161. } else {
  162. if (!BN_one(rr))
  163. goto err;
  164. }
  165. for (i = 1; i < bits; i++) {
  166. if (!BN_sqr(v, v, ctx))
  167. goto err;
  168. if (BN_is_bit_set(p, i)) {
  169. if (!BN_mul(rr, rr, v, ctx))
  170. goto err;
  171. }
  172. }
  173. if (r != rr && BN_copy(r, rr) == NULL)
  174. goto err;
  175. ret = 1;
  176. err:
  177. BN_CTX_end(ctx);
  178. bn_check_top(r);
  179. return (ret);
  180. }
  181. int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, const BIGNUM *m,
  182. BN_CTX *ctx)
  183. {
  184. int ret;
  185. bn_check_top(a);
  186. bn_check_top(p);
  187. bn_check_top(m);
  188. /*-
  189. * For even modulus m = 2^k*m_odd, it might make sense to compute
  190. * a^p mod m_odd and a^p mod 2^k separately (with Montgomery
  191. * exponentiation for the odd part), using appropriate exponent
  192. * reductions, and combine the results using the CRT.
  193. *
  194. * For now, we use Montgomery only if the modulus is odd; otherwise,
  195. * exponentiation using the reciprocal-based quick remaindering
  196. * algorithm is used.
  197. *
  198. * (Timing obtained with expspeed.c [computations a^p mod m
  199. * where a, p, m are of the same length: 256, 512, 1024, 2048,
  200. * 4096, 8192 bits], compared to the running time of the
  201. * standard algorithm:
  202. *
  203. * BN_mod_exp_mont 33 .. 40 % [AMD K6-2, Linux, debug configuration]
  204. * 55 .. 77 % [UltraSparc processor, but
  205. * debug-solaris-sparcv8-gcc conf.]
  206. *
  207. * BN_mod_exp_recp 50 .. 70 % [AMD K6-2, Linux, debug configuration]
  208. * 62 .. 118 % [UltraSparc, debug-solaris-sparcv8-gcc]
  209. *
  210. * On the Sparc, BN_mod_exp_recp was faster than BN_mod_exp_mont
  211. * at 2048 and more bits, but at 512 and 1024 bits, it was
  212. * slower even than the standard algorithm!
  213. *
  214. * "Real" timings [linux-elf, solaris-sparcv9-gcc configurations]
  215. * should be obtained when the new Montgomery reduction code
  216. * has been integrated into OpenSSL.)
  217. */
  218. #define MONT_MUL_MOD
  219. #define MONT_EXP_WORD
  220. #define RECP_MUL_MOD
  221. #ifdef MONT_MUL_MOD
  222. /*
  223. * I have finally been able to take out this pre-condition of the top bit
  224. * being set. It was caused by an error in BN_div with negatives. There
  225. * was also another problem when for a^b%m a >= m. eay 07-May-97
  226. */
  227. /* if ((m->d[m->top-1]&BN_TBIT) && BN_is_odd(m)) */
  228. if (BN_is_odd(m)) {
  229. # ifdef MONT_EXP_WORD
  230. if (a->top == 1 && !a->neg
  231. && (BN_get_flags(p, BN_FLG_CONSTTIME) == 0)
  232. && (BN_get_flags(a, BN_FLG_CONSTTIME) == 0)
  233. && (BN_get_flags(m, BN_FLG_CONSTTIME) == 0)) {
  234. BN_ULONG A = a->d[0];
  235. ret = BN_mod_exp_mont_word(r, A, p, m, ctx, NULL);
  236. } else
  237. # endif
  238. ret = BN_mod_exp_mont(r, a, p, m, ctx, NULL);
  239. } else
  240. #endif
  241. #ifdef RECP_MUL_MOD
  242. {
  243. ret = BN_mod_exp_recp(r, a, p, m, ctx);
  244. }
  245. #else
  246. {
  247. ret = BN_mod_exp_simple(r, a, p, m, ctx);
  248. }
  249. #endif
  250. bn_check_top(r);
  251. return (ret);
  252. }
  253. int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
  254. const BIGNUM *m, BN_CTX *ctx)
  255. {
  256. int i, j, bits, ret = 0, wstart, wend, window, wvalue;
  257. int start = 1;
  258. BIGNUM *aa;
  259. /* Table of variables obtained from 'ctx' */
  260. BIGNUM *val[TABLE_SIZE];
  261. BN_RECP_CTX recp;
  262. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
  263. || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
  264. || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
  265. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  266. BNerr(BN_F_BN_MOD_EXP_RECP, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  267. return 0;
  268. }
  269. bits = BN_num_bits(p);
  270. if (bits == 0) {
  271. /* x**0 mod 1 is still zero. */
  272. if (BN_is_one(m)) {
  273. ret = 1;
  274. BN_zero(r);
  275. } else {
  276. ret = BN_one(r);
  277. }
  278. return ret;
  279. }
  280. BN_CTX_start(ctx);
  281. aa = BN_CTX_get(ctx);
  282. val[0] = BN_CTX_get(ctx);
  283. if (!aa || !val[0])
  284. goto err;
  285. BN_RECP_CTX_init(&recp);
  286. if (m->neg) {
  287. /* ignore sign of 'm' */
  288. if (!BN_copy(aa, m))
  289. goto err;
  290. aa->neg = 0;
  291. if (BN_RECP_CTX_set(&recp, aa, ctx) <= 0)
  292. goto err;
  293. } else {
  294. if (BN_RECP_CTX_set(&recp, m, ctx) <= 0)
  295. goto err;
  296. }
  297. if (!BN_nnmod(val[0], a, m, ctx))
  298. goto err; /* 1 */
  299. if (BN_is_zero(val[0])) {
  300. BN_zero(r);
  301. ret = 1;
  302. goto err;
  303. }
  304. window = BN_window_bits_for_exponent_size(bits);
  305. if (window > 1) {
  306. if (!BN_mod_mul_reciprocal(aa, val[0], val[0], &recp, ctx))
  307. goto err; /* 2 */
  308. j = 1 << (window - 1);
  309. for (i = 1; i < j; i++) {
  310. if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
  311. !BN_mod_mul_reciprocal(val[i], val[i - 1], aa, &recp, ctx))
  312. goto err;
  313. }
  314. }
  315. start = 1; /* This is used to avoid multiplication etc
  316. * when there is only the value '1' in the
  317. * buffer. */
  318. wvalue = 0; /* The 'value' of the window */
  319. wstart = bits - 1; /* The top bit of the window */
  320. wend = 0; /* The bottom bit of the window */
  321. if (!BN_one(r))
  322. goto err;
  323. for (;;) {
  324. if (BN_is_bit_set(p, wstart) == 0) {
  325. if (!start)
  326. if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
  327. goto err;
  328. if (wstart == 0)
  329. break;
  330. wstart--;
  331. continue;
  332. }
  333. /*
  334. * We now have wstart on a 'set' bit, we now need to work out how bit
  335. * a window to do. To do this we need to scan forward until the last
  336. * set bit before the end of the window
  337. */
  338. j = wstart;
  339. wvalue = 1;
  340. wend = 0;
  341. for (i = 1; i < window; i++) {
  342. if (wstart - i < 0)
  343. break;
  344. if (BN_is_bit_set(p, wstart - i)) {
  345. wvalue <<= (i - wend);
  346. wvalue |= 1;
  347. wend = i;
  348. }
  349. }
  350. /* wend is the size of the current window */
  351. j = wend + 1;
  352. /* add the 'bytes above' */
  353. if (!start)
  354. for (i = 0; i < j; i++) {
  355. if (!BN_mod_mul_reciprocal(r, r, r, &recp, ctx))
  356. goto err;
  357. }
  358. /* wvalue will be an odd number < 2^window */
  359. if (!BN_mod_mul_reciprocal(r, r, val[wvalue >> 1], &recp, ctx))
  360. goto err;
  361. /* move the 'window' down further */
  362. wstart -= wend + 1;
  363. wvalue = 0;
  364. start = 0;
  365. if (wstart < 0)
  366. break;
  367. }
  368. ret = 1;
  369. err:
  370. BN_CTX_end(ctx);
  371. BN_RECP_CTX_free(&recp);
  372. bn_check_top(r);
  373. return (ret);
  374. }
  375. int BN_mod_exp_mont(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
  376. const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
  377. {
  378. int i, j, bits, ret = 0, wstart, wend, window, wvalue;
  379. int start = 1;
  380. BIGNUM *d, *r;
  381. const BIGNUM *aa;
  382. /* Table of variables obtained from 'ctx' */
  383. BIGNUM *val[TABLE_SIZE];
  384. BN_MONT_CTX *mont = NULL;
  385. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
  386. || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
  387. || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
  388. return BN_mod_exp_mont_consttime(rr, a, p, m, ctx, in_mont);
  389. }
  390. bn_check_top(a);
  391. bn_check_top(p);
  392. bn_check_top(m);
  393. if (!BN_is_odd(m)) {
  394. BNerr(BN_F_BN_MOD_EXP_MONT, BN_R_CALLED_WITH_EVEN_MODULUS);
  395. return (0);
  396. }
  397. bits = BN_num_bits(p);
  398. if (bits == 0) {
  399. /* x**0 mod 1 is still zero. */
  400. if (BN_is_one(m)) {
  401. ret = 1;
  402. BN_zero(rr);
  403. } else {
  404. ret = BN_one(rr);
  405. }
  406. return ret;
  407. }
  408. BN_CTX_start(ctx);
  409. d = BN_CTX_get(ctx);
  410. r = BN_CTX_get(ctx);
  411. val[0] = BN_CTX_get(ctx);
  412. if (!d || !r || !val[0])
  413. goto err;
  414. /*
  415. * If this is not done, things will break in the montgomery part
  416. */
  417. if (in_mont != NULL)
  418. mont = in_mont;
  419. else {
  420. if ((mont = BN_MONT_CTX_new()) == NULL)
  421. goto err;
  422. if (!BN_MONT_CTX_set(mont, m, ctx))
  423. goto err;
  424. }
  425. if (a->neg || BN_ucmp(a, m) >= 0) {
  426. if (!BN_nnmod(val[0], a, m, ctx))
  427. goto err;
  428. aa = val[0];
  429. } else
  430. aa = a;
  431. if (BN_is_zero(aa)) {
  432. BN_zero(rr);
  433. ret = 1;
  434. goto err;
  435. }
  436. if (!BN_to_montgomery(val[0], aa, mont, ctx))
  437. goto err; /* 1 */
  438. window = BN_window_bits_for_exponent_size(bits);
  439. if (window > 1) {
  440. if (!BN_mod_mul_montgomery(d, val[0], val[0], mont, ctx))
  441. goto err; /* 2 */
  442. j = 1 << (window - 1);
  443. for (i = 1; i < j; i++) {
  444. if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
  445. !BN_mod_mul_montgomery(val[i], val[i - 1], d, mont, ctx))
  446. goto err;
  447. }
  448. }
  449. start = 1; /* This is used to avoid multiplication etc
  450. * when there is only the value '1' in the
  451. * buffer. */
  452. wvalue = 0; /* The 'value' of the window */
  453. wstart = bits - 1; /* The top bit of the window */
  454. wend = 0; /* The bottom bit of the window */
  455. #if 1 /* by Shay Gueron's suggestion */
  456. j = m->top; /* borrow j */
  457. if (m->d[j - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
  458. if (bn_wexpand(r, j) == NULL)
  459. goto err;
  460. /* 2^(top*BN_BITS2) - m */
  461. r->d[0] = (0 - m->d[0]) & BN_MASK2;
  462. for (i = 1; i < j; i++)
  463. r->d[i] = (~m->d[i]) & BN_MASK2;
  464. r->top = j;
  465. /*
  466. * Upper words will be zero if the corresponding words of 'm' were
  467. * 0xfff[...], so decrement r->top accordingly.
  468. */
  469. bn_correct_top(r);
  470. } else
  471. #endif
  472. if (!BN_to_montgomery(r, BN_value_one(), mont, ctx))
  473. goto err;
  474. for (;;) {
  475. if (BN_is_bit_set(p, wstart) == 0) {
  476. if (!start) {
  477. if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
  478. goto err;
  479. }
  480. if (wstart == 0)
  481. break;
  482. wstart--;
  483. continue;
  484. }
  485. /*
  486. * We now have wstart on a 'set' bit, we now need to work out how bit
  487. * a window to do. To do this we need to scan forward until the last
  488. * set bit before the end of the window
  489. */
  490. j = wstart;
  491. wvalue = 1;
  492. wend = 0;
  493. for (i = 1; i < window; i++) {
  494. if (wstart - i < 0)
  495. break;
  496. if (BN_is_bit_set(p, wstart - i)) {
  497. wvalue <<= (i - wend);
  498. wvalue |= 1;
  499. wend = i;
  500. }
  501. }
  502. /* wend is the size of the current window */
  503. j = wend + 1;
  504. /* add the 'bytes above' */
  505. if (!start)
  506. for (i = 0; i < j; i++) {
  507. if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
  508. goto err;
  509. }
  510. /* wvalue will be an odd number < 2^window */
  511. if (!BN_mod_mul_montgomery(r, r, val[wvalue >> 1], mont, ctx))
  512. goto err;
  513. /* move the 'window' down further */
  514. wstart -= wend + 1;
  515. wvalue = 0;
  516. start = 0;
  517. if (wstart < 0)
  518. break;
  519. }
  520. #if defined(SPARC_T4_MONT)
  521. if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
  522. j = mont->N.top; /* borrow j */
  523. val[0]->d[0] = 1; /* borrow val[0] */
  524. for (i = 1; i < j; i++)
  525. val[0]->d[i] = 0;
  526. val[0]->top = j;
  527. if (!BN_mod_mul_montgomery(rr, r, val[0], mont, ctx))
  528. goto err;
  529. } else
  530. #endif
  531. if (!BN_from_montgomery(rr, r, mont, ctx))
  532. goto err;
  533. ret = 1;
  534. err:
  535. if ((in_mont == NULL) && (mont != NULL))
  536. BN_MONT_CTX_free(mont);
  537. BN_CTX_end(ctx);
  538. bn_check_top(rr);
  539. return (ret);
  540. }
  541. #if defined(SPARC_T4_MONT)
  542. static BN_ULONG bn_get_bits(const BIGNUM *a, int bitpos)
  543. {
  544. BN_ULONG ret = 0;
  545. int wordpos;
  546. wordpos = bitpos / BN_BITS2;
  547. bitpos %= BN_BITS2;
  548. if (wordpos >= 0 && wordpos < a->top) {
  549. ret = a->d[wordpos] & BN_MASK2;
  550. if (bitpos) {
  551. ret >>= bitpos;
  552. if (++wordpos < a->top)
  553. ret |= a->d[wordpos] << (BN_BITS2 - bitpos);
  554. }
  555. }
  556. return ret & BN_MASK2;
  557. }
  558. #endif
  559. /*
  560. * BN_mod_exp_mont_consttime() stores the precomputed powers in a specific
  561. * layout so that accessing any of these table values shows the same access
  562. * pattern as far as cache lines are concerned. The following functions are
  563. * used to transfer a BIGNUM from/to that table.
  564. */
  565. static int MOD_EXP_CTIME_COPY_TO_PREBUF(const BIGNUM *b, int top,
  566. unsigned char *buf, int idx,
  567. int window)
  568. {
  569. int i, j;
  570. int width = 1 << window;
  571. BN_ULONG *table = (BN_ULONG *)buf;
  572. if (top > b->top)
  573. top = b->top; /* this works because 'buf' is explicitly
  574. * zeroed */
  575. for (i = 0, j = idx; i < top; i++, j += width) {
  576. table[j] = b->d[i];
  577. }
  578. return 1;
  579. }
  580. static int MOD_EXP_CTIME_COPY_FROM_PREBUF(BIGNUM *b, int top,
  581. unsigned char *buf, int idx,
  582. int window)
  583. {
  584. int i, j;
  585. int width = 1 << window;
  586. volatile BN_ULONG *table = (volatile BN_ULONG *)buf;
  587. if (bn_wexpand(b, top) == NULL)
  588. return 0;
  589. if (window <= 3) {
  590. for (i = 0; i < top; i++, table += width) {
  591. BN_ULONG acc = 0;
  592. for (j = 0; j < width; j++) {
  593. acc |= table[j] &
  594. ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
  595. }
  596. b->d[i] = acc;
  597. }
  598. } else {
  599. int xstride = 1 << (window - 2);
  600. BN_ULONG y0, y1, y2, y3;
  601. i = idx >> (window - 2); /* equivalent of idx / xstride */
  602. idx &= xstride - 1; /* equivalent of idx % xstride */
  603. y0 = (BN_ULONG)0 - (constant_time_eq_int(i,0)&1);
  604. y1 = (BN_ULONG)0 - (constant_time_eq_int(i,1)&1);
  605. y2 = (BN_ULONG)0 - (constant_time_eq_int(i,2)&1);
  606. y3 = (BN_ULONG)0 - (constant_time_eq_int(i,3)&1);
  607. for (i = 0; i < top; i++, table += width) {
  608. BN_ULONG acc = 0;
  609. for (j = 0; j < xstride; j++) {
  610. acc |= ( (table[j + 0 * xstride] & y0) |
  611. (table[j + 1 * xstride] & y1) |
  612. (table[j + 2 * xstride] & y2) |
  613. (table[j + 3 * xstride] & y3) )
  614. & ((BN_ULONG)0 - (constant_time_eq_int(j,idx)&1));
  615. }
  616. b->d[i] = acc;
  617. }
  618. }
  619. b->top = top;
  620. bn_correct_top(b);
  621. return 1;
  622. }
  623. /*
  624. * Given a pointer value, compute the next address that is a cache line
  625. * multiple.
  626. */
  627. #define MOD_EXP_CTIME_ALIGN(x_) \
  628. ((unsigned char*)(x_) + (MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH - (((size_t)(x_)) & (MOD_EXP_CTIME_MIN_CACHE_LINE_MASK))))
  629. /*
  630. * This variant of BN_mod_exp_mont() uses fixed windows and the special
  631. * precomputation memory layout to limit data-dependency to a minimum to
  632. * protect secret exponents (cf. the hyper-threading timing attacks pointed
  633. * out by Colin Percival,
  634. * http://www.daemonology.net/hyperthreading-considered-harmful/)
  635. */
  636. int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
  637. const BIGNUM *m, BN_CTX *ctx,
  638. BN_MONT_CTX *in_mont)
  639. {
  640. int i, bits, ret = 0, window, wvalue;
  641. int top;
  642. BN_MONT_CTX *mont = NULL;
  643. int numPowers;
  644. unsigned char *powerbufFree = NULL;
  645. int powerbufLen = 0;
  646. unsigned char *powerbuf = NULL;
  647. BIGNUM tmp, am;
  648. #if defined(SPARC_T4_MONT)
  649. unsigned int t4 = 0;
  650. #endif
  651. bn_check_top(a);
  652. bn_check_top(p);
  653. bn_check_top(m);
  654. if (!BN_is_odd(m)) {
  655. BNerr(BN_F_BN_MOD_EXP_MONT_CONSTTIME, BN_R_CALLED_WITH_EVEN_MODULUS);
  656. return (0);
  657. }
  658. top = m->top;
  659. /*
  660. * Use all bits stored in |p|, rather than |BN_num_bits|, so we do not leak
  661. * whether the top bits are zero.
  662. */
  663. bits = p->top * BN_BITS2;
  664. if (bits == 0) {
  665. /* x**0 mod 1 is still zero. */
  666. if (BN_is_one(m)) {
  667. ret = 1;
  668. BN_zero(rr);
  669. } else {
  670. ret = BN_one(rr);
  671. }
  672. return ret;
  673. }
  674. BN_CTX_start(ctx);
  675. /*
  676. * Allocate a montgomery context if it was not supplied by the caller. If
  677. * this is not done, things will break in the montgomery part.
  678. */
  679. if (in_mont != NULL)
  680. mont = in_mont;
  681. else {
  682. if ((mont = BN_MONT_CTX_new()) == NULL)
  683. goto err;
  684. if (!BN_MONT_CTX_set(mont, m, ctx))
  685. goto err;
  686. }
  687. #ifdef RSAZ_ENABLED
  688. /*
  689. * If the size of the operands allow it, perform the optimized
  690. * RSAZ exponentiation. For further information see
  691. * crypto/bn/rsaz_exp.c and accompanying assembly modules.
  692. */
  693. if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024)
  694. && rsaz_avx2_eligible()) {
  695. if (NULL == bn_wexpand(rr, 16))
  696. goto err;
  697. RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d,
  698. mont->n0[0]);
  699. rr->top = 16;
  700. rr->neg = 0;
  701. bn_correct_top(rr);
  702. ret = 1;
  703. goto err;
  704. } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {
  705. if (NULL == bn_wexpand(rr, 8))
  706. goto err;
  707. RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);
  708. rr->top = 8;
  709. rr->neg = 0;
  710. bn_correct_top(rr);
  711. ret = 1;
  712. goto err;
  713. }
  714. #endif
  715. /* Get the window size to use with size of p. */
  716. window = BN_window_bits_for_ctime_exponent_size(bits);
  717. #if defined(SPARC_T4_MONT)
  718. if (window >= 5 && (top & 15) == 0 && top <= 64 &&
  719. (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) ==
  720. (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0]))
  721. window = 5;
  722. else
  723. #endif
  724. #if defined(OPENSSL_BN_ASM_MONT5)
  725. if (window >= 5) {
  726. window = 5; /* ~5% improvement for RSA2048 sign, and even
  727. * for RSA4096 */
  728. /* reserve space for mont->N.d[] copy */
  729. powerbufLen += top * sizeof(mont->N.d[0]);
  730. }
  731. #endif
  732. (void)0;
  733. /*
  734. * Allocate a buffer large enough to hold all of the pre-computed powers
  735. * of am, am itself and tmp.
  736. */
  737. numPowers = 1 << window;
  738. powerbufLen += sizeof(m->d[0]) * (top * numPowers +
  739. ((2 * top) >
  740. numPowers ? (2 * top) : numPowers));
  741. #ifdef alloca
  742. if (powerbufLen < 3072)
  743. powerbufFree =
  744. alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
  745. else
  746. #endif
  747. if ((powerbufFree =
  748. (unsigned char *)OPENSSL_malloc(powerbufLen +
  749. MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))
  750. == NULL)
  751. goto err;
  752. powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
  753. memset(powerbuf, 0, powerbufLen);
  754. #ifdef alloca
  755. if (powerbufLen < 3072)
  756. powerbufFree = NULL;
  757. #endif
  758. /* lay down tmp and am right after powers table */
  759. tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
  760. am.d = tmp.d + top;
  761. tmp.top = am.top = 0;
  762. tmp.dmax = am.dmax = top;
  763. tmp.neg = am.neg = 0;
  764. tmp.flags = am.flags = BN_FLG_STATIC_DATA;
  765. /* prepare a^0 in Montgomery domain */
  766. #if 1 /* by Shay Gueron's suggestion */
  767. if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
  768. /* 2^(top*BN_BITS2) - m */
  769. tmp.d[0] = (0 - m->d[0]) & BN_MASK2;
  770. for (i = 1; i < top; i++)
  771. tmp.d[i] = (~m->d[i]) & BN_MASK2;
  772. tmp.top = top;
  773. } else
  774. #endif
  775. if (!BN_to_montgomery(&tmp, BN_value_one(), mont, ctx))
  776. goto err;
  777. /* prepare a^1 in Montgomery domain */
  778. if (a->neg || BN_ucmp(a, m) >= 0) {
  779. if (!BN_mod(&am, a, m, ctx))
  780. goto err;
  781. if (!BN_to_montgomery(&am, &am, mont, ctx))
  782. goto err;
  783. } else if (!BN_to_montgomery(&am, a, mont, ctx))
  784. goto err;
  785. #if defined(SPARC_T4_MONT)
  786. if (t4) {
  787. typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np,
  788. const BN_ULONG *n0, const void *table,
  789. int power, int bits);
  790. int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np,
  791. const BN_ULONG *n0, const void *table,
  792. int power, int bits);
  793. int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np,
  794. const BN_ULONG *n0, const void *table,
  795. int power, int bits);
  796. int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np,
  797. const BN_ULONG *n0, const void *table,
  798. int power, int bits);
  799. int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np,
  800. const BN_ULONG *n0, const void *table,
  801. int power, int bits);
  802. static const bn_pwr5_mont_f pwr5_funcs[4] = {
  803. bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16,
  804. bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32
  805. };
  806. bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1];
  807. typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap,
  808. const void *bp, const BN_ULONG *np,
  809. const BN_ULONG *n0);
  810. int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp,
  811. const BN_ULONG *np, const BN_ULONG *n0);
  812. int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap,
  813. const void *bp, const BN_ULONG *np,
  814. const BN_ULONG *n0);
  815. int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap,
  816. const void *bp, const BN_ULONG *np,
  817. const BN_ULONG *n0);
  818. int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap,
  819. const void *bp, const BN_ULONG *np,
  820. const BN_ULONG *n0);
  821. static const bn_mul_mont_f mul_funcs[4] = {
  822. bn_mul_mont_t4_8, bn_mul_mont_t4_16,
  823. bn_mul_mont_t4_24, bn_mul_mont_t4_32
  824. };
  825. bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1];
  826. void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap,
  827. const void *bp, const BN_ULONG *np,
  828. const BN_ULONG *n0, int num);
  829. void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap,
  830. const void *bp, const BN_ULONG *np,
  831. const BN_ULONG *n0, int num);
  832. void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap,
  833. const void *table, const BN_ULONG *np,
  834. const BN_ULONG *n0, int num, int power);
  835. void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num,
  836. void *table, size_t power);
  837. void bn_gather5_t4(BN_ULONG *out, size_t num,
  838. void *table, size_t power);
  839. void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num);
  840. BN_ULONG *np = mont->N.d, *n0 = mont->n0;
  841. int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less
  842. * than 32 */
  843. /*
  844. * BN_to_montgomery can contaminate words above .top [in
  845. * BN_DEBUG[_DEBUG] build]...
  846. */
  847. for (i = am.top; i < top; i++)
  848. am.d[i] = 0;
  849. for (i = tmp.top; i < top; i++)
  850. tmp.d[i] = 0;
  851. bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0);
  852. bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1);
  853. if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) &&
  854. !(*mul_worker) (tmp.d, am.d, am.d, np, n0))
  855. bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top);
  856. bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2);
  857. for (i = 3; i < 32; i++) {
  858. /* Calculate a^i = a^(i-1) * a */
  859. if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) &&
  860. !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0))
  861. bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top);
  862. bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i);
  863. }
  864. /* switch to 64-bit domain */
  865. np = alloca(top * sizeof(BN_ULONG));
  866. top /= 2;
  867. bn_flip_t4(np, mont->N.d, top);
  868. bits--;
  869. for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
  870. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  871. bn_gather5_t4(tmp.d, top, powerbuf, wvalue);
  872. /*
  873. * Scan the exponent one window at a time starting from the most
  874. * significant bits.
  875. */
  876. while (bits >= 0) {
  877. if (bits < stride)
  878. stride = bits + 1;
  879. bits -= stride;
  880. wvalue = bn_get_bits(p, bits + 1);
  881. if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
  882. continue;
  883. /* retry once and fall back */
  884. if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
  885. continue;
  886. bits += stride - 5;
  887. wvalue >>= stride - 5;
  888. wvalue &= 31;
  889. bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
  890. bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
  891. bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
  892. bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
  893. bn_mul_mont_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
  894. bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top,
  895. wvalue);
  896. }
  897. bn_flip_t4(tmp.d, tmp.d, top);
  898. top *= 2;
  899. /* back to 32-bit domain */
  900. tmp.top = top;
  901. bn_correct_top(&tmp);
  902. OPENSSL_cleanse(np, top * sizeof(BN_ULONG));
  903. } else
  904. #endif
  905. #if defined(OPENSSL_BN_ASM_MONT5)
  906. if (window == 5 && top > 1) {
  907. /*
  908. * This optimization uses ideas from http://eprint.iacr.org/2011/239,
  909. * specifically optimization of cache-timing attack countermeasures
  910. * and pre-computation optimization.
  911. */
  912. /*
  913. * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
  914. * 512-bit RSA is hardly relevant, we omit it to spare size...
  915. */
  916. void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
  917. const void *table, const BN_ULONG *np,
  918. const BN_ULONG *n0, int num, int power);
  919. void bn_scatter5(const BN_ULONG *inp, size_t num,
  920. void *table, size_t power);
  921. void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
  922. void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,
  923. const void *table, const BN_ULONG *np,
  924. const BN_ULONG *n0, int num, int power);
  925. int bn_get_bits5(const BN_ULONG *ap, int off);
  926. int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap,
  927. const BN_ULONG *not_used, const BN_ULONG *np,
  928. const BN_ULONG *n0, int num);
  929. BN_ULONG *n0 = mont->n0, *np;
  930. /*
  931. * BN_to_montgomery can contaminate words above .top [in
  932. * BN_DEBUG[_DEBUG] build]...
  933. */
  934. for (i = am.top; i < top; i++)
  935. am.d[i] = 0;
  936. for (i = tmp.top; i < top; i++)
  937. tmp.d[i] = 0;
  938. /*
  939. * copy mont->N.d[] to improve cache locality
  940. */
  941. for (np = am.d + top, i = 0; i < top; i++)
  942. np[i] = mont->N.d[i];
  943. bn_scatter5(tmp.d, top, powerbuf, 0);
  944. bn_scatter5(am.d, am.top, powerbuf, 1);
  945. bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
  946. bn_scatter5(tmp.d, top, powerbuf, 2);
  947. # if 0
  948. for (i = 3; i < 32; i++) {
  949. /* Calculate a^i = a^(i-1) * a */
  950. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  951. bn_scatter5(tmp.d, top, powerbuf, i);
  952. }
  953. # else
  954. /* same as above, but uses squaring for 1/2 of operations */
  955. for (i = 4; i < 32; i *= 2) {
  956. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  957. bn_scatter5(tmp.d, top, powerbuf, i);
  958. }
  959. for (i = 3; i < 8; i += 2) {
  960. int j;
  961. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  962. bn_scatter5(tmp.d, top, powerbuf, i);
  963. for (j = 2 * i; j < 32; j *= 2) {
  964. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  965. bn_scatter5(tmp.d, top, powerbuf, j);
  966. }
  967. }
  968. for (; i < 16; i += 2) {
  969. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  970. bn_scatter5(tmp.d, top, powerbuf, i);
  971. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  972. bn_scatter5(tmp.d, top, powerbuf, 2 * i);
  973. }
  974. for (; i < 32; i += 2) {
  975. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  976. bn_scatter5(tmp.d, top, powerbuf, i);
  977. }
  978. # endif
  979. bits--;
  980. for (wvalue = 0, i = bits % 5; i >= 0; i--, bits--)
  981. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  982. bn_gather5(tmp.d, top, powerbuf, wvalue);
  983. /*
  984. * Scan the exponent one window at a time starting from the most
  985. * significant bits.
  986. */
  987. if (top & 7)
  988. while (bits >= 0) {
  989. for (wvalue = 0, i = 0; i < 5; i++, bits--)
  990. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  991. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  992. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  993. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  994. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  995. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  996. bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,
  997. wvalue);
  998. } else {
  999. while (bits >= 0) {
  1000. wvalue = bn_get_bits5(p->d, bits - 4);
  1001. bits -= 5;
  1002. bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top, wvalue);
  1003. }
  1004. }
  1005. ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top);
  1006. tmp.top = top;
  1007. bn_correct_top(&tmp);
  1008. if (ret) {
  1009. if (!BN_copy(rr, &tmp))
  1010. ret = 0;
  1011. goto err; /* non-zero ret means it's not error */
  1012. }
  1013. } else
  1014. #endif
  1015. {
  1016. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window))
  1017. goto err;
  1018. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window))
  1019. goto err;
  1020. /*
  1021. * If the window size is greater than 1, then calculate
  1022. * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
  1023. * powers could instead be computed as (a^(i/2))^2 to use the slight
  1024. * performance advantage of sqr over mul).
  1025. */
  1026. if (window > 1) {
  1027. if (!BN_mod_mul_montgomery(&tmp, &am, &am, mont, ctx))
  1028. goto err;
  1029. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
  1030. window))
  1031. goto err;
  1032. for (i = 3; i < numPowers; i++) {
  1033. /* Calculate a^i = a^(i-1) * a */
  1034. if (!BN_mod_mul_montgomery(&tmp, &am, &tmp, mont, ctx))
  1035. goto err;
  1036. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
  1037. window))
  1038. goto err;
  1039. }
  1040. }
  1041. bits--;
  1042. for (wvalue = 0, i = bits % window; i >= 0; i--, bits--)
  1043. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  1044. if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue,
  1045. window))
  1046. goto err;
  1047. /*
  1048. * Scan the exponent one window at a time starting from the most
  1049. * significant bits.
  1050. */
  1051. while (bits >= 0) {
  1052. wvalue = 0; /* The 'value' of the window */
  1053. /* Scan the window, squaring the result as we go */
  1054. for (i = 0; i < window; i++, bits--) {
  1055. if (!BN_mod_mul_montgomery(&tmp, &tmp, &tmp, mont, ctx))
  1056. goto err;
  1057. wvalue = (wvalue << 1) + BN_is_bit_set(p, bits);
  1058. }
  1059. /*
  1060. * Fetch the appropriate pre-computed value from the pre-buf
  1061. */
  1062. if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue,
  1063. window))
  1064. goto err;
  1065. /* Multiply the result into the intermediate result */
  1066. if (!BN_mod_mul_montgomery(&tmp, &tmp, &am, mont, ctx))
  1067. goto err;
  1068. }
  1069. }
  1070. /* Convert the final result from montgomery to standard format */
  1071. #if defined(SPARC_T4_MONT)
  1072. if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
  1073. am.d[0] = 1; /* borrow am */
  1074. for (i = 1; i < top; i++)
  1075. am.d[i] = 0;
  1076. if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))
  1077. goto err;
  1078. } else
  1079. #endif
  1080. if (!BN_from_montgomery(rr, &tmp, mont, ctx))
  1081. goto err;
  1082. ret = 1;
  1083. err:
  1084. if ((in_mont == NULL) && (mont != NULL))
  1085. BN_MONT_CTX_free(mont);
  1086. if (powerbuf != NULL) {
  1087. OPENSSL_cleanse(powerbuf, powerbufLen);
  1088. if (powerbufFree)
  1089. OPENSSL_free(powerbufFree);
  1090. }
  1091. BN_CTX_end(ctx);
  1092. return (ret);
  1093. }
  1094. int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
  1095. const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
  1096. {
  1097. BN_MONT_CTX *mont = NULL;
  1098. int b, bits, ret = 0;
  1099. int r_is_one;
  1100. BN_ULONG w, next_w;
  1101. BIGNUM *d, *r, *t;
  1102. BIGNUM *swap_tmp;
  1103. #define BN_MOD_MUL_WORD(r, w, m) \
  1104. (BN_mul_word(r, (w)) && \
  1105. (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
  1106. (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
  1107. /*
  1108. * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
  1109. * probably more overhead than always using BN_mod (which uses BN_copy if
  1110. * a similar test returns true).
  1111. */
  1112. /*
  1113. * We can use BN_mod and do not need BN_nnmod because our accumulator is
  1114. * never negative (the result of BN_mod does not depend on the sign of
  1115. * the modulus).
  1116. */
  1117. #define BN_TO_MONTGOMERY_WORD(r, w, mont) \
  1118. (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
  1119. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
  1120. || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
  1121. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  1122. BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  1123. return 0;
  1124. }
  1125. bn_check_top(p);
  1126. bn_check_top(m);
  1127. if (!BN_is_odd(m)) {
  1128. BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS);
  1129. return (0);
  1130. }
  1131. if (m->top == 1)
  1132. a %= m->d[0]; /* make sure that 'a' is reduced */
  1133. bits = BN_num_bits(p);
  1134. if (bits == 0) {
  1135. /* x**0 mod 1 is still zero. */
  1136. if (BN_is_one(m)) {
  1137. ret = 1;
  1138. BN_zero(rr);
  1139. } else {
  1140. ret = BN_one(rr);
  1141. }
  1142. return ret;
  1143. }
  1144. if (a == 0) {
  1145. BN_zero(rr);
  1146. ret = 1;
  1147. return ret;
  1148. }
  1149. BN_CTX_start(ctx);
  1150. d = BN_CTX_get(ctx);
  1151. r = BN_CTX_get(ctx);
  1152. t = BN_CTX_get(ctx);
  1153. if (d == NULL || r == NULL || t == NULL)
  1154. goto err;
  1155. if (in_mont != NULL)
  1156. mont = in_mont;
  1157. else {
  1158. if ((mont = BN_MONT_CTX_new()) == NULL)
  1159. goto err;
  1160. if (!BN_MONT_CTX_set(mont, m, ctx))
  1161. goto err;
  1162. }
  1163. r_is_one = 1; /* except for Montgomery factor */
  1164. /* bits-1 >= 0 */
  1165. /* The result is accumulated in the product r*w. */
  1166. w = a; /* bit 'bits-1' of 'p' is always set */
  1167. for (b = bits - 2; b >= 0; b--) {
  1168. /* First, square r*w. */
  1169. next_w = w * w;
  1170. if ((next_w / w) != w) { /* overflow */
  1171. if (r_is_one) {
  1172. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1173. goto err;
  1174. r_is_one = 0;
  1175. } else {
  1176. if (!BN_MOD_MUL_WORD(r, w, m))
  1177. goto err;
  1178. }
  1179. next_w = 1;
  1180. }
  1181. w = next_w;
  1182. if (!r_is_one) {
  1183. if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
  1184. goto err;
  1185. }
  1186. /* Second, multiply r*w by 'a' if exponent bit is set. */
  1187. if (BN_is_bit_set(p, b)) {
  1188. next_w = w * a;
  1189. if ((next_w / a) != w) { /* overflow */
  1190. if (r_is_one) {
  1191. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1192. goto err;
  1193. r_is_one = 0;
  1194. } else {
  1195. if (!BN_MOD_MUL_WORD(r, w, m))
  1196. goto err;
  1197. }
  1198. next_w = a;
  1199. }
  1200. w = next_w;
  1201. }
  1202. }
  1203. /* Finally, set r:=r*w. */
  1204. if (w != 1) {
  1205. if (r_is_one) {
  1206. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1207. goto err;
  1208. r_is_one = 0;
  1209. } else {
  1210. if (!BN_MOD_MUL_WORD(r, w, m))
  1211. goto err;
  1212. }
  1213. }
  1214. if (r_is_one) { /* can happen only if a == 1 */
  1215. if (!BN_one(rr))
  1216. goto err;
  1217. } else {
  1218. if (!BN_from_montgomery(rr, r, mont, ctx))
  1219. goto err;
  1220. }
  1221. ret = 1;
  1222. err:
  1223. if ((in_mont == NULL) && (mont != NULL))
  1224. BN_MONT_CTX_free(mont);
  1225. BN_CTX_end(ctx);
  1226. bn_check_top(rr);
  1227. return (ret);
  1228. }
  1229. /* The old fallback, simple version :-) */
  1230. int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
  1231. const BIGNUM *m, BN_CTX *ctx)
  1232. {
  1233. int i, j, bits, ret = 0, wstart, wend, window, wvalue;
  1234. int start = 1;
  1235. BIGNUM *d;
  1236. /* Table of variables obtained from 'ctx' */
  1237. BIGNUM *val[TABLE_SIZE];
  1238. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
  1239. || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
  1240. || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
  1241. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  1242. BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  1243. return 0;
  1244. }
  1245. bits = BN_num_bits(p);
  1246. if (bits == 0) {
  1247. /* x**0 mod 1 is still zero. */
  1248. if (BN_is_one(m)) {
  1249. ret = 1;
  1250. BN_zero(r);
  1251. } else {
  1252. ret = BN_one(r);
  1253. }
  1254. return ret;
  1255. }
  1256. BN_CTX_start(ctx);
  1257. d = BN_CTX_get(ctx);
  1258. val[0] = BN_CTX_get(ctx);
  1259. if (!d || !val[0])
  1260. goto err;
  1261. if (!BN_nnmod(val[0], a, m, ctx))
  1262. goto err; /* 1 */
  1263. if (BN_is_zero(val[0])) {
  1264. BN_zero(r);
  1265. ret = 1;
  1266. goto err;
  1267. }
  1268. window = BN_window_bits_for_exponent_size(bits);
  1269. if (window > 1) {
  1270. if (!BN_mod_mul(d, val[0], val[0], m, ctx))
  1271. goto err; /* 2 */
  1272. j = 1 << (window - 1);
  1273. for (i = 1; i < j; i++) {
  1274. if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
  1275. !BN_mod_mul(val[i], val[i - 1], d, m, ctx))
  1276. goto err;
  1277. }
  1278. }
  1279. start = 1; /* This is used to avoid multiplication etc
  1280. * when there is only the value '1' in the
  1281. * buffer. */
  1282. wvalue = 0; /* The 'value' of the window */
  1283. wstart = bits - 1; /* The top bit of the window */
  1284. wend = 0; /* The bottom bit of the window */
  1285. if (!BN_one(r))
  1286. goto err;
  1287. for (;;) {
  1288. if (BN_is_bit_set(p, wstart) == 0) {
  1289. if (!start)
  1290. if (!BN_mod_mul(r, r, r, m, ctx))
  1291. goto err;
  1292. if (wstart == 0)
  1293. break;
  1294. wstart--;
  1295. continue;
  1296. }
  1297. /*
  1298. * We now have wstart on a 'set' bit, we now need to work out how bit
  1299. * a window to do. To do this we need to scan forward until the last
  1300. * set bit before the end of the window
  1301. */
  1302. j = wstart;
  1303. wvalue = 1;
  1304. wend = 0;
  1305. for (i = 1; i < window; i++) {
  1306. if (wstart - i < 0)
  1307. break;
  1308. if (BN_is_bit_set(p, wstart - i)) {
  1309. wvalue <<= (i - wend);
  1310. wvalue |= 1;
  1311. wend = i;
  1312. }
  1313. }
  1314. /* wend is the size of the current window */
  1315. j = wend + 1;
  1316. /* add the 'bytes above' */
  1317. if (!start)
  1318. for (i = 0; i < j; i++) {
  1319. if (!BN_mod_mul(r, r, r, m, ctx))
  1320. goto err;
  1321. }
  1322. /* wvalue will be an odd number < 2^window */
  1323. if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
  1324. goto err;
  1325. /* move the 'window' down further */
  1326. wstart -= wend + 1;
  1327. wvalue = 0;
  1328. start = 0;
  1329. if (wstart < 0)
  1330. break;
  1331. }
  1332. ret = 1;
  1333. err:
  1334. BN_CTX_end(ctx);
  1335. bn_check_top(r);
  1336. return (ret);
  1337. }