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