1
0
mirror of https://github.com/Mbed-TLS/mbedtls.git synced 2025-10-23 01:52:40 +03:00

Merge remote-tracking branch 'restricted/mbedtls-3.6-restricted' into mbedtls-3.6.5rc0-pr

Signed-off-by: Minos Galanakis <minos.galanakis@arm.com>
This commit is contained in:
Minos Galanakis
2025-10-02 15:37:04 +01:00
34 changed files with 2900 additions and 413 deletions

View File

@@ -430,13 +430,6 @@ cleanup:
return ret;
}
/*
* Return the number of less significant zero-bits
*/
size_t mbedtls_mpi_lsb(const mbedtls_mpi *X)
{
size_t i;
#if defined(__has_builtin)
#if (MBEDTLS_MPI_UINT_MAX == UINT_MAX) && __has_builtin(__builtin_ctz)
#define mbedtls_mpi_uint_ctz __builtin_ctz
@@ -447,22 +440,34 @@ size_t mbedtls_mpi_lsb(const mbedtls_mpi *X)
#endif
#endif
#if defined(mbedtls_mpi_uint_ctz)
#if !defined(mbedtls_mpi_uint_ctz)
static size_t mbedtls_mpi_uint_ctz(mbedtls_mpi_uint x)
{
size_t count = 0;
mbedtls_ct_condition_t done = MBEDTLS_CT_FALSE;
for (size_t i = 0; i < biL; i++) {
mbedtls_ct_condition_t non_zero = mbedtls_ct_bool((x >> i) & 1);
done = mbedtls_ct_bool_or(done, non_zero);
count = mbedtls_ct_size_if(done, count, i + 1);
}
return count;
}
#endif
/*
* Return the number of less significant zero-bits
*/
size_t mbedtls_mpi_lsb(const mbedtls_mpi *X)
{
size_t i;
for (i = 0; i < X->n; i++) {
if (X->p[i] != 0) {
return i * biL + mbedtls_mpi_uint_ctz(X->p[i]);
}
}
#else
size_t count = 0;
for (i = 0; i < X->n; i++) {
for (size_t j = 0; j < biL; j++, count++) {
if (((X->p[i] >> j) & 1) != 0) {
return count;
}
}
}
#endif
return 0;
}
@@ -1743,104 +1748,122 @@ int mbedtls_mpi_exp_mod_unsafe(mbedtls_mpi *X, const mbedtls_mpi *A,
return mbedtls_mpi_exp_mod_optionally_safe(X, A, E, MBEDTLS_MPI_IS_PUBLIC, N, prec_RR);
}
/* Constant-time GCD and/or modinv with odd modulus and A <= N */
int mbedtls_mpi_gcd_modinv_odd(mbedtls_mpi *G,
mbedtls_mpi *I,
const mbedtls_mpi *A,
const mbedtls_mpi *N)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi local_g;
mbedtls_mpi_uint *T = NULL;
const size_t T_factor = I != NULL ? 5 : 4;
const mbedtls_mpi_uint zero = 0;
/* Check requirements on A and N */
if (mbedtls_mpi_cmp_int(A, 0) < 0 ||
mbedtls_mpi_cmp_mpi(A, N) > 0 ||
mbedtls_mpi_get_bit(N, 0) != 1 ||
(I != NULL && mbedtls_mpi_cmp_int(N, 1) == 0)) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
/* Check aliasing requirements */
if (A == N || (I != NULL && (I == N || G == N))) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
mbedtls_mpi_init(&local_g);
if (G == NULL) {
G = &local_g;
}
/* We can't modify the values of G or I before use in the main function,
* as they could be aliased to A or N. */
MBEDTLS_MPI_CHK(mbedtls_mpi_grow(G, N->n));
if (I != NULL) {
MBEDTLS_MPI_CHK(mbedtls_mpi_grow(I, N->n));
}
T = mbedtls_calloc(sizeof(mbedtls_mpi_uint) * N->n, T_factor);
if (T == NULL) {
ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
goto cleanup;
}
mbedtls_mpi_uint *Ip = I != NULL ? I->p : NULL;
/* If A is 0 (null), then A->p would be null, and A->n would be 0,
* which would be an issue if A->p and A->n were passed to
* mbedtls_mpi_core_gcd_modinv_odd below. */
const mbedtls_mpi_uint *Ap = A->p != NULL ? A->p : &zero;
size_t An = A->n >= N->n ? N->n : A->p != NULL ? A->n : 1;
mbedtls_mpi_core_gcd_modinv_odd(G->p, Ip, Ap, An, N->p, N->n, T);
G->s = 1;
if (I != NULL) {
I->s = 1;
}
if (G->n > N->n) {
memset(G->p + N->n, 0, ciL * (G->n - N->n));
}
if (I != NULL && I->n > N->n) {
memset(I->p + N->n, 0, ciL * (I->n - N->n));
}
cleanup:
mbedtls_mpi_free(&local_g);
mbedtls_free(T);
return ret;
}
/*
* Greatest common divisor: G = gcd(A, B) (HAC 14.54)
* Greatest common divisor: G = gcd(A, B)
* Wrapper around mbedtls_mpi_gcd_modinv() that removes its restrictions.
*/
int mbedtls_mpi_gcd(mbedtls_mpi *G, const mbedtls_mpi *A, const mbedtls_mpi *B)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t lz, lzt;
mbedtls_mpi TA, TB;
mbedtls_mpi_init(&TA); mbedtls_mpi_init(&TB);
/* Make copies and take absolute values */
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TA, A));
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TB, B));
TA.s = TB.s = 1;
lz = mbedtls_mpi_lsb(&TA);
lzt = mbedtls_mpi_lsb(&TB);
/* Make the two values the same (non-zero) number of limbs.
* This is needed to use mbedtls_mpi_core functions below. */
MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&TA, TB.n != 0 ? TB.n : 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&TB, TA.n)); // non-zero from above
/* The loop below gives the correct result when A==0 but not when B==0.
* So have a special case for B==0. Leverage the fact that we just
* calculated the lsb and lsb(B)==0 iff B is odd or 0 to make the test
* slightly more efficient than cmp_int(). */
if (lzt == 0 && mbedtls_mpi_get_bit(&TB, 0) == 0) {
ret = mbedtls_mpi_copy(G, A);
/* Handle special cases (that don't happen in crypto usage) */
if (mbedtls_mpi_core_check_zero_ct(TA.p, TA.n) == MBEDTLS_CT_FALSE) {
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(G, &TB)); // GCD(0, B) = abs(B)
goto cleanup;
}
if (mbedtls_mpi_core_check_zero_ct(TB.p, TB.n) == MBEDTLS_CT_FALSE) {
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(G, &TA)); // GCD(A, 0) = abs(A)
goto cleanup;
}
if (lzt < lz) {
lz = lzt;
}
/* Make boths inputs odd by putting powers of 2 on the side */
const size_t za = mbedtls_mpi_lsb(&TA);
const size_t zb = mbedtls_mpi_lsb(&TB);
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TA, za));
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TB, zb));
TA.s = TB.s = 1;
/* Ensure A <= B: if B < A, swap them */
mbedtls_ct_condition_t swap = mbedtls_mpi_core_lt_ct(TB.p, TA.p, TA.n);
mbedtls_mpi_core_cond_swap(TA.p, TB.p, TA.n, swap);
/* We mostly follow the procedure described in HAC 14.54, but with some
* minor differences:
* - Sequences of multiplications or divisions by 2 are grouped into a
* single shift operation.
* - The procedure in HAC assumes that 0 < TB <= TA.
* - The condition TB <= TA is not actually necessary for correctness.
* TA and TB have symmetric roles except for the loop termination
* condition, and the shifts at the beginning of the loop body
* remove any significance from the ordering of TA vs TB before
* the shifts.
* - If TA = 0, the loop goes through 0 iterations and the result is
* correctly TB.
* - The case TB = 0 was short-circuited above.
*
* For the correctness proof below, decompose the original values of
* A and B as
* A = sa * 2^a * A' with A'=0 or A' odd, and sa = +-1
* B = sb * 2^b * B' with B'=0 or B' odd, and sb = +-1
* Then gcd(A, B) = 2^{min(a,b)} * gcd(A',B'),
* and gcd(A',B') is odd or 0.
*
* At the beginning, we have TA = |A| and TB = |B| so gcd(A,B) = gcd(TA,TB).
* The code maintains the following invariant:
* gcd(A,B) = 2^k * gcd(TA,TB) for some k (I)
*/
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(G, NULL, &TA, &TB));
/* Proof that the loop terminates:
* At each iteration, either the right-shift by 1 is made on a nonzero
* value and the nonnegative integer bitlen(TA) + bitlen(TB) decreases
* by at least 1, or the right-shift by 1 is made on zero and then
* TA becomes 0 which ends the loop (TB cannot be 0 if it is right-shifted
* since in that case TB is calculated from TB-TA with the condition TB>TA).
*/
while (mbedtls_mpi_cmp_int(&TA, 0) != 0) {
/* Divisions by 2 preserve the invariant (I). */
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TA, mbedtls_mpi_lsb(&TA)));
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TB, mbedtls_mpi_lsb(&TB)));
/* Set either TA or TB to |TA-TB|/2. Since TA and TB are both odd,
* TA-TB is even so the division by 2 has an integer result.
* Invariant (I) is preserved since any odd divisor of both TA and TB
* also divides |TA-TB|/2, and any odd divisor of both TA and |TA-TB|/2
* also divides TB, and any odd divisor of both TB and |TA-TB|/2 also
* divides TA.
*/
if (mbedtls_mpi_cmp_mpi(&TA, &TB) >= 0) {
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(&TA, &TA, &TB));
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TA, 1));
} else {
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(&TB, &TB, &TA));
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TB, 1));
}
/* Note that one of TA or TB is still odd. */
}
/* By invariant (I), gcd(A,B) = 2^k * gcd(TA,TB) for some k.
* At the loop exit, TA = 0, so gcd(TA,TB) = TB.
* - If there was at least one loop iteration, then one of TA or TB is odd,
* and TA = 0, so TB is odd and gcd(TA,TB) = gcd(A',B'). In this case,
* lz = min(a,b) so gcd(A,B) = 2^lz * TB.
* - If there was no loop iteration, then A was 0, and gcd(A,B) = B.
* In this case, lz = 0 and B = TB so gcd(A,B) = B = 2^lz * TB as well.
*/
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(&TB, lz));
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(G, &TB));
/* Re-inject the power of 2 we had previously put aside */
size_t zg = za > zb ? zb : za; // zg = min(za, zb)
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(G, zg));
cleanup:
@@ -1899,93 +1922,141 @@ int mbedtls_mpi_random(mbedtls_mpi *X,
}
/*
* Modular inverse: X = A^-1 mod N (HAC 14.61 / 14.64)
* Modular inverse: X = A^-1 mod N with N odd (and A any range)
*/
int mbedtls_mpi_inv_mod(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N)
int mbedtls_mpi_inv_mod_odd(mbedtls_mpi *X,
const mbedtls_mpi *A,
const mbedtls_mpi *N)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi G, TA, TU, U1, U2, TB, TV, V1, V2;
mbedtls_mpi T, G;
if (mbedtls_mpi_cmp_int(N, 1) <= 0) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
mbedtls_mpi_init(&TA); mbedtls_mpi_init(&TU); mbedtls_mpi_init(&U1); mbedtls_mpi_init(&U2);
mbedtls_mpi_init(&G); mbedtls_mpi_init(&TB); mbedtls_mpi_init(&TV);
mbedtls_mpi_init(&V1); mbedtls_mpi_init(&V2);
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, A, N));
mbedtls_mpi_init(&T);
mbedtls_mpi_init(&G);
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, A, N));
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(&G, &T, &T, N));
if (mbedtls_mpi_cmp_int(&G, 1) != 0) {
ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
goto cleanup;
}
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&TA, A, N));
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TU, &TA));
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TB, N));
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&TV, N));
MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&U1, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&U2, 0));
MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&V1, 0));
MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&V2, 1));
do {
while ((TU.p[0] & 1) == 0) {
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TU, 1));
if ((U1.p[0] & 1) != 0 || (U2.p[0] & 1) != 0) {
MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&U1, &U1, &TB));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&U2, &U2, &TA));
}
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&U1, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&U2, 1));
}
while ((TV.p[0] & 1) == 0) {
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&TV, 1));
if ((V1.p[0] & 1) != 0 || (V2.p[0] & 1) != 0) {
MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&V1, &V1, &TB));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V2, &V2, &TA));
}
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&V1, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_shift_r(&V2, 1));
}
if (mbedtls_mpi_cmp_mpi(&TU, &TV) >= 0) {
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&TU, &TU, &TV));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&U1, &U1, &V1));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&U2, &U2, &V2));
} else {
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&TV, &TV, &TU));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V1, &V1, &U1));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V2, &V2, &U2));
}
} while (mbedtls_mpi_cmp_int(&TU, 0) != 0);
while (mbedtls_mpi_cmp_int(&V1, 0) < 0) {
MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&V1, &V1, N));
}
while (mbedtls_mpi_cmp_mpi(&V1, N) >= 0) {
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&V1, &V1, N));
}
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, &V1));
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, &T));
cleanup:
mbedtls_mpi_free(&TA); mbedtls_mpi_free(&TU); mbedtls_mpi_free(&U1); mbedtls_mpi_free(&U2);
mbedtls_mpi_free(&G); mbedtls_mpi_free(&TB); mbedtls_mpi_free(&TV);
mbedtls_mpi_free(&V1); mbedtls_mpi_free(&V2);
mbedtls_mpi_free(&T);
mbedtls_mpi_free(&G);
return ret;
}
/*
* Compute X = A^-1 mod N with N even, A odd and 1 < A < N.
*
* This is not obvious because our constant-time modinv function only works with
* an odd modulus, and here the modulus is even. The idea is that computing a
* a^-1 mod b is really just computing the u coefficient in the Bézout relation
* a*u + b*v = 1 (assuming gcd(a,b) = 1, i.e. the inverse exists). But if we know
* one of u, v in this relation then the other is easy to find. So we can
* actually start by computing N^-1 mod A with gives us "the wrong half" of the
* Bézout relation, from which we'll deduce the interesting half A^-1 mod N.
*
* Return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if the inverse doesn't exist.
*/
int mbedtls_mpi_inv_mod_even_in_range(mbedtls_mpi *X,
mbedtls_mpi const *A,
mbedtls_mpi const *N)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi I, G;
mbedtls_mpi_init(&I);
mbedtls_mpi_init(&G);
/* Set I = N^-1 mod A */
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&I, N, A));
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(&G, &I, &I, A));
if (mbedtls_mpi_cmp_int(&G, 1) != 0) {
ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
goto cleanup;
}
/* We know N * I = 1 + k * A for some k, which we can easily compute
* as k = (N*I - 1) / A (we know there will be no remainder). */
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&I, &I, N));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&I, &I, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&G, NULL, &I, A));
/* Now we have a Bézout relation N * (previous value of I) - G * A = 1,
* so A^-1 mod N is -G mod N, which is N - G.
* Note that 0 < k < N since 0 < I < A, so G (k) is already in range. */
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(X, N, &G));
cleanup:
mbedtls_mpi_free(&I);
mbedtls_mpi_free(&G);
return ret;
}
/*
* Compute X = A^-1 mod N with N even and A odd (but in any range).
*
* Return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if the inverse doesn't exist.
*/
static int mbedtls_mpi_inv_mod_even(mbedtls_mpi *X,
mbedtls_mpi const *A,
mbedtls_mpi const *N)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi AA;
mbedtls_mpi_init(&AA);
/* Bring A in the range [0, N). */
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&AA, A, N));
/* We know A >= 0 but the next function wants A > 1 */
int cmp = mbedtls_mpi_cmp_int(&AA, 1);
if (cmp < 0) { // AA == 0
ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
goto cleanup;
}
if (cmp == 0) { // AA = 1
MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, 1));
goto cleanup;
}
/* Now we know 1 < A < N, N is even and AA is still odd */
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod_even_in_range(X, &AA, N));
cleanup:
mbedtls_mpi_free(&AA);
return ret;
}
/*
* Modular inverse: X = A^-1 mod N
*
* Wrapper around mbedtls_mpi_gcd_modinv_odd() that lifts its limitations.
*/
int mbedtls_mpi_inv_mod(mbedtls_mpi *X, const mbedtls_mpi *A, const mbedtls_mpi *N)
{
if (mbedtls_mpi_cmp_int(N, 1) <= 0) {
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
if (mbedtls_mpi_get_bit(N, 0) == 1) {
return mbedtls_mpi_inv_mod_odd(X, A, N);
}
if (mbedtls_mpi_get_bit(A, 0) == 1) {
return mbedtls_mpi_inv_mod_even(X, A, N);
}
/* If A and N are both even, 2 divides their GCD, so no inverse. */
return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
}
#if defined(MBEDTLS_GENPRIME)
/* Gaps between primes, starting at 3. https://oeis.org/A001223 */

View File

@@ -18,6 +18,7 @@
#include "mbedtls/platform.h"
#include "bignum_core.h"
#include "bignum_core_invasive.h"
#include "bn_mul.h"
#include "constant_time_internal.h"
@@ -1019,4 +1020,221 @@ void mbedtls_mpi_core_from_mont_rep(mbedtls_mpi_uint *X,
mbedtls_mpi_core_montmul(X, A, &Rinv, 1, N, AN_limbs, mm, T);
}
/*
* Compute X = A - B mod N.
* Both A and B must be in [0, N) and so will the output.
*/
static void mpi_core_sub_mod(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *A,
const mbedtls_mpi_uint *B,
const mbedtls_mpi_uint *N,
size_t limbs)
{
mbedtls_mpi_uint c = mbedtls_mpi_core_sub(X, A, B, limbs);
(void) mbedtls_mpi_core_add_if(X, N, limbs, (unsigned) c);
}
/*
* Divide X by 2 mod N in place, assuming N is odd.
* The input must be in [0, N) and so will the output.
*/
MBEDTLS_STATIC_TESTABLE
void mbedtls_mpi_core_div2_mod_odd(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *N,
size_t limbs)
{
/* If X is odd, add N to make it even before shifting. */
unsigned odd = (unsigned) X[0] & 1;
mbedtls_mpi_uint c = mbedtls_mpi_core_add_if(X, N, limbs, odd);
mbedtls_mpi_core_shift_r(X, limbs, 1);
X[limbs - 1] |= c << (biL - 1);
}
/*
* Constant-time GCD and modular inversion - odd modulus.
*
* Pre-conditions: see public documentation.
*
* See https://www.jstage.jst.go.jp/article/transinf/E106.D/9/E106.D_2022ICP0009/_pdf
*
* The paper gives two computationally equivalent algorithms: Alg 7 (readable)
* and Alg 8 (constant-time). We use a third version that's hopefully both:
*
* u, v = A, N # N is called p in the paper but doesn't have to be prime
* q, r = 0, 1
* repeat bits(A_limbs + N_limbs) times:
* d = v - u # t1 in Alg 7
* t1 = (u and v both odd) ? u : d # t1 in Alg 8
* t2 = (u and v both odd) ? d : (u odd) ? v : u # t2 in Alg 8
* t2 >>= 1
* swap = t1 > t2 # similar to s, z in Alg 8
* u, v = (swap) ? t2, t1 : t1, t2
*
* d = r - q mod N # t2 in Alg 7
* t1 = (u and v both odd) ? q : d # t3 in Alg 8
* t2 = (u and v both odd) ? d : (u odd) ? r : q # t4 Alg 8
* t2 /= 2 mod N # see below (pre_com)
* q, r = (swap) ? t2, t1 : t1, t2
* return v, q # v: GCD, see Alg 6; q: no mult by pre_com, see below
*
* The ternary operators in the above pseudo-code need to be realised in a
* constant-time fashion. We use conditional assign for t1, t2 and conditional
* swap for the final update. (Note: the similarity between branches of Alg 7
* are highlighted in tables 2 and 3 and the surrounding text.)
*
* Also, we re-order operations, grouping things related to the inverse, which
* facilitates making its computation optional, and requires fewer temporaries.
*
* The only actual change from the paper is dropping the trick with pre_com,
* which I think complicates things for no benefit.
* See the comment on the big I != NULL block below for details.
*/
void mbedtls_mpi_core_gcd_modinv_odd(mbedtls_mpi_uint *G,
mbedtls_mpi_uint *I,
const mbedtls_mpi_uint *A,
size_t A_limbs,
const mbedtls_mpi_uint *N,
size_t N_limbs,
mbedtls_mpi_uint *T)
{
/* GCD and modinv, names common to Alg 7 and Alg 8 */
mbedtls_mpi_uint *u = T + 0 * N_limbs;
mbedtls_mpi_uint *v = G;
/* GCD and modinv, my name (t1, t2 from Alg 7) */
mbedtls_mpi_uint *d = T + 1 * N_limbs;
/* GCD and modinv, names from Alg 8 (note: t1, t2 from Alg 7 are d above) */
mbedtls_mpi_uint *t1 = T + 2 * N_limbs;
mbedtls_mpi_uint *t2 = T + 3 * N_limbs;
/* modinv only, names common to Alg 7 and Alg 8 */
mbedtls_mpi_uint *q = I;
mbedtls_mpi_uint *r = I != NULL ? T + 4 * N_limbs : NULL;
/*
* Initial values:
* u, v = A, N
* q, r = 0, 1
*
* We only write to G (aka v) after reading from inputs (A and N), which
* allows aliasing, except with N when I != NULL, as then we'll be operating
* mod N on q and r later - see the public documentation.
*/
if (A_limbs > N_limbs) {
/* Violating this precondition should not result in memory errors. */
A_limbs = N_limbs;
}
memcpy(u, A, A_limbs * ciL);
memset((char *) u + A_limbs * ciL, 0, (N_limbs - A_limbs) * ciL);
/* Avoid possible UB with memcpy when src == dst. */
if (v != N) {
memcpy(v, N, N_limbs * ciL);
}
if (I != NULL) {
memset(q, 0, N_limbs * ciL);
memset(r, 0, N_limbs * ciL);
r[0] = 1;
}
/*
* At each step, out of u, v, v - u we keep one, shift another, and discard
* the third, then update (u, v) with the ordered result.
* Then we mirror those actions with q, r, r - q mod N.
*
* Loop invariants:
* u <= v (on entry: A <= N)
* GCD(u, v) == GCD(A, N) (on entry: trivial)
* v = A * q mod N (on entry: N = A * 0 mod N)
* u = A * r mod N (on entry: A = A * 1 mod N)
* q, r in [0, N) (on entry: 0, 1)
*
* On exit:
* u = 0
* v = GCD(A, N) = A * q mod N
* if v == 1 then 1 = A * q mod N ie q is A's inverse mod N
* r = 0
*
* The exit state is a fixed point of the loop's body.
* Alg 7 and Alg 8 use 2 * bitlen(N) iterations but Theorem 2 (above in the
* paper) says bitlen(A) + bitlen(N) is actually enough.
*/
for (size_t i = 0; i < (A_limbs + N_limbs) * biL; i++) {
/* s, z in Alg 8 - use meaningful names instead */
mbedtls_ct_condition_t u_odd = mbedtls_ct_bool(u[0] & 1);
mbedtls_ct_condition_t v_odd = mbedtls_ct_bool(v[0] & 1);
/* Other conditions that will be useful below */
mbedtls_ct_condition_t u_odd_v_odd = mbedtls_ct_bool_and(u_odd, v_odd);
mbedtls_ct_condition_t v_even = mbedtls_ct_bool_not(v_odd);
mbedtls_ct_condition_t u_odd_v_even = mbedtls_ct_bool_and(u_odd, v_even);
/* This is called t1 in Alg 7 (no name in Alg 8).
* We know that u <= v so there is no carry */
(void) mbedtls_mpi_core_sub(d, v, u, N_limbs);
/* t1 (the thing that's kept) can be d (default) or u (if t2 is d) */
memcpy(t1, d, N_limbs * ciL);
mbedtls_mpi_core_cond_assign(t1, u, N_limbs, u_odd_v_odd);
/* t2 (the thing that's shifted) can be u (if even), or v (if even),
* or d (which is even if both u and v were odd) */
memcpy(t2, u, N_limbs * ciL);
mbedtls_mpi_core_cond_assign(t2, v, N_limbs, u_odd_v_even);
mbedtls_mpi_core_cond_assign(t2, d, N_limbs, u_odd_v_odd);
mbedtls_mpi_core_shift_r(t2, N_limbs, 1); // t2 is even
/* Update u, v and re-order them if needed */
memcpy(u, t1, N_limbs * ciL);
memcpy(v, t2, N_limbs * ciL);
mbedtls_ct_condition_t swap = mbedtls_mpi_core_lt_ct(v, u, N_limbs);
mbedtls_mpi_core_cond_swap(u, v, N_limbs, swap);
/* Now, if modinv was requested, do the same with q, r, but:
* - decisions still based on u and v (their initial values);
* - operations are now mod N;
* - we re-use t1, t2 for what the paper calls t3, t4 in Alg 8.
*
* Here we slightly diverge from the paper and instead do the obvious
* thing that preserves the invariants involving q and r: mirror
* operations on u and v, ie also divide by 2 here (mod N).
*
* The paper uses a trick where it replaces division by 2 with
* multiplication by 2 here, and compensates in the end by multiplying
* by pre_com, which is probably intended as an optimisation.
*
* However I believe it's not actually an optimisation, since
* constant-time modular multiplication by 2 (left-shift + conditional
* subtract) is just as costly as constant-time modular division by 2
* (conditional add + right-shift). So, skip it and keep things simple.
*/
if (I != NULL) {
/* This is called t2 in Alg 7 (no name in Alg 8). */
mpi_core_sub_mod(d, q, r, N, N_limbs);
/* t3 (the thing that's kept) */
memcpy(t1, d, N_limbs * ciL);
mbedtls_mpi_core_cond_assign(t1, r, N_limbs, u_odd_v_odd);
/* t4 (the thing that's shifted) */
memcpy(t2, r, N_limbs * ciL);
mbedtls_mpi_core_cond_assign(t2, q, N_limbs, u_odd_v_even);
mbedtls_mpi_core_cond_assign(t2, d, N_limbs, u_odd_v_odd);
mbedtls_mpi_core_div2_mod_odd(t2, N, N_limbs);
/* Update and possibly swap */
memcpy(r, t1, N_limbs * ciL);
memcpy(q, t2, N_limbs * ciL);
mbedtls_mpi_core_cond_swap(r, q, N_limbs, swap);
}
}
/* G and I already hold the correct values by virtue of being aliased */
}
#endif /* MBEDTLS_BIGNUM_C */

View File

@@ -822,4 +822,45 @@ void mbedtls_mpi_core_from_mont_rep(mbedtls_mpi_uint *X,
mbedtls_mpi_uint mm,
mbedtls_mpi_uint *T);
/** Compute GCD(A, N) and optionally the inverse of A mod N if it exists.
*
* Requires N to be odd, 0 <= A <= N and A_limbs <= N_limbs.
* When I != NULL, N (the modulus) must be greater than 1.
*
* A and N may not alias each other.
* When I == NULL (computing only the GCD), G may alias A or N.
* When I != NULL (computing the modular inverse), G or I may alias A
* but none of them may alias N (the modulus).
*
* If any of the above preconditions is not met, output values are unspecified.
*
* \param[out] G The GCD of \p A and \p N.
* Must have the same number of limbs as \p N.
* \param[out] I The inverse of \p A modulo \p N if it exists (that is,
* if \p G above is 1 on exit); indeterminate otherwise.
* This must either be NULL (to only compute the GCD),
* or have the same number of limbs as \p N.
* \param[in] A The 1st operand of GCD and number to invert.
* This value must be less than or equal to \p N.
* \param A_limbs The number of limbs of \p A.
* Must be less than or equal to \p N_limbs.
* \param[in] N The 2nd operand of GCD and modulus for inversion.
* This value must be odd.
* If I != NULL this value must be greater than 1.
* \param N_limbs The number of limbs of \p N.
* \param[in,out] T Temporary storage of size at least 5 * N_limbs limbs,
* or 4 * N_limbs if \p I is NULL (GCD only).
* Its initial content is unused and
* its final content is indeterminate.
* It must not alias or otherwise overlap any of the
* other parameters.
*/
void mbedtls_mpi_core_gcd_modinv_odd(mbedtls_mpi_uint *G,
mbedtls_mpi_uint *I,
const mbedtls_mpi_uint *A,
size_t A_limbs,
const mbedtls_mpi_uint *N,
size_t N_limbs,
mbedtls_mpi_uint *T);
#endif /* MBEDTLS_BIGNUM_CORE_H */

View File

@@ -13,11 +13,26 @@
#include "bignum_core.h"
#if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)
#if defined(MBEDTLS_TEST_HOOKS)
#if !defined(MBEDTLS_THREADING_C)
extern void (*mbedtls_safe_codepath_hook)(void);
extern void (*mbedtls_unsafe_codepath_hook)(void);
#endif /* MBEDTLS_TEST_HOOKS && !MBEDTLS_THREADING_C */
#endif /* !MBEDTLS_THREADING_C */
/** Divide X by 2 mod N in place, assuming N is odd.
*
* \param[in,out] X The value to divide by 2 mod \p N.
* \param[in] N The modulus. Must be odd.
* \param[in] limbs The number of limbs in \p X and \p N.
*/
MBEDTLS_STATIC_TESTABLE
void mbedtls_mpi_core_div2_mod_odd(mbedtls_mpi_uint *X,
const mbedtls_mpi_uint *N,
size_t limbs);
#endif /* MBEDTLS_TEST_HOOKS */
#endif /* MBEDTLS_BIGNUM_CORE_INVASIVE_H */

View File

@@ -47,4 +47,76 @@ int mbedtls_mpi_exp_mod_unsafe(mbedtls_mpi *X, const mbedtls_mpi *A,
const mbedtls_mpi *E, const mbedtls_mpi *N,
mbedtls_mpi *prec_RR);
/**
* \brief A wrapper around a constant time function to compute
* GCD(A, N) and/or A^-1 mod N if it exists.
*
* \warning Requires N to be odd, and 0 <= A <= N. Additionally, if
* I != NULL, requires N > 1.
* The wrapper part of this function is not constant time.
*
* \note A and N must not alias each other.
* When I == NULL (computing only the GCD), G can alias A or N.
* When I != NULL (computing the modular inverse), G or I can
* alias A, but neither of them can alias N (the modulus).
*
* \param[out] G The GCD of \p A and \p N.
* This may be NULL, to only compute I.
* \param[out] I The inverse of \p A modulo \p N if it exists (that is,
* if \p G above is 1 on exit), in the range [1, \p N);
* indeterminate otherwise.
* This may be NULL, to only compute G.
* \param[in] A The 1st operand of GCD and number to invert.
* This value must be less than or equal to \p N.
* \param[in] N The 2nd operand of GCD and modulus for inversion.
* Must be odd or the results are indeterminate.
*
* \return \c 0 if successful.
* \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if preconditions were not
* met.
*/
int mbedtls_mpi_gcd_modinv_odd(mbedtls_mpi *G,
mbedtls_mpi *I,
const mbedtls_mpi *A,
const mbedtls_mpi *N);
/**
* \brief Modular inverse: X = A^-1 mod N with N odd
*
* \param[out] X The inverse of \p A modulo \p N in the range [1, \p N)
* on success; indeterminate otherwise.
* \param[in] A The number to invert.
* \param[in] N The modulus. Must be odd and greater than 1.
*
* \return \c 0 if successful.
* \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if preconditions were not
* met.
* \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if A is not invertible mod N.
*/
int mbedtls_mpi_inv_mod_odd(mbedtls_mpi *X,
const mbedtls_mpi *A,
const mbedtls_mpi *N);
/**
* \brief Modular inverse: X = A^-1 mod N with N even,
* A odd and 1 < A < N.
*
* \param[out] X The inverse of \p A modulo \p N in the range [1, \p N)
* on success; indeterminate otherwise.
* \param[in] A The number to invert. Must be odd, greated than 1
* and less than \p N.
* \param[in] N The modulus. Must be even and greater than 1.
*
* \return \c 0 if successful.
* \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if preconditions were not
* met.
* \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if A is not invertible mod N.
*/
int mbedtls_mpi_inv_mod_even_in_range(mbedtls_mpi *X,
mbedtls_mpi const *A,
mbedtls_mpi const *N);
#endif /* bignum_internal.h */

View File

@@ -846,7 +846,8 @@ static void add_pkcs_padding(unsigned char *output, size_t output_len,
*/
MBEDTLS_STATIC_TESTABLE int mbedtls_get_pkcs_padding(unsigned char *input,
size_t input_len,
size_t *data_len)
size_t *data_len,
size_t *invalid_padding)
{
size_t i, pad_idx;
unsigned char padding_len;
@@ -872,7 +873,8 @@ MBEDTLS_STATIC_TESTABLE int mbedtls_get_pkcs_padding(unsigned char *input,
/* If the padding is invalid, set the output length to 0 */
*data_len = mbedtls_ct_if(bad, 0, input_len - padding_len);
return mbedtls_ct_error_if_else_0(bad, MBEDTLS_ERR_CIPHER_INVALID_PADDING);
*invalid_padding = mbedtls_ct_size_if_else_0(bad, SIZE_MAX);
return 0;
}
#endif /* MBEDTLS_CIPHER_PADDING_PKCS7 */
@@ -893,7 +895,7 @@ static void add_one_and_zeros_padding(unsigned char *output,
}
static int get_one_and_zeros_padding(unsigned char *input, size_t input_len,
size_t *data_len)
size_t *data_len, size_t *invalid_padding)
{
if (NULL == input || NULL == data_len) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
@@ -916,7 +918,8 @@ static int get_one_and_zeros_padding(unsigned char *input, size_t input_len,
in_padding = mbedtls_ct_bool_and(in_padding, mbedtls_ct_bool_not(is_nonzero));
}
return mbedtls_ct_error_if_else_0(bad, MBEDTLS_ERR_CIPHER_INVALID_PADDING);
*invalid_padding = mbedtls_ct_size_if_else_0(bad, SIZE_MAX);
return 0;
}
#endif /* MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS */
@@ -937,7 +940,7 @@ static void add_zeros_and_len_padding(unsigned char *output,
}
static int get_zeros_and_len_padding(unsigned char *input, size_t input_len,
size_t *data_len)
size_t *data_len, size_t *invalid_padding)
{
size_t i, pad_idx;
unsigned char padding_len;
@@ -963,7 +966,8 @@ static int get_zeros_and_len_padding(unsigned char *input, size_t input_len,
bad = mbedtls_ct_bool_or(bad, nonzero_pad_byte);
}
return mbedtls_ct_error_if_else_0(bad, MBEDTLS_ERR_CIPHER_INVALID_PADDING);
*invalid_padding = mbedtls_ct_size_if_else_0(bad, SIZE_MAX);
return 0;
}
#endif /* MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN */
@@ -978,7 +982,7 @@ static void add_zeros_padding(unsigned char *output,
}
static int get_zeros_padding(unsigned char *input, size_t input_len,
size_t *data_len)
size_t *data_len, size_t *invalid_padding)
{
size_t i;
mbedtls_ct_condition_t done = MBEDTLS_CT_FALSE, prev_done;
@@ -994,6 +998,7 @@ static int get_zeros_padding(unsigned char *input, size_t input_len,
*data_len = mbedtls_ct_size_if(mbedtls_ct_bool_ne(done, prev_done), i, *data_len);
}
*invalid_padding = 0;
return 0;
}
#endif /* MBEDTLS_CIPHER_PADDING_ZEROS */
@@ -1005,20 +1010,21 @@ static int get_zeros_padding(unsigned char *input, size_t input_len,
* but a trivial get_padding function
*/
static int get_no_padding(unsigned char *input, size_t input_len,
size_t *data_len)
size_t *data_len, size_t *invalid_padding)
{
if (NULL == input || NULL == data_len) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
*data_len = input_len;
*invalid_padding = 0;
return 0;
}
#endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
int mbedtls_cipher_finish(mbedtls_cipher_context_t *ctx,
unsigned char *output, size_t *olen)
int mbedtls_cipher_finish_padded(mbedtls_cipher_context_t *ctx,
unsigned char *output, size_t *olen,
size_t *invalid_padding)
{
if (ctx->cipher_info == NULL) {
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
@@ -1034,6 +1040,7 @@ int mbedtls_cipher_finish(mbedtls_cipher_context_t *ctx,
#endif /* MBEDTLS_USE_PSA_CRYPTO && !MBEDTLS_DEPRECATED_REMOVED */
*olen = 0;
*invalid_padding = 0;
#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
/* CBC mode requires padding so we make sure a call to
@@ -1110,7 +1117,7 @@ int mbedtls_cipher_finish(mbedtls_cipher_context_t *ctx,
/* Set output size for decryption */
if (MBEDTLS_DECRYPT == ctx->operation) {
return ctx->get_padding(output, mbedtls_cipher_get_block_size(ctx),
olen);
olen, invalid_padding);
}
/* Set output size for encryption */
@@ -1124,6 +1131,19 @@ int mbedtls_cipher_finish(mbedtls_cipher_context_t *ctx,
return MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;
}
int mbedtls_cipher_finish(mbedtls_cipher_context_t *ctx,
unsigned char *output, size_t *olen)
{
size_t invalid_padding = 0;
int ret = mbedtls_cipher_finish_padded(ctx, output, olen,
&invalid_padding);
if (ret == 0) {
ret = mbedtls_ct_error_if_else_0(invalid_padding,
MBEDTLS_ERR_CIPHER_INVALID_PADDING);
}
return ret;
}
#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
int mbedtls_cipher_set_padding_mode(mbedtls_cipher_context_t *ctx,
mbedtls_cipher_padding_t mode)
@@ -1393,14 +1413,17 @@ int mbedtls_cipher_crypt(mbedtls_cipher_context_t *ctx,
return ret;
}
if ((ret = mbedtls_cipher_finish(ctx, output + *olen,
&finish_olen)) != 0) {
size_t invalid_padding = 0;
if ((ret = mbedtls_cipher_finish_padded(ctx, output + *olen,
&finish_olen,
&invalid_padding)) != 0) {
return ret;
}
*olen += finish_olen;
return 0;
ret = mbedtls_ct_error_if_else_0(invalid_padding,
MBEDTLS_ERR_CIPHER_INVALID_PADDING);
return ret;
}
#if defined(MBEDTLS_CIPHER_MODE_AEAD)

View File

@@ -20,7 +20,8 @@
MBEDTLS_STATIC_TESTABLE int mbedtls_get_pkcs_padding(unsigned char *input,
size_t input_len,
size_t *data_len);
size_t *data_len,
size_t *invalid_padding);
#endif

View File

@@ -18,6 +18,7 @@
#if defined(MBEDTLS_DHM_C)
#include "mbedtls/dhm.h"
#include "bignum_internal.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
@@ -344,9 +345,6 @@ static int dhm_update_blinding(mbedtls_dhm_context *ctx,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
{
int ret;
mbedtls_mpi R;
mbedtls_mpi_init(&R);
/*
* Don't use any blinding the first time a particular X is used,
@@ -381,21 +379,11 @@ static int dhm_update_blinding(mbedtls_dhm_context *ctx,
/* Vi = random( 2, P-2 ) */
MBEDTLS_MPI_CHK(dhm_random_below(&ctx->Vi, &ctx->P, f_rng, p_rng));
/* Vf = Vi^-X mod P
* First compute Vi^-1 = R * (R Vi)^-1, (avoiding leaks from inv_mod),
* then elevate to the Xth power. */
MBEDTLS_MPI_CHK(dhm_random_below(&R, &ctx->P, f_rng, p_rng));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vi, &R));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->P));
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&ctx->Vf, &ctx->Vf, &ctx->P));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vf, &R));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->P));
/* Vf = Vi^-X = (Vi^-1)^X mod P */
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(NULL, &ctx->Vf, &ctx->Vi, &ctx->P));
MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->Vf, &ctx->Vf, &ctx->X, &ctx->P, &ctx->RP));
cleanup:
mbedtls_mpi_free(&R);
return ret;
}

