xref: /optee_os/lib/libmbedtls/mbedtls/library/ecdsa.c (revision 5b25c76ac40f830867e3d60800120ffd7874e8dc)
1 // SPDX-License-Identifier: Apache-2.0
2 /*
3  *  Elliptic curve DSA
4  *
5  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  *
19  *  This file is part of mbed TLS (https://tls.mbed.org)
20  */
21 
22 /*
23  * References:
24  *
25  * SEC1 http://www.secg.org/index.php?action=secg,docs_secg
26  */
27 
28 #if !defined(MBEDTLS_CONFIG_FILE)
29 #include "mbedtls/config.h"
30 #else
31 #include MBEDTLS_CONFIG_FILE
32 #endif
33 
34 #if defined(MBEDTLS_ECDSA_C)
35 
36 #include "mbedtls/ecdsa.h"
37 #include "mbedtls/asn1write.h"
38 
39 #include <string.h>
40 
41 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
42 #include "mbedtls/hmac_drbg.h"
43 #endif
44 
45 #if defined(MBEDTLS_PLATFORM_C)
46 #include "mbedtls/platform.h"
47 #else
48 #include <stdlib.h>
49 #define mbedtls_calloc    calloc
50 #define mbedtls_free       free
51 #endif
52 
53 #include "mbedtls/platform_util.h"
54 
55 /* Parameter validation macros based on platform_util.h */
56 #define ECDSA_VALIDATE_RET( cond )    \
57     MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA )
58 #define ECDSA_VALIDATE( cond )        \
59     MBEDTLS_INTERNAL_VALIDATE( cond )
60 
61 #if defined(MBEDTLS_ECP_RESTARTABLE)
62 
63 /*
64  * Sub-context for ecdsa_verify()
65  */
66 struct mbedtls_ecdsa_restart_ver
67 {
68     mbedtls_mpi u1, u2;     /* intermediate values  */
69     enum {                  /* what to do next?     */
70         ecdsa_ver_init = 0, /* getting started      */
71         ecdsa_ver_muladd,   /* muladd step          */
72     } state;
73 };
74 
75 /*
76  * Init verify restart sub-context
77  */
78 static void ecdsa_restart_ver_init( mbedtls_ecdsa_restart_ver_ctx *ctx )
79 {
80     mbedtls_mpi_init( &ctx->u1 );
81     mbedtls_mpi_init( &ctx->u2 );
82     ctx->state = ecdsa_ver_init;
83 }
84 
85 /*
86  * Free the components of a verify restart sub-context
87  */
88 static void ecdsa_restart_ver_free( mbedtls_ecdsa_restart_ver_ctx *ctx )
89 {
90     if( ctx == NULL )
91         return;
92 
93     mbedtls_mpi_free( &ctx->u1 );
94     mbedtls_mpi_free( &ctx->u2 );
95 
96     ecdsa_restart_ver_init( ctx );
97 }
98 
99 /*
100  * Sub-context for ecdsa_sign()
101  */
102 struct mbedtls_ecdsa_restart_sig
103 {
104     int sign_tries;
105     int key_tries;
106     mbedtls_mpi k;          /* per-signature random */
107     mbedtls_mpi r;          /* r value              */
108     enum {                  /* what to do next?     */
109         ecdsa_sig_init = 0, /* getting started      */
110         ecdsa_sig_mul,      /* doing ecp_mul()      */
111         ecdsa_sig_modn,     /* mod N computations   */
112     } state;
113 };
114 
115 /*
116  * Init verify sign sub-context
117  */
118 static void ecdsa_restart_sig_init( mbedtls_ecdsa_restart_sig_ctx *ctx )
119 {
120     ctx->sign_tries = 0;
121     ctx->key_tries = 0;
122     mbedtls_mpi_init( &ctx->k );
123     mbedtls_mpi_init( &ctx->r );
124     ctx->state = ecdsa_sig_init;
125 }
126 
127 /*
128  * Free the components of a sign restart sub-context
129  */
130 static void ecdsa_restart_sig_free( mbedtls_ecdsa_restart_sig_ctx *ctx )
131 {
132     if( ctx == NULL )
133         return;
134 
135     mbedtls_mpi_free( &ctx->k );
136     mbedtls_mpi_free( &ctx->r );
137 }
138 
139 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
140 /*
141  * Sub-context for ecdsa_sign_det()
142  */
143 struct mbedtls_ecdsa_restart_det
144 {
145     mbedtls_hmac_drbg_context rng_ctx;  /* DRBG state   */
146     enum {                      /* what to do next?     */
147         ecdsa_det_init = 0,     /* getting started      */
148         ecdsa_det_sign,         /* make signature       */
149     } state;
150 };
151 
152 /*
153  * Init verify sign_det sub-context
154  */
155 static void ecdsa_restart_det_init( mbedtls_ecdsa_restart_det_ctx *ctx )
156 {
157     mbedtls_hmac_drbg_init( &ctx->rng_ctx );
158     ctx->state = ecdsa_det_init;
159 }
160 
161 /*
162  * Free the components of a sign_det restart sub-context
163  */
164 static void ecdsa_restart_det_free( mbedtls_ecdsa_restart_det_ctx *ctx )
165 {
166     if( ctx == NULL )
167         return;
168 
169     mbedtls_hmac_drbg_free( &ctx->rng_ctx );
170 
171     ecdsa_restart_det_init( ctx );
172 }
173 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
174 
175 #define ECDSA_RS_ECP    ( rs_ctx == NULL ? NULL : &rs_ctx->ecp )
176 
177 /* Utility macro for checking and updating ops budget */
178 #define ECDSA_BUDGET( ops )   \
179     MBEDTLS_MPI_CHK( mbedtls_ecp_check_budget( grp, ECDSA_RS_ECP, ops ) );
180 
181 /* Call this when entering a function that needs its own sub-context */
182 #define ECDSA_RS_ENTER( SUB )   do {                                 \
183     /* reset ops count for this call if top-level */                 \
184     if( rs_ctx != NULL && rs_ctx->ecp.depth++ == 0 )                 \
185         rs_ctx->ecp.ops_done = 0;                                    \
186                                                                      \
187     /* set up our own sub-context if needed */                       \
188     if( mbedtls_ecp_restart_is_enabled() &&                          \
189         rs_ctx != NULL && rs_ctx->SUB == NULL )                      \
190     {                                                                \
191         rs_ctx->SUB = mbedtls_calloc( 1, sizeof( *rs_ctx->SUB ) );   \
192         if( rs_ctx->SUB == NULL )                                    \
193             return( MBEDTLS_ERR_ECP_ALLOC_FAILED );                  \
194                                                                      \
195         ecdsa_restart_## SUB ##_init( rs_ctx->SUB );                 \
196     }                                                                \
197 } while( 0 )
198 
199 /* Call this when leaving a function that needs its own sub-context */
200 #define ECDSA_RS_LEAVE( SUB )   do {                                 \
201     /* clear our sub-context when not in progress (done or error) */ \
202     if( rs_ctx != NULL && rs_ctx->SUB != NULL &&                     \
203         ret != MBEDTLS_ERR_ECP_IN_PROGRESS )                         \
204     {                                                                \
205         ecdsa_restart_## SUB ##_free( rs_ctx->SUB );                 \
206         mbedtls_free( rs_ctx->SUB );                                 \
207         rs_ctx->SUB = NULL;                                          \
208     }                                                                \
209                                                                      \
210     if( rs_ctx != NULL )                                             \
211         rs_ctx->ecp.depth--;                                         \
212 } while( 0 )
213 
214 #else /* MBEDTLS_ECP_RESTARTABLE */
215 
216 #define ECDSA_RS_ECP    NULL
217 
218 #define ECDSA_BUDGET( ops )   /* no-op; for compatibility */
219 
220 #define ECDSA_RS_ENTER( SUB )   (void) rs_ctx
221 #define ECDSA_RS_LEAVE( SUB )   (void) rs_ctx
222 
223 #endif /* MBEDTLS_ECP_RESTARTABLE */
224 
225 /*
226  * Derive a suitable integer for group grp from a buffer of length len
227  * SEC1 4.1.3 step 5 aka SEC1 4.1.4 step 3
228  */
229 static int derive_mpi( const mbedtls_ecp_group *grp, mbedtls_mpi *x,
230                        const unsigned char *buf, size_t blen )
231 {
232     int ret;
233     size_t n_size = ( grp->nbits + 7 ) / 8;
234     size_t use_size = blen > n_size ? n_size : blen;
235 
236     MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( x, buf, use_size ) );
237     if( use_size * 8 > grp->nbits )
238         MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( x, use_size * 8 - grp->nbits ) );
239 
240     /* While at it, reduce modulo N */
241     if( mbedtls_mpi_cmp_mpi( x, &grp->N ) >= 0 )
242         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( x, x, &grp->N ) );
243 
244 cleanup:
245     return( ret );
246 }
247 
248 #if !defined(MBEDTLS_ECDSA_SIGN_ALT)
249 /*
250  * Compute ECDSA signature of a hashed message (SEC1 4.1.3)
251  * Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message)
252  */
253 static int ecdsa_sign_restartable( mbedtls_ecp_group *grp,
254                 mbedtls_mpi *r, mbedtls_mpi *s,
255                 const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
256                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
257                 int (*f_rng_blind)(void *, unsigned char *, size_t),
258                 void *p_rng_blind,
259                 mbedtls_ecdsa_restart_ctx *rs_ctx )
260 {
261     int ret, key_tries, sign_tries;
262     int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries;
263     mbedtls_ecp_point R;
264     mbedtls_mpi k, e, t;
265     mbedtls_mpi *pk = &k, *pr = r;
266 
267     /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
268     if( grp->N.p == NULL )
269         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
270 
271     /* Make sure d is in range 1..n-1 */
272     if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
273         return( MBEDTLS_ERR_ECP_INVALID_KEY );
274 
275     mbedtls_ecp_point_init( &R );
276     mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t );
277 
278     ECDSA_RS_ENTER( sig );
279 
280 #if defined(MBEDTLS_ECP_RESTARTABLE)
281     if( rs_ctx != NULL && rs_ctx->sig != NULL )
282     {
283         /* redirect to our context */
284         p_sign_tries = &rs_ctx->sig->sign_tries;
285         p_key_tries = &rs_ctx->sig->key_tries;
286         pk = &rs_ctx->sig->k;
287         pr = &rs_ctx->sig->r;
288 
289         /* jump to current step */
290         if( rs_ctx->sig->state == ecdsa_sig_mul )
291             goto mul;
292         if( rs_ctx->sig->state == ecdsa_sig_modn )
293             goto modn;
294     }
295 #endif /* MBEDTLS_ECP_RESTARTABLE */
296 
297     *p_sign_tries = 0;
298     do
299     {
300         if( (*p_sign_tries)++ > 10 )
301         {
302             ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
303             goto cleanup;
304         }
305 
306         /*
307          * Steps 1-3: generate a suitable ephemeral keypair
308          * and set r = xR mod n
309          */
310         *p_key_tries = 0;
311         do
312         {
313             if( (*p_key_tries)++ > 10 )
314             {
315                 ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
316                 goto cleanup;
317             }
318 
319             MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, pk, f_rng, p_rng ) );
320 
321 #if defined(MBEDTLS_ECP_RESTARTABLE)
322             if( rs_ctx != NULL && rs_ctx->sig != NULL )
323                 rs_ctx->sig->state = ecdsa_sig_mul;
324 
325 mul:
326 #endif
327             MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G,
328                                                           f_rng_blind,
329                                                           p_rng_blind,
330                                                           ECDSA_RS_ECP ) );
331             MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) );
332         }
333         while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 );
334 
335 #if defined(MBEDTLS_ECP_RESTARTABLE)
336         if( rs_ctx != NULL && rs_ctx->sig != NULL )
337             rs_ctx->sig->state = ecdsa_sig_modn;
338 
339 modn:
340 #endif
341         /*
342          * Accounting for everything up to the end of the loop
343          * (step 6, but checking now avoids saving e and t)
344          */
345         ECDSA_BUDGET( MBEDTLS_ECP_OPS_INV + 4 );
346 
347         /*
348          * Step 5: derive MPI from hashed message
349          */
350         MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
351 
352         /*
353          * Generate a random value to blind inv_mod in next step,
354          * avoiding a potential timing leak.
355          */
356         MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng_blind,
357                                                   p_rng_blind ) );
358 
359         /*
360          * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
361          */
362         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, pr, d ) );
363         MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) );
364         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) );
365         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) );
366         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pk, pk, &grp->N ) );
367         MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) );
368         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) );
369         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) );
370     }
371     while( mbedtls_mpi_cmp_int( s, 0 ) == 0 );
372 
373 #if defined(MBEDTLS_ECP_RESTARTABLE)
374     if( rs_ctx != NULL && rs_ctx->sig != NULL )
375         mbedtls_mpi_copy( r, pr );
376 #endif
377 
378 cleanup:
379     mbedtls_ecp_point_free( &R );
380     mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t );
381 
382     ECDSA_RS_LEAVE( sig );
383 
384     return( ret );
385 }
386 
387 /*
388  * Compute ECDSA signature of a hashed message
389  */
390 int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
391                 const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
392                 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
393 {
394     ECDSA_VALIDATE_RET( grp   != NULL );
395     ECDSA_VALIDATE_RET( r     != NULL );
396     ECDSA_VALIDATE_RET( s     != NULL );
397     ECDSA_VALIDATE_RET( d     != NULL );
398     ECDSA_VALIDATE_RET( f_rng != NULL );
399     ECDSA_VALIDATE_RET( buf   != NULL || blen == 0 );
400 
401     /* Use the same RNG for both blinding and ephemeral key generation */
402     return( ecdsa_sign_restartable( grp, r, s, d, buf, blen,
403                                     f_rng, p_rng, f_rng, p_rng, NULL ) );
404 }
405 #endif /* !MBEDTLS_ECDSA_SIGN_ALT */
406 
407 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
408 /*
409  * Deterministic signature wrapper
410  */
411 static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp,
412                     mbedtls_mpi *r, mbedtls_mpi *s,
413                     const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
414                     mbedtls_md_type_t md_alg,
415                     int (*f_rng_blind)(void *, unsigned char *, size_t),
416                     void *p_rng_blind,
417                     mbedtls_ecdsa_restart_ctx *rs_ctx )
418 {
419     int ret;
420     mbedtls_hmac_drbg_context rng_ctx;
421     mbedtls_hmac_drbg_context *p_rng = &rng_ctx;
422     unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES];
423     size_t grp_len = ( grp->nbits + 7 ) / 8;
424     const mbedtls_md_info_t *md_info;
425     mbedtls_mpi h;
426 
427     if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL )
428         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
429 
430     mbedtls_mpi_init( &h );
431     mbedtls_hmac_drbg_init( &rng_ctx );
432 
433     ECDSA_RS_ENTER( det );
434 
435 #if defined(MBEDTLS_ECP_RESTARTABLE)
436     if( rs_ctx != NULL && rs_ctx->det != NULL )
437     {
438         /* redirect to our context */
439         p_rng = &rs_ctx->det->rng_ctx;
440 
441         /* jump to current step */
442         if( rs_ctx->det->state == ecdsa_det_sign )
443             goto sign;
444     }
445 #endif /* MBEDTLS_ECP_RESTARTABLE */
446 
447     /* Use private key and message hash (reduced) to initialize HMAC_DRBG */
448     MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) );
449     MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) );
450     MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) );
451     mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len );
452 
453 #if defined(MBEDTLS_ECP_RESTARTABLE)
454     if( rs_ctx != NULL && rs_ctx->det != NULL )
455         rs_ctx->det->state = ecdsa_det_sign;
456 
457 sign:
458 #endif
459 #if defined(MBEDTLS_ECDSA_SIGN_ALT)
460     ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen,
461                               mbedtls_hmac_drbg_random, p_rng );
462 #else
463     if( f_rng_blind != NULL )
464         ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen,
465                                       mbedtls_hmac_drbg_random, p_rng,
466                                       f_rng_blind, p_rng_blind, rs_ctx );
467     else
468     {
469         mbedtls_hmac_drbg_context *p_rng_blind_det;
470 
471 #if !defined(MBEDTLS_ECP_RESTARTABLE)
472         /*
473          * To avoid reusing rng_ctx and risking incorrect behavior we seed a
474          * second HMAC-DRBG with the same seed. We also apply a label to avoid
475          * reusing the bits of the ephemeral key for blinding and eliminate the
476          * risk that they leak this way.
477          */
478         const char* blind_label = "BLINDING CONTEXT";
479         mbedtls_hmac_drbg_context rng_ctx_blind;
480 
481         mbedtls_hmac_drbg_init( &rng_ctx_blind );
482         p_rng_blind_det = &rng_ctx_blind;
483 
484         mbedtls_hmac_drbg_seed_buf( p_rng_blind_det, md_info,
485                                     data, 2 * grp_len );
486         ret = mbedtls_hmac_drbg_update_ret( p_rng_blind_det,
487                                             (const unsigned char*) blind_label,
488                                             strlen( blind_label ) );
489         if( ret != 0 )
490         {
491             mbedtls_hmac_drbg_free( &rng_ctx_blind );
492             goto cleanup;
493         }
494 #else
495         /*
496          * In the case of restartable computations we would either need to store
497          * the second RNG in the restart context too or set it up at every
498          * restart. The first option would penalize the correct application of
499          * the function and the second would defeat the purpose of the
500          * restartable feature.
501          *
502          * Therefore in this case we reuse the original RNG. This comes with the
503          * price that the resulting signature might not be a valid deterministic
504          * ECDSA signature with a very low probability (same magnitude as
505          * successfully guessing the private key). However even then it is still
506          * a valid ECDSA signature.
507          */
508         p_rng_blind_det = p_rng;
509 #endif /* MBEDTLS_ECP_RESTARTABLE */
510 
511         /*
512          * Since the output of the RNGs is always the same for the same key and
513          * message, this limits the efficiency of blinding and leaks information
514          * through side channels. After mbedtls_ecdsa_sign_det() is removed NULL
515          * won't be a valid value for f_rng_blind anymore. Therefore it should
516          * be checked by the caller and this branch and check can be removed.
517          */
518         ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen,
519                                       mbedtls_hmac_drbg_random, p_rng,
520                                       mbedtls_hmac_drbg_random, p_rng_blind_det,
521                                       rs_ctx );
522 
523 #if !defined(MBEDTLS_ECP_RESTARTABLE)
524         mbedtls_hmac_drbg_free( &rng_ctx_blind );
525 #endif
526     }
527 #endif /* MBEDTLS_ECDSA_SIGN_ALT */
528 
529 cleanup:
530     mbedtls_hmac_drbg_free( &rng_ctx );
531     mbedtls_mpi_free( &h );
532 
533     ECDSA_RS_LEAVE( det );
534 
535     return( ret );
536 }
537 
538 /*
539  * Deterministic signature wrappers
540  */
541 int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r,
542                             mbedtls_mpi *s, const mbedtls_mpi *d,
543                             const unsigned char *buf, size_t blen,
544                             mbedtls_md_type_t md_alg )
545 {
546     ECDSA_VALIDATE_RET( grp   != NULL );
547     ECDSA_VALIDATE_RET( r     != NULL );
548     ECDSA_VALIDATE_RET( s     != NULL );
549     ECDSA_VALIDATE_RET( d     != NULL );
550     ECDSA_VALIDATE_RET( buf   != NULL || blen == 0 );
551 
552     return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg,
553                                         NULL, NULL, NULL ) );
554 }
555 
556 int mbedtls_ecdsa_sign_det_ext( mbedtls_ecp_group *grp, mbedtls_mpi *r,
557                                 mbedtls_mpi *s, const mbedtls_mpi *d,
558                                 const unsigned char *buf, size_t blen,
559                                 mbedtls_md_type_t md_alg,
560                                 int (*f_rng_blind)(void *, unsigned char *,
561                                                    size_t),
562                                 void *p_rng_blind )
563 {
564     ECDSA_VALIDATE_RET( grp   != NULL );
565     ECDSA_VALIDATE_RET( r     != NULL );
566     ECDSA_VALIDATE_RET( s     != NULL );
567     ECDSA_VALIDATE_RET( d     != NULL );
568     ECDSA_VALIDATE_RET( buf   != NULL || blen == 0 );
569     ECDSA_VALIDATE_RET( f_rng_blind != NULL );
570 
571     return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg,
572                                         f_rng_blind, p_rng_blind, NULL ) );
573 }
574 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
575 
576 #if !defined(MBEDTLS_ECDSA_VERIFY_ALT)
577 /*
578  * Verify ECDSA signature of hashed message (SEC1 4.1.4)
579  * Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message)
580  */
581 static int ecdsa_verify_restartable( mbedtls_ecp_group *grp,
582                                      const unsigned char *buf, size_t blen,
583                                      const mbedtls_ecp_point *Q,
584                                      const mbedtls_mpi *r, const mbedtls_mpi *s,
585                                      mbedtls_ecdsa_restart_ctx *rs_ctx )
586 {
587     int ret;
588     mbedtls_mpi e, s_inv, u1, u2;
589     mbedtls_ecp_point R;
590     mbedtls_mpi *pu1 = &u1, *pu2 = &u2;
591 
592     mbedtls_ecp_point_init( &R );
593     mbedtls_mpi_init( &e ); mbedtls_mpi_init( &s_inv );
594     mbedtls_mpi_init( &u1 ); mbedtls_mpi_init( &u2 );
595 
596     /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
597     if( grp->N.p == NULL )
598         return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
599 
600     ECDSA_RS_ENTER( ver );
601 
602 #if defined(MBEDTLS_ECP_RESTARTABLE)
603     if( rs_ctx != NULL && rs_ctx->ver != NULL )
604     {
605         /* redirect to our context */
606         pu1 = &rs_ctx->ver->u1;
607         pu2 = &rs_ctx->ver->u2;
608 
609         /* jump to current step */
610         if( rs_ctx->ver->state == ecdsa_ver_muladd )
611             goto muladd;
612     }
613 #endif /* MBEDTLS_ECP_RESTARTABLE */
614 
615     /*
616      * Step 1: make sure r and s are in range 1..n-1
617      */
618     if( mbedtls_mpi_cmp_int( r, 1 ) < 0 || mbedtls_mpi_cmp_mpi( r, &grp->N ) >= 0 ||
619         mbedtls_mpi_cmp_int( s, 1 ) < 0 || mbedtls_mpi_cmp_mpi( s, &grp->N ) >= 0 )
620     {
621         ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
622         goto cleanup;
623     }
624 
625     /*
626      * Step 3: derive MPI from hashed message
627      */
628     MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) );
629 
630     /*
631      * Step 4: u1 = e / s mod n, u2 = r / s mod n
632      */
633     ECDSA_BUDGET( MBEDTLS_ECP_OPS_CHK + MBEDTLS_ECP_OPS_INV + 2 );
634 
635     MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &s_inv, s, &grp->N ) );
636 
637     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pu1, &e, &s_inv ) );
638     MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pu1, pu1, &grp->N ) );
639 
640     MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pu2, r, &s_inv ) );
641     MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pu2, pu2, &grp->N ) );
642 
643 #if defined(MBEDTLS_ECP_RESTARTABLE)
644     if( rs_ctx != NULL && rs_ctx->ver != NULL )
645         rs_ctx->ver->state = ecdsa_ver_muladd;
646 
647 muladd:
648 #endif
649     /*
650      * Step 5: R = u1 G + u2 Q
651      */
652     MBEDTLS_MPI_CHK( mbedtls_ecp_muladd_restartable( grp,
653                      &R, pu1, &grp->G, pu2, Q, ECDSA_RS_ECP ) );
654 
655     if( mbedtls_ecp_is_zero( &R ) )
656     {
657         ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
658         goto cleanup;
659     }
660 
661     /*
662      * Step 6: convert xR to an integer (no-op)
663      * Step 7: reduce xR mod n (gives v)
664      */
665     MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &R.X, &R.X, &grp->N ) );
666 
667     /*
668      * Step 8: check if v (that is, R.X) is equal to r
669      */
670     if( mbedtls_mpi_cmp_mpi( &R.X, r ) != 0 )
671     {
672         ret = MBEDTLS_ERR_ECP_VERIFY_FAILED;
673         goto cleanup;
674     }
675 
676 cleanup:
677     mbedtls_ecp_point_free( &R );
678     mbedtls_mpi_free( &e ); mbedtls_mpi_free( &s_inv );
679     mbedtls_mpi_free( &u1 ); mbedtls_mpi_free( &u2 );
680 
681     ECDSA_RS_LEAVE( ver );
682 
683     return( ret );
684 }
685 
686 /*
687  * Verify ECDSA signature of hashed message
688  */
689 int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp,
690                           const unsigned char *buf, size_t blen,
691                           const mbedtls_ecp_point *Q,
692                           const mbedtls_mpi *r,
693                           const mbedtls_mpi *s)
694 {
695     ECDSA_VALIDATE_RET( grp != NULL );
696     ECDSA_VALIDATE_RET( Q   != NULL );
697     ECDSA_VALIDATE_RET( r   != NULL );
698     ECDSA_VALIDATE_RET( s   != NULL );
699     ECDSA_VALIDATE_RET( buf != NULL || blen == 0 );
700 
701     return( ecdsa_verify_restartable( grp, buf, blen, Q, r, s, NULL ) );
702 }
703 #endif /* !MBEDTLS_ECDSA_VERIFY_ALT */
704 
705 /*
706  * Convert a signature (given by context) to ASN.1
707  */
708 static int ecdsa_signature_to_asn1( const mbedtls_mpi *r, const mbedtls_mpi *s,
709                                     unsigned char *sig, size_t *slen )
710 {
711     int ret;
712     unsigned char buf[MBEDTLS_ECDSA_MAX_LEN];
713     unsigned char *p = buf + sizeof( buf );
714     size_t len = 0;
715 
716     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, s ) );
717     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, r ) );
718 
719     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &p, buf, len ) );
720     MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &p, buf,
721                                        MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) );
722 
723     memcpy( sig, p, len );
724     *slen = len;
725 
726     return( 0 );
727 }
728 
729 /*
730  * Compute and write signature
731  */
732 int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx,
733                            mbedtls_md_type_t md_alg,
734                            const unsigned char *hash, size_t hlen,
735                            unsigned char *sig, size_t *slen,
736                            int (*f_rng)(void *, unsigned char *, size_t),
737                            void *p_rng,
738                            mbedtls_ecdsa_restart_ctx *rs_ctx )
739 {
740     int ret;
741     mbedtls_mpi r, s;
742     ECDSA_VALIDATE_RET( ctx  != NULL );
743     ECDSA_VALIDATE_RET( hash != NULL );
744     ECDSA_VALIDATE_RET( sig  != NULL );
745     ECDSA_VALIDATE_RET( slen != NULL );
746 
747     mbedtls_mpi_init( &r );
748     mbedtls_mpi_init( &s );
749 
750 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
751     MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d,
752                                                  hash, hlen, md_alg, f_rng,
753                                                  p_rng, rs_ctx ) );
754 #else
755     (void) md_alg;
756 
757 #if defined(MBEDTLS_ECDSA_SIGN_ALT)
758     MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d,
759                          hash, hlen, f_rng, p_rng ) );
760 #else
761     /* Use the same RNG for both blinding and ephemeral key generation */
762     MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d,
763                                              hash, hlen, f_rng, p_rng, f_rng,
764                                              p_rng, rs_ctx ) );
765 #endif /* MBEDTLS_ECDSA_SIGN_ALT */
766 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */
767 
768     MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) );
769 
770 cleanup:
771     mbedtls_mpi_free( &r );
772     mbedtls_mpi_free( &s );
773 
774     return( ret );
775 }
776 
777 /*
778  * Compute and write signature
779  */
780 int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx,
781                                  mbedtls_md_type_t md_alg,
782                                  const unsigned char *hash, size_t hlen,
783                                  unsigned char *sig, size_t *slen,
784                                  int (*f_rng)(void *, unsigned char *, size_t),
785                                  void *p_rng )
786 {
787     ECDSA_VALIDATE_RET( ctx  != NULL );
788     ECDSA_VALIDATE_RET( hash != NULL );
789     ECDSA_VALIDATE_RET( sig  != NULL );
790     ECDSA_VALIDATE_RET( slen != NULL );
791     return( mbedtls_ecdsa_write_signature_restartable(
792                 ctx, md_alg, hash, hlen, sig, slen, f_rng, p_rng, NULL ) );
793 }
794 
795 #if !defined(MBEDTLS_DEPRECATED_REMOVED) && \
796     defined(MBEDTLS_ECDSA_DETERMINISTIC)
797 int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx,
798                                const unsigned char *hash, size_t hlen,
799                                unsigned char *sig, size_t *slen,
800                                mbedtls_md_type_t md_alg )
801 {
802     ECDSA_VALIDATE_RET( ctx  != NULL );
803     ECDSA_VALIDATE_RET( hash != NULL );
804     ECDSA_VALIDATE_RET( sig  != NULL );
805     ECDSA_VALIDATE_RET( slen != NULL );
806     return( mbedtls_ecdsa_write_signature( ctx, md_alg, hash, hlen, sig, slen,
807                                    NULL, NULL ) );
808 }
809 #endif
810 
811 /*
812  * Read and check signature
813  */
814 int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx,
815                           const unsigned char *hash, size_t hlen,
816                           const unsigned char *sig, size_t slen )
817 {
818     ECDSA_VALIDATE_RET( ctx  != NULL );
819     ECDSA_VALIDATE_RET( hash != NULL );
820     ECDSA_VALIDATE_RET( sig  != NULL );
821     return( mbedtls_ecdsa_read_signature_restartable(
822                 ctx, hash, hlen, sig, slen, NULL ) );
823 }
824 
825 /*
826  * Restartable read and check signature
827  */
828 int mbedtls_ecdsa_read_signature_restartable( mbedtls_ecdsa_context *ctx,
829                           const unsigned char *hash, size_t hlen,
830                           const unsigned char *sig, size_t slen,
831                           mbedtls_ecdsa_restart_ctx *rs_ctx )
832 {
833     int ret;
834     unsigned char *p = (unsigned char *) sig;
835     const unsigned char *end = sig + slen;
836     size_t len;
837     mbedtls_mpi r, s;
838     ECDSA_VALIDATE_RET( ctx  != NULL );
839     ECDSA_VALIDATE_RET( hash != NULL );
840     ECDSA_VALIDATE_RET( sig  != NULL );
841 
842     mbedtls_mpi_init( &r );
843     mbedtls_mpi_init( &s );
844 
845     if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
846                     MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
847     {
848         ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
849         goto cleanup;
850     }
851 
852     if( p + len != end )
853     {
854         ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA +
855               MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
856         goto cleanup;
857     }
858 
859     if( ( ret = mbedtls_asn1_get_mpi( &p, end, &r ) ) != 0 ||
860         ( ret = mbedtls_asn1_get_mpi( &p, end, &s ) ) != 0 )
861     {
862         ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
863         goto cleanup;
864     }
865 #if defined(MBEDTLS_ECDSA_VERIFY_ALT)
866     if( ( ret = mbedtls_ecdsa_verify( &ctx->grp, hash, hlen,
867                                       &ctx->Q, &r, &s ) ) != 0 )
868         goto cleanup;
869 #else
870     if( ( ret = ecdsa_verify_restartable( &ctx->grp, hash, hlen,
871                               &ctx->Q, &r, &s, rs_ctx ) ) != 0 )
872         goto cleanup;
873 #endif /* MBEDTLS_ECDSA_VERIFY_ALT */
874 
875     /* At this point we know that the buffer starts with a valid signature.
876      * Return 0 if the buffer just contains the signature, and a specific
877      * error code if the valid signature is followed by more data. */
878     if( p != end )
879         ret = MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH;
880 
881 cleanup:
882     mbedtls_mpi_free( &r );
883     mbedtls_mpi_free( &s );
884 
885     return( ret );
886 }
887 
888 #if !defined(MBEDTLS_ECDSA_GENKEY_ALT)
889 /*
890  * Generate key pair
891  */
892 int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
893                   int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
894 {
895     int ret = 0;
896     ECDSA_VALIDATE_RET( ctx   != NULL );
897     ECDSA_VALIDATE_RET( f_rng != NULL );
898 
899     ret = mbedtls_ecp_group_load( &ctx->grp, gid );
900     if( ret != 0 )
901         return( ret );
902 
903    return( mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d,
904                                     &ctx->Q, f_rng, p_rng ) );
905 }
906 #endif /* !MBEDTLS_ECDSA_GENKEY_ALT */
907 
908 /*
909  * Set context from an mbedtls_ecp_keypair
910  */
911 int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key )
912 {
913     int ret;
914     ECDSA_VALIDATE_RET( ctx != NULL );
915     ECDSA_VALIDATE_RET( key != NULL );
916 
917     if( ( ret = mbedtls_ecp_group_copy( &ctx->grp, &key->grp ) ) != 0 ||
918         ( ret = mbedtls_mpi_copy( &ctx->d, &key->d ) ) != 0 ||
919         ( ret = mbedtls_ecp_copy( &ctx->Q, &key->Q ) ) != 0 )
920     {
921         mbedtls_ecdsa_free( ctx );
922     }
923 
924     return( ret );
925 }
926 
927 /*
928  * Initialize context
929  */
930 void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx )
931 {
932     ECDSA_VALIDATE( ctx != NULL );
933 
934     mbedtls_ecp_keypair_init( ctx );
935 }
936 
937 /*
938  * Free context
939  */
940 void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx )
941 {
942     if( ctx == NULL )
943         return;
944 
945     mbedtls_ecp_keypair_free( ctx );
946 }
947 
948 #if defined(MBEDTLS_ECP_RESTARTABLE)
949 /*
950  * Initialize a restart context
951  */
952 void mbedtls_ecdsa_restart_init( mbedtls_ecdsa_restart_ctx *ctx )
953 {
954     ECDSA_VALIDATE( ctx != NULL );
955 
956     mbedtls_ecp_restart_init( &ctx->ecp );
957 
958     ctx->ver = NULL;
959     ctx->sig = NULL;
960 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
961     ctx->det = NULL;
962 #endif
963 }
964 
965 /*
966  * Free the components of a restart context
967  */
968 void mbedtls_ecdsa_restart_free( mbedtls_ecdsa_restart_ctx *ctx )
969 {
970     if( ctx == NULL )
971         return;
972 
973     mbedtls_ecp_restart_free( &ctx->ecp );
974 
975     ecdsa_restart_ver_free( ctx->ver );
976     mbedtls_free( ctx->ver );
977     ctx->ver = NULL;
978 
979     ecdsa_restart_sig_free( ctx->sig );
980     mbedtls_free( ctx->sig );
981     ctx->sig = NULL;
982 
983 #if defined(MBEDTLS_ECDSA_DETERMINISTIC)
984     ecdsa_restart_det_free( ctx->det );
985     mbedtls_free( ctx->det );
986     ctx->det = NULL;
987 #endif
988 }
989 #endif /* MBEDTLS_ECP_RESTARTABLE */
990 
991 #endif /* MBEDTLS_ECDSA_C */
992