diff options
author | Victor Stinner <victor.stinner@gmail.com> | 2014-12-21 00:16:38 (GMT) |
---|---|---|
committer | Victor Stinner <victor.stinner@gmail.com> | 2014-12-21 00:16:38 (GMT) |
commit | 4d6a3d6c01abc468ec85395c58f1a36f6f16560e (patch) | |
tree | 354169073a71ea73989bad9a7950bf4d3794333d /Python/random.c | |
parent | 3c6fe4da88869b03d810e870db3997b787ffff3e (diff) | |
download | cpython-4d6a3d6c01abc468ec85395c58f1a36f6f16560e.zip cpython-4d6a3d6c01abc468ec85395c58f1a36f6f16560e.tar.gz cpython-4d6a3d6c01abc468ec85395c58f1a36f6f16560e.tar.bz2 |
Issue #22585: On OpenBSD 5.6 and newer, os.urandom() now calls getentropy(),
instead of reading /dev/urandom, to get pseudo-random bytes.
Diffstat (limited to 'Python/random.c')
-rw-r--r-- | Python/random.c | 39 |
1 files changed, 35 insertions, 4 deletions
diff --git a/Python/random.c b/Python/random.c index 654612b..93d300d 100644 --- a/Python/random.c +++ b/Python/random.c @@ -36,7 +36,7 @@ error: } /* Fill buffer with size pseudo-random bytes generated by the Windows CryptoGen - API. Return 0 on success, or -1 on error. */ + API. Return 0 on success, or raise an exception and return -1 on error. */ static int win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise) { @@ -66,10 +66,35 @@ win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise) } return 0; } -#endif /* MS_WINDOWS */ +#elif HAVE_GETENTROPY +/* Fill buffer with size pseudo-random bytes generated by getentropy(). + Return 0 on success, or raise an exception and return -1 on error. -#ifndef MS_WINDOWS + If fatal is nonzero, call Py_FatalError() instead of raising an exception + on error. */ +static int +py_getentropy(unsigned char *buffer, Py_ssize_t size, int fatal) +{ + while (size > 0) { + Py_ssize_t len = Py_MIN(size, 256); + int res = getentropy(buffer, len); + if (res < 0) { + if (fatal) { + Py_FatalError("getentropy() failed"); + } + else { + PyErr_SetFromErrno(PyExc_OSError); + return -1; + } + } + buffer += len; + size -= len; + } + return 0; +} + +#else static struct { int fd; dev_t st_dev; @@ -201,7 +226,7 @@ dev_urandom_close(void) } } -#endif /* MS_WINDOWS */ +#endif /* HAVE_GETENTROPY */ /* Fill buffer with pseudo-random bytes generated by a linear congruent generator (LCG): @@ -242,6 +267,8 @@ _PyOS_URandom(void *buffer, Py_ssize_t size) #ifdef MS_WINDOWS return win32_urandom((unsigned char *)buffer, size, 1); +#elif HAVE_GETENTROPY + return py_getentropy(buffer, size, 0); #else return dev_urandom_python((char*)buffer, size); #endif @@ -287,6 +314,8 @@ _PyRandom_Init(void) else { #ifdef MS_WINDOWS (void)win32_urandom(secret, secret_size, 0); +#elif HAVE_GETENTROPY + (void)py_getentropy(secret, secret_size, 1); #else dev_urandom_noraise(secret, secret_size); #endif @@ -301,6 +330,8 @@ _PyRandom_Fini(void) CryptReleaseContext(hCryptProv, 0); hCryptProv = 0; } +#elif HAVE_GETENTROPY + /* nothing to clean */ #else dev_urandom_close(); #endif |