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