Skip to content

Commit

Permalink
rand(3): Fix up sranddev(3) a bit better.
Browse files Browse the repository at this point in the history
In case we can't read /dev/random for the seed, try kern.random. If that
fails, use the getpid()/gettimeofday() xor. For the latter, remove the
usage of an uninitialized variable.

We should probably just abort() when kern.random can't be read.

Discussed-with: dillon
  • Loading branch information
Sascha Wildner committed Feb 25, 2014
1 parent 72e717d commit 7918d77
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/libc/stdlib/rand.c
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
#include "namespace.h"
#include <sys/time.h> /* for sranddev() */
#include <sys/types.h>
#include <sys/sysctl.h>
#include <fcntl.h> /* for sranddev() */
#include <stdlib.h>
#include <unistd.h> /* for sranddev() */
Expand Down Expand Up @@ -115,12 +116,18 @@ sranddev(void)
_close(fd);
}

if (!done) {
size_t len = sizeof(next);

if (sysctlbyname("kern.random", &next, &len, NULL, 0) == 0)
done = 1;
}

if (!done) {
struct timeval tv;
unsigned long junk; /* XXX left uninitialized on purpose */

gettimeofday(&tv, NULL);
srand((getpid() << 16) ^ tv.tv_sec ^ tv.tv_usec ^ junk);
srand((getpid() << 16) ^ tv.tv_sec ^ tv.tv_usec);
}
}

Expand Down

0 comments on commit 7918d77

Please sign in to comment.