2
0

bn_exp.c 44 KB

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