summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLinus Walleij <linus.walleij@stericsson.com>2010-02-23 23:33:44 +0100
committerSamuel Lidén Borell <samuel@slbdata.se>2010-02-24 00:19:30 +0100
commit28b028d29fb75a1265ff472373936e2c558e6b51 (patch)
treeb17e43ff186a85a78c88e5e988fb02242b864510
parent34e19607424673d7fbf36380dd5e77eb8f994046 (diff)
downloadfribid-28b028d29fb75a1265ff472373936e2c558e6b51.tar.gz
fribid-28b028d29fb75a1265ff472373936e2c558e6b51.tar.bz2
fribid-28b028d29fb75a1265ff472373936e2c558e6b51.zip
Use /dev/urandom if available for random string
David Wheeler writes that you should use the available services for random numbers when generating random numbers, so let's attempt to use /dev/urandom before we try libc:s intrinsic rand(). Signed-off-by: Linus Walleij <linus.ml.walleij@gmail.com>
-rw-r--r--client/posix.c24
1 files changed, 23 insertions, 1 deletions
diff --git a/client/posix.c b/client/posix.c
index 160a2e0..3b4d3c8 100644
--- a/client/posix.c
+++ b/client/posix.c
@@ -44,6 +44,7 @@
#include "../common/defines.h"
#include "platform.h"
+#include "misc.h"
void platform_seedRandom() {
struct timeval tv;
@@ -133,9 +134,30 @@ PlatformDirIter *platform_openKeysDir() {
}
void platform_makeRandomString(char *buff, int length) {
+ // This array are characters for [0..63] i.e. a 6bit number
static const char randChars[] =
"0123456789_-ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
-
+
+ // Attempt to use the /dev/urandom device first, as
+ // adviced by Wheeler. We cannot use /dev/random because
+ // we don't want the GUI to freeze
+ // http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/
+ // random-numbers.html
+ FILE *file = fopen("/dev/urandom", "rb");
+ if (file) {
+ // Read directly into the buffer and modify
+ // since this may be a piece of secure memory
+ if ((int) fread(buff, 1, length, file) == length) {
+ for (int i = 0; i < length; i++)
+ buff[i] = randChars[buff[i] & 0x3f];
+ return;
+ }
+ // No, didn't work, fall through but cleanup first
+ guaranteed_memset(buff, 0, length);
+ }
+
+ // Else we fall back to the libc intrinsic rand() function
+ // so we *always* return something random
for (int i = 0; i < length; i++) {
int randVal = rand();
buff[i] = randChars[(i ^ randVal ^ (randVal >> 6) ^