ec_mult.c 31 KB

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