ec_mult.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  1. /*
  2. * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
  3. * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
  4. *
  5. * Licensed under the Apache License 2.0 (the "License"). You may not use
  6. * this file except in compliance with the License. You can obtain a copy
  7. * in the file LICENSE in the source distribution or at
  8. * https://www.openssl.org/source/license.html
  9. */
  10. /*
  11. * ECDSA low level APIs are deprecated for public use, but still ok for
  12. * internal use.
  13. */
  14. #include "internal/deprecated.h"
  15. #include <string.h>
  16. #include <openssl/err.h>
  17. #include "internal/cryptlib.h"
  18. #include "crypto/bn.h"
  19. #include "ec_local.h"
  20. #include "internal/refcount.h"
  21. /*
  22. * This file implements the wNAF-based interleaving multi-exponentiation method
  23. * Formerly at:
  24. * http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#multiexp
  25. * You might now find it here:
  26. * http://link.springer.com/chapter/10.1007%2F3-540-45537-X_13
  27. * http://www.bmoeller.de/pdf/TI-01-08.multiexp.pdf
  28. * For multiplication with precomputation, we use wNAF splitting, formerly at:
  29. * http://www.informatik.tu-darmstadt.de/TI/Mitarbeiter/moeller.html#fastexp
  30. */
  31. /* structure for precomputed multiples of the generator */
  32. struct ec_pre_comp_st {
  33. const EC_GROUP *group; /* parent EC_GROUP object */
  34. size_t blocksize; /* block size for wNAF splitting */
  35. size_t numblocks; /* max. number of blocks for which we have
  36. * precomputation */
  37. size_t w; /* window size */
  38. EC_POINT **points; /* array with pre-calculated multiples of
  39. * generator: 'num' pointers to EC_POINT
  40. * objects followed by a NULL */
  41. size_t num; /* numblocks * 2^(w-1) */
  42. CRYPTO_REF_COUNT references;
  43. CRYPTO_RWLOCK *lock;
  44. };
  45. static EC_PRE_COMP *ec_pre_comp_new(const EC_GROUP *group)
  46. {
  47. EC_PRE_COMP *ret = NULL;
  48. if (!group)
  49. return NULL;
  50. ret = OPENSSL_zalloc(sizeof(*ret));
  51. if (ret == NULL)
  52. return ret;
  53. ret->group = group;
  54. ret->blocksize = 8; /* default */
  55. ret->w = 4; /* default */
  56. ret->references = 1;
  57. ret->lock = CRYPTO_THREAD_lock_new();
  58. if (ret->lock == NULL) {
  59. ERR_raise(ERR_LIB_EC, ERR_R_CRYPTO_LIB);
  60. OPENSSL_free(ret);
  61. return NULL;
  62. }
  63. return ret;
  64. }
  65. EC_PRE_COMP *EC_ec_pre_comp_dup(EC_PRE_COMP *pre)
  66. {
  67. int i;
  68. if (pre != NULL)
  69. CRYPTO_UP_REF(&pre->references, &i, pre->lock);
  70. return pre;
  71. }
  72. void EC_ec_pre_comp_free(EC_PRE_COMP *pre)
  73. {
  74. int i;
  75. if (pre == NULL)
  76. return;
  77. CRYPTO_DOWN_REF(&pre->references, &i, pre->lock);
  78. REF_PRINT_COUNT("EC_ec", pre);
  79. if (i > 0)
  80. return;
  81. REF_ASSERT_ISNT(i < 0);
  82. if (pre->points != NULL) {
  83. EC_POINT **pts;
  84. for (pts = pre->points; *pts != NULL; pts++)
  85. EC_POINT_free(*pts);
  86. OPENSSL_free(pre->points);
  87. }
  88. CRYPTO_THREAD_lock_free(pre->lock);
  89. OPENSSL_free(pre);
  90. }
  91. #define EC_POINT_BN_set_flags(P, flags) do { \
  92. BN_set_flags((P)->X, (flags)); \
  93. BN_set_flags((P)->Y, (flags)); \
  94. BN_set_flags((P)->Z, (flags)); \
  95. } while(0)
  96. /*-
  97. * This functions computes a single point multiplication over the EC group,
  98. * using, at a high level, a Montgomery ladder with conditional swaps, with
  99. * various timing attack defenses.
  100. *
  101. * It performs either a fixed point multiplication
  102. * (scalar * generator)
  103. * when point is NULL, or a variable point multiplication
  104. * (scalar * point)
  105. * when point is not NULL.
  106. *
  107. * `scalar` cannot be NULL and should be in the range [0,n) otherwise all
  108. * constant time bets are off (where n is the cardinality of the EC group).
  109. *
  110. * This function expects `group->order` and `group->cardinality` to be well
  111. * defined and non-zero: it fails with an error code otherwise.
  112. *
  113. * NB: This says nothing about the constant-timeness of the ladder step
  114. * implementation (i.e., the default implementation is based on EC_POINT_add and
  115. * EC_POINT_dbl, which of course are not constant time themselves) or the
  116. * underlying multiprecision arithmetic.
  117. *
  118. * The product is stored in `r`.
  119. *
  120. * This is an internal function: callers are in charge of ensuring that the
  121. * input parameters `group`, `r`, `scalar` and `ctx` are not NULL.
  122. *
  123. * Returns 1 on success, 0 otherwise.
  124. */
  125. int ossl_ec_scalar_mul_ladder(const EC_GROUP *group, EC_POINT *r,
  126. const BIGNUM *scalar, const EC_POINT *point,
  127. BN_CTX *ctx)
  128. {
  129. int i, cardinality_bits, group_top, kbit, pbit, Z_is_one;
  130. EC_POINT *p = NULL;
  131. EC_POINT *s = NULL;
  132. BIGNUM *k = NULL;
  133. BIGNUM *lambda = NULL;
  134. BIGNUM *cardinality = NULL;
  135. int ret = 0;
  136. /* early exit if the input point is the point at infinity */
  137. if (point != NULL && EC_POINT_is_at_infinity(group, point))
  138. return EC_POINT_set_to_infinity(group, r);
  139. if (BN_is_zero(group->order)) {
  140. ERR_raise(ERR_LIB_EC, EC_R_UNKNOWN_ORDER);
  141. return 0;
  142. }
  143. if (BN_is_zero(group->cofactor)) {
  144. ERR_raise(ERR_LIB_EC, EC_R_UNKNOWN_COFACTOR);
  145. return 0;
  146. }
  147. BN_CTX_start(ctx);
  148. if (((p = EC_POINT_new(group)) == NULL)
  149. || ((s = EC_POINT_new(group)) == NULL)) {
  150. ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
  151. goto err;
  152. }
  153. if (point == NULL) {
  154. if (!EC_POINT_copy(p, group->generator)) {
  155. ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
  156. goto err;
  157. }
  158. } else {
  159. if (!EC_POINT_copy(p, point)) {
  160. ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
  161. goto err;
  162. }
  163. }
  164. EC_POINT_BN_set_flags(p, BN_FLG_CONSTTIME);
  165. EC_POINT_BN_set_flags(r, BN_FLG_CONSTTIME);
  166. EC_POINT_BN_set_flags(s, BN_FLG_CONSTTIME);
  167. cardinality = BN_CTX_get(ctx);
  168. lambda = BN_CTX_get(ctx);
  169. k = BN_CTX_get(ctx);
  170. if (k == NULL) {
  171. ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
  172. goto err;
  173. }
  174. if (!BN_mul(cardinality, group->order, group->cofactor, ctx)) {
  175. ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
  176. goto err;
  177. }
  178. /*
  179. * Group cardinalities are often on a word boundary.
  180. * So when we pad the scalar, some timing diff might
  181. * pop if it needs to be expanded due to carries.
  182. * So expand ahead of time.
  183. */
  184. cardinality_bits = BN_num_bits(cardinality);
  185. group_top = bn_get_top(cardinality);
  186. if ((bn_wexpand(k, group_top + 2) == NULL)
  187. || (bn_wexpand(lambda, group_top + 2) == NULL)) {
  188. ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
  189. goto err;
  190. }
  191. if (!BN_copy(k, scalar)) {
  192. ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
  193. goto err;
  194. }
  195. BN_set_flags(k, BN_FLG_CONSTTIME);
  196. if ((BN_num_bits(k) > cardinality_bits) || (BN_is_negative(k))) {
  197. /*-
  198. * this is an unusual input, and we don't guarantee
  199. * constant-timeness
  200. */
  201. if (!BN_nnmod(k, k, cardinality, ctx)) {
  202. ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
  203. goto err;
  204. }
  205. }
  206. if (!BN_add(lambda, k, cardinality)) {
  207. ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
  208. goto err;
  209. }
  210. BN_set_flags(lambda, BN_FLG_CONSTTIME);
  211. if (!BN_add(k, lambda, cardinality)) {
  212. ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
  213. goto err;
  214. }
  215. /*
  216. * lambda := scalar + cardinality
  217. * k := scalar + 2*cardinality
  218. */
  219. kbit = BN_is_bit_set(lambda, cardinality_bits);
  220. BN_consttime_swap(kbit, k, lambda, group_top + 2);
  221. group_top = bn_get_top(group->field);
  222. if ((bn_wexpand(s->X, group_top) == NULL)
  223. || (bn_wexpand(s->Y, group_top) == NULL)
  224. || (bn_wexpand(s->Z, group_top) == NULL)
  225. || (bn_wexpand(r->X, group_top) == NULL)
  226. || (bn_wexpand(r->Y, group_top) == NULL)
  227. || (bn_wexpand(r->Z, group_top) == NULL)
  228. || (bn_wexpand(p->X, group_top) == NULL)
  229. || (bn_wexpand(p->Y, group_top) == NULL)
  230. || (bn_wexpand(p->Z, group_top) == NULL)) {
  231. ERR_raise(ERR_LIB_EC, ERR_R_BN_LIB);
  232. goto err;
  233. }
  234. /* ensure input point is in affine coords for ladder step efficiency */
  235. if (!p->Z_is_one && (group->meth->make_affine == NULL
  236. || !group->meth->make_affine(group, p, ctx))) {
  237. ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
  238. goto err;
  239. }
  240. /* Initialize the Montgomery ladder */
  241. if (!ec_point_ladder_pre(group, r, s, p, ctx)) {
  242. ERR_raise(ERR_LIB_EC, EC_R_LADDER_PRE_FAILURE);
  243. goto err;
  244. }
  245. /* top bit is a 1, in a fixed pos */
  246. pbit = 1;
  247. #define EC_POINT_CSWAP(c, a, b, w, t) do { \
  248. BN_consttime_swap(c, (a)->X, (b)->X, w); \
  249. BN_consttime_swap(c, (a)->Y, (b)->Y, w); \
  250. BN_consttime_swap(c, (a)->Z, (b)->Z, w); \
  251. t = ((a)->Z_is_one ^ (b)->Z_is_one) & (c); \
  252. (a)->Z_is_one ^= (t); \
  253. (b)->Z_is_one ^= (t); \
  254. } while(0)
  255. /*-
  256. * The ladder step, with branches, is
  257. *
  258. * k[i] == 0: S = add(R, S), R = dbl(R)
  259. * k[i] == 1: R = add(S, R), S = dbl(S)
  260. *
  261. * Swapping R, S conditionally on k[i] leaves you with state
  262. *
  263. * k[i] == 0: T, U = R, S
  264. * k[i] == 1: T, U = S, R
  265. *
  266. * Then perform the ECC ops.
  267. *
  268. * U = add(T, U)
  269. * T = dbl(T)
  270. *
  271. * Which leaves you with state
  272. *
  273. * k[i] == 0: U = add(R, S), T = dbl(R)
  274. * k[i] == 1: U = add(S, R), T = dbl(S)
  275. *
  276. * Swapping T, U conditionally on k[i] leaves you with state
  277. *
  278. * k[i] == 0: R, S = T, U
  279. * k[i] == 1: R, S = U, T
  280. *
  281. * Which leaves you with state
  282. *
  283. * k[i] == 0: S = add(R, S), R = dbl(R)
  284. * k[i] == 1: R = add(S, R), S = dbl(S)
  285. *
  286. * So we get the same logic, but instead of a branch it's a
  287. * conditional swap, followed by ECC ops, then another conditional swap.
  288. *
  289. * Optimization: The end of iteration i and start of i-1 looks like
  290. *
  291. * ...
  292. * CSWAP(k[i], R, S)
  293. * ECC
  294. * CSWAP(k[i], R, S)
  295. * (next iteration)
  296. * CSWAP(k[i-1], R, S)
  297. * ECC
  298. * CSWAP(k[i-1], R, S)
  299. * ...
  300. *
  301. * So instead of two contiguous swaps, you can merge the condition
  302. * bits and do a single swap.
  303. *
  304. * k[i] k[i-1] Outcome
  305. * 0 0 No Swap
  306. * 0 1 Swap
  307. * 1 0 Swap
  308. * 1 1 No Swap
  309. *
  310. * This is XOR. pbit tracks the previous bit of k.
  311. */
  312. for (i = cardinality_bits - 1; i >= 0; i--) {
  313. kbit = BN_is_bit_set(k, i) ^ pbit;
  314. EC_POINT_CSWAP(kbit, r, s, group_top, Z_is_one);
  315. /* Perform a single step of the Montgomery ladder */
  316. if (!ec_point_ladder_step(group, r, s, p, ctx)) {
  317. ERR_raise(ERR_LIB_EC, EC_R_LADDER_STEP_FAILURE);
  318. goto err;
  319. }
  320. /*
  321. * pbit logic merges this cswap with that of the
  322. * next iteration
  323. */
  324. pbit ^= kbit;
  325. }
  326. /* one final cswap to move the right value into r */
  327. EC_POINT_CSWAP(pbit, r, s, group_top, Z_is_one);
  328. #undef EC_POINT_CSWAP
  329. /* Finalize ladder (and recover full point coordinates) */
  330. if (!ec_point_ladder_post(group, r, s, p, ctx)) {
  331. ERR_raise(ERR_LIB_EC, EC_R_LADDER_POST_FAILURE);
  332. goto err;
  333. }
  334. ret = 1;
  335. err:
  336. EC_POINT_free(p);
  337. EC_POINT_clear_free(s);
  338. BN_CTX_end(ctx);
  339. return ret;
  340. }
  341. #undef EC_POINT_BN_set_flags
  342. /*
  343. * Table could be optimised for the wNAF-based implementation,
  344. * sometimes smaller windows will give better performance (thus the
  345. * boundaries should be increased)
  346. */
  347. #define EC_window_bits_for_scalar_size(b) \
  348. ((size_t) \
  349. ((b) >= 2000 ? 6 : \
  350. (b) >= 800 ? 5 : \
  351. (b) >= 300 ? 4 : \
  352. (b) >= 70 ? 3 : \
  353. (b) >= 20 ? 2 : \
  354. 1))
  355. /*-
  356. * Compute
  357. * \sum scalars[i]*points[i],
  358. * also including
  359. * scalar*generator
  360. * in the addition if scalar != NULL
  361. */
  362. int ossl_ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
  363. size_t num, const EC_POINT *points[],
  364. const BIGNUM *scalars[], BN_CTX *ctx)
  365. {
  366. const EC_POINT *generator = NULL;
  367. EC_POINT *tmp = NULL;
  368. size_t totalnum;
  369. size_t blocksize = 0, numblocks = 0; /* for wNAF splitting */
  370. size_t pre_points_per_block = 0;
  371. size_t i, j;
  372. int k;
  373. int r_is_inverted = 0;
  374. int r_is_at_infinity = 1;
  375. size_t *wsize = NULL; /* individual window sizes */
  376. signed char **wNAF = NULL; /* individual wNAFs */
  377. size_t *wNAF_len = NULL;
  378. size_t max_len = 0;
  379. size_t num_val;
  380. EC_POINT **val = NULL; /* precomputation */
  381. EC_POINT **v;
  382. EC_POINT ***val_sub = NULL; /* pointers to sub-arrays of 'val' or
  383. * 'pre_comp->points' */
  384. const EC_PRE_COMP *pre_comp = NULL;
  385. int num_scalar = 0; /* flag: will be set to 1 if 'scalar' must be
  386. * treated like other scalars, i.e.
  387. * precomputation is not available */
  388. int ret = 0;
  389. if (!BN_is_zero(group->order) && !BN_is_zero(group->cofactor)) {
  390. /*-
  391. * Handle the common cases where the scalar is secret, enforcing a
  392. * scalar multiplication implementation based on a Montgomery ladder,
  393. * with various timing attack defenses.
  394. */
  395. if ((scalar != group->order) && (scalar != NULL) && (num == 0)) {
  396. /*-
  397. * In this case we want to compute scalar * GeneratorPoint: this
  398. * codepath is reached most prominently by (ephemeral) key
  399. * generation of EC cryptosystems (i.e. ECDSA keygen and sign setup,
  400. * ECDH keygen/first half), where the scalar is always secret. This
  401. * is why we ignore if BN_FLG_CONSTTIME is actually set and we
  402. * always call the ladder version.
  403. */
  404. return ossl_ec_scalar_mul_ladder(group, r, scalar, NULL, ctx);
  405. }
  406. if ((scalar == NULL) && (num == 1) && (scalars[0] != group->order)) {
  407. /*-
  408. * In this case we want to compute scalar * VariablePoint: this
  409. * codepath is reached most prominently by the second half of ECDH,
  410. * where the secret scalar is multiplied by the peer's public point.
  411. * To protect the secret scalar, we ignore if BN_FLG_CONSTTIME is
  412. * actually set and we always call the ladder version.
  413. */
  414. return ossl_ec_scalar_mul_ladder(group, r, scalars[0], points[0],
  415. ctx);
  416. }
  417. }
  418. if (scalar != NULL) {
  419. generator = EC_GROUP_get0_generator(group);
  420. if (generator == NULL) {
  421. ERR_raise(ERR_LIB_EC, EC_R_UNDEFINED_GENERATOR);
  422. goto err;
  423. }
  424. /* look if we can use precomputed multiples of generator */
  425. pre_comp = group->pre_comp.ec;
  426. if (pre_comp && pre_comp->numblocks
  427. && (EC_POINT_cmp(group, generator, pre_comp->points[0], ctx) ==
  428. 0)) {
  429. blocksize = pre_comp->blocksize;
  430. /*
  431. * determine maximum number of blocks that wNAF splitting may
  432. * yield (NB: maximum wNAF length is bit length plus one)
  433. */
  434. numblocks = (BN_num_bits(scalar) / blocksize) + 1;
  435. /*
  436. * we cannot use more blocks than we have precomputation for
  437. */
  438. if (numblocks > pre_comp->numblocks)
  439. numblocks = pre_comp->numblocks;
  440. pre_points_per_block = (size_t)1 << (pre_comp->w - 1);
  441. /* check that pre_comp looks sane */
  442. if (pre_comp->num != (pre_comp->numblocks * pre_points_per_block)) {
  443. ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
  444. goto err;
  445. }
  446. } else {
  447. /* can't use precomputation */
  448. pre_comp = NULL;
  449. numblocks = 1;
  450. num_scalar = 1; /* treat 'scalar' like 'num'-th element of
  451. * 'scalars' */
  452. }
  453. }
  454. totalnum = num + numblocks;
  455. wsize = OPENSSL_malloc(totalnum * sizeof(wsize[0]));
  456. wNAF_len = OPENSSL_malloc(totalnum * sizeof(wNAF_len[0]));
  457. /* include space for pivot */
  458. wNAF = OPENSSL_malloc((totalnum + 1) * sizeof(wNAF[0]));
  459. val_sub = OPENSSL_malloc(totalnum * sizeof(val_sub[0]));
  460. /* Ensure wNAF is initialised in case we end up going to err */
  461. if (wNAF != NULL)
  462. wNAF[0] = NULL; /* preliminary pivot */
  463. if (wsize == NULL || wNAF_len == NULL || wNAF == NULL || val_sub == NULL)
  464. goto err;
  465. /*
  466. * num_val will be the total number of temporarily precomputed points
  467. */
  468. num_val = 0;
  469. for (i = 0; i < num + num_scalar; i++) {
  470. size_t bits;
  471. bits = i < num ? BN_num_bits(scalars[i]) : BN_num_bits(scalar);
  472. wsize[i] = EC_window_bits_for_scalar_size(bits);
  473. num_val += (size_t)1 << (wsize[i] - 1);
  474. wNAF[i + 1] = NULL; /* make sure we always have a pivot */
  475. wNAF[i] =
  476. bn_compute_wNAF((i < num ? scalars[i] : scalar), wsize[i],
  477. &wNAF_len[i]);
  478. if (wNAF[i] == NULL)
  479. goto err;
  480. if (wNAF_len[i] > max_len)
  481. max_len = wNAF_len[i];
  482. }
  483. if (numblocks) {
  484. /* we go here iff scalar != NULL */
  485. if (pre_comp == NULL) {
  486. if (num_scalar != 1) {
  487. ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
  488. goto err;
  489. }
  490. /* we have already generated a wNAF for 'scalar' */
  491. } else {
  492. signed char *tmp_wNAF = NULL;
  493. size_t tmp_len = 0;
  494. if (num_scalar != 0) {
  495. ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
  496. goto err;
  497. }
  498. /*
  499. * use the window size for which we have precomputation
  500. */
  501. wsize[num] = pre_comp->w;
  502. tmp_wNAF = bn_compute_wNAF(scalar, wsize[num], &tmp_len);
  503. if (!tmp_wNAF)
  504. goto err;
  505. if (tmp_len <= max_len) {
  506. /*
  507. * One of the other wNAFs is at least as long as the wNAF
  508. * belonging to the generator, so wNAF splitting will not buy
  509. * us anything.
  510. */
  511. numblocks = 1;
  512. totalnum = num + 1; /* don't use wNAF splitting */
  513. wNAF[num] = tmp_wNAF;
  514. wNAF[num + 1] = NULL;
  515. wNAF_len[num] = tmp_len;
  516. /*
  517. * pre_comp->points starts with the points that we need here:
  518. */
  519. val_sub[num] = pre_comp->points;
  520. } else {
  521. /*
  522. * don't include tmp_wNAF directly into wNAF array - use wNAF
  523. * splitting and include the blocks
  524. */
  525. signed char *pp;
  526. EC_POINT **tmp_points;
  527. if (tmp_len < numblocks * blocksize) {
  528. /*
  529. * possibly we can do with fewer blocks than estimated
  530. */
  531. numblocks = (tmp_len + blocksize - 1) / blocksize;
  532. if (numblocks > pre_comp->numblocks) {
  533. ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
  534. OPENSSL_free(tmp_wNAF);
  535. goto err;
  536. }
  537. totalnum = num + numblocks;
  538. }
  539. /* split wNAF in 'numblocks' parts */
  540. pp = tmp_wNAF;
  541. tmp_points = pre_comp->points;
  542. for (i = num; i < totalnum; i++) {
  543. if (i < totalnum - 1) {
  544. wNAF_len[i] = blocksize;
  545. if (tmp_len < blocksize) {
  546. ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
  547. OPENSSL_free(tmp_wNAF);
  548. goto err;
  549. }
  550. tmp_len -= blocksize;
  551. } else
  552. /*
  553. * last block gets whatever is left (this could be
  554. * more or less than 'blocksize'!)
  555. */
  556. wNAF_len[i] = tmp_len;
  557. wNAF[i + 1] = NULL;
  558. wNAF[i] = OPENSSL_malloc(wNAF_len[i]);
  559. if (wNAF[i] == NULL) {
  560. OPENSSL_free(tmp_wNAF);
  561. goto err;
  562. }
  563. memcpy(wNAF[i], pp, wNAF_len[i]);
  564. if (wNAF_len[i] > max_len)
  565. max_len = wNAF_len[i];
  566. if (*tmp_points == NULL) {
  567. ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
  568. OPENSSL_free(tmp_wNAF);
  569. goto err;
  570. }
  571. val_sub[i] = tmp_points;
  572. tmp_points += pre_points_per_block;
  573. pp += blocksize;
  574. }
  575. OPENSSL_free(tmp_wNAF);
  576. }
  577. }
  578. }
  579. /*
  580. * All points we precompute now go into a single array 'val'.
  581. * 'val_sub[i]' is a pointer to the subarray for the i-th point, or to a
  582. * subarray of 'pre_comp->points' if we already have precomputation.
  583. */
  584. val = OPENSSL_malloc((num_val + 1) * sizeof(val[0]));
  585. if (val == NULL)
  586. goto err;
  587. val[num_val] = NULL; /* pivot element */
  588. /* allocate points for precomputation */
  589. v = val;
  590. for (i = 0; i < num + num_scalar; i++) {
  591. val_sub[i] = v;
  592. for (j = 0; j < ((size_t)1 << (wsize[i] - 1)); j++) {
  593. *v = EC_POINT_new(group);
  594. if (*v == NULL)
  595. goto err;
  596. v++;
  597. }
  598. }
  599. if (!(v == val + num_val)) {
  600. ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
  601. goto err;
  602. }
  603. if ((tmp = EC_POINT_new(group)) == NULL)
  604. goto err;
  605. /*-
  606. * prepare precomputed values:
  607. * val_sub[i][0] := points[i]
  608. * val_sub[i][1] := 3 * points[i]
  609. * val_sub[i][2] := 5 * points[i]
  610. * ...
  611. */
  612. for (i = 0; i < num + num_scalar; i++) {
  613. if (i < num) {
  614. if (!EC_POINT_copy(val_sub[i][0], points[i]))
  615. goto err;
  616. } else {
  617. if (!EC_POINT_copy(val_sub[i][0], generator))
  618. goto err;
  619. }
  620. if (wsize[i] > 1) {
  621. if (!EC_POINT_dbl(group, tmp, val_sub[i][0], ctx))
  622. goto err;
  623. for (j = 1; j < ((size_t)1 << (wsize[i] - 1)); j++) {
  624. if (!EC_POINT_add
  625. (group, val_sub[i][j], val_sub[i][j - 1], tmp, ctx))
  626. goto err;
  627. }
  628. }
  629. }
  630. if (group->meth->points_make_affine == NULL
  631. || !group->meth->points_make_affine(group, num_val, val, ctx))
  632. goto err;
  633. r_is_at_infinity = 1;
  634. for (k = max_len - 1; k >= 0; k--) {
  635. if (!r_is_at_infinity) {
  636. if (!EC_POINT_dbl(group, r, r, ctx))
  637. goto err;
  638. }
  639. for (i = 0; i < totalnum; i++) {
  640. if (wNAF_len[i] > (size_t)k) {
  641. int digit = wNAF[i][k];
  642. int is_neg;
  643. if (digit) {
  644. is_neg = digit < 0;
  645. if (is_neg)
  646. digit = -digit;
  647. if (is_neg != r_is_inverted) {
  648. if (!r_is_at_infinity) {
  649. if (!EC_POINT_invert(group, r, ctx))
  650. goto err;
  651. }
  652. r_is_inverted = !r_is_inverted;
  653. }
  654. /* digit > 0 */
  655. if (r_is_at_infinity) {
  656. if (!EC_POINT_copy(r, val_sub[i][digit >> 1]))
  657. goto err;
  658. /*-
  659. * Apply coordinate blinding for EC_POINT.
  660. *
  661. * The underlying EC_METHOD can optionally implement this function:
  662. * ossl_ec_point_blind_coordinates() returns 0 in case of errors or 1 on
  663. * success or if coordinate blinding is not implemented for this
  664. * group.
  665. */
  666. if (!ossl_ec_point_blind_coordinates(group, r, ctx)) {
  667. ERR_raise(ERR_LIB_EC, EC_R_POINT_COORDINATES_BLIND_FAILURE);
  668. goto err;
  669. }
  670. r_is_at_infinity = 0;
  671. } else {
  672. if (!EC_POINT_add
  673. (group, r, r, val_sub[i][digit >> 1], ctx))
  674. goto err;
  675. }
  676. }
  677. }
  678. }
  679. }
  680. if (r_is_at_infinity) {
  681. if (!EC_POINT_set_to_infinity(group, r))
  682. goto err;
  683. } else {
  684. if (r_is_inverted)
  685. if (!EC_POINT_invert(group, r, ctx))
  686. goto err;
  687. }
  688. ret = 1;
  689. err:
  690. EC_POINT_free(tmp);
  691. OPENSSL_free(wsize);
  692. OPENSSL_free(wNAF_len);
  693. if (wNAF != NULL) {
  694. signed char **w;
  695. for (w = wNAF; *w != NULL; w++)
  696. OPENSSL_free(*w);
  697. OPENSSL_free(wNAF);
  698. }
  699. if (val != NULL) {
  700. for (v = val; *v != NULL; v++)
  701. EC_POINT_clear_free(*v);
  702. OPENSSL_free(val);
  703. }
  704. OPENSSL_free(val_sub);
  705. return ret;
  706. }
  707. /*-
  708. * ossl_ec_wNAF_precompute_mult()
  709. * creates an EC_PRE_COMP object with preprecomputed multiples of the generator
  710. * for use with wNAF splitting as implemented in ossl_ec_wNAF_mul().
  711. *
  712. * 'pre_comp->points' is an array of multiples of the generator
  713. * of the following form:
  714. * points[0] = generator;
  715. * points[1] = 3 * generator;
  716. * ...
  717. * points[2^(w-1)-1] = (2^(w-1)-1) * generator;
  718. * points[2^(w-1)] = 2^blocksize * generator;
  719. * points[2^(w-1)+1] = 3 * 2^blocksize * generator;
  720. * ...
  721. * points[2^(w-1)*(numblocks-1)-1] = (2^(w-1)) * 2^(blocksize*(numblocks-2)) * generator
  722. * points[2^(w-1)*(numblocks-1)] = 2^(blocksize*(numblocks-1)) * generator
  723. * ...
  724. * points[2^(w-1)*numblocks-1] = (2^(w-1)) * 2^(blocksize*(numblocks-1)) * generator
  725. * points[2^(w-1)*numblocks] = NULL
  726. */
  727. int ossl_ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *ctx)
  728. {
  729. const EC_POINT *generator;
  730. EC_POINT *tmp_point = NULL, *base = NULL, **var;
  731. const BIGNUM *order;
  732. size_t i, bits, w, pre_points_per_block, blocksize, numblocks, num;
  733. EC_POINT **points = NULL;
  734. EC_PRE_COMP *pre_comp;
  735. int ret = 0;
  736. int used_ctx = 0;
  737. #ifndef FIPS_MODULE
  738. BN_CTX *new_ctx = NULL;
  739. #endif
  740. /* if there is an old EC_PRE_COMP object, throw it away */
  741. EC_pre_comp_free(group);
  742. if ((pre_comp = ec_pre_comp_new(group)) == NULL)
  743. return 0;
  744. generator = EC_GROUP_get0_generator(group);
  745. if (generator == NULL) {
  746. ERR_raise(ERR_LIB_EC, EC_R_UNDEFINED_GENERATOR);
  747. goto err;
  748. }
  749. #ifndef FIPS_MODULE
  750. if (ctx == NULL)
  751. ctx = new_ctx = BN_CTX_new();
  752. #endif
  753. if (ctx == NULL)
  754. goto err;
  755. BN_CTX_start(ctx);
  756. used_ctx = 1;
  757. order = EC_GROUP_get0_order(group);
  758. if (order == NULL)
  759. goto err;
  760. if (BN_is_zero(order)) {
  761. ERR_raise(ERR_LIB_EC, EC_R_UNKNOWN_ORDER);
  762. goto err;
  763. }
  764. bits = BN_num_bits(order);
  765. /*
  766. * The following parameters mean we precompute (approximately) one point
  767. * per bit. TBD: The combination 8, 4 is perfect for 160 bits; for other
  768. * bit lengths, other parameter combinations might provide better
  769. * efficiency.
  770. */
  771. blocksize = 8;
  772. w = 4;
  773. if (EC_window_bits_for_scalar_size(bits) > w) {
  774. /* let's not make the window too small ... */
  775. w = EC_window_bits_for_scalar_size(bits);
  776. }
  777. numblocks = (bits + blocksize - 1) / blocksize; /* max. number of blocks
  778. * to use for wNAF
  779. * splitting */
  780. pre_points_per_block = (size_t)1 << (w - 1);
  781. num = pre_points_per_block * numblocks; /* number of points to compute
  782. * and store */
  783. points = OPENSSL_malloc(sizeof(*points) * (num + 1));
  784. if (points == NULL)
  785. goto err;
  786. var = points;
  787. var[num] = NULL; /* pivot */
  788. for (i = 0; i < num; i++) {
  789. if ((var[i] = EC_POINT_new(group)) == NULL) {
  790. ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
  791. goto err;
  792. }
  793. }
  794. if ((tmp_point = EC_POINT_new(group)) == NULL
  795. || (base = EC_POINT_new(group)) == NULL) {
  796. ERR_raise(ERR_LIB_EC, ERR_R_EC_LIB);
  797. goto err;
  798. }
  799. if (!EC_POINT_copy(base, generator))
  800. goto err;
  801. /* do the precomputation */
  802. for (i = 0; i < numblocks; i++) {
  803. size_t j;
  804. if (!EC_POINT_dbl(group, tmp_point, base, ctx))
  805. goto err;
  806. if (!EC_POINT_copy(*var++, base))
  807. goto err;
  808. for (j = 1; j < pre_points_per_block; j++, var++) {
  809. /*
  810. * calculate odd multiples of the current base point
  811. */
  812. if (!EC_POINT_add(group, *var, tmp_point, *(var - 1), ctx))
  813. goto err;
  814. }
  815. if (i < numblocks - 1) {
  816. /*
  817. * get the next base (multiply current one by 2^blocksize)
  818. */
  819. size_t k;
  820. if (blocksize <= 2) {
  821. ERR_raise(ERR_LIB_EC, ERR_R_INTERNAL_ERROR);
  822. goto err;
  823. }
  824. if (!EC_POINT_dbl(group, base, tmp_point, ctx))
  825. goto err;
  826. for (k = 2; k < blocksize; k++) {
  827. if (!EC_POINT_dbl(group, base, base, ctx))
  828. goto err;
  829. }
  830. }
  831. }
  832. if (group->meth->points_make_affine == NULL
  833. || !group->meth->points_make_affine(group, num, points, ctx))
  834. goto err;
  835. pre_comp->group = group;
  836. pre_comp->blocksize = blocksize;
  837. pre_comp->numblocks = numblocks;
  838. pre_comp->w = w;
  839. pre_comp->points = points;
  840. points = NULL;
  841. pre_comp->num = num;
  842. SETPRECOMP(group, ec, pre_comp);
  843. pre_comp = NULL;
  844. ret = 1;
  845. err:
  846. if (used_ctx)
  847. BN_CTX_end(ctx);
  848. #ifndef FIPS_MODULE
  849. BN_CTX_free(new_ctx);
  850. #endif
  851. EC_ec_pre_comp_free(pre_comp);
  852. if (points) {
  853. EC_POINT **p;
  854. for (p = points; *p != NULL; p++)
  855. EC_POINT_free(*p);
  856. OPENSSL_free(points);
  857. }
  858. EC_POINT_free(tmp_point);
  859. EC_POINT_free(base);
  860. return ret;
  861. }
  862. int ossl_ec_wNAF_have_precompute_mult(const EC_GROUP *group)
  863. {
  864. return HAVEPRECOMP(group, ec);
  865. }