View File

@@ -17,6 +17,7 @@
#include "mbedtls/ecdsa.h"
#include "mbedtls/asn1write.h"
#include "bignum_internal.h"
#include <string.h>
@@ -251,7 +252,7 @@ int mbedtls_ecdsa_sign_restartable(mbedtls_ecp_group *grp,
int ret, key_tries, sign_tries;
int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries;
mbedtls_ecp_point R;
mbedtls_mpi k, e, t;
mbedtls_mpi k, e;
mbedtls_mpi *pk = &k, *pr = r;
/* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */
@@ -265,7 +266,7 @@ int mbedtls_ecdsa_sign_restartable(mbedtls_ecp_group *grp,
}
mbedtls_ecp_point_init(&R);
mbedtls_mpi_init(&k); mbedtls_mpi_init(&e); mbedtls_mpi_init(&t);
mbedtls_mpi_init(&k); mbedtls_mpi_init(&e);
ECDSA_RS_ENTER(sig);
@@ -340,21 +341,11 @@ modn:
MBEDTLS_MPI_CHK(derive_mpi(grp, &e, buf, blen));
/*
* Generate a random value to blind inv_mod in next step,
* avoiding a potential timing leak.
*/
MBEDTLS_MPI_CHK(mbedtls_ecp_gen_privkey(grp, &t, f_rng_blind,
p_rng_blind));
/*
* Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n
* Step 6: compute s = (e + r * d) / k
*/
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(s, pr, d));
MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&e, &e, s));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&e, &e, &t));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(pk, pk, &t));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(pk, pk, &grp->N));
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(s, pk, &grp->N));
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(NULL, s, pk, &grp->N));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(s, s, &e));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(s, s, &grp->N));
} while (mbedtls_mpi_cmp_int(s, 0) == 0);
@@ -367,7 +358,7 @@ modn:
cleanup:
mbedtls_ecp_point_free(&R);
mbedtls_mpi_free(&k); mbedtls_mpi_free(&e); mbedtls_mpi_free(&t);
mbedtls_mpi_free(&k); mbedtls_mpi_free(&e);
ECDSA_RS_LEAVE(sig);
@@ -540,7 +531,7 @@ int mbedtls_ecdsa_verify_restartable(mbedtls_ecp_group *grp,
*/
ECDSA_BUDGET(MBEDTLS_ECP_OPS_CHK + MBEDTLS_ECP_OPS_INV + 2);
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&s_inv, s, &grp->N));
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(NULL, &s_inv, s, &grp->N));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(pu1, &e, &s_inv));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(pu1, pu1, &grp->N));

