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