[dovecot-cvs] dovecot/src/lib randgen.c,1.13,1.14

cras at dovecot.org cras at dovecot.org
Sat Mar 25 11:25:12 EET 2006


Update of /var/lib/cvs/dovecot/src/lib
In directory talvi:/tmp/cvs-serv3039/src/lib

Modified Files:
	randgen.c 
Log Message:
If /dev/urandom didn't exist and we used OpenSSL's random number generator,
it wasn't seeded properly at startup. Patch by Vilmos Nebehaj.



Index: randgen.c
===================================================================
RCS file: /var/lib/cvs/dovecot/src/lib/randgen.c,v
retrieving revision 1.13
retrieving revision 1.14
diff -u -d -r1.13 -r1.14
--- randgen.c	6 Jan 2005 19:08:19 -0000	1.13
+++ randgen.c	25 Mar 2006 09:25:09 -0000	1.14
@@ -65,6 +65,11 @@
 #include <openssl/rand.h>
 #include <openssl/err.h>
 
+#include <sys/time.h>
+#ifdef HAVE_SYS_RESOURCE_H
+#  include <sys/resource.h>
+#endif
+
 static const char *ssl_last_error(void)
 {
 	unsigned long err;
@@ -81,6 +86,37 @@
 	return buf;
 }
 
+static void random_init_rng(void)
+{
+	unsigned int counter = 0;
+	struct timeval tv;
+#ifdef HAVE_GETRUSAGE
+	struct rusage ru;
+#endif
+
+	/* If the RNG is already seeded, we can return immediately. */
+	if (RAND_status() == 1)
+		return;
+
+	/* Else, try to seed it. Unfortunately we don't have
+	   /dev/urandom, so we can only use weak random sources. */
+	while (RAND_status() != 1) {
+		if (gettimeofday(&tv, NULL) < 0)
+			i_fatal("gettimeofday() failed: %m");
+		RAND_add(&tv, sizeof(tv), sizeof(tv) / 2);
+#ifdef HAVE_GETRUSAGE
+		if (getrusage(RUSAGE_SELF, &ru) < 0)
+			i_fatal("getrusage() failed: %m");
+		RAND_add(&ru, sizeof(ru), sizeof(ru) / 2);
+#endif
+
+		if (counter++ > 100) {
+			i_fatal("Random generator initialization failed: "
+				"Couldn't get enough entropy");
+		}
+	}
+}
+
 void random_fill(void *buf, size_t size)
 {
 	if (RAND_bytes(buf, size) != 1)
@@ -91,6 +127,8 @@
 {
 	unsigned int seed;
 
+	random_init_rng();
+
 	random_fill(&seed, sizeof(seed));
 	srand(seed);
 }



More information about the dovecot-cvs mailing list