xref: /OK3568_Linux_fs/external/security/librkcrypto/test/c_mode/ecp.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 /*
2  *  Elliptic curves over GF(p): generic functions
3  *
4  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  This file is part of mbed TLS (https://tls.mbed.org)
20  */
21 
22 /*
23  * References:
24  *
25  * SEC1 http://www.secg.org/index.php?action=secg,docs_secg
26  * GECC = Guide to Elliptic Curve Cryptography - Hankerson, Menezes, Vanstone
27  * FIPS 186-3 http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
28  * RFC 4492 for the related TLS structures and constants
29  *
30  * [Curve25519] http://cr.yp.to/ecdh/curve25519-20060209.pdf
31  *
32  * [2] CORON, Jean-S'ebastien. Resistance against differential power analysis
33  *     for elliptic curve cryptosystems. In : Cryptographic Hardware and
34  *     Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302.
35  *     <http://link.springer.com/chapter/10.1007/3-540-48059-5_25>
36  *
37  * [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to
38  *     render ECC resistant against Side Channel Attacks. IACR Cryptology
39  *     ePrint Archive, 2004, vol. 2004, p. 342.
40  *     <http://eprint.iacr.org/2004/342.pdf>
41  */
42 
43 #if !defined(MBEDTLS_CONFIG_FILE)
44 #include "config.h"
45 #else
46 #include MBEDTLS_CONFIG_FILE
47 #endif
48 
49 //#define MBEDTLS_SELF_TEST
50 #if defined(MBEDTLS_ECP_C)
51 #define DEBUG(format,...) printf("[%s]:%d: "format"\n", __func__,__LINE__, ##__VA_ARGS__)
52 #include "ecp.h"
53 
54 #include <string.h>
55 
56 #if defined(MBEDTLS_PLATFORM_C)
57 #include "mbedtls/platform.h"
58 #else
59 #include <stdlib.h>
60 #include <stdio.h>
61 #define mbedtls_printf     printf
62 #define mbedtls_calloc    calloc
63 #define mbedtls_free       free
64 #endif
65 
66 #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
67     !defined(inline) && !defined(__cplusplus)
68 #define inline __inline
69 #endif
70 
71 /* Implementation that should never be optimized out by the compiler */
mbedtls_zeroize(void * v,size_t n)72 static void mbedtls_zeroize( void *v, size_t n ) {
73     volatile unsigned char *p = v; while( n-- ) *p++ = 0;
74 }
75 
76 #if defined(MBEDTLS_SELF_TEST)
77 /*
78  * Counts of point addition and doubling, and field multiplications.
79  * Used to test resistance of point multiplication to simple timing attacks.
80  */
81 static unsigned long add_count, dbl_count, mul_count;
82 #endif
83 
84 #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) ||   \
85     defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) ||   \
86     defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) ||   \
87     defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) ||   \
88     defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) ||   \
89     defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)   ||   \
90     defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)   ||   \
91     defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)   ||   \
92     defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) ||   \
93     defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) ||   \
94     defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
95 #define ECP_SHORTWEIERSTRASS
96 #endif
97 
98 #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
99 #define ECP_MONTGOMERY
100 #endif
101 
102 /*
103  * Curve types: internal for now, might be exposed later
104  */
105 typedef enum
106 {
107     ECP_TYPE_NONE = 0,
108     ECP_TYPE_SHORT_WEIERSTRASS,    /* y^2 = x^3 + a x + b      */
109     ECP_TYPE_MONTGOMERY            /* y^2 = x^3 + a x^2 + x    */
110 } ecp_curve_type;
111 
112 /*
113  * List of supported curves:
114  *  - internal ID
115  *  - TLS NamedCurve ID (RFC 4492 sec. 5.1.1, RFC 7071 sec. 2)
116  *  - size in bits
117  *  - readable name
118  *
119  * Curves are listed in order: largest curves first, and for a given size,
120  * fastest curves first. This provides the default order for the SSL module.
121  *
122  * Reminder: update profiles in x509_crt.c when adding a new curves!
123  */
124 static const mbedtls_ecp_curve_info ecp_supported_curves[] =
125 {
126 #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
127     { MBEDTLS_ECP_DP_SECP521R1,    25,     521,    "secp521r1"         },
128 #endif
129 #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
130     { MBEDTLS_ECP_DP_BP512R1,      28,     512,    "brainpoolP512r1"   },
131 #endif
132 #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
133     { MBEDTLS_ECP_DP_SECP384R1,    24,     384,    "secp384r1"         },
134 #endif
135 #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
136     { MBEDTLS_ECP_DP_BP384R1,      27,     384,    "brainpoolP384r1"   },
137 #endif
138 #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
139     { MBEDTLS_ECP_DP_SECP256R1,    23,     256,    "secp256r1"         },
140 #endif
141 #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
142     { MBEDTLS_ECP_DP_SECP256K1,    22,     256,    "secp256k1"         },
143 #endif
144 #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
145     { MBEDTLS_ECP_DP_BP256R1,      26,     256,    "brainpoolP256r1"   },
146 #endif
147 #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
148     { MBEDTLS_ECP_DP_SECP224R1,    21,     224,    "secp224r1"         },
149 #endif
150 #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
151     { MBEDTLS_ECP_DP_SECP224K1,    20,     224,    "secp224k1"         },
152 #endif
153 #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
154     { MBEDTLS_ECP_DP_SECP192R1,    19,     192,    "secp192r1"         },
155 #endif
156 #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
157     { MBEDTLS_ECP_DP_SECP192K1,    18,     192,    "secp192k1"         },
158 #endif
159     { MBEDTLS_ECP_DP_NONE,          0,     0,      NULL                },
160 };
161 
162 #define ECP_NB_CURVES   sizeof( ecp_supported_curves ) /    \
163                         sizeof( ecp_supported_curves[0] )
164 
165 static mbedtls_ecp_group_id ecp_supported_grp_id[ECP_NB_CURVES];
166 
167 /*
168  * List of supported curves and associated info
169  */
mbedtls_ecp_curve_list(void)170 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void )
171 {
172     return( ecp_supported_curves );
173 }
174 
175 /*
176  * List of supported curves, group ID only
177  */
mbedtls_ecp_grp_id_list(void)178 const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list( void )
179 {
180     static int init_done = 0;
181 
182     if( ! init_done )
183     {
184         size_t i = 0;
185         const mbedtls_ecp_curve_info *curve_info;
186 
187         for( curve_info = mbedtls_ecp_curve_list();
188              curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
189              curve_info++ )
190         {
191             ecp_supported_grp_id[i++] = curve_info->grp_id;
192         }
193         ecp_supported_grp_id[i] = MBEDTLS_ECP_DP_NONE;
194 
195         init_done = 1;
196     }
197 
198     return( ecp_supported_grp_id );
199 }
200 
201 /*
202  * Get the curve info for the internal identifier
203  */
mbedtls_ecp_curve_info_from_grp_id(mbedtls_ecp_group_id grp_id)204 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id( mbedtls_ecp_group_id grp_id )
205 {
206     const mbedtls_ecp_curve_info *curve_info;
207 
208     for( curve_info = mbedtls_ecp_curve_list();
209          curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
210          curve_info++ )
211     {
212         if( curve_info->grp_id == grp_id )
213             return( curve_info );
214     }
215 
216     return( NULL );
217 }
218 
219 /*
220  * Get the curve info from the TLS identifier
221  */
mbedtls_ecp_curve_info_from_tls_id(uint16_t tls_id)222 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id( uint16_t tls_id )
223 {
224     const mbedtls_ecp_curve_info *curve_info;
225 
226     for( curve_info = mbedtls_ecp_curve_list();
227          curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
228          curve_info++ )
229     {
230         if( curve_info->tls_id == tls_id )
231             return( curve_info );
232     }
233 
234     return( NULL );
235 }
236 
237 /*
238  * Get the curve info from the name
239  */
mbedtls_ecp_curve_info_from_name(const char * name)240 const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name( const char *name )
241 {
242     const mbedtls_ecp_curve_info *curve_info;
243 
244     for( curve_info = mbedtls_ecp_curve_list();
245          curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
246          curve_info++ )
247     {
248         if( strcmp( curve_info->name, name ) == 0 )
249             return( curve_info );
250     }
251 
252     return( NULL );
253 }
254 
255 /*
256  * Get the type of a curve
257  */
ecp_get_type(const mbedtls_ecp_group * grp)258 static inline ecp_curve_type ecp_get_type( const mbedtls_ecp_group *grp )
259 {
260     if( grp->G.X.p == NULL )
261         return( ECP_TYPE_NONE );
262 
263     if( grp->G.Y.p == NULL )
264         return( ECP_TYPE_MONTGOMERY );
265     else
266         return( ECP_TYPE_SHORT_WEIERSTRASS );
267 }
268 
269 /*
270  * Initialize (the components of) a point
271  */
mbedtls_ecp_point_init(mbedtls_ecp_point * pt)272 void mbedtls_ecp_point_init( mbedtls_ecp_point *pt )
273 {
274     if( pt == NULL )
275         return;
276 
277     mbedtls_mpi_init( &pt->X );
278     mbedtls_mpi_init( &pt->Y );
279     mbedtls_mpi_init( &pt->Z );
280 }
281 
282 /*
283  * Initialize (the components of) a group
284  */
mbedtls_ecp_group_init(mbedtls_ecp_group * grp)285 void mbedtls_ecp_group_init( mbedtls_ecp_group *grp )
286 {
287     if( grp == NULL )
288         return;
289 
290     memset( grp, 0, sizeof( mbedtls_ecp_group ) );
291 }
292 
293 /*
294  * Initialize (the components of) a key pair
295  */
mbedtls_ecp_keypair_init(mbedtls_ecp_keypair * key)296 void mbedtls_ecp_keypair_init( mbedtls_ecp_keypair *key )
297 {
298     if( key == NULL )
299         return;
300 
301     mbedtls_ecp_group_init( &key->grp );
302     mbedtls_mpi_init( &key->d );
303     mbedtls_ecp_point_init( &key->Q );
304 }
305 
306 /*
307  * Unallocate (the components of) a point
308  */
mbedtls_ecp_point_free(mbedtls_ecp_point * pt)309 void mbedtls_ecp_point_free( mbedtls_ecp_point *pt )
310 {
311     if( pt == NULL )
312         return;
313 
314     mbedtls_mpi_free( &( pt->X ) );
315     mbedtls_mpi_free( &( pt->Y ) );
316     mbedtls_mpi_free( &( pt->Z ) );
317 }
318 
319 /*
320  * Unallocate (the components of) a group
321  */
mbedtls_ecp_group_free(mbedtls_ecp_group * grp)322 void mbedtls_ecp_group_free( mbedtls_ecp_group *grp )
323 {
324     size_t i;
325 
326     if( grp == NULL )
327         return;
328 
329     if( grp->h != 1 )
330     {
331         mbedtls_mpi_free( &grp->P );
332         mbedtls_mpi_free( &grp->A );
333         mbedtls_mpi_free( &grp->B );
334         mbedtls_ecp_point_free( &grp->G );
335         mbedtls_mpi_free( &grp->N );
336     }
337 
338     if( grp->T != NULL )
339     {
340         for( i = 0; i < grp->T_size; i++ )
341             mbedtls_ecp_point_free( &grp->T[i] );
342         mbedtls_free( grp->T );
343     }
344 
345     mbedtls_zeroize( grp, sizeof( mbedtls_ecp_group ) );
346 }
347 
348 /*
349  * Unallocate (the components of) a key pair
350  */
mbedtls_ecp_keypair_free(mbedtls_ecp_keypair * key)351 void mbedtls_ecp_keypair_free( mbedtls_ecp_keypair *key )
352 {
353     if( key == NULL )
354         return;
355 
356     mbedtls_ecp_group_free( &key->grp );
357     mbedtls_mpi_free( &key->d );
358     mbedtls_ecp_point_free( &key->Q );
359 }
360 
361 /*
362  * Copy the contents of a point
363  */
mbedtls_ecp_copy(mbedtls_ecp_point * P,const mbedtls_ecp_point * Q)364 int mbedtls_ecp_copy( mbedtls_ecp_point *P, const mbedtls_ecp_point *Q )
365 {
366     int ret;
367 
368     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->X, &Q->X ) );
369     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->Y, &Q->Y ) );
370     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->Z, &Q->Z ) );
371 
372 cleanup:
373     return( ret );
374 }
375 
376 /*
377  * Copy the contents of a group object
378  */
mbedtls_ecp_group_copy(mbedtls_ecp_group * dst,const mbedtls_ecp_group * src)379 int mbedtls_ecp_group_copy( mbedtls_ecp_group *dst, const mbedtls_ecp_group *src )
380 {
381     return mbedtls_ecp_group_load( dst, src->id );
382 }
383 
384 /*
385  * Set point to zero
386  */
mbedtls_ecp_set_zero(mbedtls_ecp_point * pt)387 int mbedtls_ecp_set_zero( mbedtls_ecp_point *pt )
388 {
389     int ret;
390 
391     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->X , 1 ) );
392     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Y , 1 ) );
393     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z , 0 ) );
394 
395 cleanup:
396     return( ret );
397 }
398 
399 /*
400  * Tell if a point is zero
401  */
mbedtls_ecp_is_zero(mbedtls_ecp_point * pt)402 int mbedtls_ecp_is_zero( mbedtls_ecp_point *pt )
403 {
404     return( mbedtls_mpi_cmp_int( &pt->Z, 0 ) == 0 );
405 }
406 
407 /*
408  * Compare two points lazyly
409  */
mbedtls_ecp_point_cmp(const mbedtls_ecp_point * P,const mbedtls_ecp_point * Q)410 int mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P,
411                            const mbedtls_ecp_point *Q )
412 {
413     if( mbedtls_mpi_cmp_mpi( &P->X, &Q->X ) == 0 &&
414         mbedtls_mpi_cmp_mpi( &P->Y, &Q->Y ) == 0 &&
415         mbedtls_mpi_cmp_mpi( &P->Z, &Q->Z ) == 0 )
416     {
417         return( 0 );
418     }
419 
420     return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
421 }
422 
423 /*
424  * Import a non-zero point from ASCII strings
425  */
mbedtls_ecp_point_read_string(mbedtls_ecp_point * P,int radix,const char * x,const char * y)426 int mbedtls_ecp_point_read_string( mbedtls_ecp_point *P, int radix,
427                            const char *x, const char *y )
428 {
429     int ret;
430 
431     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &P->X, radix, x ) );
432     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &P->Y, radix, y ) );
433     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &P->Z, 1 ) );
434 
435 cleanup:
436     return( ret );
437 }
438 
439 /*
440  * Export a point into unsigned binary data (SEC1 2.3.3)
441  */
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)442 int mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *P,
443                             int format, size_t *olen,
444                             unsigned char *buf, size_t buflen )
445 {
446     int ret = 0;
447     size_t plen;
448 
449     if( format != MBEDTLS_ECP_PF_UNCOMPRESSED &&
450         format != MBEDTLS_ECP_PF_COMPRESSED )
451         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
452 
453     /*
454      * Common case: P == 0
455      */
456     if( mbedtls_mpi_cmp_int( &P->Z, 0 ) == 0 )
457     {
458         if( buflen < 1 )
459             return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
460 
461         buf[0] = 0x00;
462         *olen = 1;
463 
464         return( 0 );
465     }
466 
467     plen = mbedtls_mpi_size( &grp->P );
468 
469     if( format == MBEDTLS_ECP_PF_UNCOMPRESSED )
470     {
471         *olen = 2 * plen + 1;
472 
473         if( buflen < *olen )
474             return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
475 
476         buf[0] = 0x04;
477         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->X, buf + 1, plen ) );
478         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->Y, buf + 1 + plen, plen ) );
479     }
480     else if( format == MBEDTLS_ECP_PF_COMPRESSED )
481     {
482         *olen = plen + 1;
483 
484         if( buflen < *olen )
485             return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
486 
487         buf[0] = 0x02 + mbedtls_mpi_get_bit( &P->Y, 0 );
488         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->X, buf + 1, plen ) );
489     }
490 
491 cleanup:
492     return( ret );
493 }
494 
495 /*
496  * Import a point from unsigned binary data (SEC1 2.3.4)
497  */
mbedtls_ecp_point_read_binary(const mbedtls_ecp_group * grp,mbedtls_ecp_point * pt,const unsigned char * buf,size_t ilen)498 int mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt,
499                            const unsigned char *buf, size_t ilen )
500 {
501     int ret;
502     size_t plen;
503 
504     if( ilen < 1 )
505         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
506 
507     if( buf[0] == 0x00 )
508     {
509         if( ilen == 1 )
510             return( mbedtls_ecp_set_zero( pt ) );
511         else
512             return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
513     }
514 
515     plen = mbedtls_mpi_size( &grp->P );
516 
517     if( buf[0] != 0x04 )
518         return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
519 
520     if( ilen != 2 * plen + 1 )
521         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
522 
523     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &pt->X, buf + 1, plen ) );
524     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &pt->Y, buf + 1 + plen, plen ) );
525     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z, 1 ) );
526 
527 cleanup:
528     return( ret );
529 }
530 
531 /*
532  * Import a point from a TLS ECPoint record (RFC 4492)
533  *      struct {
534  *          opaque point <1..2^8-1>;
535  *      } ECPoint;
536  */
mbedtls_ecp_tls_read_point(const mbedtls_ecp_group * grp,mbedtls_ecp_point * pt,const unsigned char ** buf,size_t buf_len)537 int mbedtls_ecp_tls_read_point( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt,
538                         const unsigned char **buf, size_t buf_len )
539 {
540     unsigned char data_len;
541     const unsigned char *buf_start;
542 
543     /*
544      * We must have at least two bytes (1 for length, at least one for data)
545      */
546     if( buf_len < 2 )
547         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
548 
549     data_len = *(*buf)++;
550     if( data_len < 1 || data_len > buf_len - 1 )
551         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
552 
553     /*
554      * Save buffer start for read_binary and update buf
555      */
556     buf_start = *buf;
557     *buf += data_len;
558 
559     return mbedtls_ecp_point_read_binary( grp, pt, buf_start, data_len );
560 }
561 
562 /*
563  * Export a point as a TLS ECPoint record (RFC 4492)
564  *      struct {
565  *          opaque point <1..2^8-1>;
566  *      } ECPoint;
567  */
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)568 int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt,
569                          int format, size_t *olen,
570                          unsigned char *buf, size_t blen )
571 {
572     int ret;
573 
574     /*
575      * buffer length must be at least one, for our length byte
576      */
577     if( blen < 1 )
578         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
579 
580     if( ( ret = mbedtls_ecp_point_write_binary( grp, pt, format,
581                     olen, buf + 1, blen - 1) ) != 0 )
582         return( ret );
583 
584     /*
585      * write length to the first byte and update total length
586      */
587     buf[0] = (unsigned char) *olen;
588     ++*olen;
589 
590     return( 0 );
591 }
592 
593 /*
594  * Set a group from an ECParameters record (RFC 4492)
595  */
mbedtls_ecp_tls_read_group(mbedtls_ecp_group * grp,const unsigned char ** buf,size_t len)596 int mbedtls_ecp_tls_read_group( mbedtls_ecp_group *grp, const unsigned char **buf, size_t len )
597 {
598     uint16_t tls_id;
599     const mbedtls_ecp_curve_info *curve_info;
600 
601     /*
602      * We expect at least three bytes (see below)
603      */
604     if( len < 3 )
605         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
606 
607     /*
608      * First byte is curve_type; only named_curve is handled
609      */
610     if( *(*buf)++ != MBEDTLS_ECP_TLS_NAMED_CURVE )
611         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
612 
613     /*
614      * Next two bytes are the namedcurve value
615      */
616     tls_id = *(*buf)++;
617     tls_id <<= 8;
618     tls_id |= *(*buf)++;
619 
620     if( ( curve_info = mbedtls_ecp_curve_info_from_tls_id( tls_id ) ) == NULL )
621         return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
622 
623     return mbedtls_ecp_group_load( grp, curve_info->grp_id );
624 }
625 
626 /*
627  * Write the ECParameters record corresponding to a group (RFC 4492)
628  */
mbedtls_ecp_tls_write_group(const mbedtls_ecp_group * grp,size_t * olen,unsigned char * buf,size_t blen)629 int mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, size_t *olen,
630                          unsigned char *buf, size_t blen )
631 {
632     const mbedtls_ecp_curve_info *curve_info;
633 
634     if( ( curve_info = mbedtls_ecp_curve_info_from_grp_id( grp->id ) ) == NULL )
635         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
636 
637     /*
638      * We are going to write 3 bytes (see below)
639      */
640     *olen = 3;
641     if( blen < *olen )
642         return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
643 
644     /*
645      * First byte is curve_type, always named_curve
646      */
647     *buf++ = MBEDTLS_ECP_TLS_NAMED_CURVE;
648 
649     /*
650      * Next two bytes are the namedcurve value
651      */
652     buf[0] = curve_info->tls_id >> 8;
653     buf[1] = curve_info->tls_id & 0xFF;
654 
655     return( 0 );
656 }
657 
658 /*
659  * Wrapper around fast quasi-modp functions, with fall-back to mbedtls_mpi_mod_mpi.
660  * See the documentation of struct mbedtls_ecp_group.
661  *
662  * This function is in the critial loop for mbedtls_ecp_mul, so pay attention to perf.
663  */
ecp_modp(mbedtls_mpi * N,const mbedtls_ecp_group * grp)664 static int ecp_modp( mbedtls_mpi *N, const mbedtls_ecp_group *grp )
665 {
666     int ret;
667 
668     if( grp->modp == NULL )
669         return( mbedtls_mpi_mod_mpi( N, N, &grp->P ) );
670 
671     /* N->s < 0 is a much faster test, which fails only if N is 0 */
672     if( ( N->s < 0 && mbedtls_mpi_cmp_int( N, 0 ) != 0 ) ||
673         mbedtls_mpi_bitlen( N ) > 2 * grp->pbits )
674     {
675         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
676     }
677 
678     MBEDTLS_MPI_CHK( grp->modp( N ) );
679 
680     /* N->s < 0 is a much faster test, which fails only if N is 0 */
681     while( N->s < 0 && mbedtls_mpi_cmp_int( N, 0 ) != 0 )
682         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &grp->P ) );
683 
684     while( mbedtls_mpi_cmp_mpi( N, &grp->P ) >= 0 )
685         /* we known P, N and the result are positive */
686         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( N, N, &grp->P ) );
687 
688 cleanup:
689     return( ret );
690 }
691 
692 /*
693  * Fast mod-p functions expect their argument to be in the 0..p^2 range.
694  *
695  * In order to guarantee that, we need to ensure that operands of
696  * mbedtls_mpi_mul_mpi are in the 0..p range. So, after each operation we will
697  * bring the result back to this range.
698  *
699  * The following macros are shortcuts for doing that.
700  */
701 
702 /*
703  * Reduce a mbedtls_mpi mod p in-place, general case, to use after mbedtls_mpi_mul_mpi
704  */
705 #if defined(MBEDTLS_SELF_TEST)
706 #define INC_MUL_COUNT   mul_count++;
707 #else
708 #define INC_MUL_COUNT
709 #endif
710 
711 #define MOD_MUL( N )    do { MBEDTLS_MPI_CHK( ecp_modp( &N, grp ) ); INC_MUL_COUNT } \
712                         while( 0 )
713 
714 /*
715  * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_sub_mpi
716  * N->s < 0 is a very fast test, which fails only if N is 0
717  */
718 #define MOD_SUB( N )                                \
719     while( N.s < 0 && mbedtls_mpi_cmp_int( &N, 0 ) != 0 )   \
720         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &N, &N, &grp->P ) )
721 
722 /*
723  * Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_add_mpi and mbedtls_mpi_mul_int.
724  * We known P, N and the result are positive, so sub_abs is correct, and
725  * a bit faster.
726  */
727 #define MOD_ADD( N )                                \
728     while( mbedtls_mpi_cmp_mpi( &N, &grp->P ) >= 0 )        \
729         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &N, &N, &grp->P ) )
730 
731 #if defined(ECP_SHORTWEIERSTRASS)
732 /*
733  * For curves in short Weierstrass form, we do all the internal operations in
734  * Jacobian coordinates.
735  *
736  * For multiplication, we'll use a comb method with coutermeasueres against
737  * SPA, hence timing attacks.
738  */
739 
740 /*
741  * Normalize jacobian coordinates so that Z == 0 || Z == 1  (GECC 3.2.1)
742  * Cost: 1N := 1I + 3M + 1S
743  */
ecp_normalize_jac(const mbedtls_ecp_group * grp,mbedtls_ecp_point * pt)744 static int ecp_normalize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt )
745 {
746     int ret;
747     mbedtls_mpi Zi, ZZi;
748 
749     if( mbedtls_mpi_cmp_int( &pt->Z, 0 ) == 0 )
750         return( 0 );
751 
752     mbedtls_mpi_init( &Zi ); mbedtls_mpi_init( &ZZi );
753 
754     /*
755      * X = X / Z^2  mod p
756      */
757     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &Zi,      &pt->Z,     &grp->P ) );
758     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ZZi,     &Zi,        &Zi     ) ); MOD_MUL( ZZi );
759     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->X,   &pt->X,     &ZZi    ) ); MOD_MUL( pt->X );
760 
761     /*
762      * Y = Y / Z^3  mod p
763      */
764     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->Y,   &pt->Y,     &ZZi    ) ); MOD_MUL( pt->Y );
765     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->Y,   &pt->Y,     &Zi     ) ); MOD_MUL( pt->Y );
766 
767     /*
768      * Z = 1
769      */
770     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z, 1 ) );
771 
772 cleanup:
773 
774     mbedtls_mpi_free( &Zi ); mbedtls_mpi_free( &ZZi );
775 
776     return( ret );
777 }
778 
779 /*
780  * Normalize jacobian coordinates of an array of (pointers to) points,
781  * using Montgomery's trick to perform only one inversion mod P.
782  * (See for example Cohen's "A Course in Computational Algebraic Number
783  * Theory", Algorithm 10.3.4.)
784  *
785  * Warning: fails (returning an error) if one of the points is zero!
786  * This should never happen, see choice of w in ecp_mul_comb().
787  *
788  * Cost: 1N(t) := 1I + (6t - 3)M + 1S
789  */
ecp_normalize_jac_many(const mbedtls_ecp_group * grp,mbedtls_ecp_point * T[],size_t t_len)790 static int ecp_normalize_jac_many( const mbedtls_ecp_group *grp,
791                                    mbedtls_ecp_point *T[], size_t t_len )
792 {
793     int ret;
794     size_t i;
795     mbedtls_mpi *c, u, Zi, ZZi;
796 
797     if( t_len < 2 )
798         return( ecp_normalize_jac( grp, *T ) );
799 
800     if( ( c = mbedtls_calloc( t_len, sizeof( mbedtls_mpi ) ) ) == NULL )
801         return( MBEDTLS_ERR_ECP_ALLOC_FAILED );
802 
803     mbedtls_mpi_init( &u ); mbedtls_mpi_init( &Zi ); mbedtls_mpi_init( &ZZi );
804 
805     /*
806      * c[i] = Z_0 * ... * Z_i
807      */
808     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &c[0], &T[0]->Z ) );
809     for( i = 1; i < t_len; i++ )
810     {
811         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &c[i], &c[i-1], &T[i]->Z ) );
812         MOD_MUL( c[i] );
813     }
814 
815     /*
816      * u = 1 / (Z_0 * ... * Z_n) mod P
817      */
818     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &u, &c[t_len-1], &grp->P ) );
819 
820     for( i = t_len - 1; ; i-- )
821     {
822         /*
823          * Zi = 1 / Z_i mod p
824          * u = 1 / (Z_0 * ... * Z_i) mod P
825          */
826         if( i == 0 ) {
827             MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Zi, &u ) );
828         }
829         else
830         {
831             MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &Zi, &u, &c[i-1]  ) ); MOD_MUL( Zi );
832             MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &u,  &u, &T[i]->Z ) ); MOD_MUL( u );
833         }
834 
835         /*
836          * proceed as in normalize()
837          */
838         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ZZi,     &Zi,      &Zi  ) ); MOD_MUL( ZZi );
839         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T[i]->X, &T[i]->X, &ZZi ) ); MOD_MUL( T[i]->X );
840         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T[i]->Y, &T[i]->Y, &ZZi ) ); MOD_MUL( T[i]->Y );
841         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T[i]->Y, &T[i]->Y, &Zi  ) ); MOD_MUL( T[i]->Y );
842 
843         /*
844          * Post-precessing: reclaim some memory by shrinking coordinates
845          * - not storing Z (always 1)
846          * - shrinking other coordinates, but still keeping the same number of
847          *   limbs as P, as otherwise it will too likely be regrown too fast.
848          */
849         MBEDTLS_MPI_CHK( mbedtls_mpi_shrink( &T[i]->X, grp->P.n ) );
850         MBEDTLS_MPI_CHK( mbedtls_mpi_shrink( &T[i]->Y, grp->P.n ) );
851         mbedtls_mpi_free( &T[i]->Z );
852 
853         if( i == 0 )
854             break;
855     }
856 
857 cleanup:
858 
859     mbedtls_mpi_free( &u ); mbedtls_mpi_free( &Zi ); mbedtls_mpi_free( &ZZi );
860     for( i = 0; i < t_len; i++ )
861         mbedtls_mpi_free( &c[i] );
862     mbedtls_free( c );
863 
864     return( ret );
865 }
866 
867 /*
868  * Conditional point inversion: Q -> -Q = (Q.X, -Q.Y, Q.Z) without leak.
869  * "inv" must be 0 (don't invert) or 1 (invert) or the result will be invalid
870  */
ecp_safe_invert_jac(const mbedtls_ecp_group * grp,mbedtls_ecp_point * Q,unsigned char inv)871 static int ecp_safe_invert_jac( const mbedtls_ecp_group *grp,
872                             mbedtls_ecp_point *Q,
873                             unsigned char inv )
874 {
875     int ret;
876     unsigned char nonzero;
877     mbedtls_mpi mQY;
878 
879     mbedtls_mpi_init( &mQY );
880 
881     /* Use the fact that -Q.Y mod P = P - Q.Y unless Q.Y == 0 */
882     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &mQY, &grp->P, &Q->Y ) );
883     nonzero = mbedtls_mpi_cmp_int( &Q->Y, 0 ) != 0;
884     MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &Q->Y, &mQY, inv & nonzero ) );
885 
886 cleanup:
887     mbedtls_mpi_free( &mQY );
888 
889     return( ret );
890 }
891 
892 /*
893  * Point doubling R = 2 P, Jacobian coordinates
894  *
895  * Based on http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-1998-cmo-2 .
896  *
897  * We follow the variable naming fairly closely. The formula variations that trade a MUL for a SQR
898  * (plus a few ADDs) aren't useful as our bignum implementation doesn't distinguish squaring.
899  *
900  * Standard optimizations are applied when curve parameter A is one of { 0, -3 }.
901  *
902  * Cost: 1D := 3M + 4S          (A ==  0)
903  *             4M + 4S          (A == -3)
904  *             3M + 6S + 1a     otherwise
905  */
ecp_double_jac(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_ecp_point * P)906 static int ecp_double_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
907                            const mbedtls_ecp_point *P )
908 {
909     int ret;
910     mbedtls_mpi M, S, T, U;
911 
912 #if defined(MBEDTLS_SELF_TEST)
913     dbl_count++;
914 #endif
915 
916     mbedtls_mpi_init( &M ); mbedtls_mpi_init( &S ); mbedtls_mpi_init( &T ); mbedtls_mpi_init( &U );
917 
918     /* Special case for A = -3 */
919     if( grp->A.p == NULL )
920     {
921         /* M = 3(X + Z^2)(X - Z^2) */
922         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &P->Z,  &P->Z   ) ); MOD_MUL( S );
923         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &T,  &P->X,  &S      ) ); MOD_ADD( T );
924         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &U,  &P->X,  &S      ) ); MOD_SUB( U );
925         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &T,     &U      ) ); MOD_MUL( S );
926         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M,  &S,     3       ) ); MOD_ADD( M );
927     }
928     else
929     {
930         /* M = 3.X^2 */
931         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &P->X,  &P->X   ) ); MOD_MUL( S );
932         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M,  &S,     3       ) ); MOD_ADD( M );
933 
934         /* Optimize away for "koblitz" curves with A = 0 */
935         if( mbedtls_mpi_cmp_int( &grp->A, 0 ) != 0 )
936         {
937             /* M += A.Z^4 */
938             MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &P->Z,  &P->Z   ) ); MOD_MUL( S );
939             MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T,  &S,     &S      ) ); MOD_MUL( T );
940             MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &T,     &grp->A ) ); MOD_MUL( S );
941             MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &M,  &M,     &S      ) ); MOD_ADD( M );
942         }
943     }
944 
945     /* S = 4.X.Y^2 */
946     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T,  &P->Y,  &P->Y   ) ); MOD_MUL( T );
947     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &T,  1               ) ); MOD_ADD( T );
948     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &P->X,  &T      ) ); MOD_MUL( S );
949     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &S,  1               ) ); MOD_ADD( S );
950 
951     /* U = 8.Y^4 */
952     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &U,  &T,     &T      ) ); MOD_MUL( U );
953     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &U,  1               ) ); MOD_ADD( U );
954 
955     /* T = M^2 - 2.S */
956     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T,  &M,     &M      ) ); MOD_MUL( T );
957     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T,  &T,     &S      ) ); MOD_SUB( T );
958     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T,  &T,     &S      ) ); MOD_SUB( T );
959 
960     /* S = M(S - T) - U */
961     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &S,  &S,     &T      ) ); MOD_SUB( S );
962     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S,  &S,     &M      ) ); MOD_MUL( S );
963     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &S,  &S,     &U      ) ); MOD_SUB( S );
964 
965     /* U = 2.Y.Z */
966     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &U,  &P->Y,  &P->Z   ) ); MOD_MUL( U );
967     MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( &U,  1               ) ); MOD_ADD( U );
968 
969     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->X, &T ) );
970     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Y, &S ) );
971     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Z, &U ) );
972 
973 cleanup:
974     mbedtls_mpi_free( &M ); mbedtls_mpi_free( &S ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &U );
975 
976     return( ret );
977 }
978 
979 /*
980  * Addition: R = P + Q, mixed affine-Jacobian coordinates (GECC 3.22)
981  *
982  * The coordinates of Q must be normalized (= affine),
983  * but those of P don't need to. R is not normalized.
984  *
985  * Special cases: (1) P or Q is zero, (2) R is zero, (3) P == Q.
986  * None of these cases can happen as intermediate step in ecp_mul_comb():
987  * - at each step, P, Q and R are multiples of the base point, the factor
988  *   being less than its order, so none of them is zero;
989  * - Q is an odd multiple of the base point, P an even multiple,
990  *   due to the choice of precomputed points in the modified comb method.
991  * So branches for these cases do not leak secret information.
992  *
993  * We accept Q->Z being unset (saving memory in tables) as meaning 1.
994  *
995  * Cost: 1A := 8M + 3S
996  */
ecp_add_mixed(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_ecp_point * P,const mbedtls_ecp_point * Q)997 static int ecp_add_mixed( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
998                           const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q )
999 {
1000     int ret;
1001     mbedtls_mpi T1, T2, T3, T4, X, Y, Z;
1002 
1003 #if defined(MBEDTLS_SELF_TEST)
1004     add_count++;
1005 #endif
1006 
1007     /*
1008      * Trivial cases: P == 0 or Q == 0 (case 1)
1009      */
1010     if( mbedtls_mpi_cmp_int( &P->Z, 0 ) == 0 )
1011         return( mbedtls_ecp_copy( R, Q ) );
1012 
1013     if( Q->Z.p != NULL && mbedtls_mpi_cmp_int( &Q->Z, 0 ) == 0 )
1014         return( mbedtls_ecp_copy( R, P ) );
1015 
1016     /*
1017      * Make sure Q coordinates are normalized
1018      */
1019     if( Q->Z.p != NULL && mbedtls_mpi_cmp_int( &Q->Z, 1 ) != 0 )
1020         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1021 
1022     mbedtls_mpi_init( &T1 ); mbedtls_mpi_init( &T2 ); mbedtls_mpi_init( &T3 ); mbedtls_mpi_init( &T4 );
1023     mbedtls_mpi_init( &X ); mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &Z );
1024 
1025     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T1,  &P->Z,  &P->Z ) );  MOD_MUL( T1 );
1026     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T2,  &T1,    &P->Z ) );  MOD_MUL( T2 );
1027     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T1,  &T1,    &Q->X ) );  MOD_MUL( T1 );
1028     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T2,  &T2,    &Q->Y ) );  MOD_MUL( T2 );
1029     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T1,  &T1,    &P->X ) );  MOD_SUB( T1 );
1030     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T2,  &T2,    &P->Y ) );  MOD_SUB( T2 );
1031 
1032     /* Special cases (2) and (3) */
1033     if( mbedtls_mpi_cmp_int( &T1, 0 ) == 0 )
1034     {
1035         if( mbedtls_mpi_cmp_int( &T2, 0 ) == 0 )
1036         {
1037             ret = ecp_double_jac( grp, R, P );
1038             goto cleanup;
1039         }
1040         else
1041         {
1042             ret = mbedtls_ecp_set_zero( R );
1043             goto cleanup;
1044         }
1045     }
1046 
1047     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &Z,   &P->Z,  &T1   ) );  MOD_MUL( Z  );
1048     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T3,  &T1,    &T1   ) );  MOD_MUL( T3 );
1049     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T4,  &T3,    &T1   ) );  MOD_MUL( T4 );
1050     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T3,  &T3,    &P->X ) );  MOD_MUL( T3 );
1051     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &T1,  &T3,    2     ) );  MOD_ADD( T1 );
1052     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &X,   &T2,    &T2   ) );  MOD_MUL( X  );
1053     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &X,   &X,     &T1   ) );  MOD_SUB( X  );
1054     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &X,   &X,     &T4   ) );  MOD_SUB( X  );
1055     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T3,  &T3,    &X    ) );  MOD_SUB( T3 );
1056     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T3,  &T3,    &T2   ) );  MOD_MUL( T3 );
1057     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T4,  &T4,    &P->Y ) );  MOD_MUL( T4 );
1058     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &Y,   &T3,    &T4   ) );  MOD_SUB( Y  );
1059 
1060     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->X, &X ) );
1061     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Y, &Y ) );
1062     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Z, &Z ) );
1063 
1064 cleanup:
1065 
1066     mbedtls_mpi_free( &T1 ); mbedtls_mpi_free( &T2 ); mbedtls_mpi_free( &T3 ); mbedtls_mpi_free( &T4 );
1067     mbedtls_mpi_free( &X ); mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &Z );
1068 
1069     return( ret );
1070 }
1071 
1072 /*
1073  * Randomize jacobian coordinates:
1074  * (X, Y, Z) -> (l^2 X, l^3 Y, l Z) for random l
1075  * This is sort of the reverse operation of ecp_normalize_jac().
1076  *
1077  * This countermeasure was first suggested in [2].
1078  */
ecp_randomize_jac(const mbedtls_ecp_group * grp,mbedtls_ecp_point * pt,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1079 static int ecp_randomize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt,
1080                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
1081 {
1082     int ret;
1083     mbedtls_mpi l, ll;
1084     size_t p_size = ( grp->pbits + 7 ) / 8;
1085     int count = 0;
1086 
1087     mbedtls_mpi_init( &l ); mbedtls_mpi_init( &ll );
1088 
1089     /* Generate l such that 1 < l < p */
1090     do
1091     {
1092         mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng );
1093 
1094         while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 )
1095             MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) );
1096 
1097         if( count++ > 10 )
1098             return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
1099     }
1100     while( mbedtls_mpi_cmp_int( &l, 1 ) <= 0 );
1101 
1102     /* Z = l * Z */
1103     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->Z,   &pt->Z,     &l  ) ); MOD_MUL( pt->Z );
1104 
1105     /* X = l^2 * X */
1106     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ll,      &l,         &l  ) ); MOD_MUL( ll );
1107     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->X,   &pt->X,     &ll ) ); MOD_MUL( pt->X );
1108 
1109     /* Y = l^3 * Y */
1110     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &ll,      &ll,        &l  ) ); MOD_MUL( ll );
1111     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &pt->Y,   &pt->Y,     &ll ) ); MOD_MUL( pt->Y );
1112 
1113 cleanup:
1114     mbedtls_mpi_free( &l ); mbedtls_mpi_free( &ll );
1115 
1116     return( ret );
1117 }
1118 
1119 /*
1120  * Check and define parameters used by the comb method (see below for details)
1121  */
1122 #if MBEDTLS_ECP_WINDOW_SIZE < 2 || MBEDTLS_ECP_WINDOW_SIZE > 7
1123 #error "MBEDTLS_ECP_WINDOW_SIZE out of bounds"
1124 #endif
1125 
1126 /* d = ceil( n / w ) */
1127 #define COMB_MAX_D      ( MBEDTLS_ECP_MAX_BITS + 1 ) / 2
1128 
1129 /* number of precomputed points */
1130 #define COMB_MAX_PRE    ( 1 << ( MBEDTLS_ECP_WINDOW_SIZE - 1 ) )
1131 
1132 /*
1133  * Compute the representation of m that will be used with our comb method.
1134  *
1135  * The basic comb method is described in GECC 3.44 for example. We use a
1136  * modified version that provides resistance to SPA by avoiding zero
1137  * digits in the representation as in [3]. We modify the method further by
1138  * requiring that all K_i be odd, which has the small cost that our
1139  * representation uses one more K_i, due to carries.
1140  *
1141  * Also, for the sake of compactness, only the seven low-order bits of x[i]
1142  * are used to represent K_i, and the msb of x[i] encodes the the sign (s_i in
1143  * the paper): it is set if and only if if s_i == -1;
1144  *
1145  * Calling conventions:
1146  * - x is an array of size d + 1
1147  * - w is the size, ie number of teeth, of the comb, and must be between
1148  *   2 and 7 (in practice, between 2 and MBEDTLS_ECP_WINDOW_SIZE)
1149  * - m is the MPI, expected to be odd and such that bitlength(m) <= w * d
1150  *   (the result will be incorrect if these assumptions are not satisfied)
1151  */
ecp_comb_fixed(unsigned char x[],size_t d,unsigned char w,const mbedtls_mpi * m)1152 static void ecp_comb_fixed( unsigned char x[], size_t d,
1153                             unsigned char w, const mbedtls_mpi *m )
1154 {
1155     size_t i, j;
1156     unsigned char c, cc, adjust;
1157 
1158     memset( x, 0, d+1 );
1159 
1160     /* First get the classical comb values (except for x_d = 0) */
1161     for( i = 0; i < d; i++ )
1162         for( j = 0; j < w; j++ )
1163             x[i] |= mbedtls_mpi_get_bit( m, i + d * j ) << j;
1164 
1165     /* Now make sure x_1 .. x_d are odd */
1166     c = 0;
1167     for( i = 1; i <= d; i++ )
1168     {
1169         /* Add carry and update it */
1170         cc   = x[i] & c;
1171         x[i] = x[i] ^ c;
1172         c = cc;
1173 
1174         /* Adjust if needed, avoiding branches */
1175         adjust = 1 - ( x[i] & 0x01 );
1176         c   |= x[i] & ( x[i-1] * adjust );
1177         x[i] = x[i] ^ ( x[i-1] * adjust );
1178         x[i-1] |= adjust << 7;
1179     }
1180 }
1181 
1182 /*
1183  * Precompute points for the comb method
1184  *
1185  * If i = i_{w-1} ... i_1 is the binary representation of i, then
1186  * T[i] = i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + P
1187  *
1188  * T must be able to hold 2^{w - 1} elements
1189  *
1190  * Cost: d(w-1) D + (2^{w-1} - 1) A + 1 N(w-1) + 1 N(2^{w-1} - 1)
1191  */
ecp_precompute_comb(const mbedtls_ecp_group * grp,mbedtls_ecp_point T[],const mbedtls_ecp_point * P,unsigned char w,size_t d)1192 static int ecp_precompute_comb( const mbedtls_ecp_group *grp,
1193                                 mbedtls_ecp_point T[], const mbedtls_ecp_point *P,
1194                                 unsigned char w, size_t d )
1195 {
1196     int ret;
1197     unsigned char i, k;
1198     size_t j;
1199     mbedtls_ecp_point *cur, *TT[COMB_MAX_PRE - 1];
1200 
1201     /*
1202      * Set T[0] = P and
1203      * T[2^{l-1}] = 2^{dl} P for l = 1 .. w-1 (this is not the final value)
1204      */
1205     MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &T[0], P ) );
1206 
1207     k = 0;
1208     for( i = 1; i < ( 1U << ( w - 1 ) ); i <<= 1 )
1209     {
1210         cur = T + i;
1211         MBEDTLS_MPI_CHK( mbedtls_ecp_copy( cur, T + ( i >> 1 ) ) );
1212         for( j = 0; j < d; j++ )
1213             MBEDTLS_MPI_CHK( ecp_double_jac( grp, cur, cur ) );
1214 
1215         TT[k++] = cur;
1216     }
1217 
1218     MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, k ) );
1219 
1220     /*
1221      * Compute the remaining ones using the minimal number of additions
1222      * Be careful to update T[2^l] only after using it!
1223      */
1224     k = 0;
1225     for( i = 1; i < ( 1U << ( w - 1 ) ); i <<= 1 )
1226     {
1227         j = i;
1228         while( j-- )
1229         {
1230             MBEDTLS_MPI_CHK( ecp_add_mixed( grp, &T[i + j], &T[j], &T[i] ) );
1231             TT[k++] = &T[i + j];
1232         }
1233     }
1234 
1235     MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, k ) );
1236 
1237 cleanup:
1238     return( ret );
1239 }
1240 
1241 /*
1242  * Select precomputed point: R = sign(i) * T[ abs(i) / 2 ]
1243  */
ecp_select_comb(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_ecp_point T[],unsigned char t_len,unsigned char i)1244 static int ecp_select_comb( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1245                             const mbedtls_ecp_point T[], unsigned char t_len,
1246                             unsigned char i )
1247 {
1248     int ret;
1249     unsigned char ii, j;
1250 
1251     /* Ignore the "sign" bit and scale down */
1252     ii =  ( i & 0x7Fu ) >> 1;
1253 
1254     /* Read the whole table to thwart cache-based timing attacks */
1255     for( j = 0; j < t_len; j++ )
1256     {
1257         MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &R->X, &T[j].X, j == ii ) );
1258         MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &R->Y, &T[j].Y, j == ii ) );
1259     }
1260 
1261     /* Safely invert result if i is "negative" */
1262     MBEDTLS_MPI_CHK( ecp_safe_invert_jac( grp, R, i >> 7 ) );
1263 
1264 cleanup:
1265     return( ret );
1266 }
1267 
1268 /*
1269  * Core multiplication algorithm for the (modified) comb method.
1270  * This part is actually common with the basic comb method (GECC 3.44)
1271  *
1272  * Cost: d A + d D + 1 R
1273  */
ecp_mul_comb_core(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_ecp_point T[],unsigned char t_len,const unsigned char x[],size_t d,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1274 static int ecp_mul_comb_core( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1275                               const mbedtls_ecp_point T[], unsigned char t_len,
1276                               const unsigned char x[], size_t d,
1277                               int (*f_rng)(void *, unsigned char *, size_t),
1278                               void *p_rng )
1279 {
1280     int ret;
1281     mbedtls_ecp_point Txi;
1282     size_t i;
1283 
1284     mbedtls_ecp_point_init( &Txi );
1285 
1286     /* Start with a non-zero point and randomize its coordinates */
1287     i = d;
1288     MBEDTLS_MPI_CHK( ecp_select_comb( grp, R, T, t_len, x[i] ) );
1289     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->Z, 1 ) );
1290     if( f_rng != 0 )
1291         MBEDTLS_MPI_CHK( ecp_randomize_jac( grp, R, f_rng, p_rng ) );
1292 
1293     while( i-- != 0 )
1294     {
1295         MBEDTLS_MPI_CHK( ecp_double_jac( grp, R, R ) );
1296         MBEDTLS_MPI_CHK( ecp_select_comb( grp, &Txi, T, t_len, x[i] ) );
1297         MBEDTLS_MPI_CHK( ecp_add_mixed( grp, R, R, &Txi ) );
1298     }
1299 
1300 cleanup:
1301     mbedtls_ecp_point_free( &Txi );
1302 
1303     return( ret );
1304 }
1305 
1306 /*
1307  * Multiplication using the comb method,
1308  * for curves in short Weierstrass form
1309  */
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)1310 static int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1311                          const mbedtls_mpi *m, const mbedtls_ecp_point *P,
1312                          int (*f_rng)(void *, unsigned char *, size_t),
1313                          void *p_rng )
1314 {
1315     int ret;
1316     unsigned char w, m_is_odd, p_eq_g, pre_len, i;
1317     size_t d;
1318     unsigned char k[COMB_MAX_D + 1];
1319     mbedtls_ecp_point *T;
1320     mbedtls_mpi M, mm;
1321 
1322     mbedtls_mpi_init( &M );
1323     mbedtls_mpi_init( &mm );
1324 
1325     /* we need N to be odd to trnaform m in an odd number, check now */
1326     if( mbedtls_mpi_get_bit( &grp->N, 0 ) != 1 )
1327         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1328 
1329     /*
1330      * Minimize the number of multiplications, that is minimize
1331      * 10 * d * w + 18 * 2^(w-1) + 11 * d + 7 * w, with d = ceil( nbits / w )
1332      * (see costs of the various parts, with 1S = 1M)
1333      */
1334     w = grp->nbits >= 384 ? 5 : 4;
1335 
1336     /*
1337      * If P == G, pre-compute a bit more, since this may be re-used later.
1338      * Just adding one avoids upping the cost of the first mul too much,
1339      * and the memory cost too.
1340      */
1341 #if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1
1342     p_eq_g = ( mbedtls_mpi_cmp_mpi( &P->Y, &grp->G.Y ) == 0 &&
1343                mbedtls_mpi_cmp_mpi( &P->X, &grp->G.X ) == 0 );
1344     if( p_eq_g )
1345         w++;
1346 #else
1347     p_eq_g = 0;
1348 #endif
1349 
1350     /*
1351      * Make sure w is within bounds.
1352      * (The last test is useful only for very small curves in the test suite.)
1353      */
1354     if( w > MBEDTLS_ECP_WINDOW_SIZE )
1355         w = MBEDTLS_ECP_WINDOW_SIZE;
1356     if( w >= grp->nbits )
1357         w = 2;
1358 
1359     /* Other sizes that depend on w */
1360     pre_len = 1U << ( w - 1 );
1361     d = ( grp->nbits + w - 1 ) / w;
1362 
1363     /*
1364      * Prepare precomputed points: if P == G we want to
1365      * use grp->T if already initialized, or initialize it.
1366      */
1367     T = p_eq_g ? grp->T : NULL;
1368 
1369     if( T == NULL )
1370     {
1371         T = mbedtls_calloc( pre_len, sizeof( mbedtls_ecp_point ) );
1372         if( T == NULL )
1373         {
1374             ret = MBEDTLS_ERR_ECP_ALLOC_FAILED;
1375             goto cleanup;
1376         }
1377 
1378         MBEDTLS_MPI_CHK( ecp_precompute_comb( grp, T, P, w, d ) );
1379 
1380         if( p_eq_g )
1381         {
1382             grp->T = T;
1383             grp->T_size = pre_len;
1384         }
1385     }
1386 
1387     /*
1388      * Make sure M is odd (M = m or M = N - m, since N is odd)
1389      * using the fact that m * P = - (N - m) * P
1390      */
1391     m_is_odd = ( mbedtls_mpi_get_bit( m, 0 ) == 1 );
1392     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &M, m ) );
1393     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &mm, &grp->N, m ) );
1394     MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &M, &mm, ! m_is_odd ) );
1395 
1396     /*
1397      * Go for comb multiplication, R = M * P
1398      */
1399     ecp_comb_fixed( k, d, w, &M );
1400     MBEDTLS_MPI_CHK( ecp_mul_comb_core( grp, R, T, pre_len, k, d, f_rng, p_rng ) );
1401 
1402     /*
1403      * Now get m * P from M * P and normalize it
1404      */
1405     MBEDTLS_MPI_CHK( ecp_safe_invert_jac( grp, R, ! m_is_odd ) );
1406     MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, R ) );
1407 
1408 cleanup:
1409 
1410     if( T != NULL && ! p_eq_g )
1411     {
1412         for( i = 0; i < pre_len; i++ )
1413             mbedtls_ecp_point_free( &T[i] );
1414         mbedtls_free( T );
1415     }
1416 
1417     mbedtls_mpi_free( &M );
1418     mbedtls_mpi_free( &mm );
1419 
1420     if( ret != 0 )
1421         mbedtls_ecp_point_free( R );
1422 
1423     return( ret );
1424 }
1425 
1426 #endif /* ECP_SHORTWEIERSTRASS */
1427 
1428 #if defined(ECP_MONTGOMERY)
1429 /*
1430  * For Montgomery curves, we do all the internal arithmetic in projective
1431  * coordinates. Import/export of points uses only the x coordinates, which is
1432  * internaly represented as X / Z.
1433  *
1434  * For scalar multiplication, we'll use a Montgomery ladder.
1435  */
1436 
1437 /*
1438  * Normalize Montgomery x/z coordinates: X = X/Z, Z = 1
1439  * Cost: 1M + 1I
1440  */
ecp_normalize_mxz(const mbedtls_ecp_group * grp,mbedtls_ecp_point * P)1441 static int ecp_normalize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P )
1442 {
1443     int ret;
1444 
1445     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &P->Z, &P->Z, &grp->P ) );
1446     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &P->X, &P->X, &P->Z ) ); MOD_MUL( P->X );
1447     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &P->Z, 1 ) );
1448 
1449 cleanup:
1450     return( ret );
1451 }
1452 
1453 /*
1454  * Randomize projective x/z coordinates:
1455  * (X, Z) -> (l X, l Z) for random l
1456  * This is sort of the reverse operation of ecp_normalize_mxz().
1457  *
1458  * This countermeasure was first suggested in [2].
1459  * Cost: 2M
1460  */
ecp_randomize_mxz(const mbedtls_ecp_group * grp,mbedtls_ecp_point * P,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1461 static int ecp_randomize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P,
1462                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
1463 {
1464     int ret;
1465     mbedtls_mpi l;
1466     size_t p_size = ( grp->pbits + 7 ) / 8;
1467     int count = 0;
1468 
1469     mbedtls_mpi_init( &l );
1470 
1471     /* Generate l such that 1 < l < p */
1472     do
1473     {
1474         mbedtls_mpi_fill_random( &l, p_size, f_rng, p_rng );
1475 
1476         while( mbedtls_mpi_cmp_mpi( &l, &grp->P ) >= 0 )
1477             MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &l, 1 ) );
1478 
1479         if( count++ > 10 )
1480             return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
1481     }
1482     while( mbedtls_mpi_cmp_int( &l, 1 ) <= 0 );
1483 
1484     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &P->X, &P->X, &l ) ); MOD_MUL( P->X );
1485     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &P->Z, &P->Z, &l ) ); MOD_MUL( P->Z );
1486 
1487 cleanup:
1488     mbedtls_mpi_free( &l );
1489 
1490     return( ret );
1491 }
1492 
1493 /*
1494  * Double-and-add: R = 2P, S = P + Q, with d = X(P - Q),
1495  * for Montgomery curves in x/z coordinates.
1496  *
1497  * http://www.hyperelliptic.org/EFD/g1p/auto-code/montgom/xz/ladder/mladd-1987-m.op3
1498  * with
1499  * d =  X1
1500  * P = (X2, Z2)
1501  * Q = (X3, Z3)
1502  * R = (X4, Z4)
1503  * S = (X5, Z5)
1504  * and eliminating temporary variables tO, ..., t4.
1505  *
1506  * Cost: 5M + 4S
1507  */
ecp_double_add_mxz(const mbedtls_ecp_group * grp,mbedtls_ecp_point * R,mbedtls_ecp_point * S,const mbedtls_ecp_point * P,const mbedtls_ecp_point * Q,const mbedtls_mpi * d)1508 static int ecp_double_add_mxz( const mbedtls_ecp_group *grp,
1509                                mbedtls_ecp_point *R, mbedtls_ecp_point *S,
1510                                const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q,
1511                                const mbedtls_mpi *d )
1512 {
1513     int ret;
1514     mbedtls_mpi A, AA, B, BB, E, C, D, DA, CB;
1515 
1516     mbedtls_mpi_init( &A ); mbedtls_mpi_init( &AA ); mbedtls_mpi_init( &B );
1517     mbedtls_mpi_init( &BB ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &C );
1518     mbedtls_mpi_init( &D ); mbedtls_mpi_init( &DA ); mbedtls_mpi_init( &CB );
1519 
1520     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &A,    &P->X,   &P->Z ) ); MOD_ADD( A    );
1521     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &AA,   &A,      &A    ) ); MOD_MUL( AA   );
1522     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &B,    &P->X,   &P->Z ) ); MOD_SUB( B    );
1523     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &BB,   &B,      &B    ) ); MOD_MUL( BB   );
1524     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &E,    &AA,     &BB   ) ); MOD_SUB( E    );
1525     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &C,    &Q->X,   &Q->Z ) ); MOD_ADD( C    );
1526     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &D,    &Q->X,   &Q->Z ) ); MOD_SUB( D    );
1527     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &DA,   &D,      &A    ) ); MOD_MUL( DA   );
1528     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &CB,   &C,      &B    ) ); MOD_MUL( CB   );
1529     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &S->X, &DA,     &CB   ) ); MOD_MUL( S->X );
1530     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S->X, &S->X,   &S->X ) ); MOD_MUL( S->X );
1531     MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &S->Z, &DA,     &CB   ) ); MOD_SUB( S->Z );
1532     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S->Z, &S->Z,   &S->Z ) ); MOD_MUL( S->Z );
1533     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &S->Z, d,       &S->Z ) ); MOD_MUL( S->Z );
1534     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &R->X, &AA,     &BB   ) ); MOD_MUL( R->X );
1535     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &R->Z, &grp->A, &E    ) ); MOD_MUL( R->Z );
1536     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &R->Z, &BB,     &R->Z ) ); MOD_ADD( R->Z );
1537     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &R->Z, &E,      &R->Z ) ); MOD_MUL( R->Z );
1538 
1539 cleanup:
1540     mbedtls_mpi_free( &A ); mbedtls_mpi_free( &AA ); mbedtls_mpi_free( &B );
1541     mbedtls_mpi_free( &BB ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &C );
1542     mbedtls_mpi_free( &D ); mbedtls_mpi_free( &DA ); mbedtls_mpi_free( &CB );
1543 
1544     return( ret );
1545 }
1546 
1547 /*
1548  * Multiplication with Montgomery ladder in x/z coordinates,
1549  * for curves in Montgomery form
1550  */
ecp_mul_mxz(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1551 static int ecp_mul_mxz( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1552                         const mbedtls_mpi *m, const mbedtls_ecp_point *P,
1553                         int (*f_rng)(void *, unsigned char *, size_t),
1554                         void *p_rng )
1555 {
1556     int ret;
1557     size_t i;
1558     unsigned char b;
1559     mbedtls_ecp_point RP;
1560     mbedtls_mpi PX;
1561 
1562     mbedtls_ecp_point_init( &RP ); mbedtls_mpi_init( &PX );
1563 
1564     /* Save PX and read from P before writing to R, in case P == R */
1565     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &PX, &P->X ) );
1566     MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &RP, P ) );
1567 
1568     /* Set R to zero in modified x/z coordinates */
1569     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->X, 1 ) );
1570     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->Z, 0 ) );
1571     mbedtls_mpi_free( &R->Y );
1572 
1573     /* RP.X might be sligtly larger than P, so reduce it */
1574     MOD_ADD( RP.X );
1575 
1576     /* Randomize coordinates of the starting point */
1577     if( f_rng != NULL )
1578         MBEDTLS_MPI_CHK( ecp_randomize_mxz( grp, &RP, f_rng, p_rng ) );
1579 
1580     /* Loop invariant: R = result so far, RP = R + P */
1581     i = mbedtls_mpi_bitlen( m ); /* one past the (zero-based) most significant bit */
1582     while( i-- > 0 )
1583     {
1584         b = mbedtls_mpi_get_bit( m, i );
1585         /*
1586          *  if (b) R = 2R + P else R = 2R,
1587          * which is:
1588          *  if (b) double_add( RP, R, RP, R )
1589          *  else   double_add( R, RP, R, RP )
1590          * but using safe conditional swaps to avoid leaks
1591          */
1592         MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->X, &RP.X, b ) );
1593         MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->Z, &RP.Z, b ) );
1594         MBEDTLS_MPI_CHK( ecp_double_add_mxz( grp, R, &RP, R, &RP, &PX ) );
1595         MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->X, &RP.X, b ) );
1596         MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->Z, &RP.Z, b ) );
1597     }
1598 
1599     MBEDTLS_MPI_CHK( ecp_normalize_mxz( grp, R ) );
1600 
1601 cleanup:
1602     mbedtls_ecp_point_free( &RP ); mbedtls_mpi_free( &PX );
1603 
1604     return( ret );
1605 }
1606 
1607 #endif /* ECP_MONTGOMERY */
1608 
1609 /*
1610  * Multiplication R = m * P
1611  */
mbedtls_ecp_mul(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1612 int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1613              const mbedtls_mpi *m, const mbedtls_ecp_point *P,
1614              int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
1615 {
1616     int ret;
1617 
1618     /* Common sanity checks */
1619     if( mbedtls_mpi_cmp_int( &P->Z, 1 ) != 0 )
1620         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1621 
1622     if( ( ret = mbedtls_ecp_check_privkey( grp, m ) ) != 0 ||
1623         ( ret = mbedtls_ecp_check_pubkey( grp, P ) ) != 0 )
1624         return( ret );
1625 
1626 #if defined(ECP_MONTGOMERY)
1627     if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )
1628         return( ecp_mul_mxz( grp, R, m, P, f_rng, p_rng ) );
1629 #endif
1630 #if defined(ECP_SHORTWEIERSTRASS)
1631     if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )
1632         return( ecp_mul_comb( grp, R, m, P, f_rng, p_rng ) );
1633 #endif
1634     return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1635 }
1636 
1637 #if defined(ECP_SHORTWEIERSTRASS)
1638 /*
1639  * Check that an affine point is valid as a public key,
1640  * short weierstrass curves (SEC1 3.2.3.1)
1641  */
ecp_check_pubkey_sw(const mbedtls_ecp_group * grp,const mbedtls_ecp_point * pt)1642 static int ecp_check_pubkey_sw( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt )
1643 {
1644     int ret;
1645     mbedtls_mpi YY, RHS;
1646 
1647     /* pt coordinates must be normalized for our checks */
1648     if( mbedtls_mpi_cmp_int( &pt->X, 0 ) < 0 ||
1649         mbedtls_mpi_cmp_int( &pt->Y, 0 ) < 0 ||
1650         mbedtls_mpi_cmp_mpi( &pt->X, &grp->P ) >= 0 ||
1651         mbedtls_mpi_cmp_mpi( &pt->Y, &grp->P ) >= 0 )
1652         return( MBEDTLS_ERR_ECP_INVALID_KEY );
1653 
1654     mbedtls_mpi_init( &YY ); mbedtls_mpi_init( &RHS );
1655 
1656     /*
1657      * YY = Y^2
1658      * RHS = X (X^2 + A) + B = X^3 + A X + B
1659      */
1660     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &YY,  &pt->Y,   &pt->Y  ) );  MOD_MUL( YY  );
1661     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &RHS, &pt->X,   &pt->X  ) );  MOD_MUL( RHS );
1662 
1663     /* Special case for A = -3 */
1664     if( grp->A.p == NULL )
1665     {
1666         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &RHS, &RHS, 3       ) );  MOD_SUB( RHS );
1667     }
1668     else
1669     {
1670         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &RHS, &RHS, &grp->A ) );  MOD_ADD( RHS );
1671     }
1672 
1673     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &RHS, &RHS,     &pt->X  ) );  MOD_MUL( RHS );
1674     MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &RHS, &RHS,     &grp->B ) );  MOD_ADD( RHS );
1675 
1676     if( mbedtls_mpi_cmp_mpi( &YY, &RHS ) != 0 )
1677         ret = MBEDTLS_ERR_ECP_INVALID_KEY;
1678 
1679 cleanup:
1680 
1681     mbedtls_mpi_free( &YY ); mbedtls_mpi_free( &RHS );
1682 
1683     return( ret );
1684 }
1685 #endif /* ECP_SHORTWEIERSTRASS */
1686 
1687 /*
1688  * R = m * P with shortcuts for m == 1 and m == -1
1689  * NOT constant-time - ONLY for short Weierstrass!
1690  */
mbedtls_ecp_mul_shortcuts(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P)1691 static int mbedtls_ecp_mul_shortcuts( mbedtls_ecp_group *grp,
1692                                       mbedtls_ecp_point *R,
1693                                       const mbedtls_mpi *m,
1694                                       const mbedtls_ecp_point *P )
1695 {
1696     int ret;
1697 
1698     if( mbedtls_mpi_cmp_int( m, 1 ) == 0 )
1699     {
1700         MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) );
1701     }
1702     else if( mbedtls_mpi_cmp_int( m, -1 ) == 0 )
1703     {
1704         MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) );
1705         if( mbedtls_mpi_cmp_int( &R->Y, 0 ) != 0 )
1706             MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &R->Y, &grp->P, &R->Y ) );
1707     }
1708     else
1709     {
1710         MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, R, m, P, NULL, NULL ) );
1711     }
1712 
1713 cleanup:
1714     return( ret );
1715 }
1716 
1717 /*
1718  * Linear combination
1719  * NOT constant-time
1720  */
mbedtls_ecp_muladd(mbedtls_ecp_group * grp,mbedtls_ecp_point * R,const mbedtls_mpi * m,const mbedtls_ecp_point * P,const mbedtls_mpi * n,const mbedtls_ecp_point * Q)1721 int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
1722              const mbedtls_mpi *m, const mbedtls_ecp_point *P,
1723              const mbedtls_mpi *n, const mbedtls_ecp_point *Q )
1724 {
1725     int ret;
1726     mbedtls_ecp_point mP;
1727 
1728     if( ecp_get_type( grp ) != ECP_TYPE_SHORT_WEIERSTRASS )
1729         return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
1730 
1731     mbedtls_ecp_point_init( &mP );
1732 
1733     MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, &mP, m, P ) );
1734     MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, R,   n, Q ) );
1735 
1736     MBEDTLS_MPI_CHK( ecp_add_mixed( grp, R, &mP, R ) );
1737     MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, R ) );
1738 
1739 cleanup:
1740     mbedtls_ecp_point_free( &mP );
1741 
1742     return( ret );
1743 }
1744 
1745 
1746 #if defined(ECP_MONTGOMERY)
1747 /*
1748  * Check validity of a public key for Montgomery curves with x-only schemes
1749  */
ecp_check_pubkey_mx(const mbedtls_ecp_group * grp,const mbedtls_ecp_point * pt)1750 static int ecp_check_pubkey_mx( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt )
1751 {
1752     /* [Curve25519 p. 5] Just check X is the correct number of bytes */
1753     if( mbedtls_mpi_size( &pt->X ) > ( grp->nbits + 7 ) / 8 )
1754         return( MBEDTLS_ERR_ECP_INVALID_KEY );
1755 
1756     return( 0 );
1757 }
1758 #endif /* ECP_MONTGOMERY */
1759 
1760 /*
1761  * Check that a point is valid as a public key
1762  */
mbedtls_ecp_check_pubkey(const mbedtls_ecp_group * grp,const mbedtls_ecp_point * pt)1763 int mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt )
1764 {
1765     /* Must use affine coordinates */
1766     if( mbedtls_mpi_cmp_int( &pt->Z, 1 ) != 0 )
1767         return( MBEDTLS_ERR_ECP_INVALID_KEY );
1768 
1769 #if defined(ECP_MONTGOMERY)
1770     if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )
1771         return( ecp_check_pubkey_mx( grp, pt ) );
1772 #endif
1773 #if defined(ECP_SHORTWEIERSTRASS)
1774     if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )
1775         return( ecp_check_pubkey_sw( grp, pt ) );
1776 #endif
1777     return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1778 }
1779 
1780 /*
1781  * Check that an mbedtls_mpi is valid as a private key
1782  */
mbedtls_ecp_check_privkey(const mbedtls_ecp_group * grp,const mbedtls_mpi * d)1783 int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, const mbedtls_mpi *d )
1784 {
1785 #if defined(ECP_MONTGOMERY)
1786     if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )
1787     {
1788         /* see [Curve25519] page 5 */
1789         if( mbedtls_mpi_get_bit( d, 0 ) != 0 ||
1790             mbedtls_mpi_get_bit( d, 1 ) != 0 ||
1791             mbedtls_mpi_get_bit( d, 2 ) != 0 ||
1792             mbedtls_mpi_bitlen( d ) - 1 != grp->nbits ) /* mbedtls_mpi_bitlen is one-based! */
1793             return( MBEDTLS_ERR_ECP_INVALID_KEY );
1794         else
1795             return( 0 );
1796     }
1797 #endif /* ECP_MONTGOMERY */
1798 #if defined(ECP_SHORTWEIERSTRASS)
1799     if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )
1800     {
1801         /* see SEC1 3.2 */
1802         if( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||
1803             mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
1804             return( MBEDTLS_ERR_ECP_INVALID_KEY );
1805         else
1806             return( 0 );
1807     }
1808 #endif /* ECP_SHORTWEIERSTRASS */
1809 
1810     return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1811 }
1812 
1813 /*
1814  * Generate a keypair with configurable base point
1815  */
mbedtls_ecp_gen_keypair_base(mbedtls_ecp_group * grp,const mbedtls_ecp_point * G,mbedtls_mpi * d,mbedtls_ecp_point * Q,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1816 int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
1817                      const mbedtls_ecp_point *G,
1818                      mbedtls_mpi *d, mbedtls_ecp_point *Q,
1819                      int (*f_rng)(void *, unsigned char *, size_t),
1820                      void *p_rng )
1821 {
1822     int ret;
1823     size_t n_size = ( grp->nbits + 7 ) / 8;
1824 
1825 #if defined(ECP_MONTGOMERY)
1826     if( ecp_get_type( grp ) == ECP_TYPE_MONTGOMERY )
1827     {
1828         /* [M225] page 5 */
1829         size_t b;
1830 
1831         do {
1832             MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_size, f_rng, p_rng ) );
1833         } while( mbedtls_mpi_bitlen( d ) == 0);
1834 
1835         /* Make sure the most significant bit is nbits */
1836         b = mbedtls_mpi_bitlen( d ) - 1; /* mbedtls_mpi_bitlen is one-based */
1837         if( b > grp->nbits )
1838             MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, b - grp->nbits ) );
1839         else
1840             MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, grp->nbits, 1 ) );
1841 
1842         /* Make sure the last three bits are unset */
1843         MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );
1844         MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );
1845         MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );
1846     }
1847     else
1848 #endif /* ECP_MONTGOMERY */
1849 #if defined(ECP_SHORTWEIERSTRASS)
1850     if( ecp_get_type( grp ) == ECP_TYPE_SHORT_WEIERSTRASS )
1851     {
1852         /* SEC1 3.2.1: Generate d such that 1 <= n < N */
1853         int count = 0;
1854         unsigned char rnd[MBEDTLS_ECP_MAX_BYTES];
1855 
1856         /*
1857          * Match the procedure given in RFC 6979 (deterministic ECDSA):
1858          * - use the same byte ordering;
1859          * - keep the leftmost nbits bits of the generated octet string;
1860          * - try until result is in the desired range.
1861          * This also avoids any biais, which is especially important for ECDSA.
1862          */
1863         do
1864         {
1865             MBEDTLS_MPI_CHK( f_rng( p_rng, rnd, n_size ) );
1866             MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( d, rnd, n_size ) );
1867             MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_size - grp->nbits ) );
1868 
1869             /*
1870              * Each try has at worst a probability 1/2 of failing (the msb has
1871              * a probability 1/2 of being 0, and then the result will be < N),
1872              * so after 30 tries failure probability is a most 2**(-30).
1873              *
1874              * For most curves, 1 try is enough with overwhelming probability,
1875              * since N starts with a lot of 1s in binary, but some curves
1876              * such as secp224k1 are actually very close to the worst case.
1877              */
1878             if( ++count > 30 )
1879                 return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
1880         }
1881         while( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||
1882                mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 );
1883     }
1884     else
1885 #endif /* ECP_SHORTWEIERSTRASS */
1886         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1887 
1888 cleanup:
1889     if( ret != 0 )
1890         return( ret );
1891 
1892     return( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) );
1893 }
1894 
1895 /*
1896  * Generate key pair, wrapper for conventional base point
1897  */
mbedtls_ecp_gen_keypair(mbedtls_ecp_group * grp,mbedtls_mpi * d,mbedtls_ecp_point * Q,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1898 int mbedtls_ecp_gen_keypair( mbedtls_ecp_group *grp,
1899                              mbedtls_mpi *d, mbedtls_ecp_point *Q,
1900                              int (*f_rng)(void *, unsigned char *, size_t),
1901                              void *p_rng )
1902 {
1903     return( mbedtls_ecp_gen_keypair_base( grp, &grp->G, d, Q, f_rng, p_rng ) );
1904 }
1905 
1906 /*
1907  * Generate a keypair, prettier wrapper
1908  */
mbedtls_ecp_gen_key(mbedtls_ecp_group_id grp_id,mbedtls_ecp_keypair * key,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)1909 int mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
1910                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
1911 {
1912     int ret;
1913 
1914     if( ( ret = mbedtls_ecp_group_load( &key->grp, grp_id ) ) != 0 )
1915         return( ret );
1916 
1917     return( mbedtls_ecp_gen_keypair( &key->grp, &key->d, &key->Q, f_rng, p_rng ) );
1918 }
1919 
1920 /*
1921  * Check a public-private key pair
1922  */
mbedtls_ecp_check_pub_priv(const mbedtls_ecp_keypair * pub,const mbedtls_ecp_keypair * prv)1923 int mbedtls_ecp_check_pub_priv( const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv )
1924 {
1925     int ret;
1926     mbedtls_ecp_point Q;
1927     mbedtls_ecp_group grp;
1928 
1929     if( pub->grp.id == MBEDTLS_ECP_DP_NONE ||
1930         pub->grp.id != prv->grp.id ||
1931         mbedtls_mpi_cmp_mpi( &pub->Q.X, &prv->Q.X ) ||
1932         mbedtls_mpi_cmp_mpi( &pub->Q.Y, &prv->Q.Y ) ||
1933         mbedtls_mpi_cmp_mpi( &pub->Q.Z, &prv->Q.Z ) )
1934     {
1935         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
1936     }
1937 
1938     mbedtls_ecp_point_init( &Q );
1939     mbedtls_ecp_group_init( &grp );
1940 
1941     /* mbedtls_ecp_mul() needs a non-const group... */
1942     mbedtls_ecp_group_copy( &grp, &prv->grp );
1943 
1944     /* Also checks d is valid */
1945     MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &Q, &prv->d, &prv->grp.G, NULL, NULL ) );
1946 
1947     if( mbedtls_mpi_cmp_mpi( &Q.X, &prv->Q.X ) ||
1948         mbedtls_mpi_cmp_mpi( &Q.Y, &prv->Q.Y ) ||
1949         mbedtls_mpi_cmp_mpi( &Q.Z, &prv->Q.Z ) )
1950     {
1951         ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
1952         goto cleanup;
1953     }
1954 
1955 cleanup:
1956     mbedtls_ecp_point_free( &Q );
1957     mbedtls_ecp_group_free( &grp );
1958 
1959     return( ret );
1960 }
1961 
1962 
1963 #if defined(MBEDTLS_SELF_TEST)
1964 
1965 /*
1966  * Checkup routine
1967  */
mbedtls_ecp_self_test(int verbose)1968 int mbedtls_ecp_self_test( int verbose )
1969 {
1970     int ret;
1971     size_t i;
1972     mbedtls_ecp_group grp;
1973     mbedtls_ecp_point R, P;
1974     mbedtls_mpi m;
1975     unsigned long add_c_prev, dbl_c_prev, mul_c_prev;
1976 
1977     /* exponents especially adapted for secp192r1 */
1978     const char *exponents[] =
1979     {
1980         "000000000000000000000000000000000000000000000001", /* one */
1981         "FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22830", /* N - 1 */
1982         "5EA6F389A38B8BC81E767753B15AA5569E1782E30ABE7D25", /* random */
1983         "400000000000000000000000000000000000000000000000", /* one and zeros */
1984         "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* all ones */
1985         "555555555555555555555555555555555555555555555555", /* 101010... */
1986     };
1987 
1988     mbedtls_ecp_group_init( &grp );
1989     mbedtls_ecp_point_init( &R );
1990     mbedtls_ecp_point_init( &P );
1991     mbedtls_mpi_init( &m );
1992 
1993     /* Use secp192r1 if available, or any available curve */
1994 #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
1995     MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_SECP192R1 ) );
1996 #else
1997     MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, mbedtls_ecp_curve_list()->grp_id ) );
1998 #endif
1999 
2000     if( verbose != 0 )
2001         mbedtls_printf( "  ECP test #1 (constant op_count, base point G): " );
2002 
2003     /* Do a dummy multiplication first to trigger precomputation */
2004     MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &m, 2 ) );
2005     MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &P, &m, &grp.G, NULL, NULL ) );
2006 
2007     add_count = 0;
2008     dbl_count = 0;
2009     mul_count = 0;
2010     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[0] ) );
2011     MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &grp.G, NULL, NULL ) );
2012 
2013     for( i = 1; i < sizeof( exponents ) / sizeof( exponents[0] ); i++ )
2014     {
2015         add_c_prev = add_count;
2016         dbl_c_prev = dbl_count;
2017         mul_c_prev = mul_count;
2018         add_count = 0;
2019         dbl_count = 0;
2020         mul_count = 0;
2021 
2022         MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[i] ) );
2023         MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &grp.G, NULL, NULL ) );
2024 
2025         if( add_count != add_c_prev ||
2026             dbl_count != dbl_c_prev ||
2027             mul_count != mul_c_prev )
2028         {
2029             if( verbose != 0 )
2030                 mbedtls_printf( "failed (%u)\n", (unsigned int) i );
2031 
2032             ret = 1;
2033             goto cleanup;
2034         }
2035     }
2036 
2037     if( verbose != 0 )
2038         mbedtls_printf( "passed\n" );
2039 
2040     if( verbose != 0 )
2041         mbedtls_printf( "  ECP test #2 (constant op_count, other point): " );
2042     /* We computed P = 2G last time, use it */
2043 
2044     add_count = 0;
2045     dbl_count = 0;
2046     mul_count = 0;
2047     MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[0] ) );
2048     MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &P, NULL, NULL ) );
2049 
2050     for( i = 1; i < sizeof( exponents ) / sizeof( exponents[0] ); i++ )
2051     {
2052         add_c_prev = add_count;
2053         dbl_c_prev = dbl_count;
2054         mul_c_prev = mul_count;
2055         add_count = 0;
2056         dbl_count = 0;
2057         mul_count = 0;
2058 
2059         MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &m, 16, exponents[i] ) );
2060         MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &R, &m, &P, NULL, NULL ) );
2061 
2062         if( add_count != add_c_prev ||
2063             dbl_count != dbl_c_prev ||
2064             mul_count != mul_c_prev )
2065         {
2066             if( verbose != 0 )
2067                 mbedtls_printf( "failed (%u)\n", (unsigned int) i );
2068 
2069             ret = 1;
2070             goto cleanup;
2071         }
2072     }
2073 
2074     if( verbose != 0 )
2075         mbedtls_printf( "passed\n" );
2076 
2077 cleanup:
2078 
2079     if( ret < 0 && verbose != 0 )
2080         mbedtls_printf( "Unexpected error, return code = %08X\n", ret );
2081 
2082     mbedtls_ecp_group_free( &grp );
2083     mbedtls_ecp_point_free( &R );
2084     mbedtls_ecp_point_free( &P );
2085     mbedtls_mpi_free( &m );
2086 
2087     if( verbose != 0 )
2088         mbedtls_printf( "\n" );
2089 
2090     return( ret );
2091 }
2092 
2093 #endif /* MBEDTLS_SELF_TEST */
2094 
2095 #endif /* MBEDTLS_ECP_C */
2096