View File

@@ -68,6 +68,7 @@
#include "mbedtls/error.h"
#include "bn_mul.h"
#include "bignum_internal.h"
#include "ecp_invasive.h"
#include <string.h>
@@ -1173,7 +1174,7 @@ cleanup:
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_int_mod(grp, X, A, c))
#define MPI_ECP_INV(dst, src) \
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod((dst), (src), &grp->P))
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(NULL, (dst), (src), &grp->P))
#define MPI_ECP_MOV(X, A) \
MBEDTLS_MPI_CHK(mbedtls_mpi_copy(X, A))
@@ -2201,21 +2202,6 @@ static int ecp_mul_comb_after_precomp(const mbedtls_ecp_group *grp,
final_norm:
MBEDTLS_ECP_BUDGET(MBEDTLS_ECP_OPS_INV);
#endif
/*
* Knowledge of the jacobian coordinates may leak the last few bits of the
* scalar [1], and since our MPI implementation isn't constant-flow,
* inversion (used for coordinate normalization) may leak the full value
* of its input via side-channels [2].
*
* [1] https://eprint.iacr.org/2003/191
* [2] https://eprint.iacr.org/2020/055
*
* Avoid the leak by randomizing coordinates before we normalize them.
*/
if (f_rng != 0) {
MBEDTLS_MPI_CHK(ecp_randomize_jac(grp, RR, f_rng, p_rng));
}
MBEDTLS_MPI_CHK(ecp_normalize_jac(grp, RR));
#if defined(MBEDTLS_ECP_RESTARTABLE)
@@ -2594,18 +2580,6 @@ static int ecp_mul_mxz(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
MPI_ECP_COND_SWAP(&R->Z, &RP.Z, b);
}
/*
* Knowledge of the projective coordinates may leak the last few bits of the
* scalar [1], and since our MPI implementation isn't constant-flow,
* inversion (used for coordinate normalization) may leak the full value
* of its input via side-channels [2].
*
* [1] https://eprint.iacr.org/2003/191
* [2] https://eprint.iacr.org/2020/055
*
* Avoid the leak by randomizing coordinates before we normalize them.
*/
MBEDTLS_MPI_CHK(ecp_randomize_mxz(grp, R, f_rng, p_rng));
MBEDTLS_MPI_CHK(ecp_normalize_mxz(grp, R));
cleanup:

View File

@@ -73,6 +73,8 @@
#include "mbedtls/psa_util.h"
#include "mbedtls/threading.h"
#include "constant_time_internal.h"
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
@@ -4692,13 +4694,27 @@ psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation,
output_length);
exit:
if (status == PSA_SUCCESS) {
status = psa_cipher_abort(operation);
} else {
*output_length = 0;
(void) psa_cipher_abort(operation);
/* C99 doesn't allow a declaration to follow a label */;
psa_status_t abort_status = psa_cipher_abort(operation);
/* Normally abort shouldn't fail unless the operation is in a bad
* state, in which case we'd expect finish to fail with the same error.
* So it doesn't matter much which call's error code we pick when both
* fail. However, in unauthenticated decryption specifically, the
* distinction between PSA_SUCCESS and PSA_ERROR_INVALID_PADDING is
* security-sensitive (risk of a padding oracle attack), so here we
* must not have a code path that depends on the value of status. */
if (abort_status != PSA_SUCCESS) {
status = abort_status;
}
/* Set *output_length to 0 if status != PSA_SUCCESS, without
* leaking the value of status through a timing side channel
* (status == PSA_ERROR_INVALID_PADDING is sensitive when doing
* unpadded decryption, due to the risk of padding oracle attack). */
mbedtls_ct_condition_t success =
mbedtls_ct_bool_not(mbedtls_ct_bool(status));
*output_length = mbedtls_ct_size_if_else_0(success, *output_length);
LOCAL_OUTPUT_FREE(output_external, output);
return status;
@@ -4841,13 +4857,17 @@ psa_status_t psa_cipher_decrypt(mbedtls_svc_key_id_t key,
exit:
unlock_status = psa_unregister_read_under_mutex(slot);
if (status == PSA_SUCCESS) {
if (unlock_status != PSA_SUCCESS) {
status = unlock_status;
}
if (status != PSA_SUCCESS) {
*output_length = 0;
}
/* Set *output_length to 0 if status != PSA_SUCCESS, without
* leaking the value of status through a timing side channel
* (status == PSA_ERROR_INVALID_PADDING is sensitive when doing
* unpadded decryption, due to the risk of padding oracle attack). */
mbedtls_ct_condition_t success =
mbedtls_ct_bool_not(mbedtls_ct_bool(status));
*output_length = mbedtls_ct_size_if_else_0(success, *output_length);
LOCAL_INPUT_FREE(input_external, input);
LOCAL_OUTPUT_FREE(output_external, output);

View File

@@ -13,6 +13,7 @@
#include "psa_crypto_cipher.h"
#include "psa_crypto_core.h"
#include "psa_crypto_random_impl.h"
#include "constant_time_internal.h"
#include "mbedtls/cipher.h"
#include "mbedtls/error.h"
@@ -551,7 +552,19 @@ psa_status_t mbedtls_psa_cipher_finish(
uint8_t *output, size_t output_size, size_t *output_length)
{
psa_status_t status = PSA_ERROR_GENERIC_ERROR;
uint8_t temp_output_buffer[MBEDTLS_MAX_BLOCK_LENGTH];
size_t invalid_padding = 0;
/* We will copy output_size bytes from temp_output_buffer to the
* output buffer. We can't use *output_length to determine how
* much to copy because we must not leak that value through timing
* when doing decryption with unpadding. But the underlying function
* is not guaranteed to write beyond *output_length. To ensure we don't
* leak the former content of the stack to the caller, wipe that
* former content. */
uint8_t temp_output_buffer[MBEDTLS_MAX_BLOCK_LENGTH] = { 0 };
if (output_size > sizeof(temp_output_buffer)) {
output_size = sizeof(temp_output_buffer);
}
if (operation->ctx.cipher.unprocessed_len != 0) {
if (operation->alg == PSA_ALG_ECB_NO_PADDING ||
@@ -562,25 +575,34 @@ psa_status_t mbedtls_psa_cipher_finish(
}
status = mbedtls_to_psa_error(
mbedtls_cipher_finish(&operation->ctx.cipher,
temp_output_buffer,
output_length));
mbedtls_cipher_finish_padded(&operation->ctx.cipher,
temp_output_buffer,
output_length,
&invalid_padding));
if (status != PSA_SUCCESS) {
goto exit;
}
if (*output_length == 0) {
if (output_size == 0) {
; /* Nothing to copy. Note that output may be NULL in this case. */
} else if (output_size >= *output_length) {
memcpy(output, temp_output_buffer, *output_length);
} else {
status = PSA_ERROR_BUFFER_TOO_SMALL;
/* Do not use the value of *output_length to determine how much
* to copy. When decrypting a padded cipher, the output length is
* sensitive, and leaking it could allow a padding oracle attack. */
memcpy(output, temp_output_buffer, output_size);
}
status = mbedtls_ct_error_if_else_0(invalid_padding,
PSA_ERROR_INVALID_PADDING);
mbedtls_ct_condition_t buffer_too_small =
mbedtls_ct_uint_lt(output_size, *output_length);
status = mbedtls_ct_error_if(buffer_too_small,
PSA_ERROR_BUFFER_TOO_SMALL,
status);
exit:
mbedtls_platform_zeroize(temp_output_buffer,
sizeof(temp_output_buffer));
return status;
}
@@ -701,17 +723,21 @@ psa_status_t mbedtls_psa_cipher_decrypt(
&operation,
mbedtls_buffer_offset(output, accumulated_length),
output_size - accumulated_length, &olength);
if (status != PSA_SUCCESS) {
goto exit;
}
*output_length = accumulated_length + olength;
exit:
if (status == PSA_SUCCESS) {
status = mbedtls_psa_cipher_abort(&operation);
} else {
mbedtls_psa_cipher_abort(&operation);
/* C99 doesn't allow a declaration to follow a label */;
psa_status_t abort_status = mbedtls_psa_cipher_abort(&operation);
/* Normally abort shouldn't fail unless the operation is in a bad
* state, in which case we'd expect finish to fail with the same error.
* So it doesn't matter much which call's error code we pick when both
* fail. However, in unauthenticated decryption specifically, the
* distinction between PSA_SUCCESS and PSA_ERROR_INVALID_PADDING is
* security-sensitive (risk of a padding oracle attack), so here we
* must not have a code path that depends on the value of status. */
if (abort_status != PSA_SUCCESS) {
status = abort_status;
}
return status;

View File

@@ -1047,7 +1047,7 @@ int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx,
unsigned int nbits, int exponent)
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi H, G, L;
mbedtls_mpi H;
int prime_quality = 0;
/*
@@ -1060,8 +1060,6 @@ int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx,
}
mbedtls_mpi_init(&H);
mbedtls_mpi_init(&G);
mbedtls_mpi_init(&L);
if (exponent < 3 || nbits % 2 != 0) {
ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
@@ -1099,35 +1097,28 @@ int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx,
mbedtls_mpi_swap(&ctx->P, &ctx->Q);
}
/* Temporarily replace P,Q by P-1, Q-1 */
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->P, &ctx->P, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->Q, &ctx->Q, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&H, &ctx->P, &ctx->Q));
/* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->E, &H));
if (mbedtls_mpi_cmp_int(&G, 1) != 0) {
/* Compute D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b))
* if it exists (FIPS 186-4 §B.3.1 criterion 2(a)) */
ret = mbedtls_rsa_deduce_private_exponent(&ctx->P, &ctx->Q, &ctx->E, &ctx->D);
if (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
mbedtls_mpi_lset(&ctx->D, 0); /* needed for the next call */
continue;
}
if (ret != 0) {
goto cleanup;
}
/* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->P, &ctx->Q));
MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&L, NULL, &H, &G));
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&ctx->D, &ctx->E, &L));
if (mbedtls_mpi_bitlen(&ctx->D) <= ((nbits + 1) / 2)) { // (FIPS 186-4 §B.3.1 criterion 3(a))
/* (FIPS 186-4 §B.3.1 criterion 3(a)) */
if (mbedtls_mpi_bitlen(&ctx->D) <= ((nbits + 1) / 2)) {
continue;
}
break;
} while (1);
/* Restore P,Q */
MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->P, &ctx->P, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->Q, &ctx->Q, 1));
/* N = P * Q */
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q));
ctx->len = mbedtls_mpi_size(&ctx->N);
#if !defined(MBEDTLS_RSA_NO_CRT)
@@ -1146,8 +1137,6 @@ int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx,
cleanup:
mbedtls_mpi_free(&H);
mbedtls_mpi_free(&G);
mbedtls_mpi_free(&L);
if (ret != 0) {
mbedtls_rsa_free(ctx);
@@ -1304,33 +1293,16 @@ static int rsa_prepare_blinding(mbedtls_rsa_context *ctx,
}
/* Unblinding value: Vf = random number, invertible mod N */
mbedtls_mpi_lset(&R, 0);
do {
if (count++ > 10) {
ret = MBEDTLS_ERR_RSA_RNG_FAILED;
goto cleanup;
}
MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&ctx->Vf, ctx->len - 1, f_rng, p_rng));
/* Compute Vf^-1 as R * (R Vf)^-1 to avoid leaks from inv_mod. */
MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, ctx->len - 1, f_rng, p_rng));
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vf, &R));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
/* At this point, Vi is invertible mod N if and only if both Vf and R
* are invertible mod N. If one of them isn't, we don't need to know
* which one, we just loop and choose new values for both of them.
* (Each iteration succeeds with overwhelming probability.) */
ret = mbedtls_mpi_inv_mod(&ctx->Vi, &ctx->Vi, &ctx->N);
if (ret != 0 && ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
goto cleanup;
}
} while (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE);
/* Finish the computation of Vf^-1 = R * (R Vf)^-1 */
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &R));
MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
MBEDTLS_MPI_CHK(mbedtls_mpi_random(&ctx->Vf, 1, &ctx->N, f_rng, p_rng));
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(&R, &ctx->Vi, &ctx->Vf, &ctx->N));
} while (mbedtls_mpi_cmp_int(&R, 1) != 0);
/* Blinding value: Vi = Vf^(-e) mod N
* (Vi already contains Vf^-1 at this point) */

