[PATCH] Avoid undefined behavior for hashes using XOF

Peter Wu peter at lekensteyn.nl
Thu Mar 24 00:29:36 CET 2016


cipher/md.c: skip memcpy for hashes without a fixed length.
--

Caught by UndefinedBehaviorSanitizer wjile running tests/benchmarks.

While the functions could simply shortcircuit and return early, let's
perform the hash calculations anyway such that the benchmarks can be
run. Copying zero bytes is valid according to the documentation of
gcry_md_hash_buffer{,s} as gcry_md_get_algo_dlen() returns 0.

Signed-off-by: Peter Wu <peter at lekensteyn.nl>
---
Given the variable length output of XOFs like SHAKE128 and SHAKE256, I
doubt that these convenience functions are useful. Let's prevent the
undefined behavior at least.
---
 cipher/md.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/cipher/md.c b/cipher/md.c
index 0414dcb..5982b8f 100644
--- a/cipher/md.c
+++ b/cipher/md.c
@@ -972,7 +972,8 @@ _gcry_md_hash_buffer (int algo, void *digest,
                  algo, gpg_strerror (gcry_error(err)));
       md_write (h, (byte *) buffer, length);
       md_final (h);
-      memcpy (digest, md_read (h, algo), md_digest_length (algo));
+      if (md_digest_length (algo))
+        memcpy (digest, md_read (h, algo), md_digest_length (algo));
       md_close (h);
     }
 }
@@ -1046,7 +1047,8 @@ _gcry_md_hash_buffers (int algo, unsigned int flags, void *digest,
       for (;iovcnt; iov++, iovcnt--)
         md_write (h, (const char*)iov[0].data + iov[0].off, iov[0].len);
       md_final (h);
-      memcpy (digest, md_read (h, algo), md_digest_length (algo));
+      if (md_digest_length (algo))
+        memcpy (digest, md_read (h, algo), md_digest_length (algo));
       md_close (h);
     }
 
-- 
2.7.4




More information about the Gcrypt-devel mailing list