OSDN Git Service

hwrng: core - credit entropy for low quality sources of randomness
authorDominik Brodowski <linux@dominikbrodowski.net>
Fri, 28 Jan 2022 07:02:54 +0000 (08:02 +0100)
committerHerbert Xu <herbert@gondor.apana.org.au>
Sat, 5 Feb 2022 04:10:51 +0000 (15:10 +1100)
In case the entropy quality is low, there may be less than one bit to
credit in the call to add_hwgenerator_randomness(): The number of bytes
returned by rng_get_data() multiplied by the current quality (in entropy
bits per 1024 bits of input) must be larger than 128 to credit at least
one bit. However, imx-rngc.c sets the quality to 19, but may return less
than 32 bytes; hid_u2fzero.c sets the quality to 1; and users may override
the quality setting manually.

In case there is less than one bit to credit, keep track of it and add
that credit to the next iteration.

Cc: Herbert Xu <herbert@gondor.apana.org.au>
Cc: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Dominik Brodowski <linux@dominikbrodowski.net>
Signed-off-by: Herbert Xu <herbert@gondor.apana.org.au>
drivers/char/hw_random/core.c

index bc9f95c..f327f74 100644 (file)
@@ -424,6 +424,7 @@ static int __init register_miscdev(void)
 
 static int hwrng_fillfn(void *unused)
 {
+       size_t entropy, entropy_credit = 0; /* in 1/1024 of a bit */
        long rc;
 
        while (!kthread_should_stop()) {
@@ -445,9 +446,17 @@ static int hwrng_fillfn(void *unused)
                        msleep_interruptible(10000);
                        continue;
                }
+
+               /* If we cannot credit at least one bit of entropy,
+                * keep track of the remainder for the next iteration
+                */
+               entropy = rc * current_quality * 8 + entropy_credit;
+               if ((entropy >> 10) == 0)
+                       entropy_credit = entropy;
+
                /* Outside lock, sure, but y'know: randomness. */
                add_hwgenerator_randomness((void *)rng_fillbuf, rc,
-                                          rc * current_quality * 8 >> 10);
+                                          entropy >> 10);
        }
        hwrng_fill = NULL;
        return 0;