diff --git a/library/bignum_core.c b/library/bignum_core.c index 1a3e0b9b6..ee3d704a1 100644 --- a/library/bignum_core.c +++ b/library/bignum_core.c @@ -449,9 +449,10 @@ mbedtls_mpi_uint mbedtls_mpi_core_sub(mbedtls_mpi_uint *X, mbedtls_mpi_uint c = 0; for (size_t i = 0; i < limbs; i++) { - mbedtls_mpi_uint z = (A[i] < c); + mbedtls_mpi_uint z = mbedtls_ct_mpi_uint_if(mbedtls_ct_uint_lt(A[i], c), + 1, 0); mbedtls_mpi_uint t = A[i] - c; - c = (t < B[i]) + z; + c = mbedtls_ct_mpi_uint_if(mbedtls_ct_uint_lt(t, B[i]), 1, 0) + z; X[i] = t - B[i]; } diff --git a/library/bignum_core.h b/library/bignum_core.h index 92c8d47db..b32d60736 100644 --- a/library/bignum_core.h +++ b/library/bignum_core.h @@ -376,6 +376,9 @@ mbedtls_mpi_uint mbedtls_mpi_core_add_if(mbedtls_mpi_uint *X, * \p X may be aliased to \p A or \p B, or even both, but may not overlap * either otherwise. * + * This function operates in constant time with respect to the values + * of \p A and \p B. + * * \param[out] X The result of the subtraction. * \param[in] A Little-endian presentation of left operand. * \param[in] B Little-endian presentation of right operand. diff --git a/tests/suites/test_suite_bignum_core.function b/tests/suites/test_suite_bignum_core.function index db84d6238..bd1dfa687 100644 --- a/tests/suites/test_suite_bignum_core.function +++ b/tests/suites/test_suite_bignum_core.function @@ -660,31 +660,48 @@ void mpi_core_sub(char *input_A, char *input_B, memcpy(b, B.p, B.n * sizeof(mbedtls_mpi_uint)); memcpy(x, X.p, X.n * sizeof(mbedtls_mpi_uint)); + TEST_CF_SECRET(a, bytes); + TEST_CF_SECRET(b, bytes); + /* 1a) r = a - b => we should get the correct carry */ TEST_EQUAL(carry, mbedtls_mpi_core_sub(r, a, b, limbs)); + TEST_CF_PUBLIC(r, bytes); + /* 1b) r = a - b => we should get the correct result */ TEST_MEMORY_COMPARE(r, bytes, x, bytes); /* 2 and 3 test "r may be aliased to a or b" */ /* 2a) r = a; r -= b => we should get the correct carry (use r to avoid clobbering a) */ memcpy(r, a, bytes); + + TEST_CF_SECRET(r, bytes); + TEST_EQUAL(carry, mbedtls_mpi_core_sub(r, r, b, limbs)); + TEST_CF_PUBLIC(r, bytes); + /* 2b) r -= b => we should get the correct result */ TEST_MEMORY_COMPARE(r, bytes, x, bytes); /* 3a) r = b; r = a - r => we should get the correct carry (use r to avoid clobbering b) */ memcpy(r, b, bytes); + + TEST_CF_SECRET(r, bytes); + TEST_EQUAL(carry, mbedtls_mpi_core_sub(r, a, r, limbs)); + TEST_CF_PUBLIC(r, bytes); + /* 3b) r = a - b => we should get the correct result */ TEST_MEMORY_COMPARE(r, bytes, x, bytes); /* 4 tests "r may be aliased to [...] both" */ if (A.n == B.n && memcmp(A.p, B.p, bytes) == 0) { memcpy(r, b, bytes); + TEST_CF_SECRET(r, bytes); TEST_EQUAL(carry, mbedtls_mpi_core_sub(r, r, r, limbs)); + TEST_CF_PUBLIC(r, bytes); TEST_MEMORY_COMPARE(r, bytes, x, bytes); }