#include "Python.h"1#include "pycore_initconfig.h"2#include "pycore_fileutils.h" // _Py_fstat_noraise()3#include "pycore_runtime.h" // _PyRuntime45#ifdef MS_WINDOWS6# include <windows.h>7# include <bcrypt.h>8#else9# include <fcntl.h>10# ifdef HAVE_SYS_STAT_H11# include <sys/stat.h>12# endif13# ifdef HAVE_LINUX_RANDOM_H14# include <linux/random.h>15# endif16# if defined(HAVE_SYS_RANDOM_H) && (defined(HAVE_GETRANDOM) || defined(HAVE_GETENTROPY))17# include <sys/random.h>18# endif19# if !defined(HAVE_GETRANDOM) && defined(HAVE_GETRANDOM_SYSCALL)20# include <sys/syscall.h>21# endif22#endif2324#ifdef _Py_MEMORY_SANITIZER25# include <sanitizer/msan_interface.h>26#endif2728#if defined(__APPLE__) && defined(__has_builtin)29# if __has_builtin(__builtin_available)30# define HAVE_GETENTRYPY_GETRANDOM_RUNTIME __builtin_available(macOS 10.12, iOS 10.10, tvOS 10.0, watchOS 3.0, *)31# endif32#endif33#ifndef HAVE_GETENTRYPY_GETRANDOM_RUNTIME34# define HAVE_GETENTRYPY_GETRANDOM_RUNTIME 135#endif363738#ifdef Py_DEBUG39int _Py_HashSecret_Initialized = 0;40#else41static int _Py_HashSecret_Initialized = 0;42#endif4344#ifdef MS_WINDOWS4546/* Fill buffer with size pseudo-random bytes generated by the Windows CryptoGen47API. Return 0 on success, or raise an exception and return -1 on error. */48static int49win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise)50{51while (size > 0)52{53DWORD chunk = (DWORD)Py_MIN(size, PY_DWORD_MAX);54NTSTATUS status = BCryptGenRandom(NULL, buffer, chunk, BCRYPT_USE_SYSTEM_PREFERRED_RNG);55if (!BCRYPT_SUCCESS(status)) {56/* BCryptGenRandom() failed */57if (raise) {58PyErr_SetFromWindowsErr(0);59}60return -1;61}62buffer += chunk;63size -= chunk;64}65return 0;66}6768#else /* !MS_WINDOWS */6970#if defined(HAVE_GETRANDOM) || defined(HAVE_GETRANDOM_SYSCALL)71#define PY_GETRANDOM 17273/* Call getrandom() to get random bytes:7475- Return 1 on success76- Return 0 if getrandom() is not available (failed with ENOSYS or EPERM),77or if getrandom(GRND_NONBLOCK) failed with EAGAIN (system urandom not78initialized yet) and raise=0.79- Raise an exception (if raise is non-zero) and return -1 on error:80if getrandom() failed with EINTR, raise is non-zero and the Python signal81handler raised an exception, or if getrandom() failed with a different82error.8384getrandom() is retried if it failed with EINTR: interrupted by a signal. */85static int86py_getrandom(void *buffer, Py_ssize_t size, int blocking, int raise)87{88/* Is getrandom() supported by the running kernel? Set to 0 if getrandom()89failed with ENOSYS or EPERM. Need Linux kernel 3.17 or newer, or Solaris9011.3 or newer */91static int getrandom_works = 1;92int flags;93char *dest;94long n;9596if (!getrandom_works) {97return 0;98}99100flags = blocking ? 0 : GRND_NONBLOCK;101dest = buffer;102while (0 < size) {103#if defined(__sun) && defined(__SVR4)104/* Issue #26735: On Solaris, getrandom() is limited to returning up105to 1024 bytes. Call it multiple times if more bytes are106requested. */107n = Py_MIN(size, 1024);108#else109n = Py_MIN(size, LONG_MAX);110#endif111112errno = 0;113#ifdef HAVE_GETRANDOM114if (raise) {115Py_BEGIN_ALLOW_THREADS116n = getrandom(dest, n, flags);117Py_END_ALLOW_THREADS118}119else {120n = getrandom(dest, n, flags);121}122#else123/* On Linux, use the syscall() function because the GNU libc doesn't124expose the Linux getrandom() syscall yet. See:125https://sourceware.org/bugzilla/show_bug.cgi?id=17252 */126if (raise) {127Py_BEGIN_ALLOW_THREADS128n = syscall(SYS_getrandom, dest, n, flags);129Py_END_ALLOW_THREADS130}131else {132n = syscall(SYS_getrandom, dest, n, flags);133}134# ifdef _Py_MEMORY_SANITIZER135if (n > 0) {136__msan_unpoison(dest, n);137}138# endif139#endif140141if (n < 0) {142/* ENOSYS: the syscall is not supported by the kernel.143EPERM: the syscall is blocked by a security policy (ex: SECCOMP)144or something else. */145if (errno == ENOSYS || errno == EPERM) {146getrandom_works = 0;147return 0;148}149150/* getrandom(GRND_NONBLOCK) fails with EAGAIN if the system urandom151is not initialized yet. For _PyRandom_Init(), we ignore the152error and fall back on reading /dev/urandom which never blocks,153even if the system urandom is not initialized yet:154see the PEP 524. */155if (errno == EAGAIN && !raise && !blocking) {156return 0;157}158159if (errno == EINTR) {160if (raise) {161if (PyErr_CheckSignals()) {162return -1;163}164}165166/* retry getrandom() if it was interrupted by a signal */167continue;168}169170if (raise) {171PyErr_SetFromErrno(PyExc_OSError);172}173return -1;174}175176dest += n;177size -= n;178}179return 1;180}181182#elif defined(HAVE_GETENTROPY)183#define PY_GETENTROPY 1184185/* Fill buffer with size pseudo-random bytes generated by getentropy():186187- Return 1 on success188- Return 0 if getentropy() syscall is not available (failed with ENOSYS or189EPERM).190- Raise an exception (if raise is non-zero) and return -1 on error:191if getentropy() failed with EINTR, raise is non-zero and the Python signal192handler raised an exception, or if getentropy() failed with a different193error.194195getentropy() is retried if it failed with EINTR: interrupted by a signal. */196197#if defined(__APPLE__) && defined(__has_attribute) && __has_attribute(availability)198static int199py_getentropy(char *buffer, Py_ssize_t size, int raise)200__attribute__((availability(macos,introduced=10.12)))201__attribute__((availability(ios,introduced=10.0)))202__attribute__((availability(tvos,introduced=10.0)))203__attribute__((availability(watchos,introduced=3.0)));204#endif205206static int207py_getentropy(char *buffer, Py_ssize_t size, int raise)208{209/* Is getentropy() supported by the running kernel? Set to 0 if210getentropy() failed with ENOSYS or EPERM. */211static int getentropy_works = 1;212213if (!getentropy_works) {214return 0;215}216217while (size > 0) {218/* getentropy() is limited to returning up to 256 bytes. Call it219multiple times if more bytes are requested. */220Py_ssize_t len = Py_MIN(size, 256);221int res;222223if (raise) {224Py_BEGIN_ALLOW_THREADS225res = getentropy(buffer, len);226Py_END_ALLOW_THREADS227}228else {229res = getentropy(buffer, len);230}231232if (res < 0) {233/* ENOSYS: the syscall is not supported by the running kernel.234EPERM: the syscall is blocked by a security policy (ex: SECCOMP)235or something else. */236if (errno == ENOSYS || errno == EPERM) {237getentropy_works = 0;238return 0;239}240241if (errno == EINTR) {242if (raise) {243if (PyErr_CheckSignals()) {244return -1;245}246}247248/* retry getentropy() if it was interrupted by a signal */249continue;250}251252if (raise) {253PyErr_SetFromErrno(PyExc_OSError);254}255return -1;256}257258buffer += len;259size -= len;260}261return 1;262}263#endif /* defined(HAVE_GETENTROPY) && !(defined(__sun) && defined(__SVR4)) */264265266#define urandom_cache (_PyRuntime.pyhash_state.urandom_cache)267268/* Read random bytes from the /dev/urandom device:269270- Return 0 on success271- Raise an exception (if raise is non-zero) and return -1 on error272273Possible causes of errors:274275- open() failed with ENOENT, ENXIO, ENODEV, EACCES: the /dev/urandom device276was not found. For example, it was removed manually or not exposed in a277chroot or container.278- open() failed with a different error279- fstat() failed280- read() failed or returned 0281282read() is retried if it failed with EINTR: interrupted by a signal.283284The file descriptor of the device is kept open between calls to avoid using285many file descriptors when run in parallel from multiple threads:286see the issue #18756.287288st_dev and st_ino fields of the file descriptor (from fstat()) are cached to289check if the file descriptor was replaced by a different file (which is290likely a bug in the application): see the issue #21207.291292If the file descriptor was closed or replaced, open a new file descriptor293but don't close the old file descriptor: it probably points to something294important for some third-party code. */295static int296dev_urandom(char *buffer, Py_ssize_t size, int raise)297{298int fd;299Py_ssize_t n;300301if (raise) {302struct _Py_stat_struct st;303int fstat_result;304305if (urandom_cache.fd >= 0) {306Py_BEGIN_ALLOW_THREADS307fstat_result = _Py_fstat_noraise(urandom_cache.fd, &st);308Py_END_ALLOW_THREADS309310/* Does the fd point to the same thing as before? (issue #21207) */311if (fstat_result312|| st.st_dev != urandom_cache.st_dev313|| st.st_ino != urandom_cache.st_ino) {314/* Something changed: forget the cached fd (but don't close it,315since it probably points to something important for some316third-party code). */317urandom_cache.fd = -1;318}319}320if (urandom_cache.fd >= 0)321fd = urandom_cache.fd;322else {323fd = _Py_open("/dev/urandom", O_RDONLY);324if (fd < 0) {325if (errno == ENOENT || errno == ENXIO ||326errno == ENODEV || errno == EACCES) {327PyErr_SetString(PyExc_NotImplementedError,328"/dev/urandom (or equivalent) not found");329}330/* otherwise, keep the OSError exception raised by _Py_open() */331return -1;332}333if (urandom_cache.fd >= 0) {334/* urandom_fd was initialized by another thread while we were335not holding the GIL, keep it. */336close(fd);337fd = urandom_cache.fd;338}339else {340if (_Py_fstat(fd, &st)) {341close(fd);342return -1;343}344else {345urandom_cache.fd = fd;346urandom_cache.st_dev = st.st_dev;347urandom_cache.st_ino = st.st_ino;348}349}350}351352do {353n = _Py_read(fd, buffer, (size_t)size);354if (n == -1)355return -1;356if (n == 0) {357PyErr_Format(PyExc_RuntimeError,358"Failed to read %zi bytes from /dev/urandom",359size);360return -1;361}362363buffer += n;364size -= n;365} while (0 < size);366}367else {368fd = _Py_open_noraise("/dev/urandom", O_RDONLY);369if (fd < 0) {370return -1;371}372373while (0 < size)374{375do {376n = read(fd, buffer, (size_t)size);377} while (n < 0 && errno == EINTR);378379if (n <= 0) {380/* stop on error or if read(size) returned 0 */381close(fd);382return -1;383}384385buffer += n;386size -= n;387}388close(fd);389}390return 0;391}392393static void394dev_urandom_close(void)395{396if (urandom_cache.fd >= 0) {397close(urandom_cache.fd);398urandom_cache.fd = -1;399}400}401402#undef urandom_cache403404#endif /* !MS_WINDOWS */405406407/* Fill buffer with pseudo-random bytes generated by a linear congruent408generator (LCG):409410x(n+1) = (x(n) * 214013 + 2531011) % 2^32411412Use bits 23..16 of x(n) to generate a byte. */413static void414lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)415{416size_t index;417unsigned int x;418419x = x0;420for (index=0; index < size; index++) {421x *= 214013;422x += 2531011;423/* modulo 2 ^ (8 * sizeof(int)) */424buffer[index] = (x >> 16) & 0xff;425}426}427428/* Read random bytes:429430- Return 0 on success431- Raise an exception (if raise is non-zero) and return -1 on error432433Used sources of entropy ordered by preference, preferred source first:434435- BCryptGenRandom() on Windows436- getrandom() function (ex: Linux and Solaris): call py_getrandom()437- getentropy() function (ex: OpenBSD): call py_getentropy()438- /dev/urandom device439440Read from the /dev/urandom device if getrandom() or getentropy() function441is not available or does not work.442443Prefer getrandom() over getentropy() because getrandom() supports blocking444and non-blocking mode: see the PEP 524. Python requires non-blocking RNG at445startup to initialize its hash secret, but os.urandom() must block until the446system urandom is initialized (at least on Linux 3.17 and newer).447448Prefer getrandom() and getentropy() over reading directly /dev/urandom449because these functions don't need file descriptors and so avoid ENFILE or450EMFILE errors (too many open files): see the issue #18756.451452Only the getrandom() function supports non-blocking mode.453454Only use RNG running in the kernel. They are more secure because it is455harder to get the internal state of a RNG running in the kernel land than a456RNG running in the user land. The kernel has a direct access to the hardware457and has access to hardware RNG, they are used as entropy sources.458459Note: the OpenSSL RAND_pseudo_bytes() function does not automatically reseed460its RNG on fork(), two child processes (with the same pid) generate the same461random numbers: see issue #18747. Kernel RNGs don't have this issue,462they have access to good quality entropy sources.463464If raise is zero:465466- Don't raise an exception on error467- Don't call the Python signal handler (don't call PyErr_CheckSignals()) if468a function fails with EINTR: retry directly the interrupted function469- Don't release the GIL to call functions.470*/471static int472pyurandom(void *buffer, Py_ssize_t size, int blocking, int raise)473{474#if defined(PY_GETRANDOM) || defined(PY_GETENTROPY)475int res;476#endif477478if (size < 0) {479if (raise) {480PyErr_Format(PyExc_ValueError,481"negative argument not allowed");482}483return -1;484}485486if (size == 0) {487return 0;488}489490#ifdef MS_WINDOWS491return win32_urandom((unsigned char *)buffer, size, raise);492#else493494#if defined(PY_GETRANDOM) || defined(PY_GETENTROPY)495if (HAVE_GETENTRYPY_GETRANDOM_RUNTIME) {496#ifdef PY_GETRANDOM497res = py_getrandom(buffer, size, blocking, raise);498#else499res = py_getentropy(buffer, size, raise);500#endif501if (res < 0) {502return -1;503}504if (res == 1) {505return 0;506}507/* getrandom() or getentropy() function is not available: failed with508ENOSYS or EPERM. Fall back on reading from /dev/urandom. */509} /* end of availability block */510#endif511512return dev_urandom(buffer, size, raise);513#endif514}515516/* Fill buffer with size pseudo-random bytes from the operating system random517number generator (RNG). It is suitable for most cryptographic purposes518except long living private keys for asymmetric encryption.519520On Linux 3.17 and newer, the getrandom() syscall is used in blocking mode:521block until the system urandom entropy pool is initialized (128 bits are522collected by the kernel).523524Return 0 on success. Raise an exception and return -1 on error. */525int526_PyOS_URandom(void *buffer, Py_ssize_t size)527{528return pyurandom(buffer, size, 1, 1);529}530531/* Fill buffer with size pseudo-random bytes from the operating system random532number generator (RNG). It is not suitable for cryptographic purpose.533534On Linux 3.17 and newer (when getrandom() syscall is used), if the system535urandom is not initialized yet, the function returns "weak" entropy read536from /dev/urandom.537538Return 0 on success. Raise an exception and return -1 on error. */539int540_PyOS_URandomNonblock(void *buffer, Py_ssize_t size)541{542return pyurandom(buffer, size, 0, 1);543}544545546PyStatus547_Py_HashRandomization_Init(const PyConfig *config)548{549void *secret = &_Py_HashSecret;550Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);551552if (_Py_HashSecret_Initialized) {553return _PyStatus_OK();554}555_Py_HashSecret_Initialized = 1;556557if (config->use_hash_seed) {558if (config->hash_seed == 0) {559/* disable the randomized hash */560memset(secret, 0, secret_size);561}562else {563/* use the specified hash seed */564lcg_urandom(config->hash_seed, secret, secret_size);565}566}567else {568/* use a random hash seed */569int res;570571/* _PyRandom_Init() is called very early in the Python initialization572and so exceptions cannot be used (use raise=0).573574_PyRandom_Init() must not block Python initialization: call575pyurandom() is non-blocking mode (blocking=0): see the PEP 524. */576res = pyurandom(secret, secret_size, 0, 0);577if (res < 0) {578return _PyStatus_ERR("failed to get random numbers "579"to initialize Python");580}581}582return _PyStatus_OK();583}584585586void587_Py_HashRandomization_Fini(void)588{589#ifndef MS_WINDOWS590dev_urandom_close();591#endif592}593594595