From 760dc943af4854f28bf7b14b5c60bd9027be5743 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Niels=20M=C3=B6ller?= <nisse@lysator.liu.se>
Date: Sun, 25 Nov 2018 16:23:06 +0100
Subject: [PATCH] Tweak valgrind marking is rsa_sec_decrypt tests.

* testsuite/rsa-sec-decrypt-test.c (rsa_decrypt_for_test): Tweak
valgrind marking, and document potential leakage of lowest and
highest bits of p and q.
---
 ChangeLog                        |  4 ++++
 testsuite/rsa-sec-decrypt-test.c | 14 +++++++++++---
 2 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 3f51fa45..705dfd95 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,5 +1,9 @@
 2018-11-25  Niels Möller  <nisse@lysator.liu.se>
 
+	* testsuite/rsa-sec-decrypt-test.c (rsa_decrypt_for_test): Tweak
+	valgrind marking, and document potential leakage of lowest and
+	highest bits of p and q.
+
 	* rsa-sec-compute-root.c (_rsa_sec_compute_root): Avoid calls to
 	mpz_sizeinbase, since that potentially leaks most significant bits
 	of private key parameters a and b.
diff --git a/testsuite/rsa-sec-decrypt-test.c b/testsuite/rsa-sec-decrypt-test.c
index ea5494d4..64f0b13c 100644
--- a/testsuite/rsa-sec-decrypt-test.c
+++ b/testsuite/rsa-sec-decrypt-test.c
@@ -21,18 +21,26 @@ rsa_decrypt_for_test(const struct rsa_public_key *pub,
 {
   int ret;
   /* Makes valgrind trigger on any branches depending on the input
-     data. */
+     data. Except that (i) we have to allow rsa_sec_compute_root_tr to
+     check that p and q are odd, (ii) mpn_sec_div_r may leak
+     information about the most significant bits of p and q, due to
+     normalization check and table lookup in invert_limb, and (iii)
+     mpn_sec_powm may leak information about the least significant
+     bits of p and q, due to table lookup in binvert_limb. */
   VALGRIND_MAKE_MEM_UNDEFINED (message, length);
   MARK_MPZ_LIMBS_UNDEFINED(gibberish);
   MARK_MPZ_LIMBS_UNDEFINED(key->a);
   MARK_MPZ_LIMBS_UNDEFINED(key->b);
   MARK_MPZ_LIMBS_UNDEFINED(key->c);
-  MARK_MPZ_LIMBS_UNDEFINED(key->p);
-  MARK_MPZ_LIMBS_UNDEFINED(key->q);
+  VALGRIND_MAKE_MEM_UNDEFINED(mpz_limbs_read (key->p) + 1,
+			      (mpz_size (key->p) - 3) * sizeof(mp_limb_t));
+  VALGRIND_MAKE_MEM_UNDEFINED(mpz_limbs_read (key->q) + 1,
+			      (mpz_size (key->q) - 3) * sizeof(mp_limb_t));
 
   ret = rsa_sec_decrypt (pub, key, random_ctx, random, length, message, gibberish);
 
   VALGRIND_MAKE_MEM_DEFINED (message, length);
+  VALGRIND_MAKE_MEM_DEFINED (&ret, sizeof(ret));
   MARK_MPZ_LIMBS_DEFINED(gibberish);
   MARK_MPZ_LIMBS_DEFINED(key->a);
   MARK_MPZ_LIMBS_DEFINED(key->b);
-- 
GitLab