[PATCH] mpi: Fix NULL pointer dereference in mpi_invm for a zero.
Florian Bauckholt
florian.bauckholt at cispa.de
Thu Nov 26 10:09:29 CET 2026
* mpi/mpi-inv.c (_gcry_mpi_invm): Check for an MPI without limbs.
* tests/mpitests.c (test_invm_cmpui): Add a test.
--
_gcry_mpih_cmp_ui reads the first limb unconditionally.
gcry_mpi_new (0), for example, has no allocated limb space, thus
gcry_mpi_invm (x, a, n) crashed for a=0.
Signed-off-by: Florian Bauckholt <florian.bauckholt at cispa.de>
---
mpi/mpi-inv.c | 4 +++-
tests/mpitests.c | 10 ++++++++++
2 files changed, 13 insertions(+), 1 deletion(-)
diff --git a/mpi/mpi-inv.c b/mpi/mpi-inv.c
index 1b6965d8..bac50020 100644
--- a/mpi/mpi-inv.c
+++ b/mpi/mpi-inv.c
@@ -438,7 +438,9 @@ _gcry_mpi_invm (gcry_mpi_t x, gcry_mpi_t a, gcry_mpi_t n)
{
mpi_ptr_t ap, xp;
- if (!_gcry_mpih_cmp_ui (a->d, a->nlimbs, 0))
+ /* Note that a zero may also be represented by an MPI without any
+ allocated limb. */
+ if (!a->nlimbs || !_gcry_mpih_cmp_ui (a->d, a->nlimbs, 0))
return 0; /* Inverse does not exists. */
if (!mpi_cmp_ui (n, 1))
return 0; /* Inverse does not exists. */
diff --git a/tests/mpitests.c b/tests/mpitests.c
index 4a0be5de..9666ee23 100644
--- a/tests/mpitests.c
+++ b/tests/mpitests.c
@@ -774,6 +774,16 @@ test_invm_cmpui(void)
gcry_mpi_release(C);
}
+ /* A zero without any allocated limb has no inverse. */
+ A = gcry_mpi_new(0);
+ B = gcry_mpi_set_ui(NULL, 7);
+ C = gcry_mpi_new(0);
+ if (gcry_mpi_invm(C, A, B))
+ die ("test_invm_cmpui failed at %d\n", __LINE__);
+ gcry_mpi_release(A);
+ gcry_mpi_release(B);
+ gcry_mpi_release(C);
+
return 1;
}
--
2.56.0
More information about the Gcrypt-devel
mailing list