Crash in gcry_mpi_powm

Werner Koch wk at gnupg.org
Wed Jul 17 10:21:48 CEST 2013


On Tue, 16 Jul 2013 23:27, linux at paip.net said:

> But if I pass zero, it segfaults in gcry_mpi_powm:

Find a patch below.  I am going to apply this also to stable.  You may
want to use the workaround for now.


Shalom-Salam,

   Werner


>From 6e1adb05d290aeeb1c230c763970695f4a538526 Mon Sep 17 00:00:00 2001
From: Werner Koch <wk at gnupg.org>
Date: Wed, 17 Jul 2013 10:18:39 +0200
Subject: [PATCH] Fix a special case bug in mpi_powm for e==0.

* mpi/mpi-pow.c (gcry_mpi_powm): For a zero exponent, make sure that
the result has been allocated.
--

This code triggered the problem:

    modulus = gcry_mpi_set_ui(NULL, 100);
    generator = gcry_mpi_set_ui(NULL, 3);
    exponent = gcry_mpi_set_ui(NULL, 0);
    result = gcry_mpi_new(0);
    gcry_mpi_powm(result, generator, exponent, modulus);

gcry_mpi_new(0) does not allocate the limb space thus it is not
possible to write even into the first limb.  Workaround was to use
gcry_mpi_new (1) but a real fix is better.

Reported-by: Ian Goldberg
Signed-off-by: Werner Koch <wk at gnupg.org>
---
 mpi/mpi-pow.c |    9 +++++++--
 1 files changed, 7 insertions(+), 2 deletions(-)

diff --git a/mpi/mpi-pow.c b/mpi/mpi-pow.c
index 891a7e6..7ec49d7 100644
--- a/mpi/mpi-pow.c
+++ b/mpi/mpi-pow.c
@@ -81,9 +81,14 @@ gcry_mpi_powm (gcry_mpi_t res,
   if (!esize)
     {
       /* Exponent is zero, result is 1 mod MOD, i.e., 1 or 0 depending
-        on if MOD equals 1.  */
-      rp[0] = 1;
+         on if MOD equals 1.  */
       res->nlimbs = (msize == 1 && mod->d[0] == 1) ? 0 : 1;
+      if (res->nlimbs)
+        {
+          RESIZE_IF_NEEDED (res, 1);
+          rp = res->d;
+          rp[0] = 1;
+        }
       res->sign = 0;
       goto leave;
     }
-- 
1.7.7.1


-- 
Die Gedanken sind frei.  Ausnahmen regelt ein Bundesgesetz.




More information about the Gcrypt-devel mailing list