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 331e85c commit e667691
Showing 1 changed file with 24 additions and 16 deletions.
40 changes: 24 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 @@ -462,19 +457,32 @@ 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);
ssize_t ret = getrandom(dest, size, GRND_NONBLOCK);
if (ret == -1)
{
if (errno == ENOSYS)
{
Log::Warn("getrandom syscall is not supported");

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
{
Sys::Error("getrandom syscall failed: %s", strerror(errno));
}
}
else if (ret != size)
{
Sys::Error("getrandom syscall returned insufficient data");
}
#else
arc4random_buf(dest, size);

#endif
}

Expand Down

0 comments on commit e667691

Please sign in to comment.