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