1 /*
2 * Multi-precision integer library
3 *
4 * Copyright The Mbed TLS Contributors
5 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6 */
7
8 /*
9 * The following sources were referenced in the design of this Multi-precision
10 * Integer library:
11 *
12 * [1] Handbook of Applied Cryptography - 1997
13 * Menezes, van Oorschot and Vanstone
14 *
15 * [2] Multi-Precision Math
16 * Tom St Denis
17 * https://github.com/libtom/libtommath/blob/develop/tommath.pdf
18 *
19 * [3] GNU Multi-Precision Arithmetic Library
20 * https://gmplib.org/manual/index.html
21 *
22 */
23
24 #include "common.h"
25
26 #if defined(MBEDTLS_BIGNUM_C)
27
28 #include "mbedtls/bignum.h"
29 #include "bignum_core.h"
30 #include "bn_mul.h"
31 #include "mbedtls/platform_util.h"
32 #include "mbedtls/error.h"
33 #include "constant_time_internal.h"
34
35 #include <limits.h>
36 #include <string.h>
37
38 #include "mbedtls/platform.h"
39
40 #define MPI_VALIDATE_RET(cond) \
41 MBEDTLS_INTERNAL_VALIDATE_RET(cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA)
42 #define MPI_VALIDATE(cond) \
43 MBEDTLS_INTERNAL_VALIDATE(cond)
44
45 /*
46 * Compare signed values in constant time
47 */
mbedtls_mpi_lt_mpi_ct(const mbedtls_mpi * X,const mbedtls_mpi * Y,unsigned * ret)48 int mbedtls_mpi_lt_mpi_ct(const mbedtls_mpi *X,
49 const mbedtls_mpi *Y,
50 unsigned *ret)
51 {
52 mbedtls_ct_condition_t different_sign, X_is_negative, Y_is_negative, result;
53
54 MPI_VALIDATE_RET(X != NULL);
55 MPI_VALIDATE_RET(Y != NULL);
56 MPI_VALIDATE_RET(ret != NULL);
57
58 if (X->n != Y->n) {
59 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
60 }
61
62 /*
63 * Set N_is_negative to MBEDTLS_CT_FALSE if N >= 0, MBEDTLS_CT_TRUE if N < 0.
64 * We know that N->s == 1 if N >= 0 and N->s == -1 if N < 0.
65 */
66 X_is_negative = mbedtls_ct_bool((X->s & 2) >> 1);
67 Y_is_negative = mbedtls_ct_bool((Y->s & 2) >> 1);
68
69 /*
70 * If the signs are different, then the positive operand is the bigger.
71 * That is if X is negative (X_is_negative == 1), then X < Y is true and it
72 * is false if X is positive (X_is_negative == 0).
73 */
74 different_sign = mbedtls_ct_bool_ne(X_is_negative, Y_is_negative); // true if different sign
75 result = mbedtls_ct_bool_and(different_sign, X_is_negative);
76
77 /*
78 * Assuming signs are the same, compare X and Y. We switch the comparison
79 * order if they are negative so that we get the right result, regardles of
80 * sign.
81 */
82
83 /* This array is used to conditionally swap the pointers in const time */
84 void * const p[2] = { X->p, Y->p };
85 size_t i = mbedtls_ct_size_if_else_0(X_is_negative, 1);
86 mbedtls_ct_condition_t lt = mbedtls_mpi_core_lt_ct(p[i], p[i ^ 1], X->n);
87
88 /*
89 * Store in result iff the signs are the same (i.e., iff different_sign == false). If
90 * the signs differ, result has already been set, so we don't change it.
91 */
92 result = mbedtls_ct_bool_or(result,
93 mbedtls_ct_bool_and(mbedtls_ct_bool_not(different_sign), lt));
94
95 *ret = mbedtls_ct_uint_if_else_0(result, 1);
96
97 return 0;
98 }
99
100 /*
101 * Conditionally assign X = Y, without leaking information
102 * about whether the assignment was made or not.
103 * (Leaking information about the respective sizes of X and Y is ok however.)
104 */
105 #if defined(_MSC_VER) && defined(_M_ARM64) && (_MSC_FULL_VER < 193131103)
106 /*
107 * MSVC miscompiles this function if it's inlined prior to Visual Studio 2022 version 17.1. See:
108 * https://developercommunity.visualstudio.com/t/c-compiler-miscompiles-part-of-mbedtls-library-on/1646989
109 */
110 __declspec(noinline)
111 #endif
mbedtls_mpi_safe_cond_assign(mbedtls_mpi * X,const mbedtls_mpi * Y,unsigned char assign)112 int mbedtls_mpi_safe_cond_assign(mbedtls_mpi *X,
113 const mbedtls_mpi *Y,
114 unsigned char assign)
115 {
116 int ret = 0;
117 MPI_VALIDATE_RET(X != NULL);
118 MPI_VALIDATE_RET(Y != NULL);
119
120 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, Y->n));
121
122 {
123 mbedtls_ct_condition_t do_assign = mbedtls_ct_bool(assign);
124
125 X->s = (int) mbedtls_ct_uint_if(do_assign, Y->s, X->s);
126
127 mbedtls_mpi_core_cond_assign(X->p, Y->p, Y->n, do_assign);
128
129 mbedtls_ct_condition_t do_not_assign = mbedtls_ct_bool_not(do_assign);
130 for (size_t i = Y->n; i < X->n; i++) {
131 X->p[i] = mbedtls_ct_mpi_uint_if_else_0(do_not_assign, X->p[i]);
132 }
133 }
134
135 cleanup:
136 return ret;
137 }
138
139 /*
140 * Conditionally swap X and Y, without leaking information
141 * about whether the swap was made or not.
142 * Here it is not ok to simply swap the pointers, which would lead to
143 * different memory access patterns when X and Y are used afterwards.
144 */
mbedtls_mpi_safe_cond_swap(mbedtls_mpi * X,mbedtls_mpi * Y,unsigned char swap)145 int mbedtls_mpi_safe_cond_swap(mbedtls_mpi *X,
146 mbedtls_mpi *Y,
147 unsigned char swap)
148 {
149 int ret = 0;
150 int s;
151 MPI_VALIDATE_RET(X != NULL);
152 MPI_VALIDATE_RET(Y != NULL);
153
154 if (X == Y) {
155 return 0;
156 }
157
158 mbedtls_ct_condition_t do_swap = mbedtls_ct_bool(swap);
159
160 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, Y->n));
161 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Y, X->n));
162
163 s = X->s;
164 X->s = (int) mbedtls_ct_uint_if(do_swap, Y->s, X->s);
165 Y->s = (int) mbedtls_ct_uint_if(do_swap, s, Y->s);
166
167 mbedtls_mpi_core_cond_swap(X->p, Y->p, X->n, do_swap);
168
169 cleanup:
170 return ret;
171 }
172
173 /* Implementation that should never be optimized out by the compiler */
174 #define mbedtls_mpi_zeroize_and_free(v, n) mbedtls_zeroize_and_free(v, ciL * (n))
175
176 /*
177 * Initialize one MPI
178 */
mbedtls_mpi_init(mbedtls_mpi * X)179 void mbedtls_mpi_init(mbedtls_mpi *X)
180 {
181 MPI_VALIDATE(X != NULL);
182
183 X->s = 1;
184 X->n = 0;
185 X->p = NULL;
186 }
187
188 /*
189 * Unallocate one MPI
190 */
mbedtls_mpi_free(mbedtls_mpi * X)191 void mbedtls_mpi_free(mbedtls_mpi *X)
192 {
193 if (X == NULL) {
194 return;
195 }
196
197 if (X->p != NULL) {
198 mbedtls_mpi_zeroize_and_free(X->p, X->n);
199 }
200
201 X->s = 1;
202 X->n = 0;
203 X->p = NULL;
204 }
205
206 /*
207 * Enlarge to the specified number of limbs
208 */
mbedtls_mpi_grow(mbedtls_mpi * X,size_t nblimbs)209 int mbedtls_mpi_grow(mbedtls_mpi *X, size_t nblimbs)
210 {
211 mbedtls_mpi_uint *p;
212 MPI_VALIDATE_RET(X != NULL);
213
214 if (nblimbs > MBEDTLS_MPI_MAX_LIMBS) {
215 return MBEDTLS_ERR_MPI_ALLOC_FAILED;
216 }
217
218 if (X->n < nblimbs) {
219 if ((p = (mbedtls_mpi_uint *) mbedtls_calloc(nblimbs, ciL)) == NULL) {
220 return MBEDTLS_ERR_MPI_ALLOC_FAILED;
221 }
222
223 if (X->p != NULL) {
224 memcpy(p, X->p, X->n * ciL);
225 mbedtls_mpi_zeroize_and_free(X->p, X->n);
226 }
227
228 /* nblimbs fits in n because we ensure that MBEDTLS_MPI_MAX_LIMBS
229 * fits, and we've checked that nblimbs <= MBEDTLS_MPI_MAX_LIMBS. */
230 X->n = (unsigned short) nblimbs;
231 X->p = p;
232 }
233
234 return 0;
235 }
236
237 /*
238 * Resize down as much as possible,
239 * while keeping at least the specified number of limbs
240 */
mbedtls_mpi_shrink(mbedtls_mpi * X,size_t nblimbs)241 int mbedtls_mpi_shrink(mbedtls_mpi *X, size_t nblimbs)
242 {
243 mbedtls_mpi_uint *p;
244 size_t i;
245 MPI_VALIDATE_RET(X != NULL);
246
247 if (nblimbs > MBEDTLS_MPI_MAX_LIMBS) {
248 return MBEDTLS_ERR_MPI_ALLOC_FAILED;
249 }
250
251 /* Actually resize up if there are currently fewer than nblimbs limbs. */
252 if (X->n <= nblimbs) {
253 return mbedtls_mpi_grow(X, nblimbs);
254 }
255 /* After this point, then X->n > nblimbs and in particular X->n > 0. */
256
257 for (i = X->n - 1; i > 0; i--) {
258 if (X->p[i] != 0) {
259 break;
260 }
261 }
262 i++;
263
264 if (i < nblimbs) {
265 i = nblimbs;
266 }
267
268 if ((p = (mbedtls_mpi_uint *) mbedtls_calloc(i, ciL)) == NULL) {
269 return MBEDTLS_ERR_MPI_ALLOC_FAILED;
270 }
271
272 if (X->p != NULL) {
273 memcpy(p, X->p, i * ciL);
274 mbedtls_mpi_zeroize_and_free(X->p, X->n);
275 }
276
277 /* i fits in n because we ensure that MBEDTLS_MPI_MAX_LIMBS
278 * fits, and we've checked that i <= nblimbs <= MBEDTLS_MPI_MAX_LIMBS. */
279 X->n = (unsigned short) i;
280 X->p = p;
281
282 return 0;
283 }
284
285 /* Resize X to have exactly n limbs and set it to 0. */
mbedtls_mpi_resize_clear(mbedtls_mpi * X,size_t limbs)286 static int mbedtls_mpi_resize_clear(mbedtls_mpi *X, size_t limbs)
287 {
288 if (limbs == 0) {
289 mbedtls_mpi_free(X);
290 return 0;
291 } else if (X->n == limbs) {
292 memset(X->p, 0, limbs * ciL);
293 X->s = 1;
294 return 0;
295 } else {
296 mbedtls_mpi_free(X);
297 return mbedtls_mpi_grow(X, limbs);
298 }
299 }
300
301 /*
302 * Copy the contents of Y into X.
303 *
304 * This function is not constant-time. Leading zeros in Y may be removed.
305 *
306 * Ensure that X does not shrink. This is not guaranteed by the public API,
307 * but some code in the bignum module relies on this property, for example
308 * in mbedtls_mpi_exp_mod().
309 */
mbedtls_mpi_copy(mbedtls_mpi * X,const mbedtls_mpi * Y)310 int mbedtls_mpi_copy(mbedtls_mpi *X, const mbedtls_mpi *Y)
311 {
312 int ret = 0;
313 size_t i;
314 MPI_VALIDATE_RET(X != NULL);
315 MPI_VALIDATE_RET(Y != NULL);
316
317 if (X == Y) {
318 return 0;
319 }
320
321 if (Y->n == 0) {
322 if (X->n != 0) {
323 X->s = 1;
324 memset(X->p, 0, X->n * ciL);
325 }
326 return 0;
327 }
328
329 for (i = Y->n - 1; i > 0; i--) {
330 if (Y->p[i] != 0) {
331 break;
332 }
333 }
334 i++;
335
336 X->s = Y->s;
337
338 if (X->n < i) {
339 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, i));
340 } else {
341 memset(X->p + i, 0, (X->n - i) * ciL);
342 }
343
344 memcpy(X->p, Y->p, i * ciL);
345
346 cleanup:
347
348 return ret;
349 }
350
351 /*
352 * Swap the contents of X and Y
353 */
mbedtls_mpi_swap(mbedtls_mpi * X,mbedtls_mpi * Y)354 void mbedtls_mpi_swap(mbedtls_mpi *X, mbedtls_mpi *Y)
355 {
356 mbedtls_mpi T;
357 MPI_VALIDATE(X != NULL);
358 MPI_VALIDATE(Y != NULL);
359
360 memcpy(&T, X, sizeof(mbedtls_mpi));
361 memcpy(X, Y, sizeof(mbedtls_mpi));
362 memcpy(Y, &T, sizeof(mbedtls_mpi));
363 }
364
mpi_sint_abs(mbedtls_mpi_sint z)365 static inline mbedtls_mpi_uint mpi_sint_abs(mbedtls_mpi_sint z)
366 {
367 if (z >= 0) {
368 return z;
369 }
370 /* Take care to handle the most negative value (-2^(biL-1)) correctly.
371 * A naive -z would have undefined behavior.
372 * Write this in a way that makes popular compilers happy (GCC, Clang,
373 * MSVC). */
374 return (mbedtls_mpi_uint) 0 - (mbedtls_mpi_uint) z;
375 }
376
377 /* Convert x to a sign, i.e. to 1, if x is positive, or -1, if x is negative.
378 * This looks awkward but generates smaller code than (x < 0 ? -1 : 1) */
379 #define TO_SIGN(x) ((mbedtls_mpi_sint) (((mbedtls_mpi_uint) x) >> (biL - 1)) * -2 + 1)
380
381 /*
382 * Set value from integer
383 */
mbedtls_mpi_lset(mbedtls_mpi * X,mbedtls_mpi_sint z)384 int mbedtls_mpi_lset(mbedtls_mpi *X, mbedtls_mpi_sint z)
385 {
386 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
387 MPI_VALIDATE_RET(X != NULL);
388
389 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, 1));
390 memset(X->p, 0, X->n * ciL);
391
392 X->p[0] = mpi_sint_abs(z);
393 X->s = TO_SIGN(z);
394
395 cleanup:
396
397 return ret;
398 }
399
400 /*
401 * Get a specific bit
402 */
mbedtls_mpi_get_bit(const mbedtls_mpi * X,size_t pos)403 int mbedtls_mpi_get_bit(const mbedtls_mpi *X, size_t pos)
404 {
405 MPI_VALIDATE_RET(X != NULL);
406
407 if (X->n * biL <= pos) {
408 return 0;
409 }
410
411 return (X->p[pos / biL] >> (pos % biL)) & 0x01;
412 }
413
414 /*
415 * Set a bit to a specific value of 0 or 1
416 */
mbedtls_mpi_set_bit(mbedtls_mpi * X,size_t pos,unsigned char val)417 int mbedtls_mpi_set_bit(mbedtls_mpi *X, size_t pos, unsigned char val)
418 {
419 int ret = 0;
420 size_t off = pos / biL;
421 size_t idx = pos % biL;
422 MPI_VALIDATE_RET(X != NULL);
423
424 if (val != 0 && val != 1) {
425 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
426 }
427
428 if (X->n * biL <= pos) {
429 if (val == 0) {
430 return 0;
431 }
432
433 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, off + 1));
434 }
435
436 X->p[off] &= ~((mbedtls_mpi_uint) 0x01 << idx);
437 X->p[off] |= (mbedtls_mpi_uint) val << idx;
438
439 cleanup:
440
441 return ret;
442 }
443
444 /*
445 * Return the number of less significant zero-bits
446 */
mbedtls_mpi_lsb(const mbedtls_mpi * X)447 size_t mbedtls_mpi_lsb(const mbedtls_mpi *X)
448 {
449 size_t i;
450 MBEDTLS_INTERNAL_VALIDATE_RET(X != NULL, 0);
451
452 #if defined(__has_builtin)
453 #if (MBEDTLS_MPI_UINT_MAX == UINT_MAX) && __has_builtin(__builtin_ctz)
454 #define mbedtls_mpi_uint_ctz __builtin_ctz
455 #elif (MBEDTLS_MPI_UINT_MAX == ULONG_MAX) && __has_builtin(__builtin_ctzl)
456 #define mbedtls_mpi_uint_ctz __builtin_ctzl
457 #elif (MBEDTLS_MPI_UINT_MAX == ULLONG_MAX) && __has_builtin(__builtin_ctzll)
458 #define mbedtls_mpi_uint_ctz __builtin_ctzll
459 #endif
460 #endif
461
462 #if defined(mbedtls_mpi_uint_ctz)
463 for (i = 0; i < X->n; i++) {
464 if (X->p[i] != 0) {
465 return i * biL + mbedtls_mpi_uint_ctz(X->p[i]);
466 }
467 }
468 #else
469 size_t count = 0;
470 for (i = 0; i < X->n; i++) {
471 for (size_t j = 0; j < biL; j++, count++) {
472 if (((X->p[i] >> j) & 1) != 0) {
473 return count;
474 }
475 }
476 }
477 #endif
478
479 return 0;
480 }
481
482 /*
483 * Return the number of bits
484 */
mbedtls_mpi_bitlen(const mbedtls_mpi * X)485 size_t mbedtls_mpi_bitlen(const mbedtls_mpi *X)
486 {
487 return mbedtls_mpi_core_bitlen(X->p, X->n);
488 }
489
490 /*
491 * Return the total size in bytes
492 */
mbedtls_mpi_size(const mbedtls_mpi * X)493 size_t mbedtls_mpi_size(const mbedtls_mpi *X)
494 {
495 return (mbedtls_mpi_bitlen(X) + 7) >> 3;
496 }
497
498 /*
499 * Convert an ASCII character to digit value
500 */
mpi_get_digit(mbedtls_mpi_uint * d,int radix,char c)501 static int mpi_get_digit(mbedtls_mpi_uint *d, int radix, char c)
502 {
503 *d = 255;
504
505 if (c >= 0x30 && c <= 0x39) {
506 *d = c - 0x30;
507 }
508 if (c >= 0x41 && c <= 0x46) {
509 *d = c - 0x37;
510 }
511 if (c >= 0x61 && c <= 0x66) {
512 *d = c - 0x57;
513 }
514
515 if (*d >= (mbedtls_mpi_uint) radix) {
516 return MBEDTLS_ERR_MPI_INVALID_CHARACTER;
517 }
518
519 return 0;
520 }
521
522 /*
523 * Import from an ASCII string
524 */
mbedtls_mpi_read_string(mbedtls_mpi * X,int radix,const char * s)525 int mbedtls_mpi_read_string(mbedtls_mpi *X, int radix, const char *s)
526 {
527 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
528 size_t i, j, slen, n;
529 int sign = 1;
530 mbedtls_mpi_uint d;
531 mbedtls_mpi T;
532 MPI_VALIDATE_RET(X != NULL);
533 MPI_VALIDATE_RET(s != NULL);
534
535 if (radix < 2 || radix > 16) {
536 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
537 }
538
539 mbedtls_mpi_init(&T);
540
541 if (s[0] == 0) {
542 mbedtls_mpi_free(X);
543 return 0;
544 }
545
546 if (s[0] == '-') {
547 ++s;
548 sign = -1;
549 }
550
551 slen = strlen(s);
552
553 if (radix == 16) {
554 if (slen > SIZE_MAX >> 2) {
555 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
556 }
557
558 n = BITS_TO_LIMBS(slen << 2);
559
560 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, n));
561 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, 0));
562
563 for (i = slen, j = 0; i > 0; i--, j++) {
564 MBEDTLS_MPI_CHK(mpi_get_digit(&d, radix, s[i - 1]));
565 X->p[j / (2 * ciL)] |= d << ((j % (2 * ciL)) << 2);
566 }
567 } else {
568 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, 0));
569
570 for (i = 0; i < slen; i++) {
571 MBEDTLS_MPI_CHK(mpi_get_digit(&d, radix, s[i]));
572 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int(&T, X, radix));
573 MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(X, &T, d));
574 }
575 }
576
577 if (sign < 0 && mbedtls_mpi_bitlen(X) != 0) {
578 X->s = -1;
579 }
580
581 cleanup:
582
583 mbedtls_mpi_free(&T);
584
585 return ret;
586 }
587
588 /*
589 * Helper to write the digits high-order first.
590 */
mpi_write_hlp(mbedtls_mpi * X,int radix,char ** p,const size_t buflen)591 static int mpi_write_hlp(mbedtls_mpi *X, int radix,
592 char **p, const size_t buflen)
593 {
594 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
595 mbedtls_mpi_uint r;
596 size_t length = 0;
597 char *p_end = *p + buflen;
598
599 do {
600 if (length >= buflen) {
601 return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;
602 }
603
604 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_int(&r, X, radix));
605 MBEDTLS_MPI_CHK(mbedtls_mpi_div_int(X, NULL, X, radix));
606 /*
607 * Write the residue in the current position, as an ASCII character.
608 */
609 if (r < 0xA) {
610 *(--p_end) = (char) ('0' + r);
611 } else {
612 *(--p_end) = (char) ('A' + (r - 0xA));
613 }
614
615 length++;
616 } while (mbedtls_mpi_cmp_int(X, 0) != 0);
617
618 memmove(*p, p_end, length);
619 *p += length;
620
621 cleanup:
622
623 return ret;
624 }
625
626 /*
627 * Export into an ASCII string
628 */
mbedtls_mpi_write_string(const mbedtls_mpi * X,int radix,char * buf,size_t buflen,size_t * olen)629 int mbedtls_mpi_write_string(const mbedtls_mpi *X, int radix,
630 char *buf, size_t buflen, size_t *olen)
631 {
632 int ret = 0;
633 size_t n;
634 char *p;
635 mbedtls_mpi T;
636 MPI_VALIDATE_RET(X != NULL);
637 MPI_VALIDATE_RET(olen != NULL);
638 MPI_VALIDATE_RET(buflen == 0 || buf != NULL);
639
640 if (radix < 2 || radix > 16) {
641 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
642 }
643
644 n = mbedtls_mpi_bitlen(X); /* Number of bits necessary to present `n`. */
645 if (radix >= 4) {
646 n >>= 1; /* Number of 4-adic digits necessary to present
647 * `n`. If radix > 4, this might be a strict
648 * overapproximation of the number of
649 * radix-adic digits needed to present `n`. */
650 }
651 if (radix >= 16) {
652 n >>= 1; /* Number of hexadecimal digits necessary to
653 * present `n`. */
654
655 }
656 n += 1; /* Terminating null byte */
657 n += 1; /* Compensate for the divisions above, which round down `n`
658 * in case it's not even. */
659 n += 1; /* Potential '-'-sign. */
660 n += (n & 1); /* Make n even to have enough space for hexadecimal writing,
661 * which always uses an even number of hex-digits. */
662
663 if (buflen < n) {
664 *olen = n;
665 return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;
666 }
667
668 p = buf;
669 mbedtls_mpi_init(&T);
670
671 if (X->s == -1) {
672 *p++ = '-';
673 buflen--;
674 }
675
676 if (radix == 16) {
677 int c;
678 size_t i, j, k;
679
680 for (i = X->n, k = 0; i > 0; i--) {
681 for (j = ciL; j > 0; j--) {
682 c = (X->p[i - 1] >> ((j - 1) << 3)) & 0xFF;
683
684 if (c == 0 && k == 0 && (i + j) != 2) {
685 continue;
686 }
687
688 *(p++) = "0123456789ABCDEF" [c / 16];
689 *(p++) = "0123456789ABCDEF" [c % 16];
690 k = 1;
691 }
692 }
693 } else {
694 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&T, X));
695
696 if (T.s == -1) {
697 T.s = 1;
698 }
699
700 MBEDTLS_MPI_CHK(mpi_write_hlp(&T, radix, &p, buflen));
701 }
702
703 *p++ = '\0';
704 *olen = p - buf;
705
706 cleanup:
707
708 mbedtls_mpi_free(&T);
709
710 return ret;
711 }
712
713 #if defined(MBEDTLS_FS_IO)
714 /*
715 * Read X from an opened file
716 */
mbedtls_mpi_read_file(mbedtls_mpi * X,int radix,FILE * fin)717 int mbedtls_mpi_read_file(mbedtls_mpi *X, int radix, FILE *fin)
718 {
719 mbedtls_mpi_uint d;
720 size_t slen;
721 char *p;
722 /*
723 * Buffer should have space for (short) label and decimal formatted MPI,
724 * newline characters and '\0'
725 */
726 char s[MBEDTLS_MPI_RW_BUFFER_SIZE];
727
728 MPI_VALIDATE_RET(X != NULL);
729 MPI_VALIDATE_RET(fin != NULL);
730
731 if (radix < 2 || radix > 16) {
732 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
733 }
734
735 memset(s, 0, sizeof(s));
736 if (fgets(s, sizeof(s) - 1, fin) == NULL) {
737 return MBEDTLS_ERR_MPI_FILE_IO_ERROR;
738 }
739
740 slen = strlen(s);
741 if (slen == sizeof(s) - 2) {
742 return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;
743 }
744
745 if (slen > 0 && s[slen - 1] == '\n') {
746 slen--; s[slen] = '\0';
747 }
748 if (slen > 0 && s[slen - 1] == '\r') {
749 slen--; s[slen] = '\0';
750 }
751
752 p = s + slen;
753 while (p-- > s) {
754 if (mpi_get_digit(&d, radix, *p) != 0) {
755 break;
756 }
757 }
758
759 return mbedtls_mpi_read_string(X, radix, p + 1);
760 }
761
762 /*
763 * Write X into an opened file (or stdout if fout == NULL)
764 */
mbedtls_mpi_write_file(const char * p,const mbedtls_mpi * X,int radix,FILE * fout)765 int mbedtls_mpi_write_file(const char *p, const mbedtls_mpi *X, int radix, FILE *fout)
766 {
767 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
768 size_t n, slen, plen;
769 /*
770 * Buffer should have space for (short) label and decimal formatted MPI,
771 * newline characters and '\0'
772 */
773 char s[MBEDTLS_MPI_RW_BUFFER_SIZE];
774 MPI_VALIDATE_RET(X != NULL);
775
776 if (radix < 2 || radix > 16) {
777 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
778 }
779
780 memset(s, 0, sizeof(s));
781
782 MBEDTLS_MPI_CHK(mbedtls_mpi_write_string(X, radix, s, sizeof(s) - 2, &n));
783
784 if (p == NULL) {
785 p = "";
786 }
787
788 plen = strlen(p);
789 slen = strlen(s);
790 s[slen++] = '\r';
791 s[slen++] = '\n';
792
793 if (fout != NULL) {
794 if (fwrite(p, 1, plen, fout) != plen ||
795 fwrite(s, 1, slen, fout) != slen) {
796 return MBEDTLS_ERR_MPI_FILE_IO_ERROR;
797 }
798 } else {
799 mbedtls_printf("%s%s", p, s);
800 }
801
802 cleanup:
803
804 return ret;
805 }
806 #endif /* MBEDTLS_FS_IO */
807
808 /*
809 * Import X from unsigned binary data, little endian
810 *
811 * This function is guaranteed to return an MPI with exactly the necessary
812 * number of limbs (in particular, it does not skip 0s in the input).
813 */
mbedtls_mpi_read_binary_le(mbedtls_mpi * X,const unsigned char * buf,size_t buflen)814 int mbedtls_mpi_read_binary_le(mbedtls_mpi *X,
815 const unsigned char *buf, size_t buflen)
816 {
817 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
818 const size_t limbs = CHARS_TO_LIMBS(buflen);
819
820 /* Ensure that target MPI has exactly the necessary number of limbs */
821 MBEDTLS_MPI_CHK(mbedtls_mpi_resize_clear(X, limbs));
822
823 MBEDTLS_MPI_CHK(mbedtls_mpi_core_read_le(X->p, X->n, buf, buflen));
824
825 cleanup:
826
827 /*
828 * This function is also used to import keys. However, wiping the buffers
829 * upon failure is not necessary because failure only can happen before any
830 * input is copied.
831 */
832 return ret;
833 }
834
835 /*
836 * Import X from unsigned binary data, big endian
837 *
838 * This function is guaranteed to return an MPI with exactly the necessary
839 * number of limbs (in particular, it does not skip 0s in the input).
840 */
mbedtls_mpi_read_binary(mbedtls_mpi * X,const unsigned char * buf,size_t buflen)841 int mbedtls_mpi_read_binary(mbedtls_mpi *X, const unsigned char *buf, size_t buflen)
842 {
843 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
844 const size_t limbs = CHARS_TO_LIMBS(buflen);
845
846 MPI_VALIDATE_RET(X != NULL);
847 MPI_VALIDATE_RET(buflen == 0 || buf != NULL);
848
849 /* Ensure that target MPI has exactly the necessary number of limbs */
850 MBEDTLS_MPI_CHK(mbedtls_mpi_resize_clear(X, limbs));
851
852 MBEDTLS_MPI_CHK(mbedtls_mpi_core_read_be(X->p, X->n, buf, buflen));
853
854 cleanup:
855
856 /*
857 * This function is also used to import keys. However, wiping the buffers
858 * upon failure is not necessary because failure only can happen before any
859 * input is copied.
860 */
861 return ret;
862 }
863
864 /*
865 * Export X into unsigned binary data, little endian
866 */
mbedtls_mpi_write_binary_le(const mbedtls_mpi * X,unsigned char * buf,size_t buflen)867 int mbedtls_mpi_write_binary_le(const mbedtls_mpi *X,
868 unsigned char *buf, size_t buflen)
869 {
870 return mbedtls_mpi_core_write_le(X->p, X->n, buf, buflen);
871 }
872
873 /*
874 * Export X into unsigned binary data, big endian
875 */
mbedtls_mpi_write_binary(const mbedtls_mpi * X,unsigned char * buf,size_t buflen)876 int mbedtls_mpi_write_binary(const mbedtls_mpi *X,
877 unsigned char *buf, size_t buflen)
878 {
879 return mbedtls_mpi_core_write_be(X->p, X->n, buf, buflen);
880 }
881
882 /*
883 * Left-shift: X <<= count
884 */
mbedtls_mpi_shift_l(mbedtls_mpi * X,size_t count)885 int mbedtls_mpi_shift_l(mbedtls_mpi *X, size_t count)
886 {
887 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
888 size_t i;
889 MPI_VALIDATE_RET(X != NULL);
890
891 i = mbedtls_mpi_bitlen(X) + count;
892
893 if (X->n * biL < i) {
894 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, BITS_TO_LIMBS(i)));
895 }
896
897 ret = 0;
898
899 mbedtls_mpi_core_shift_l(X->p, X->n, count);
900 cleanup:
901
902 return ret;
903 }
904
905 /*
906 * Right-shift: X >>= count
907 */
mbedtls_mpi_shift_r(mbedtls_mpi * X,size_t count)908 int mbedtls_mpi_shift_r(mbedtls_mpi *X, size_t count)
909 {
910 MPI_VALIDATE_RET(X != NULL);
911 if (X->n != 0) {
912 mbedtls_mpi_core_shift_r(X->p, X->n, count);
913 }
914 return 0;
915 }
916
917 /*
918 * Compare unsigned values
919 */
mbedtls_mpi_cmp_abs(const mbedtls_mpi * X,const mbedtls_mpi * Y)920 int mbedtls_mpi_cmp_abs(const mbedtls_mpi *X, const mbedtls_mpi *Y)
921 {
922 size_t i, j;
923 MPI_VALIDATE_RET(X != NULL);
924 MPI_VALIDATE_RET(Y != NULL);
925
926 for (i = X->n; i > 0; i--) {
927 if (X->p[i - 1] != 0) {
928 break;
929 }
930 }
931
932 for (j = Y->n; j > 0; j--) {
933 if (Y->p[j - 1] != 0) {
934 break;
935 }
936 }
937
938 /* If i == j == 0, i.e. abs(X) == abs(Y),
939 * we end up returning 0 at the end of the function. */
940
941 if (i > j) {
942 return 1;
943 }
944 if (j > i) {
945 return -1;
946 }
947
948 for (; i > 0; i--) {
949 if (X->p[i - 1] > Y->p[i - 1]) {
950 return 1;
951 }
952 if (X->p[i - 1] < Y->p[i - 1]) {
953 return -1;
954 }
955 }
956
957 return 0;
958 }
959
960 /*
961 * Compare signed values
962 */
mbedtls_mpi_cmp_mpi(const mbedtls_mpi * X,const mbedtls_mpi * Y)963 int mbedtls_mpi_cmp_mpi(const mbedtls_mpi *X, const mbedtls_mpi *Y)
964 {
965 size_t i, j;
966 MPI_VALIDATE_RET(X != NULL);
967 MPI_VALIDATE_RET(Y != NULL);
968
969 for (i = X->n; i > 0; i--) {
970 if (X->p[i - 1] != 0) {
971 break;
972 }
973 }
974
975 for (j = Y->n; j > 0; j--) {
976 if (Y->p[j - 1] != 0) {
977 break;
978 }
979 }
980
981 if (i == 0 && j == 0) {
982 return 0;
983 }
984
985 if (i > j) {
986 return X->s;
987 }
988 if (j > i) {
989 return -Y->s;
990 }
991
992 if (X->s > 0 && Y->s < 0) {
993 return 1;
994 }
995 if (Y->s > 0 && X->s < 0) {
996 return -1;
997 }
998
999 for (; i > 0; i--) {
1000 if (X->p[i - 1] > Y->p[i - 1]) {
1001 return X->s;
1002 }
1003 if (X->p[i - 1] < Y->p[i - 1]) {
1004 return -X->s;
1005 }
1006 }
1007
1008 return 0;
1009 }
1010
1011 /*
1012 * Compare signed values
1013 */
mbedtls_mpi_cmp_int(const mbedtls_mpi * X,mbedtls_mpi_sint z)1014 int mbedtls_mpi_cmp_int(const mbedtls_mpi *X, mbedtls_mpi_sint z)
1015 {
1016 mbedtls_mpi Y;
1017 mbedtls_mpi_uint p[1];
1018 MPI_VALIDATE_RET(X != NULL);
1019
1020 *p = mpi_sint_abs(z);
1021 Y.s = TO_SIGN(z);
1022 Y.n = 1;
1023 Y.p = p;
1024
1025 return mbedtls_mpi_cmp_mpi(X, &Y);
1026 }
1027
1028 /*
1029 * Unsigned addition: X = |A| + |B| (HAC 14.7)
1030 */
mbedtls_mpi_add_abs(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1031 int mbedtls_mpi_add_abs(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B)
1032 {
1033 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1034 size_t j;
1035 mbedtls_mpi_uint *p;
1036 mbedtls_mpi_uint c;
1037 MPI_VALIDATE_RET(X != NULL);
1038 MPI_VALIDATE_RET(A != NULL);
1039 MPI_VALIDATE_RET(B != NULL);
1040
1041 if (X == B) {
1042 const mbedtls_mpi *T = A; A = X; B = T;
1043 }
1044
1045 if (X != A) {
1046 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, A));
1047 }
1048
1049 /*
1050 * X must always be positive as a result of unsigned additions.
1051 */
1052 X->s = 1;
1053
1054 for (j = B->n; j > 0; j--) {
1055 if (B->p[j - 1] != 0) {
1056 break;
1057 }
1058 }
1059
1060 /* Exit early to avoid undefined behavior on NULL+0 when X->n == 0
1061 * and B is 0 (of any size). */
1062 if (j == 0) {
1063 return 0;
1064 }
1065
1066 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, j));
1067
1068 /* j is the number of non-zero limbs of B. Add those to X. */
1069
1070 p = X->p;
1071
1072 c = mbedtls_mpi_core_add(p, p, B->p, j);
1073
1074 p += j;
1075
1076 /* Now propagate any carry */
1077
1078 while (c != 0) {
1079 if (j >= X->n) {
1080 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, j + 1));
1081 p = X->p + j;
1082 }
1083
1084 *p += c; c = (*p < c); j++; p++;
1085 }
1086
1087 cleanup:
1088
1089 return ret;
1090 }
1091
1092 /*
1093 * Unsigned subtraction: X = |A| - |B| (HAC 14.9, 14.10)
1094 */
mbedtls_mpi_sub_abs(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1095 int mbedtls_mpi_sub_abs(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B)
1096 {
1097 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1098 size_t n;
1099 mbedtls_mpi_uint carry;
1100 MPI_VALIDATE_RET(X != NULL);
1101 MPI_VALIDATE_RET(A != NULL);
1102 MPI_VALIDATE_RET(B != NULL);
1103
1104 for (n = B->n; n > 0; n--) {
1105 if (B->p[n - 1] != 0) {
1106 break;
1107 }
1108 }
1109 if (n > A->n) {
1110 /* B >= (2^ciL)^n > A */
1111 ret = MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
1112 goto cleanup;
1113 }
1114
1115 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, A->n));
1116
1117 /* Set the high limbs of X to match A. Don't touch the lower limbs
1118 * because X might be aliased to B, and we must not overwrite the
1119 * significant digits of B. */
1120 if (A->n > n && A != X) {
1121 memcpy(X->p + n, A->p + n, (A->n - n) * ciL);
1122 }
1123 if (X->n > A->n) {
1124 memset(X->p + A->n, 0, (X->n - A->n) * ciL);
1125 }
1126
1127 carry = mbedtls_mpi_core_sub(X->p, A->p, B->p, n);
1128 if (carry != 0) {
1129 /* Propagate the carry through the rest of X. */
1130 carry = mbedtls_mpi_core_sub_int(X->p + n, X->p + n, carry, X->n - n);
1131
1132 /* If we have further carry/borrow, the result is negative. */
1133 if (carry != 0) {
1134 ret = MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
1135 goto cleanup;
1136 }
1137 }
1138
1139 /* X should always be positive as a result of unsigned subtractions. */
1140 X->s = 1;
1141
1142 cleanup:
1143 return ret;
1144 }
1145
1146 /* Common function for signed addition and subtraction.
1147 * Calculate A + B * flip_B where flip_B is 1 or -1.
1148 */
add_sub_mpi(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B,int flip_B)1149 static int add_sub_mpi(mbedtls_mpi *X,
1150 const mbedtls_mpi *A, const mbedtls_mpi *B,
1151 int flip_B)
1152 {
1153 int ret, s;
1154 MPI_VALIDATE_RET(X != NULL);
1155 MPI_VALIDATE_RET(A != NULL);
1156 MPI_VALIDATE_RET(B != NULL);
1157
1158 s = A->s;
1159 if (A->s * B->s * flip_B < 0) {
1160 int cmp = mbedtls_mpi_cmp_abs(A, B);
1161 if (cmp >= 0) {
1162 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(X, A, B));
1163 /* If |A| = |B|, the result is 0 and we must set the sign bit
1164 * to +1 regardless of which of A or B was negative. Otherwise,
1165 * since |A| > |B|, the sign is the sign of A. */
1166 X->s = cmp == 0 ? 1 : s;
1167 } else {
1168 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(X, B, A));
1169 /* Since |A| < |B|, the sign is the opposite of A. */
1170 X->s = -s;
1171 }
1172 } else {
1173 MBEDTLS_MPI_CHK(mbedtls_mpi_add_abs(X, A, B));
1174 X->s = s;
1175 }
1176
1177 cleanup:
1178
1179 return ret;
1180 }
1181
1182 /*
1183 * Signed addition: X = A + B
1184 */
mbedtls_mpi_add_mpi(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1185 int mbedtls_mpi_add_mpi(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B)
1186 {
1187 return add_sub_mpi(X, A, B, 1);
1188 }
1189
1190 /*
1191 * Signed subtraction: X = A - B
1192 */
mbedtls_mpi_sub_mpi(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1193 int mbedtls_mpi_sub_mpi(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B)
1194 {
1195 return add_sub_mpi(X, A, B, -1);
1196 }
1197
1198 /*
1199 * Signed addition: X = A + b
1200 */
mbedtls_mpi_add_int(mbedtls_mpi * X,const mbedtls_mpi * A,mbedtls_mpi_sint b)1201 int mbedtls_mpi_add_int(mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b)
1202 {
1203 mbedtls_mpi B;
1204 mbedtls_mpi_uint p[1];
1205 MPI_VALIDATE_RET(X != NULL);
1206 MPI_VALIDATE_RET(A != NULL);
1207
1208 p[0] = mpi_sint_abs(b);
1209 B.s = TO_SIGN(b);
1210 B.n = 1;
1211 B.p = p;
1212
1213 return mbedtls_mpi_add_mpi(X, A, &B);
1214 }
1215
1216 /*
1217 * Signed subtraction: X = A - b
1218 */
mbedtls_mpi_sub_int(mbedtls_mpi * X,const mbedtls_mpi * A,mbedtls_mpi_sint b)1219 int mbedtls_mpi_sub_int(mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_sint b)
1220 {
1221 mbedtls_mpi B;
1222 mbedtls_mpi_uint p[1];
1223 MPI_VALIDATE_RET(X != NULL);
1224 MPI_VALIDATE_RET(A != NULL);
1225
1226 p[0] = mpi_sint_abs(b);
1227 B.s = TO_SIGN(b);
1228 B.n = 1;
1229 B.p = p;
1230
1231 return mbedtls_mpi_sub_mpi(X, A, &B);
1232 }
1233
1234 /*
1235 * Baseline multiplication: X = A * B (HAC 14.12)
1236 */
mbedtls_mpi_mul_mpi(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * B)1237 int mbedtls_mpi_mul_mpi(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *B)
1238 {
1239 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1240 size_t i, j;
1241 mbedtls_mpi TA, TB;
1242 int result_is_zero = 0;
1243 MPI_VALIDATE_RET(X != NULL);
1244 MPI_VALIDATE_RET(A != NULL);
1245 MPI_VALIDATE_RET(B != NULL);
1246
1247 mbedtls_mpi_init(&TA);
1248 mbedtls_mpi_init(&TB);
1249
1250 if (X == A) {
1251 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TA, A)); A = &TA;
1252 }
1253 if (X == B) {
1254 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TB, B)); B = &TB;
1255 }
1256
1257 for (i = A->n; i > 0; i--) {
1258 if (A->p[i - 1] != 0) {
1259 break;
1260 }
1261 }
1262 if (i == 0) {
1263 result_is_zero = 1;
1264 }
1265
1266 for (j = B->n; j > 0; j--) {
1267 if (B->p[j - 1] != 0) {
1268 break;
1269 }
1270 }
1271 if (j == 0) {
1272 result_is_zero = 1;
1273 }
1274
1275 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, i + j));
1276 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, 0));
1277
1278 mbedtls_mpi_core_mul(X->p, A->p, i, B->p, j);
1279
1280 /* If the result is 0, we don't shortcut the operation, which reduces
1281 * but does not eliminate side channels leaking the zero-ness. We do
1282 * need to take care to set the sign bit properly since the library does
1283 * not fully support an MPI object with a value of 0 and s == -1. */
1284 if (result_is_zero) {
1285 X->s = 1;
1286 } else {
1287 X->s = A->s * B->s;
1288 }
1289
1290 cleanup:
1291
1292 mbedtls_mpi_free(&TB); mbedtls_mpi_free(&TA);
1293
1294 return ret;
1295 }
1296
1297 /*
1298 * Baseline multiplication: X = A * b
1299 */
mbedtls_mpi_mul_int(mbedtls_mpi * X,const mbedtls_mpi * A,mbedtls_mpi_uint b)1300 int mbedtls_mpi_mul_int(mbedtls_mpi *X, const mbedtls_mpi *A, mbedtls_mpi_uint b)
1301 {
1302 MPI_VALIDATE_RET(X != NULL);
1303 MPI_VALIDATE_RET(A != NULL);
1304
1305 size_t n = A->n;
1306 while (n > 0 && A->p[n - 1] == 0) {
1307 --n;
1308 }
1309
1310 /* The general method below doesn't work if b==0. */
1311 if (b == 0 || n == 0) {
1312 return mbedtls_mpi_lset(X, 0);
1313 }
1314
1315 /* Calculate A*b as A + A*(b-1) to take advantage of mbedtls_mpi_core_mla */
1316 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1317 /* In general, A * b requires 1 limb more than b. If
1318 * A->p[n - 1] * b / b == A->p[n - 1], then A * b fits in the same
1319 * number of limbs as A and the call to grow() is not required since
1320 * copy() will take care of the growth if needed. However, experimentally,
1321 * making the call to grow() unconditional causes slightly fewer
1322 * calls to calloc() in ECP code, presumably because it reuses the
1323 * same mpi for a while and this way the mpi is more likely to directly
1324 * grow to its final size.
1325 *
1326 * Note that calculating A*b as 0 + A*b doesn't work as-is because
1327 * A,X can be the same. */
1328 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(X, n + 1));
1329 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, A));
1330 mbedtls_mpi_core_mla(X->p, X->n, A->p, n, b - 1);
1331
1332 cleanup:
1333 return ret;
1334 }
1335
1336 /*
1337 * Unsigned integer divide - double mbedtls_mpi_uint dividend, u1/u0, and
1338 * mbedtls_mpi_uint divisor, d
1339 */
mbedtls_int_div_int(mbedtls_mpi_uint u1,mbedtls_mpi_uint u0,mbedtls_mpi_uint d,mbedtls_mpi_uint * r)1340 static mbedtls_mpi_uint mbedtls_int_div_int(mbedtls_mpi_uint u1,
1341 mbedtls_mpi_uint u0,
1342 mbedtls_mpi_uint d,
1343 mbedtls_mpi_uint *r)
1344 {
1345 #if defined(MBEDTLS_HAVE_UDBL)
1346 mbedtls_t_udbl dividend, quotient;
1347 #else
1348 const mbedtls_mpi_uint radix = (mbedtls_mpi_uint) 1 << biH;
1349 const mbedtls_mpi_uint uint_halfword_mask = ((mbedtls_mpi_uint) 1 << biH) - 1;
1350 mbedtls_mpi_uint d0, d1, q0, q1, rAX, r0, quotient;
1351 mbedtls_mpi_uint u0_msw, u0_lsw;
1352 size_t s;
1353 #endif
1354
1355 /*
1356 * Check for overflow
1357 */
1358 if (0 == d || u1 >= d) {
1359 if (r != NULL) {
1360 *r = ~(mbedtls_mpi_uint) 0u;
1361 }
1362
1363 return ~(mbedtls_mpi_uint) 0u;
1364 }
1365
1366 #if defined(MBEDTLS_HAVE_UDBL)
1367 dividend = (mbedtls_t_udbl) u1 << biL;
1368 dividend |= (mbedtls_t_udbl) u0;
1369 quotient = dividend / d;
1370 if (quotient > ((mbedtls_t_udbl) 1 << biL) - 1) {
1371 quotient = ((mbedtls_t_udbl) 1 << biL) - 1;
1372 }
1373
1374 if (r != NULL) {
1375 *r = (mbedtls_mpi_uint) (dividend - (quotient * d));
1376 }
1377
1378 return (mbedtls_mpi_uint) quotient;
1379 #else
1380
1381 /*
1382 * Algorithm D, Section 4.3.1 - The Art of Computer Programming
1383 * Vol. 2 - Seminumerical Algorithms, Knuth
1384 */
1385
1386 /*
1387 * Normalize the divisor, d, and dividend, u0, u1
1388 */
1389 s = mbedtls_mpi_core_clz(d);
1390 d = d << s;
1391
1392 u1 = u1 << s;
1393 u1 |= (u0 >> (biL - s)) & (-(mbedtls_mpi_sint) s >> (biL - 1));
1394 u0 = u0 << s;
1395
1396 d1 = d >> biH;
1397 d0 = d & uint_halfword_mask;
1398
1399 u0_msw = u0 >> biH;
1400 u0_lsw = u0 & uint_halfword_mask;
1401
1402 /*
1403 * Find the first quotient and remainder
1404 */
1405 q1 = u1 / d1;
1406 r0 = u1 - d1 * q1;
1407
1408 while (q1 >= radix || (q1 * d0 > radix * r0 + u0_msw)) {
1409 q1 -= 1;
1410 r0 += d1;
1411
1412 if (r0 >= radix) {
1413 break;
1414 }
1415 }
1416
1417 rAX = (u1 * radix) + (u0_msw - q1 * d);
1418 q0 = rAX / d1;
1419 r0 = rAX - q0 * d1;
1420
1421 while (q0 >= radix || (q0 * d0 > radix * r0 + u0_lsw)) {
1422 q0 -= 1;
1423 r0 += d1;
1424
1425 if (r0 >= radix) {
1426 break;
1427 }
1428 }
1429
1430 if (r != NULL) {
1431 *r = (rAX * radix + u0_lsw - q0 * d) >> s;
1432 }
1433
1434 quotient = q1 * radix + q0;
1435
1436 return quotient;
1437 #endif
1438 }
1439
1440 /*
1441 * Division by mbedtls_mpi: A = Q * B + R (HAC 14.20)
1442 */
mbedtls_mpi_div_mpi(mbedtls_mpi * Q,mbedtls_mpi * R,const mbedtls_mpi * A,const mbedtls_mpi * B)1443 int mbedtls_mpi_div_mpi(mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A,
1444 const mbedtls_mpi *B)
1445 {
1446 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1447 size_t i, n, t, k;
1448 mbedtls_mpi X, Y, Z, T1, T2;
1449 mbedtls_mpi_uint TP2[3];
1450 MPI_VALIDATE_RET(A != NULL);
1451 MPI_VALIDATE_RET(B != NULL);
1452
1453 if (mbedtls_mpi_cmp_int(B, 0) == 0) {
1454 return MBEDTLS_ERR_MPI_DIVISION_BY_ZERO;
1455 }
1456
1457 mbedtls_mpi_init(&X); mbedtls_mpi_init(&Y); mbedtls_mpi_init(&Z);
1458 mbedtls_mpi_init(&T1);
1459 /*
1460 * Avoid dynamic memory allocations for constant-size T2.
1461 *
1462 * T2 is used for comparison only and the 3 limbs are assigned explicitly,
1463 * so nobody increase the size of the MPI and we're safe to use an on-stack
1464 * buffer.
1465 */
1466 T2.s = 1;
1467 T2.n = sizeof(TP2) / sizeof(*TP2);
1468 T2.p = TP2;
1469
1470 if (mbedtls_mpi_cmp_abs(A, B) < 0) {
1471 if (Q != NULL) {
1472 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(Q, 0));
1473 }
1474 if (R != NULL) {
1475 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(R, A));
1476 }
1477 return 0;
1478 }
1479
1480 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&X, A));
1481 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&Y, B));
1482 X.s = Y.s = 1;
1483
1484 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&Z, A->n + 2));
1485 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&Z, 0));
1486 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&T1, A->n + 2));
1487
1488 k = mbedtls_mpi_bitlen(&Y) % biL;
1489 if (k < biL - 1) {
1490 k = biL - 1 - k;
1491 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&X, k));
1492 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&Y, k));
1493 } else {
1494 k = 0;
1495 }
1496
1497 n = X.n - 1;
1498 t = Y.n - 1;
1499 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&Y, biL * (n - t)));
1500
1501 while (mbedtls_mpi_cmp_mpi(&X, &Y) >= 0) {
1502 Z.p[n - t]++;
1503 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&X, &X, &Y));
1504 }
1505 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&Y, biL * (n - t)));
1506
1507 for (i = n; i > t; i--) {
1508 if (X.p[i] >= Y.p[t]) {
1509 Z.p[i - t - 1] = ~(mbedtls_mpi_uint) 0u;
1510 } else {
1511 Z.p[i - t - 1] = mbedtls_int_div_int(X.p[i], X.p[i - 1],
1512 Y.p[t], NULL);
1513 }
1514
1515 T2.p[0] = (i < 2) ? 0 : X.p[i - 2];
1516 T2.p[1] = (i < 1) ? 0 : X.p[i - 1];
1517 T2.p[2] = X.p[i];
1518
1519 Z.p[i - t - 1]++;
1520 do {
1521 Z.p[i - t - 1]--;
1522
1523 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&T1, 0));
1524 T1.p[0] = (t < 1) ? 0 : Y.p[t - 1];
1525 T1.p[1] = Y.p[t];
1526 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int(&T1, &T1, Z.p[i - t - 1]));
1527 } while (mbedtls_mpi_cmp_mpi(&T1, &T2) > 0);
1528
1529 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int(&T1, &Y, Z.p[i - t - 1]));
1530 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&T1, biL * (i - t - 1)));
1531 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&X, &X, &T1));
1532
1533 if (mbedtls_mpi_cmp_int(&X, 0) < 0) {
1534 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&T1, &Y));
1535 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&T1, biL * (i - t - 1)));
1536 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&X, &X, &T1));
1537 Z.p[i - t - 1]--;
1538 }
1539 }
1540
1541 if (Q != NULL) {
1542 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(Q, &Z));
1543 Q->s = A->s * B->s;
1544 }
1545
1546 if (R != NULL) {
1547 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&X, k));
1548 X.s = A->s;
1549 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(R, &X));
1550
1551 if (mbedtls_mpi_cmp_int(R, 0) == 0) {
1552 R->s = 1;
1553 }
1554 }
1555
1556 cleanup:
1557
1558 mbedtls_mpi_free(&X); mbedtls_mpi_free(&Y); mbedtls_mpi_free(&Z);
1559 mbedtls_mpi_free(&T1);
1560 mbedtls_platform_zeroize(TP2, sizeof(TP2));
1561
1562 return ret;
1563 }
1564
1565 /*
1566 * Division by int: A = Q * b + R
1567 */
mbedtls_mpi_div_int(mbedtls_mpi * Q,mbedtls_mpi * R,const mbedtls_mpi * A,mbedtls_mpi_sint b)1568 int mbedtls_mpi_div_int(mbedtls_mpi *Q, mbedtls_mpi *R,
1569 const mbedtls_mpi *A,
1570 mbedtls_mpi_sint b)
1571 {
1572 mbedtls_mpi B;
1573 mbedtls_mpi_uint p[1];
1574 MPI_VALIDATE_RET(A != NULL);
1575
1576 p[0] = mpi_sint_abs(b);
1577 B.s = TO_SIGN(b);
1578 B.n = 1;
1579 B.p = p;
1580
1581 return mbedtls_mpi_div_mpi(Q, R, A, &B);
1582 }
1583
1584 /*
1585 * Modulo: R = A mod B
1586 */
mbedtls_mpi_mod_mpi(mbedtls_mpi * R,const mbedtls_mpi * A,const mbedtls_mpi * B)1587 int mbedtls_mpi_mod_mpi(mbedtls_mpi *R, const mbedtls_mpi *A, const mbedtls_mpi *B)
1588 {
1589 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1590 MPI_VALIDATE_RET(R != NULL);
1591 MPI_VALIDATE_RET(A != NULL);
1592 MPI_VALIDATE_RET(B != NULL);
1593
1594 if (mbedtls_mpi_cmp_int(B, 0) < 0) {
1595 return MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
1596 }
1597
1598 MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(NULL, R, A, B));
1599
1600 while (mbedtls_mpi_cmp_int(R, 0) < 0) {
1601 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(R, R, B));
1602 }
1603
1604 while (mbedtls_mpi_cmp_mpi(R, B) >= 0) {
1605 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(R, R, B));
1606 }
1607
1608 cleanup:
1609
1610 return ret;
1611 }
1612
1613 /*
1614 * Modulo: r = A mod b
1615 */
mbedtls_mpi_mod_int(mbedtls_mpi_uint * r,const mbedtls_mpi * A,mbedtls_mpi_sint b)1616 int mbedtls_mpi_mod_int(mbedtls_mpi_uint *r, const mbedtls_mpi *A, mbedtls_mpi_sint b)
1617 {
1618 size_t i;
1619 mbedtls_mpi_uint x, y, z;
1620 MPI_VALIDATE_RET(r != NULL);
1621 MPI_VALIDATE_RET(A != NULL);
1622
1623 if (b == 0) {
1624 return MBEDTLS_ERR_MPI_DIVISION_BY_ZERO;
1625 }
1626
1627 if (b < 0) {
1628 return MBEDTLS_ERR_MPI_NEGATIVE_VALUE;
1629 }
1630
1631 /*
1632 * handle trivial cases
1633 */
1634 if (b == 1 || A->n == 0) {
1635 *r = 0;
1636 return 0;
1637 }
1638
1639 if (b == 2) {
1640 *r = A->p[0] & 1;
1641 return 0;
1642 }
1643
1644 /*
1645 * general case
1646 */
1647 for (i = A->n, y = 0; i > 0; i--) {
1648 x = A->p[i - 1];
1649 y = (y << biH) | (x >> biH);
1650 z = y / b;
1651 y -= z * b;
1652
1653 x <<= biH;
1654 y = (y << biH) | (x >> biH);
1655 z = y / b;
1656 y -= z * b;
1657 }
1658
1659 /*
1660 * If A is negative, then the current y represents a negative value.
1661 * Flipping it to the positive side.
1662 */
1663 if (A->s < 0 && y != 0) {
1664 y = b - y;
1665 }
1666
1667 *r = y;
1668
1669 return 0;
1670 }
1671
mpi_montg_init(mbedtls_mpi_uint * mm,const mbedtls_mpi * N)1672 static void mpi_montg_init(mbedtls_mpi_uint *mm, const mbedtls_mpi *N)
1673 {
1674 *mm = mbedtls_mpi_core_montmul_init(N->p);
1675 }
1676
1677 /** Montgomery multiplication: A = A * B * R^-1 mod N (HAC 14.36)
1678 *
1679 * \param[in,out] A One of the numbers to multiply.
1680 * It must have at least as many limbs as N
1681 * (A->n >= N->n), and any limbs beyond n are ignored.
1682 * On successful completion, A contains the result of
1683 * the multiplication A * B * R^-1 mod N where
1684 * R = (2^ciL)^n.
1685 * \param[in] B One of the numbers to multiply.
1686 * It must be nonzero and must not have more limbs than N
1687 * (B->n <= N->n).
1688 * \param[in] N The modulus. \p N must be odd.
1689 * \param mm The value calculated by `mpi_montg_init(&mm, N)`.
1690 * This is -N^-1 mod 2^ciL.
1691 * \param[in,out] T A bignum for temporary storage.
1692 * It must be at least twice the limb size of N plus 1
1693 * (T->n >= 2 * N->n + 1).
1694 * Its initial content is unused and
1695 * its final content is indeterminate.
1696 * It does not get reallocated.
1697 */
mpi_montmul(mbedtls_mpi * A,const mbedtls_mpi * B,const mbedtls_mpi * N,mbedtls_mpi_uint mm,mbedtls_mpi * T)1698 static void mpi_montmul(mbedtls_mpi *A, const mbedtls_mpi *B,
1699 const mbedtls_mpi *N, mbedtls_mpi_uint mm,
1700 mbedtls_mpi *T)
1701 {
1702 mbedtls_mpi_core_montmul(A->p, A->p, B->p, B->n, N->p, N->n, mm, T->p);
1703 }
1704
1705 /*
1706 * Montgomery reduction: A = A * R^-1 mod N
1707 *
1708 * See mpi_montmul() regarding constraints and guarantees on the parameters.
1709 */
mpi_montred(mbedtls_mpi * A,const mbedtls_mpi * N,mbedtls_mpi_uint mm,mbedtls_mpi * T)1710 static void mpi_montred(mbedtls_mpi *A, const mbedtls_mpi *N,
1711 mbedtls_mpi_uint mm, mbedtls_mpi *T)
1712 {
1713 mbedtls_mpi_uint z = 1;
1714 mbedtls_mpi U;
1715 U.n = 1;
1716 U.s = 1;
1717 U.p = &z;
1718
1719 mpi_montmul(A, &U, N, mm, T);
1720 }
1721
1722 /**
1723 * Select an MPI from a table without leaking the index.
1724 *
1725 * This is functionally equivalent to mbedtls_mpi_copy(R, T[idx]) except it
1726 * reads the entire table in order to avoid leaking the value of idx to an
1727 * attacker able to observe memory access patterns.
1728 *
1729 * \param[out] R Where to write the selected MPI.
1730 * \param[in] T The table to read from.
1731 * \param[in] T_size The number of elements in the table.
1732 * \param[in] idx The index of the element to select;
1733 * this must satisfy 0 <= idx < T_size.
1734 *
1735 * \return \c 0 on success, or a negative error code.
1736 */
mpi_select(mbedtls_mpi * R,const mbedtls_mpi * T,size_t T_size,size_t idx)1737 static int mpi_select(mbedtls_mpi *R, const mbedtls_mpi *T, size_t T_size, size_t idx)
1738 {
1739 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1740
1741 for (size_t i = 0; i < T_size; i++) {
1742 MBEDTLS_MPI_CHK(mbedtls_mpi_safe_cond_assign(R, &T[i],
1743 (unsigned char) mbedtls_ct_uint_eq(i, idx)));
1744 }
1745 cleanup:
1746 return ret;
1747 }
1748
1749 /*
1750 * Sliding-window exponentiation: X = A^E mod N (HAC 14.85)
1751 */
mbedtls_mpi_exp_mod(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * E,const mbedtls_mpi * N,mbedtls_mpi * prec_RR)1752 int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
1753 const mbedtls_mpi *E, const mbedtls_mpi *N,
1754 mbedtls_mpi *prec_RR)
1755 {
1756 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1757 size_t window_bitsize;
1758 size_t i, j, nblimbs;
1759 size_t bufsize, nbits;
1760 size_t exponent_bits_in_window = 0;
1761 mbedtls_mpi_uint ei, mm, state;
1762 mbedtls_mpi RR, T, W[(size_t) 1 << MBEDTLS_MPI_WINDOW_SIZE], WW, Apos;
1763 int neg;
1764
1765 MPI_VALIDATE_RET(X != NULL);
1766 MPI_VALIDATE_RET(A != NULL);
1767 MPI_VALIDATE_RET(E != NULL);
1768 MPI_VALIDATE_RET(N != NULL);
1769
1770 if (mbedtls_mpi_cmp_int(N, 0) <= 0 || (N->p[0] & 1) == 0) {
1771 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
1772 }
1773
1774 if (mbedtls_mpi_cmp_int(E, 0) < 0) {
1775 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
1776 }
1777
1778 if (mbedtls_mpi_bitlen(E) > MBEDTLS_MPI_MAX_BITS ||
1779 mbedtls_mpi_bitlen(N) > MBEDTLS_MPI_MAX_BITS) {
1780 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
1781 }
1782
1783 /*
1784 * Init temps and window size
1785 */
1786 mpi_montg_init(&mm, N);
1787 mbedtls_mpi_init(&RR); mbedtls_mpi_init(&T);
1788 mbedtls_mpi_init(&Apos);
1789 mbedtls_mpi_init(&WW);
1790 memset(W, 0, sizeof(W));
1791
1792 i = mbedtls_mpi_bitlen(E);
1793
1794 window_bitsize = (i > 671) ? 6 : (i > 239) ? 5 :
1795 (i > 79) ? 4 : (i > 23) ? 3 : 1;
1796
1797 #if (MBEDTLS_MPI_WINDOW_SIZE < 6)
1798 if (window_bitsize > MBEDTLS_MPI_WINDOW_SIZE) {
1799 window_bitsize = MBEDTLS_MPI_WINDOW_SIZE;
1800 }
1801 #endif
1802
1803 const size_t w_table_used_size = (size_t) 1 << window_bitsize;
1804
1805 /*
1806 * This function is not constant-trace: its memory accesses depend on the
1807 * exponent value. To defend against timing attacks, callers (such as RSA
1808 * and DHM) should use exponent blinding. However this is not enough if the
1809 * adversary can find the exponent in a single trace, so this function
1810 * takes extra precautions against adversaries who can observe memory
1811 * access patterns.
1812 *
1813 * This function performs a series of multiplications by table elements and
1814 * squarings, and we want the prevent the adversary from finding out which
1815 * table element was used, and from distinguishing between multiplications
1816 * and squarings. Firstly, when multiplying by an element of the window
1817 * W[i], we do a constant-trace table lookup to obfuscate i. This leaves
1818 * squarings as having a different memory access patterns from other
1819 * multiplications. So secondly, we put the accumulator in the table as
1820 * well, and also do a constant-trace table lookup to multiply by the
1821 * accumulator which is W[x_index].
1822 *
1823 * This way, all multiplications take the form of a lookup-and-multiply.
1824 * The number of lookup-and-multiply operations inside each iteration of
1825 * the main loop still depends on the bits of the exponent, but since the
1826 * other operations in the loop don't have an easily recognizable memory
1827 * trace, an adversary is unlikely to be able to observe the exact
1828 * patterns.
1829 *
1830 * An adversary may still be able to recover the exponent if they can
1831 * observe both memory accesses and branches. However, branch prediction
1832 * exploitation typically requires many traces of execution over the same
1833 * data, which is defeated by randomized blinding.
1834 */
1835 const size_t x_index = 0;
1836 mbedtls_mpi_init(&W[x_index]);
1837
1838 j = N->n + 1;
1839 /* All W[i] including the accumulator must have at least N->n limbs for
1840 * the mpi_montmul() and mpi_montred() calls later. Here we ensure that
1841 * W[1] and the accumulator W[x_index] are large enough. later we'll grow
1842 * other W[i] to the same length. They must not be shrunk midway through
1843 * this function!
1844 */
1845 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[x_index], j));
1846 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[1], j));
1847 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&T, j * 2));
1848
1849 /*
1850 * Compensate for negative A (and correct at the end)
1851 */
1852 neg = (A->s == -1);
1853 if (neg) {
1854 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&Apos, A));
1855 Apos.s = 1;
1856 A = &Apos;
1857 }
1858
1859 /*
1860 * If 1st call, pre-compute R^2 mod N
1861 */
1862 if (prec_RR == NULL || prec_RR->p == NULL) {
1863 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&RR, 1));
1864 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&RR, N->n * 2 * biL));
1865 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&RR, &RR, N));
1866
1867 if (prec_RR != NULL) {
1868 memcpy(prec_RR, &RR, sizeof(mbedtls_mpi));
1869 }
1870 } else {
1871 memcpy(&RR, prec_RR, sizeof(mbedtls_mpi));
1872 }
1873
1874 /*
1875 * W[1] = A * R^2 * R^-1 mod N = A * R mod N
1876 */
1877 if (mbedtls_mpi_cmp_mpi(A, N) >= 0) {
1878 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&W[1], A, N));
1879 /* This should be a no-op because W[1] is already that large before
1880 * mbedtls_mpi_mod_mpi(), but it's necessary to avoid an overflow
1881 * in mpi_montmul() below, so let's make sure. */
1882 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[1], N->n + 1));
1883 } else {
1884 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&W[1], A));
1885 }
1886
1887 /* Note that this is safe because W[1] always has at least N->n limbs
1888 * (it grew above and was preserved by mbedtls_mpi_copy()). */
1889 mpi_montmul(&W[1], &RR, N, mm, &T);
1890
1891 /*
1892 * W[x_index] = R^2 * R^-1 mod N = R mod N
1893 */
1894 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&W[x_index], &RR));
1895 mpi_montred(&W[x_index], N, mm, &T);
1896
1897
1898 if (window_bitsize > 1) {
1899 /*
1900 * W[i] = W[1] ^ i
1901 *
1902 * The first bit of the sliding window is always 1 and therefore we
1903 * only need to store the second half of the table.
1904 *
1905 * (There are two special elements in the table: W[0] for the
1906 * accumulator/result and W[1] for A in Montgomery form. Both of these
1907 * are already set at this point.)
1908 */
1909 j = w_table_used_size / 2;
1910
1911 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[j], N->n + 1));
1912 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&W[j], &W[1]));
1913
1914 for (i = 0; i < window_bitsize - 1; i++) {
1915 mpi_montmul(&W[j], &W[j], N, mm, &T);
1916 }
1917
1918 /*
1919 * W[i] = W[i - 1] * W[1]
1920 */
1921 for (i = j + 1; i < w_table_used_size; i++) {
1922 MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&W[i], N->n + 1));
1923 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&W[i], &W[i - 1]));
1924
1925 mpi_montmul(&W[i], &W[1], N, mm, &T);
1926 }
1927 }
1928
1929 nblimbs = E->n;
1930 bufsize = 0;
1931 nbits = 0;
1932 state = 0;
1933
1934 while (1) {
1935 if (bufsize == 0) {
1936 if (nblimbs == 0) {
1937 break;
1938 }
1939
1940 nblimbs--;
1941
1942 bufsize = sizeof(mbedtls_mpi_uint) << 3;
1943 }
1944
1945 bufsize--;
1946
1947 ei = (E->p[nblimbs] >> bufsize) & 1;
1948
1949 /*
1950 * skip leading 0s
1951 */
1952 if (ei == 0 && state == 0) {
1953 continue;
1954 }
1955
1956 if (ei == 0 && state == 1) {
1957 /*
1958 * out of window, square W[x_index]
1959 */
1960 MBEDTLS_MPI_CHK(mpi_select(&WW, W, w_table_used_size, x_index));
1961 mpi_montmul(&W[x_index], &WW, N, mm, &T);
1962 continue;
1963 }
1964
1965 /*
1966 * add ei to current window
1967 */
1968 state = 2;
1969
1970 nbits++;
1971 exponent_bits_in_window |= (ei << (window_bitsize - nbits));
1972
1973 if (nbits == window_bitsize) {
1974 /*
1975 * W[x_index] = W[x_index]^window_bitsize R^-1 mod N
1976 */
1977 for (i = 0; i < window_bitsize; i++) {
1978 MBEDTLS_MPI_CHK(mpi_select(&WW, W, w_table_used_size,
1979 x_index));
1980 mpi_montmul(&W[x_index], &WW, N, mm, &T);
1981 }
1982
1983 /*
1984 * W[x_index] = W[x_index] * W[exponent_bits_in_window] R^-1 mod N
1985 */
1986 MBEDTLS_MPI_CHK(mpi_select(&WW, W, w_table_used_size,
1987 exponent_bits_in_window));
1988 mpi_montmul(&W[x_index], &WW, N, mm, &T);
1989
1990 state--;
1991 nbits = 0;
1992 exponent_bits_in_window = 0;
1993 }
1994 }
1995
1996 /*
1997 * process the remaining bits
1998 */
1999 for (i = 0; i < nbits; i++) {
2000 MBEDTLS_MPI_CHK(mpi_select(&WW, W, w_table_used_size, x_index));
2001 mpi_montmul(&W[x_index], &WW, N, mm, &T);
2002
2003 exponent_bits_in_window <<= 1;
2004
2005 if ((exponent_bits_in_window & ((size_t) 1 << window_bitsize)) != 0) {
2006 MBEDTLS_MPI_CHK(mpi_select(&WW, W, w_table_used_size, 1));
2007 mpi_montmul(&W[x_index], &WW, N, mm, &T);
2008 }
2009 }
2010
2011 /*
2012 * W[x_index] = A^E * R * R^-1 mod N = A^E mod N
2013 */
2014 mpi_montred(&W[x_index], N, mm, &T);
2015
2016 if (neg && E->n != 0 && (E->p[0] & 1) != 0) {
2017 W[x_index].s = -1;
2018 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&W[x_index], N, &W[x_index]));
2019 }
2020
2021 /*
2022 * Load the result in the output variable.
2023 */
2024 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, &W[x_index]));
2025
2026 cleanup:
2027
2028 /* The first bit of the sliding window is always 1 and therefore the first
2029 * half of the table was unused. */
2030 for (i = w_table_used_size/2; i < w_table_used_size; i++) {
2031 mbedtls_mpi_free(&W[i]);
2032 }
2033
2034 mbedtls_mpi_free(&W[x_index]);
2035 mbedtls_mpi_free(&W[1]);
2036 mbedtls_mpi_free(&T);
2037 mbedtls_mpi_free(&Apos);
2038 mbedtls_mpi_free(&WW);
2039
2040 if (prec_RR == NULL || prec_RR->p == NULL) {
2041 mbedtls_mpi_free(&RR);
2042 }
2043
2044 return ret;
2045 }
2046
2047 /*
2048 * Greatest common divisor: G = gcd(A, B) (HAC 14.54)
2049 */
mbedtls_mpi_gcd(mbedtls_mpi * G,const mbedtls_mpi * A,const mbedtls_mpi * B)2050 int mbedtls_mpi_gcd(mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B)
2051 {
2052 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2053 size_t lz, lzt;
2054 mbedtls_mpi TA, TB;
2055
2056 MPI_VALIDATE_RET(G != NULL);
2057 MPI_VALIDATE_RET(A != NULL);
2058 MPI_VALIDATE_RET(B != NULL);
2059
2060 mbedtls_mpi_init(&TA); mbedtls_mpi_init(&TB);
2061
2062 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TA, A));
2063 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TB, B));
2064
2065 lz = mbedtls_mpi_lsb(&TA);
2066 lzt = mbedtls_mpi_lsb(&TB);
2067
2068 /* The loop below gives the correct result when A==0 but not when B==0.
2069 * So have a special case for B==0. Leverage the fact that we just
2070 * calculated the lsb and lsb(B)==0 iff B is odd or 0 to make the test
2071 * slightly more efficient than cmp_int(). */
2072 if (lzt == 0 && mbedtls_mpi_get_bit(&TB, 0) == 0) {
2073 ret = mbedtls_mpi_copy(G, A);
2074 goto cleanup;
2075 }
2076
2077 if (lzt < lz) {
2078 lz = lzt;
2079 }
2080
2081 TA.s = TB.s = 1;
2082
2083 /* We mostly follow the procedure described in HAC 14.54, but with some
2084 * minor differences:
2085 * - Sequences of multiplications or divisions by 2 are grouped into a
2086 * single shift operation.
2087 * - The procedure in HAC assumes that 0 < TB <= TA.
2088 * - The condition TB <= TA is not actually necessary for correctness.
2089 * TA and TB have symmetric roles except for the loop termination
2090 * condition, and the shifts at the beginning of the loop body
2091 * remove any significance from the ordering of TA vs TB before
2092 * the shifts.
2093 * - If TA = 0, the loop goes through 0 iterations and the result is
2094 * correctly TB.
2095 * - The case TB = 0 was short-circuited above.
2096 *
2097 * For the correctness proof below, decompose the original values of
2098 * A and B as
2099 * A = sa * 2^a * A' with A'=0 or A' odd, and sa = +-1
2100 * B = sb * 2^b * B' with B'=0 or B' odd, and sb = +-1
2101 * Then gcd(A, B) = 2^{min(a,b)} * gcd(A',B'),
2102 * and gcd(A',B') is odd or 0.
2103 *
2104 * At the beginning, we have TA = |A| and TB = |B| so gcd(A,B) = gcd(TA,TB).
2105 * The code maintains the following invariant:
2106 * gcd(A,B) = 2^k * gcd(TA,TB) for some k (I)
2107 */
2108
2109 /* Proof that the loop terminates:
2110 * At each iteration, either the right-shift by 1 is made on a nonzero
2111 * value and the nonnegative integer bitlen(TA) + bitlen(TB) decreases
2112 * by at least 1, or the right-shift by 1 is made on zero and then
2113 * TA becomes 0 which ends the loop (TB cannot be 0 if it is right-shifted
2114 * since in that case TB is calculated from TB-TA with the condition TB>TA).
2115 */
2116 while (mbedtls_mpi_cmp_int(&TA, 0) != 0) {
2117 /* Divisions by 2 preserve the invariant (I). */
2118 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TA, mbedtls_mpi_lsb(&TA)));
2119 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TB, mbedtls_mpi_lsb(&TB)));
2120
2121 /* Set either TA or TB to |TA-TB|/2. Since TA and TB are both odd,
2122 * TA-TB is even so the division by 2 has an integer result.
2123 * Invariant (I) is preserved since any odd divisor of both TA and TB
2124 * also divides |TA-TB|/2, and any odd divisor of both TA and |TA-TB|/2
2125 * also divides TB, and any odd divisor of both TB and |TA-TB|/2 also
2126 * divides TA.
2127 */
2128 if (mbedtls_mpi_cmp_mpi(&TA, &TB) >= 0) {
2129 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(&TA, &TA, &TB));
2130 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TA, 1));
2131 } else {
2132 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(&TB, &TB, &TA));
2133 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TB, 1));
2134 }
2135 /* Note that one of TA or TB is still odd. */
2136 }
2137
2138 /* By invariant (I), gcd(A,B) = 2^k * gcd(TA,TB) for some k.
2139 * At the loop exit, TA = 0, so gcd(TA,TB) = TB.
2140 * - If there was at least one loop iteration, then one of TA or TB is odd,
2141 * and TA = 0, so TB is odd and gcd(TA,TB) = gcd(A',B'). In this case,
2142 * lz = min(a,b) so gcd(A,B) = 2^lz * TB.
2143 * - If there was no loop iteration, then A was 0, and gcd(A,B) = B.
2144 * In this case, lz = 0 and B = TB so gcd(A,B) = B = 2^lz * TB as well.
2145 */
2146
2147 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&TB, lz));
2148 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(G, &TB));
2149
2150 cleanup:
2151
2152 mbedtls_mpi_free(&TA); mbedtls_mpi_free(&TB);
2153
2154 return ret;
2155 }
2156
2157 /*
2158 * Fill X with size bytes of random.
2159 * The bytes returned from the RNG are used in a specific order which
2160 * is suitable for deterministic ECDSA (see the specification of
2161 * mbedtls_mpi_random() and the implementation in mbedtls_mpi_fill_random()).
2162 */
mbedtls_mpi_fill_random(mbedtls_mpi * X,size_t size,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2163 int mbedtls_mpi_fill_random(mbedtls_mpi *X, size_t size,
2164 int (*f_rng)(void *, unsigned char *, size_t),
2165 void *p_rng)
2166 {
2167 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2168 const size_t limbs = CHARS_TO_LIMBS(size);
2169
2170 MPI_VALIDATE_RET(X != NULL);
2171 MPI_VALIDATE_RET(f_rng != NULL);
2172
2173 /* Ensure that target MPI has exactly the necessary number of limbs */
2174 MBEDTLS_MPI_CHK(mbedtls_mpi_resize_clear(X, limbs));
2175 if (size == 0) {
2176 return 0;
2177 }
2178
2179 ret = mbedtls_mpi_core_fill_random(X->p, X->n, size, f_rng, p_rng);
2180
2181 cleanup:
2182 return ret;
2183 }
2184
mbedtls_mpi_random(mbedtls_mpi * X,mbedtls_mpi_sint min,const mbedtls_mpi * N,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2185 int mbedtls_mpi_random(mbedtls_mpi *X,
2186 mbedtls_mpi_sint min,
2187 const mbedtls_mpi *N,
2188 int (*f_rng)(void *, unsigned char *, size_t),
2189 void *p_rng)
2190 {
2191 if (min < 0) {
2192 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
2193 }
2194 if (mbedtls_mpi_cmp_int(N, min) <= 0) {
2195 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
2196 }
2197
2198 /* Ensure that target MPI has exactly the same number of limbs
2199 * as the upper bound, even if the upper bound has leading zeros.
2200 * This is necessary for mbedtls_mpi_core_random. */
2201 int ret = mbedtls_mpi_resize_clear(X, N->n);
2202 if (ret != 0) {
2203 return ret;
2204 }
2205
2206 return mbedtls_mpi_core_random(X->p, min, N->p, X->n, f_rng, p_rng);
2207 }
2208
2209 /*
2210 * Modular inverse: X = A^-1 mod N (HAC 14.61 / 14.64)
2211 */
mbedtls_mpi_inv_mod(mbedtls_mpi * X,const mbedtls_mpi * A,const mbedtls_mpi * N)2212 int mbedtls_mpi_inv_mod(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N)
2213 {
2214 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2215 mbedtls_mpi G, TA, TU, U1, U2, TB, TV, V1, V2;
2216 MPI_VALIDATE_RET(X != NULL);
2217 MPI_VALIDATE_RET(A != NULL);
2218 MPI_VALIDATE_RET(N != NULL);
2219
2220 if (mbedtls_mpi_cmp_int(N, 1) <= 0) {
2221 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
2222 }
2223
2224 mbedtls_mpi_init(&TA); mbedtls_mpi_init(&TU); mbedtls_mpi_init(&U1); mbedtls_mpi_init(&U2);
2225 mbedtls_mpi_init(&G); mbedtls_mpi_init(&TB); mbedtls_mpi_init(&TV);
2226 mbedtls_mpi_init(&V1); mbedtls_mpi_init(&V2);
2227
2228 MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, A, N));
2229
2230 if (mbedtls_mpi_cmp_int(&G, 1) != 0) {
2231 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2232 goto cleanup;
2233 }
2234
2235 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&TA, A, N));
2236 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TU, &TA));
2237 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TB, N));
2238 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TV, N));
2239
2240 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&U1, 1));
2241 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&U2, 0));
2242 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&V1, 0));
2243 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&V2, 1));
2244
2245 do {
2246 while ((TU.p[0] & 1) == 0) {
2247 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TU, 1));
2248
2249 if ((U1.p[0] & 1) != 0 || (U2.p[0] & 1) != 0) {
2250 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&U1, &U1, &TB));
2251 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&U2, &U2, &TA));
2252 }
2253
2254 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&U1, 1));
2255 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&U2, 1));
2256 }
2257
2258 while ((TV.p[0] & 1) == 0) {
2259 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TV, 1));
2260
2261 if ((V1.p[0] & 1) != 0 || (V2.p[0] & 1) != 0) {
2262 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&V1, &V1, &TB));
2263 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V2, &V2, &TA));
2264 }
2265
2266 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&V1, 1));
2267 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&V2, 1));
2268 }
2269
2270 if (mbedtls_mpi_cmp_mpi(&TU, &TV) >= 0) {
2271 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&TU, &TU, &TV));
2272 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&U1, &U1, &V1));
2273 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&U2, &U2, &V2));
2274 } else {
2275 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&TV, &TV, &TU));
2276 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V1, &V1, &U1));
2277 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V2, &V2, &U2));
2278 }
2279 } while (mbedtls_mpi_cmp_int(&TU, 0) != 0);
2280
2281 while (mbedtls_mpi_cmp_int(&V1, 0) < 0) {
2282 MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&V1, &V1, N));
2283 }
2284
2285 while (mbedtls_mpi_cmp_mpi(&V1, N) >= 0) {
2286 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V1, &V1, N));
2287 }
2288
2289 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, &V1));
2290
2291 cleanup:
2292
2293 mbedtls_mpi_free(&TA); mbedtls_mpi_free(&TU); mbedtls_mpi_free(&U1); mbedtls_mpi_free(&U2);
2294 mbedtls_mpi_free(&G); mbedtls_mpi_free(&TB); mbedtls_mpi_free(&TV);
2295 mbedtls_mpi_free(&V1); mbedtls_mpi_free(&V2);
2296
2297 return ret;
2298 }
2299
2300 #if defined(MBEDTLS_GENPRIME)
2301
2302 /* Gaps between primes, starting at 3. https://oeis.org/A001223 */
2303 static const unsigned char small_prime_gaps[] = {
2304 2, 2, 4, 2, 4, 2, 4, 6,
2305 2, 6, 4, 2, 4, 6, 6, 2,
2306 6, 4, 2, 6, 4, 6, 8, 4,
2307 2, 4, 2, 4, 14, 4, 6, 2,
2308 10, 2, 6, 6, 4, 6, 6, 2,
2309 10, 2, 4, 2, 12, 12, 4, 2,
2310 4, 6, 2, 10, 6, 6, 6, 2,
2311 6, 4, 2, 10, 14, 4, 2, 4,
2312 14, 6, 10, 2, 4, 6, 8, 6,
2313 6, 4, 6, 8, 4, 8, 10, 2,
2314 10, 2, 6, 4, 6, 8, 4, 2,
2315 4, 12, 8, 4, 8, 4, 6, 12,
2316 2, 18, 6, 10, 6, 6, 2, 6,
2317 10, 6, 6, 2, 6, 6, 4, 2,
2318 12, 10, 2, 4, 6, 6, 2, 12,
2319 4, 6, 8, 10, 8, 10, 8, 6,
2320 6, 4, 8, 6, 4, 8, 4, 14,
2321 10, 12, 2, 10, 2, 4, 2, 10,
2322 14, 4, 2, 4, 14, 4, 2, 4,
2323 20, 4, 8, 10, 8, 4, 6, 6,
2324 14, 4, 6, 6, 8, 6, /*reaches 997*/
2325 0 /* the last entry is effectively unused */
2326 };
2327
2328 /*
2329 * Small divisors test (X must be positive)
2330 *
2331 * Return values:
2332 * 0: no small factor (possible prime, more tests needed)
2333 * 1: certain prime
2334 * MBEDTLS_ERR_MPI_NOT_ACCEPTABLE: certain non-prime
2335 * other negative: error
2336 */
mpi_check_small_factors(const mbedtls_mpi * X)2337 static int mpi_check_small_factors(const mbedtls_mpi *X)
2338 {
2339 int ret = 0;
2340 size_t i;
2341 mbedtls_mpi_uint r;
2342 unsigned p = 3; /* The first odd prime */
2343
2344 if ((X->p[0] & 1) == 0) {
2345 return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2346 }
2347
2348 for (i = 0; i < sizeof(small_prime_gaps); p += small_prime_gaps[i], i++) {
2349 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_int(&r, X, p));
2350 if (r == 0) {
2351 if (mbedtls_mpi_cmp_int(X, p) == 0) {
2352 return 1;
2353 } else {
2354 return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2355 }
2356 }
2357 }
2358
2359 cleanup:
2360 return ret;
2361 }
2362
2363 /*
2364 * Miller-Rabin pseudo-primality test (HAC 4.24)
2365 */
mpi_miller_rabin(const mbedtls_mpi * X,size_t rounds,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2366 static int mpi_miller_rabin(const mbedtls_mpi *X, size_t rounds,
2367 int (*f_rng)(void *, unsigned char *, size_t),
2368 void *p_rng)
2369 {
2370 int ret, count;
2371 size_t i, j, k, s;
2372 mbedtls_mpi W, R, T, A, RR;
2373
2374 MPI_VALIDATE_RET(X != NULL);
2375 MPI_VALIDATE_RET(f_rng != NULL);
2376
2377 mbedtls_mpi_init(&W); mbedtls_mpi_init(&R);
2378 mbedtls_mpi_init(&T); mbedtls_mpi_init(&A);
2379 mbedtls_mpi_init(&RR);
2380
2381 /*
2382 * W = |X| - 1
2383 * R = W >> lsb( W )
2384 */
2385 MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&W, X, 1));
2386 s = mbedtls_mpi_lsb(&W);
2387 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&R, &W));
2388 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&R, s));
2389
2390 for (i = 0; i < rounds; i++) {
2391 /*
2392 * pick a random A, 1 < A < |X| - 1
2393 */
2394 count = 0;
2395 do {
2396 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&A, X->n * ciL, f_rng, p_rng));
2397
2398 j = mbedtls_mpi_bitlen(&A);
2399 k = mbedtls_mpi_bitlen(&W);
2400 if (j > k) {
2401 A.p[A.n - 1] &= ((mbedtls_mpi_uint) 1 << (k - (A.n - 1) * biL - 1)) - 1;
2402 }
2403
2404 if (count++ > 30) {
2405 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2406 goto cleanup;
2407 }
2408
2409 } while (mbedtls_mpi_cmp_mpi(&A, &W) >= 0 ||
2410 mbedtls_mpi_cmp_int(&A, 1) <= 0);
2411
2412 /*
2413 * A = A^R mod |X|
2414 */
2415 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&A, &A, &R, X, &RR));
2416
2417 if (mbedtls_mpi_cmp_mpi(&A, &W) == 0 ||
2418 mbedtls_mpi_cmp_int(&A, 1) == 0) {
2419 continue;
2420 }
2421
2422 j = 1;
2423 while (j < s && mbedtls_mpi_cmp_mpi(&A, &W) != 0) {
2424 /*
2425 * A = A * A mod |X|
2426 */
2427 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &A, &A));
2428 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&A, &T, X));
2429
2430 if (mbedtls_mpi_cmp_int(&A, 1) == 0) {
2431 break;
2432 }
2433
2434 j++;
2435 }
2436
2437 /*
2438 * not prime if A != |X| - 1 or A == 1
2439 */
2440 if (mbedtls_mpi_cmp_mpi(&A, &W) != 0 ||
2441 mbedtls_mpi_cmp_int(&A, 1) == 0) {
2442 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2443 break;
2444 }
2445 }
2446
2447 cleanup:
2448 mbedtls_mpi_free(&W); mbedtls_mpi_free(&R);
2449 mbedtls_mpi_free(&T); mbedtls_mpi_free(&A);
2450 mbedtls_mpi_free(&RR);
2451
2452 return ret;
2453 }
2454
2455 /*
2456 * Pseudo-primality test: small factors, then Miller-Rabin
2457 */
mbedtls_mpi_is_prime_ext(const mbedtls_mpi * X,int rounds,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2458 int mbedtls_mpi_is_prime_ext(const mbedtls_mpi *X, int rounds,
2459 int (*f_rng)(void *, unsigned char *, size_t),
2460 void *p_rng)
2461 {
2462 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2463 mbedtls_mpi XX;
2464 MPI_VALIDATE_RET(X != NULL);
2465 MPI_VALIDATE_RET(f_rng != NULL);
2466
2467 XX.s = 1;
2468 XX.n = X->n;
2469 XX.p = X->p;
2470
2471 if (mbedtls_mpi_cmp_int(&XX, 0) == 0 ||
2472 mbedtls_mpi_cmp_int(&XX, 1) == 0) {
2473 return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2474 }
2475
2476 if (mbedtls_mpi_cmp_int(&XX, 2) == 0) {
2477 return 0;
2478 }
2479
2480 if ((ret = mpi_check_small_factors(&XX)) != 0) {
2481 if (ret == 1) {
2482 return 0;
2483 }
2484
2485 return ret;
2486 }
2487
2488 return mpi_miller_rabin(&XX, rounds, f_rng, p_rng);
2489 }
2490
2491 /*
2492 * Prime number generation
2493 *
2494 * To generate an RSA key in a way recommended by FIPS 186-4, both primes must
2495 * be either 1024 bits or 1536 bits long, and flags must contain
2496 * MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR.
2497 */
mbedtls_mpi_gen_prime(mbedtls_mpi * X,size_t nbits,int flags,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)2498 int mbedtls_mpi_gen_prime(mbedtls_mpi *X, size_t nbits, int flags,
2499 int (*f_rng)(void *, unsigned char *, size_t),
2500 void *p_rng)
2501 {
2502 #ifdef MBEDTLS_HAVE_INT64
2503 // ceil(2^63.5)
2504 #define CEIL_MAXUINT_DIV_SQRT2 0xb504f333f9de6485ULL
2505 #else
2506 // ceil(2^31.5)
2507 #define CEIL_MAXUINT_DIV_SQRT2 0xb504f334U
2508 #endif
2509 int ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2510 size_t k, n;
2511 int rounds;
2512 mbedtls_mpi_uint r;
2513 mbedtls_mpi Y;
2514
2515 MPI_VALIDATE_RET(X != NULL);
2516 MPI_VALIDATE_RET(f_rng != NULL);
2517
2518 if (nbits < 3 || nbits > MBEDTLS_MPI_MAX_BITS) {
2519 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
2520 }
2521
2522 mbedtls_mpi_init(&Y);
2523
2524 n = BITS_TO_LIMBS(nbits);
2525
2526 if ((flags & MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR) == 0) {
2527 /*
2528 * 2^-80 error probability, number of rounds chosen per HAC, table 4.4
2529 */
2530 rounds = ((nbits >= 1300) ? 2 : (nbits >= 850) ? 3 :
2531 (nbits >= 650) ? 4 : (nbits >= 350) ? 8 :
2532 (nbits >= 250) ? 12 : (nbits >= 150) ? 18 : 27);
2533 } else {
2534 /*
2535 * 2^-100 error probability, number of rounds computed based on HAC,
2536 * fact 4.48
2537 */
2538 rounds = ((nbits >= 1450) ? 4 : (nbits >= 1150) ? 5 :
2539 (nbits >= 1000) ? 6 : (nbits >= 850) ? 7 :
2540 (nbits >= 750) ? 8 : (nbits >= 500) ? 13 :
2541 (nbits >= 250) ? 28 : (nbits >= 150) ? 40 : 51);
2542 }
2543
2544 while (1) {
2545 MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(X, n * ciL, f_rng, p_rng));
2546 /* make sure generated number is at least (nbits-1)+0.5 bits (FIPS 186-4 §B.3.3 steps 4.4, 5.5) */
2547 if (X->p[n-1] < CEIL_MAXUINT_DIV_SQRT2) {
2548 continue;
2549 }
2550
2551 k = n * biL;
2552 if (k > nbits) {
2553 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(X, k - nbits));
2554 }
2555 X->p[0] |= 1;
2556
2557 if ((flags & MBEDTLS_MPI_GEN_PRIME_FLAG_DH) == 0) {
2558 ret = mbedtls_mpi_is_prime_ext(X, rounds, f_rng, p_rng);
2559
2560 if (ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
2561 goto cleanup;
2562 }
2563 } else {
2564 /*
2565 * A necessary condition for Y and X = 2Y + 1 to be prime
2566 * is X = 2 mod 3 (which is equivalent to Y = 2 mod 3).
2567 * Make sure it is satisfied, while keeping X = 3 mod 4
2568 */
2569
2570 X->p[0] |= 2;
2571
2572 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_int(&r, X, 3));
2573 if (r == 0) {
2574 MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(X, X, 8));
2575 } else if (r == 1) {
2576 MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(X, X, 4));
2577 }
2578
2579 /* Set Y = (X-1) / 2, which is X / 2 because X is odd */
2580 MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&Y, X));
2581 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&Y, 1));
2582
2583 while (1) {
2584 /*
2585 * First, check small factors for X and Y
2586 * before doing Miller-Rabin on any of them
2587 */
2588 if ((ret = mpi_check_small_factors(X)) == 0 &&
2589 (ret = mpi_check_small_factors(&Y)) == 0 &&
2590 (ret = mpi_miller_rabin(X, rounds, f_rng, p_rng))
2591 == 0 &&
2592 (ret = mpi_miller_rabin(&Y, rounds, f_rng, p_rng))
2593 == 0) {
2594 goto cleanup;
2595 }
2596
2597 if (ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
2598 goto cleanup;
2599 }
2600
2601 /*
2602 * Next candidates. We want to preserve Y = (X-1) / 2 and
2603 * Y = 1 mod 2 and Y = 2 mod 3 (eq X = 3 mod 4 and X = 2 mod 3)
2604 * so up Y by 6 and X by 12.
2605 */
2606 MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(X, X, 12));
2607 MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&Y, &Y, 6));
2608 }
2609 }
2610 }
2611
2612 cleanup:
2613
2614 mbedtls_mpi_free(&Y);
2615
2616 return ret;
2617 }
2618
2619 #endif /* MBEDTLS_GENPRIME */
2620
2621 #if defined(MBEDTLS_SELF_TEST)
2622
2623 #define GCD_PAIR_COUNT 3
2624
2625 static const int gcd_pairs[GCD_PAIR_COUNT][3] =
2626 {
2627 { 693, 609, 21 },
2628 { 1764, 868, 28 },
2629 { 768454923, 542167814, 1 }
2630 };
2631
2632 /*
2633 * Checkup routine
2634 */
mbedtls_mpi_self_test(int verbose)2635 int mbedtls_mpi_self_test(int verbose)
2636 {
2637 int ret, i;
2638 mbedtls_mpi A, E, N, X, Y, U, V;
2639
2640 mbedtls_mpi_init(&A); mbedtls_mpi_init(&E); mbedtls_mpi_init(&N); mbedtls_mpi_init(&X);
2641 mbedtls_mpi_init(&Y); mbedtls_mpi_init(&U); mbedtls_mpi_init(&V);
2642
2643 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&A, 16,
2644 "EFE021C2645FD1DC586E69184AF4A31E" \
2645 "D5F53E93B5F123FA41680867BA110131" \
2646 "944FE7952E2517337780CB0DB80E61AA" \
2647 "E7C8DDC6C5C6AADEB34EB38A2F40D5E6"));
2648
2649 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&E, 16,
2650 "B2E7EFD37075B9F03FF989C7C5051C20" \
2651 "34D2A323810251127E7BF8625A4F49A5" \
2652 "F3E27F4DA8BD59C47D6DAABA4C8127BD" \
2653 "5B5C25763222FEFCCFC38B832366C29E"));
2654
2655 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&N, 16,
2656 "0066A198186C18C10B2F5ED9B522752A" \
2657 "9830B69916E535C8F047518A889A43A5" \
2658 "94B6BED27A168D31D4A52F88925AA8F5"));
2659
2660 MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&X, &A, &N));
2661
2662 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&U, 16,
2663 "602AB7ECA597A3D6B56FF9829A5E8B85" \
2664 "9E857EA95A03512E2BAE7391688D264A" \
2665 "A5663B0341DB9CCFD2C4C5F421FEC814" \
2666 "8001B72E848A38CAE1C65F78E56ABDEF" \
2667 "E12D3C039B8A02D6BE593F0BBBDA56F1" \
2668 "ECF677152EF804370C1A305CAF3B5BF1" \
2669 "30879B56C61DE584A0F53A2447A51E"));
2670
2671 if (verbose != 0) {
2672 mbedtls_printf(" MPI test #1 (mul_mpi): ");
2673 }
2674
2675 if (mbedtls_mpi_cmp_mpi(&X, &U) != 0) {
2676 if (verbose != 0) {
2677 mbedtls_printf("failed\n");
2678 }
2679
2680 ret = 1;
2681 goto cleanup;
2682 }
2683
2684 if (verbose != 0) {
2685 mbedtls_printf("passed\n");
2686 }
2687
2688 MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&X, &Y, &A, &N));
2689
2690 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&U, 16,
2691 "256567336059E52CAE22925474705F39A94"));
2692
2693 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&V, 16,
2694 "6613F26162223DF488E9CD48CC132C7A" \
2695 "0AC93C701B001B092E4E5B9F73BCD27B" \
2696 "9EE50D0657C77F374E903CDFA4C642"));
2697
2698 if (verbose != 0) {
2699 mbedtls_printf(" MPI test #2 (div_mpi): ");
2700 }
2701
2702 if (mbedtls_mpi_cmp_mpi(&X, &U) != 0 ||
2703 mbedtls_mpi_cmp_mpi(&Y, &V) != 0) {
2704 if (verbose != 0) {
2705 mbedtls_printf("failed\n");
2706 }
2707
2708 ret = 1;
2709 goto cleanup;
2710 }
2711
2712 if (verbose != 0) {
2713 mbedtls_printf("passed\n");
2714 }
2715
2716 MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&X, &A, &E, &N, NULL));
2717
2718 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&U, 16,
2719 "36E139AEA55215609D2816998ED020BB" \
2720 "BD96C37890F65171D948E9BC7CBAA4D9" \
2721 "325D24D6A3C12710F10A09FA08AB87"));
2722
2723 if (verbose != 0) {
2724 mbedtls_printf(" MPI test #3 (exp_mod): ");
2725 }
2726
2727 if (mbedtls_mpi_cmp_mpi(&X, &U) != 0) {
2728 if (verbose != 0) {
2729 mbedtls_printf("failed\n");
2730 }
2731
2732 ret = 1;
2733 goto cleanup;
2734 }
2735
2736 if (verbose != 0) {
2737 mbedtls_printf("passed\n");
2738 }
2739
2740 MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&X, &A, &N));
2741
2742 MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&U, 16,
2743 "003A0AAEDD7E784FC07D8F9EC6E3BFD5" \
2744 "C3DBA76456363A10869622EAC2DD84EC" \
2745 "C5B8A74DAC4D09E03B5E0BE779F2DF61"));
2746
2747 if (verbose != 0) {
2748 mbedtls_printf(" MPI test #4 (inv_mod): ");
2749 }
2750
2751 if (mbedtls_mpi_cmp_mpi(&X, &U) != 0) {
2752 if (verbose != 0) {
2753 mbedtls_printf("failed\n");
2754 }
2755
2756 ret = 1;
2757 goto cleanup;
2758 }
2759
2760 if (verbose != 0) {
2761 mbedtls_printf("passed\n");
2762 }
2763
2764 if (verbose != 0) {
2765 mbedtls_printf(" MPI test #5 (simple gcd): ");
2766 }
2767
2768 for (i = 0; i < GCD_PAIR_COUNT; i++) {
2769 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&X, gcd_pairs[i][0]));
2770 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&Y, gcd_pairs[i][1]));
2771
2772 MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&A, &X, &Y));
2773
2774 if (mbedtls_mpi_cmp_int(&A, gcd_pairs[i][2]) != 0) {
2775 if (verbose != 0) {
2776 mbedtls_printf("failed at %d\n", i);
2777 }
2778
2779 ret = 1;
2780 goto cleanup;
2781 }
2782 }
2783
2784 if (verbose != 0) {
2785 mbedtls_printf("passed\n");
2786 }
2787
2788 cleanup:
2789
2790 if (ret != 0 && verbose != 0) {
2791 mbedtls_printf("Unexpected error, return code = %08X\n", (unsigned int) ret);
2792 }
2793
2794 mbedtls_mpi_free(&A); mbedtls_mpi_free(&E); mbedtls_mpi_free(&N); mbedtls_mpi_free(&X);
2795 mbedtls_mpi_free(&Y); mbedtls_mpi_free(&U); mbedtls_mpi_free(&V);
2796
2797 if (verbose != 0) {
2798 mbedtls_printf("\n");
2799 }
2800
2801 return ret;
2802 }
2803
2804 #endif /* MBEDTLS_SELF_TEST */
2805
2806 #endif /* MBEDTLS_BIGNUM_C */
2807