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