2
0

bn_exp.c 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395
  1. /*
  2. * Copyright 1995-2019 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. /* 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. if (a->neg || BN_ucmp(a, m) >= 0) {
  579. BIGNUM *reduced = BN_CTX_get(ctx);
  580. if (reduced == NULL
  581. || !BN_nnmod(reduced, a, m, ctx)) {
  582. goto err;
  583. }
  584. a = reduced;
  585. }
  586. #ifdef RSAZ_ENABLED
  587. /*
  588. * If the size of the operands allow it, perform the optimized
  589. * RSAZ exponentiation. For further information see
  590. * crypto/bn/rsaz_exp.c and accompanying assembly modules.
  591. */
  592. if ((16 == a->top) && (16 == p->top) && (BN_num_bits(m) == 1024)
  593. && rsaz_avx2_eligible()) {
  594. if (NULL == bn_wexpand(rr, 16))
  595. goto err;
  596. RSAZ_1024_mod_exp_avx2(rr->d, a->d, p->d, m->d, mont->RR.d,
  597. mont->n0[0]);
  598. rr->top = 16;
  599. rr->neg = 0;
  600. bn_correct_top(rr);
  601. ret = 1;
  602. goto err;
  603. } else if ((8 == a->top) && (8 == p->top) && (BN_num_bits(m) == 512)) {
  604. if (NULL == bn_wexpand(rr, 8))
  605. goto err;
  606. RSAZ_512_mod_exp(rr->d, a->d, p->d, m->d, mont->n0[0], mont->RR.d);
  607. rr->top = 8;
  608. rr->neg = 0;
  609. bn_correct_top(rr);
  610. ret = 1;
  611. goto err;
  612. }
  613. #endif
  614. /* Get the window size to use with size of p. */
  615. window = BN_window_bits_for_ctime_exponent_size(bits);
  616. #if defined(SPARC_T4_MONT)
  617. if (window >= 5 && (top & 15) == 0 && top <= 64 &&
  618. (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) ==
  619. (CFR_MONTMUL | CFR_MONTSQR) && (t4 = OPENSSL_sparcv9cap_P[0]))
  620. window = 5;
  621. else
  622. #endif
  623. #if defined(OPENSSL_BN_ASM_MONT5)
  624. if (window >= 5) {
  625. window = 5; /* ~5% improvement for RSA2048 sign, and even
  626. * for RSA4096 */
  627. /* reserve space for mont->N.d[] copy */
  628. powerbufLen += top * sizeof(mont->N.d[0]);
  629. }
  630. #endif
  631. (void)0;
  632. /*
  633. * Allocate a buffer large enough to hold all of the pre-computed powers
  634. * of am, am itself and tmp.
  635. */
  636. numPowers = 1 << window;
  637. powerbufLen += sizeof(m->d[0]) * (top * numPowers +
  638. ((2 * top) >
  639. numPowers ? (2 * top) : numPowers));
  640. #ifdef alloca
  641. if (powerbufLen < 3072)
  642. powerbufFree =
  643. alloca(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
  644. else
  645. #endif
  646. if ((powerbufFree =
  647. OPENSSL_malloc(powerbufLen + MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH))
  648. == NULL)
  649. goto err;
  650. powerbuf = MOD_EXP_CTIME_ALIGN(powerbufFree);
  651. memset(powerbuf, 0, powerbufLen);
  652. #ifdef alloca
  653. if (powerbufLen < 3072)
  654. powerbufFree = NULL;
  655. #endif
  656. /* lay down tmp and am right after powers table */
  657. tmp.d = (BN_ULONG *)(powerbuf + sizeof(m->d[0]) * top * numPowers);
  658. am.d = tmp.d + top;
  659. tmp.top = am.top = 0;
  660. tmp.dmax = am.dmax = top;
  661. tmp.neg = am.neg = 0;
  662. tmp.flags = am.flags = BN_FLG_STATIC_DATA;
  663. /* prepare a^0 in Montgomery domain */
  664. #if 1 /* by Shay Gueron's suggestion */
  665. if (m->d[top - 1] & (((BN_ULONG)1) << (BN_BITS2 - 1))) {
  666. /* 2^(top*BN_BITS2) - m */
  667. tmp.d[0] = (0 - m->d[0]) & BN_MASK2;
  668. for (i = 1; i < top; i++)
  669. tmp.d[i] = (~m->d[i]) & BN_MASK2;
  670. tmp.top = top;
  671. } else
  672. #endif
  673. if (!bn_to_mont_fixed_top(&tmp, BN_value_one(), mont, ctx))
  674. goto err;
  675. /* prepare a^1 in Montgomery domain */
  676. if (!bn_to_mont_fixed_top(&am, a, mont, ctx))
  677. goto err;
  678. #if defined(SPARC_T4_MONT)
  679. if (t4) {
  680. typedef int (*bn_pwr5_mont_f) (BN_ULONG *tp, const BN_ULONG *np,
  681. const BN_ULONG *n0, const void *table,
  682. int power, int bits);
  683. int bn_pwr5_mont_t4_8(BN_ULONG *tp, const BN_ULONG *np,
  684. const BN_ULONG *n0, const void *table,
  685. int power, int bits);
  686. int bn_pwr5_mont_t4_16(BN_ULONG *tp, const BN_ULONG *np,
  687. const BN_ULONG *n0, const void *table,
  688. int power, int bits);
  689. int bn_pwr5_mont_t4_24(BN_ULONG *tp, const BN_ULONG *np,
  690. const BN_ULONG *n0, const void *table,
  691. int power, int bits);
  692. int bn_pwr5_mont_t4_32(BN_ULONG *tp, const BN_ULONG *np,
  693. const BN_ULONG *n0, const void *table,
  694. int power, int bits);
  695. static const bn_pwr5_mont_f pwr5_funcs[4] = {
  696. bn_pwr5_mont_t4_8, bn_pwr5_mont_t4_16,
  697. bn_pwr5_mont_t4_24, bn_pwr5_mont_t4_32
  698. };
  699. bn_pwr5_mont_f pwr5_worker = pwr5_funcs[top / 16 - 1];
  700. typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap,
  701. const void *bp, const BN_ULONG *np,
  702. const BN_ULONG *n0);
  703. int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const void *bp,
  704. const BN_ULONG *np, const BN_ULONG *n0);
  705. int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap,
  706. const void *bp, const BN_ULONG *np,
  707. const BN_ULONG *n0);
  708. int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap,
  709. const void *bp, const BN_ULONG *np,
  710. const BN_ULONG *n0);
  711. int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap,
  712. const void *bp, const BN_ULONG *np,
  713. const BN_ULONG *n0);
  714. static const bn_mul_mont_f mul_funcs[4] = {
  715. bn_mul_mont_t4_8, bn_mul_mont_t4_16,
  716. bn_mul_mont_t4_24, bn_mul_mont_t4_32
  717. };
  718. bn_mul_mont_f mul_worker = mul_funcs[top / 16 - 1];
  719. void bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap,
  720. const void *bp, const BN_ULONG *np,
  721. const BN_ULONG *n0, int num);
  722. void bn_mul_mont_t4(BN_ULONG *rp, const BN_ULONG *ap,
  723. const void *bp, const BN_ULONG *np,
  724. const BN_ULONG *n0, int num);
  725. void bn_mul_mont_gather5_t4(BN_ULONG *rp, const BN_ULONG *ap,
  726. const void *table, const BN_ULONG *np,
  727. const BN_ULONG *n0, int num, int power);
  728. void bn_flip_n_scatter5_t4(const BN_ULONG *inp, size_t num,
  729. void *table, size_t power);
  730. void bn_gather5_t4(BN_ULONG *out, size_t num,
  731. void *table, size_t power);
  732. void bn_flip_t4(BN_ULONG *dst, BN_ULONG *src, size_t num);
  733. BN_ULONG *np = mont->N.d, *n0 = mont->n0;
  734. int stride = 5 * (6 - (top / 16 - 1)); /* multiple of 5, but less
  735. * than 32 */
  736. /*
  737. * BN_to_montgomery can contaminate words above .top [in
  738. * BN_DEBUG[_DEBUG] build]...
  739. */
  740. for (i = am.top; i < top; i++)
  741. am.d[i] = 0;
  742. for (i = tmp.top; i < top; i++)
  743. tmp.d[i] = 0;
  744. bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 0);
  745. bn_flip_n_scatter5_t4(am.d, top, powerbuf, 1);
  746. if (!(*mul_worker) (tmp.d, am.d, am.d, np, n0) &&
  747. !(*mul_worker) (tmp.d, am.d, am.d, np, n0))
  748. bn_mul_mont_vis3(tmp.d, am.d, am.d, np, n0, top);
  749. bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, 2);
  750. for (i = 3; i < 32; i++) {
  751. /* Calculate a^i = a^(i-1) * a */
  752. if (!(*mul_worker) (tmp.d, tmp.d, am.d, np, n0) &&
  753. !(*mul_worker) (tmp.d, tmp.d, am.d, np, n0))
  754. bn_mul_mont_vis3(tmp.d, tmp.d, am.d, np, n0, top);
  755. bn_flip_n_scatter5_t4(tmp.d, top, powerbuf, i);
  756. }
  757. /* switch to 64-bit domain */
  758. np = alloca(top * sizeof(BN_ULONG));
  759. top /= 2;
  760. bn_flip_t4(np, mont->N.d, top);
  761. /*
  762. * The exponent may not have a whole number of fixed-size windows.
  763. * To simplify the main loop, the initial window has between 1 and
  764. * full-window-size bits such that what remains is always a whole
  765. * number of windows
  766. */
  767. window0 = (bits - 1) % 5 + 1;
  768. wmask = (1 << window0) - 1;
  769. bits -= window0;
  770. wvalue = bn_get_bits(p, bits) & wmask;
  771. bn_gather5_t4(tmp.d, top, powerbuf, wvalue);
  772. /*
  773. * Scan the exponent one window at a time starting from the most
  774. * significant bits.
  775. */
  776. while (bits > 0) {
  777. if (bits < stride)
  778. stride = bits;
  779. bits -= stride;
  780. wvalue = bn_get_bits(p, bits);
  781. if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
  782. continue;
  783. /* retry once and fall back */
  784. if ((*pwr5_worker) (tmp.d, np, n0, powerbuf, wvalue, stride))
  785. continue;
  786. bits += stride - 5;
  787. wvalue >>= stride - 5;
  788. wvalue &= 31;
  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_t4(tmp.d, tmp.d, tmp.d, np, n0, top);
  794. bn_mul_mont_gather5_t4(tmp.d, tmp.d, powerbuf, np, n0, top,
  795. wvalue);
  796. }
  797. bn_flip_t4(tmp.d, tmp.d, top);
  798. top *= 2;
  799. /* back to 32-bit domain */
  800. tmp.top = top;
  801. bn_correct_top(&tmp);
  802. OPENSSL_cleanse(np, top * sizeof(BN_ULONG));
  803. } else
  804. #endif
  805. #if defined(OPENSSL_BN_ASM_MONT5)
  806. if (window == 5 && top > 1) {
  807. /*
  808. * This optimization uses ideas from http://eprint.iacr.org/2011/239,
  809. * specifically optimization of cache-timing attack countermeasures
  810. * and pre-computation optimization.
  811. */
  812. /*
  813. * Dedicated window==4 case improves 512-bit RSA sign by ~15%, but as
  814. * 512-bit RSA is hardly relevant, we omit it to spare size...
  815. */
  816. void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
  817. const void *table, const BN_ULONG *np,
  818. const BN_ULONG *n0, int num, int power);
  819. void bn_scatter5(const BN_ULONG *inp, size_t num,
  820. void *table, size_t power);
  821. void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
  822. void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,
  823. const void *table, const BN_ULONG *np,
  824. const BN_ULONG *n0, int num, int power);
  825. int bn_get_bits5(const BN_ULONG *ap, int off);
  826. int bn_from_montgomery(BN_ULONG *rp, const BN_ULONG *ap,
  827. const BN_ULONG *not_used, const BN_ULONG *np,
  828. const BN_ULONG *n0, int num);
  829. BN_ULONG *n0 = mont->n0, *np;
  830. /*
  831. * BN_to_montgomery can contaminate words above .top [in
  832. * BN_DEBUG[_DEBUG] build]...
  833. */
  834. for (i = am.top; i < top; i++)
  835. am.d[i] = 0;
  836. for (i = tmp.top; i < top; i++)
  837. tmp.d[i] = 0;
  838. /*
  839. * copy mont->N.d[] to improve cache locality
  840. */
  841. for (np = am.d + top, i = 0; i < top; i++)
  842. np[i] = mont->N.d[i];
  843. bn_scatter5(tmp.d, top, powerbuf, 0);
  844. bn_scatter5(am.d, am.top, powerbuf, 1);
  845. bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
  846. bn_scatter5(tmp.d, top, powerbuf, 2);
  847. # if 0
  848. for (i = 3; i < 32; i++) {
  849. /* Calculate a^i = a^(i-1) * a */
  850. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  851. bn_scatter5(tmp.d, top, powerbuf, i);
  852. }
  853. # else
  854. /* same as above, but uses squaring for 1/2 of operations */
  855. for (i = 4; i < 32; i *= 2) {
  856. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  857. bn_scatter5(tmp.d, top, powerbuf, i);
  858. }
  859. for (i = 3; i < 8; i += 2) {
  860. int j;
  861. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  862. bn_scatter5(tmp.d, top, powerbuf, i);
  863. for (j = 2 * i; j < 32; j *= 2) {
  864. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  865. bn_scatter5(tmp.d, top, powerbuf, j);
  866. }
  867. }
  868. for (; i < 16; i += 2) {
  869. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  870. bn_scatter5(tmp.d, top, powerbuf, i);
  871. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  872. bn_scatter5(tmp.d, top, powerbuf, 2 * i);
  873. }
  874. for (; i < 32; i += 2) {
  875. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  876. bn_scatter5(tmp.d, top, powerbuf, i);
  877. }
  878. # endif
  879. /*
  880. * The exponent may not have a whole number of fixed-size windows.
  881. * To simplify the main loop, the initial window has between 1 and
  882. * full-window-size bits such that what remains is always a whole
  883. * number of windows
  884. */
  885. window0 = (bits - 1) % 5 + 1;
  886. wmask = (1 << window0) - 1;
  887. bits -= window0;
  888. wvalue = bn_get_bits(p, bits) & wmask;
  889. bn_gather5(tmp.d, top, powerbuf, wvalue);
  890. /*
  891. * Scan the exponent one window at a time starting from the most
  892. * significant bits.
  893. */
  894. if (top & 7) {
  895. while (bits > 0) {
  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(tmp.d, tmp.d, tmp.d, np, n0, top);
  901. bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,
  902. bn_get_bits5(p->d, bits -= 5));
  903. }
  904. } else {
  905. while (bits > 0) {
  906. bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top,
  907. bn_get_bits5(p->d, bits -= 5));
  908. }
  909. }
  910. ret = bn_from_montgomery(tmp.d, tmp.d, NULL, np, n0, top);
  911. tmp.top = top;
  912. bn_correct_top(&tmp);
  913. if (ret) {
  914. if (!BN_copy(rr, &tmp))
  915. ret = 0;
  916. goto err; /* non-zero ret means it's not error */
  917. }
  918. } else
  919. #endif
  920. {
  921. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window))
  922. goto err;
  923. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window))
  924. goto err;
  925. /*
  926. * If the window size is greater than 1, then calculate
  927. * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
  928. * powers could instead be computed as (a^(i/2))^2 to use the slight
  929. * performance advantage of sqr over mul).
  930. */
  931. if (window > 1) {
  932. if (!bn_mul_mont_fixed_top(&tmp, &am, &am, mont, ctx))
  933. goto err;
  934. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
  935. window))
  936. goto err;
  937. for (i = 3; i < numPowers; i++) {
  938. /* Calculate a^i = a^(i-1) * a */
  939. if (!bn_mul_mont_fixed_top(&tmp, &am, &tmp, mont, ctx))
  940. goto err;
  941. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
  942. window))
  943. goto err;
  944. }
  945. }
  946. /*
  947. * The exponent may not have a whole number of fixed-size windows.
  948. * To simplify the main loop, the initial window has between 1 and
  949. * full-window-size bits such that what remains is always a whole
  950. * number of windows
  951. */
  952. window0 = (bits - 1) % window + 1;
  953. wmask = (1 << window0) - 1;
  954. bits -= window0;
  955. wvalue = bn_get_bits(p, bits) & wmask;
  956. if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue,
  957. window))
  958. goto err;
  959. wmask = (1 << window) - 1;
  960. /*
  961. * Scan the exponent one window at a time starting from the most
  962. * significant bits.
  963. */
  964. while (bits > 0) {
  965. /* Square the result window-size times */
  966. for (i = 0; i < window; i++)
  967. if (!bn_mul_mont_fixed_top(&tmp, &tmp, &tmp, mont, ctx))
  968. goto err;
  969. /*
  970. * Get a window's worth of bits from the exponent
  971. * This avoids calling BN_is_bit_set for each bit, which
  972. * is not only slower but also makes each bit vulnerable to
  973. * EM (and likely other) side-channel attacks like One&Done
  974. * (for details see "One&Done: A Single-Decryption EM-Based
  975. * Attack on OpenSSL's Constant-Time Blinded RSA" by M. Alam,
  976. * H. Khan, M. Dey, N. Sinha, R. Callan, A. Zajic, and
  977. * M. Prvulovic, in USENIX Security'18)
  978. */
  979. bits -= window;
  980. wvalue = bn_get_bits(p, bits) & wmask;
  981. /*
  982. * Fetch the appropriate pre-computed value from the pre-buf
  983. */
  984. if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue,
  985. window))
  986. goto err;
  987. /* Multiply the result into the intermediate result */
  988. if (!bn_mul_mont_fixed_top(&tmp, &tmp, &am, mont, ctx))
  989. goto err;
  990. }
  991. }
  992. /*
  993. * Done with zero-padded intermediate BIGNUMs. Final BN_from_montgomery
  994. * removes padding [if any] and makes return value suitable for public
  995. * API consumer.
  996. */
  997. #if defined(SPARC_T4_MONT)
  998. if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
  999. am.d[0] = 1; /* borrow am */
  1000. for (i = 1; i < top; i++)
  1001. am.d[i] = 0;
  1002. if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))
  1003. goto err;
  1004. } else
  1005. #endif
  1006. if (!BN_from_montgomery(rr, &tmp, mont, ctx))
  1007. goto err;
  1008. ret = 1;
  1009. err:
  1010. if (in_mont == NULL)
  1011. BN_MONT_CTX_free(mont);
  1012. if (powerbuf != NULL) {
  1013. OPENSSL_cleanse(powerbuf, powerbufLen);
  1014. OPENSSL_free(powerbufFree);
  1015. }
  1016. BN_CTX_end(ctx);
  1017. return ret;
  1018. }
  1019. int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
  1020. const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
  1021. {
  1022. BN_MONT_CTX *mont = NULL;
  1023. int b, bits, ret = 0;
  1024. int r_is_one;
  1025. BN_ULONG w, next_w;
  1026. BIGNUM *r, *t;
  1027. BIGNUM *swap_tmp;
  1028. #define BN_MOD_MUL_WORD(r, w, m) \
  1029. (BN_mul_word(r, (w)) && \
  1030. (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
  1031. (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
  1032. /*
  1033. * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
  1034. * probably more overhead than always using BN_mod (which uses BN_copy if
  1035. * a similar test returns true).
  1036. */
  1037. /*
  1038. * We can use BN_mod and do not need BN_nnmod because our accumulator is
  1039. * never negative (the result of BN_mod does not depend on the sign of
  1040. * the modulus).
  1041. */
  1042. #define BN_TO_MONTGOMERY_WORD(r, w, mont) \
  1043. (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
  1044. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
  1045. || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
  1046. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  1047. BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  1048. return 0;
  1049. }
  1050. bn_check_top(p);
  1051. bn_check_top(m);
  1052. if (!BN_is_odd(m)) {
  1053. BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS);
  1054. return 0;
  1055. }
  1056. if (m->top == 1)
  1057. a %= m->d[0]; /* make sure that 'a' is reduced */
  1058. bits = BN_num_bits(p);
  1059. if (bits == 0) {
  1060. /* x**0 mod 1, or x**0 mod -1 is still zero. */
  1061. if (BN_abs_is_word(m, 1)) {
  1062. ret = 1;
  1063. BN_zero(rr);
  1064. } else {
  1065. ret = BN_one(rr);
  1066. }
  1067. return ret;
  1068. }
  1069. if (a == 0) {
  1070. BN_zero(rr);
  1071. ret = 1;
  1072. return ret;
  1073. }
  1074. BN_CTX_start(ctx);
  1075. r = BN_CTX_get(ctx);
  1076. t = BN_CTX_get(ctx);
  1077. if (t == NULL)
  1078. goto err;
  1079. if (in_mont != NULL)
  1080. mont = in_mont;
  1081. else {
  1082. if ((mont = BN_MONT_CTX_new()) == NULL)
  1083. goto err;
  1084. if (!BN_MONT_CTX_set(mont, m, ctx))
  1085. goto err;
  1086. }
  1087. r_is_one = 1; /* except for Montgomery factor */
  1088. /* bits-1 >= 0 */
  1089. /* The result is accumulated in the product r*w. */
  1090. w = a; /* bit 'bits-1' of 'p' is always set */
  1091. for (b = bits - 2; b >= 0; b--) {
  1092. /* First, square r*w. */
  1093. next_w = w * w;
  1094. if ((next_w / w) != w) { /* overflow */
  1095. if (r_is_one) {
  1096. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1097. goto err;
  1098. r_is_one = 0;
  1099. } else {
  1100. if (!BN_MOD_MUL_WORD(r, w, m))
  1101. goto err;
  1102. }
  1103. next_w = 1;
  1104. }
  1105. w = next_w;
  1106. if (!r_is_one) {
  1107. if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
  1108. goto err;
  1109. }
  1110. /* Second, multiply r*w by 'a' if exponent bit is set. */
  1111. if (BN_is_bit_set(p, b)) {
  1112. next_w = w * a;
  1113. if ((next_w / a) != w) { /* overflow */
  1114. if (r_is_one) {
  1115. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1116. goto err;
  1117. r_is_one = 0;
  1118. } else {
  1119. if (!BN_MOD_MUL_WORD(r, w, m))
  1120. goto err;
  1121. }
  1122. next_w = a;
  1123. }
  1124. w = next_w;
  1125. }
  1126. }
  1127. /* Finally, set r:=r*w. */
  1128. if (w != 1) {
  1129. if (r_is_one) {
  1130. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1131. goto err;
  1132. r_is_one = 0;
  1133. } else {
  1134. if (!BN_MOD_MUL_WORD(r, w, m))
  1135. goto err;
  1136. }
  1137. }
  1138. if (r_is_one) { /* can happen only if a == 1 */
  1139. if (!BN_one(rr))
  1140. goto err;
  1141. } else {
  1142. if (!BN_from_montgomery(rr, r, mont, ctx))
  1143. goto err;
  1144. }
  1145. ret = 1;
  1146. err:
  1147. if (in_mont == NULL)
  1148. BN_MONT_CTX_free(mont);
  1149. BN_CTX_end(ctx);
  1150. bn_check_top(rr);
  1151. return ret;
  1152. }
  1153. /* The old fallback, simple version :-) */
  1154. int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
  1155. const BIGNUM *m, BN_CTX *ctx)
  1156. {
  1157. int i, j, bits, ret = 0, wstart, wend, window, wvalue;
  1158. int start = 1;
  1159. BIGNUM *d;
  1160. /* Table of variables obtained from 'ctx' */
  1161. BIGNUM *val[TABLE_SIZE];
  1162. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
  1163. || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
  1164. || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
  1165. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  1166. BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  1167. return 0;
  1168. }
  1169. bits = BN_num_bits(p);
  1170. if (bits == 0) {
  1171. /* x**0 mod 1, or x**0 mod -1 is still zero. */
  1172. if (BN_abs_is_word(m, 1)) {
  1173. ret = 1;
  1174. BN_zero(r);
  1175. } else {
  1176. ret = BN_one(r);
  1177. }
  1178. return ret;
  1179. }
  1180. BN_CTX_start(ctx);
  1181. d = BN_CTX_get(ctx);
  1182. val[0] = BN_CTX_get(ctx);
  1183. if (val[0] == NULL)
  1184. goto err;
  1185. if (!BN_nnmod(val[0], a, m, ctx))
  1186. goto err; /* 1 */
  1187. if (BN_is_zero(val[0])) {
  1188. BN_zero(r);
  1189. ret = 1;
  1190. goto err;
  1191. }
  1192. window = BN_window_bits_for_exponent_size(bits);
  1193. if (window > 1) {
  1194. if (!BN_mod_mul(d, val[0], val[0], m, ctx))
  1195. goto err; /* 2 */
  1196. j = 1 << (window - 1);
  1197. for (i = 1; i < j; i++) {
  1198. if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
  1199. !BN_mod_mul(val[i], val[i - 1], d, m, ctx))
  1200. goto err;
  1201. }
  1202. }
  1203. start = 1; /* This is used to avoid multiplication etc
  1204. * when there is only the value '1' in the
  1205. * buffer. */
  1206. wvalue = 0; /* The 'value' of the window */
  1207. wstart = bits - 1; /* The top bit of the window */
  1208. wend = 0; /* The bottom bit of the window */
  1209. if (!BN_one(r))
  1210. goto err;
  1211. for (;;) {
  1212. if (BN_is_bit_set(p, wstart) == 0) {
  1213. if (!start)
  1214. if (!BN_mod_mul(r, r, r, m, ctx))
  1215. goto err;
  1216. if (wstart == 0)
  1217. break;
  1218. wstart--;
  1219. continue;
  1220. }
  1221. /*
  1222. * We now have wstart on a 'set' bit, we now need to work out how bit
  1223. * a window to do. To do this we need to scan forward until the last
  1224. * set bit before the end of the window
  1225. */
  1226. j = wstart;
  1227. wvalue = 1;
  1228. wend = 0;
  1229. for (i = 1; i < window; i++) {
  1230. if (wstart - i < 0)
  1231. break;
  1232. if (BN_is_bit_set(p, wstart - i)) {
  1233. wvalue <<= (i - wend);
  1234. wvalue |= 1;
  1235. wend = i;
  1236. }
  1237. }
  1238. /* wend is the size of the current window */
  1239. j = wend + 1;
  1240. /* add the 'bytes above' */
  1241. if (!start)
  1242. for (i = 0; i < j; i++) {
  1243. if (!BN_mod_mul(r, r, r, m, ctx))
  1244. goto err;
  1245. }
  1246. /* wvalue will be an odd number < 2^window */
  1247. if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
  1248. goto err;
  1249. /* move the 'window' down further */
  1250. wstart -= wend + 1;
  1251. wvalue = 0;
  1252. start = 0;
  1253. if (wstart < 0)
  1254. break;
  1255. }
  1256. ret = 1;
  1257. err:
  1258. BN_CTX_end(ctx);
  1259. bn_check_top(r);
  1260. return ret;
  1261. }