1 /*
2  *  Elliptic curves over GF(p): generic functions
3  *
4  *  Copyright (C) 2006-2022, ARM Limited, All Rights Reserved
5  *  Copyright (C) 2019, STMicroelectronics, All Rights Reserved
6  *  SPDX-License-Identifier: Apache-2.0
7  *
8  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
9  *  not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  *
12  *  http://www.apache.org/licenses/LICENSE-2.0
13  *
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  *
20  *  This file implements STMicroelectronics EC scalar mul and point check
21  *  with HW services based on mbed TLS API
22  */
23 
24 /*
25  * References:
26  *
27  * SEC1 http://www.secg.org/index.php?action=secg,docs_secg
28  * GECC = Guide to Elliptic Curve Cryptography - Hankerson, Menezes, Vanstone
29  * FIPS 186-3 http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
30  * RFC 4492 for the related TLS structures and constants
31  * RFC 7748 for the Curve448 and Curve25519 curve definitions
32  *
33  * [Curve25519] http://cr.yp.to/ecdh/curve25519-20060209.pdf
34  *
35  * [2] CORON, Jean-S'ebastien. Resistance against differential power analysis
36  *     for elliptic curve cryptosystems. In : Cryptographic Hardware and
37  *     Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302.
38  *     <http://link.springer.com/chapter/10.1007/3-540-48059-5_25>
39  *
40  * [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to
41  *     render ECC resistant against Side Channel Attacks. IACR Cryptology
42  *     ePrint Archive, 2004, vol. 2004, p. 342.
43  *     <http://eprint.iacr.org/2004/342.pdf>
44  */
45 
46 #include "mbedtls/build_info.h"
47 
48 /**
49  * \brief Function level alternative implementation.
50  *
51  * The MBEDTLS_ECP_INTERNAL_ALT macro enables alternative implementations to
52  * replace certain functions in this module. The alternative implementations are
53  * typically hardware accelerators and need to activate the hardware before the
54  * computation starts and deactivate it after it finishes. The
55  * mbedtls_internal_ecp_init() and mbedtls_internal_ecp_free() functions serve
56  * this purpose.
57  *
58  * To preserve the correct functionality the following conditions must hold:
59  *
60  * - The alternative implementation must be activated by
61  *   mbedtls_internal_ecp_init() before any of the replaceable functions is
62  *   called.
63  * - mbedtls_internal_ecp_free() must \b only be called when the alternative
64  *   implementation is activated.
65  * - mbedtls_internal_ecp_init() must \b not be called when the alternative
66  *   implementation is activated.
67  * - Public functions must not return while the alternative implementation is
68  *   activated.
69  * - Replaceable functions are guarded by \c MBEDTLS_ECP_XXX_ALT macros and
70  *   before calling them an \code if( mbedtls_internal_ecp_grp_capable( grp ) )
71  *   \endcode ensures that the alternative implementation supports the current
72  *   group.
73  */
74 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
75 #endif
76 
77 #if defined(MBEDTLS_ECP_C)
78 
79 #include "mbedtls/ecp.h"
80 #include "mbedtls/threading.h"
81 #include "mbedtls/platform_util.h"
82 #include "mbedtls/error.h"
83 
84 #include <string.h>
85 
86 #if defined(MBEDTLS_ECP_ALT)
87 
88 /* Parameter validation macros - mbedtls/platform_util.h has deprecated them */
89 #define ECP_VALIDATE_RET( cond ) do { } while(0)
90 #define ECP_VALIDATE( cond ) do { } while(0)
91 
92 #if defined(MBEDTLS_PLATFORM_C)
93 #include "mbedtls/platform.h"
94 #else
95 #include <stdlib.h>
96 #include <stdio.h>
97 #define mbedtls_printf     printf
98 #define mbedtls_calloc    calloc
99 #define mbedtls_free       free
100 #endif
101 
102 #include "ecp_internal_alt.h"
103 #include "stm32hal.h"
104 
105 #define ST_ECP_TIMEOUT     (5000U)
106 
107 #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) \
108     && !defined(inline) && !defined(__cplusplus)
109 #define inline __inline
110 #endif
111 
112 #if defined(MBEDTLS_SELF_TEST)
113 /*
114  * Counts of point addition and doubling, and field multiplications.
115  * Used to test resistance of point multiplication to simple timing attacks.
116  */
117 static unsigned long add_count, dbl_count, mul_count;
118 #endif
119 
120 #if defined(MBEDTLS_ECP_RESTARTABLE)
121 /*
122  * Maximum number of "basic operations" to be done in a row.
123  *
124  * Default value 0 means that ECC operations will not yield.
125  * Note that regardless of the value of ecp_max_ops, always at
126  * least one step is performed before yielding.
127  *
128  * Setting ecp_max_ops=1 can be suitable for testing purposes
129  * as it will interrupt computation at all possible points.
130  */
131 static unsigned ecp_max_ops = 0;
132 
133 /*
134  * Set ecp_max_ops
135  */
mbedtls_ecp_set_max_ops(unsigned max_ops)136 void mbedtls_ecp_set_max_ops( unsigned max_ops )
137 {
138     ecp_max_ops = max_ops;
139 }
140 
141 /*
142  * Check if restart is enabled
143  */
mbedtls_ecp_restart_is_enabled(void)144 int mbedtls_ecp_restart_is_enabled( void )
145 {
146     return( ecp_max_ops != 0 );
147 }
148 
149 /*
150  * Restart sub-context for ecp_mul_comb()
151  */
152 struct mbedtls_ecp_restart_mul
153 {
154     mbedtls_ecp_point R;    /* current intermediate result                  */
155     size_t i;               /* current index in various loops, 0 outside    */
156     mbedtls_ecp_point *T;   /* table for precomputed points                 */
157     unsigned char T_size;   /* number of points in table T                  */
158     enum {                  /* what were we doing last time we returned?    */
159         ecp_rsm_init = 0,       /* nothing so far, dummy initial state      */
160         ecp_rsm_pre_dbl,        /* precompute 2^n multiples                 */
161         ecp_rsm_pre_norm_dbl,   /* normalize precomputed 2^n multiples      */
162         ecp_rsm_pre_add,        /* precompute remaining points by adding    */
163         ecp_rsm_pre_norm_add,   /* normalize all precomputed points         */
164         ecp_rsm_comb_core,      /* ecp_mul_comb_core()                      */
165         ecp_rsm_final_norm,     /* do the final normalization               */
166     } state;
167 };
168 
169 /*
170  * Init restart_mul sub-context
171  */
ecp_restart_rsm_init(mbedtls_ecp_restart_mul_ctx * ctx)172 static void ecp_restart_rsm_init( mbedtls_ecp_restart_mul_ctx *ctx )
173 {
174     mbedtls_ecp_point_init( &ctx->R );
175     ctx->i = 0;
176     ctx->T = NULL;
177     ctx->T_size = 0;
178     ctx->state = ecp_rsm_init;
179 }
180 
181 /*
182  * Free the components of a restart_mul sub-context
183  */
ecp_restart_rsm_free(mbedtls_ecp_restart_mul_ctx * ctx)184 static void ecp_restart_rsm_free( mbedtls_ecp_restart_mul_ctx *ctx )
185 {
186     unsigned char i;
187 
188     if( ctx == NULL )
189         return;
190 
191     mbedtls_ecp_point_free( &ctx->R );
192 
193     if( ctx->T != NULL )
194     {
195         for( i = 0; i < ctx->T_size; i++ )
196             mbedtls_ecp_point_free( ctx->T + i );
197         mbedtls_free( ctx->T );
198     }
199 
200     ecp_restart_rsm_init( ctx );
201 }
202 
203 /*
204  * Restart context for ecp_muladd()
205  */
206 struct mbedtls_ecp_restart_muladd
207 {
208     mbedtls_ecp_point mP;       /* mP value                             */
209     mbedtls_ecp_point R;        /* R intermediate result                */
210     enum {                      /* what should we do next?              */
211         ecp_rsma_mul1 = 0,      /* first multiplication                 */
212         ecp_rsma_mul2,          /* second multiplication                */
213         ecp_rsma_add,           /* addition                             */
214         ecp_rsma_norm,          /* normalization                        */
215     } state;
216 };
217 
218 /*
219  * Init restart_muladd sub-context
220  */
ecp_restart_ma_init(mbedtls_ecp_restart_muladd_ctx * ctx)221 static void ecp_restart_ma_init( mbedtls_ecp_restart_muladd_ctx *ctx )
222 {
223     mbedtls_ecp_point_init( &ctx->mP );
224     mbedtls_ecp_point_init( &ctx->R );
225     ctx->state = ecp_rsma_mul1;
226 }
227 
228 /*
229  * Free the components of a restart_muladd sub-context
230  */
ecp_restart_ma_free(mbedtls_ecp_restart_muladd_ctx * ctx)231 static void ecp_restart_ma_free( mbedtls_ecp_restart_muladd_ctx *ctx )
232 {
233     if( ctx == NULL )
234         return;
235 
236     mbedtls_ecp_point_free( &ctx->mP );
237     mbedtls_ecp_point_free( &ctx->R );
238 
239     ecp_restart_ma_init( ctx );
240 }
241 
242 /*
243  * Initialize a restart context
244  */
mbedtls_ecp_restart_init(mbedtls_ecp_restart_ctx * ctx)245 void mbedtls_ecp_restart_init( mbedtls_ecp_restart_ctx *ctx )
246 {
247     ECP_VALIDATE( ctx != NULL );
248     ctx->ops_done = 0;
249     ctx->depth = 0;
250     ctx->rsm = NULL;
251     ctx->ma = NULL;
252 }
253 
254 /*
255  * Free the components of a restart context
256  */
mbedtls_ecp_restart_free(mbedtls_ecp_restart_ctx * ctx)257 void mbedtls_ecp_restart_free( mbedtls_ecp_restart_ctx *ctx )
258 {
259     if( ctx == NULL )
260         return;
261 
262     ecp_restart_rsm_free( ctx->rsm );
263     mbedtls_free( ctx->rsm );
264 
265     ecp_restart_ma_free( ctx->ma );
266     mbedtls_free( ctx->ma );
267 
268     mbedtls_ecp_restart_init( ctx );
269 }
270 
271 /*
272  * Check if we can do the next step
273  */
mbedtls_ecp_check_budget(const mbedtls_ecp_group * grp,mbedtls_ecp_restart_ctx * rs_ctx,unsigned ops)274 int mbedtls_ecp_check_budget( const mbedtls_ecp_group *grp,
275                               mbedtls_ecp_restart_ctx *rs_ctx,
276                               unsigned ops )
277 {
278     ECP_VALIDATE_RET( grp != NULL );
279 
280     if( rs_ctx != NULL && ecp_max_ops != 0 )
281     {
282         /* scale depending on curve size: the chosen reference is 256-bit,
283          * and multiplication is quadratic. Round to the closest integer. */
284         if( grp->pbits >= 512 )
285             ops *= 4;
286         else if( grp->pbits >= 384 )
287             ops *= 2;
288 
289         /* Avoid infinite loops: always allow first step.
290          * Because of that, however, it's not generally true
291          * that ops_done <= ecp_max_ops, so the check
292          * ops_done > ecp_max_ops below is mandatory. */
293         if( ( rs_ctx->ops_done != 0 ) &&
294             ( rs_ctx->ops_done > ecp_max_ops ||
295               ops > ecp_max_ops - rs_ctx->ops_done ) )
296         {
297             return( MBEDTLS_ERR_ECP_IN_PROGRESS );
298         }
299 
300         /* update running count */
301         rs_ctx->ops_done += ops;
302     }
303 
304     return( 0 );
305 }
306 
307 /* Call this when entering a function that needs its own sub-context */
308 #define ECP_RS_ENTER( SUB )   do {                                      \
309     /* reset ops count for this call if top-level */                    \
310     if( rs_ctx != NULL && rs_ctx->depth++ == 0 )                        \
311         rs_ctx->ops_done = 0;                                           \
312                                                                         \
313     /* set up our own sub-context if needed */                          \
314     if( mbedtls_ecp_restart_is_enabled() &&                             \
315         rs_ctx != NULL && rs_ctx->SUB == NULL )                         \
316     {                                                                   \
317         rs_ctx->SUB = mbedtls_calloc( 1, sizeof( *rs_ctx->SUB ) );      \
318         if( rs_ctx->SUB == NULL )                                       \
319             return( MBEDTLS_ERR_ECP_ALLOC_FAILED );                     \
320                                                                         \
321         ecp_restart_## SUB ##_init( rs_ctx->SUB );                      \
322     }                                                                   \
323 } while( 0 )
324 
325 /* Call this when leaving a function that needs its own sub-context */
326 #define ECP_RS_LEAVE( SUB )   do {                                      \
327     /* clear our sub-context when not in progress (done or error) */    \
328     if( rs_ctx != NULL && rs_ctx->SUB != NULL &&                        \
329         ret != MBEDTLS_ERR_ECP_IN_PROGRESS )                            \
330     {                                                                   \
331         ecp_restart_## SUB ##_free( rs_ctx->SUB );                      \
332         mbedtls_free( rs_ctx->SUB );                                    \
333         rs_ctx->SUB = NULL;                                             \
334     }                                                                   \
335                                                                         \
336     if( rs_ctx != NULL )                                                \
337         rs_ctx->depth--;                                                \
338 } while( 0 )
339 
340 #else /* MBEDTLS_ECP_RESTARTABLE */
341 
342 #define ECP_RS_ENTER( sub )     (void) rs_ctx;
343 #define ECP_RS_LEAVE( sub )     (void) rs_ctx;
344 
345 #endif /* MBEDTLS_ECP_RESTARTABLE */
346 
347 /*
348  * List of supported curves:
349  *  - internal ID
350  *  - TLS NamedCurve ID (RFC 4492 sec. 5.1.1, RFC 7071 sec. 2)
351  *  - size in bits
352  *  - readable name
353  *
354  * Curves are listed in order: largest curves first, and for a given size,
355  * fastest curves first. This provides the default order for the SSL module.
356  *
357  * Reminder: update profiles in x509_crt.c when adding a new curve!
358  */
359 static const mbedtls_ecp_curve_info ecp_supported_curves[] =
360 {
361 #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
362     { MBEDTLS_ECP_DP_SECP521R1,    25,     521,    "secp521r1"         },
363 #endif
364 #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
365     { MBEDTLS_ECP_DP_BP512R1,      28,     512,    "brainpoolP512r1"   },
366 #endif
367 #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
368     { MBEDTLS_ECP_DP_SECP384R1,    24,     384,    "secp384r1"         },
369 #endif
370 #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
371     { MBEDTLS_ECP_DP_BP384R1,      27,     384,    "brainpoolP384r1"   },
372 #endif
373 #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
374     { MBEDTLS_ECP_DP_SECP256R1,    23,     256,    "secp256r1"         },
375 #endif
376 #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
377     { MBEDTLS_ECP_DP_SECP256K1,    22,     256,    "secp256k1"         },
378 #endif
379 #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
380     { MBEDTLS_ECP_DP_BP256R1,      26,     256,    "brainpoolP256r1"   },
381 #endif
382 #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
383     { MBEDTLS_ECP_DP_SECP224R1,    21,     224,    "secp224r1"         },
384 #endif
385 #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
386     { MBEDTLS_ECP_DP_SECP224K1,    20,     224,    "secp224k1"         },
387 #endif
388 #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
389     { MBEDTLS_ECP_DP_SECP192R1,    19,     192,    "secp192r1"         },
390 #endif
391 #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
392     { MBEDTLS_ECP_DP_SECP192K1,    18,     192,    "secp192k1"         },
393 #endif
394 #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
395     { MBEDTLS_ECP_DP_CURVE25519,   29,     256,    "x25519"            },
396 #endif
397 #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
398     { MBEDTLS_ECP_DP_CURVE448,     30,     448,    "x448"              },
399 #endif
400     { MBEDTLS_ECP_DP_NONE,          0,     0,      NULL                },
401 };
402 
403 #define ECP_NB_CURVES   sizeof( ecp_supported_curves ) /    \
404                         sizeof( ecp_supported_curves[0] )
405 
406 static mbedtls_ecp_group_id ecp_supported_grp_id[ECP_NB_CURVES];
407 
408 /*
409  * List of supported curves and associated info
410  */
mbedtls_ecp_curve_list(void)411 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void )
412 {
413     return( ecp_supported_curves );
414 }
415 
416 /*
417  * List of supported curves, group ID only
418  */
mbedtls_ecp_grp_id_list(void)419 const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list( void )
420 {
421     static int init_done = 0;
422 
423     if( ! init_done )
424     {
425         size_t i = 0;
426         const mbedtls_ecp_curve_info *curve_info;
427 
428         for( curve_info = mbedtls_ecp_curve_list();
429              curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
430              curve_info++ )
431         {
432             ecp_supported_grp_id[i++] = curve_info->grp_id;
433         }
434         ecp_supported_grp_id[i] = MBEDTLS_ECP_DP_NONE;
435 
436         init_done = 1;
437     }
438 
439     return( ecp_supported_grp_id );
440 }
441 
442 /*
443  * Get the curve info for the internal identifier
444  */
mbedtls_ecp_curve_info_from_grp_id(mbedtls_ecp_group_id grp_id)445 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id( mbedtls_ecp_group_id grp_id )
446 {
447     const mbedtls_ecp_curve_info *curve_info;
448 
449     for( curve_info = mbedtls_ecp_curve_list();
450          curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
451          curve_info++ )
452     {
453         if( curve_info->grp_id == grp_id )
454             return( curve_info );
455     }
456 
457     return( NULL );
458 }
459 
460 /*
461  * Get the curve info from the TLS identifier
462  */
mbedtls_ecp_curve_info_from_tls_id(uint16_t tls_id)463 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id( uint16_t tls_id )
464 {
465     const mbedtls_ecp_curve_info *curve_info;
466 
467     for( curve_info = mbedtls_ecp_curve_list();
468          curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
469          curve_info++ )
470     {
471         if( curve_info->tls_id == tls_id )
472             return( curve_info );
473     }
474 
475     return( NULL );
476 }
477 
478 /*
479  * Get the curve info from the name
480  */
mbedtls_ecp_curve_info_from_name(const char * name)481 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name( const char *name )
482 {
483     const mbedtls_ecp_curve_info *curve_info;
484 
485     if( name == NULL )
486         return( NULL );
487 
488     for( curve_info = mbedtls_ecp_curve_list();
489          curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
490          curve_info++ )
491     {
492         if( strcmp( curve_info->name, name ) == 0 )
493             return( curve_info );
494     }
495 
496     return( NULL );
497 }
498 
499 /*
500  * Get the type of a curve
501  */
mbedtls_ecp_get_type(const mbedtls_ecp_group * grp)502 mbedtls_ecp_curve_type mbedtls_ecp_get_type( const mbedtls_ecp_group *grp )
503 {
504     if( grp->G.MBEDTLS_PRIVATE(X).MBEDTLS_PRIVATE(p) == NULL )
505         return( MBEDTLS_ECP_TYPE_NONE );
506 
507     if( grp->G.MBEDTLS_PRIVATE(Y).MBEDTLS_PRIVATE(p) == NULL )
508         return( MBEDTLS_ECP_TYPE_MONTGOMERY );
509     else
510         return( MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS );
511 }
512 
513 /*
514  * Initialize (the components of) a point
515  */
mbedtls_ecp_point_init(mbedtls_ecp_point * pt)516 void mbedtls_ecp_point_init( mbedtls_ecp_point *pt )
517 {
518     ECP_VALIDATE( pt != NULL );
519 
520     mbedtls_mpi_init( &pt->MBEDTLS_PRIVATE(X) );
521     mbedtls_mpi_init( &pt->MBEDTLS_PRIVATE(Y) );
522     mbedtls_mpi_init( &pt->MBEDTLS_PRIVATE(Z) );
523 }
524 
525 /*
526  * Initialize (the components of) a group
527  *
528  * STMicroelectronics edition
529  *
530  */
mbedtls_ecp_group_init(mbedtls_ecp_group * grp)531 void mbedtls_ecp_group_init( mbedtls_ecp_group *grp )
532 {
533     ECP_VALIDATE( grp != NULL );
534 
535     grp->id = MBEDTLS_ECP_DP_NONE;
536     mbedtls_mpi_init( &grp->P );
537     mbedtls_mpi_init( &grp->A );
538     mbedtls_mpi_init( &grp->B );
539     mbedtls_ecp_point_init( &grp->G );
540     mbedtls_mpi_init( &grp->N );
541     grp->pbits = 0;
542     grp->nbits = 0;
543     grp->h = 0;
544     grp->modp = NULL;
545     grp->t_pre = NULL;
546     grp->t_post = NULL;
547     grp->t_data = NULL;
548     grp->T = NULL;
549     grp->T_size = 0;
550 
551     grp->st_modulus_size = 0;
552     grp->st_order_size = 0;
553     grp->st_p = NULL;
554     grp->st_a_sign = 0;
555     grp->st_a_abs = NULL;
556     grp->st_b = NULL;
557     grp->st_gx = NULL;
558     grp->st_gy = NULL;
559     grp->st_n = NULL;
560 }
561 
562 /*
563  * Initialize (the components of) a key pair
564  */
mbedtls_ecp_keypair_init(mbedtls_ecp_keypair * key)565 void mbedtls_ecp_keypair_init( mbedtls_ecp_keypair *key )
566 {
567     ECP_VALIDATE( key != NULL );
568 
569     mbedtls_ecp_group_init( &key->MBEDTLS_PRIVATE(grp) );
570     mbedtls_mpi_init( &key->MBEDTLS_PRIVATE(d) );
571     mbedtls_ecp_point_init( &key->MBEDTLS_PRIVATE(Q) );
572 }
573 
574 /*
575  * Unallocate (the components of) a point
576  */
mbedtls_ecp_point_free(mbedtls_ecp_point * pt)577 void mbedtls_ecp_point_free( mbedtls_ecp_point *pt )
578 {
579     if( pt == NULL )
580         return;
581 
582     mbedtls_mpi_free( &( pt->MBEDTLS_PRIVATE(X) ) );
583     mbedtls_mpi_free( &( pt->MBEDTLS_PRIVATE(Y) ) );
584     mbedtls_mpi_free( &( pt->MBEDTLS_PRIVATE(Z) ) );
585 }
586 
587 /*
588  * Unallocate (the components of) a group
589  *
590  * STMicroelectronics edition
591  *
592  */
mbedtls_ecp_group_free(mbedtls_ecp_group * grp)593 void mbedtls_ecp_group_free( mbedtls_ecp_group *grp )
594 {
595     size_t i;
596 
597     if( grp == NULL )
598         return;
599 
600     if( grp->h != 1 )
601     {
602         mbedtls_mpi_free( &grp->P );
603         mbedtls_mpi_free( &grp->A );
604         mbedtls_mpi_free( &grp->B );
605         mbedtls_ecp_point_free( &grp->G );
606         mbedtls_mpi_free( &grp->N );
607     }
608 
609     if( grp->T != NULL )
610     {
611         for( i = 0; i < grp->T_size; i++ )
612             mbedtls_ecp_point_free( &grp->T[i] );
613         mbedtls_free( grp->T );
614     }
615 
616     if ( grp->st_p != NULL )
617     {
618         mbedtls_platform_zeroize( grp->st_p, grp->st_modulus_size );
619         mbedtls_free( grp->st_p );
620     }
621     if ( grp->st_a_abs != NULL )
622     {
623         mbedtls_platform_zeroize( grp->st_a_abs, grp->st_modulus_size );
624         mbedtls_free( grp->st_a_abs );
625     }
626     if ( grp->st_b != NULL )
627     {
628         mbedtls_platform_zeroize( grp->st_b, grp->st_modulus_size );
629         mbedtls_free( grp->st_b );
630     }
631     if ( grp->st_gx != NULL )
632     {
633         mbedtls_platform_zeroize( grp->st_gx, grp->st_modulus_size );
634         mbedtls_free( grp->st_gx );
635     }
636     if ( grp->st_gy != NULL )
637     {
638         mbedtls_platform_zeroize( grp->st_gy, grp->st_modulus_size );
639         mbedtls_free( grp->st_gy );
640     }
641     if ( grp->st_n != NULL )
642     {
643         mbedtls_platform_zeroize( grp->st_n, grp->st_order_size );
644         mbedtls_free( grp->st_n );
645     }
646 
647     mbedtls_platform_zeroize( grp, sizeof( mbedtls_ecp_group ) );
648 }
649 
650 /*
651  * Unallocate (the components of) a key pair
652  */
mbedtls_ecp_keypair_free(mbedtls_ecp_keypair * key)653 void mbedtls_ecp_keypair_free( mbedtls_ecp_keypair *key )
654 {
655     if( key == NULL )
656         return;
657 
658     mbedtls_ecp_group_free( &key->MBEDTLS_PRIVATE(grp) );
659     mbedtls_mpi_free( &key->MBEDTLS_PRIVATE(d) );
660     mbedtls_ecp_point_free( &key->MBEDTLS_PRIVATE(Q) );
661 }
662 
663 /*
664  * Copy the contents of a point
665  */
mbedtls_ecp_copy(mbedtls_ecp_point * P,const mbedtls_ecp_point * Q)666 int mbedtls_ecp_copy( mbedtls_ecp_point *P, const mbedtls_ecp_point *Q )
667 {
668     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
669     ECP_VALIDATE_RET( P != NULL );
670     ECP_VALIDATE_RET( Q != NULL );
671 
672     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->MBEDTLS_PRIVATE(X), &Q->MBEDTLS_PRIVATE(X) ) );
673     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->MBEDTLS_PRIVATE(Y), &Q->MBEDTLS_PRIVATE(Y) ) );
674     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->MBEDTLS_PRIVATE(Z), &Q->MBEDTLS_PRIVATE(Z) ) );
675 
676 cleanup:
677     return( ret );
678 }
679 
680 /*
681  * Copy the contents of a group object
682  */
mbedtls_ecp_group_copy(mbedtls_ecp_group * dst,const mbedtls_ecp_group * src)683 int mbedtls_ecp_group_copy( mbedtls_ecp_group *dst, const mbedtls_ecp_group *src )
684 {
685     ECP_VALIDATE_RET( dst != NULL );
686     ECP_VALIDATE_RET( src != NULL );
687 
688     return( mbedtls_ecp_group_load( dst, src->id ) );
689 }
690 
691 /*
692  * Set point to zero
693  */
mbedtls_ecp_set_zero(mbedtls_ecp_point * pt)694 int mbedtls_ecp_set_zero( mbedtls_ecp_point *pt )
695 {
696     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
697     ECP_VALIDATE_RET( pt != NULL );
698 
699     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->MBEDTLS_PRIVATE(X) , 1 ) );
700     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->MBEDTLS_PRIVATE(Y) , 1 ) );
701     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->MBEDTLS_PRIVATE(Z) , 0 ) );
702 
703 cleanup:
704     return( ret );
705 }
706 
707 /*
708  * Tell if a point is zero
709  */
mbedtls_ecp_is_zero(mbedtls_ecp_point * pt)710 int mbedtls_ecp_is_zero( mbedtls_ecp_point *pt )
711 {
712     ECP_VALIDATE_RET( pt != NULL );
713 
714     return( mbedtls_mpi_cmp_int( &pt->MBEDTLS_PRIVATE(Z), 0 ) == 0 );
715 }
716 
717 /*
718  * Compare two points lazily
719  */
mbedtls_ecp_point_cmp(const mbedtls_ecp_point * P,const mbedtls_ecp_point * Q)720 int mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P,
721                            const mbedtls_ecp_point *Q )
722 {
723     ECP_VALIDATE_RET( P != NULL );
724     ECP_VALIDATE_RET( Q != NULL );
725 
726     if( mbedtls_mpi_cmp_mpi( &P->MBEDTLS_PRIVATE(X), &Q->MBEDTLS_PRIVATE(X) ) == 0 &&
727         mbedtls_mpi_cmp_mpi( &P->MBEDTLS_PRIVATE(Y), &Q->MBEDTLS_PRIVATE(Y) ) == 0 &&
728         mbedtls_mpi_cmp_mpi( &P->MBEDTLS_PRIVATE(Z), &Q->MBEDTLS_PRIVATE(Z) ) == 0 )
729     {
730         return( 0 );
731     }
732 
733     return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
734 }
735 
736 /*
737  * Import a non-zero point from ASCII strings
738  */
mbedtls_ecp_point_read_string(mbedtls_ecp_point * P,int radix,const char * x,const char * y)739 int mbedtls_ecp_point_read_string( mbedtls_ecp_point *P, int radix,
740                            const char *x, const char *y )
741 {
742     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
743     ECP_VALIDATE_RET( P != NULL );
744     ECP_VALIDATE_RET( x != NULL );
745     ECP_VALIDATE_RET( y != NULL );
746 
747     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &P->MBEDTLS_PRIVATE(X), radix, x ) );
748     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &P->MBEDTLS_PRIVATE(Y), radix, y ) );
749     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &P->MBEDTLS_PRIVATE(Z), 1 ) );
750 
751 cleanup:
752     return( ret );
753 }
754 
755 /*
756  * Export a point into unsigned binary data (SEC1 2.3.3 and RFC7748)
757  */
mbedtls_ecp_point_write_binary(const mbedtls_ecp_group * grp,const mbedtls_ecp_point * P,int format,size_t * olen,unsigned char * buf,size_t buflen)758 int mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp,
759                                     const mbedtls_ecp_point *P,
760                                     int format, size_t *olen,
761                                     unsigned char *buf, size_t buflen )
762 {
763     int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
764     size_t plen;
765     ECP_VALIDATE_RET( grp  != NULL );
766     ECP_VALIDATE_RET( P    != NULL );
767     ECP_VALIDATE_RET( olen != NULL );
768     ECP_VALIDATE_RET( buf  != NULL );
769     ECP_VALIDATE_RET( format == MBEDTLS_ECP_PF_UNCOMPRESSED ||
770                       format == MBEDTLS_ECP_PF_COMPRESSED );
771 
772     plen = mbedtls_mpi_size( &grp->P );
773 
774 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
775     (void) format; /* Montgomery curves always use the same point format */
776     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
777     {
778         *olen = plen;
779         if( buflen < *olen )
780             return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
781 
782         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary_le( &P->MBEDTLS_PRIVATE(X), buf, plen ) );
783     }
784 #endif
785 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
786     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
787     {
788         /*
789          * Common case: P == 0
790          */
791         if( mbedtls_mpi_cmp_int( &P->MBEDTLS_PRIVATE(Z), 0 ) == 0 )
792         {
793             if( buflen < 1 )
794                 return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
795 
796             buf[0] = 0x00;
797             *olen = 1;
798 
799             return( 0 );
800         }
801 
802         if( format == MBEDTLS_ECP_PF_UNCOMPRESSED )
803         {
804             *olen = 2 * plen + 1;
805 
806             if( buflen < *olen )
807                 return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
808 
809             buf[0] = 0x04;
810             MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->MBEDTLS_PRIVATE(X), buf + 1, plen ) );
811             MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->MBEDTLS_PRIVATE(Y), buf + 1 + plen, plen ) );
812         }
813         else if( format == MBEDTLS_ECP_PF_COMPRESSED )
814         {
815             *olen = plen + 1;
816 
817             if( buflen < *olen )
818                 return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
819 
820             buf[0] = 0x02 + mbedtls_mpi_get_bit( &P->MBEDTLS_PRIVATE(Y), 0 );
821             MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->MBEDTLS_PRIVATE(X), buf + 1, plen ) );
822         }
823     }
824 #endif
825 
826 cleanup:
827     return( ret );
828 }
829 
830 /*
831  * Import a point from unsigned binary data (SEC1 2.3.4 and RFC7748)
832  */
mbedtls_ecp_point_read_binary(const mbedtls_ecp_group * grp,mbedtls_ecp_point * pt,const unsigned char * buf,size_t ilen)833 int mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp,
834                                    mbedtls_ecp_point *pt,
835                                    const unsigned char *buf, size_t ilen )
836 {
837     int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
838     size_t plen;
839     ECP_VALIDATE_RET( grp != NULL );
840     ECP_VALIDATE_RET( pt  != NULL );
841     ECP_VALIDATE_RET( buf != NULL );
842 
843     if( ilen < 1 )
844         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
845 
846     plen = mbedtls_mpi_size( &grp->P );
847 
848 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
849     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
850     {
851         if( plen != ilen )
852             return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
853 
854         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary_le( &pt->MBEDTLS_PRIVATE(X), buf, plen ) );
855         mbedtls_mpi_free( &pt->MBEDTLS_PRIVATE(Y) );
856 
857         if( grp->id == MBEDTLS_ECP_DP_CURVE25519 )
858             /* Set most significant bit to 0 as prescribed in RFC7748 §5 */
859             MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &pt->MBEDTLS_PRIVATE(X), plen * 8 - 1, 0 ) );
860 
861         MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->MBEDTLS_PRIVATE(Z), 1 ) );
862     }
863 #endif
864 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
865     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
866     {
867         if( buf[0] == 0x00 )
868         {
869             if( ilen == 1 )
870                 return( mbedtls_ecp_set_zero( pt ) );
871             else
872                 return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
873         }
874 
875         if( buf[0] != 0x04 )
876             return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
877 
878         if( ilen != 2 * plen + 1 )
879             return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
880 
881         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &pt->MBEDTLS_PRIVATE(X), buf + 1, plen ) );
882         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &pt->MBEDTLS_PRIVATE(Y),
883                                                   buf + 1 + plen, plen ) );
884         MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->MBEDTLS_PRIVATE(Z), 1 ) );
885     }
886 #endif
887 
888 cleanup:
889     return( ret );
890 }
891 
892 /*
893  * Import a point from a TLS ECPoint record (RFC 4492)
894  *      struct {
895  *          opaque point <1..2^8-1>;
896  *      } ECPoint;
897  */
mbedtls_ecp_tls_read_point(const mbedtls_ecp_group * grp,mbedtls_ecp_point * pt,const unsigned char ** buf,size_t buf_len)898 int mbedtls_ecp_tls_read_point( const mbedtls_ecp_group *grp,
899                                 mbedtls_ecp_point *pt,
900                                 const unsigned char **buf, size_t buf_len )
901 {
902     unsigned char data_len;
903     const unsigned char *buf_start;
904     ECP_VALIDATE_RET( grp != NULL );
905     ECP_VALIDATE_RET( pt  != NULL );
906     ECP_VALIDATE_RET( buf != NULL );
907     ECP_VALIDATE_RET( *buf != NULL );
908 
909     /*
910      * We must have at least two bytes (1 for length, at least one for data)
911      */
912     if( buf_len < 2 )
913         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
914 
915     data_len = *(*buf)++;
916     if( data_len < 1 || data_len > buf_len - 1 )
917         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
918 
919     /*
920      * Save buffer start for read_binary and update buf
921      */
922     buf_start = *buf;
923     *buf += data_len;
924 
925     return( mbedtls_ecp_point_read_binary( grp, pt, buf_start, data_len ) );
926 }
927 
928 /*
929  * Export a point as a TLS ECPoint record (RFC 4492)
930  *      struct {
931  *          opaque point <1..2^8-1>;
932  *      } ECPoint;
933  */
mbedtls_ecp_tls_write_point(const mbedtls_ecp_group * grp,const mbedtls_ecp_point * pt,int format,size_t * olen,unsigned char * buf,size_t blen)934 int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt,
935                          int format, size_t *olen,
936                          unsigned char *buf, size_t blen )
937 {
938     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
939     ECP_VALIDATE_RET( grp  != NULL );
940     ECP_VALIDATE_RET( pt   != NULL );
941     ECP_VALIDATE_RET( olen != NULL );
942     ECP_VALIDATE_RET( buf  != NULL );
943     ECP_VALIDATE_RET( format == MBEDTLS_ECP_PF_UNCOMPRESSED ||
944                       format == MBEDTLS_ECP_PF_COMPRESSED );
945 
946     /*
947      * buffer length must be at least one, for our length byte
948      */
949     if( blen < 1 )
950         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
951 
952     if( ( ret = mbedtls_ecp_point_write_binary( grp, pt, format,
953                     olen, buf + 1, blen - 1) ) != 0 )
954         return( ret );
955 
956     /*
957      * write length to the first byte and update total length
958      */
959     buf[0] = (unsigned char) *olen;
960     ++*olen;
961 
962     return( 0 );
963 }
964 
965 /*
966  * Set a group from an ECParameters record (RFC 4492)
967  */
mbedtls_ecp_tls_read_group(mbedtls_ecp_group * grp,const unsigned char ** buf,size_t len)968 int mbedtls_ecp_tls_read_group( mbedtls_ecp_group *grp,
969                                 const unsigned char **buf, size_t len )
970 {
971     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
972     mbedtls_ecp_group_id grp_id;
973     ECP_VALIDATE_RET( grp  != NULL );
974     ECP_VALIDATE_RET( buf  != NULL );
975     ECP_VALIDATE_RET( *buf != NULL );
976 
977     if( ( ret = mbedtls_ecp_tls_read_group_id( &grp_id, buf, len ) ) != 0 )
978         return( ret );
979 
980     return( mbedtls_ecp_group_load( grp, grp_id ) );
981 }
982 
983 /*
984  * Read a group id from an ECParameters record (RFC 4492) and convert it to
985  * mbedtls_ecp_group_id.
986  */
mbedtls_ecp_tls_read_group_id(mbedtls_ecp_group_id * grp,const unsigned char ** buf,size_t len)987 int mbedtls_ecp_tls_read_group_id( mbedtls_ecp_group_id *grp,
988                                    const unsigned char **buf, size_t len )
989 {
990     uint16_t tls_id;
991     const mbedtls_ecp_curve_info *curve_info;
992     ECP_VALIDATE_RET( grp  != NULL );
993     ECP_VALIDATE_RET( buf  != NULL );
994     ECP_VALIDATE_RET( *buf != NULL );
995 
996     /*
997      * We expect at least three bytes (see below)
998      */
999     if( len < 3 )
1000         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1001 
1002     /*
1003      * First byte is curve_type; only named_curve is handled
1004      */
1005     if( *(*buf)++ != MBEDTLS_ECP_TLS_NAMED_CURVE )
1006         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1007 
1008     /*
1009      * Next two bytes are the namedcurve value
1010      */
1011     tls_id = *(*buf)++;
1012     tls_id <<= 8;
1013     tls_id |= *(*buf)++;
1014 
1015     if( ( curve_info = mbedtls_ecp_curve_info_from_tls_id( tls_id ) ) == NULL )
1016         return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
1017 
1018     *grp = curve_info->grp_id;
1019 
1020     return( 0 );
1021 }
1022 
1023 /*
1024  * Write the ECParameters record corresponding to a group (RFC 4492)
1025  */
mbedtls_ecp_tls_write_group(const mbedtls_ecp_group * grp,size_t * olen,unsigned char * buf,size_t blen)1026 int mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, size_t *olen,
1027                          unsigned char *buf, size_t blen )
1028 {
1029     const mbedtls_ecp_curve_info *curve_info;
1030     ECP_VALIDATE_RET( grp  != NULL );
1031     ECP_VALIDATE_RET( buf  != NULL );
1032     ECP_VALIDATE_RET( olen != NULL );
1033 
1034     if( ( curve_info = mbedtls_ecp_curve_info_from_grp_id( grp->id ) ) == NULL )
1035         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1036 
1037     /*
1038      * We are going to write 3 bytes (see below)
1039      */
1040     *olen = 3;
1041     if( blen < *olen )
1042         return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
1043 
1044     /*
1045      * First byte is curve_type, always named_curve
1046      */
1047     *buf++ = MBEDTLS_ECP_TLS_NAMED_CURVE;
1048 
1049     /*
1050      * Next two bytes are the namedcurve value
1051      */
1052     buf[0] = curve_info->tls_id >> 8;
1053     buf[1] = curve_info->tls_id & 0xFF;
1054 
1055     return( 0 );
1056 }
1057 
1058 /*
1059  * Wrapper around fast quasi-modp functions, with fall-back to mbedtls_mpi_mod_mpi.
1060  * See the documentation of struct mbedtls_ecp_group.
1061  *
1062  * This function is in the critial loop for mbedtls_ecp_mul, so pay attention to perf.
1063  */
ecp_modp(mbedtls_mpi * N,const mbedtls_ecp_group * grp)1064 static int ecp_modp( mbedtls_mpi *N, const mbedtls_ecp_group *grp )
1065 {
1066     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1067 
1068     if( grp->modp == NULL )
1069         return( mbedtls_mpi_mod_mpi( N, N, &grp->P ) );
1070 
1071     /* N->MBEDTLS_PRIVATE(s) < 0 is a much faster test, which fails only if N is 0 */
1072     if( ( N->MBEDTLS_PRIVATE(s) < 0 && mbedtls_mpi_cmp_int( N, 0 ) != 0 ) ||
1073         mbedtls_mpi_bitlen( N ) > 2 * grp->pbits )
1074     {
1075         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1076     }
1077 
1078     MBEDTLS_MPI_CHK( grp->modp( N ) );
1079 
1080     /* N->MBEDTLS_PRIVATE(s) < 0 is a much faster test, which fails only if N is 0 */
1081     while( N->MBEDTLS_PRIVATE(s) < 0 && mbedtls_mpi_cmp_int( N, 0 ) != 0 )
1082         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &grp->P ) );
1083 
1084     while( mbedtls_mpi_cmp_mpi( N, &grp->P ) >= 0 )
1085         /* we known P, N and the result are positive */
1086         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( N, N, &grp->P ) );
1087 
1088 cleanup:
1089     return( ret );
1090 }
1091 
1092 /*
1093  * Fast mod-p functions expect their argument to be in the 0..p^2 range.
1094  *
1095  * In order to guarantee that, we need to ensure that operands of
1096  * mbedtls_mpi_mul_mpi are in the 0..p range. So, after each operation we will
1097  * bring the result back to this range.
1098  *
1099  * The following macros are shortcuts for doing that.
1100  */
1101 
1102 /*
1103  * Reduce a mbedtls_mpi mod p in-place, general case, to use after mbedtls_mpi_mul_mpi
1104  */
1105 #if defined(MBEDTLS_SELF_TEST)
1106 #define INC_MUL_COUNT   mul_count++;
1107 #else
1108 #define INC_MUL_COUNT
1109 #endif
1110 
1111 #define MOD_MUL( N )                                                    \
1112     do                                                                  \
1113     {                                                                   \
1114         MBEDTLS_MPI_CHK( ecp_modp( &(N), grp ) );                       \
1115         INC_MUL_COUNT                                                   \
1116     } while( 0 )
1117 
mbedtls_mpi_mul_mod(const mbedtls_ecp_group * grp,mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1118 static inline int mbedtls_mpi_mul_mod( const mbedtls_ecp_group *grp,
1119                                        mbedtls_mpi *X,
1120                                        const mbedtls_mpi *A,
1121                                        const mbedtls_mpi *B )
1122 {
1123     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1124     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( X, A, B ) );
1125     MOD_MUL( *X );
1126 cleanup:
1127     return( ret );
1128 }
1129 
1130 /*
1131  * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_sub_mpi
1132  * N->MBEDTLS_PRIVATE(s) < 0 is a very fast test, which fails only if N is 0
1133  */
1134 #define MOD_SUB( N )                                                    \
1135     while( (N).MBEDTLS_PRIVATE(s) < 0 && mbedtls_mpi_cmp_int( &(N), 0 ) != 0 )           \
1136         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &(N), &(N), &grp->P ) )
1137 
mbedtls_mpi_sub_mod(const mbedtls_ecp_group * grp,mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1138 static inline int mbedtls_mpi_sub_mod( const mbedtls_ecp_group *grp,
1139                                        mbedtls_mpi *X,
1140                                        const mbedtls_mpi *A,
1141                                        const mbedtls_mpi *B )
1142 {
1143     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1144     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( X, A, B ) );
1145     MOD_SUB( *X );
1146 cleanup:
1147     return( ret );
1148 }
1149 
1150 /*
1151  * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_add_mpi and mbedtls_mpi_mul_int.
1152  * We known P, N and the result are positive, so sub_abs is correct, and
1153  * a bit faster.
1154  */
1155 #define MOD_ADD( N )                                                    \
1156     while( mbedtls_mpi_cmp_mpi( &(N), &grp->P ) >= 0 )                  \
1157         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &(N), &(N), &grp->P ) )
1158 
mbedtls_mpi_add_mod(const mbedtls_ecp_group * grp,mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1159 static inline int mbedtls_mpi_add_mod( const mbedtls_ecp_group *grp,
1160                                        mbedtls_mpi *X,
1161                                        const mbedtls_mpi *A,
1162                                        const mbedtls_mpi *B )
1163 {
1164     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1165     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( X, A, B ) );
1166     MOD_ADD( *X );
1167 cleanup:
1168     return( ret );
1169 }
1170 
mbedtls_mpi_shift_l_mod(const mbedtls_ecp_group * grp,mbedtls_mpi * X,size_t count)1171 static inline int mbedtls_mpi_shift_l_mod( const mbedtls_ecp_group *grp,
1172                                            mbedtls_mpi *X,
1173                                            size_t count )
1174 {
1175     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1176     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( X, count ) );
1177     MOD_ADD( *X );
1178 cleanup:
1179     return( ret );
1180 }
1181 
1182 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
1183 /*
1184  * For curves in short Weierstrass form, we do all the internal operations in
1185  * Jacobian coordinates.
1186  *
1187  * For multiplication, we'll use a comb method with coutermeasueres against
1188  * SPA, hence timing attacks.
1189  */
1190 
1191 /*
1192  * Normalize jacobian coordinates so that Z == 0 || Z == 1  (GECC 3.2.1)
1193  * Cost: 1N := 1I + 3M + 1S
1194  */
ecp_normalize_jac(const mbedtls_ecp_group * grp,mbedtls_ecp_point * pt)1195 static int ecp_normalize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt )
1196 {
1197     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1198     mbedtls_mpi Zi, ZZi;
1199 
1200     if( mbedtls_mpi_cmp_int( &pt->MBEDTLS_PRIVATE(Z), 0 ) == 0 )
1201         return( 0 );
1202 
1203 #if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
1204     if( mbedtls_internal_ecp_grp_capable( grp ) )
1205         return( mbedtls_internal_ecp_normalize_jac( grp, pt ) );
1206 #endif /* MBEDTLS_ECP_NORMALIZE_JAC_ALT */
1207 
1208     mbedtls_mpi_init( &Zi ); mbedtls_mpi_init( &ZZi );
1209 
1210     /*
1211      * X = X / Z^2  mod p
1212      */
1213     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &Zi,      &pt->MBEDTLS_PRIVATE(Z),     &grp->P ) );
1214     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &ZZi,     &Zi,        &Zi     ) );
1215     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->MBEDTLS_PRIVATE(X),   &pt->MBEDTLS_PRIVATE(X),     &ZZi    ) );
1216 
1217     /*
1218      * Y = Y / Z^3  mod p
1219      */
1220     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->MBEDTLS_PRIVATE(Y),   &pt->MBEDTLS_PRIVATE(Y),     &ZZi    ) );
1221     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->MBEDTLS_PRIVATE(Y),   &pt->MBEDTLS_PRIVATE(Y),     &Zi     ) );
1222 
1223     /*
1224      * Z = 1
1225      */
1226     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->MBEDTLS_PRIVATE(Z), 1 ) );
1227 
1228 cleanup:
1229 
1230     mbedtls_mpi_free( &Zi ); mbedtls_mpi_free( &ZZi );
1231 
1232     return( ret );
1233 }
1234 
1235 /*
1236  * Point doubling R = 2 P, Jacobian coordinates
1237  *
1238  * Based on http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-1998-cmo-2 .
1239  *
1240  * We follow the variable naming fairly closely. The formula variations that trade a MUL for a SQR
1241  * (plus a few ADDs) aren't useful as our bignum implementation doesn't distinguish squaring.
1242  *
1243  * Standard optimizations are applied when curve parameter A is one of { 0, -3 }.
1244  *
1245  * Cost: 1D := 3M + 4S          (A ==  0)
1246  *             4M + 4S          (A == -3)
1247  *             3M + 6S + 1a     otherwise
1248  */
ecp_double_jac(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_ecp_point * P)1249 static int ecp_double_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1250                            const mbedtls_ecp_point *P )
1251 {
1252     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1253     mbedtls_mpi M, S, T, U;
1254 
1255 #if defined(MBEDTLS_SELF_TEST)
1256     dbl_count++;
1257 #endif
1258 
1259 #if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
1260     if( mbedtls_internal_ecp_grp_capable( grp ) )
1261         return( mbedtls_internal_ecp_double_jac( grp, R, P ) );
1262 #endif /* MBEDTLS_ECP_DOUBLE_JAC_ALT */
1263 
1264     mbedtls_mpi_init( &M ); mbedtls_mpi_init( &S ); mbedtls_mpi_init( &T ); mbedtls_mpi_init( &U );
1265 
1266     /* Special case for A = -3 */
1267     if( grp->A.MBEDTLS_PRIVATE(p) == NULL )
1268     {
1269         /* M = 3(X + Z^2)(X - Z^2) */
1270         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S,  &P->MBEDTLS_PRIVATE(Z),  &P->MBEDTLS_PRIVATE(Z)   ) );
1271         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &T,  &P->MBEDTLS_PRIVATE(X),  &S      ) );
1272         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &U,  &P->MBEDTLS_PRIVATE(X),  &S      ) );
1273         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S,  &T,     &U      ) );
1274         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M,  &S,     3       ) ); MOD_ADD( M );
1275     }
1276     else
1277     {
1278         /* M = 3.X^2 */
1279         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S,  &P->MBEDTLS_PRIVATE(X),  &P->MBEDTLS_PRIVATE(X)   ) );
1280         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M,  &S,     3       ) ); MOD_ADD( M );
1281 
1282         /* Optimize away for "koblitz" curves with A = 0 */
1283         if( mbedtls_mpi_cmp_int( &grp->A, 0 ) != 0 )
1284         {
1285             /* M += A.Z^4 */
1286             MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S,  &P->MBEDTLS_PRIVATE(Z),  &P->MBEDTLS_PRIVATE(Z)   ) );
1287             MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T,  &S,     &S      ) );
1288             MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S,  &T,     &grp->A ) );
1289             MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &M,  &M,     &S      ) );
1290         }
1291     }
1292 
1293     /* S = 4.X.Y^2 */
1294     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T,  &P->MBEDTLS_PRIVATE(Y),  &P->MBEDTLS_PRIVATE(Y)   ) );
1295     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &T,  1               ) );
1296     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S,  &P->MBEDTLS_PRIVATE(X),  &T      ) );
1297     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &S,  1               ) );
1298 
1299     /* U = 8.Y^4 */
1300     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &U,  &T,     &T      ) );
1301     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &U,  1               ) );
1302 
1303     /* T = M^2 - 2.S */
1304     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T,  &M,     &M      ) );
1305     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T,  &T,     &S      ) );
1306     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T,  &T,     &S      ) );
1307 
1308     /* S = M(S - T) - U */
1309     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &S,  &S,     &T      ) );
1310     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S,  &S,     &M      ) );
1311     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &S,  &S,     &U      ) );
1312 
1313     /* U = 2.Y.Z */
1314     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &U,  &P->MBEDTLS_PRIVATE(Y),  &P->MBEDTLS_PRIVATE(Z)   ) );
1315     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &U,  1               ) );
1316 
1317     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->MBEDTLS_PRIVATE(X), &T ) );
1318     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->MBEDTLS_PRIVATE(Y), &S ) );
1319     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->MBEDTLS_PRIVATE(Z), &U ) );
1320 
1321 cleanup:
1322     mbedtls_mpi_free( &M ); mbedtls_mpi_free( &S ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &U );
1323 
1324     return( ret );
1325 }
1326 
1327 /*
1328  * Addition: R = P + Q, mixed affine-Jacobian coordinates (GECC 3.22)
1329  *
1330  * The coordinates of Q must be normalized (= affine),
1331  * but those of P don't need to. R is not normalized.
1332  *
1333  * Special cases: (1) P or Q is zero, (2) R is zero, (3) P == Q.
1334  * None of these cases can happen as intermediate step in ecp_mul_comb():
1335  * - at each step, P, Q and R are multiples of the base point, the factor
1336  *   being less than its order, so none of them is zero;
1337  * - Q is an odd multiple of the base point, P an even multiple,
1338  *   due to the choice of precomputed points in the modified comb method.
1339  * So branches for these cases do not leak secret information.
1340  *
1341  * We accept Q->MBEDTLS_PRIVATE(Z) being unset (saving memory in tables) as meaning 1.
1342  *
1343  * Cost: 1A := 8M + 3S
1344  */
ecp_add_mixed(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_ecp_point * P,const mbedtls_ecp_point * Q)1345 static int ecp_add_mixed( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1346                           const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q )
1347 {
1348     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1349     mbedtls_mpi T1, T2, T3, T4, X, Y, Z;
1350 
1351 #if defined(MBEDTLS_SELF_TEST)
1352     add_count++;
1353 #endif
1354 
1355 #if defined(MBEDTLS_ECP_ADD_MIXED_ALT)
1356     if( mbedtls_internal_ecp_grp_capable( grp ) )
1357         return( mbedtls_internal_ecp_add_mixed( grp, R, P, Q ) );
1358 #endif /* MBEDTLS_ECP_ADD_MIXED_ALT */
1359 
1360     /*
1361      * Trivial cases: P == 0 or Q == 0 (case 1)
1362      */
1363     if( mbedtls_mpi_cmp_int( &P->MBEDTLS_PRIVATE(Z), 0 ) == 0 )
1364         return( mbedtls_ecp_copy( R, Q ) );
1365 
1366     if( Q->MBEDTLS_PRIVATE(Z).MBEDTLS_PRIVATE(p) != NULL && mbedtls_mpi_cmp_int( &Q->MBEDTLS_PRIVATE(Z), 0 ) == 0 )
1367         return( mbedtls_ecp_copy( R, P ) );
1368 
1369     /*
1370      * Make sure Q coordinates are normalized
1371      */
1372     if( Q->MBEDTLS_PRIVATE(Z).MBEDTLS_PRIVATE(p) != NULL && mbedtls_mpi_cmp_int( &Q->MBEDTLS_PRIVATE(Z), 1 ) != 0 )
1373         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1374 
1375     mbedtls_mpi_init( &T1 ); mbedtls_mpi_init( &T2 ); mbedtls_mpi_init( &T3 ); mbedtls_mpi_init( &T4 );
1376     mbedtls_mpi_init( &X ); mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &Z );
1377 
1378     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T1,  &P->MBEDTLS_PRIVATE(Z),  &P->MBEDTLS_PRIVATE(Z) ) );
1379     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T2,  &T1,    &P->MBEDTLS_PRIVATE(Z) ) );
1380     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T1,  &T1,    &Q->MBEDTLS_PRIVATE(X) ) );
1381     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T2,  &T2,    &Q->MBEDTLS_PRIVATE(Y) ) );
1382     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T1,  &T1,    &P->MBEDTLS_PRIVATE(X) ) );
1383     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T2,  &T2,    &P->MBEDTLS_PRIVATE(Y) ) );
1384 
1385     /* Special cases (2) and (3) */
1386     if( mbedtls_mpi_cmp_int( &T1, 0 ) == 0 )
1387     {
1388         if( mbedtls_mpi_cmp_int( &T2, 0 ) == 0 )
1389         {
1390             ret = ecp_double_jac( grp, R, P );
1391             goto cleanup;
1392         }
1393         else
1394         {
1395             ret = mbedtls_ecp_set_zero( R );
1396             goto cleanup;
1397         }
1398     }
1399 
1400     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &Z,   &P->MBEDTLS_PRIVATE(Z),  &T1   ) );
1401     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T3,  &T1,    &T1   ) );
1402     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T4,  &T3,    &T1   ) );
1403     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T3,  &T3,    &P->MBEDTLS_PRIVATE(X) ) );
1404     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &T1, &T3 ) );
1405     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &T1,  1     ) );
1406     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &X,   &T2,    &T2   ) );
1407     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &X,   &X,     &T1   ) );
1408     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &X,   &X,     &T4   ) );
1409     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T3,  &T3,    &X    ) );
1410     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T3,  &T3,    &T2   ) );
1411     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T4,  &T4,    &P->MBEDTLS_PRIVATE(Y) ) );
1412     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &Y,   &T3,    &T4   ) );
1413 
1414     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->MBEDTLS_PRIVATE(X), &X ) );
1415     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->MBEDTLS_PRIVATE(Y), &Y ) );
1416     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->MBEDTLS_PRIVATE(Z), &Z ) );
1417 
1418 cleanup:
1419 
1420     mbedtls_mpi_free( &T1 ); mbedtls_mpi_free( &T2 ); mbedtls_mpi_free( &T3 ); mbedtls_mpi_free( &T4 );
1421     mbedtls_mpi_free( &X ); mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &Z );
1422 
1423     return( ret );
1424 }
1425 
1426 /*
1427  * Check and define parameters used by the comb method (see below for details)
1428  */
1429 #if MBEDTLS_ECP_WINDOW_SIZE < 2 || MBEDTLS_ECP_WINDOW_SIZE > 7
1430 #error "MBEDTLS_ECP_WINDOW_SIZE out of bounds"
1431 #endif
1432 
1433 /*
1434  * Multiplication using the comb method - for curves in short Weierstrass form
1435  *
1436  * This function is mainly responsible for administrative work:
1437  * - managing the restart context if enabled
1438  * - managing the table of precomputed points (passed between the below two
1439  *   functions): allocation, computation, ownership transfer, freeing.
1440  *
1441  * It delegates the actual arithmetic work to:
1442  *      ecp_precompute_comb() and ecp_mul_comb_with_precomp()
1443  *
1444  * See comments on ecp_comb_recode_core() regarding the computation strategy.
1445  *
1446  * STMicroelectronics edition
1447  *
1448  */
ecp_mul_comb(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,mbedtls_ecp_restart_ctx * rs_ctx)1449 static int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1450                          const mbedtls_mpi *m, const mbedtls_ecp_point *P,
1451                          int (*f_rng)(void *, unsigned char *, size_t),
1452                          void *p_rng,
1453                          mbedtls_ecp_restart_ctx *rs_ctx )
1454 {
1455     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1456     size_t olen;
1457     size_t scalarMulSize;
1458     uint8_t *P_binary;
1459     uint8_t *m_binary = NULL;
1460     uint8_t *R_binary = NULL;
1461     PKA_HandleTypeDef hpka = {0};
1462     PKA_ECCMulInTypeDef ECC_MulIn = {0};
1463     PKA_ECCMulOutTypeDef ECC_MulOut;
1464 
1465     /* Set HW peripheral input parameter: scalar m size */
1466     scalarMulSize = mbedtls_mpi_size(m);
1467     ECC_MulIn.scalarMulSize = scalarMulSize;
1468 
1469     /* Set HW peripheral Input parameter: curve coefs */
1470     ECC_MulIn.modulusSize = grp->st_modulus_size;
1471     ECC_MulIn.coefSign    = grp->st_a_sign;
1472     ECC_MulIn.coefA       = grp->st_a_abs;
1473     ECC_MulIn.modulus     = grp->st_p;
1474 #if defined(GENERATOR_HW_PKA_EXTENDED_API)
1475     ECC_MulIn.coefB       = grp->st_b;
1476     ECC_MulIn.primeOrder  = grp->st_n;
1477 #endif
1478 
1479     /* Set HW peripheral input parameter: coordinates of P point */
1480     P_binary = mbedtls_calloc(2U * grp->st_modulus_size + 1U, sizeof( uint8_t ));
1481     MBEDTLS_MPI_CHK((P_binary == NULL) ? MBEDTLS_ERR_ECP_ALLOC_FAILED : 0);
1482 
1483     MBEDTLS_MPI_CHK( mbedtls_ecp_point_write_binary( grp, P, MBEDTLS_ECP_PF_UNCOMPRESSED, &olen, P_binary, 2U * grp->st_modulus_size + 1U) );
1484 
1485     ECC_MulIn.pointX = P_binary + 1U;
1486     ECC_MulIn.pointY = P_binary + grp->st_modulus_size + 1U;
1487 
1488     /* Set HW peripheral input parameter: scalar m */
1489     m_binary = mbedtls_calloc(scalarMulSize, sizeof( uint8_t ));
1490     MBEDTLS_MPI_CHK((m_binary == NULL) ? MBEDTLS_ERR_ECP_ALLOC_FAILED : 0);
1491 
1492     MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( m, m_binary, scalarMulSize ) );
1493     ECC_MulIn.scalarMul = m_binary;
1494 
1495     /* Enable HW peripheral clock */
1496     __HAL_RCC_PKA_CLK_ENABLE();
1497 
1498     /* Initialize HW peripheral */
1499     hpka.Instance = PKA;
1500     MBEDTLS_MPI_CHK((HAL_PKA_Init(&hpka) != HAL_OK) ? MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED : 0);
1501 
1502     /* Reset PKA RAM */
1503     HAL_PKA_RAMReset(&hpka);
1504 
1505     /* Launch the scalar multiplication */
1506     MBEDTLS_MPI_CHK((HAL_PKA_ECCMul(&hpka, &ECC_MulIn, ST_ECP_TIMEOUT) != HAL_OK) ? MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED : 0);
1507 
1508     /* Allocate memory space for scalar multiplication result */
1509     R_binary = mbedtls_calloc(2U * grp->st_modulus_size + 1U, sizeof( uint8_t ));
1510     MBEDTLS_MPI_CHK((R_binary == NULL) ? MBEDTLS_ERR_ECP_ALLOC_FAILED : 0);
1511 
1512     ECC_MulOut.ptX = R_binary + 1U;
1513     ECC_MulOut.ptY = R_binary + grp->st_modulus_size + 1U;
1514 
1515     /* Get the scalar multiplication result */
1516     HAL_PKA_ECCMul_GetResult(&hpka, &ECC_MulOut);
1517 
1518     /* Convert the scalar multiplication result into ecp point format */
1519     R_binary[0] = 0x04U;
1520     MBEDTLS_MPI_CHK( mbedtls_ecp_point_read_binary( grp, R, R_binary, 2U * grp->st_modulus_size + 1U) );
1521 
1522 cleanup:
1523     /* De-initialize HW peripheral */
1524     HAL_PKA_DeInit(&hpka);
1525 
1526     /* Disable HW peripheral clock */
1527     __HAL_RCC_PKA_CLK_DISABLE();
1528 
1529     /* Free memory */
1530     if (P_binary != NULL)
1531     {
1532         mbedtls_platform_zeroize(P_binary, 2U * grp->st_modulus_size + 1U);
1533         mbedtls_free(P_binary);
1534     }
1535 
1536     if (m_binary != NULL)
1537     {
1538         mbedtls_platform_zeroize(m_binary, scalarMulSize);
1539         mbedtls_free(m_binary);
1540     }
1541 
1542     if (R_binary != NULL)
1543     {
1544         mbedtls_platform_zeroize(R_binary, 2U * grp->st_modulus_size + 1U);
1545         mbedtls_free(R_binary);
1546     }
1547 
1548     return ret;
1549 }
1550 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
1551 
1552 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
1553 /*
1554  * For Montgomery curves, we do all the internal arithmetic in projective
1555  * coordinates. Import/export of points uses only the x coordinates, which is
1556  * internaly represented as X / Z.
1557  *
1558  * For scalar multiplication, we'll use a Montgomery ladder.
1559  */
1560 
1561 /*
1562  * Normalize Montgomery x/z coordinates: X = X/Z, Z = 1
1563  * Cost: 1M + 1I
1564  */
ecp_normalize_mxz(const mbedtls_ecp_group * grp,mbedtls_ecp_point * P)1565 static int ecp_normalize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P )
1566 {
1567     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1568 
1569 #if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
1570     if( mbedtls_internal_ecp_grp_capable( grp ) )
1571         return( mbedtls_internal_ecp_normalize_mxz( grp, P ) );
1572 #endif /* MBEDTLS_ECP_NORMALIZE_MXZ_ALT */
1573 
1574     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &P->MBEDTLS_PRIVATE(Z), &P->MBEDTLS_PRIVATE(Z), &grp->P ) );
1575     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &P->MBEDTLS_PRIVATE(X), &P->MBEDTLS_PRIVATE(X), &P->MBEDTLS_PRIVATE(Z) ) );
1576     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &P->MBEDTLS_PRIVATE(Z), 1 ) );
1577 
1578 cleanup:
1579     return( ret );
1580 }
1581 
1582 /*
1583  * Randomize projective x/z coordinates:
1584  * (X, Z) -> (l X, l Z) for random l
1585  * This is sort of the reverse operation of ecp_normalize_mxz().
1586  *
1587  * This countermeasure was first suggested in [2].
1588  * Cost: 2M
1589  */
ecp_randomize_mxz(const mbedtls_ecp_group * grp,mbedtls_ecp_point * P,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1590 static int ecp_randomize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P,
1591                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
1592 {
1593     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1594     mbedtls_mpi l;
1595     size_t p_size;
1596     int count = 0;
1597 
1598 #if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
1599     if( mbedtls_internal_ecp_grp_capable( grp ) )
1600         return( mbedtls_internal_ecp_randomize_mxz( grp, P, f_rng, p_rng );
1601 #endif /* MBEDTLS_ECP_RANDOMIZE_MXZ_ALT */
1602 
1603     p_size = ( grp->pbits + 7 ) / 8;
1604     mbedtls_mpi_init( &l );
1605 
1606     /* Generate l such that 1 < l < p */
1607     do
1608     {
1609         MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng ) );
1610 
1611         while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 )
1612             MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) );
1613 
1614         if( count++ > 10 )
1615         {
1616             ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
1617             goto cleanup;
1618         }
1619     }
1620     while( mbedtls_mpi_cmp_int( &l, 1 ) <= 0 );
1621 
1622     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &P->MBEDTLS_PRIVATE(X), &P->MBEDTLS_PRIVATE(X), &l ) );
1623     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &P->MBEDTLS_PRIVATE(Z), &P->MBEDTLS_PRIVATE(Z), &l ) );
1624 
1625 cleanup:
1626     mbedtls_mpi_free( &l );
1627 
1628     return( ret );
1629 }
1630 
1631 /*
1632  * Double-and-add: R = 2P, S = P + Q, with d = X(P - Q),
1633  * for Montgomery curves in x/z coordinates.
1634  *
1635  * http://www.hyperelliptic.org/EFD/g1p/auto-code/montgom/xz/ladder/mladd-1987-m.op3
1636  * with
1637  * d =  X1
1638  * P = (X2, Z2)
1639  * Q = (X3, Z3)
1640  * R = (X4, Z4)
1641  * S = (X5, Z5)
1642  * and eliminating temporary variables tO, ..., t4.
1643  *
1644  * Cost: 5M + 4S
1645  */
1646 static int ecp_double_add_mxz( const mbedtls_ecp_group *grp,
1647                                mbedtls_ecp_point *R, mbedtls_ecp_point *S,
1648                                const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q,
1649                                const mbedtls_mpi *d )
1650 {
1651     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1652     mbedtls_mpi A, AA, B, BB, E, C, D, DA, CB;
1653 
1654 #if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
1655     if( mbedtls_internal_ecp_grp_capable( grp ) )
1656         return( mbedtls_internal_ecp_double_add_mxz( grp, R, S, P, Q, d ) );
1657 #endif /* MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT */
1658 
1659     mbedtls_mpi_init( &A ); mbedtls_mpi_init( &AA ); mbedtls_mpi_init( &B );
1660     mbedtls_mpi_init( &BB ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &C );
1661     mbedtls_mpi_init( &D ); mbedtls_mpi_init( &DA ); mbedtls_mpi_init( &CB );
1662 
1663     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &A,    &P->MBEDTLS_PRIVATE(X),   &P->MBEDTLS_PRIVATE(Z) ) );
1664     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &AA,   &A,      &A    ) );
1665     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &B,    &P->MBEDTLS_PRIVATE(X),   &P->MBEDTLS_PRIVATE(Z) ) );
1666     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &BB,   &B,      &B    ) );
1667     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &E,    &AA,     &BB   ) );
1668     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &C,    &Q->MBEDTLS_PRIVATE(X),   &Q->MBEDTLS_PRIVATE(Z) ) );
1669     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &D,    &Q->MBEDTLS_PRIVATE(X),   &Q->MBEDTLS_PRIVATE(Z) ) );
1670     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &DA,   &D,      &A    ) );
1671     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &CB,   &C,      &B    ) );
1672     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &S->MBEDTLS_PRIVATE(X), &DA,     &CB   ) );
1673     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S->MBEDTLS_PRIVATE(X), &S->MBEDTLS_PRIVATE(X),   &S->MBEDTLS_PRIVATE(X) ) );
1674     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &S->MBEDTLS_PRIVATE(Z), &DA,     &CB   ) );
1675     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S->MBEDTLS_PRIVATE(Z), &S->MBEDTLS_PRIVATE(Z),   &S->MBEDTLS_PRIVATE(Z) ) );
1676     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S->MBEDTLS_PRIVATE(Z), d,       &S->MBEDTLS_PRIVATE(Z) ) );
1677     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &R->MBEDTLS_PRIVATE(X), &AA,     &BB   ) );
1678     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &R->MBEDTLS_PRIVATE(Z), &grp->A, &E    ) );
1679     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &R->MBEDTLS_PRIVATE(Z), &BB,     &R->MBEDTLS_PRIVATE(Z) ) );
1680     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &R->MBEDTLS_PRIVATE(Z), &E,      &R->MBEDTLS_PRIVATE(Z) ) );
1681 
1682 cleanup:
1683     mbedtls_mpi_free( &A ); mbedtls_mpi_free( &AA ); mbedtls_mpi_free( &B );
1684     mbedtls_mpi_free( &BB ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &C );
1685     mbedtls_mpi_free( &D ); mbedtls_mpi_free( &DA ); mbedtls_mpi_free( &CB );
1686 
1687     return( ret );
1688 }
1689 
1690 /*
1691  * Multiplication with Montgomery ladder in x/z coordinates,
1692  * for curves in Montgomery form
1693  */
1694 static int ecp_mul_mxz( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1695                         const mbedtls_mpi *m, const mbedtls_ecp_point *P,
1696                         int (*f_rng)(void *, unsigned char *, size_t),
1697                         void *p_rng )
1698 {
1699     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1700     size_t i;
1701     unsigned char b;
1702     mbedtls_ecp_point RP;
1703     mbedtls_mpi PX;
1704 
1705     mbedtls_ecp_point_init( &RP ); mbedtls_mpi_init( &PX );
1706 
1707     /* Save PX and read from P before writing to R, in case P == R */
1708     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &PX, &P->MBEDTLS_PRIVATE(X) ) );
1709     MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &RP, P ) );
1710 
1711     /* Set R to zero in modified x/z coordinates */
1712     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->MBEDTLS_PRIVATE(X), 1 ) );
1713     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->MBEDTLS_PRIVATE(Z), 0 ) );
1714     mbedtls_mpi_free( &R->MBEDTLS_PRIVATE(Y) );
1715 
1716     /* RP.X might be sligtly larger than P, so reduce it */
1717     MOD_ADD( RP.MBEDTLS_PRIVATE(X)  );
1718 
1719     /* Randomize coordinates of the starting point */
1720     if( f_rng != NULL )
1721         MBEDTLS_MPI_CHK( ecp_randomize_mxz( grp, &RP, f_rng, p_rng ) );
1722 
1723     /* Loop invariant: R = result so far, RP = R + P */
1724     i = mbedtls_mpi_bitlen( m ); /* one past the (zero-based) most significant bit */
1725     while( i-- > 0 )
1726     {
1727         b = mbedtls_mpi_get_bit( m, i );
1728         /*
1729          *  if (b) R = 2R + P else R = 2R,
1730          * which is:
1731          *  if (b) double_add( RP, R, RP, R )
1732          *  else   double_add( R, RP, R, RP )
1733          * but using safe conditional swaps to avoid leaks
1734          */
1735         MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->MBEDTLS_PRIVATE(X), &RP.MBEDTLS_PRIVATE(X), b ) );
1736         MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->MBEDTLS_PRIVATE(Z), &RP.MBEDTLS_PRIVATE(Z), b ) );
1737         MBEDTLS_MPI_CHK( ecp_double_add_mxz( grp, R, &RP, R, &RP, &PX ) );
1738         MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->MBEDTLS_PRIVATE(X), &RP.MBEDTLS_PRIVATE(X), b ) );
1739         MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->MBEDTLS_PRIVATE(Z), &RP.MBEDTLS_PRIVATE(Z), b ) );
1740     }
1741 
1742     MBEDTLS_MPI_CHK( ecp_normalize_mxz( grp, R ) );
1743 
1744 cleanup:
1745     mbedtls_ecp_point_free( &RP ); mbedtls_mpi_free( &PX );
1746 
1747     return( ret );
1748 }
1749 
1750 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
1751 
1752 /*
1753  * Restartable multiplication R = m * P
1754  */
1755 int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1756              const mbedtls_mpi *m, const mbedtls_ecp_point *P,
1757              int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
1758              mbedtls_ecp_restart_ctx *rs_ctx )
1759 {
1760     int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
1761 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
1762     char is_grp_capable = 0;
1763 #endif
1764     ECP_VALIDATE_RET( grp != NULL );
1765     ECP_VALIDATE_RET( R   != NULL );
1766     ECP_VALIDATE_RET( m   != NULL );
1767     ECP_VALIDATE_RET( P   != NULL );
1768 
1769 #if defined(MBEDTLS_ECP_RESTARTABLE)
1770     /* reset ops count for this call if top-level */
1771     if( rs_ctx != NULL && rs_ctx->depth++ == 0 )
1772         rs_ctx->ops_done = 0;
1773 #else
1774     (void) rs_ctx;
1775 #endif
1776 
1777 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
1778     if( ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) )
1779         MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) );
1780 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
1781 
1782 #if defined(MBEDTLS_ECP_RESTARTABLE)
1783     /* skip argument check when restarting */
1784     if( rs_ctx == NULL || rs_ctx->rsm == NULL )
1785 #endif
1786     {
1787         /* check_privkey is free */
1788         MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_CHK );
1789 
1790         /* Common sanity checks */
1791         MBEDTLS_MPI_CHK( mbedtls_ecp_check_privkey( grp, m ) );
1792         MBEDTLS_MPI_CHK( mbedtls_ecp_check_pubkey( grp, P ) );
1793     }
1794 
1795     ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
1796 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
1797     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
1798         MBEDTLS_MPI_CHK( ecp_mul_mxz( grp, R, m, P, f_rng, p_rng ) );
1799 #endif
1800 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
1801     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
1802         MBEDTLS_MPI_CHK( ecp_mul_comb( grp, R, m, P, f_rng, p_rng, rs_ctx ) );
1803 #endif
1804 
1805 cleanup:
1806 
1807 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
1808     if( is_grp_capable )
1809         mbedtls_internal_ecp_free( grp );
1810 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
1811 
1812 #if defined(MBEDTLS_ECP_RESTARTABLE)
1813     if( rs_ctx != NULL )
1814         rs_ctx->depth--;
1815 #endif
1816 
1817     return( ret );
1818 }
1819 
1820 /*
1821  * Multiplication R = m * P
1822  */
1823 int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1824              const mbedtls_mpi *m, const mbedtls_ecp_point *P,
1825              int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
1826 {
1827     ECP_VALIDATE_RET( grp != NULL );
1828     ECP_VALIDATE_RET( R   != NULL );
1829     ECP_VALIDATE_RET( m   != NULL );
1830     ECP_VALIDATE_RET( P   != NULL );
1831     return( mbedtls_ecp_mul_restartable( grp, R, m, P, f_rng, p_rng, NULL ) );
1832 }
1833 
1834 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
1835 /*
1836  * Check that an affine point is valid as a public key,
1837  * short weierstrass curves (SEC1 3.2.3.1)
1838  *
1839  * STMicroelectronics edition
1840  *
1841  */
1842 static int ecp_check_pubkey_sw( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt )
1843 {
1844     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1845     size_t olen;
1846     uint8_t *pt_binary;
1847     PKA_HandleTypeDef hpka = {0};
1848     PKA_PointCheckInTypeDef ECC_PointCheck = {0};
1849 
1850     /* pt coordinates must be normalized for our checks */
1851     if( mbedtls_mpi_cmp_int( &pt->MBEDTLS_PRIVATE(X), 0 ) < 0 ||
1852         mbedtls_mpi_cmp_int( &pt->MBEDTLS_PRIVATE(Y), 0 ) < 0 ||
1853         mbedtls_mpi_cmp_mpi( &pt->MBEDTLS_PRIVATE(X), &grp->P ) >= 0 ||
1854         mbedtls_mpi_cmp_mpi( &pt->MBEDTLS_PRIVATE(Y), &grp->P ) >= 0 )
1855         return( MBEDTLS_ERR_ECP_INVALID_KEY );
1856 
1857     /* Set HW peripheral Input parameter: curve coefs */
1858     ECC_PointCheck.modulusSize = grp->st_modulus_size;
1859     ECC_PointCheck.modulus     = grp->st_p;
1860     ECC_PointCheck.coefSign    = grp->st_a_sign;
1861     ECC_PointCheck.coefA       = grp->st_a_abs;
1862     ECC_PointCheck.coefB       = grp->st_b;
1863 
1864 #if defined(GENERATOR_HW_PKA_EXTENDED_API)
1865     ECC_PointCheck.pMontgomeryParam = NULL;
1866 #endif
1867 
1868     /* Set HW peripheral input parameter: coordinates of point to check */
1869     pt_binary = mbedtls_calloc(( 2U * grp->st_modulus_size ) + 1U, sizeof( uint8_t ));
1870     MBEDTLS_MPI_CHK((pt_binary == NULL) ? MBEDTLS_ERR_ECP_ALLOC_FAILED : 0);
1871 
1872     MBEDTLS_MPI_CHK( mbedtls_ecp_point_write_binary( grp, pt, MBEDTLS_ECP_PF_UNCOMPRESSED, &olen, pt_binary, ( 2U * grp->st_modulus_size ) + 1U ) );
1873 
1874     ECC_PointCheck.pointX = pt_binary + 1U;
1875     ECC_PointCheck.pointY = pt_binary + grp->st_modulus_size + 1U;
1876 
1877     /* Enable HW peripheral clock */
1878     __HAL_RCC_PKA_CLK_ENABLE();
1879 
1880     /* Initialize HW peripheral */
1881     hpka.Instance = PKA;
1882     MBEDTLS_MPI_CHK((HAL_PKA_Init(&hpka) != HAL_OK) ? MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED : 0);
1883 
1884     /* Reset PKA RAM */
1885     HAL_PKA_RAMReset(&hpka);
1886 
1887     /* Launch the point check */
1888     MBEDTLS_MPI_CHK((HAL_PKA_PointCheck(&hpka, &ECC_PointCheck, ST_ECP_TIMEOUT) != HAL_OK) ? MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED : 0);
1889 
1890     /* Get the result of the point check */
1891     if( HAL_PKA_PointCheck_IsOnCurve(&hpka) != 1U)
1892         ret = MBEDTLS_ERR_ECP_INVALID_KEY;
1893 
1894 cleanup:
1895     /* De-initialize HW peripheral */
1896     HAL_PKA_DeInit(&hpka);
1897 
1898     /* Disable HW peripheral clock */
1899     __HAL_RCC_PKA_CLK_DISABLE();
1900 
1901     /* Free memory */
1902     if (pt_binary != NULL)
1903     {
1904         mbedtls_platform_zeroize(pt_binary, ( 2U * grp->st_modulus_size ) + 1U );
1905         mbedtls_free(pt_binary);
1906     }
1907 
1908     return ret;
1909 }
1910 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
1911 
1912 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
1913 /*
1914  * R = m * P with shortcuts for m == 1 and m == -1
1915  * NOT constant-time - ONLY for short Weierstrass!
1916  */
1917 static int mbedtls_ecp_mul_shortcuts( mbedtls_ecp_group *grp,
1918                                       mbedtls_ecp_point *R,
1919                                       const mbedtls_mpi *m,
1920                                       const mbedtls_ecp_point *P,
1921                                       mbedtls_ecp_restart_ctx *rs_ctx )
1922 {
1923     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1924 
1925     if( mbedtls_mpi_cmp_int( m, 1 ) == 0 )
1926     {
1927         MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) );
1928     }
1929     else if( mbedtls_mpi_cmp_int( m, -1 ) == 0 )
1930     {
1931         MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) );
1932         if( mbedtls_mpi_cmp_int( &R->MBEDTLS_PRIVATE(Y), 0 ) != 0 )
1933             MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &R->MBEDTLS_PRIVATE(Y), &grp->P, &R->MBEDTLS_PRIVATE(Y) ) );
1934     }
1935     else
1936     {
1937         MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, R, m, P,
1938                                                       NULL, NULL, rs_ctx ) );
1939     }
1940 
1941 cleanup:
1942     return( ret );
1943 }
1944 
1945 /*
1946  * Restartable linear combination
1947  * NOT constant-time
1948  */
1949 int mbedtls_ecp_muladd_restartable(
1950              mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1951              const mbedtls_mpi *m, const mbedtls_ecp_point *P,
1952              const mbedtls_mpi *n, const mbedtls_ecp_point *Q,
1953              mbedtls_ecp_restart_ctx *rs_ctx )
1954 {
1955     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1956     mbedtls_ecp_point mP;
1957     mbedtls_ecp_point *pmP = &mP;
1958     mbedtls_ecp_point *pR = R;
1959 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
1960     char is_grp_capable = 0;
1961 #endif
1962     ECP_VALIDATE_RET( grp != NULL );
1963     ECP_VALIDATE_RET( R   != NULL );
1964     ECP_VALIDATE_RET( m   != NULL );
1965     ECP_VALIDATE_RET( P   != NULL );
1966     ECP_VALIDATE_RET( n   != NULL );
1967     ECP_VALIDATE_RET( Q   != NULL );
1968 
1969     if( mbedtls_ecp_get_type( grp ) != MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
1970         return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
1971 
1972     mbedtls_ecp_point_init( &mP );
1973 
1974     ECP_RS_ENTER( ma );
1975 
1976 #if defined(MBEDTLS_ECP_RESTARTABLE)
1977     if( rs_ctx != NULL && rs_ctx->ma != NULL )
1978     {
1979         /* redirect intermediate results to restart context */
1980         pmP = &rs_ctx->ma->mP;
1981         pR  = &rs_ctx->ma->R;
1982 
1983         /* jump to next operation */
1984         if( rs_ctx->ma->state == ecp_rsma_mul2 )
1985             goto mul2;
1986         if( rs_ctx->ma->state == ecp_rsma_add )
1987             goto add;
1988         if( rs_ctx->ma->state == ecp_rsma_norm )
1989             goto norm;
1990     }
1991 #endif /* MBEDTLS_ECP_RESTARTABLE */
1992 
1993     MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, pmP, m, P, rs_ctx ) );
1994 #if defined(MBEDTLS_ECP_RESTARTABLE)
1995     if( rs_ctx != NULL && rs_ctx->ma != NULL )
1996         rs_ctx->ma->state = ecp_rsma_mul2;
1997 
1998 mul2:
1999 #endif
2000     MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, pR,  n, Q, rs_ctx ) );
2001 
2002 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2003     if( ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) )
2004         MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) );
2005 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
2006 
2007 #if defined(MBEDTLS_ECP_RESTARTABLE)
2008     if( rs_ctx != NULL && rs_ctx->ma != NULL )
2009         rs_ctx->ma->state = ecp_rsma_add;
2010 
2011 add:
2012 #endif
2013     MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_ADD );
2014     MBEDTLS_MPI_CHK( ecp_add_mixed( grp, pR, pmP, pR ) );
2015 #if defined(MBEDTLS_ECP_RESTARTABLE)
2016     if( rs_ctx != NULL && rs_ctx->ma != NULL )
2017         rs_ctx->ma->state = ecp_rsma_norm;
2018 
2019 norm:
2020 #endif
2021     MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV );
2022     MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, pR ) );
2023 
2024 #if defined(MBEDTLS_ECP_RESTARTABLE)
2025     if( rs_ctx != NULL && rs_ctx->ma != NULL )
2026         MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, pR ) );
2027 #endif
2028 
2029 cleanup:
2030 #if defined(MBEDTLS_ECP_INTERNAL_ALT)
2031     if( is_grp_capable )
2032         mbedtls_internal_ecp_free( grp );
2033 #endif /* MBEDTLS_ECP_INTERNAL_ALT */
2034 
2035     mbedtls_ecp_point_free( &mP );
2036 
2037     ECP_RS_LEAVE( ma );
2038 
2039     return( ret );
2040 }
2041 
2042 /*
2043  * Linear combination
2044  * NOT constant-time
2045  */
2046 int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
2047              const mbedtls_mpi *m, const mbedtls_ecp_point *P,
2048              const mbedtls_mpi *n, const mbedtls_ecp_point *Q )
2049 {
2050     ECP_VALIDATE_RET( grp != NULL );
2051     ECP_VALIDATE_RET( R   != NULL );
2052     ECP_VALIDATE_RET( m   != NULL );
2053     ECP_VALIDATE_RET( P   != NULL );
2054     ECP_VALIDATE_RET( n   != NULL );
2055     ECP_VALIDATE_RET( Q   != NULL );
2056     return( mbedtls_ecp_muladd_restartable( grp, R, m, P, n, Q, NULL ) );
2057 }
2058 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
2059 
2060 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2061 /*
2062  * Check validity of a public key for Montgomery curves with x-only schemes
2063  */
2064 static int ecp_check_pubkey_mx( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt )
2065 {
2066     /* [Curve25519 p. 5] Just check X is the correct number of bytes */
2067     /* Allow any public value, if it's too big then we'll just reduce it mod p
2068      * (RFC 7748 sec. 5 para. 3). */
2069     if( mbedtls_mpi_size( &pt->MBEDTLS_PRIVATE(X) ) > ( grp->nbits + 7 ) / 8 )
2070         return( MBEDTLS_ERR_ECP_INVALID_KEY );
2071 
2072     return( 0 );
2073 }
2074 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
2075 
2076 /*
2077  * Check that a point is valid as a public key
2078  */
2079 int mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp,
2080                               const mbedtls_ecp_point *pt )
2081 {
2082     ECP_VALIDATE_RET( grp != NULL );
2083     ECP_VALIDATE_RET( pt  != NULL );
2084 
2085     /* Must use affine coordinates */
2086     if( mbedtls_mpi_cmp_int( &pt->MBEDTLS_PRIVATE(Z), 1 ) != 0 )
2087         return( MBEDTLS_ERR_ECP_INVALID_KEY );
2088 
2089 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2090     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
2091         return( ecp_check_pubkey_mx( grp, pt ) );
2092 #endif
2093 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2094     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
2095         return( ecp_check_pubkey_sw( grp, pt ) );
2096 #endif
2097     return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
2098 }
2099 
2100 /*
2101  * Check that an mbedtls_mpi is valid as a private key
2102  */
2103 int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp,
2104                                const mbedtls_mpi *d )
2105 {
2106     ECP_VALIDATE_RET( grp != NULL );
2107     ECP_VALIDATE_RET( d   != NULL );
2108 
2109 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2110     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
2111     {
2112         /* see RFC 7748 sec. 5 para. 5 */
2113         if( mbedtls_mpi_get_bit( d, 0 ) != 0 ||
2114             mbedtls_mpi_get_bit( d, 1 ) != 0 ||
2115             mbedtls_mpi_bitlen( d ) - 1 != grp->nbits ) /* mbedtls_mpi_bitlen is one-based! */
2116             return( MBEDTLS_ERR_ECP_INVALID_KEY );
2117 
2118         /* see [Curve25519] page 5 */
2119         if( grp->nbits == 254 && mbedtls_mpi_get_bit( d, 2 ) != 0 )
2120             return( MBEDTLS_ERR_ECP_INVALID_KEY );
2121 
2122         return( 0 );
2123     }
2124 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
2125 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2126     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
2127     {
2128         /* see SEC1 3.2 */
2129         if( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||
2130             mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
2131             return( MBEDTLS_ERR_ECP_INVALID_KEY );
2132         else
2133             return( 0 );
2134     }
2135 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
2136 
2137     return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
2138 }
2139 
2140 /*
2141  * Generate a private key
2142  */
2143 int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp,
2144                      mbedtls_mpi *d,
2145                      int (*f_rng)(void *, unsigned char *, size_t),
2146                      void *p_rng )
2147 {
2148     int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2149     size_t n_size;
2150 
2151     ECP_VALIDATE_RET( grp   != NULL );
2152     ECP_VALIDATE_RET( d     != NULL );
2153     ECP_VALIDATE_RET( f_rng != NULL );
2154 
2155     n_size = ( grp->nbits + 7 ) / 8;
2156 
2157 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2158     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
2159     {
2160         /* [M225] page 5 */
2161         size_t b;
2162 
2163         do {
2164             MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
2165         } while( mbedtls_mpi_bitlen( d ) == 0);
2166 
2167         /* Make sure the most significant bit is nbits */
2168         b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */
2169         if( b > grp->nbits )
2170             MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) );
2171         else
2172             MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) );
2173 
2174         /* Make sure the last two bits are unset for Curve448, three bits for
2175            Curve25519 */
2176         MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );
2177         MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );
2178         if( grp->nbits == 254 )
2179         {
2180             MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );
2181         }
2182     }
2183 #endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
2184 
2185 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2186     if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
2187     {
2188         /* SEC1 3.2.1: Generate d such that 1 <= n < N */
2189         int count = 0;
2190         unsigned cmp = 0;
2191 
2192         /*
2193          * Match the procedure given in RFC 6979 (deterministic ECDSA):
2194          * - use the same byte ordering;
2195          * - keep the leftmost nbits bits of the generated octet string;
2196          * - try until result is in the desired range.
2197          * This also avoids any biais, which is especially important for ECDSA.
2198          */
2199         do
2200         {
2201             MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
2202             MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );
2203 
2204             /*
2205              * Each try has at worst a probability 1/2 of failing (the msb has
2206              * a probability 1/2 of being 0, and then the result will be < N),
2207              * so after 30 tries failure probability is a most 2**(-30).
2208              *
2209              * For most curves, 1 try is enough with overwhelming probability,
2210              * since N starts with a lot of 1s in binary, but some curves
2211              * such as secp224k1 are actually very close to the worst case.
2212              */
2213             if( ++count > 30 )
2214             {
2215                 ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
2216                 goto cleanup;
2217             }
2218 
2219             ret = mbedtls_mpi_lt_mpi_ct( d, &grp->N, &cmp );
2220             if( ret != 0 )
2221             {
2222                 goto cleanup;
2223             }
2224         }
2225         while( mbedtls_mpi_cmp_int( d, 1 ) < 0 || cmp != 1 );
2226     }
2227 #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
2228 
2229 cleanup:
2230     return( ret );
2231 }
2232 
2233 /*
2234  * Generate a keypair with configurable base point
2235  */
2236 int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
2237                      const mbedtls_ecp_point *G,
2238                      mbedtls_mpi *d, mbedtls_ecp_point *Q,
2239                      int (*f_rng)(void *, unsigned char *, size_t),
2240                      void *p_rng )
2241 {
2242     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2243     ECP_VALIDATE_RET( grp   != NULL );
2244     ECP_VALIDATE_RET( d     != NULL );
2245     ECP_VALIDATE_RET( G     != NULL );
2246     ECP_VALIDATE_RET( Q     != NULL );
2247     ECP_VALIDATE_RET( f_rng != NULL );
2248 
2249     MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, d, f_rng, p_rng ) );
2250     MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) );
2251 
2252 cleanup:
2253     return( ret );
2254 }
2255 
2256 /*
2257  * Generate key pair, wrapper for conventional base point
2258  */
2259 int mbedtls_ecp_gen_keypair( mbedtls_ecp_group *grp,
2260                              mbedtls_mpi *d, mbedtls_ecp_point *Q,
2261                              int (*f_rng)(void *, unsigned char *, size_t),
2262                              void *p_rng )
2263 {
2264     ECP_VALIDATE_RET( grp   != NULL );
2265     ECP_VALIDATE_RET( d     != NULL );
2266     ECP_VALIDATE_RET( Q     != NULL );
2267     ECP_VALIDATE_RET( f_rng != NULL );
2268 
2269     return( mbedtls_ecp_gen_keypair_base( grp, &grp->G, d, Q, f_rng, p_rng ) );
2270 }
2271 
2272 /*
2273  * Generate a keypair, prettier wrapper
2274  */
2275 int mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
2276                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
2277 {
2278     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2279     ECP_VALIDATE_RET( key   != NULL );
2280     ECP_VALIDATE_RET( f_rng != NULL );
2281 
2282     if( ( ret = mbedtls_ecp_group_load( &key->MBEDTLS_PRIVATE(grp), grp_id ) ) != 0 )
2283         return( ret );
2284 
2285     return( mbedtls_ecp_gen_keypair( &key->MBEDTLS_PRIVATE(grp), &key->MBEDTLS_PRIVATE(d), &key->MBEDTLS_PRIVATE(Q), f_rng, p_rng ) );
2286 }
2287 
2288 #define ECP_CURVE25519_KEY_SIZE 32
2289 /*
2290  * Read a private key.
2291  */
2292 int mbedtls_ecp_read_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
2293                           const unsigned char *buf, size_t buflen )
2294 {
2295     int ret = 0;
2296 
2297     ECP_VALIDATE_RET( key  != NULL );
2298     ECP_VALIDATE_RET( buf  != NULL );
2299 
2300     if( ( ret = mbedtls_ecp_group_load( &key->MBEDTLS_PRIVATE(grp), grp_id ) ) != 0 )
2301         return( ret );
2302 
2303     ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
2304 
2305 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2306     if( mbedtls_ecp_get_type( &key->MBEDTLS_PRIVATE(grp) ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
2307     {
2308         /*
2309          * If it is Curve25519 curve then mask the key as mandated by RFC7748
2310          */
2311         if( grp_id == MBEDTLS_ECP_DP_CURVE25519 )
2312         {
2313             if( buflen != ECP_CURVE25519_KEY_SIZE )
2314                 return MBEDTLS_ERR_ECP_INVALID_KEY;
2315 
2316             MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary_le( &key->MBEDTLS_PRIVATE(d), buf, buflen ) );
2317 
2318             /* Set the three least significant bits to 0 */
2319             MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &key->MBEDTLS_PRIVATE(d), 0, 0 ) );
2320             MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &key->MBEDTLS_PRIVATE(d), 1, 0 ) );
2321             MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &key->MBEDTLS_PRIVATE(d), 2, 0 ) );
2322 
2323             /* Set the most significant bit to 0 */
2324             MBEDTLS_MPI_CHK(
2325                     mbedtls_mpi_set_bit( &key->MBEDTLS_PRIVATE(d),
2326                                          ECP_CURVE25519_KEY_SIZE * 8 - 1, 0 )
2327                     );
2328 
2329             /* Set the second most significant bit to 1 */
2330             MBEDTLS_MPI_CHK(
2331                     mbedtls_mpi_set_bit( &key->MBEDTLS_PRIVATE(d),
2332                                          ECP_CURVE25519_KEY_SIZE * 8 - 2, 1 )
2333                     );
2334         }
2335         else
2336             ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
2337     }
2338 
2339 #endif
2340 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2341     if( mbedtls_ecp_get_type( &key->MBEDTLS_PRIVATE(grp) ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
2342     {
2343         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &key->MBEDTLS_PRIVATE(d), buf, buflen ) );
2344 
2345         MBEDTLS_MPI_CHK( mbedtls_ecp_check_privkey( &key->MBEDTLS_PRIVATE(grp), &key->MBEDTLS_PRIVATE(d) ) );
2346     }
2347 
2348 #endif
2349 cleanup:
2350 
2351     if( ret != 0 )
2352         mbedtls_mpi_free( &key->MBEDTLS_PRIVATE(d) );
2353 
2354     return( ret );
2355 }
2356 
2357 /*
2358  * Write a private key - This is deprecated now as of Mbed TLS 3.6.0
2359  */
2360 int mbedtls_ecp_write_key( mbedtls_ecp_keypair *key,
2361                            unsigned char *buf, size_t buflen )
2362 {
2363     int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
2364 
2365     ECP_VALIDATE_RET( key != NULL );
2366     ECP_VALIDATE_RET( buf != NULL );
2367 
2368 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2369     if( mbedtls_ecp_get_type( &key->MBEDTLS_PRIVATE(grp) ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
2370     {
2371         if( key->MBEDTLS_PRIVATE(grp).id == MBEDTLS_ECP_DP_CURVE25519 )
2372         {
2373             if( buflen < ECP_CURVE25519_KEY_SIZE )
2374                 return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
2375 
2376             MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary_le( &key->MBEDTLS_PRIVATE(d), buf, buflen ) );
2377         }
2378         else
2379             ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
2380     }
2381 
2382 #endif
2383 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2384     if( mbedtls_ecp_get_type( &key->MBEDTLS_PRIVATE(grp) ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
2385     {
2386         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &key->MBEDTLS_PRIVATE(d), buf, buflen ) );
2387     }
2388 
2389 #endif
2390 cleanup:
2391 
2392     return( ret );
2393 }
2394 
2395 int mbedtls_ecp_write_key_ext(const mbedtls_ecp_keypair *key,
2396                               size_t *olen, unsigned char *buf, size_t buflen)
2397 {
2398     size_t len = (key->MBEDTLS_PRIVATE(grp).nbits + 7) / 8;
2399     if (len > buflen) {
2400         /* For robustness, ensure *olen <= buflen even on error. */
2401         *olen = 0;
2402         return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
2403     }
2404     *olen = len;
2405 
2406     /* Private key not set */
2407     if (key->MBEDTLS_PRIVATE(d).MBEDTLS_PRIVATE(n) == 0) {
2408         return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2409     }
2410 
2411 #if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
2412     if (mbedtls_ecp_get_type(&key->MBEDTLS_PRIVATE(grp)) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
2413         return mbedtls_mpi_write_binary_le(&key->MBEDTLS_PRIVATE(d), buf, len);
2414     }
2415 #endif
2416 
2417 #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
2418     if (mbedtls_ecp_get_type(&key->MBEDTLS_PRIVATE(grp)) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
2419         return mbedtls_mpi_write_binary(&key->MBEDTLS_PRIVATE(d), buf, len);
2420     }
2421 #endif
2422 
2423     /* Private key set but no recognized curve type? This shouldn't happen. */
2424     return MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2425 }
2426 
2427 /*
2428  * Check a public-private key pair
2429  */
2430 int mbedtls_ecp_check_pub_priv(
2431         const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv,
2432         int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
2433 {
2434     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2435     mbedtls_ecp_point Q;
2436     mbedtls_ecp_group grp;
2437     ECP_VALIDATE_RET( pub != NULL );
2438     ECP_VALIDATE_RET( prv != NULL );
2439 
2440     if( pub->MBEDTLS_PRIVATE(grp).id == MBEDTLS_ECP_DP_NONE ||
2441         pub->MBEDTLS_PRIVATE(grp).id != prv->MBEDTLS_PRIVATE(grp).id ||
2442         mbedtls_mpi_cmp_mpi( &pub->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(X), &prv->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(X) ) ||
2443         mbedtls_mpi_cmp_mpi( &pub->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(Y), &prv->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(Y) ) ||
2444         mbedtls_mpi_cmp_mpi( &pub->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(Z), &prv->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(Z) ) )
2445     {
2446         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
2447     }
2448 
2449     mbedtls_ecp_point_init( &Q );
2450     mbedtls_ecp_group_init( &grp );
2451 
2452     /* mbedtls_ecp_mul() needs a non-const group... */
2453     mbedtls_ecp_group_copy( &grp, &prv->MBEDTLS_PRIVATE(grp) );
2454 
2455     /* Also checks d is valid */
2456     MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &Q, &prv->MBEDTLS_PRIVATE(d), &prv->MBEDTLS_PRIVATE(grp).G, NULL, NULL ) );
2457 
2458     if( mbedtls_mpi_cmp_mpi( &Q.MBEDTLS_PRIVATE(X), &prv->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(X) ) ||
2459         mbedtls_mpi_cmp_mpi( &Q.MBEDTLS_PRIVATE(Y), &prv->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(Y) ) ||
2460         mbedtls_mpi_cmp_mpi( &Q.MBEDTLS_PRIVATE(Z), &prv->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(Z) ) )
2461     {
2462         ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2463         goto cleanup;
2464     }
2465 
2466 cleanup:
2467     mbedtls_ecp_point_free( &Q );
2468     mbedtls_ecp_group_free( &grp );
2469 
2470     return( ret );
2471 }
2472 
2473 #if defined(MBEDTLS_SELF_TEST)
2474 
2475 /*
2476  * Checkup routine
2477  */
2478 int mbedtls_ecp_self_test( int verbose )
2479 {
2480     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2481     size_t i;
2482     mbedtls_ecp_group grp;
2483     mbedtls_ecp_point R, P;
2484     mbedtls_mpi m;
2485     unsigned long add_c_prev, dbl_c_prev, mul_c_prev;
2486     /* exponents especially adapted for secp192r1 */
2487     const char *exponents[] =
2488     {
2489         "000000000000000000000000000000000000000000000001", /* one */
2490         "FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22830", /* N - 1 */
2491         "5EA6F389A38B8BC81E767753B15AA5569E1782E30ABE7D25", /* random */
2492         "400000000000000000000000000000000000000000000000", /* one and zeros */
2493         "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* all ones */
2494         "555555555555555555555555555555555555555555555555", /* 101010... */
2495     };
2496 
2497     mbedtls_ecp_group_init( &grp );
2498     mbedtls_ecp_point_init( &R );
2499     mbedtls_ecp_point_init( &P );
2500     mbedtls_mpi_init( &m );
2501 
2502     /* Use secp192r1 if available, or any available curve */
2503 #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
2504     MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_SECP192R1 ) );
2505 #else
2506     MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, mbedtls_ecp_curve_list()->grp_id ) );
2507 #endif
2508 
2509     if( verbose != 0 )
2510         mbedtls_printf( "  ECP test #1 (constant op_count, base point G): " );
2511 
2512     /* Do a dummy multiplication first to trigger precomputation */
2513     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &m, 2 ) );
2514     MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &P, &m, &grp.G, NULL, NULL ) );
2515 
2516     add_count = 0;
2517     dbl_count = 0;
2518     mul_count = 0;
2519     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[0] ) );
2520     MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &grp.G, NULL, NULL ) );
2521 
2522     for( i = 1; i < sizeof( exponents ) / sizeof( exponents[0] ); i++ )
2523     {
2524         add_c_prev = add_count;
2525         dbl_c_prev = dbl_count;
2526         mul_c_prev = mul_count;
2527         add_count = 0;
2528         dbl_count = 0;
2529         mul_count = 0;
2530 
2531         MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[i] ) );
2532         MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &grp.G, NULL, NULL ) );
2533 
2534         if( add_count != add_c_prev ||
2535             dbl_count != dbl_c_prev ||
2536             mul_count != mul_c_prev )
2537         {
2538             if( verbose != 0 )
2539                 mbedtls_printf( "failed (%u)\n", (unsigned int) i );
2540 
2541             ret = 1;
2542             goto cleanup;
2543         }
2544     }
2545 
2546     if( verbose != 0 )
2547         mbedtls_printf( "passed\n" );
2548 
2549     if( verbose != 0 )
2550         mbedtls_printf( "  ECP test #2 (constant op_count, other point): " );
2551     /* We computed P = 2G last time, use it */
2552 
2553     add_count = 0;
2554     dbl_count = 0;
2555     mul_count = 0;
2556     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[0] ) );
2557     MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &P, NULL, NULL ) );
2558 
2559     for( i = 1; i < sizeof( exponents ) / sizeof( exponents[0] ); i++ )
2560     {
2561         add_c_prev = add_count;
2562         dbl_c_prev = dbl_count;
2563         mul_c_prev = mul_count;
2564         add_count = 0;
2565         dbl_count = 0;
2566         mul_count = 0;
2567 
2568         MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[i] ) );
2569         MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &P, NULL, NULL ) );
2570 
2571         if( add_count != add_c_prev ||
2572             dbl_count != dbl_c_prev ||
2573             mul_count != mul_c_prev )
2574         {
2575             if( verbose != 0 )
2576                 mbedtls_printf( "failed (%u)\n", (unsigned int) i );
2577 
2578             ret = 1;
2579             goto cleanup;
2580         }
2581     }
2582 
2583     if( verbose != 0 )
2584         mbedtls_printf( "passed\n" );
2585 
2586 cleanup:
2587 
2588     if( ret < 0 && verbose != 0 )
2589         mbedtls_printf( "Unexpected error, return code = %08X\n", ret );
2590 
2591     mbedtls_ecp_group_free( &grp );
2592     mbedtls_ecp_point_free( &R );
2593     mbedtls_ecp_point_free( &P );
2594     mbedtls_mpi_free( &m );
2595 
2596     if( verbose != 0 )
2597         mbedtls_printf( "\n" );
2598 
2599     return( ret );
2600 }
2601 
2602 #endif /* MBEDTLS_SELF_TEST */
2603 
2604 #endif /* MBEDTLS_ECP_ALT */
2605 
2606 #endif /* MBEDTLS_ECP_C */
2607