Fwd: mpi_set_secure leads to heap corruption

Andreas Metzler ametzler at bebt.de
Mon Jul 3 19:15:14 CEST 2017


Hello,

this is http://bugs.debian.org/866964 submitted by Mark Wooding
<mdw at distorted.org.uk> against libgcrypt 1.7.6-1.7.8:

-------------------------------------------------------------
The function `mpi_set_secure' is used by `gcry_mpi_set_flag' to convert
an integer so as to use `secure' (i.e., locked, non-swappable) memory.
[...] 
The code allocates enough secure memory for the active limbs, copies
them from the existing buffer, and stores a pointer to the new buffer --
all without reducing the separate count of the number of allocated
limbs.  In particular, when the securified integer is freed,
`_gcry_mpi_free' calls `_gcry_mpi_free_limb_space' to release the limb
buffer, giving it the allocated size, and the latter attempts to zeroize
the storage, leading to a heap corruption.

The patch fixes the problem.  I've not thought deeply about the
performance effects: maybe it'd be better to allocate the same total
limb buffer rather than just the active size, but this patch is simple
and obviously right.

diff --git a/mpi/mpiutil.c b/mpi/mpiutil.c
index 6dee0b9..2a32d26 100644
--- a/mpi/mpiutil.c
+++ b/mpi/mpiutil.c
@@ -260,6 +260,7 @@ mpi_set_secure( gcry_mpi_t a )
   MPN_COPY( bp, ap, a->nlimbs );
   a->d = bp;
   _gcry_mpi_free_limb_space (ap, a->alloced);
+  a->alloced = a->nlimbs;
 }
-------------------------------------------------------------

cu Andreas



More information about the Gcrypt-devel mailing list