1 /*
2 * Elliptic curves over GF(p): generic functions
3 *
4 * Copyright The Mbed TLS Contributors
5 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6 */
7
8 /*
9 * References:
10 *
11 * SEC1 https://www.secg.org/sec1-v2.pdf
12 * GECC = Guide to Elliptic Curve Cryptography - Hankerson, Menezes, Vanstone
13 * FIPS 186-3 http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
14 * RFC 4492 for the related TLS structures and constants
15 * - https://www.rfc-editor.org/rfc/rfc4492
16 * RFC 7748 for the Curve448 and Curve25519 curve definitions
17 * - https://www.rfc-editor.org/rfc/rfc7748
18 *
19 * [Curve25519] https://cr.yp.to/ecdh/curve25519-20060209.pdf
20 *
21 * [2] CORON, Jean-S'ebastien. Resistance against differential power analysis
22 * for elliptic curve cryptosystems. In : Cryptographic Hardware and
23 * Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302.
24 * <http://link.springer.com/chapter/10.1007/3-540-48059-5_25>
25 *
26 * [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to
27 * render ECC resistant against Side Channel Attacks. IACR Cryptology
28 * ePrint Archive, 2004, vol. 2004, p. 342.
29 * <http://eprint.iacr.org/2004/342.pdf>
30 */
31
32 #include "common.h"
33
34 /**
35 * \brief Function level alternative implementation.
36 *
37 * The MBEDTLS_ECP_INTERNAL_ALT macro enables alternative implementations to
38 * replace certain functions in this module. The alternative implementations are
39 * typically hardware accelerators and need to activate the hardware before the
40 * computation starts and deactivate it after it finishes. The
41 * mbedtls_internal_ecp_init() and mbedtls_internal_ecp_free() functions serve
42 * this purpose.
43 *
44 * To preserve the correct functionality the following conditions must hold:
45 *
46 * - The alternative implementation must be activated by
47 * mbedtls_internal_ecp_init() before any of the replaceable functions is
48 * called.
49 * - mbedtls_internal_ecp_free() must \b only be called when the alternative
50 * implementation is activated.
51 * - mbedtls_internal_ecp_init() must \b not be called when the alternative
52 * implementation is activated.
53 * - Public functions must not return while the alternative implementation is
54 * activated.
55 * - Replaceable functions are guarded by \c MBEDTLS_ECP_XXX_ALT macros and
56 * before calling them an \code if( mbedtls_internal_ecp_grp_capable( grp ) )
57 * \endcode ensures that the alternative implementation supports the current
58 * group.
59 */
60 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
61 #endif
62
63 #if defined(MBEDTLS_ECP_LIGHT)
64
65 #include "mbedtls/ecp.h"
66 #include "mbedtls/threading.h"
67 #include "mbedtls/platform_util.h"
68 #include "mbedtls/error.h"
69
70 #include "bn_mul.h"
71 #include "ecp_invasive.h"
72
73 #include <string.h>
74
75 #if !defined(MBEDTLS_ECP_ALT)
76
77 #include "mbedtls/platform.h"
78
79 #include "ecp_internal_alt.h"
80
81 #if defined(MBEDTLS_SELF_TEST)
82 /*
83 * Counts of point addition and doubling, and field multiplications.
84 * Used to test resistance of point multiplication to simple timing attacks.
85 */
86 #if defined(MBEDTLS_ECP_C)
87 static unsigned long add_count, dbl_count;
88 #endif /* MBEDTLS_ECP_C */
89 static unsigned long mul_count;
90 #endif
91
92 #if defined(MBEDTLS_ECP_RESTARTABLE)
93 /*
94 * Maximum number of "basic operations" to be done in a row.
95 *
96 * Default value 0 means that ECC operations will not yield.
97 * Note that regardless of the value of ecp_max_ops, always at
98 * least one step is performed before yielding.
99 *
100 * Setting ecp_max_ops=1 can be suitable for testing purposes
101 * as it will interrupt computation at all possible points.
102 */
103 static unsigned ecp_max_ops = 0;
104
105 /*
106 * Set ecp_max_ops
107 */
mbedtls_ecp_set_max_ops(unsigned max_ops)108 void mbedtls_ecp_set_max_ops(unsigned max_ops)
109 {
110 ecp_max_ops = max_ops;
111 }
112
113 /*
114 * Check if restart is enabled
115 */
mbedtls_ecp_restart_is_enabled(void)116 int mbedtls_ecp_restart_is_enabled(void)
117 {
118 return ecp_max_ops != 0;
119 }
120
121 /*
122 * Restart sub-context for ecp_mul_comb()
123 */
124 struct mbedtls_ecp_restart_mul {
125 mbedtls_ecp_point R; /* current intermediate result */
126 size_t i; /* current index in various loops, 0 outside */
127 mbedtls_ecp_point *T; /* table for precomputed points */
128 unsigned char T_size; /* number of points in table T */
129 enum { /* what were we doing last time we returned? */
130 ecp_rsm_init = 0, /* nothing so far, dummy initial state */
131 ecp_rsm_pre_dbl, /* precompute 2^n multiples */
132 ecp_rsm_pre_norm_dbl, /* normalize precomputed 2^n multiples */
133 ecp_rsm_pre_add, /* precompute remaining points by adding */
134 ecp_rsm_pre_norm_add, /* normalize all precomputed points */
135 ecp_rsm_comb_core, /* ecp_mul_comb_core() */
136 ecp_rsm_final_norm, /* do the final normalization */
137 } state;
138 };
139
140 /*
141 * Init restart_mul sub-context
142 */
ecp_restart_rsm_init(mbedtls_ecp_restart_mul_ctx * ctx)143 static void ecp_restart_rsm_init(mbedtls_ecp_restart_mul_ctx *ctx)
144 {
145 mbedtls_ecp_point_init(&ctx->R);
146 ctx->i = 0;
147 ctx->T = NULL;
148 ctx->T_size = 0;
149 ctx->state = ecp_rsm_init;
150 }
151
152 /*
153 * Free the components of a restart_mul sub-context
154 */
ecp_restart_rsm_free(mbedtls_ecp_restart_mul_ctx * ctx)155 static void ecp_restart_rsm_free(mbedtls_ecp_restart_mul_ctx *ctx)
156 {
157 unsigned char i;
158
159 if (ctx == NULL) {
160 return;
161 }
162
163 mbedtls_ecp_point_free(&ctx->R);
164
165 if (ctx->T != NULL) {
166 for (i = 0; i < ctx->T_size; i++) {
167 mbedtls_ecp_point_free(ctx->T + i);
168 }
169 mbedtls_free(ctx->T);
170 }
171
172 ecp_restart_rsm_init(ctx);
173 }
174
175 /*
176 * Restart context for ecp_muladd()
177 */
178 struct mbedtls_ecp_restart_muladd {
179 mbedtls_ecp_point mP; /* mP value */
180 mbedtls_ecp_point R; /* R intermediate result */
181 enum { /* what should we do next? */
182 ecp_rsma_mul1 = 0, /* first multiplication */
183 ecp_rsma_mul2, /* second multiplication */
184 ecp_rsma_add, /* addition */
185 ecp_rsma_norm, /* normalization */
186 } state;
187 };
188
189 /*
190 * Init restart_muladd sub-context
191 */
ecp_restart_ma_init(mbedtls_ecp_restart_muladd_ctx * ctx)192 static void ecp_restart_ma_init(mbedtls_ecp_restart_muladd_ctx *ctx)
193 {
194 mbedtls_ecp_point_init(&ctx->mP);
195 mbedtls_ecp_point_init(&ctx->R);
196 ctx->state = ecp_rsma_mul1;
197 }
198
199 /*
200 * Free the components of a restart_muladd sub-context
201 */
ecp_restart_ma_free(mbedtls_ecp_restart_muladd_ctx * ctx)202 static void ecp_restart_ma_free(mbedtls_ecp_restart_muladd_ctx *ctx)
203 {
204 if (ctx == NULL) {
205 return;
206 }
207
208 mbedtls_ecp_point_free(&ctx->mP);
209 mbedtls_ecp_point_free(&ctx->R);
210
211 ecp_restart_ma_init(ctx);
212 }
213
214 /*
215 * Initialize a restart context
216 */
mbedtls_ecp_restart_init(mbedtls_ecp_restart_ctx * ctx)217 void mbedtls_ecp_restart_init(mbedtls_ecp_restart_ctx *ctx)
218 {
219 ctx->ops_done = 0;
220 ctx->depth = 0;
221 ctx->rsm = NULL;
222 ctx->ma = NULL;
223 }
224
225 /*
226 * Free the components of a restart context
227 */
mbedtls_ecp_restart_free(mbedtls_ecp_restart_ctx * ctx)228 void mbedtls_ecp_restart_free(mbedtls_ecp_restart_ctx *ctx)
229 {
230 if (ctx == NULL) {
231 return;
232 }
233
234 ecp_restart_rsm_free(ctx->rsm);
235 mbedtls_free(ctx->rsm);
236
237 ecp_restart_ma_free(ctx->ma);
238 mbedtls_free(ctx->ma);
239
240 mbedtls_ecp_restart_init(ctx);
241 }
242
243 /*
244 * Check if we can do the next step
245 */
mbedtls_ecp_check_budget(const mbedtls_ecp_group * grp,mbedtls_ecp_restart_ctx * rs_ctx,unsigned ops)246 int mbedtls_ecp_check_budget(const mbedtls_ecp_group *grp,
247 mbedtls_ecp_restart_ctx *rs_ctx,
248 unsigned ops)
249 {
250 if (rs_ctx != NULL && ecp_max_ops != 0) {
251 /* scale depending on curve size: the chosen reference is 256-bit,
252 * and multiplication is quadratic. Round to the closest integer. */
253 if (grp->pbits >= 512) {
254 ops *= 4;
255 } else if (grp->pbits >= 384) {
256 ops *= 2;
257 }
258
259 /* Avoid infinite loops: always allow first step.
260 * Because of that, however, it's not generally true
261 * that ops_done <= ecp_max_ops, so the check
262 * ops_done > ecp_max_ops below is mandatory. */
263 if ((rs_ctx->ops_done != 0) &&
264 (rs_ctx->ops_done > ecp_max_ops ||
265 ops > ecp_max_ops - rs_ctx->ops_done)) {
266 return MBEDTLS_ERR_ECP_IN_PROGRESS;
267 }
268
269 /* update running count */
270 rs_ctx->ops_done += ops;
271 }
272
273 return 0;
274 }
275
276 /* Call this when entering a function that needs its own sub-context */
277 #define ECP_RS_ENTER(SUB) do { \
278 /* reset ops count for this call if top-level */ \
279 if (rs_ctx != NULL && rs_ctx->depth++ == 0) \
280 rs_ctx->ops_done = 0; \
281 \
282 /* set up our own sub-context if needed */ \
283 if (mbedtls_ecp_restart_is_enabled() && \
284 rs_ctx != NULL && rs_ctx->SUB == NULL) \
285 { \
286 rs_ctx->SUB = mbedtls_calloc(1, sizeof(*rs_ctx->SUB)); \
287 if (rs_ctx->SUB == NULL) \
288 return MBEDTLS_ERR_ECP_ALLOC_FAILED; \
289 \
290 ecp_restart_## SUB ##_init(rs_ctx->SUB); \
291 } \
292 } while (0)
293
294 /* Call this when leaving a function that needs its own sub-context */
295 #define ECP_RS_LEAVE(SUB) do { \
296 /* clear our sub-context when not in progress (done or error) */ \
297 if (rs_ctx != NULL && rs_ctx->SUB != NULL && \
298 ret != MBEDTLS_ERR_ECP_IN_PROGRESS) \
299 { \
300 ecp_restart_## SUB ##_free(rs_ctx->SUB); \
301 mbedtls_free(rs_ctx->SUB); \
302 rs_ctx->SUB = NULL; \
303 } \
304 \
305 if (rs_ctx != NULL) \
306 rs_ctx->depth--; \
307 } while (0)
308
309 #else /* MBEDTLS_ECP_RESTARTABLE */
310
311 #define ECP_RS_ENTER(sub) (void) rs_ctx;
312 #define ECP_RS_LEAVE(sub) (void) rs_ctx;
313
314 #endif /* MBEDTLS_ECP_RESTARTABLE */
315
316 #if defined(MBEDTLS_ECP_C)
mpi_init_many(mbedtls_mpi * arr,size_t size)317 static void mpi_init_many(mbedtls_mpi *arr, size_t size)
318 {
319 while (size--) {
320 mbedtls_mpi_init(arr++);
321 }
322 }
323
mpi_free_many(mbedtls_mpi * arr,size_t size)324 static void mpi_free_many(mbedtls_mpi *arr, size_t size)
325 {
326 while (size--) {
327 mbedtls_mpi_free(arr++);
328 }
329 }
330 #endif /* MBEDTLS_ECP_C */
331
332 /*
333 * List of supported curves:
334 * - internal ID
335 * - TLS NamedCurve ID (RFC 4492 sec. 5.1.1, RFC 7071 sec. 2, RFC 8446 sec. 4.2.7)
336 * - size in bits
337 * - readable name
338 *
339 * Curves are listed in order: largest curves first, and for a given size,
340 * fastest curves first.
341 *
342 * Reminder: update profiles in x509_crt.c and ssl_tls.c when adding a new curve!
343 */
344 static const mbedtls_ecp_curve_info ecp_supported_curves[] =
345 {
346 #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
347 { MBEDTLS_ECP_DP_SECP521R1, 25, 521, "secp521r1" },
348 #endif
349 #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
350 { MBEDTLS_ECP_DP_BP512R1, 28, 512, "brainpoolP512r1" },
351 #endif
352 #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
353 { MBEDTLS_ECP_DP_SECP384R1, 24, 384, "secp384r1" },
354 #endif
355 #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
356 { MBEDTLS_ECP_DP_BP384R1, 27, 384, "brainpoolP384r1" },
357 #endif
358 #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
359 { MBEDTLS_ECP_DP_SECP256R1, 23, 256, "secp256r1" },
360 #endif
361 #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
362 { MBEDTLS_ECP_DP_SECP256K1, 22, 256, "secp256k1" },
363 #endif
364 #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
365 { MBEDTLS_ECP_DP_BP256R1, 26, 256, "brainpoolP256r1" },
366 #endif
367 #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
368 { MBEDTLS_ECP_DP_SECP224R1, 21, 224, "secp224r1" },
369 #endif
370 #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
371 { MBEDTLS_ECP_DP_SECP224K1, 20, 224, "secp224k1" },
372 #endif
373 #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
374 { MBEDTLS_ECP_DP_SECP192R1, 19, 192, "secp192r1" },
375 #endif
376 #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
377 { MBEDTLS_ECP_DP_SECP192K1, 18, 192, "secp192k1" },
378 #endif
379 #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
380 { MBEDTLS_ECP_DP_CURVE25519, 29, 256, "x25519" },
381 #endif
382 #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
383 { MBEDTLS_ECP_DP_CURVE448, 30, 448, "x448" },
384 #endif
385 #if defined(MBEDTLS_ECP_DP_SM2_ENABLED)
386 /* https://tools.ietf.org/id/draft-yang-tls-tls13-sm-suites-05.html */
387 { MBEDTLS_ECP_DP_SM2, 41, 256, "sm2" },
388 #endif
389 { MBEDTLS_ECP_DP_NONE, 0, 0, NULL },
390 };
391
392 #define ECP_NB_CURVES sizeof(ecp_supported_curves) / \
393 sizeof(ecp_supported_curves[0])
394
395 static mbedtls_ecp_group_id ecp_supported_grp_id[ECP_NB_CURVES];
396
397 /*
398 * List of supported curves and associated info
399 */
mbedtls_ecp_curve_list(void)400 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list(void)
401 {
402 return ecp_supported_curves;
403 }
404
405 /*
406 * List of supported curves, group ID only
407 */
mbedtls_ecp_grp_id_list(void)408 const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list(void)
409 {
410 static int init_done = 0;
411
412 if (!init_done) {
413 size_t i = 0;
414 const mbedtls_ecp_curve_info *curve_info;
415
416 for (curve_info = mbedtls_ecp_curve_list();
417 curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
418 curve_info++) {
419 ecp_supported_grp_id[i++] = curve_info->grp_id;
420 }
421 ecp_supported_grp_id[i] = MBEDTLS_ECP_DP_NONE;
422
423 init_done = 1;
424 }
425
426 return ecp_supported_grp_id;
427 }
428
429 /*
430 * Get the curve info for the internal identifier
431 */
mbedtls_ecp_curve_info_from_grp_id(mbedtls_ecp_group_id grp_id)432 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id(mbedtls_ecp_group_id grp_id)
433 {
434 const mbedtls_ecp_curve_info *curve_info;
435
436 for (curve_info = mbedtls_ecp_curve_list();
437 curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
438 curve_info++) {
439 if (curve_info->grp_id == grp_id) {
440 return curve_info;
441 }
442 }
443
444 return NULL;
445 }
446
447 /*
448 * Get the curve info from the TLS identifier
449 */
mbedtls_ecp_curve_info_from_tls_id(uint16_t tls_id)450 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id(uint16_t tls_id)
451 {
452 const mbedtls_ecp_curve_info *curve_info;
453
454 for (curve_info = mbedtls_ecp_curve_list();
455 curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
456 curve_info++) {
457 if (curve_info->tls_id == tls_id) {
458 return curve_info;
459 }
460 }
461
462 return NULL;
463 }
464
465 /*
466 * Get the curve info from the name
467 */
mbedtls_ecp_curve_info_from_name(const char * name)468 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name(const char *name)
469 {
470 const mbedtls_ecp_curve_info *curve_info;
471
472 if (name == NULL) {
473 return NULL;
474 }
475
476 for (curve_info = mbedtls_ecp_curve_list();
477 curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
478 curve_info++) {
479 if (strcmp(curve_info->name, name) == 0) {
480 return curve_info;
481 }
482 }
483
484 return NULL;
485 }
486
487 /*
488 * Get the type of a curve
489 */
mbedtls_ecp_get_type(const mbedtls_ecp_group * grp)490 mbedtls_ecp_curve_type mbedtls_ecp_get_type(const mbedtls_ecp_group *grp)
491 {
492 if (grp->G.X.p == NULL) {
493 return MBEDTLS_ECP_TYPE_NONE;
494 }
495
496 if (grp->G.Y.p == NULL) {
497 return MBEDTLS_ECP_TYPE_MONTGOMERY;
498 } else {
499 return MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS;
500 }
501 }
502
503 /*
504 * Initialize (the components of) a point
505 */
mbedtls_ecp_point_init(mbedtls_ecp_point * pt)506 void mbedtls_ecp_point_init(mbedtls_ecp_point *pt)
507 {
508 mbedtls_mpi_init(&pt->X);
509 mbedtls_mpi_init(&pt->Y);
510 mbedtls_mpi_init(&pt->Z);
511 }
512
513 /*
514 * Initialize (the components of) a group
515 */
mbedtls_ecp_group_init(mbedtls_ecp_group * grp)516 void mbedtls_ecp_group_init(mbedtls_ecp_group *grp)
517 {
518 grp->id = MBEDTLS_ECP_DP_NONE;
519 mbedtls_mpi_init(&grp->P);
520 mbedtls_mpi_init(&grp->A);
521 mbedtls_mpi_init(&grp->B);
522 mbedtls_ecp_point_init(&grp->G);
523 mbedtls_mpi_init(&grp->N);
524 grp->pbits = 0;
525 grp->nbits = 0;
526 grp->h = 0;
527 grp->modp = NULL;
528 grp->t_pre = NULL;
529 grp->t_post = NULL;
530 grp->t_data = NULL;
531 grp->T = NULL;
532 grp->T_size = 0;
533 }
534
535 /*
536 * Initialize (the components of) a key pair
537 */
mbedtls_ecp_keypair_init(mbedtls_ecp_keypair * key)538 void mbedtls_ecp_keypair_init(mbedtls_ecp_keypair *key)
539 {
540 mbedtls_ecp_group_init(&key->grp);
541 mbedtls_mpi_init(&key->d);
542 mbedtls_ecp_point_init(&key->Q);
543 }
544
545 /*
546 * Unallocate (the components of) a point
547 */
mbedtls_ecp_point_free(mbedtls_ecp_point * pt)548 void mbedtls_ecp_point_free(mbedtls_ecp_point *pt)
549 {
550 if (pt == NULL) {
551 return;
552 }
553
554 mbedtls_mpi_free(&(pt->X));
555 mbedtls_mpi_free(&(pt->Y));
556 mbedtls_mpi_free(&(pt->Z));
557 }
558
559 /*
560 * Check that the comb table (grp->T) is static initialized.
561 */
ecp_group_is_static_comb_table(const mbedtls_ecp_group * grp)562 static int ecp_group_is_static_comb_table(const mbedtls_ecp_group *grp)
563 {
564 #if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1
565 return grp->T != NULL && grp->T_size == 0;
566 #else
567 (void) grp;
568 return 0;
569 #endif
570 }
571
572 /*
573 * Unallocate (the components of) a group
574 */
mbedtls_ecp_group_free(mbedtls_ecp_group * grp)575 void mbedtls_ecp_group_free(mbedtls_ecp_group *grp)
576 {
577 size_t i;
578
579 if (grp == NULL) {
580 return;
581 }
582
583 if (grp->h != 1) {
584 mbedtls_mpi_free(&grp->A);
585 mbedtls_mpi_free(&grp->B);
586 mbedtls_ecp_point_free(&grp->G);
587
588 #if !defined(MBEDTLS_ECP_WITH_MPI_UINT)
589 mbedtls_mpi_free(&grp->N);
590 mbedtls_mpi_free(&grp->P);
591 #endif
592 }
593
594 if (!ecp_group_is_static_comb_table(grp) && grp->T != NULL) {
595 for (i = 0; i < grp->T_size; i++) {
596 mbedtls_ecp_point_free(&grp->T[i]);
597 }
598 mbedtls_free(grp->T);
599 }
600
601 mbedtls_platform_zeroize(grp, sizeof(mbedtls_ecp_group));
602 }
603
604 /*
605 * Unallocate (the components of) a key pair
606 */
mbedtls_ecp_keypair_free(mbedtls_ecp_keypair * key)607 void mbedtls_ecp_keypair_free(mbedtls_ecp_keypair *key)
608 {
609 if (key == NULL) {
610 return;
611 }
612
613 mbedtls_ecp_group_free(&key->grp);
614 mbedtls_mpi_free(&key->d);
615 mbedtls_ecp_point_free(&key->Q);
616 }
617
618 /*
619 * Copy the contents of a point
620 */
mbedtls_ecp_copy(mbedtls_ecp_point * P,const mbedtls_ecp_point * Q)621 int mbedtls_ecp_copy(mbedtls_ecp_point *P, const mbedtls_ecp_point *Q)
622 {
623 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
624 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&P->X, &Q->X));
625 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&P->Y, &Q->Y));
626 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&P->Z, &Q->Z));
627
628 cleanup:
629 return ret;
630 }
631
632 /*
633 * Copy the contents of a group object
634 */
mbedtls_ecp_group_copy(mbedtls_ecp_group * dst,const mbedtls_ecp_group * src)635 int mbedtls_ecp_group_copy(mbedtls_ecp_group *dst, const mbedtls_ecp_group *src)
636 {
637 return mbedtls_ecp_group_load(dst, src->id);
638 }
639
640 /*
641 * Set point to zero
642 */
mbedtls_ecp_set_zero(mbedtls_ecp_point * pt)643 int mbedtls_ecp_set_zero(mbedtls_ecp_point *pt)
644 {
645 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
646 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->X, 1));
647 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Y, 1));
648 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Z, 0));
649
650 cleanup:
651 return ret;
652 }
653
654 /*
655 * Tell if a point is zero
656 */
mbedtls_ecp_is_zero(mbedtls_ecp_point * pt)657 int mbedtls_ecp_is_zero(mbedtls_ecp_point *pt)
658 {
659 return mbedtls_mpi_cmp_int(&pt->Z, 0) == 0;
660 }
661
662 /*
663 * Compare two points lazily
664 */
mbedtls_ecp_point_cmp(const mbedtls_ecp_point * P,const mbedtls_ecp_point * Q)665 int mbedtls_ecp_point_cmp(const mbedtls_ecp_point *P,
666 const mbedtls_ecp_point *Q)
667 {
668 if (mbedtls_mpi_cmp_mpi(&P->X, &Q->X) == 0 &&
669 mbedtls_mpi_cmp_mpi(&P->Y, &Q->Y) == 0 &&
670 mbedtls_mpi_cmp_mpi(&P->Z, &Q->Z) == 0) {
671 return 0;
672 }
673
674 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
675 }
676
677 /*
678 * Import a non-zero point from ASCII strings
679 */
mbedtls_ecp_point_read_string(mbedtls_ecp_point * P,int radix,const char * x,const char * y)680 int mbedtls_ecp_point_read_string(mbedtls_ecp_point *P, int radix,
681 const char *x, const char *y)
682 {
683 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
684 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&P->X, radix, x));
685 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&P->Y, radix, y));
686 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&P->Z, 1));
687
688 cleanup:
689 return ret;
690 }
691
692 /*
693 * Export a point into unsigned binary data (SEC1 2.3.3 and RFC7748)
694 */
mbedtls_ecp_point_write_binary(const mbedtls_ecp_group * grp,const mbedtls_ecp_point * P,int format,size_t * olen,unsigned char * buf,size_t buflen)695 int mbedtls_ecp_point_write_binary(const mbedtls_ecp_group *grp,
696 const mbedtls_ecp_point *P,
697 int format, size_t *olen,
698 unsigned char *buf, size_t buflen)
699 {
700 int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
701 size_t plen;
702 if (format != MBEDTLS_ECP_PF_UNCOMPRESSED &&
703 format != MBEDTLS_ECP_PF_COMPRESSED) {
704 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
705 }
706
707 plen = mbedtls_mpi_size(&grp->P);
708
709 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
710 (void) format; /* Montgomery curves always use the same point format */
711 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
712 *olen = plen;
713 if (buflen < *olen) {
714 return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
715 }
716
717 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary_le(&P->X, buf, plen));
718 }
719 #endif
720 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
721 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
722 /*
723 * Common case: P == 0
724 */
725 if (mbedtls_mpi_cmp_int(&P->Z, 0) == 0) {
726 if (buflen < 1) {
727 return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
728 }
729
730 buf[0] = 0x00;
731 *olen = 1;
732
733 return 0;
734 }
735
736 if (format == MBEDTLS_ECP_PF_UNCOMPRESSED) {
737 *olen = 2 * plen + 1;
738
739 if (buflen < *olen) {
740 return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
741 }
742
743 buf[0] = 0x04;
744 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&P->X, buf + 1, plen));
745 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&P->Y, buf + 1 + plen, plen));
746 } else if (format == MBEDTLS_ECP_PF_COMPRESSED) {
747 *olen = plen + 1;
748
749 if (buflen < *olen) {
750 return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
751 }
752
753 buf[0] = 0x02 + mbedtls_mpi_get_bit(&P->Y, 0);
754 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&P->X, buf + 1, plen));
755 }
756 }
757 #endif
758
759 cleanup:
760 return ret;
761 }
762
763 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
764 static int mbedtls_ecp_sw_derive_y(const mbedtls_ecp_group *grp,
765 const mbedtls_mpi *X,
766 mbedtls_mpi *Y,
767 int parity_bit);
768 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
769
770 /*
771 * Import a point from unsigned binary data (SEC1 2.3.4 and RFC7748)
772 */
mbedtls_ecp_point_read_binary(const mbedtls_ecp_group * grp,mbedtls_ecp_point * pt,const unsigned char * buf,size_t ilen)773 int mbedtls_ecp_point_read_binary(const mbedtls_ecp_group *grp,
774 mbedtls_ecp_point *pt,
775 const unsigned char *buf, size_t ilen)
776 {
777 int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
778 size_t plen;
779 if (ilen < 1) {
780 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
781 }
782
783 plen = mbedtls_mpi_size(&grp->P);
784
785 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
786 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
787 if (plen != ilen) {
788 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
789 }
790
791 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary_le(&pt->X, buf, plen));
792 mbedtls_mpi_free(&pt->Y);
793
794 if (grp->id == MBEDTLS_ECP_DP_CURVE25519) {
795 /* Set most significant bit to 0 as prescribed in RFC7748 §5 */
796 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&pt->X, plen * 8 - 1, 0));
797 }
798
799 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Z, 1));
800 }
801 #endif
802 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
803 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
804 if (buf[0] == 0x00) {
805 if (ilen == 1) {
806 return mbedtls_ecp_set_zero(pt);
807 } else {
808 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
809 }
810 }
811
812 if (ilen < 1 + plen) {
813 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
814 }
815
816 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&pt->X, buf + 1, plen));
817 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&pt->Z, 1));
818
819 if (buf[0] == 0x04) {
820 /* format == MBEDTLS_ECP_PF_UNCOMPRESSED */
821 if (ilen != 1 + plen * 2) {
822 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
823 }
824 return mbedtls_mpi_read_binary(&pt->Y, buf + 1 + plen, plen);
825 } else if (buf[0] == 0x02 || buf[0] == 0x03) {
826 /* format == MBEDTLS_ECP_PF_COMPRESSED */
827 if (ilen != 1 + plen) {
828 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
829 }
830 return mbedtls_ecp_sw_derive_y(grp, &pt->X, &pt->Y,
831 (buf[0] & 1));
832 } else {
833 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
834 }
835 }
836 #endif
837
838 cleanup:
839 return ret;
840 }
841
842 /*
843 * Import a point from a TLS ECPoint record (RFC 4492)
844 * struct {
845 * opaque point <1..2^8-1>;
846 * } ECPoint;
847 */
mbedtls_ecp_tls_read_point(const mbedtls_ecp_group * grp,mbedtls_ecp_point * pt,const unsigned char ** buf,size_t buf_len)848 int mbedtls_ecp_tls_read_point(const mbedtls_ecp_group *grp,
849 mbedtls_ecp_point *pt,
850 const unsigned char **buf, size_t buf_len)
851 {
852 unsigned char data_len;
853 const unsigned char *buf_start;
854 /*
855 * We must have at least two bytes (1 for length, at least one for data)
856 */
857 if (buf_len < 2) {
858 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
859 }
860
861 data_len = *(*buf)++;
862 if (data_len < 1 || data_len > buf_len - 1) {
863 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
864 }
865
866 /*
867 * Save buffer start for read_binary and update buf
868 */
869 buf_start = *buf;
870 *buf += data_len;
871
872 return mbedtls_ecp_point_read_binary(grp, pt, buf_start, data_len);
873 }
874
875 /*
876 * Export a point as a TLS ECPoint record (RFC 4492)
877 * struct {
878 * opaque point <1..2^8-1>;
879 * } ECPoint;
880 */
mbedtls_ecp_tls_write_point(const mbedtls_ecp_group * grp,const mbedtls_ecp_point * pt,int format,size_t * olen,unsigned char * buf,size_t blen)881 int mbedtls_ecp_tls_write_point(const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt,
882 int format, size_t *olen,
883 unsigned char *buf, size_t blen)
884 {
885 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
886 if (format != MBEDTLS_ECP_PF_UNCOMPRESSED &&
887 format != MBEDTLS_ECP_PF_COMPRESSED) {
888 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
889 }
890
891 /*
892 * buffer length must be at least one, for our length byte
893 */
894 if (blen < 1) {
895 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
896 }
897
898 if ((ret = mbedtls_ecp_point_write_binary(grp, pt, format,
899 olen, buf + 1, blen - 1)) != 0) {
900 return ret;
901 }
902
903 /*
904 * write length to the first byte and update total length
905 */
906 buf[0] = (unsigned char) *olen;
907 ++*olen;
908
909 return 0;
910 }
911
912 /*
913 * Set a group from an ECParameters record (RFC 4492)
914 */
mbedtls_ecp_tls_read_group(mbedtls_ecp_group * grp,const unsigned char ** buf,size_t len)915 int mbedtls_ecp_tls_read_group(mbedtls_ecp_group *grp,
916 const unsigned char **buf, size_t len)
917 {
918 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
919 mbedtls_ecp_group_id grp_id;
920 if ((ret = mbedtls_ecp_tls_read_group_id(&grp_id, buf, len)) != 0) {
921 return ret;
922 }
923
924 return mbedtls_ecp_group_load(grp, grp_id);
925 }
926
927 /*
928 * Read a group id from an ECParameters record (RFC 4492) and convert it to
929 * mbedtls_ecp_group_id.
930 */
mbedtls_ecp_tls_read_group_id(mbedtls_ecp_group_id * grp,const unsigned char ** buf,size_t len)931 int mbedtls_ecp_tls_read_group_id(mbedtls_ecp_group_id *grp,
932 const unsigned char **buf, size_t len)
933 {
934 uint16_t tls_id;
935 const mbedtls_ecp_curve_info *curve_info;
936 /*
937 * We expect at least three bytes (see below)
938 */
939 if (len < 3) {
940 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
941 }
942
943 /*
944 * First byte is curve_type; only named_curve is handled
945 */
946 if (*(*buf)++ != MBEDTLS_ECP_TLS_NAMED_CURVE) {
947 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
948 }
949
950 /*
951 * Next two bytes are the namedcurve value
952 */
953 tls_id = MBEDTLS_GET_UINT16_BE(*buf, 0);
954 *buf += 2;
955
956 if ((curve_info = mbedtls_ecp_curve_info_from_tls_id(tls_id)) == NULL) {
957 return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
958 }
959
960 *grp = curve_info->grp_id;
961
962 return 0;
963 }
964
965 /*
966 * Write the ECParameters record corresponding to a group (RFC 4492)
967 */
mbedtls_ecp_tls_write_group(const mbedtls_ecp_group * grp,size_t * olen,unsigned char * buf,size_t blen)968 int mbedtls_ecp_tls_write_group(const mbedtls_ecp_group *grp, size_t *olen,
969 unsigned char *buf, size_t blen)
970 {
971 const mbedtls_ecp_curve_info *curve_info;
972 if ((curve_info = mbedtls_ecp_curve_info_from_grp_id(grp->id)) == NULL) {
973 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
974 }
975
976 /*
977 * We are going to write 3 bytes (see below)
978 */
979 *olen = 3;
980 if (blen < *olen) {
981 return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
982 }
983
984 /*
985 * First byte is curve_type, always named_curve
986 */
987 *buf++ = MBEDTLS_ECP_TLS_NAMED_CURVE;
988
989 /*
990 * Next two bytes are the namedcurve value
991 */
992 MBEDTLS_PUT_UINT16_BE(curve_info->tls_id, buf, 0);
993
994 return 0;
995 }
996
997 /*
998 * Wrapper around fast quasi-modp functions, with fall-back to mbedtls_mpi_mod_mpi.
999 * See the documentation of struct mbedtls_ecp_group.
1000 *
1001 * This function is in the critial loop for mbedtls_ecp_mul, so pay attention to perf.
1002 */
ecp_modp(mbedtls_mpi * N,const mbedtls_ecp_group * grp)1003 static int ecp_modp(mbedtls_mpi *N, const mbedtls_ecp_group *grp)
1004 {
1005 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1006
1007 if (grp->modp == NULL) {
1008 return mbedtls_mpi_mod_mpi(N, N, &grp->P);
1009 }
1010
1011 /* N->s < 0 is a much faster test, which fails only if N is 0 */
1012 if ((N->s < 0 && mbedtls_mpi_cmp_int(N, 0) != 0) ||
1013 mbedtls_mpi_bitlen(N) > 2 * grp->pbits) {
1014 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
1015 }
1016
1017 MBEDTLS_MPI_CHK(grp->modp(N));
1018
1019 /* N->s < 0 is a much faster test, which fails only if N is 0 */
1020 while (N->s < 0 && mbedtls_mpi_cmp_int(N, 0) != 0) {
1021 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(N, N, &grp->P));
1022 }
1023
1024 while (mbedtls_mpi_cmp_mpi(N, &grp->P) >= 0) {
1025 /* we known P, N and the result are positive */
1026 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(N, N, &grp->P));
1027 }
1028
1029 cleanup:
1030 return ret;
1031 }
1032
1033 /*
1034 * Fast mod-p functions expect their argument to be in the 0..p^2 range.
1035 *
1036 * In order to guarantee that, we need to ensure that operands of
1037 * mbedtls_mpi_mul_mpi are in the 0..p range. So, after each operation we will
1038 * bring the result back to this range.
1039 *
1040 * The following macros are shortcuts for doing that.
1041 */
1042
1043 /*
1044 * Reduce a mbedtls_mpi mod p in-place, general case, to use after mbedtls_mpi_mul_mpi
1045 */
1046 #if defined(MBEDTLS_SELF_TEST)
1047 #define INC_MUL_COUNT mul_count++;
1048 #else
1049 #define INC_MUL_COUNT
1050 #endif
1051
1052 #define MOD_MUL(N) \
1053 do \
1054 { \
1055 MBEDTLS_MPI_CHK(ecp_modp(&(N), grp)); \
1056 INC_MUL_COUNT \
1057 } while (0)
1058
mbedtls_mpi_mul_mod(const mbedtls_ecp_group * grp,mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1059 static inline int mbedtls_mpi_mul_mod(const mbedtls_ecp_group *grp,
1060 mbedtls_mpi *X,
1061 const mbedtls_mpi *A,
1062 const mbedtls_mpi *B)
1063 {
1064 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1065 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(X, A, B));
1066 MOD_MUL(*X);
1067 cleanup:
1068 return ret;
1069 }
1070
1071 /*
1072 * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_sub_mpi
1073 * N->s < 0 is a very fast test, which fails only if N is 0
1074 */
1075 #define MOD_SUB(N) \
1076 do { \
1077 while ((N)->s < 0 && mbedtls_mpi_cmp_int((N), 0) != 0) \
1078 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi((N), (N), &grp->P)); \
1079 } while (0)
1080
1081 MBEDTLS_MAYBE_UNUSED
mbedtls_mpi_sub_mod(const mbedtls_ecp_group * grp,mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1082 static inline int mbedtls_mpi_sub_mod(const mbedtls_ecp_group *grp,
1083 mbedtls_mpi *X,
1084 const mbedtls_mpi *A,
1085 const mbedtls_mpi *B)
1086 {
1087 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1088 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(X, A, B));
1089 MOD_SUB(X);
1090 cleanup:
1091 return ret;
1092 }
1093
1094 /*
1095 * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_add_mpi and mbedtls_mpi_mul_int.
1096 * We known P, N and the result are positive, so sub_abs is correct, and
1097 * a bit faster.
1098 */
1099 #define MOD_ADD(N) \
1100 while (mbedtls_mpi_cmp_mpi((N), &grp->P) >= 0) \
1101 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs((N), (N), &grp->P))
1102
mbedtls_mpi_add_mod(const mbedtls_ecp_group * grp,mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1103 static inline int mbedtls_mpi_add_mod(const mbedtls_ecp_group *grp,
1104 mbedtls_mpi *X,
1105 const mbedtls_mpi *A,
1106 const mbedtls_mpi *B)
1107 {
1108 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1109 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(X, A, B));
1110 MOD_ADD(X);
1111 cleanup:
1112 return ret;
1113 }
1114
1115 MBEDTLS_MAYBE_UNUSED
mbedtls_mpi_mul_int_mod(const mbedtls_ecp_group * grp,mbedtls_mpi * X,const mbedtls_mpi * A,mbedtls_mpi_uint c)1116 static inline int mbedtls_mpi_mul_int_mod(const mbedtls_ecp_group *grp,
1117 mbedtls_mpi *X,
1118 const mbedtls_mpi *A,
1119 mbedtls_mpi_uint c)
1120 {
1121 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1122
1123 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int(X, A, c));
1124 MOD_ADD(X);
1125 cleanup:
1126 return ret;
1127 }
1128
1129 MBEDTLS_MAYBE_UNUSED
mbedtls_mpi_sub_int_mod(const mbedtls_ecp_group * grp,mbedtls_mpi * X,const mbedtls_mpi * A,mbedtls_mpi_uint c)1130 static inline int mbedtls_mpi_sub_int_mod(const mbedtls_ecp_group *grp,
1131 mbedtls_mpi *X,
1132 const mbedtls_mpi *A,
1133 mbedtls_mpi_uint c)
1134 {
1135 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1136
1137 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(X, A, c));
1138 MOD_SUB(X);
1139 cleanup:
1140 return ret;
1141 }
1142
1143 #define MPI_ECP_SUB_INT(X, A, c) \
1144 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int_mod(grp, X, A, c))
1145
1146 MBEDTLS_MAYBE_UNUSED
mbedtls_mpi_shift_l_mod(const mbedtls_ecp_group * grp,mbedtls_mpi * X,size_t count)1147 static inline int mbedtls_mpi_shift_l_mod(const mbedtls_ecp_group *grp,
1148 mbedtls_mpi *X,
1149 size_t count)
1150 {
1151 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1152 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(X, count));
1153 MOD_ADD(X);
1154 cleanup:
1155 return ret;
1156 }
1157
1158 /*
1159 * Macro wrappers around ECP modular arithmetic
1160 *
1161 * Currently, these wrappers are defined via the bignum module.
1162 */
1163
1164 #define MPI_ECP_ADD(X, A, B) \
1165 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mod(grp, X, A, B))
1166
1167 #define MPI_ECP_SUB(X, A, B) \
1168 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mod(grp, X, A, B))
1169
1170 #define MPI_ECP_MUL(X, A, B) \
1171 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, X, A, B))
1172
1173 #define MPI_ECP_SQR(X, A) \
1174 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mod(grp, X, A, A))
1175
1176 #define MPI_ECP_MUL_INT(X, A, c) \
1177 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int_mod(grp, X, A, c))
1178
1179 #define MPI_ECP_INV(dst, src) \
1180 MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod((dst), (src), &grp->P))
1181
1182 #define MPI_ECP_MOV(X, A) \
1183 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, A))
1184
1185 #define MPI_ECP_SHIFT_L(X, count) \
1186 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l_mod(grp, X, count))
1187
1188 #define MPI_ECP_LSET(X, c) \
1189 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, c))
1190
1191 #define MPI_ECP_CMP_INT(X, c) \
1192 mbedtls_mpi_cmp_int(X, c)
1193
1194 #define MPI_ECP_CMP(X, Y) \
1195 mbedtls_mpi_cmp_mpi(X, Y)
1196
1197 /* Needs f_rng, p_rng to be defined. */
1198 #define MPI_ECP_RAND(X) \
1199 MBEDTLS_MPI_CHK(mbedtls_mpi_random((X), 2, &grp->P, f_rng, p_rng))
1200
1201 /* Conditional negation
1202 * Needs grp and a temporary MPI tmp to be defined. */
1203 #define MPI_ECP_COND_NEG(X, cond) \
1204 do \
1205 { \
1206 unsigned char nonzero = mbedtls_mpi_cmp_int((X), 0) != 0; \
1207 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&tmp, &grp->P, (X))); \
1208 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign((X), &tmp, \
1209 nonzero & cond)); \
1210 } while (0)
1211
1212 #define MPI_ECP_NEG(X) MPI_ECP_COND_NEG((X), 1)
1213
1214 #define MPI_ECP_VALID(X) \
1215 ((X)->p != NULL)
1216
1217 #define MPI_ECP_COND_ASSIGN(X, Y, cond) \
1218 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign((X), (Y), (cond)))
1219
1220 #define MPI_ECP_COND_SWAP(X, Y, cond) \
1221 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_swap((X), (Y), (cond)))
1222
1223 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
1224
1225 /*
1226 * Computes the right-hand side of the Short Weierstrass equation
1227 * RHS = X^3 + A X + B
1228 */
ecp_sw_rhs(const mbedtls_ecp_group * grp,mbedtls_mpi * rhs,const mbedtls_mpi * X)1229 static int ecp_sw_rhs(const mbedtls_ecp_group *grp,
1230 mbedtls_mpi *rhs,
1231 const mbedtls_mpi *X)
1232 {
1233 int ret;
1234
1235 /* Compute X^3 + A X + B as X (X^2 + A) + B */
1236 MPI_ECP_SQR(rhs, X);
1237
1238 /* Special case for A = -3 */
1239 if (mbedtls_ecp_group_a_is_minus_3(grp)) {
1240 MPI_ECP_SUB_INT(rhs, rhs, 3);
1241 } else {
1242 MPI_ECP_ADD(rhs, rhs, &grp->A);
1243 }
1244
1245 MPI_ECP_MUL(rhs, rhs, X);
1246 MPI_ECP_ADD(rhs, rhs, &grp->B);
1247
1248 cleanup:
1249 return ret;
1250 }
1251
1252 /*
1253 * Derive Y from X and a parity bit
1254 */
mbedtls_ecp_sw_derive_y(const mbedtls_ecp_group * grp,const mbedtls_mpi * X,mbedtls_mpi * Y,int parity_bit)1255 static int mbedtls_ecp_sw_derive_y(const mbedtls_ecp_group *grp,
1256 const mbedtls_mpi *X,
1257 mbedtls_mpi *Y,
1258 int parity_bit)
1259 {
1260 /* w = y^2 = x^3 + ax + b
1261 * y = sqrt(w) = w^((p+1)/4) mod p (for prime p where p = 3 mod 4)
1262 *
1263 * Note: this method for extracting square root does not validate that w
1264 * was indeed a square so this function will return garbage in Y if X
1265 * does not correspond to a point on the curve.
1266 */
1267
1268 /* Check prerequisite p = 3 mod 4 */
1269 if (mbedtls_mpi_get_bit(&grp->P, 0) != 1 ||
1270 mbedtls_mpi_get_bit(&grp->P, 1) != 1) {
1271 return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
1272 }
1273
1274 int ret;
1275 mbedtls_mpi exp;
1276 mbedtls_mpi_init(&exp);
1277
1278 /* use Y to store intermediate result, actually w above */
1279 MBEDTLS_MPI_CHK(ecp_sw_rhs(grp, Y, X));
1280
1281 /* w = y^2 */ /* Y contains y^2 intermediate result */
1282 /* exp = ((p+1)/4) */
1283 MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&exp, &grp->P, 1));
1284 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&exp, 2));
1285 /* sqrt(w) = w^((p+1)/4) mod p (for prime p where p = 3 mod 4) */
1286 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(Y, Y /*y^2*/, &exp, &grp->P, NULL));
1287
1288 /* check parity bit match or else invert Y */
1289 /* This quick inversion implementation is valid because Y != 0 for all
1290 * Short Weierstrass curves supported by mbedtls, as each supported curve
1291 * has an order that is a large prime, so each supported curve does not
1292 * have any point of order 2, and a point with Y == 0 would be of order 2 */
1293 if (mbedtls_mpi_get_bit(Y, 0) != parity_bit) {
1294 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(Y, &grp->P, Y));
1295 }
1296
1297 cleanup:
1298
1299 mbedtls_mpi_free(&exp);
1300 return ret;
1301 }
1302 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
1303
1304 #if defined(MBEDTLS_ECP_C)
1305 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
1306 /*
1307 * For curves in short Weierstrass form, we do all the internal operations in
1308 * Jacobian coordinates.
1309 *
1310 * For multiplication, we'll use a comb method with countermeasures against
1311 * SPA, hence timing attacks.
1312 */
1313
1314 /*
1315 * Normalize jacobian coordinates so that Z == 0 || Z == 1 (GECC 3.2.1)
1316 * Cost: 1N := 1I + 3M + 1S
1317 */
ecp_normalize_jac(const mbedtls_ecp_group * grp,mbedtls_ecp_point * pt)1318 static int ecp_normalize_jac(const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt)
1319 {
1320 if (MPI_ECP_CMP_INT(&pt->Z, 0) == 0) {
1321 return 0;
1322 }
1323
1324 #if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
1325 if (mbedtls_internal_ecp_grp_capable(grp)) {
1326 return mbedtls_internal_ecp_normalize_jac(grp, pt);
1327 }
1328 #endif /* MBEDTLS_ECP_NORMALIZE_JAC_ALT */
1329
1330 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
1331 return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
1332 #else
1333 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1334 mbedtls_mpi T;
1335 mbedtls_mpi_init(&T);
1336
1337 MPI_ECP_INV(&T, &pt->Z); /* T <- 1 / Z */
1338 MPI_ECP_MUL(&pt->Y, &pt->Y, &T); /* Y' <- Y*T = Y / Z */
1339 MPI_ECP_SQR(&T, &T); /* T <- T^2 = 1 / Z^2 */
1340 MPI_ECP_MUL(&pt->X, &pt->X, &T); /* X <- X * T = X / Z^2 */
1341 MPI_ECP_MUL(&pt->Y, &pt->Y, &T); /* Y'' <- Y' * T = Y / Z^3 */
1342
1343 MPI_ECP_LSET(&pt->Z, 1);
1344
1345 cleanup:
1346
1347 mbedtls_mpi_free(&T);
1348
1349 return ret;
1350 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) */
1351 }
1352
1353 /*
1354 * Normalize jacobian coordinates of an array of (pointers to) points,
1355 * using Montgomery's trick to perform only one inversion mod P.
1356 * (See for example Cohen's "A Course in Computational Algebraic Number
1357 * Theory", Algorithm 10.3.4.)
1358 *
1359 * Warning: fails (returning an error) if one of the points is zero!
1360 * This should never happen, see choice of w in ecp_mul_comb().
1361 *
1362 * Cost: 1N(t) := 1I + (6t - 3)M + 1S
1363 */
ecp_normalize_jac_many(const mbedtls_ecp_group * grp,mbedtls_ecp_point * T[],size_t T_size)1364 static int ecp_normalize_jac_many(const mbedtls_ecp_group *grp,
1365 mbedtls_ecp_point *T[], size_t T_size)
1366 {
1367 if (T_size < 2) {
1368 return ecp_normalize_jac(grp, *T);
1369 }
1370
1371 #if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)
1372 if (mbedtls_internal_ecp_grp_capable(grp)) {
1373 return mbedtls_internal_ecp_normalize_jac_many(grp, T, T_size);
1374 }
1375 #endif
1376
1377 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)
1378 return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
1379 #else
1380 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1381 size_t i;
1382 mbedtls_mpi *c, t;
1383
1384 if ((c = mbedtls_calloc(T_size, sizeof(mbedtls_mpi))) == NULL) {
1385 return MBEDTLS_ERR_ECP_ALLOC_FAILED;
1386 }
1387
1388 mbedtls_mpi_init(&t);
1389
1390 mpi_init_many(c, T_size);
1391 /*
1392 * c[i] = Z_0 * ... * Z_i, i = 0,..,n := T_size-1
1393 */
1394 MPI_ECP_MOV(&c[0], &T[0]->Z);
1395 for (i = 1; i < T_size; i++) {
1396 MPI_ECP_MUL(&c[i], &c[i-1], &T[i]->Z);
1397 }
1398
1399 /*
1400 * c[n] = 1 / (Z_0 * ... * Z_n) mod P
1401 */
1402 MPI_ECP_INV(&c[T_size-1], &c[T_size-1]);
1403
1404 for (i = T_size - 1;; i--) {
1405 /* At the start of iteration i (note that i decrements), we have
1406 * - c[j] = Z_0 * .... * Z_j for j < i,
1407 * - c[j] = 1 / (Z_0 * .... * Z_j) for j == i,
1408 *
1409 * This is maintained via
1410 * - c[i-1] <- c[i] * Z_i
1411 *
1412 * We also derive 1/Z_i = c[i] * c[i-1] for i>0 and use that
1413 * to do the actual normalization. For i==0, we already have
1414 * c[0] = 1 / Z_0.
1415 */
1416
1417 if (i > 0) {
1418 /* Compute 1/Z_i and establish invariant for the next iteration. */
1419 MPI_ECP_MUL(&t, &c[i], &c[i-1]);
1420 MPI_ECP_MUL(&c[i-1], &c[i], &T[i]->Z);
1421 } else {
1422 MPI_ECP_MOV(&t, &c[0]);
1423 }
1424
1425 /* Now t holds 1 / Z_i; normalize as in ecp_normalize_jac() */
1426 MPI_ECP_MUL(&T[i]->Y, &T[i]->Y, &t);
1427 MPI_ECP_SQR(&t, &t);
1428 MPI_ECP_MUL(&T[i]->X, &T[i]->X, &t);
1429 MPI_ECP_MUL(&T[i]->Y, &T[i]->Y, &t);
1430
1431 /*
1432 * Post-precessing: reclaim some memory by shrinking coordinates
1433 * - not storing Z (always 1)
1434 * - shrinking other coordinates, but still keeping the same number of
1435 * limbs as P, as otherwise it will too likely be regrown too fast.
1436 */
1437 MBEDTLS_MPI_CHK(mbedtls_mpi_shrink(&T[i]->X, grp->P.n));
1438 MBEDTLS_MPI_CHK(mbedtls_mpi_shrink(&T[i]->Y, grp->P.n));
1439
1440 MPI_ECP_LSET(&T[i]->Z, 1);
1441
1442 if (i == 0) {
1443 break;
1444 }
1445 }
1446
1447 cleanup:
1448
1449 mbedtls_mpi_free(&t);
1450 mpi_free_many(c, T_size);
1451 mbedtls_free(c);
1452
1453 return ret;
1454 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) */
1455 }
1456
1457 /*
1458 * Conditional point inversion: Q -> -Q = (Q.X, -Q.Y, Q.Z) without leak.
1459 * "inv" must be 0 (don't invert) or 1 (invert) or the result will be invalid
1460 */
ecp_safe_invert_jac(const mbedtls_ecp_group * grp,mbedtls_ecp_point * Q,unsigned char inv)1461 static int ecp_safe_invert_jac(const mbedtls_ecp_group *grp,
1462 mbedtls_ecp_point *Q,
1463 unsigned char inv)
1464 {
1465 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1466 mbedtls_mpi tmp;
1467 mbedtls_mpi_init(&tmp);
1468
1469 MPI_ECP_COND_NEG(&Q->Y, inv);
1470
1471 cleanup:
1472 mbedtls_mpi_free(&tmp);
1473 return ret;
1474 }
1475
1476 /*
1477 * Point doubling R = 2 P, Jacobian coordinates
1478 *
1479 * Based on http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-1998-cmo-2 .
1480 *
1481 * We follow the variable naming fairly closely. The formula variations that trade a MUL for a SQR
1482 * (plus a few ADDs) aren't useful as our bignum implementation doesn't distinguish squaring.
1483 *
1484 * Standard optimizations are applied when curve parameter A is one of { 0, -3 }.
1485 *
1486 * Cost: 1D := 3M + 4S (A == 0)
1487 * 4M + 4S (A == -3)
1488 * 3M + 6S + 1a otherwise
1489 */
ecp_double_jac(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_ecp_point * P,mbedtls_mpi tmp[4])1490 static int ecp_double_jac(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1491 const mbedtls_ecp_point *P,
1492 mbedtls_mpi tmp[4])
1493 {
1494 #if defined(MBEDTLS_SELF_TEST)
1495 dbl_count++;
1496 #endif
1497
1498 #if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
1499 if (mbedtls_internal_ecp_grp_capable(grp)) {
1500 return mbedtls_internal_ecp_double_jac(grp, R, P);
1501 }
1502 #endif /* MBEDTLS_ECP_DOUBLE_JAC_ALT */
1503
1504 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
1505 return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
1506 #else
1507 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1508
1509 /* Special case for A = -3 */
1510 if (mbedtls_ecp_group_a_is_minus_3(grp)) {
1511 /* tmp[0] <- M = 3(X + Z^2)(X - Z^2) */
1512 MPI_ECP_SQR(&tmp[1], &P->Z);
1513 MPI_ECP_ADD(&tmp[2], &P->X, &tmp[1]);
1514 MPI_ECP_SUB(&tmp[3], &P->X, &tmp[1]);
1515 MPI_ECP_MUL(&tmp[1], &tmp[2], &tmp[3]);
1516 MPI_ECP_MUL_INT(&tmp[0], &tmp[1], 3);
1517 } else {
1518 /* tmp[0] <- M = 3.X^2 + A.Z^4 */
1519 MPI_ECP_SQR(&tmp[1], &P->X);
1520 MPI_ECP_MUL_INT(&tmp[0], &tmp[1], 3);
1521
1522 /* Optimize away for "koblitz" curves with A = 0 */
1523 if (MPI_ECP_CMP_INT(&grp->A, 0) != 0) {
1524 /* M += A.Z^4 */
1525 MPI_ECP_SQR(&tmp[1], &P->Z);
1526 MPI_ECP_SQR(&tmp[2], &tmp[1]);
1527 MPI_ECP_MUL(&tmp[1], &tmp[2], &grp->A);
1528 MPI_ECP_ADD(&tmp[0], &tmp[0], &tmp[1]);
1529 }
1530 }
1531
1532 /* tmp[1] <- S = 4.X.Y^2 */
1533 MPI_ECP_SQR(&tmp[2], &P->Y);
1534 MPI_ECP_SHIFT_L(&tmp[2], 1);
1535 MPI_ECP_MUL(&tmp[1], &P->X, &tmp[2]);
1536 MPI_ECP_SHIFT_L(&tmp[1], 1);
1537
1538 /* tmp[3] <- U = 8.Y^4 */
1539 MPI_ECP_SQR(&tmp[3], &tmp[2]);
1540 MPI_ECP_SHIFT_L(&tmp[3], 1);
1541
1542 /* tmp[2] <- T = M^2 - 2.S */
1543 MPI_ECP_SQR(&tmp[2], &tmp[0]);
1544 MPI_ECP_SUB(&tmp[2], &tmp[2], &tmp[1]);
1545 MPI_ECP_SUB(&tmp[2], &tmp[2], &tmp[1]);
1546
1547 /* tmp[1] <- S = M(S - T) - U */
1548 MPI_ECP_SUB(&tmp[1], &tmp[1], &tmp[2]);
1549 MPI_ECP_MUL(&tmp[1], &tmp[1], &tmp[0]);
1550 MPI_ECP_SUB(&tmp[1], &tmp[1], &tmp[3]);
1551
1552 /* tmp[3] <- U = 2.Y.Z */
1553 MPI_ECP_MUL(&tmp[3], &P->Y, &P->Z);
1554 MPI_ECP_SHIFT_L(&tmp[3], 1);
1555
1556 /* Store results */
1557 MPI_ECP_MOV(&R->X, &tmp[2]);
1558 MPI_ECP_MOV(&R->Y, &tmp[1]);
1559 MPI_ECP_MOV(&R->Z, &tmp[3]);
1560
1561 cleanup:
1562
1563 return ret;
1564 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) */
1565 }
1566
1567 /*
1568 * Addition: R = P + Q, mixed affine-Jacobian coordinates (GECC 3.22)
1569 *
1570 * The coordinates of Q must be normalized (= affine),
1571 * but those of P don't need to. R is not normalized.
1572 *
1573 * P,Q,R may alias, but only at the level of EC points: they must be either
1574 * equal as pointers, or disjoint (including the coordinate data buffers).
1575 * Fine-grained aliasing at the level of coordinates is not supported.
1576 *
1577 * Special cases: (1) P or Q is zero, (2) R is zero, (3) P == Q.
1578 * None of these cases can happen as intermediate step in ecp_mul_comb():
1579 * - at each step, P, Q and R are multiples of the base point, the factor
1580 * being less than its order, so none of them is zero;
1581 * - Q is an odd multiple of the base point, P an even multiple,
1582 * due to the choice of precomputed points in the modified comb method.
1583 * So branches for these cases do not leak secret information.
1584 *
1585 * Cost: 1A := 8M + 3S
1586 */
ecp_add_mixed(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_ecp_point * P,const mbedtls_ecp_point * Q,mbedtls_mpi tmp[4])1587 static int ecp_add_mixed(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1588 const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q,
1589 mbedtls_mpi tmp[4])
1590 {
1591 #if defined(MBEDTLS_SELF_TEST)
1592 add_count++;
1593 #endif
1594
1595 #if defined(MBEDTLS_ECP_ADD_MIXED_ALT)
1596 if (mbedtls_internal_ecp_grp_capable(grp)) {
1597 return mbedtls_internal_ecp_add_mixed(grp, R, P, Q);
1598 }
1599 #endif /* MBEDTLS_ECP_ADD_MIXED_ALT */
1600
1601 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_ADD_MIXED_ALT)
1602 return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
1603 #else
1604 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1605
1606 /* NOTE: Aliasing between input and output is allowed, so one has to make
1607 * sure that at the point X,Y,Z are written, {P,Q}->{X,Y,Z} are no
1608 * longer read from. */
1609 mbedtls_mpi * const X = &R->X;
1610 mbedtls_mpi * const Y = &R->Y;
1611 mbedtls_mpi * const Z = &R->Z;
1612
1613 if (!MPI_ECP_VALID(&Q->Z)) {
1614 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
1615 }
1616
1617 /*
1618 * Trivial cases: P == 0 or Q == 0 (case 1)
1619 */
1620 if (MPI_ECP_CMP_INT(&P->Z, 0) == 0) {
1621 return mbedtls_ecp_copy(R, Q);
1622 }
1623
1624 if (MPI_ECP_CMP_INT(&Q->Z, 0) == 0) {
1625 return mbedtls_ecp_copy(R, P);
1626 }
1627
1628 /*
1629 * Make sure Q coordinates are normalized
1630 */
1631 if (MPI_ECP_CMP_INT(&Q->Z, 1) != 0) {
1632 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
1633 }
1634
1635 MPI_ECP_SQR(&tmp[0], &P->Z);
1636 MPI_ECP_MUL(&tmp[1], &tmp[0], &P->Z);
1637 MPI_ECP_MUL(&tmp[0], &tmp[0], &Q->X);
1638 MPI_ECP_MUL(&tmp[1], &tmp[1], &Q->Y);
1639 MPI_ECP_SUB(&tmp[0], &tmp[0], &P->X);
1640 MPI_ECP_SUB(&tmp[1], &tmp[1], &P->Y);
1641
1642 /* Special cases (2) and (3) */
1643 if (MPI_ECP_CMP_INT(&tmp[0], 0) == 0) {
1644 if (MPI_ECP_CMP_INT(&tmp[1], 0) == 0) {
1645 ret = ecp_double_jac(grp, R, P, tmp);
1646 goto cleanup;
1647 } else {
1648 ret = mbedtls_ecp_set_zero(R);
1649 goto cleanup;
1650 }
1651 }
1652
1653 /* {P,Q}->Z no longer used, so OK to write to Z even if there's aliasing. */
1654 MPI_ECP_MUL(Z, &P->Z, &tmp[0]);
1655 MPI_ECP_SQR(&tmp[2], &tmp[0]);
1656 MPI_ECP_MUL(&tmp[3], &tmp[2], &tmp[0]);
1657 MPI_ECP_MUL(&tmp[2], &tmp[2], &P->X);
1658
1659 MPI_ECP_MOV(&tmp[0], &tmp[2]);
1660 MPI_ECP_SHIFT_L(&tmp[0], 1);
1661
1662 /* {P,Q}->X no longer used, so OK to write to X even if there's aliasing. */
1663 MPI_ECP_SQR(X, &tmp[1]);
1664 MPI_ECP_SUB(X, X, &tmp[0]);
1665 MPI_ECP_SUB(X, X, &tmp[3]);
1666 MPI_ECP_SUB(&tmp[2], &tmp[2], X);
1667 MPI_ECP_MUL(&tmp[2], &tmp[2], &tmp[1]);
1668 MPI_ECP_MUL(&tmp[3], &tmp[3], &P->Y);
1669 /* {P,Q}->Y no longer used, so OK to write to Y even if there's aliasing. */
1670 MPI_ECP_SUB(Y, &tmp[2], &tmp[3]);
1671
1672 cleanup:
1673
1674 return ret;
1675 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_ADD_MIXED_ALT) */
1676 }
1677
1678 /*
1679 * Randomize jacobian coordinates:
1680 * (X, Y, Z) -> (l^2 X, l^3 Y, l Z) for random l
1681 * This is sort of the reverse operation of ecp_normalize_jac().
1682 *
1683 * This countermeasure was first suggested in [2].
1684 */
ecp_randomize_jac(const mbedtls_ecp_group * grp,mbedtls_ecp_point * pt,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1685 static int ecp_randomize_jac(const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt,
1686 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1687 {
1688 #if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)
1689 if (mbedtls_internal_ecp_grp_capable(grp)) {
1690 return mbedtls_internal_ecp_randomize_jac(grp, pt, f_rng, p_rng);
1691 }
1692 #endif /* MBEDTLS_ECP_RANDOMIZE_JAC_ALT */
1693
1694 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)
1695 return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
1696 #else
1697 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1698 mbedtls_mpi l;
1699
1700 mbedtls_mpi_init(&l);
1701
1702 /* Generate l such that 1 < l < p */
1703 MPI_ECP_RAND(&l);
1704
1705 /* Z' = l * Z */
1706 MPI_ECP_MUL(&pt->Z, &pt->Z, &l);
1707
1708 /* Y' = l * Y */
1709 MPI_ECP_MUL(&pt->Y, &pt->Y, &l);
1710
1711 /* X' = l^2 * X */
1712 MPI_ECP_SQR(&l, &l);
1713 MPI_ECP_MUL(&pt->X, &pt->X, &l);
1714
1715 /* Y'' = l^2 * Y' = l^3 * Y */
1716 MPI_ECP_MUL(&pt->Y, &pt->Y, &l);
1717
1718 cleanup:
1719 mbedtls_mpi_free(&l);
1720
1721 if (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
1722 ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
1723 }
1724 return ret;
1725 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) */
1726 }
1727
1728 /*
1729 * Check and define parameters used by the comb method (see below for details)
1730 */
1731 #if MBEDTLS_ECP_WINDOW_SIZE < 2 || MBEDTLS_ECP_WINDOW_SIZE > 7
1732 #error "MBEDTLS_ECP_WINDOW_SIZE out of bounds"
1733 #endif
1734
1735 /* d = ceil( n / w ) */
1736 #define COMB_MAX_D (MBEDTLS_ECP_MAX_BITS + 1) / 2
1737
1738 /* number of precomputed points */
1739 #define COMB_MAX_PRE (1 << (MBEDTLS_ECP_WINDOW_SIZE - 1))
1740
1741 /*
1742 * Compute the representation of m that will be used with our comb method.
1743 *
1744 * The basic comb method is described in GECC 3.44 for example. We use a
1745 * modified version that provides resistance to SPA by avoiding zero
1746 * digits in the representation as in [3]. We modify the method further by
1747 * requiring that all K_i be odd, which has the small cost that our
1748 * representation uses one more K_i, due to carries, but saves on the size of
1749 * the precomputed table.
1750 *
1751 * Summary of the comb method and its modifications:
1752 *
1753 * - The goal is to compute m*P for some w*d-bit integer m.
1754 *
1755 * - The basic comb method splits m into the w-bit integers
1756 * x[0] .. x[d-1] where x[i] consists of the bits in m whose
1757 * index has residue i modulo d, and computes m * P as
1758 * S[x[0]] + 2 * S[x[1]] + .. + 2^(d-1) S[x[d-1]], where
1759 * S[i_{w-1} .. i_0] := i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + i_0 P.
1760 *
1761 * - If it happens that, say, x[i+1]=0 (=> S[x[i+1]]=0), one can replace the sum by
1762 * .. + 2^{i-1} S[x[i-1]] - 2^i S[x[i]] + 2^{i+1} S[x[i]] + 2^{i+2} S[x[i+2]] ..,
1763 * thereby successively converting it into a form where all summands
1764 * are nonzero, at the cost of negative summands. This is the basic idea of [3].
1765 *
1766 * - More generally, even if x[i+1] != 0, we can first transform the sum as
1767 * .. - 2^i S[x[i]] + 2^{i+1} ( S[x[i]] + S[x[i+1]] ) + 2^{i+2} S[x[i+2]] ..,
1768 * and then replace S[x[i]] + S[x[i+1]] = S[x[i] ^ x[i+1]] + 2 S[x[i] & x[i+1]].
1769 * Performing and iterating this procedure for those x[i] that are even
1770 * (keeping track of carry), we can transform the original sum into one of the form
1771 * S[x'[0]] +- 2 S[x'[1]] +- .. +- 2^{d-1} S[x'[d-1]] + 2^d S[x'[d]]
1772 * with all x'[i] odd. It is therefore only necessary to know S at odd indices,
1773 * which is why we are only computing half of it in the first place in
1774 * ecp_precompute_comb and accessing it with index abs(i) / 2 in ecp_select_comb.
1775 *
1776 * - For the sake of compactness, only the seven low-order bits of x[i]
1777 * are used to represent its absolute value (K_i in the paper), and the msb
1778 * of x[i] encodes the sign (s_i in the paper): it is set if and only if
1779 * if s_i == -1;
1780 *
1781 * Calling conventions:
1782 * - x is an array of size d + 1
1783 * - w is the size, ie number of teeth, of the comb, and must be between
1784 * 2 and 7 (in practice, between 2 and MBEDTLS_ECP_WINDOW_SIZE)
1785 * - m is the MPI, expected to be odd and such that bitlength(m) <= w * d
1786 * (the result will be incorrect if these assumptions are not satisfied)
1787 */
ecp_comb_recode_core(unsigned char x[],size_t d,unsigned char w,const mbedtls_mpi * m)1788 static void ecp_comb_recode_core(unsigned char x[], size_t d,
1789 unsigned char w, const mbedtls_mpi *m)
1790 {
1791 size_t i, j;
1792 unsigned char c, cc, adjust;
1793
1794 memset(x, 0, d+1);
1795
1796 /* First get the classical comb values (except for x_d = 0) */
1797 for (i = 0; i < d; i++) {
1798 for (j = 0; j < w; j++) {
1799 x[i] |= mbedtls_mpi_get_bit(m, i + d * j) << j;
1800 }
1801 }
1802
1803 /* Now make sure x_1 .. x_d are odd */
1804 c = 0;
1805 for (i = 1; i <= d; i++) {
1806 /* Add carry and update it */
1807 cc = x[i] & c;
1808 x[i] = x[i] ^ c;
1809 c = cc;
1810
1811 /* Adjust if needed, avoiding branches */
1812 adjust = 1 - (x[i] & 0x01);
1813 c |= x[i] & (x[i-1] * adjust);
1814 x[i] = x[i] ^ (x[i-1] * adjust);
1815 x[i-1] |= adjust << 7;
1816 }
1817 }
1818
1819 /*
1820 * Precompute points for the adapted comb method
1821 *
1822 * Assumption: T must be able to hold 2^{w - 1} elements.
1823 *
1824 * Operation: If i = i_{w-1} ... i_1 is the binary representation of i,
1825 * sets T[i] = i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + P.
1826 *
1827 * Cost: d(w-1) D + (2^{w-1} - 1) A + 1 N(w-1) + 1 N(2^{w-1} - 1)
1828 *
1829 * Note: Even comb values (those where P would be omitted from the
1830 * sum defining T[i] above) are not needed in our adaption
1831 * the comb method. See ecp_comb_recode_core().
1832 *
1833 * This function currently works in four steps:
1834 * (1) [dbl] Computation of intermediate T[i] for 2-power values of i
1835 * (2) [norm_dbl] Normalization of coordinates of these T[i]
1836 * (3) [add] Computation of all T[i]
1837 * (4) [norm_add] Normalization of all T[i]
1838 *
1839 * Step 1 can be interrupted but not the others; together with the final
1840 * coordinate normalization they are the largest steps done at once, depending
1841 * on the window size. Here are operation counts for P-256:
1842 *
1843 * step (2) (3) (4)
1844 * w = 5 142 165 208
1845 * w = 4 136 77 160
1846 * w = 3 130 33 136
1847 * w = 2 124 11 124
1848 *
1849 * So if ECC operations are blocking for too long even with a low max_ops
1850 * value, it's useful to set MBEDTLS_ECP_WINDOW_SIZE to a lower value in order
1851 * to minimize maximum blocking time.
1852 */
ecp_precompute_comb(const mbedtls_ecp_group * grp,mbedtls_ecp_point T[],const mbedtls_ecp_point * P,unsigned char w,size_t d,mbedtls_ecp_restart_ctx * rs_ctx)1853 static int ecp_precompute_comb(const mbedtls_ecp_group *grp,
1854 mbedtls_ecp_point T[], const mbedtls_ecp_point *P,
1855 unsigned char w, size_t d,
1856 mbedtls_ecp_restart_ctx *rs_ctx)
1857 {
1858 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1859 unsigned char i;
1860 size_t j = 0;
1861 const unsigned char T_size = 1U << (w - 1);
1862 mbedtls_ecp_point *cur, *TT[COMB_MAX_PRE - 1] = { NULL };
1863
1864 mbedtls_mpi tmp[4];
1865
1866 mpi_init_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
1867
1868 #if defined(MBEDTLS_ECP_RESTARTABLE)
1869 if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
1870 if (rs_ctx->rsm->state == ecp_rsm_pre_dbl) {
1871 goto dbl;
1872 }
1873 if (rs_ctx->rsm->state == ecp_rsm_pre_norm_dbl) {
1874 goto norm_dbl;
1875 }
1876 if (rs_ctx->rsm->state == ecp_rsm_pre_add) {
1877 goto add;
1878 }
1879 if (rs_ctx->rsm->state == ecp_rsm_pre_norm_add) {
1880 goto norm_add;
1881 }
1882 }
1883 #else
1884 (void) rs_ctx;
1885 #endif
1886
1887 #if defined(MBEDTLS_ECP_RESTARTABLE)
1888 if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
1889 rs_ctx->rsm->state = ecp_rsm_pre_dbl;
1890
1891 /* initial state for the loop */
1892 rs_ctx->rsm->i = 0;
1893 }
1894
1895 dbl:
1896 #endif
1897 /*
1898 * Set T[0] = P and
1899 * T[2^{l-1}] = 2^{dl} P for l = 1 .. w-1 (this is not the final value)
1900 */
1901 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(&T[0], P));
1902
1903 #if defined(MBEDTLS_ECP_RESTARTABLE)
1904 if (rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->i != 0) {
1905 j = rs_ctx->rsm->i;
1906 } else
1907 #endif
1908 j = 0;
1909
1910 for (; j < d * (w - 1); j++) {
1911 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_DBL);
1912
1913 i = 1U << (j / d);
1914 cur = T + i;
1915
1916 if (j % d == 0) {
1917 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(cur, T + (i >> 1)));
1918 }
1919
1920 MBEDTLS_MPI_CHK(ecp_double_jac(grp, cur, cur, tmp));
1921 }
1922
1923 #if defined(MBEDTLS_ECP_RESTARTABLE)
1924 if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
1925 rs_ctx->rsm->state = ecp_rsm_pre_norm_dbl;
1926 }
1927
1928 norm_dbl:
1929 #endif
1930 /*
1931 * Normalize current elements in T to allow them to be used in
1932 * ecp_add_mixed() below, which requires one normalized input.
1933 *
1934 * As T has holes, use an auxiliary array of pointers to elements in T.
1935 *
1936 */
1937 j = 0;
1938 for (i = 1; i < T_size; i <<= 1) {
1939 TT[j++] = T + i;
1940 }
1941
1942 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV + 6 * j - 2);
1943
1944 MBEDTLS_MPI_CHK(ecp_normalize_jac_many(grp, TT, j));
1945
1946 #if defined(MBEDTLS_ECP_RESTARTABLE)
1947 if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
1948 rs_ctx->rsm->state = ecp_rsm_pre_add;
1949 }
1950
1951 add:
1952 #endif
1953 /*
1954 * Compute the remaining ones using the minimal number of additions
1955 * Be careful to update T[2^l] only after using it!
1956 */
1957 MBEDTLS_ECP_BUDGET((T_size - 1) * MBEDTLS_ECP_OPS_ADD);
1958
1959 for (i = 1; i < T_size; i <<= 1) {
1960 j = i;
1961 while (j--) {
1962 MBEDTLS_MPI_CHK(ecp_add_mixed(grp, &T[i + j], &T[j], &T[i], tmp));
1963 }
1964 }
1965
1966 #if defined(MBEDTLS_ECP_RESTARTABLE)
1967 if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
1968 rs_ctx->rsm->state = ecp_rsm_pre_norm_add;
1969 }
1970
1971 norm_add:
1972 #endif
1973 /*
1974 * Normalize final elements in T. Even though there are no holes now, we
1975 * still need the auxiliary array for homogeneity with the previous
1976 * call. Also, skip T[0] which is already normalised, being a copy of P.
1977 */
1978 for (j = 0; j + 1 < T_size; j++) {
1979 TT[j] = T + j + 1;
1980 }
1981
1982 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV + 6 * j - 2);
1983
1984 MBEDTLS_MPI_CHK(ecp_normalize_jac_many(grp, TT, j));
1985
1986 /* Free Z coordinate (=1 after normalization) to save RAM.
1987 * This makes T[i] invalid as mbedtls_ecp_points, but this is OK
1988 * since from this point onwards, they are only accessed indirectly
1989 * via the getter function ecp_select_comb() which does set the
1990 * target's Z coordinate to 1. */
1991 for (i = 0; i < T_size; i++) {
1992 mbedtls_mpi_free(&T[i].Z);
1993 }
1994
1995 cleanup:
1996
1997 mpi_free_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
1998
1999 #if defined(MBEDTLS_ECP_RESTARTABLE)
2000 if (rs_ctx != NULL && rs_ctx->rsm != NULL &&
2001 ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
2002 if (rs_ctx->rsm->state == ecp_rsm_pre_dbl) {
2003 rs_ctx->rsm->i = j;
2004 }
2005 }
2006 #endif
2007
2008 return ret;
2009 }
2010
2011 /*
2012 * Select precomputed point: R = sign(i) * T[ abs(i) / 2 ]
2013 *
2014 * See ecp_comb_recode_core() for background
2015 */
ecp_select_comb(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_ecp_point T[],unsigned char T_size,unsigned char i)2016 static int ecp_select_comb(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2017 const mbedtls_ecp_point T[], unsigned char T_size,
2018 unsigned char i)
2019 {
2020 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2021 unsigned char ii, j;
2022
2023 /* Ignore the "sign" bit and scale down */
2024 ii = (i & 0x7Fu) >> 1;
2025
2026 /* Read the whole table to thwart cache-based timing attacks */
2027 for (j = 0; j < T_size; j++) {
2028 MPI_ECP_COND_ASSIGN(&R->X, &T[j].X, j == ii);
2029 MPI_ECP_COND_ASSIGN(&R->Y, &T[j].Y, j == ii);
2030 }
2031
2032 /* Safely invert result if i is "negative" */
2033 MBEDTLS_MPI_CHK(ecp_safe_invert_jac(grp, R, i >> 7));
2034
2035 MPI_ECP_LSET(&R->Z, 1);
2036
2037 cleanup:
2038 return ret;
2039 }
2040
2041 /*
2042 * Core multiplication algorithm for the (modified) comb method.
2043 * This part is actually common with the basic comb method (GECC 3.44)
2044 *
2045 * Cost: d A + d D + 1 R
2046 */
ecp_mul_comb_core(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_ecp_point T[],unsigned char T_size,const unsigned char x[],size_t d,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_ecp_restart_ctx * rs_ctx)2047 static int ecp_mul_comb_core(const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2048 const mbedtls_ecp_point T[], unsigned char T_size,
2049 const unsigned char x[], size_t d,
2050 int (*f_rng)(void *, unsigned char *, size_t),
2051 void *p_rng,
2052 mbedtls_ecp_restart_ctx *rs_ctx)
2053 {
2054 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2055 mbedtls_ecp_point Txi;
2056 mbedtls_mpi tmp[4];
2057 size_t i;
2058
2059 mbedtls_ecp_point_init(&Txi);
2060 mpi_init_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
2061
2062 #if !defined(MBEDTLS_ECP_RESTARTABLE)
2063 (void) rs_ctx;
2064 #endif
2065
2066 #if defined(MBEDTLS_ECP_RESTARTABLE)
2067 if (rs_ctx != NULL && rs_ctx->rsm != NULL &&
2068 rs_ctx->rsm->state != ecp_rsm_comb_core) {
2069 rs_ctx->rsm->i = 0;
2070 rs_ctx->rsm->state = ecp_rsm_comb_core;
2071 }
2072
2073 /* new 'if' instead of nested for the sake of the 'else' branch */
2074 if (rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->i != 0) {
2075 /* restore current index (R already pointing to rs_ctx->rsm->R) */
2076 i = rs_ctx->rsm->i;
2077 } else
2078 #endif
2079 {
2080 /* Start with a non-zero point and randomize its coordinates */
2081 i = d;
2082 MBEDTLS_MPI_CHK(ecp_select_comb(grp, R, T, T_size, x[i]));
2083 if (f_rng != 0) {
2084 MBEDTLS_MPI_CHK(ecp_randomize_jac(grp, R, f_rng, p_rng));
2085 }
2086 }
2087
2088 while (i != 0) {
2089 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_DBL + MBEDTLS_ECP_OPS_ADD);
2090 --i;
2091
2092 MBEDTLS_MPI_CHK(ecp_double_jac(grp, R, R, tmp));
2093 MBEDTLS_MPI_CHK(ecp_select_comb(grp, &Txi, T, T_size, x[i]));
2094 MBEDTLS_MPI_CHK(ecp_add_mixed(grp, R, R, &Txi, tmp));
2095 }
2096
2097 cleanup:
2098
2099 mbedtls_ecp_point_free(&Txi);
2100 mpi_free_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
2101
2102 #if defined(MBEDTLS_ECP_RESTARTABLE)
2103 if (rs_ctx != NULL && rs_ctx->rsm != NULL &&
2104 ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
2105 rs_ctx->rsm->i = i;
2106 /* no need to save R, already pointing to rs_ctx->rsm->R */
2107 }
2108 #endif
2109
2110 return ret;
2111 }
2112
2113 /*
2114 * Recode the scalar to get constant-time comb multiplication
2115 *
2116 * As the actual scalar recoding needs an odd scalar as a starting point,
2117 * this wrapper ensures that by replacing m by N - m if necessary, and
2118 * informs the caller that the result of multiplication will be negated.
2119 *
2120 * This works because we only support large prime order for Short Weierstrass
2121 * curves, so N is always odd hence either m or N - m is.
2122 *
2123 * See ecp_comb_recode_core() for background.
2124 */
ecp_comb_recode_scalar(const mbedtls_ecp_group * grp,const mbedtls_mpi * m,unsigned char k[COMB_MAX_D+1],size_t d,unsigned char w,unsigned char * parity_trick)2125 static int ecp_comb_recode_scalar(const mbedtls_ecp_group *grp,
2126 const mbedtls_mpi *m,
2127 unsigned char k[COMB_MAX_D + 1],
2128 size_t d,
2129 unsigned char w,
2130 unsigned char *parity_trick)
2131 {
2132 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2133 mbedtls_mpi M, mm;
2134
2135 mbedtls_mpi_init(&M);
2136 mbedtls_mpi_init(&mm);
2137
2138 /* N is always odd (see above), just make extra sure */
2139 if (mbedtls_mpi_get_bit(&grp->N, 0) != 1) {
2140 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2141 }
2142
2143 /* do we need the parity trick? */
2144 *parity_trick = (mbedtls_mpi_get_bit(m, 0) == 0);
2145
2146 /* execute parity fix in constant time */
2147 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&M, m));
2148 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&mm, &grp->N, m));
2149 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign(&M, &mm, *parity_trick));
2150
2151 /* actual scalar recoding */
2152 ecp_comb_recode_core(k, d, w, &M);
2153
2154 cleanup:
2155 mbedtls_mpi_free(&mm);
2156 mbedtls_mpi_free(&M);
2157
2158 return ret;
2159 }
2160
2161 /*
2162 * Perform comb multiplication (for short Weierstrass curves)
2163 * once the auxiliary table has been pre-computed.
2164 *
2165 * Scalar recoding may use a parity trick that makes us compute -m * P,
2166 * if that is the case we'll need to recover m * P at the end.
2167 */
ecp_mul_comb_after_precomp(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * T,unsigned char T_size,unsigned char w,size_t d,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_ecp_restart_ctx * rs_ctx)2168 static int ecp_mul_comb_after_precomp(const mbedtls_ecp_group *grp,
2169 mbedtls_ecp_point *R,
2170 const mbedtls_mpi *m,
2171 const mbedtls_ecp_point *T,
2172 unsigned char T_size,
2173 unsigned char w,
2174 size_t d,
2175 int (*f_rng)(void *, unsigned char *, size_t),
2176 void *p_rng,
2177 mbedtls_ecp_restart_ctx *rs_ctx)
2178 {
2179 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2180 unsigned char parity_trick;
2181 unsigned char k[COMB_MAX_D + 1];
2182 mbedtls_ecp_point *RR = R;
2183
2184 #if defined(MBEDTLS_ECP_RESTARTABLE)
2185 if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
2186 RR = &rs_ctx->rsm->R;
2187
2188 if (rs_ctx->rsm->state == ecp_rsm_final_norm) {
2189 goto final_norm;
2190 }
2191 }
2192 #endif
2193
2194 MBEDTLS_MPI_CHK(ecp_comb_recode_scalar(grp, m, k, d, w,
2195 &parity_trick));
2196 MBEDTLS_MPI_CHK(ecp_mul_comb_core(grp, RR, T, T_size, k, d,
2197 f_rng, p_rng, rs_ctx));
2198 MBEDTLS_MPI_CHK(ecp_safe_invert_jac(grp, RR, parity_trick));
2199
2200 #if defined(MBEDTLS_ECP_RESTARTABLE)
2201 if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
2202 rs_ctx->rsm->state = ecp_rsm_final_norm;
2203 }
2204
2205 final_norm:
2206 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV);
2207 #endif
2208 /*
2209 * Knowledge of the jacobian coordinates may leak the last few bits of the
2210 * scalar [1], and since our MPI implementation isn't constant-flow,
2211 * inversion (used for coordinate normalization) may leak the full value
2212 * of its input via side-channels [2].
2213 *
2214 * [1] https://eprint.iacr.org/2003/191
2215 * [2] https://eprint.iacr.org/2020/055
2216 *
2217 * Avoid the leak by randomizing coordinates before we normalize them.
2218 */
2219 if (f_rng != 0) {
2220 MBEDTLS_MPI_CHK(ecp_randomize_jac(grp, RR, f_rng, p_rng));
2221 }
2222
2223 MBEDTLS_MPI_CHK(ecp_normalize_jac(grp, RR));
2224
2225 #if defined(MBEDTLS_ECP_RESTARTABLE)
2226 if (rs_ctx != NULL && rs_ctx->rsm != NULL) {
2227 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, RR));
2228 }
2229 #endif
2230
2231 cleanup:
2232 return ret;
2233 }
2234
2235 /*
2236 * Pick window size based on curve size and whether we optimize for base point
2237 */
ecp_pick_window_size(const mbedtls_ecp_group * grp,unsigned char p_eq_g)2238 static unsigned char ecp_pick_window_size(const mbedtls_ecp_group *grp,
2239 unsigned char p_eq_g)
2240 {
2241 unsigned char w;
2242
2243 /*
2244 * Minimize the number of multiplications, that is minimize
2245 * 10 * d * w + 18 * 2^(w-1) + 11 * d + 7 * w, with d = ceil( nbits / w )
2246 * (see costs of the various parts, with 1S = 1M)
2247 */
2248 w = grp->nbits >= 384 ? 5 : 4;
2249
2250 /*
2251 * If P == G, pre-compute a bit more, since this may be re-used later.
2252 * Just adding one avoids upping the cost of the first mul too much,
2253 * and the memory cost too.
2254 */
2255 if (p_eq_g) {
2256 w++;
2257 }
2258
2259 /*
2260 * If static comb table may not be used (!p_eq_g) or static comb table does
2261 * not exists, make sure w is within bounds.
2262 * (The last test is useful only for very small curves in the test suite.)
2263 *
2264 * The user reduces MBEDTLS_ECP_WINDOW_SIZE does not changes the size of
2265 * static comb table, because the size of static comb table is fixed when
2266 * it is generated.
2267 */
2268 #if (MBEDTLS_ECP_WINDOW_SIZE < 6)
2269 if ((!p_eq_g || !ecp_group_is_static_comb_table(grp)) && w > MBEDTLS_ECP_WINDOW_SIZE) {
2270 w = MBEDTLS_ECP_WINDOW_SIZE;
2271 }
2272 #endif
2273 if (w >= grp->nbits) {
2274 w = 2;
2275 }
2276
2277 return w;
2278 }
2279
2280 /*
2281 * Multiplication using the comb method - for curves in short Weierstrass form
2282 *
2283 * This function is mainly responsible for administrative work:
2284 * - managing the restart context if enabled
2285 * - managing the table of precomputed points (passed between the below two
2286 * functions): allocation, computation, ownership transfer, freeing.
2287 *
2288 * It delegates the actual arithmetic work to:
2289 * ecp_precompute_comb() and ecp_mul_comb_with_precomp()
2290 *
2291 * See comments on ecp_comb_recode_core() regarding the computation strategy.
2292 */
ecp_mul_comb(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_ecp_restart_ctx * rs_ctx)2293 static int ecp_mul_comb(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2294 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2295 int (*f_rng)(void *, unsigned char *, size_t),
2296 void *p_rng,
2297 mbedtls_ecp_restart_ctx *rs_ctx)
2298 {
2299 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2300 unsigned char w, p_eq_g, i;
2301 size_t d;
2302 unsigned char T_size = 0, T_ok = 0;
2303 mbedtls_ecp_point *T = NULL;
2304
2305 ECP_RS_ENTER(rsm);
2306
2307 /* Is P the base point ? */
2308 #if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1
2309 p_eq_g = (MPI_ECP_CMP(&P->Y, &grp->G.Y) == 0 &&
2310 MPI_ECP_CMP(&P->X, &grp->G.X) == 0);
2311 #else
2312 p_eq_g = 0;
2313 #endif
2314
2315 /* Pick window size and deduce related sizes */
2316 w = ecp_pick_window_size(grp, p_eq_g);
2317 T_size = 1U << (w - 1);
2318 d = (grp->nbits + w - 1) / w;
2319
2320 /* Pre-computed table: do we have it already for the base point? */
2321 if (p_eq_g && grp->T != NULL) {
2322 /* second pointer to the same table, will be deleted on exit */
2323 T = grp->T;
2324 T_ok = 1;
2325 } else
2326 #if defined(MBEDTLS_ECP_RESTARTABLE)
2327 /* Pre-computed table: do we have one in progress? complete? */
2328 if (rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->T != NULL) {
2329 /* transfer ownership of T from rsm to local function */
2330 T = rs_ctx->rsm->T;
2331 rs_ctx->rsm->T = NULL;
2332 rs_ctx->rsm->T_size = 0;
2333
2334 /* This effectively jumps to the call to mul_comb_after_precomp() */
2335 T_ok = rs_ctx->rsm->state >= ecp_rsm_comb_core;
2336 } else
2337 #endif
2338 /* Allocate table if we didn't have any */
2339 {
2340 T = mbedtls_calloc(T_size, sizeof(mbedtls_ecp_point));
2341 if (T == NULL) {
2342 ret = MBEDTLS_ERR_ECP_ALLOC_FAILED;
2343 goto cleanup;
2344 }
2345
2346 for (i = 0; i < T_size; i++) {
2347 mbedtls_ecp_point_init(&T[i]);
2348 }
2349
2350 T_ok = 0;
2351 }
2352
2353 /* Compute table (or finish computing it) if not done already */
2354 if (!T_ok) {
2355 MBEDTLS_MPI_CHK(ecp_precompute_comb(grp, T, P, w, d, rs_ctx));
2356
2357 if (p_eq_g) {
2358 /* almost transfer ownership of T to the group, but keep a copy of
2359 * the pointer to use for calling the next function more easily */
2360 grp->T = T;
2361 grp->T_size = T_size;
2362 }
2363 }
2364
2365 /* Actual comb multiplication using precomputed points */
2366 MBEDTLS_MPI_CHK(ecp_mul_comb_after_precomp(grp, R, m,
2367 T, T_size, w, d,
2368 f_rng, p_rng, rs_ctx));
2369
2370 cleanup:
2371
2372 /* does T belong to the group? */
2373 if (T == grp->T) {
2374 T = NULL;
2375 }
2376
2377 /* does T belong to the restart context? */
2378 #if defined(MBEDTLS_ECP_RESTARTABLE)
2379 if (rs_ctx != NULL && rs_ctx->rsm != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS && T != NULL) {
2380 /* transfer ownership of T from local function to rsm */
2381 rs_ctx->rsm->T_size = T_size;
2382 rs_ctx->rsm->T = T;
2383 T = NULL;
2384 }
2385 #endif
2386
2387 /* did T belong to us? then let's destroy it! */
2388 if (T != NULL) {
2389 for (i = 0; i < T_size; i++) {
2390 mbedtls_ecp_point_free(&T[i]);
2391 }
2392 mbedtls_free(T);
2393 }
2394
2395 /* prevent caller from using invalid value */
2396 int should_free_R = (ret != 0);
2397 #if defined(MBEDTLS_ECP_RESTARTABLE)
2398 /* don't free R while in progress in case R == P */
2399 if (ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
2400 should_free_R = 0;
2401 }
2402 #endif
2403 if (should_free_R) {
2404 mbedtls_ecp_point_free(R);
2405 }
2406
2407 ECP_RS_LEAVE(rsm);
2408
2409 return ret;
2410 }
2411
2412 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
2413
2414 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2415 /*
2416 * For Montgomery curves, we do all the internal arithmetic in projective
2417 * coordinates. Import/export of points uses only the x coordinates, which is
2418 * internally represented as X / Z.
2419 *
2420 * For scalar multiplication, we'll use a Montgomery ladder.
2421 */
2422
2423 /*
2424 * Normalize Montgomery x/z coordinates: X = X/Z, Z = 1
2425 * Cost: 1M + 1I
2426 */
ecp_normalize_mxz(const mbedtls_ecp_group * grp,mbedtls_ecp_point * P)2427 static int ecp_normalize_mxz(const mbedtls_ecp_group *grp, mbedtls_ecp_point *P)
2428 {
2429 #if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
2430 if (mbedtls_internal_ecp_grp_capable(grp)) {
2431 return mbedtls_internal_ecp_normalize_mxz(grp, P);
2432 }
2433 #endif /* MBEDTLS_ECP_NORMALIZE_MXZ_ALT */
2434
2435 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
2436 return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
2437 #else
2438 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2439 MPI_ECP_INV(&P->Z, &P->Z);
2440 MPI_ECP_MUL(&P->X, &P->X, &P->Z);
2441 MPI_ECP_LSET(&P->Z, 1);
2442
2443 cleanup:
2444 return ret;
2445 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) */
2446 }
2447
2448 /*
2449 * Randomize projective x/z coordinates:
2450 * (X, Z) -> (l X, l Z) for random l
2451 * This is sort of the reverse operation of ecp_normalize_mxz().
2452 *
2453 * This countermeasure was first suggested in [2].
2454 * Cost: 2M
2455 */
ecp_randomize_mxz(const mbedtls_ecp_group * grp,mbedtls_ecp_point * P,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2456 static int ecp_randomize_mxz(const mbedtls_ecp_group *grp, mbedtls_ecp_point *P,
2457 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
2458 {
2459 #if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
2460 if (mbedtls_internal_ecp_grp_capable(grp)) {
2461 return mbedtls_internal_ecp_randomize_mxz(grp, P, f_rng, p_rng);
2462 }
2463 #endif /* MBEDTLS_ECP_RANDOMIZE_MXZ_ALT */
2464
2465 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
2466 return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
2467 #else
2468 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2469 mbedtls_mpi l;
2470 mbedtls_mpi_init(&l);
2471
2472 /* Generate l such that 1 < l < p */
2473 MPI_ECP_RAND(&l);
2474
2475 MPI_ECP_MUL(&P->X, &P->X, &l);
2476 MPI_ECP_MUL(&P->Z, &P->Z, &l);
2477
2478 cleanup:
2479 mbedtls_mpi_free(&l);
2480
2481 if (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
2482 ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
2483 }
2484 return ret;
2485 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) */
2486 }
2487
2488 /*
2489 * Double-and-add: R = 2P, S = P + Q, with d = X(P - Q),
2490 * for Montgomery curves in x/z coordinates.
2491 *
2492 * http://www.hyperelliptic.org/EFD/g1p/auto-code/montgom/xz/ladder/mladd-1987-m.op3
2493 * with
2494 * d = X1
2495 * P = (X2, Z2)
2496 * Q = (X3, Z3)
2497 * R = (X4, Z4)
2498 * S = (X5, Z5)
2499 * and eliminating temporary variables tO, ..., t4.
2500 *
2501 * Cost: 5M + 4S
2502 */
ecp_double_add_mxz(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,mbedtls_ecp_point * S,const mbedtls_ecp_point * P,const mbedtls_ecp_point * Q,const mbedtls_mpi * d,mbedtls_mpi T[4])2503 static int ecp_double_add_mxz(const mbedtls_ecp_group *grp,
2504 mbedtls_ecp_point *R, mbedtls_ecp_point *S,
2505 const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q,
2506 const mbedtls_mpi *d,
2507 mbedtls_mpi T[4])
2508 {
2509 #if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
2510 if (mbedtls_internal_ecp_grp_capable(grp)) {
2511 return mbedtls_internal_ecp_double_add_mxz(grp, R, S, P, Q, d);
2512 }
2513 #endif /* MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT */
2514
2515 #if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
2516 return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
2517 #else
2518 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2519
2520 MPI_ECP_ADD(&T[0], &P->X, &P->Z); /* Pp := PX + PZ */
2521 MPI_ECP_SUB(&T[1], &P->X, &P->Z); /* Pm := PX - PZ */
2522 MPI_ECP_ADD(&T[2], &Q->X, &Q->Z); /* Qp := QX + XZ */
2523 MPI_ECP_SUB(&T[3], &Q->X, &Q->Z); /* Qm := QX - QZ */
2524 MPI_ECP_MUL(&T[3], &T[3], &T[0]); /* Qm * Pp */
2525 MPI_ECP_MUL(&T[2], &T[2], &T[1]); /* Qp * Pm */
2526 MPI_ECP_SQR(&T[0], &T[0]); /* Pp^2 */
2527 MPI_ECP_SQR(&T[1], &T[1]); /* Pm^2 */
2528 MPI_ECP_MUL(&R->X, &T[0], &T[1]); /* Pp^2 * Pm^2 */
2529 MPI_ECP_SUB(&T[0], &T[0], &T[1]); /* Pp^2 - Pm^2 */
2530 MPI_ECP_MUL(&R->Z, &grp->A, &T[0]); /* A * (Pp^2 - Pm^2) */
2531 MPI_ECP_ADD(&R->Z, &T[1], &R->Z); /* [ A * (Pp^2-Pm^2) ] + Pm^2 */
2532 MPI_ECP_ADD(&S->X, &T[3], &T[2]); /* Qm*Pp + Qp*Pm */
2533 MPI_ECP_SQR(&S->X, &S->X); /* (Qm*Pp + Qp*Pm)^2 */
2534 MPI_ECP_SUB(&S->Z, &T[3], &T[2]); /* Qm*Pp - Qp*Pm */
2535 MPI_ECP_SQR(&S->Z, &S->Z); /* (Qm*Pp - Qp*Pm)^2 */
2536 MPI_ECP_MUL(&S->Z, d, &S->Z); /* d * ( Qm*Pp - Qp*Pm )^2 */
2537 MPI_ECP_MUL(&R->Z, &T[0], &R->Z); /* [A*(Pp^2-Pm^2)+Pm^2]*(Pp^2-Pm^2) */
2538
2539 cleanup:
2540
2541 return ret;
2542 #endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) */
2543 }
2544
2545 /*
2546 * Multiplication with Montgomery ladder in x/z coordinates,
2547 * for curves in Montgomery form
2548 */
ecp_mul_mxz(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2549 static int ecp_mul_mxz(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2550 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2551 int (*f_rng)(void *, unsigned char *, size_t),
2552 void *p_rng)
2553 {
2554 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2555 size_t i;
2556 unsigned char b;
2557 mbedtls_ecp_point RP;
2558 mbedtls_mpi PX;
2559 mbedtls_mpi tmp[4];
2560 mbedtls_ecp_point_init(&RP); mbedtls_mpi_init(&PX);
2561
2562 mpi_init_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
2563
2564 if (f_rng == NULL) {
2565 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2566 }
2567
2568 /* Save PX and read from P before writing to R, in case P == R */
2569 MPI_ECP_MOV(&PX, &P->X);
2570 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(&RP, P));
2571
2572 /* Set R to zero in modified x/z coordinates */
2573 MPI_ECP_LSET(&R->X, 1);
2574 MPI_ECP_LSET(&R->Z, 0);
2575 mbedtls_mpi_free(&R->Y);
2576
2577 /* RP.X might be slightly larger than P, so reduce it */
2578 MOD_ADD(&RP.X);
2579
2580 /* Randomize coordinates of the starting point */
2581 MBEDTLS_MPI_CHK(ecp_randomize_mxz(grp, &RP, f_rng, p_rng));
2582
2583 /* Loop invariant: R = result so far, RP = R + P */
2584 i = grp->nbits + 1; /* one past the (zero-based) required msb for private keys */
2585 while (i-- > 0) {
2586 b = mbedtls_mpi_get_bit(m, i);
2587 /*
2588 * if (b) R = 2R + P else R = 2R,
2589 * which is:
2590 * if (b) double_add( RP, R, RP, R )
2591 * else double_add( R, RP, R, RP )
2592 * but using safe conditional swaps to avoid leaks
2593 */
2594 MPI_ECP_COND_SWAP(&R->X, &RP.X, b);
2595 MPI_ECP_COND_SWAP(&R->Z, &RP.Z, b);
2596 MBEDTLS_MPI_CHK(ecp_double_add_mxz(grp, R, &RP, R, &RP, &PX, tmp));
2597 MPI_ECP_COND_SWAP(&R->X, &RP.X, b);
2598 MPI_ECP_COND_SWAP(&R->Z, &RP.Z, b);
2599 }
2600
2601 /*
2602 * Knowledge of the projective coordinates may leak the last few bits of the
2603 * scalar [1], and since our MPI implementation isn't constant-flow,
2604 * inversion (used for coordinate normalization) may leak the full value
2605 * of its input via side-channels [2].
2606 *
2607 * [1] https://eprint.iacr.org/2003/191
2608 * [2] https://eprint.iacr.org/2020/055
2609 *
2610 * Avoid the leak by randomizing coordinates before we normalize them.
2611 */
2612 MBEDTLS_MPI_CHK(ecp_randomize_mxz(grp, R, f_rng, p_rng));
2613 MBEDTLS_MPI_CHK(ecp_normalize_mxz(grp, R));
2614
2615 cleanup:
2616 mbedtls_ecp_point_free(&RP); mbedtls_mpi_free(&PX);
2617
2618 mpi_free_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
2619 return ret;
2620 }
2621
2622 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
2623
2624 /*
2625 * Restartable multiplication R = m * P
2626 *
2627 * This internal function can be called without an RNG in case where we know
2628 * the inputs are not sensitive.
2629 */
ecp_mul_restartable_internal(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_ecp_restart_ctx * rs_ctx)2630 static int ecp_mul_restartable_internal(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2631 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2632 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
2633 mbedtls_ecp_restart_ctx *rs_ctx)
2634 {
2635 int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2636 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2637 char is_grp_capable = 0;
2638 #endif
2639
2640 #if defined(MBEDTLS_ECP_RESTARTABLE)
2641 /* reset ops count for this call if top-level */
2642 if (rs_ctx != NULL && rs_ctx->depth++ == 0) {
2643 rs_ctx->ops_done = 0;
2644 }
2645 #else
2646 (void) rs_ctx;
2647 #endif
2648
2649 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2650 if ((is_grp_capable = mbedtls_internal_ecp_grp_capable(grp))) {
2651 MBEDTLS_MPI_CHK(mbedtls_internal_ecp_init(grp));
2652 }
2653 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
2654
2655 int restarting = 0;
2656 #if defined(MBEDTLS_ECP_RESTARTABLE)
2657 restarting = (rs_ctx != NULL && rs_ctx->rsm != NULL);
2658 #endif
2659 /* skip argument check when restarting */
2660 if (!restarting) {
2661 /* check_privkey is free */
2662 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_CHK);
2663
2664 /* Common sanity checks */
2665 MBEDTLS_MPI_CHK(mbedtls_ecp_check_privkey(grp, m));
2666 MBEDTLS_MPI_CHK(mbedtls_ecp_check_pubkey(grp, P));
2667 }
2668
2669 ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2670 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2671 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
2672 MBEDTLS_MPI_CHK(ecp_mul_mxz(grp, R, m, P, f_rng, p_rng));
2673 }
2674 #endif
2675 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2676 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
2677 MBEDTLS_MPI_CHK(ecp_mul_comb(grp, R, m, P, f_rng, p_rng, rs_ctx));
2678 }
2679 #endif
2680
2681 cleanup:
2682
2683 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2684 if (is_grp_capable) {
2685 mbedtls_internal_ecp_free(grp);
2686 }
2687 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
2688
2689 #if defined(MBEDTLS_ECP_RESTARTABLE)
2690 if (rs_ctx != NULL) {
2691 rs_ctx->depth--;
2692 }
2693 #endif
2694
2695 return ret;
2696 }
2697
2698 /*
2699 * Restartable multiplication R = m * P
2700 */
mbedtls_ecp_mul_restartable(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_ecp_restart_ctx * rs_ctx)2701 int mbedtls_ecp_mul_restartable(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2702 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2703 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
2704 mbedtls_ecp_restart_ctx *rs_ctx)
2705 {
2706 if (f_rng == NULL) {
2707 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2708 }
2709
2710 return ecp_mul_restartable_internal(grp, R, m, P, f_rng, p_rng, rs_ctx);
2711 }
2712
2713 /*
2714 * Multiplication R = m * P
2715 */
mbedtls_ecp_mul(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2716 int mbedtls_ecp_mul(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2717 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2718 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
2719 {
2720 return mbedtls_ecp_mul_restartable(grp, R, m, P, f_rng, p_rng, NULL);
2721 }
2722 #endif /* MBEDTLS_ECP_C */
2723
2724 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2725 /*
2726 * Check that an affine point is valid as a public key,
2727 * short weierstrass curves (SEC1 3.2.3.1)
2728 */
ecp_check_pubkey_sw(const mbedtls_ecp_group * grp,const mbedtls_ecp_point * pt)2729 static int ecp_check_pubkey_sw(const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt)
2730 {
2731 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2732 mbedtls_mpi YY, RHS;
2733
2734 /* pt coordinates must be normalized for our checks */
2735 if (mbedtls_mpi_cmp_int(&pt->X, 0) < 0 ||
2736 mbedtls_mpi_cmp_int(&pt->Y, 0) < 0 ||
2737 mbedtls_mpi_cmp_mpi(&pt->X, &grp->P) >= 0 ||
2738 mbedtls_mpi_cmp_mpi(&pt->Y, &grp->P) >= 0) {
2739 return MBEDTLS_ERR_ECP_INVALID_KEY;
2740 }
2741
2742 mbedtls_mpi_init(&YY); mbedtls_mpi_init(&RHS);
2743
2744 /*
2745 * YY = Y^2
2746 * RHS = X^3 + A X + B
2747 */
2748 MPI_ECP_SQR(&YY, &pt->Y);
2749 MBEDTLS_MPI_CHK(ecp_sw_rhs(grp, &RHS, &pt->X));
2750
2751 if (MPI_ECP_CMP(&YY, &RHS) != 0) {
2752 ret = MBEDTLS_ERR_ECP_INVALID_KEY;
2753 }
2754
2755 cleanup:
2756
2757 mbedtls_mpi_free(&YY); mbedtls_mpi_free(&RHS);
2758
2759 return ret;
2760 }
2761 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
2762
2763 #if defined(MBEDTLS_ECP_C)
2764 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2765 /*
2766 * R = m * P with shortcuts for m == 0, m == 1 and m == -1
2767 * NOT constant-time - ONLY for short Weierstrass!
2768 */
mbedtls_ecp_mul_shortcuts(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,mbedtls_ecp_restart_ctx * rs_ctx)2769 static int mbedtls_ecp_mul_shortcuts(mbedtls_ecp_group *grp,
2770 mbedtls_ecp_point *R,
2771 const mbedtls_mpi *m,
2772 const mbedtls_ecp_point *P,
2773 mbedtls_ecp_restart_ctx *rs_ctx)
2774 {
2775 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2776 mbedtls_mpi tmp;
2777 mbedtls_mpi_init(&tmp);
2778
2779 if (mbedtls_mpi_cmp_int(m, 0) == 0) {
2780 MBEDTLS_MPI_CHK(mbedtls_ecp_check_pubkey(grp, P));
2781 MBEDTLS_MPI_CHK(mbedtls_ecp_set_zero(R));
2782 } else if (mbedtls_mpi_cmp_int(m, 1) == 0) {
2783 MBEDTLS_MPI_CHK(mbedtls_ecp_check_pubkey(grp, P));
2784 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, P));
2785 } else if (mbedtls_mpi_cmp_int(m, -1) == 0) {
2786 MBEDTLS_MPI_CHK(mbedtls_ecp_check_pubkey(grp, P));
2787 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, P));
2788 MPI_ECP_NEG(&R->Y);
2789 } else {
2790 MBEDTLS_MPI_CHK(ecp_mul_restartable_internal(grp, R, m, P,
2791 NULL, NULL, rs_ctx));
2792 }
2793
2794 cleanup:
2795 mbedtls_mpi_free(&tmp);
2796
2797 return ret;
2798 }
2799
2800 /*
2801 * Restartable linear combination
2802 * NOT constant-time
2803 */
mbedtls_ecp_muladd_restartable(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,const mbedtls_mpi * n,const mbedtls_ecp_point * Q,mbedtls_ecp_restart_ctx * rs_ctx)2804 int mbedtls_ecp_muladd_restartable(
2805 mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2806 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2807 const mbedtls_mpi *n, const mbedtls_ecp_point *Q,
2808 mbedtls_ecp_restart_ctx *rs_ctx)
2809 {
2810 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2811 mbedtls_ecp_point mP;
2812 mbedtls_ecp_point *pmP = &mP;
2813 mbedtls_ecp_point *pR = R;
2814 mbedtls_mpi tmp[4];
2815 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2816 char is_grp_capable = 0;
2817 #endif
2818 if (mbedtls_ecp_get_type(grp) != MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
2819 return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
2820 }
2821
2822 mbedtls_ecp_point_init(&mP);
2823 mpi_init_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
2824
2825 ECP_RS_ENTER(ma);
2826
2827 #if defined(MBEDTLS_ECP_RESTARTABLE)
2828 if (rs_ctx != NULL && rs_ctx->ma != NULL) {
2829 /* redirect intermediate results to restart context */
2830 pmP = &rs_ctx->ma->mP;
2831 pR = &rs_ctx->ma->R;
2832
2833 /* jump to next operation */
2834 if (rs_ctx->ma->state == ecp_rsma_mul2) {
2835 goto mul2;
2836 }
2837 if (rs_ctx->ma->state == ecp_rsma_add) {
2838 goto add;
2839 }
2840 if (rs_ctx->ma->state == ecp_rsma_norm) {
2841 goto norm;
2842 }
2843 }
2844 #endif /* MBEDTLS_ECP_RESTARTABLE */
2845
2846 MBEDTLS_MPI_CHK(mbedtls_ecp_mul_shortcuts(grp, pmP, m, P, rs_ctx));
2847 #if defined(MBEDTLS_ECP_RESTARTABLE)
2848 if (rs_ctx != NULL && rs_ctx->ma != NULL) {
2849 rs_ctx->ma->state = ecp_rsma_mul2;
2850 }
2851
2852 mul2:
2853 #endif
2854 MBEDTLS_MPI_CHK(mbedtls_ecp_mul_shortcuts(grp, pR, n, Q, rs_ctx));
2855
2856 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2857 if ((is_grp_capable = mbedtls_internal_ecp_grp_capable(grp))) {
2858 MBEDTLS_MPI_CHK(mbedtls_internal_ecp_init(grp));
2859 }
2860 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
2861
2862 #if defined(MBEDTLS_ECP_RESTARTABLE)
2863 if (rs_ctx != NULL && rs_ctx->ma != NULL) {
2864 rs_ctx->ma->state = ecp_rsma_add;
2865 }
2866
2867 add:
2868 #endif
2869 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_ADD);
2870 MBEDTLS_MPI_CHK(ecp_add_mixed(grp, pR, pmP, pR, tmp));
2871 #if defined(MBEDTLS_ECP_RESTARTABLE)
2872 if (rs_ctx != NULL && rs_ctx->ma != NULL) {
2873 rs_ctx->ma->state = ecp_rsma_norm;
2874 }
2875
2876 norm:
2877 #endif
2878 MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV);
2879 MBEDTLS_MPI_CHK(ecp_normalize_jac(grp, pR));
2880
2881 #if defined(MBEDTLS_ECP_RESTARTABLE)
2882 if (rs_ctx != NULL && rs_ctx->ma != NULL) {
2883 MBEDTLS_MPI_CHK(mbedtls_ecp_copy(R, pR));
2884 }
2885 #endif
2886
2887 cleanup:
2888
2889 mpi_free_many(tmp, sizeof(tmp) / sizeof(mbedtls_mpi));
2890
2891 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2892 if (is_grp_capable) {
2893 mbedtls_internal_ecp_free(grp);
2894 }
2895 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
2896
2897 mbedtls_ecp_point_free(&mP);
2898
2899 ECP_RS_LEAVE(ma);
2900
2901 return ret;
2902 }
2903
2904 /*
2905 * Linear combination
2906 * NOT constant-time
2907 */
mbedtls_ecp_muladd(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,const mbedtls_mpi * n,const mbedtls_ecp_point * Q)2908 int mbedtls_ecp_muladd(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2909 const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2910 const mbedtls_mpi *n, const mbedtls_ecp_point *Q)
2911 {
2912 return mbedtls_ecp_muladd_restartable(grp, R, m, P, n, Q, NULL);
2913 }
2914 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
2915 #endif /* MBEDTLS_ECP_C */
2916
2917 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2918 #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
2919 #define ECP_MPI_INIT(_p, _n) { .p = (mbedtls_mpi_uint *) (_p), .s = 1, .n = (_n), .use_mempool = 0 }
2920 #define ECP_MPI_INIT_ARRAY(x) \
2921 ECP_MPI_INIT(x, sizeof(x) / sizeof(mbedtls_mpi_uint))
2922 /*
2923 * Constants for the two points other than 0, 1, -1 (mod p) in
2924 * https://cr.yp.to/ecdh.html#validate
2925 * See ecp_check_pubkey_x25519().
2926 */
2927 static const mbedtls_mpi_uint x25519_bad_point_1[] = {
2928 MBEDTLS_BYTES_TO_T_UINT_8(0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae),
2929 MBEDTLS_BYTES_TO_T_UINT_8(0x16, 0x56, 0xe3, 0xfa, 0xf1, 0x9f, 0xc4, 0x6a),
2930 MBEDTLS_BYTES_TO_T_UINT_8(0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32, 0xb1, 0xfd),
2931 MBEDTLS_BYTES_TO_T_UINT_8(0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00),
2932 };
2933 static const mbedtls_mpi_uint x25519_bad_point_2[] = {
2934 MBEDTLS_BYTES_TO_T_UINT_8(0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24),
2935 MBEDTLS_BYTES_TO_T_UINT_8(0xb1, 0xd0, 0xb1, 0x55, 0x9c, 0x83, 0xef, 0x5b),
2936 MBEDTLS_BYTES_TO_T_UINT_8(0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c, 0x8e, 0x86),
2937 MBEDTLS_BYTES_TO_T_UINT_8(0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57),
2938 };
2939 static const mbedtls_mpi ecp_x25519_bad_point_1 = ECP_MPI_INIT_ARRAY(
2940 x25519_bad_point_1);
2941 static const mbedtls_mpi ecp_x25519_bad_point_2 = ECP_MPI_INIT_ARRAY(
2942 x25519_bad_point_2);
2943 #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */
2944
2945 /*
2946 * Check that the input point is not one of the low-order points.
2947 * This is recommended by the "May the Fourth" paper:
2948 * https://eprint.iacr.org/2017/806.pdf
2949 * Those points are never sent by an honest peer.
2950 */
ecp_check_bad_points_mx(const mbedtls_mpi * X,const mbedtls_mpi * P,const mbedtls_ecp_group_id grp_id)2951 static int ecp_check_bad_points_mx(const mbedtls_mpi *X, const mbedtls_mpi *P,
2952 const mbedtls_ecp_group_id grp_id)
2953 {
2954 int ret;
2955 mbedtls_mpi XmP;
2956
2957 mbedtls_mpi_init(&XmP);
2958
2959 /* Reduce X mod P so that we only need to check values less than P.
2960 * We know X < 2^256 so we can proceed by subtraction. */
2961 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&XmP, X));
2962 while (mbedtls_mpi_cmp_mpi(&XmP, P) >= 0) {
2963 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&XmP, &XmP, P));
2964 }
2965
2966 /* Check against the known bad values that are less than P. For Curve448
2967 * these are 0, 1 and -1. For Curve25519 we check the values less than P
2968 * from the following list: https://cr.yp.to/ecdh.html#validate */
2969 if (mbedtls_mpi_cmp_int(&XmP, 1) <= 0) { /* takes care of 0 and 1 */
2970 ret = MBEDTLS_ERR_ECP_INVALID_KEY;
2971 goto cleanup;
2972 }
2973
2974 #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
2975 if (grp_id == MBEDTLS_ECP_DP_CURVE25519) {
2976 if (mbedtls_mpi_cmp_mpi(&XmP, &ecp_x25519_bad_point_1) == 0) {
2977 ret = MBEDTLS_ERR_ECP_INVALID_KEY;
2978 goto cleanup;
2979 }
2980
2981 if (mbedtls_mpi_cmp_mpi(&XmP, &ecp_x25519_bad_point_2) == 0) {
2982 ret = MBEDTLS_ERR_ECP_INVALID_KEY;
2983 goto cleanup;
2984 }
2985 }
2986 #else
2987 (void) grp_id;
2988 #endif
2989
2990 /* Final check: check if XmP + 1 is P (final because it changes XmP!) */
2991 MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&XmP, &XmP, 1));
2992 if (mbedtls_mpi_cmp_mpi(&XmP, P) == 0) {
2993 ret = MBEDTLS_ERR_ECP_INVALID_KEY;
2994 goto cleanup;
2995 }
2996
2997 ret = 0;
2998
2999 cleanup:
3000 mbedtls_mpi_free(&XmP);
3001
3002 return ret;
3003 }
3004
3005 /*
3006 * Check validity of a public key for Montgomery curves with x-only schemes
3007 */
ecp_check_pubkey_mx(const mbedtls_ecp_group * grp,const mbedtls_ecp_point * pt)3008 static int ecp_check_pubkey_mx(const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt)
3009 {
3010 /* [Curve25519 p. 5] Just check X is the correct number of bytes */
3011 /* Allow any public value, if it's too big then we'll just reduce it mod p
3012 * (RFC 7748 sec. 5 para. 3). */
3013 if (mbedtls_mpi_size(&pt->X) > (grp->nbits + 7) / 8) {
3014 return MBEDTLS_ERR_ECP_INVALID_KEY;
3015 }
3016
3017 /* Implicit in all standards (as they don't consider negative numbers):
3018 * X must be non-negative. This is normally ensured by the way it's
3019 * encoded for transmission, but let's be extra sure. */
3020 if (mbedtls_mpi_cmp_int(&pt->X, 0) < 0) {
3021 return MBEDTLS_ERR_ECP_INVALID_KEY;
3022 }
3023
3024 return ecp_check_bad_points_mx(&pt->X, &grp->P, grp->id);
3025 }
3026 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
3027
3028 /*
3029 * Check that a point is valid as a public key
3030 */
mbedtls_ecp_check_pubkey(const mbedtls_ecp_group * grp,const mbedtls_ecp_point * pt)3031 int mbedtls_ecp_check_pubkey(const mbedtls_ecp_group *grp,
3032 const mbedtls_ecp_point *pt)
3033 {
3034 /* Must use affine coordinates */
3035 if (mbedtls_mpi_cmp_int(&pt->Z, 1) != 0) {
3036 return MBEDTLS_ERR_ECP_INVALID_KEY;
3037 }
3038
3039 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3040 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
3041 return ecp_check_pubkey_mx(grp, pt);
3042 }
3043 #endif
3044 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3045 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
3046 return ecp_check_pubkey_sw(grp, pt);
3047 }
3048 #endif
3049 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
3050 }
3051
3052 /*
3053 * Check that an mbedtls_mpi is valid as a private key
3054 */
mbedtls_ecp_check_privkey(const mbedtls_ecp_group * grp,const mbedtls_mpi * d)3055 int mbedtls_ecp_check_privkey(const mbedtls_ecp_group *grp,
3056 const mbedtls_mpi *d)
3057 {
3058 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3059 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
3060 /* see RFC 7748 sec. 5 para. 5 */
3061 if (mbedtls_mpi_get_bit(d, 0) != 0 ||
3062 mbedtls_mpi_get_bit(d, 1) != 0 ||
3063 mbedtls_mpi_bitlen(d) != grp->nbits + 1) { /* mbedtls_mpi_bitlen is one-based! */
3064 return MBEDTLS_ERR_ECP_INVALID_KEY;
3065 }
3066
3067 /* see [Curve25519] page 5 */
3068 if (grp->nbits == 254 && mbedtls_mpi_get_bit(d, 2) != 0) {
3069 return MBEDTLS_ERR_ECP_INVALID_KEY;
3070 }
3071
3072 return 0;
3073 }
3074 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
3075 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3076 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
3077 /* see SEC1 3.2 */
3078 if (mbedtls_mpi_cmp_int(d, 1) < 0 ||
3079 mbedtls_mpi_cmp_mpi(d, &grp->N) >= 0) {
3080 return MBEDTLS_ERR_ECP_INVALID_KEY;
3081 } else {
3082 return 0;
3083 }
3084 }
3085 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
3086
3087 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
3088 }
3089
3090 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3091 MBEDTLS_STATIC_TESTABLE
mbedtls_ecp_gen_privkey_mx(size_t high_bit,mbedtls_mpi * d,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)3092 int mbedtls_ecp_gen_privkey_mx(size_t high_bit,
3093 mbedtls_mpi *d,
3094 int (*f_rng)(void *, unsigned char *, size_t),
3095 void *p_rng)
3096 {
3097 int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
3098 size_t n_random_bytes = high_bit / 8 + 1;
3099
3100 /* [Curve25519] page 5 */
3101 /* Generate a (high_bit+1)-bit random number by generating just enough
3102 * random bytes, then shifting out extra bits from the top (necessary
3103 * when (high_bit+1) is not a multiple of 8). */
3104 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(d, n_random_bytes,
3105 f_rng, p_rng));
3106 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(d, 8 * n_random_bytes - high_bit - 1));
3107
3108 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, high_bit, 1));
3109
3110 /* Make sure the last two bits are unset for Curve448, three bits for
3111 Curve25519 */
3112 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, 0, 0));
3113 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, 1, 0));
3114 if (high_bit == 254) {
3115 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(d, 2, 0));
3116 }
3117
3118 cleanup:
3119 return ret;
3120 }
3121 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
3122
3123 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
mbedtls_ecp_gen_privkey_sw(const mbedtls_mpi * N,mbedtls_mpi * d,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)3124 static int mbedtls_ecp_gen_privkey_sw(
3125 const mbedtls_mpi *N, mbedtls_mpi *d,
3126 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
3127 {
3128 int ret = mbedtls_mpi_random(d, 1, N, f_rng, p_rng);
3129 switch (ret) {
3130 case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE:
3131 return MBEDTLS_ERR_ECP_RANDOM_FAILED;
3132 default:
3133 return ret;
3134 }
3135 }
3136 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
3137
3138 /*
3139 * Generate a private key
3140 */
mbedtls_ecp_gen_privkey(const mbedtls_ecp_group * grp,mbedtls_mpi * d,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)3141 int mbedtls_ecp_gen_privkey(const mbedtls_ecp_group *grp,
3142 mbedtls_mpi *d,
3143 int (*f_rng)(void *, unsigned char *, size_t),
3144 void *p_rng)
3145 {
3146 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3147 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
3148 return mbedtls_ecp_gen_privkey_mx(grp->nbits, d, f_rng, p_rng);
3149 }
3150 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
3151
3152 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3153 if (mbedtls_ecp_get_type(grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
3154 return mbedtls_ecp_gen_privkey_sw(&grp->N, d, f_rng, p_rng);
3155 }
3156 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
3157
3158 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
3159 }
3160
3161 #if defined(MBEDTLS_ECP_C)
3162 /*
3163 * Generate a keypair with configurable base point
3164 */
mbedtls_ecp_gen_keypair_base(mbedtls_ecp_group * grp,const mbedtls_ecp_point * G,mbedtls_mpi * d,mbedtls_ecp_point * Q,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)3165 int mbedtls_ecp_gen_keypair_base(mbedtls_ecp_group *grp,
3166 const mbedtls_ecp_point *G,
3167 mbedtls_mpi *d, mbedtls_ecp_point *Q,
3168 int (*f_rng)(void *, unsigned char *, size_t),
3169 void *p_rng)
3170 {
3171 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3172 MBEDTLS_MPI_CHK(mbedtls_ecp_gen_privkey(grp, d, f_rng, p_rng));
3173 MBEDTLS_MPI_CHK(mbedtls_ecp_mul(grp, Q, d, G, f_rng, p_rng));
3174
3175 cleanup:
3176 return ret;
3177 }
3178
3179 /*
3180 * Generate key pair, wrapper for conventional base point
3181 */
mbedtls_ecp_gen_keypair(mbedtls_ecp_group * grp,mbedtls_mpi * d,mbedtls_ecp_point * Q,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)3182 int mbedtls_ecp_gen_keypair(mbedtls_ecp_group *grp,
3183 mbedtls_mpi *d, mbedtls_ecp_point *Q,
3184 int (*f_rng)(void *, unsigned char *, size_t),
3185 void *p_rng)
3186 {
3187 return mbedtls_ecp_gen_keypair_base(grp, &grp->G, d, Q, f_rng, p_rng);
3188 }
3189
3190 /*
3191 * Generate a keypair, prettier wrapper
3192 */
mbedtls_ecp_gen_key(mbedtls_ecp_group_id grp_id,mbedtls_ecp_keypair * key,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)3193 int mbedtls_ecp_gen_key(mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
3194 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
3195 {
3196 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3197 if ((ret = mbedtls_ecp_group_load(&key->grp, grp_id)) != 0) {
3198 return ret;
3199 }
3200
3201 return mbedtls_ecp_gen_keypair(&key->grp, &key->d, &key->Q, f_rng, p_rng);
3202 }
3203 #endif /* MBEDTLS_ECP_C */
3204
mbedtls_ecp_set_public_key(mbedtls_ecp_group_id grp_id,mbedtls_ecp_keypair * key,const mbedtls_ecp_point * Q)3205 int mbedtls_ecp_set_public_key(mbedtls_ecp_group_id grp_id,
3206 mbedtls_ecp_keypair *key,
3207 const mbedtls_ecp_point *Q)
3208 {
3209 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3210
3211 if (key->grp.id == MBEDTLS_ECP_DP_NONE) {
3212 /* Group not set yet */
3213 if ((ret = mbedtls_ecp_group_load(&key->grp, grp_id)) != 0) {
3214 return ret;
3215 }
3216 } else if (key->grp.id != grp_id) {
3217 /* Group mismatch */
3218 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
3219 }
3220 return mbedtls_ecp_copy(&key->Q, Q);
3221 }
3222
3223
3224 #define ECP_CURVE25519_KEY_SIZE 32
3225 #define ECP_CURVE448_KEY_SIZE 56
3226 /*
3227 * Read a private key.
3228 */
mbedtls_ecp_read_key(mbedtls_ecp_group_id grp_id,mbedtls_ecp_keypair * key,const unsigned char * buf,size_t buflen)3229 int mbedtls_ecp_read_key(mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
3230 const unsigned char *buf, size_t buflen)
3231 {
3232 int ret = 0;
3233
3234 if ((ret = mbedtls_ecp_group_load(&key->grp, grp_id)) != 0) {
3235 return ret;
3236 }
3237
3238 ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
3239
3240 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3241 if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
3242 /*
3243 * Mask the key as mandated by RFC7748 for Curve25519 and Curve448.
3244 */
3245 if (grp_id == MBEDTLS_ECP_DP_CURVE25519) {
3246 if (buflen != ECP_CURVE25519_KEY_SIZE) {
3247 return MBEDTLS_ERR_ECP_INVALID_KEY;
3248 }
3249
3250 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary_le(&key->d, buf, buflen));
3251
3252 /* Set the three least significant bits to 0 */
3253 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 0, 0));
3254 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 1, 0));
3255 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 2, 0));
3256
3257 /* Set the most significant bit to 0 */
3258 MBEDTLS_MPI_CHK(
3259 mbedtls_mpi_set_bit(&key->d,
3260 ECP_CURVE25519_KEY_SIZE * 8 - 1, 0)
3261 );
3262
3263 /* Set the second most significant bit to 1 */
3264 MBEDTLS_MPI_CHK(
3265 mbedtls_mpi_set_bit(&key->d,
3266 ECP_CURVE25519_KEY_SIZE * 8 - 2, 1)
3267 );
3268 } else if (grp_id == MBEDTLS_ECP_DP_CURVE448) {
3269 if (buflen != ECP_CURVE448_KEY_SIZE) {
3270 return MBEDTLS_ERR_ECP_INVALID_KEY;
3271 }
3272
3273 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary_le(&key->d, buf, buflen));
3274
3275 /* Set the two least significant bits to 0 */
3276 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 0, 0));
3277 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(&key->d, 1, 0));
3278
3279 /* Set the most significant bit to 1 */
3280 MBEDTLS_MPI_CHK(
3281 mbedtls_mpi_set_bit(&key->d,
3282 ECP_CURVE448_KEY_SIZE * 8 - 1, 1)
3283 );
3284 }
3285 }
3286 #endif
3287 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3288 if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
3289 MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&key->d, buf, buflen));
3290 }
3291 #endif
3292
3293 if (ret == 0) {
3294 MBEDTLS_MPI_CHK(mbedtls_ecp_check_privkey(&key->grp, &key->d));
3295 }
3296
3297 cleanup:
3298
3299 if (ret != 0) {
3300 mbedtls_mpi_free(&key->d);
3301 }
3302
3303 return ret;
3304 }
3305
3306 /*
3307 * Write a private key.
3308 */
3309 #if !defined MBEDTLS_DEPRECATED_REMOVED
mbedtls_ecp_write_key(mbedtls_ecp_keypair * key,unsigned char * buf,size_t buflen)3310 int mbedtls_ecp_write_key(mbedtls_ecp_keypair *key,
3311 unsigned char *buf, size_t buflen)
3312 {
3313 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3314
3315 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3316 if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
3317 if (key->grp.id == MBEDTLS_ECP_DP_CURVE25519) {
3318 if (buflen < ECP_CURVE25519_KEY_SIZE) {
3319 return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
3320 }
3321
3322 } else if (key->grp.id == MBEDTLS_ECP_DP_CURVE448) {
3323 if (buflen < ECP_CURVE448_KEY_SIZE) {
3324 return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
3325 }
3326 }
3327 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary_le(&key->d, buf, buflen));
3328 }
3329 #endif
3330 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3331 if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
3332 MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&key->d, buf, buflen));
3333 }
3334
3335 #endif
3336 cleanup:
3337
3338 return ret;
3339 }
3340 #endif /* MBEDTLS_DEPRECATED_REMOVED */
3341
mbedtls_ecp_write_key_ext(const mbedtls_ecp_keypair * key,size_t * olen,unsigned char * buf,size_t buflen)3342 int mbedtls_ecp_write_key_ext(const mbedtls_ecp_keypair *key,
3343 size_t *olen, unsigned char *buf, size_t buflen)
3344 {
3345 size_t len = (key->grp.nbits + 7) / 8;
3346 if (len > buflen) {
3347 /* For robustness, ensure *olen <= buflen even on error. */
3348 *olen = 0;
3349 return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
3350 }
3351 *olen = len;
3352
3353 /* Private key not set */
3354 if (key->d.n == 0) {
3355 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
3356 }
3357
3358 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3359 if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
3360 return mbedtls_mpi_write_binary_le(&key->d, buf, len);
3361 }
3362 #endif
3363
3364 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3365 if (mbedtls_ecp_get_type(&key->grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
3366 return mbedtls_mpi_write_binary(&key->d, buf, len);
3367 }
3368 #endif
3369
3370 /* Private key set but no recognized curve type? This shouldn't happen. */
3371 return MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3372 }
3373
3374 /*
3375 * Write a public key.
3376 */
mbedtls_ecp_write_public_key(const mbedtls_ecp_keypair * key,int format,size_t * olen,unsigned char * buf,size_t buflen)3377 int mbedtls_ecp_write_public_key(const mbedtls_ecp_keypair *key,
3378 int format, size_t *olen,
3379 unsigned char *buf, size_t buflen)
3380 {
3381 return mbedtls_ecp_point_write_binary(&key->grp, &key->Q,
3382 format, olen, buf, buflen);
3383 }
3384
3385
3386 #if defined(MBEDTLS_ECP_C)
3387 /*
3388 * Check a public-private key pair
3389 */
mbedtls_ecp_check_pub_priv(const mbedtls_ecp_keypair * pub,const mbedtls_ecp_keypair * prv,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)3390 int mbedtls_ecp_check_pub_priv(
3391 const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv,
3392 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
3393 {
3394 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3395 mbedtls_ecp_point Q;
3396 mbedtls_ecp_group grp;
3397 if (pub->grp.id == MBEDTLS_ECP_DP_NONE ||
3398 pub->grp.id != prv->grp.id ||
3399 mbedtls_mpi_cmp_mpi(&pub->Q.X, &prv->Q.X) ||
3400 mbedtls_mpi_cmp_mpi(&pub->Q.Y, &prv->Q.Y) ||
3401 mbedtls_mpi_cmp_mpi(&pub->Q.Z, &prv->Q.Z)) {
3402 return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
3403 }
3404
3405 mbedtls_ecp_point_init(&Q);
3406 mbedtls_ecp_group_init(&grp);
3407
3408 /* mbedtls_ecp_mul() needs a non-const group... */
3409 mbedtls_ecp_group_copy(&grp, &prv->grp);
3410
3411 /* Also checks d is valid */
3412 MBEDTLS_MPI_CHK(mbedtls_ecp_mul(&grp, &Q, &prv->d, &prv->grp.G, f_rng, p_rng));
3413
3414 if (mbedtls_mpi_cmp_mpi(&Q.X, &prv->Q.X) ||
3415 mbedtls_mpi_cmp_mpi(&Q.Y, &prv->Q.Y) ||
3416 mbedtls_mpi_cmp_mpi(&Q.Z, &prv->Q.Z)) {
3417 ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
3418 goto cleanup;
3419 }
3420
3421 cleanup:
3422 mbedtls_ecp_point_free(&Q);
3423 mbedtls_ecp_group_free(&grp);
3424
3425 return ret;
3426 }
3427
mbedtls_ecp_keypair_calc_public(mbedtls_ecp_keypair * key,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)3428 int mbedtls_ecp_keypair_calc_public(mbedtls_ecp_keypair *key,
3429 int (*f_rng)(void *, unsigned char *, size_t),
3430 void *p_rng)
3431 {
3432 return mbedtls_ecp_mul(&key->grp, &key->Q, &key->d, &key->grp.G,
3433 f_rng, p_rng);
3434 }
3435 #endif /* MBEDTLS_ECP_C */
3436
mbedtls_ecp_keypair_get_group_id(const mbedtls_ecp_keypair * key)3437 mbedtls_ecp_group_id mbedtls_ecp_keypair_get_group_id(
3438 const mbedtls_ecp_keypair *key)
3439 {
3440 return key->grp.id;
3441 }
3442
3443 /*
3444 * Export generic key-pair parameters.
3445 */
mbedtls_ecp_export(const mbedtls_ecp_keypair * key,mbedtls_ecp_group * grp,mbedtls_mpi * d,mbedtls_ecp_point * Q)3446 int mbedtls_ecp_export(const mbedtls_ecp_keypair *key, mbedtls_ecp_group *grp,
3447 mbedtls_mpi *d, mbedtls_ecp_point *Q)
3448 {
3449 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3450
3451 if (grp != NULL && (ret = mbedtls_ecp_group_copy(grp, &key->grp)) != 0) {
3452 return ret;
3453 }
3454
3455 if (d != NULL && (ret = mbedtls_mpi_copy(d, &key->d)) != 0) {
3456 return ret;
3457 }
3458
3459 if (Q != NULL && (ret = mbedtls_ecp_copy(Q, &key->Q)) != 0) {
3460 return ret;
3461 }
3462
3463 return 0;
3464 }
3465
3466 #if defined(MBEDTLS_SELF_TEST)
3467
3468 #if defined(MBEDTLS_ECP_C)
3469 /*
3470 * PRNG for test - !!!INSECURE NEVER USE IN PRODUCTION!!!
3471 *
3472 * This is the linear congruential generator from numerical recipes,
3473 * except we only use the low byte as the output. See
3474 * https://en.wikipedia.org/wiki/Linear_congruential_generator#Parameters_in_common_use
3475 */
self_test_rng(void * ctx,unsigned char * out,size_t len)3476 static int self_test_rng(void *ctx, unsigned char *out, size_t len)
3477 {
3478 static uint32_t state = 42;
3479
3480 (void) ctx;
3481
3482 for (size_t i = 0; i < len; i++) {
3483 state = state * 1664525u + 1013904223u;
3484 out[i] = (unsigned char) state;
3485 }
3486
3487 return 0;
3488 }
3489
3490 /* Adjust the exponent to be a valid private point for the specified curve.
3491 * This is sometimes necessary because we use a single set of exponents
3492 * for all curves but the validity of values depends on the curve. */
self_test_adjust_exponent(const mbedtls_ecp_group * grp,mbedtls_mpi * m)3493 static int self_test_adjust_exponent(const mbedtls_ecp_group *grp,
3494 mbedtls_mpi *m)
3495 {
3496 int ret = 0;
3497 switch (grp->id) {
3498 /* If Curve25519 is available, then that's what we use for the
3499 * Montgomery test, so we don't need the adjustment code. */
3500 #if !defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
3501 #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
3502 case MBEDTLS_ECP_DP_CURVE448:
3503 /* Move highest bit from 254 to N-1. Setting bit N-1 is
3504 * necessary to enforce the highest-bit-set constraint. */
3505 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(m, 254, 0));
3506 MBEDTLS_MPI_CHK(mbedtls_mpi_set_bit(m, grp->nbits, 1));
3507 /* Copy second-highest bit from 253 to N-2. This is not
3508 * necessary but improves the test variety a bit. */
3509 MBEDTLS_MPI_CHK(
3510 mbedtls_mpi_set_bit(m, grp->nbits - 1,
3511 mbedtls_mpi_get_bit(m, 253)));
3512 break;
3513 #endif
3514 #endif /* ! defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) */
3515 default:
3516 /* Non-Montgomery curves and Curve25519 need no adjustment. */
3517 (void) grp;
3518 (void) m;
3519 goto cleanup;
3520 }
3521 cleanup:
3522 return ret;
3523 }
3524
3525 /* Calculate R = m.P for each m in exponents. Check that the number of
3526 * basic operations doesn't depend on the value of m. */
self_test_point(int verbose,mbedtls_ecp_group * grp,mbedtls_ecp_point * R,mbedtls_mpi * m,const mbedtls_ecp_point * P,const char * const * exponents,size_t n_exponents)3527 static int self_test_point(int verbose,
3528 mbedtls_ecp_group *grp,
3529 mbedtls_ecp_point *R,
3530 mbedtls_mpi *m,
3531 const mbedtls_ecp_point *P,
3532 const char *const *exponents,
3533 size_t n_exponents)
3534 {
3535 int ret = 0;
3536 size_t i = 0;
3537 unsigned long add_c_prev, dbl_c_prev, mul_c_prev;
3538 add_count = 0;
3539 dbl_count = 0;
3540 mul_count = 0;
3541
3542 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(m, 16, exponents[0]));
3543 MBEDTLS_MPI_CHK(self_test_adjust_exponent(grp, m));
3544 MBEDTLS_MPI_CHK(mbedtls_ecp_mul(grp, R, m, P, self_test_rng, NULL));
3545
3546 for (i = 1; i < n_exponents; i++) {
3547 add_c_prev = add_count;
3548 dbl_c_prev = dbl_count;
3549 mul_c_prev = mul_count;
3550 add_count = 0;
3551 dbl_count = 0;
3552 mul_count = 0;
3553
3554 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(m, 16, exponents[i]));
3555 MBEDTLS_MPI_CHK(self_test_adjust_exponent(grp, m));
3556 MBEDTLS_MPI_CHK(mbedtls_ecp_mul(grp, R, m, P, self_test_rng, NULL));
3557
3558 if (add_count != add_c_prev ||
3559 dbl_count != dbl_c_prev ||
3560 mul_count != mul_c_prev) {
3561 ret = 1;
3562 break;
3563 }
3564 }
3565
3566 cleanup:
3567 if (verbose != 0) {
3568 if (ret != 0) {
3569 mbedtls_printf("failed (%u)\n", (unsigned int) i);
3570 } else {
3571 mbedtls_printf("passed\n");
3572 }
3573 }
3574 return ret;
3575 }
3576 #endif /* MBEDTLS_ECP_C */
3577
3578 /*
3579 * Checkup routine
3580 */
mbedtls_ecp_self_test(int verbose)3581 int mbedtls_ecp_self_test(int verbose)
3582 {
3583 #if defined(MBEDTLS_ECP_C)
3584 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3585 mbedtls_ecp_group grp;
3586 mbedtls_ecp_point R, P;
3587 mbedtls_mpi m;
3588
3589 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3590 /* Exponents especially adapted for secp192k1, which has the lowest
3591 * order n of all supported curves (secp192r1 is in a slightly larger
3592 * field but the order of its base point is slightly smaller). */
3593 const char *sw_exponents[] =
3594 {
3595 "000000000000000000000000000000000000000000000001", /* one */
3596 "FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8C", /* n - 1 */
3597 "5EA6F389A38B8BC81E767753B15AA5569E1782E30ABE7D25", /* random */
3598 "400000000000000000000000000000000000000000000000", /* one and zeros */
3599 "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* all ones */
3600 "555555555555555555555555555555555555555555555555", /* 101010... */
3601 };
3602 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
3603 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3604 const char *m_exponents[] =
3605 {
3606 /* Valid private values for Curve25519. In a build with Curve448
3607 * but not Curve25519, they will be adjusted in
3608 * self_test_adjust_exponent(). */
3609 "4000000000000000000000000000000000000000000000000000000000000000",
3610 "5C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C30",
3611 "5715ECCE24583F7A7023C24164390586842E816D7280A49EF6DF4EAE6B280BF8",
3612 "41A2B017516F6D254E1F002BCCBADD54BE30F8CEC737A0E912B4963B6BA74460",
3613 "5555555555555555555555555555555555555555555555555555555555555550",
3614 "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8",
3615 };
3616 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
3617
3618 mbedtls_ecp_group_init(&grp);
3619 mbedtls_ecp_point_init(&R);
3620 mbedtls_ecp_point_init(&P);
3621 mbedtls_mpi_init(&m);
3622
3623 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
3624 /* Use secp192r1 if available, or any available curve */
3625 #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
3626 MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_SECP192R1));
3627 #else
3628 MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, mbedtls_ecp_curve_list()->grp_id));
3629 #endif
3630
3631 if (verbose != 0) {
3632 mbedtls_printf(" ECP SW test #1 (constant op_count, base point G): ");
3633 }
3634 /* Do a dummy multiplication first to trigger precomputation */
3635 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&m, 2));
3636 MBEDTLS_MPI_CHK(mbedtls_ecp_mul(&grp, &P, &m, &grp.G, self_test_rng, NULL));
3637 ret = self_test_point(verbose,
3638 &grp, &R, &m, &grp.G,
3639 sw_exponents,
3640 sizeof(sw_exponents) / sizeof(sw_exponents[0]));
3641 if (ret != 0) {
3642 goto cleanup;
3643 }
3644
3645 if (verbose != 0) {
3646 mbedtls_printf(" ECP SW test #2 (constant op_count, other point): ");
3647 }
3648 /* We computed P = 2G last time, use it */
3649 ret = self_test_point(verbose,
3650 &grp, &R, &m, &P,
3651 sw_exponents,
3652 sizeof(sw_exponents) / sizeof(sw_exponents[0]));
3653 if (ret != 0) {
3654 goto cleanup;
3655 }
3656
3657 mbedtls_ecp_group_free(&grp);
3658 mbedtls_ecp_point_free(&R);
3659 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
3660
3661 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
3662 if (verbose != 0) {
3663 mbedtls_printf(" ECP Montgomery test (constant op_count): ");
3664 }
3665 #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
3666 MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_CURVE25519));
3667 #elif defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
3668 MBEDTLS_MPI_CHK(mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_CURVE448));
3669 #else
3670 #error "MBEDTLS_ECP_MONTGOMERY_ENABLED is defined, but no curve is supported for self-test"
3671 #endif
3672 ret = self_test_point(verbose,
3673 &grp, &R, &m, &grp.G,
3674 m_exponents,
3675 sizeof(m_exponents) / sizeof(m_exponents[0]));
3676 if (ret != 0) {
3677 goto cleanup;
3678 }
3679 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
3680
3681 cleanup:
3682
3683 if (ret < 0 && verbose != 0) {
3684 mbedtls_printf("Unexpected error, return code = %08X\n", (unsigned int) ret);
3685 }
3686
3687 mbedtls_ecp_group_free(&grp);
3688 mbedtls_ecp_point_free(&R);
3689 mbedtls_ecp_point_free(&P);
3690 mbedtls_mpi_free(&m);
3691
3692 if (verbose != 0) {
3693 mbedtls_printf("\n");
3694 }
3695
3696 return ret;
3697 #else /* MBEDTLS_ECP_C */
3698 (void) verbose;
3699 return 0;
3700 #endif /* MBEDTLS_ECP_C */
3701 }
3702
3703 #endif /* MBEDTLS_SELF_TEST */
3704
3705 #endif /* !MBEDTLS_ECP_ALT */
3706
3707 #endif /* MBEDTLS_ECP_LIGHT */
3708