From ec08e22ed78cd1989b8a90bf1454c752eceec94f Mon Sep 17 00:00:00 2001 From: psychon Date: Sun, 7 Mar 2010 14:55:20 +0000 Subject: [PATCH] Use a better seed for srand() Instead of just time() (which can be easily guessed by an attacker when he gets a couple of samples of rand() results), this now also uses the current microseconds, znc's pid and the old PRNG state for computing a seed. git-svn-id: https://znc.svn.sourceforge.net/svnroot/znc/trunk@1813 726aef4b-f618-498e-8847-2d620e286838 --- main.cpp | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/main.cpp b/main.cpp index 8055e997..56554cd7 100644 --- a/main.cpp +++ b/main.cpp @@ -75,11 +75,32 @@ static bool isRoot() { return false; } +static void seedPRNG() { + struct timeval tv; + unsigned int seed; + + // Try to find a seed which can't be as easily guessed as only time() + + if (gettimeofday(&tv, NULL) == 0) { + seed = tv.tv_sec; + + // This is in [0:1e6], which means that roughly 20 bits are + // actually used, let's try to shuffle the high bits. + seed ^= (tv.tv_usec << 10) | tv.tv_usec; + } else + seed = time(NULL); + + seed ^= rand(); + seed ^= getpid(); + + srand(seed); +} + int main(int argc, char** argv) { CString sConfig; CString sDataDir = ""; - srand(time(NULL)); + seedPRNG(); CUtils::SetStdoutIsTTY(isatty(1)); int iArg, iOptIndex = -1;