From eefdfe99a47d8d7b8a8c67f8f1e621d06e6042b2 Mon Sep 17 00:00:00 2001 From: Felix Conway Date: Tue, 5 Aug 2025 14:35:53 +0100 Subject: [PATCH] Change A=0 (null) handling in mpi_gcd_invmod_odd() Signed-off-by: Felix Conway --- library/bignum.c | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/library/bignum.c b/library/bignum.c index e141cda740..53ff95eadd 100644 --- a/library/bignum.c +++ b/library/bignum.c @@ -1751,9 +1751,9 @@ int mbedtls_mpi_gcd_modinv_odd(mbedtls_mpi *G, { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_mpi local_g; - mbedtls_mpi local_a; 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 || @@ -1768,16 +1768,6 @@ int mbedtls_mpi_gcd_modinv_odd(mbedtls_mpi *G, return MBEDTLS_ERR_MPI_BAD_INPUT_DATA; } - mbedtls_mpi_init(&local_a); - /* If A is 0 (null), then A->p will be null, which is an issue when A->p is - * passed to mbedtls_mpi_core_gcd_modinv_odd below, so set A to 0 (1 limb) - * in this case. */ - if (A->n == 0 && A->p == NULL) { - mbedtls_mpi_read_string(&local_a, 16, "00"); - } else { - mbedtls_mpi_copy(&local_a, A); - } - mbedtls_mpi_init(&local_g); if (G == NULL) { @@ -1797,9 +1787,15 @@ int mbedtls_mpi_gcd_modinv_odd(mbedtls_mpi *G, goto cleanup; } + /* We have to handle G and I carefully as they could be aliased + * to A or N. */ mbedtls_mpi_uint *Ip = I != NULL ? I->p : NULL; - size_t An = local_a.n <= N->n ? local_a.n : N->n; - mbedtls_mpi_core_gcd_modinv_odd(G->p, Ip, local_a.p, An, N->p, N->n, T); + /* If A is 0 (null), then A->p would be null, which would be an issue if + * A->p was passed to mbedtls_mpi_core_gcd_modinv_odd below. */ + const mbedtls_mpi_uint *Ap = A->p != NULL ? A->p : &zero; + size_t An = A->p == NULL ? 0 : A->n; + An = A->n <= N->n ? A->n : N->n; + mbedtls_mpi_core_gcd_modinv_odd(G->p, Ip, Ap, An, N->p, N->n, T); if (G->n > N->n) { memset(G->p + N->n, 0, ciL * (G->n - N->n)); @@ -1810,7 +1806,6 @@ int mbedtls_mpi_gcd_modinv_odd(mbedtls_mpi *G, cleanup: mbedtls_mpi_free(&local_g); - mbedtls_mpi_free(&local_a); mbedtls_free(T); return ret; }