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