View File

@@ -12,6 +12,7 @@
#include "mbedtls/rsa.h"
#include "mbedtls/bignum.h"
#include "bignum_internal.h"
#include "rsa_alt_helpers.h"
/*
@@ -117,7 +118,7 @@ int mbedtls_rsa_deduce_primes(mbedtls_mpi const *N,
MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&K, primes[attempt]));
/* Check if gcd(K,N) = 1 */
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(P, &K, N));
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(P, NULL, &K, N));
if (mbedtls_mpi_cmp_int(P, 1) != 0) {
continue;
}
@@ -136,7 +137,7 @@ int mbedtls_rsa_deduce_primes(mbedtls_mpi const *N,
}
MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&K, &K, 1));
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(P, &K, N));
MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(P, NULL, &K, N));
if (mbedtls_mpi_cmp_int(P, 1) == 1 &&
mbedtls_mpi_cmp_mpi(P, N) == -1) {
@@ -197,6 +198,10 @@ int mbedtls_rsa_deduce_private_exponent(mbedtls_mpi const *P,
return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
}
if (mbedtls_mpi_get_bit(E, 0) != 1) {
return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
}
mbedtls_mpi_init(&K);
mbedtls_mpi_init(&L);
@@ -211,8 +216,11 @@ int mbedtls_rsa_deduce_private_exponent(mbedtls_mpi const *P,
MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&K, &K, &L));
MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&K, NULL, &K, D));
/* Compute modular inverse of E in LCM(P-1, Q-1) */
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(D, E, &K));
/* Compute modular inverse of E mod LCM(P-1, Q-1)
* This is FIPS 186-4 §B.3.1 criterion 3(b).
* This will return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if E is not coprime to
* (P-1)(Q-1), also validating FIPS 186-4 §B.3.1 criterion 2(a). */
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod_even_in_range(D, E, &K));
cleanup:
@@ -244,7 +252,7 @@ int mbedtls_rsa_deduce_crt(const mbedtls_mpi *P, const mbedtls_mpi *Q,
/* QP = Q^{-1} mod P */
if (QP != NULL) {
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(QP, Q, P));
MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod_odd(QP, Q, P));
}
cleanup:

View File

@@ -89,12 +89,15 @@ int mbedtls_rsa_deduce_primes(mbedtls_mpi const *N, mbedtls_mpi const *E,
* \param P First prime factor of RSA modulus
* \param Q Second prime factor of RSA modulus
* \param E RSA public exponent
* \param D Pointer to MPI holding the private exponent on success.
* \param D Pointer to MPI holding the private exponent on success,
* i.e. the modular inverse of E modulo LCM(P-1,Q-1).
*
* \return
* - 0 if successful. In this case, D is set to a simultaneous
* modular inverse of E modulo both P-1 and Q-1.
* - A non-zero error code otherwise.
* \return \c 0 if successful.
* \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
* \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if E is not coprime to P-1
* and Q-1, that is, if GCD( E, (P-1)*(Q-1) ) != 1.
* \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if inputs are otherwise
* invalid.
*
* \note This function does not check whether P and Q are primes.
*