bn_exp.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404
  1. /*
  2. * Copyright 1995-2022 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_RECP_CTX_init(&recp);
  170. BN_CTX_start(ctx);
  171. aa = BN_CTX_get(ctx);
  172. val[0] = BN_CTX_get(ctx);
  173. if (val[0] == NULL)
  174. goto err;
  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 https://eprint.iacr.org/2011/239,
  809. * specifically optimization of cache-timing attack countermeasures,
  810. * pre-computation optimization, and Almost Montgomery Multiplication.
  811. *
  812. * The paper discusses a 4-bit window to optimize 512-bit modular
  813. * exponentiation, used in RSA-1024 with CRT, but RSA-1024 is no longer
  814. * important.
  815. *
  816. * |bn_mul_mont_gather5| and |bn_power5| implement the "almost"
  817. * reduction variant, so the values here may not be fully reduced.
  818. * They are bounded by R (i.e. they fit in |top| words), not |m|.
  819. * Additionally, we pass these "almost" reduced inputs into
  820. * |bn_mul_mont|, which implements the normal reduction variant.
  821. * Given those inputs, |bn_mul_mont| may not give reduced
  822. * output, but it will still produce "almost" reduced output.
  823. */
  824. void bn_mul_mont_gather5(BN_ULONG *rp, const BN_ULONG *ap,
  825. const void *table, const BN_ULONG *np,
  826. const BN_ULONG *n0, int num, int power);
  827. void bn_scatter5(const BN_ULONG *inp, size_t num,
  828. void *table, size_t power);
  829. void bn_gather5(BN_ULONG *out, size_t num, void *table, size_t power);
  830. void bn_power5(BN_ULONG *rp, const BN_ULONG *ap,
  831. const void *table, const BN_ULONG *np,
  832. const BN_ULONG *n0, int num, int power);
  833. int bn_get_bits5(const BN_ULONG *ap, int off);
  834. BN_ULONG *n0 = mont->n0, *np;
  835. /*
  836. * BN_to_montgomery can contaminate words above .top [in
  837. * BN_DEBUG[_DEBUG] build]...
  838. */
  839. for (i = am.top; i < top; i++)
  840. am.d[i] = 0;
  841. for (i = tmp.top; i < top; i++)
  842. tmp.d[i] = 0;
  843. /*
  844. * copy mont->N.d[] to improve cache locality
  845. */
  846. for (np = am.d + top, i = 0; i < top; i++)
  847. np[i] = mont->N.d[i];
  848. bn_scatter5(tmp.d, top, powerbuf, 0);
  849. bn_scatter5(am.d, am.top, powerbuf, 1);
  850. bn_mul_mont(tmp.d, am.d, am.d, np, n0, top);
  851. bn_scatter5(tmp.d, top, powerbuf, 2);
  852. # if 0
  853. for (i = 3; i < 32; i++) {
  854. /* Calculate a^i = a^(i-1) * a */
  855. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  856. bn_scatter5(tmp.d, top, powerbuf, i);
  857. }
  858. # else
  859. /* same as above, but uses squaring for 1/2 of operations */
  860. for (i = 4; i < 32; i *= 2) {
  861. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  862. bn_scatter5(tmp.d, top, powerbuf, i);
  863. }
  864. for (i = 3; i < 8; i += 2) {
  865. int j;
  866. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  867. bn_scatter5(tmp.d, top, powerbuf, i);
  868. for (j = 2 * i; j < 32; j *= 2) {
  869. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  870. bn_scatter5(tmp.d, top, powerbuf, j);
  871. }
  872. }
  873. for (; i < 16; 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. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  877. bn_scatter5(tmp.d, top, powerbuf, 2 * i);
  878. }
  879. for (; i < 32; i += 2) {
  880. bn_mul_mont_gather5(tmp.d, am.d, powerbuf, np, n0, top, i - 1);
  881. bn_scatter5(tmp.d, top, powerbuf, i);
  882. }
  883. # endif
  884. /*
  885. * The exponent may not have a whole number of fixed-size windows.
  886. * To simplify the main loop, the initial window has between 1 and
  887. * full-window-size bits such that what remains is always a whole
  888. * number of windows
  889. */
  890. window0 = (bits - 1) % 5 + 1;
  891. wmask = (1 << window0) - 1;
  892. bits -= window0;
  893. wvalue = bn_get_bits(p, bits) & wmask;
  894. bn_gather5(tmp.d, top, powerbuf, wvalue);
  895. /*
  896. * Scan the exponent one window at a time starting from the most
  897. * significant bits.
  898. */
  899. if (top & 7) {
  900. while (bits > 0) {
  901. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  902. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  903. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  904. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  905. bn_mul_mont(tmp.d, tmp.d, tmp.d, np, n0, top);
  906. bn_mul_mont_gather5(tmp.d, tmp.d, powerbuf, np, n0, top,
  907. bn_get_bits5(p->d, bits -= 5));
  908. }
  909. } else {
  910. while (bits > 0) {
  911. bn_power5(tmp.d, tmp.d, powerbuf, np, n0, top,
  912. bn_get_bits5(p->d, bits -= 5));
  913. }
  914. }
  915. tmp.top = top;
  916. /*
  917. * The result is now in |tmp| in Montgomery form, but it may not be
  918. * fully reduced. This is within bounds for |BN_from_montgomery|
  919. * (tmp < R <= m*R) so it will, when converting from Montgomery form,
  920. * produce a fully reduced result.
  921. *
  922. * This differs from Figure 2 of the paper, which uses AMM(h, 1) to
  923. * convert from Montgomery form with unreduced output, followed by an
  924. * extra reduction step. In the paper's terminology, we replace
  925. * steps 9 and 10 with MM(h, 1).
  926. */
  927. } else
  928. #endif
  929. {
  930. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 0, window))
  931. goto err;
  932. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&am, top, powerbuf, 1, window))
  933. goto err;
  934. /*
  935. * If the window size is greater than 1, then calculate
  936. * val[i=2..2^winsize-1]. Powers are computed as a*a^(i-1) (even
  937. * powers could instead be computed as (a^(i/2))^2 to use the slight
  938. * performance advantage of sqr over mul).
  939. */
  940. if (window > 1) {
  941. if (!bn_mul_mont_fixed_top(&tmp, &am, &am, mont, ctx))
  942. goto err;
  943. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, 2,
  944. window))
  945. goto err;
  946. for (i = 3; i < numPowers; i++) {
  947. /* Calculate a^i = a^(i-1) * a */
  948. if (!bn_mul_mont_fixed_top(&tmp, &am, &tmp, mont, ctx))
  949. goto err;
  950. if (!MOD_EXP_CTIME_COPY_TO_PREBUF(&tmp, top, powerbuf, i,
  951. window))
  952. goto err;
  953. }
  954. }
  955. /*
  956. * The exponent may not have a whole number of fixed-size windows.
  957. * To simplify the main loop, the initial window has between 1 and
  958. * full-window-size bits such that what remains is always a whole
  959. * number of windows
  960. */
  961. window0 = (bits - 1) % window + 1;
  962. wmask = (1 << window0) - 1;
  963. bits -= window0;
  964. wvalue = bn_get_bits(p, bits) & wmask;
  965. if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&tmp, top, powerbuf, wvalue,
  966. window))
  967. goto err;
  968. wmask = (1 << window) - 1;
  969. /*
  970. * Scan the exponent one window at a time starting from the most
  971. * significant bits.
  972. */
  973. while (bits > 0) {
  974. /* Square the result window-size times */
  975. for (i = 0; i < window; i++)
  976. if (!bn_mul_mont_fixed_top(&tmp, &tmp, &tmp, mont, ctx))
  977. goto err;
  978. /*
  979. * Get a window's worth of bits from the exponent
  980. * This avoids calling BN_is_bit_set for each bit, which
  981. * is not only slower but also makes each bit vulnerable to
  982. * EM (and likely other) side-channel attacks like One&Done
  983. * (for details see "One&Done: A Single-Decryption EM-Based
  984. * Attack on OpenSSL's Constant-Time Blinded RSA" by M. Alam,
  985. * H. Khan, M. Dey, N. Sinha, R. Callan, A. Zajic, and
  986. * M. Prvulovic, in USENIX Security'18)
  987. */
  988. bits -= window;
  989. wvalue = bn_get_bits(p, bits) & wmask;
  990. /*
  991. * Fetch the appropriate pre-computed value from the pre-buf
  992. */
  993. if (!MOD_EXP_CTIME_COPY_FROM_PREBUF(&am, top, powerbuf, wvalue,
  994. window))
  995. goto err;
  996. /* Multiply the result into the intermediate result */
  997. if (!bn_mul_mont_fixed_top(&tmp, &tmp, &am, mont, ctx))
  998. goto err;
  999. }
  1000. }
  1001. /*
  1002. * Done with zero-padded intermediate BIGNUMs. Final BN_from_montgomery
  1003. * removes padding [if any] and makes return value suitable for public
  1004. * API consumer.
  1005. */
  1006. #if defined(SPARC_T4_MONT)
  1007. if (OPENSSL_sparcv9cap_P[0] & (SPARCV9_VIS3 | SPARCV9_PREFER_FPU)) {
  1008. am.d[0] = 1; /* borrow am */
  1009. for (i = 1; i < top; i++)
  1010. am.d[i] = 0;
  1011. if (!BN_mod_mul_montgomery(rr, &tmp, &am, mont, ctx))
  1012. goto err;
  1013. } else
  1014. #endif
  1015. if (!BN_from_montgomery(rr, &tmp, mont, ctx))
  1016. goto err;
  1017. ret = 1;
  1018. err:
  1019. if (in_mont == NULL)
  1020. BN_MONT_CTX_free(mont);
  1021. if (powerbuf != NULL) {
  1022. OPENSSL_cleanse(powerbuf, powerbufLen);
  1023. OPENSSL_free(powerbufFree);
  1024. }
  1025. BN_CTX_end(ctx);
  1026. return ret;
  1027. }
  1028. int BN_mod_exp_mont_word(BIGNUM *rr, BN_ULONG a, const BIGNUM *p,
  1029. const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *in_mont)
  1030. {
  1031. BN_MONT_CTX *mont = NULL;
  1032. int b, bits, ret = 0;
  1033. int r_is_one;
  1034. BN_ULONG w, next_w;
  1035. BIGNUM *r, *t;
  1036. BIGNUM *swap_tmp;
  1037. #define BN_MOD_MUL_WORD(r, w, m) \
  1038. (BN_mul_word(r, (w)) && \
  1039. (/* BN_ucmp(r, (m)) < 0 ? 1 :*/ \
  1040. (BN_mod(t, r, m, ctx) && (swap_tmp = r, r = t, t = swap_tmp, 1))))
  1041. /*
  1042. * BN_MOD_MUL_WORD is only used with 'w' large, so the BN_ucmp test is
  1043. * probably more overhead than always using BN_mod (which uses BN_copy if
  1044. * a similar test returns true).
  1045. */
  1046. /*
  1047. * We can use BN_mod and do not need BN_nnmod because our accumulator is
  1048. * never negative (the result of BN_mod does not depend on the sign of
  1049. * the modulus).
  1050. */
  1051. #define BN_TO_MONTGOMERY_WORD(r, w, mont) \
  1052. (BN_set_word(r, (w)) && BN_to_montgomery(r, r, (mont), ctx))
  1053. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
  1054. || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
  1055. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  1056. BNerr(BN_F_BN_MOD_EXP_MONT_WORD, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  1057. return 0;
  1058. }
  1059. bn_check_top(p);
  1060. bn_check_top(m);
  1061. if (!BN_is_odd(m)) {
  1062. BNerr(BN_F_BN_MOD_EXP_MONT_WORD, BN_R_CALLED_WITH_EVEN_MODULUS);
  1063. return 0;
  1064. }
  1065. if (m->top == 1)
  1066. a %= m->d[0]; /* make sure that 'a' is reduced */
  1067. bits = BN_num_bits(p);
  1068. if (bits == 0) {
  1069. /* x**0 mod 1, or x**0 mod -1 is still zero. */
  1070. if (BN_abs_is_word(m, 1)) {
  1071. ret = 1;
  1072. BN_zero(rr);
  1073. } else {
  1074. ret = BN_one(rr);
  1075. }
  1076. return ret;
  1077. }
  1078. if (a == 0) {
  1079. BN_zero(rr);
  1080. ret = 1;
  1081. return ret;
  1082. }
  1083. BN_CTX_start(ctx);
  1084. r = BN_CTX_get(ctx);
  1085. t = BN_CTX_get(ctx);
  1086. if (t == NULL)
  1087. goto err;
  1088. if (in_mont != NULL)
  1089. mont = in_mont;
  1090. else {
  1091. if ((mont = BN_MONT_CTX_new()) == NULL)
  1092. goto err;
  1093. if (!BN_MONT_CTX_set(mont, m, ctx))
  1094. goto err;
  1095. }
  1096. r_is_one = 1; /* except for Montgomery factor */
  1097. /* bits-1 >= 0 */
  1098. /* The result is accumulated in the product r*w. */
  1099. w = a; /* bit 'bits-1' of 'p' is always set */
  1100. for (b = bits - 2; b >= 0; b--) {
  1101. /* First, square r*w. */
  1102. next_w = w * w;
  1103. if ((next_w / w) != w) { /* overflow */
  1104. if (r_is_one) {
  1105. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1106. goto err;
  1107. r_is_one = 0;
  1108. } else {
  1109. if (!BN_MOD_MUL_WORD(r, w, m))
  1110. goto err;
  1111. }
  1112. next_w = 1;
  1113. }
  1114. w = next_w;
  1115. if (!r_is_one) {
  1116. if (!BN_mod_mul_montgomery(r, r, r, mont, ctx))
  1117. goto err;
  1118. }
  1119. /* Second, multiply r*w by 'a' if exponent bit is set. */
  1120. if (BN_is_bit_set(p, b)) {
  1121. next_w = w * a;
  1122. if ((next_w / a) != w) { /* overflow */
  1123. if (r_is_one) {
  1124. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1125. goto err;
  1126. r_is_one = 0;
  1127. } else {
  1128. if (!BN_MOD_MUL_WORD(r, w, m))
  1129. goto err;
  1130. }
  1131. next_w = a;
  1132. }
  1133. w = next_w;
  1134. }
  1135. }
  1136. /* Finally, set r:=r*w. */
  1137. if (w != 1) {
  1138. if (r_is_one) {
  1139. if (!BN_TO_MONTGOMERY_WORD(r, w, mont))
  1140. goto err;
  1141. r_is_one = 0;
  1142. } else {
  1143. if (!BN_MOD_MUL_WORD(r, w, m))
  1144. goto err;
  1145. }
  1146. }
  1147. if (r_is_one) { /* can happen only if a == 1 */
  1148. if (!BN_one(rr))
  1149. goto err;
  1150. } else {
  1151. if (!BN_from_montgomery(rr, r, mont, ctx))
  1152. goto err;
  1153. }
  1154. ret = 1;
  1155. err:
  1156. if (in_mont == NULL)
  1157. BN_MONT_CTX_free(mont);
  1158. BN_CTX_end(ctx);
  1159. bn_check_top(rr);
  1160. return ret;
  1161. }
  1162. /* The old fallback, simple version :-) */
  1163. int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
  1164. const BIGNUM *m, BN_CTX *ctx)
  1165. {
  1166. int i, j, bits, ret = 0, wstart, wend, window, wvalue;
  1167. int start = 1;
  1168. BIGNUM *d;
  1169. /* Table of variables obtained from 'ctx' */
  1170. BIGNUM *val[TABLE_SIZE];
  1171. if (BN_get_flags(p, BN_FLG_CONSTTIME) != 0
  1172. || BN_get_flags(a, BN_FLG_CONSTTIME) != 0
  1173. || BN_get_flags(m, BN_FLG_CONSTTIME) != 0) {
  1174. /* BN_FLG_CONSTTIME only supported by BN_mod_exp_mont() */
  1175. BNerr(BN_F_BN_MOD_EXP_SIMPLE, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  1176. return 0;
  1177. }
  1178. bits = BN_num_bits(p);
  1179. if (bits == 0) {
  1180. /* x**0 mod 1, or x**0 mod -1 is still zero. */
  1181. if (BN_abs_is_word(m, 1)) {
  1182. ret = 1;
  1183. BN_zero(r);
  1184. } else {
  1185. ret = BN_one(r);
  1186. }
  1187. return ret;
  1188. }
  1189. BN_CTX_start(ctx);
  1190. d = BN_CTX_get(ctx);
  1191. val[0] = BN_CTX_get(ctx);
  1192. if (val[0] == NULL)
  1193. goto err;
  1194. if (!BN_nnmod(val[0], a, m, ctx))
  1195. goto err; /* 1 */
  1196. if (BN_is_zero(val[0])) {
  1197. BN_zero(r);
  1198. ret = 1;
  1199. goto err;
  1200. }
  1201. window = BN_window_bits_for_exponent_size(bits);
  1202. if (window > 1) {
  1203. if (!BN_mod_mul(d, val[0], val[0], m, ctx))
  1204. goto err; /* 2 */
  1205. j = 1 << (window - 1);
  1206. for (i = 1; i < j; i++) {
  1207. if (((val[i] = BN_CTX_get(ctx)) == NULL) ||
  1208. !BN_mod_mul(val[i], val[i - 1], d, m, ctx))
  1209. goto err;
  1210. }
  1211. }
  1212. start = 1; /* This is used to avoid multiplication etc
  1213. * when there is only the value '1' in the
  1214. * buffer. */
  1215. wvalue = 0; /* The 'value' of the window */
  1216. wstart = bits - 1; /* The top bit of the window */
  1217. wend = 0; /* The bottom bit of the window */
  1218. if (!BN_one(r))
  1219. goto err;
  1220. for (;;) {
  1221. if (BN_is_bit_set(p, wstart) == 0) {
  1222. if (!start)
  1223. if (!BN_mod_mul(r, r, r, m, ctx))
  1224. goto err;
  1225. if (wstart == 0)
  1226. break;
  1227. wstart--;
  1228. continue;
  1229. }
  1230. /*
  1231. * We now have wstart on a 'set' bit, we now need to work out how bit
  1232. * a window to do. To do this we need to scan forward until the last
  1233. * set bit before the end of the window
  1234. */
  1235. j = wstart;
  1236. wvalue = 1;
  1237. wend = 0;
  1238. for (i = 1; i < window; i++) {
  1239. if (wstart - i < 0)
  1240. break;
  1241. if (BN_is_bit_set(p, wstart - i)) {
  1242. wvalue <<= (i - wend);
  1243. wvalue |= 1;
  1244. wend = i;
  1245. }
  1246. }
  1247. /* wend is the size of the current window */
  1248. j = wend + 1;
  1249. /* add the 'bytes above' */
  1250. if (!start)
  1251. for (i = 0; i < j; i++) {
  1252. if (!BN_mod_mul(r, r, r, m, ctx))
  1253. goto err;
  1254. }
  1255. /* wvalue will be an odd number < 2^window */
  1256. if (!BN_mod_mul(r, r, val[wvalue >> 1], m, ctx))
  1257. goto err;
  1258. /* move the 'window' down further */
  1259. wstart -= wend + 1;
  1260. wvalue = 0;
  1261. start = 0;
  1262. if (wstart < 0)
  1263. break;
  1264. }
  1265. ret = 1;
  1266. err:
  1267. BN_CTX_end(ctx);
  1268. bn_check_top(r);
  1269. return ret;
  1270. }