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