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