bn_exp.c 46 KB

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