From b4e98c0253feb3eaa03861ac59c05624813e5f06 Mon Sep 17 00:00:00 2001 From: Frank Denis Date: Mon, 5 May 2014 14:39:12 -0700 Subject: [PATCH] Ensure that /dev/urandom is a char device. --- .../salsa20/randombytes_salsa20_random.c | 15 +++++++++++---- .../randombytes/sysrandom/randombytes_sysrandom.c | 15 +++++++++++---- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/libsodium/randombytes/salsa20/randombytes_salsa20_random.c b/src/libsodium/randombytes/salsa20/randombytes_salsa20_random.c index f8c05ad5..243c9c4b 100644 --- a/src/libsodium/randombytes/salsa20/randombytes_salsa20_random.c +++ b/src/libsodium/randombytes/salsa20/randombytes_salsa20_random.c @@ -1,6 +1,7 @@ #include #ifndef _WIN32 +# include # include #endif @@ -107,17 +108,23 @@ safe_read(const int fd, void * const buf_, size_t count) static int randombytes_salsa20_random_random_dev_open(void) { - static const char * const devices[] = { + struct stat st; + static const char *devices[] = { # ifndef USE_BLOCKING_RANDOM "/dev/urandom", # endif "/dev/random", NULL }; - const char * const *device = devices; + const char ** device = devices; + int fd; do { - if (access(*device, F_OK | R_OK) == 0) { - return open(*device, O_RDONLY); + if (access(*device, F_OK | R_OK) == 0 && + (fd = open(*device, O_RDONLY)) != -1) { + if (fstat(fd, &st) == 0 && S_ISCHR(st.st_mode)) { + return fd; + } + (void) close(fd); } device++; } while (*device != NULL); diff --git a/src/libsodium/randombytes/sysrandom/randombytes_sysrandom.c b/src/libsodium/randombytes/sysrandom/randombytes_sysrandom.c index 3bb521b9..a7c827e5 100644 --- a/src/libsodium/randombytes/sysrandom/randombytes_sysrandom.c +++ b/src/libsodium/randombytes/sysrandom/randombytes_sysrandom.c @@ -1,6 +1,7 @@ #include #ifndef _WIN32 +# include # include #endif @@ -99,17 +100,23 @@ safe_read(const int fd, void * const buf_, size_t count) static int randombytes_sysrandom_random_dev_open(void) { - static const char * const devices[] = { + struct stat st; + static const char *devices[] = { # ifndef USE_BLOCKING_RANDOM "/dev/urandom", # endif "/dev/random", NULL }; - const char * const *device = devices; + const char ** device = devices; + int fd; do { - if (access(*device, F_OK | R_OK) == 0) { - return open(*device, O_RDONLY); + if (access(*device, F_OK | R_OK) == 0 && + (fd = open(*device, O_RDONLY)) != -1) { + if (fstat(fd, &st) == 0 && S_ISCHR(st.st_mode)) { + return fd; + } + (void) close(fd); } device++; } while (*device != NULL);