cb4ff2
commit f430293d842031f2afc3013f156e1018065e480e
cb4ff2
Author: Adhemerval Zanella <adhemerval.zanella@linaro.org>
cb4ff2
Date:   Tue Jan 12 09:17:09 2021 -0300
cb4ff2
cb4ff2
    posix: consume less entropy on tempname
cb4ff2
    
cb4ff2
    The first getrandom is used only for __GT_NOCREATE, which is inherently
cb4ff2
    insecure and can use the entropy as a small improvement.  On the
cb4ff2
    second and later attempts it might help against DoS attacks.
cb4ff2
    
cb4ff2
    It sync with gnulib commit 854fbb81d91f7a0f2b463e7ace2499dee2f380f2.
cb4ff2
    
cb4ff2
    Checked on x86_64-linux-gnu.
cb4ff2
cb4ff2
diff --git a/sysdeps/posix/tempname.c b/sysdeps/posix/tempname.c
cb4ff2
index fcab9b26364021e4..3435c4bf75a01f42 100644
cb4ff2
--- a/sysdeps/posix/tempname.c
cb4ff2
+++ b/sysdeps/posix/tempname.c
cb4ff2
@@ -22,6 +22,7 @@
cb4ff2
 
cb4ff2
 #include <sys/types.h>
cb4ff2
 #include <assert.h>
cb4ff2
+#include <stdbool.h>
cb4ff2
 
cb4ff2
 #include <errno.h>
cb4ff2
 
cb4ff2
@@ -79,11 +80,11 @@ typedef uint_fast64_t random_value;
cb4ff2
 #define BASE_62_POWER (62LL * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62 * 62)
cb4ff2
 
cb4ff2
 static random_value
cb4ff2
-random_bits (random_value var)
cb4ff2
+random_bits (random_value var, bool use_getrandom)
cb4ff2
 {
cb4ff2
   random_value r;
cb4ff2
   /* Without GRND_NONBLOCK it can be blocked for minutes on some systems.  */
cb4ff2
-  if (__getrandom (&r, sizeof r, GRND_NONBLOCK) == sizeof r)
cb4ff2
+  if (use_getrandom && __getrandom (&r, sizeof r, GRND_NONBLOCK) == sizeof r)
cb4ff2
     return r;
cb4ff2
 #if _LIBC || (defined CLOCK_MONOTONIC && HAVE_CLOCK_GETTIME)
cb4ff2
   /* Add entropy if getrandom did not work.  */
cb4ff2
@@ -271,6 +272,13 @@ try_tempname_len (char *tmpl, int suffixlen, void *args,
cb4ff2
   /* How many random base-62 digits can currently be extracted from V.  */
cb4ff2
   int vdigits = 0;
cb4ff2
 
cb4ff2
+  /* Whether to consume entropy when acquiring random bits.  On the
cb4ff2
+     first try it's worth the entropy cost with __GT_NOCREATE, which
cb4ff2
+     is inherently insecure and can use the entropy to make it a bit
cb4ff2
+     less secure.  On the (rare) second and later attempts it might
cb4ff2
+     help against DoS attacks.  */
cb4ff2
+  bool use_getrandom = tryfunc == try_nocreate;
cb4ff2
+
cb4ff2
   /* Least unfair value for V.  If V is less than this, V can generate
cb4ff2
      BASE_62_DIGITS digits fairly.  Otherwise it might be biased.  */
cb4ff2
   random_value const unfair_min
cb4ff2
@@ -294,7 +302,10 @@ try_tempname_len (char *tmpl, int suffixlen, void *args,
cb4ff2
           if (vdigits == 0)
cb4ff2
             {
cb4ff2
               do
cb4ff2
-                v = random_bits (v);
cb4ff2
+                {
cb4ff2
+                  v = random_bits (v, use_getrandom);
cb4ff2
+                  use_getrandom = true;
cb4ff2
+                }
cb4ff2
               while (unfair_min <= v);
cb4ff2
 
cb4ff2
               vdigits = BASE_62_DIGITS;