Skip to content

Commit

Permalink
system: use getrandom() and fallback on urandom if syscall doesn't work
Browse files Browse the repository at this point in the history
  • Loading branch information
illwieckz committed Apr 26, 2023
1 parent c659393 commit 2b55034
Showing 1 changed file with 12 additions and 16 deletions.
28 changes: 12 additions & 16 deletions src/common/System.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <fcntl.h>
#include <signal.h>
#ifdef __linux__
#include <linux/version.h>
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3,17,0)
#include <sys/syscall.h>
#include <linux/random.h>
#define HAS_GETRANDOM_SYSCALL 1
#endif
#include <sys/random.h>
#endif
#ifdef __native_client__
#include <nacl/nacl_exception.h>
Expand Down Expand Up @@ -410,19 +405,20 @@ void GenRandomBytes(void* dest, size_t size)
size_t bytes_written;
if (nacl_secure_random(dest, size, &bytes_written) != 0 || bytes_written != size)
Sys::Error("nacl_secure_random failed");
#elif defined(__linux__) && defined(HAS_GETRANDOM_SYSCALL)
if (syscall(SYS_getrandom, dest, size, GRND_NONBLOCK) == -1)
Sys::Error("Failed getrandom syscall: %s", strerror(errno));
#elif defined(__linux__)
int fd = open("/dev/urandom", O_RDONLY);
if (fd == -1)
Sys::Error("Failed to open /dev/urandom: %s", strerror(errno));
if (read(fd, dest, size) != (ssize_t) size)
Sys::Error("Failed to read from /dev/urandom: %s", strerror(errno));
close(fd);
if (getrandom(dest, size, GRND_NONBLOCK) == -1)
{
Log::Warn("Failed getrandom syscall: %s", strerror(errno));

int fd = open("/dev/urandom", O_RDONLY);
if (fd == -1)
Sys::Error("Failed to open /dev/urandom: %s", strerror(errno));
if (read(fd, dest, size) != (ssize_t) size)
Sys::Error("Failed to read from /dev/urandom: %s", strerror(errno));
close(fd);
}
#else
arc4random_buf(dest, size);

#endif
}

Expand Down

0 comments on commit 2b55034

Please sign in to comment.