Skip to content

Commit b75b107

Browse files
committed
plugins: urandom: improve entropy gathering in fallback path
Enhance fallback entropy generation by mixing in multiple sources: runtime statistics, PID, and high-resolution timestamps. This provides better initialization for the PRNG when neither saved entropy nor hardware RNG are available during early boot. Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
1 parent 1f2c1d2 commit b75b107

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

plugins/urandom.c

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
#include <sys/stat.h>
2727
#include <sys/time.h> /* gettimeofday() */
2828
#include <sys/types.h>
29+
#include <sys/resource.h> /* getrusage() */
2930
#ifdef _LIBITE_LITE
3031
# include <libite/lite.h>
3132
#else
@@ -43,13 +44,27 @@
4344
#endif
4445

4546
#ifdef RANDOMSEED
47+
/*
48+
* This is the fallback seed function, please make sure you have drivers
49+
* enabling /dev/hwrng instead.
50+
*/
4651
static void fallback(FILE *fp)
4752
{
53+
unsigned long seed;
4854
struct timeval tv;
55+
struct rusage ru;
4956
int iter = 128;
5057

5158
gettimeofday(&tv, NULL);
52-
srandom(tv.tv_sec % 3600);
59+
getrusage(RUSAGE_SELF, &ru);
60+
61+
/* Mix multiple sources of "randomness" */
62+
seed = tv.tv_sec ^ (tv.tv_usec << 16);
63+
seed ^= ru.ru_utime.tv_sec ^ (ru.ru_utime.tv_usec << 16);
64+
seed ^= ru.ru_stime.tv_sec ^ (ru.ru_stime.tv_usec << 16);
65+
seed ^= getpid() << 8;
66+
67+
srandom(seed);
5368
while (iter--) {
5469
uint32_t i, prng = random();
5570

0 commit comments

Comments
 (0)