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