You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

623 lines
18 KiB

bpo-36763: Implement the PEP 587 (GH-13592) * Add a whole new documentation page: "Python Initialization Configuration" * PyWideStringList_Append() return type is now PyStatus, instead of int * PyInterpreterState_New() now calls PyConfig_Clear() if PyConfig_InitPythonConfig() fails. * Rename files: * Python/coreconfig.c => Python/initconfig.c * Include/cpython/coreconfig.h => Include/cpython/initconfig.h * Include/internal/: pycore_coreconfig.h => pycore_initconfig.h * Rename structures * _PyCoreConfig => PyConfig * _PyPreConfig => PyPreConfig * _PyInitError => PyStatus * _PyWstrList => PyWideStringList * Rename PyConfig fields: * use_module_search_paths => module_search_paths_set * module_search_path_env => pythonpath_env * Rename PyStatus field: _func => func * PyInterpreterState: rename core_config field to config * Rename macros and functions: * _PyCoreConfig_SetArgv() => PyConfig_SetBytesArgv() * _PyCoreConfig_SetWideArgv() => PyConfig_SetArgv() * _PyCoreConfig_DecodeLocale() => PyConfig_SetBytesString() * _PyInitError_Failed() => PyStatus_Exception() * _Py_INIT_ERROR_TYPE_xxx enums => _PyStatus_TYPE_xxx * _Py_UnixMain() => Py_BytesMain() * _Py_ExitInitError() => Py_ExitStatusException() * _Py_PreInitializeFromArgs() => Py_PreInitializeFromBytesArgs() * _Py_PreInitializeFromWideArgs() => Py_PreInitializeFromArgs() * _Py_PreInitialize() => Py_PreInitialize() * _Py_RunMain() => Py_RunMain() * _Py_InitializeFromConfig() => Py_InitializeFromConfig() * _Py_INIT_XXX() => _PyStatus_XXX() * _Py_INIT_FAILED() => _PyStatus_EXCEPTION() * Rename 'err' PyStatus variables to 'status' * Convert RUN_CODE() macro to config_run_code() static inline function * Remove functions: * _Py_InitializeFromArgs() * _Py_InitializeFromWideArgs() * _PyInterpreterState_GetCoreConfig()
7 years ago
bpo-36763: Implement the PEP 587 (GH-13592) * Add a whole new documentation page: "Python Initialization Configuration" * PyWideStringList_Append() return type is now PyStatus, instead of int * PyInterpreterState_New() now calls PyConfig_Clear() if PyConfig_InitPythonConfig() fails. * Rename files: * Python/coreconfig.c => Python/initconfig.c * Include/cpython/coreconfig.h => Include/cpython/initconfig.h * Include/internal/: pycore_coreconfig.h => pycore_initconfig.h * Rename structures * _PyCoreConfig => PyConfig * _PyPreConfig => PyPreConfig * _PyInitError => PyStatus * _PyWstrList => PyWideStringList * Rename PyConfig fields: * use_module_search_paths => module_search_paths_set * module_search_path_env => pythonpath_env * Rename PyStatus field: _func => func * PyInterpreterState: rename core_config field to config * Rename macros and functions: * _PyCoreConfig_SetArgv() => PyConfig_SetBytesArgv() * _PyCoreConfig_SetWideArgv() => PyConfig_SetArgv() * _PyCoreConfig_DecodeLocale() => PyConfig_SetBytesString() * _PyInitError_Failed() => PyStatus_Exception() * _Py_INIT_ERROR_TYPE_xxx enums => _PyStatus_TYPE_xxx * _Py_UnixMain() => Py_BytesMain() * _Py_ExitInitError() => Py_ExitStatusException() * _Py_PreInitializeFromArgs() => Py_PreInitializeFromBytesArgs() * _Py_PreInitializeFromWideArgs() => Py_PreInitializeFromArgs() * _Py_PreInitialize() => Py_PreInitialize() * _Py_RunMain() => Py_RunMain() * _Py_InitializeFromConfig() => Py_InitializeFromConfig() * _Py_INIT_XXX() => _PyStatus_XXX() * _Py_INIT_FAILED() => _PyStatus_EXCEPTION() * Rename 'err' PyStatus variables to 'status' * Convert RUN_CODE() macro to config_run_code() static inline function * Remove functions: * _Py_InitializeFromArgs() * _Py_InitializeFromWideArgs() * _PyInterpreterState_GetCoreConfig()
7 years ago
bpo-32030: Split Py_Main() into subfunctions (#4399) * Don't use "Python runtime" anymore to parse command line options or to get environment variables: pymain_init() is now a strict separation. * Use an error message rather than "crashing" directly with Py_FatalError(). Limit the number of calls to Py_FatalError(). It prepares the code to handle errors more nicely later. * Warnings options (-W, PYTHONWARNINGS) and "XOptions" (-X) are now only added to the sys module once Python core is properly initialized. * _PyMain is now the well identified owner of some important strings like: warnings options, XOptions, and the "program name". The program name string is now properly freed at exit. pymain_free() is now responsible to free the "command" string. * Rename most methods in Modules/main.c to use a "pymain_" prefix to avoid conflits and ease debug. * Replace _Py_CommandLineDetails_INIT with memset(0) * Reorder a lot of code to fix the initialization ordering. For example, initializing standard streams now comes before parsing PYTHONWARNINGS. * Py_Main() now handles errors when adding warnings options and XOptions. * Add _PyMem_GetDefaultRawAllocator() private function. * Cleanup _PyMem_Initialize(): remove useless global constants: move them into _PyMem_Initialize(). * Call _PyRuntime_Initialize() as soon as possible: _PyRuntime_Initialize() now returns an error message on failure. * Add _PyInitError structure and following macros: * _Py_INIT_OK() * _Py_INIT_ERR(msg) * _Py_INIT_USER_ERR(msg): "user" error, don't abort() in that case * _Py_INIT_FAILED(err)
8 years ago
bpo-36763: Implement the PEP 587 (GH-13592) * Add a whole new documentation page: "Python Initialization Configuration" * PyWideStringList_Append() return type is now PyStatus, instead of int * PyInterpreterState_New() now calls PyConfig_Clear() if PyConfig_InitPythonConfig() fails. * Rename files: * Python/coreconfig.c => Python/initconfig.c * Include/cpython/coreconfig.h => Include/cpython/initconfig.h * Include/internal/: pycore_coreconfig.h => pycore_initconfig.h * Rename structures * _PyCoreConfig => PyConfig * _PyPreConfig => PyPreConfig * _PyInitError => PyStatus * _PyWstrList => PyWideStringList * Rename PyConfig fields: * use_module_search_paths => module_search_paths_set * module_search_path_env => pythonpath_env * Rename PyStatus field: _func => func * PyInterpreterState: rename core_config field to config * Rename macros and functions: * _PyCoreConfig_SetArgv() => PyConfig_SetBytesArgv() * _PyCoreConfig_SetWideArgv() => PyConfig_SetArgv() * _PyCoreConfig_DecodeLocale() => PyConfig_SetBytesString() * _PyInitError_Failed() => PyStatus_Exception() * _Py_INIT_ERROR_TYPE_xxx enums => _PyStatus_TYPE_xxx * _Py_UnixMain() => Py_BytesMain() * _Py_ExitInitError() => Py_ExitStatusException() * _Py_PreInitializeFromArgs() => Py_PreInitializeFromBytesArgs() * _Py_PreInitializeFromWideArgs() => Py_PreInitializeFromArgs() * _Py_PreInitialize() => Py_PreInitialize() * _Py_RunMain() => Py_RunMain() * _Py_InitializeFromConfig() => Py_InitializeFromConfig() * _Py_INIT_XXX() => _PyStatus_XXX() * _Py_INIT_FAILED() => _PyStatus_EXCEPTION() * Rename 'err' PyStatus variables to 'status' * Convert RUN_CODE() macro to config_run_code() static inline function * Remove functions: * _Py_InitializeFromArgs() * _Py_InitializeFromWideArgs() * _PyInterpreterState_GetCoreConfig()
7 years ago
bpo-32030: Split Py_Main() into subfunctions (#4399) * Don't use "Python runtime" anymore to parse command line options or to get environment variables: pymain_init() is now a strict separation. * Use an error message rather than "crashing" directly with Py_FatalError(). Limit the number of calls to Py_FatalError(). It prepares the code to handle errors more nicely later. * Warnings options (-W, PYTHONWARNINGS) and "XOptions" (-X) are now only added to the sys module once Python core is properly initialized. * _PyMain is now the well identified owner of some important strings like: warnings options, XOptions, and the "program name". The program name string is now properly freed at exit. pymain_free() is now responsible to free the "command" string. * Rename most methods in Modules/main.c to use a "pymain_" prefix to avoid conflits and ease debug. * Replace _Py_CommandLineDetails_INIT with memset(0) * Reorder a lot of code to fix the initialization ordering. For example, initializing standard streams now comes before parsing PYTHONWARNINGS. * Py_Main() now handles errors when adding warnings options and XOptions. * Add _PyMem_GetDefaultRawAllocator() private function. * Cleanup _PyMem_Initialize(): remove useless global constants: move them into _PyMem_Initialize(). * Call _PyRuntime_Initialize() as soon as possible: _PyRuntime_Initialize() now returns an error message on failure. * Add _PyInitError structure and following macros: * _Py_INIT_OK() * _Py_INIT_ERR(msg) * _Py_INIT_USER_ERR(msg): "user" error, don't abort() in that case * _Py_INIT_FAILED(err)
8 years ago
bpo-36763: Implement the PEP 587 (GH-13592) * Add a whole new documentation page: "Python Initialization Configuration" * PyWideStringList_Append() return type is now PyStatus, instead of int * PyInterpreterState_New() now calls PyConfig_Clear() if PyConfig_InitPythonConfig() fails. * Rename files: * Python/coreconfig.c => Python/initconfig.c * Include/cpython/coreconfig.h => Include/cpython/initconfig.h * Include/internal/: pycore_coreconfig.h => pycore_initconfig.h * Rename structures * _PyCoreConfig => PyConfig * _PyPreConfig => PyPreConfig * _PyInitError => PyStatus * _PyWstrList => PyWideStringList * Rename PyConfig fields: * use_module_search_paths => module_search_paths_set * module_search_path_env => pythonpath_env * Rename PyStatus field: _func => func * PyInterpreterState: rename core_config field to config * Rename macros and functions: * _PyCoreConfig_SetArgv() => PyConfig_SetBytesArgv() * _PyCoreConfig_SetWideArgv() => PyConfig_SetArgv() * _PyCoreConfig_DecodeLocale() => PyConfig_SetBytesString() * _PyInitError_Failed() => PyStatus_Exception() * _Py_INIT_ERROR_TYPE_xxx enums => _PyStatus_TYPE_xxx * _Py_UnixMain() => Py_BytesMain() * _Py_ExitInitError() => Py_ExitStatusException() * _Py_PreInitializeFromArgs() => Py_PreInitializeFromBytesArgs() * _Py_PreInitializeFromWideArgs() => Py_PreInitializeFromArgs() * _Py_PreInitialize() => Py_PreInitialize() * _Py_RunMain() => Py_RunMain() * _Py_InitializeFromConfig() => Py_InitializeFromConfig() * _Py_INIT_XXX() => _PyStatus_XXX() * _Py_INIT_FAILED() => _PyStatus_EXCEPTION() * Rename 'err' PyStatus variables to 'status' * Convert RUN_CODE() macro to config_run_code() static inline function * Remove functions: * _Py_InitializeFromArgs() * _Py_InitializeFromWideArgs() * _PyInterpreterState_GetCoreConfig()
7 years ago
bpo-36763: Implement the PEP 587 (GH-13592) * Add a whole new documentation page: "Python Initialization Configuration" * PyWideStringList_Append() return type is now PyStatus, instead of int * PyInterpreterState_New() now calls PyConfig_Clear() if PyConfig_InitPythonConfig() fails. * Rename files: * Python/coreconfig.c => Python/initconfig.c * Include/cpython/coreconfig.h => Include/cpython/initconfig.h * Include/internal/: pycore_coreconfig.h => pycore_initconfig.h * Rename structures * _PyCoreConfig => PyConfig * _PyPreConfig => PyPreConfig * _PyInitError => PyStatus * _PyWstrList => PyWideStringList * Rename PyConfig fields: * use_module_search_paths => module_search_paths_set * module_search_path_env => pythonpath_env * Rename PyStatus field: _func => func * PyInterpreterState: rename core_config field to config * Rename macros and functions: * _PyCoreConfig_SetArgv() => PyConfig_SetBytesArgv() * _PyCoreConfig_SetWideArgv() => PyConfig_SetArgv() * _PyCoreConfig_DecodeLocale() => PyConfig_SetBytesString() * _PyInitError_Failed() => PyStatus_Exception() * _Py_INIT_ERROR_TYPE_xxx enums => _PyStatus_TYPE_xxx * _Py_UnixMain() => Py_BytesMain() * _Py_ExitInitError() => Py_ExitStatusException() * _Py_PreInitializeFromArgs() => Py_PreInitializeFromBytesArgs() * _Py_PreInitializeFromWideArgs() => Py_PreInitializeFromArgs() * _Py_PreInitialize() => Py_PreInitialize() * _Py_RunMain() => Py_RunMain() * _Py_InitializeFromConfig() => Py_InitializeFromConfig() * _Py_INIT_XXX() => _PyStatus_XXX() * _Py_INIT_FAILED() => _PyStatus_EXCEPTION() * Rename 'err' PyStatus variables to 'status' * Convert RUN_CODE() macro to config_run_code() static inline function * Remove functions: * _Py_InitializeFromArgs() * _Py_InitializeFromWideArgs() * _PyInterpreterState_GetCoreConfig()
7 years ago
  1. #include "Python.h"
  2. #include "pycore_initconfig.h"
  3. #ifdef MS_WINDOWS
  4. # include <windows.h>
  5. /* All sample MSDN wincrypt programs include the header below. It is at least
  6. * required with Min GW. */
  7. # include <wincrypt.h>
  8. #else
  9. # include <fcntl.h>
  10. # ifdef HAVE_SYS_STAT_H
  11. # include <sys/stat.h>
  12. # endif
  13. # ifdef HAVE_LINUX_RANDOM_H
  14. # include <linux/random.h>
  15. # endif
  16. # if defined(HAVE_SYS_RANDOM_H) && (defined(HAVE_GETRANDOM) || defined(HAVE_GETENTROPY))
  17. # include <sys/random.h>
  18. # endif
  19. # if !defined(HAVE_GETRANDOM) && defined(HAVE_GETRANDOM_SYSCALL)
  20. # include <sys/syscall.h>
  21. # endif
  22. #endif
  23. #ifdef _Py_MEMORY_SANITIZER
  24. # include <sanitizer/msan_interface.h>
  25. #endif
  26. #if defined(__APPLE__) && defined(__has_builtin)
  27. # if __has_builtin(__builtin_available)
  28. # define HAVE_GETENTRYPY_GETRANDOM_RUNTIME __builtin_available(macOS 10.12, iOS 10.10, tvOS 10.0, watchOS 3.0, *)
  29. # endif
  30. #endif
  31. #ifndef HAVE_GETENTRYPY_GETRANDOM_RUNTIME
  32. # define HAVE_GETENTRYPY_GETRANDOM_RUNTIME 1
  33. #endif
  34. #ifdef Py_DEBUG
  35. int _Py_HashSecret_Initialized = 0;
  36. #else
  37. static int _Py_HashSecret_Initialized = 0;
  38. #endif
  39. #ifdef MS_WINDOWS
  40. static HCRYPTPROV hCryptProv = 0;
  41. static int
  42. win32_urandom_init(int raise)
  43. {
  44. /* Acquire context */
  45. if (!CryptAcquireContextW(&hCryptProv, NULL, NULL,
  46. PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
  47. goto error;
  48. return 0;
  49. error:
  50. if (raise) {
  51. PyErr_SetFromWindowsErr(0);
  52. }
  53. return -1;
  54. }
  55. /* Fill buffer with size pseudo-random bytes generated by the Windows CryptoGen
  56. API. Return 0 on success, or raise an exception and return -1 on error. */
  57. static int
  58. win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise)
  59. {
  60. if (hCryptProv == 0)
  61. {
  62. if (win32_urandom_init(raise) == -1) {
  63. return -1;
  64. }
  65. }
  66. while (size > 0)
  67. {
  68. DWORD chunk = (DWORD)Py_MIN(size, PY_DWORD_MAX);
  69. if (!CryptGenRandom(hCryptProv, chunk, buffer))
  70. {
  71. /* CryptGenRandom() failed */
  72. if (raise) {
  73. PyErr_SetFromWindowsErr(0);
  74. }
  75. return -1;
  76. }
  77. buffer += chunk;
  78. size -= chunk;
  79. }
  80. return 0;
  81. }
  82. #else /* !MS_WINDOWS */
  83. #if defined(HAVE_GETRANDOM) || defined(HAVE_GETRANDOM_SYSCALL)
  84. #define PY_GETRANDOM 1
  85. /* Call getrandom() to get random bytes:
  86. - Return 1 on success
  87. - Return 0 if getrandom() is not available (failed with ENOSYS or EPERM),
  88. or if getrandom(GRND_NONBLOCK) failed with EAGAIN (system urandom not
  89. initialized yet) and raise=0.
  90. - Raise an exception (if raise is non-zero) and return -1 on error:
  91. if getrandom() failed with EINTR, raise is non-zero and the Python signal
  92. handler raised an exception, or if getrandom() failed with a different
  93. error.
  94. getrandom() is retried if it failed with EINTR: interrupted by a signal. */
  95. static int
  96. py_getrandom(void *buffer, Py_ssize_t size, int blocking, int raise)
  97. {
  98. /* Is getrandom() supported by the running kernel? Set to 0 if getrandom()
  99. failed with ENOSYS or EPERM. Need Linux kernel 3.17 or newer, or Solaris
  100. 11.3 or newer */
  101. static int getrandom_works = 1;
  102. int flags;
  103. char *dest;
  104. long n;
  105. if (!getrandom_works) {
  106. return 0;
  107. }
  108. flags = blocking ? 0 : GRND_NONBLOCK;
  109. dest = buffer;
  110. while (0 < size) {
  111. #if defined(__sun) && defined(__SVR4)
  112. /* Issue #26735: On Solaris, getrandom() is limited to returning up
  113. to 1024 bytes. Call it multiple times if more bytes are
  114. requested. */
  115. n = Py_MIN(size, 1024);
  116. #else
  117. n = Py_MIN(size, LONG_MAX);
  118. #endif
  119. errno = 0;
  120. #ifdef HAVE_GETRANDOM
  121. if (raise) {
  122. Py_BEGIN_ALLOW_THREADS
  123. n = getrandom(dest, n, flags);
  124. Py_END_ALLOW_THREADS
  125. }
  126. else {
  127. n = getrandom(dest, n, flags);
  128. }
  129. #else
  130. /* On Linux, use the syscall() function because the GNU libc doesn't
  131. expose the Linux getrandom() syscall yet. See:
  132. https://sourceware.org/bugzilla/show_bug.cgi?id=17252 */
  133. if (raise) {
  134. Py_BEGIN_ALLOW_THREADS
  135. n = syscall(SYS_getrandom, dest, n, flags);
  136. Py_END_ALLOW_THREADS
  137. }
  138. else {
  139. n = syscall(SYS_getrandom, dest, n, flags);
  140. }
  141. # ifdef _Py_MEMORY_SANITIZER
  142. if (n > 0) {
  143. __msan_unpoison(dest, n);
  144. }
  145. # endif
  146. #endif
  147. if (n < 0) {
  148. /* ENOSYS: the syscall is not supported by the kernel.
  149. EPERM: the syscall is blocked by a security policy (ex: SECCOMP)
  150. or something else. */
  151. if (errno == ENOSYS || errno == EPERM) {
  152. getrandom_works = 0;
  153. return 0;
  154. }
  155. /* getrandom(GRND_NONBLOCK) fails with EAGAIN if the system urandom
  156. is not initialized yet. For _PyRandom_Init(), we ignore the
  157. error and fall back on reading /dev/urandom which never blocks,
  158. even if the system urandom is not initialized yet:
  159. see the PEP 524. */
  160. if (errno == EAGAIN && !raise && !blocking) {
  161. return 0;
  162. }
  163. if (errno == EINTR) {
  164. if (raise) {
  165. if (PyErr_CheckSignals()) {
  166. return -1;
  167. }
  168. }
  169. /* retry getrandom() if it was interrupted by a signal */
  170. continue;
  171. }
  172. if (raise) {
  173. PyErr_SetFromErrno(PyExc_OSError);
  174. }
  175. return -1;
  176. }
  177. dest += n;
  178. size -= n;
  179. }
  180. return 1;
  181. }
  182. #elif defined(HAVE_GETENTROPY)
  183. #define PY_GETENTROPY 1
  184. /* Fill buffer with size pseudo-random bytes generated by getentropy():
  185. - Return 1 on success
  186. - Return 0 if getentropy() syscall is not available (failed with ENOSYS or
  187. EPERM).
  188. - Raise an exception (if raise is non-zero) and return -1 on error:
  189. if getentropy() failed with EINTR, raise is non-zero and the Python signal
  190. handler raised an exception, or if getentropy() failed with a different
  191. error.
  192. getentropy() is retried if it failed with EINTR: interrupted by a signal. */
  193. #if defined(__APPLE__) && defined(__has_attribute) && __has_attribute(availability)
  194. static int
  195. py_getentropy(char *buffer, Py_ssize_t size, int raise)
  196. __attribute__((availability(macos,introduced=10.12)))
  197. __attribute__((availability(ios,introduced=10.0)))
  198. __attribute__((availability(tvos,introduced=10.0)))
  199. __attribute__((availability(watchos,introduced=3.0)));
  200. #endif
  201. static int
  202. py_getentropy(char *buffer, Py_ssize_t size, int raise)
  203. {
  204. /* Is getentropy() supported by the running kernel? Set to 0 if
  205. getentropy() failed with ENOSYS or EPERM. */
  206. static int getentropy_works = 1;
  207. if (!getentropy_works) {
  208. return 0;
  209. }
  210. while (size > 0) {
  211. /* getentropy() is limited to returning up to 256 bytes. Call it
  212. multiple times if more bytes are requested. */
  213. Py_ssize_t len = Py_MIN(size, 256);
  214. int res;
  215. if (raise) {
  216. Py_BEGIN_ALLOW_THREADS
  217. res = getentropy(buffer, len);
  218. Py_END_ALLOW_THREADS
  219. }
  220. else {
  221. res = getentropy(buffer, len);
  222. }
  223. if (res < 0) {
  224. /* ENOSYS: the syscall is not supported by the running kernel.
  225. EPERM: the syscall is blocked by a security policy (ex: SECCOMP)
  226. or something else. */
  227. if (errno == ENOSYS || errno == EPERM) {
  228. getentropy_works = 0;
  229. return 0;
  230. }
  231. if (errno == EINTR) {
  232. if (raise) {
  233. if (PyErr_CheckSignals()) {
  234. return -1;
  235. }
  236. }
  237. /* retry getentropy() if it was interrupted by a signal */
  238. continue;
  239. }
  240. if (raise) {
  241. PyErr_SetFromErrno(PyExc_OSError);
  242. }
  243. return -1;
  244. }
  245. buffer += len;
  246. size -= len;
  247. }
  248. return 1;
  249. }
  250. #endif /* defined(HAVE_GETENTROPY) && !(defined(__sun) && defined(__SVR4)) */
  251. static struct {
  252. int fd;
  253. dev_t st_dev;
  254. ino_t st_ino;
  255. } urandom_cache = { -1 };
  256. /* Read random bytes from the /dev/urandom device:
  257. - Return 0 on success
  258. - Raise an exception (if raise is non-zero) and return -1 on error
  259. Possible causes of errors:
  260. - open() failed with ENOENT, ENXIO, ENODEV, EACCES: the /dev/urandom device
  261. was not found. For example, it was removed manually or not exposed in a
  262. chroot or container.
  263. - open() failed with a different error
  264. - fstat() failed
  265. - read() failed or returned 0
  266. read() is retried if it failed with EINTR: interrupted by a signal.
  267. The file descriptor of the device is kept open between calls to avoid using
  268. many file descriptors when run in parallel from multiple threads:
  269. see the issue #18756.
  270. st_dev and st_ino fields of the file descriptor (from fstat()) are cached to
  271. check if the file descriptor was replaced by a different file (which is
  272. likely a bug in the application): see the issue #21207.
  273. If the file descriptor was closed or replaced, open a new file descriptor
  274. but don't close the old file descriptor: it probably points to something
  275. important for some third-party code. */
  276. static int
  277. dev_urandom(char *buffer, Py_ssize_t size, int raise)
  278. {
  279. int fd;
  280. Py_ssize_t n;
  281. if (raise) {
  282. struct _Py_stat_struct st;
  283. int fstat_result;
  284. if (urandom_cache.fd >= 0) {
  285. Py_BEGIN_ALLOW_THREADS
  286. fstat_result = _Py_fstat_noraise(urandom_cache.fd, &st);
  287. Py_END_ALLOW_THREADS
  288. /* Does the fd point to the same thing as before? (issue #21207) */
  289. if (fstat_result
  290. || st.st_dev != urandom_cache.st_dev
  291. || st.st_ino != urandom_cache.st_ino) {
  292. /* Something changed: forget the cached fd (but don't close it,
  293. since it probably points to something important for some
  294. third-party code). */
  295. urandom_cache.fd = -1;
  296. }
  297. }
  298. if (urandom_cache.fd >= 0)
  299. fd = urandom_cache.fd;
  300. else {
  301. fd = _Py_open("/dev/urandom", O_RDONLY);
  302. if (fd < 0) {
  303. if (errno == ENOENT || errno == ENXIO ||
  304. errno == ENODEV || errno == EACCES) {
  305. PyErr_SetString(PyExc_NotImplementedError,
  306. "/dev/urandom (or equivalent) not found");
  307. }
  308. /* otherwise, keep the OSError exception raised by _Py_open() */
  309. return -1;
  310. }
  311. if (urandom_cache.fd >= 0) {
  312. /* urandom_fd was initialized by another thread while we were
  313. not holding the GIL, keep it. */
  314. close(fd);
  315. fd = urandom_cache.fd;
  316. }
  317. else {
  318. if (_Py_fstat(fd, &st)) {
  319. close(fd);
  320. return -1;
  321. }
  322. else {
  323. urandom_cache.fd = fd;
  324. urandom_cache.st_dev = st.st_dev;
  325. urandom_cache.st_ino = st.st_ino;
  326. }
  327. }
  328. }
  329. do {
  330. n = _Py_read(fd, buffer, (size_t)size);
  331. if (n == -1)
  332. return -1;
  333. if (n == 0) {
  334. PyErr_Format(PyExc_RuntimeError,
  335. "Failed to read %zi bytes from /dev/urandom",
  336. size);
  337. return -1;
  338. }
  339. buffer += n;
  340. size -= n;
  341. } while (0 < size);
  342. }
  343. else {
  344. fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
  345. if (fd < 0) {
  346. return -1;
  347. }
  348. while (0 < size)
  349. {
  350. do {
  351. n = read(fd, buffer, (size_t)size);
  352. } while (n < 0 && errno == EINTR);
  353. if (n <= 0) {
  354. /* stop on error or if read(size) returned 0 */
  355. close(fd);
  356. return -1;
  357. }
  358. buffer += n;
  359. size -= n;
  360. }
  361. close(fd);
  362. }
  363. return 0;
  364. }
  365. static void
  366. dev_urandom_close(void)
  367. {
  368. if (urandom_cache.fd >= 0) {
  369. close(urandom_cache.fd);
  370. urandom_cache.fd = -1;
  371. }
  372. }
  373. #endif /* !MS_WINDOWS */
  374. /* Fill buffer with pseudo-random bytes generated by a linear congruent
  375. generator (LCG):
  376. x(n+1) = (x(n) * 214013 + 2531011) % 2^32
  377. Use bits 23..16 of x(n) to generate a byte. */
  378. static void
  379. lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
  380. {
  381. size_t index;
  382. unsigned int x;
  383. x = x0;
  384. for (index=0; index < size; index++) {
  385. x *= 214013;
  386. x += 2531011;
  387. /* modulo 2 ^ (8 * sizeof(int)) */
  388. buffer[index] = (x >> 16) & 0xff;
  389. }
  390. }
  391. /* Read random bytes:
  392. - Return 0 on success
  393. - Raise an exception (if raise is non-zero) and return -1 on error
  394. Used sources of entropy ordered by preference, preferred source first:
  395. - CryptGenRandom() on Windows
  396. - getrandom() function (ex: Linux and Solaris): call py_getrandom()
  397. - getentropy() function (ex: OpenBSD): call py_getentropy()
  398. - /dev/urandom device
  399. Read from the /dev/urandom device if getrandom() or getentropy() function
  400. is not available or does not work.
  401. Prefer getrandom() over getentropy() because getrandom() supports blocking
  402. and non-blocking mode: see the PEP 524. Python requires non-blocking RNG at
  403. startup to initialize its hash secret, but os.urandom() must block until the
  404. system urandom is initialized (at least on Linux 3.17 and newer).
  405. Prefer getrandom() and getentropy() over reading directly /dev/urandom
  406. because these functions don't need file descriptors and so avoid ENFILE or
  407. EMFILE errors (too many open files): see the issue #18756.
  408. Only the getrandom() function supports non-blocking mode.
  409. Only use RNG running in the kernel. They are more secure because it is
  410. harder to get the internal state of a RNG running in the kernel land than a
  411. RNG running in the user land. The kernel has a direct access to the hardware
  412. and has access to hardware RNG, they are used as entropy sources.
  413. Note: the OpenSSL RAND_pseudo_bytes() function does not automatically reseed
  414. its RNG on fork(), two child processes (with the same pid) generate the same
  415. random numbers: see issue #18747. Kernel RNGs don't have this issue,
  416. they have access to good quality entropy sources.
  417. If raise is zero:
  418. - Don't raise an exception on error
  419. - Don't call the Python signal handler (don't call PyErr_CheckSignals()) if
  420. a function fails with EINTR: retry directly the interrupted function
  421. - Don't release the GIL to call functions.
  422. */
  423. static int
  424. pyurandom(void *buffer, Py_ssize_t size, int blocking, int raise)
  425. {
  426. #if defined(PY_GETRANDOM) || defined(PY_GETENTROPY)
  427. int res;
  428. #endif
  429. if (size < 0) {
  430. if (raise) {
  431. PyErr_Format(PyExc_ValueError,
  432. "negative argument not allowed");
  433. }
  434. return -1;
  435. }
  436. if (size == 0) {
  437. return 0;
  438. }
  439. #ifdef MS_WINDOWS
  440. return win32_urandom((unsigned char *)buffer, size, raise);
  441. #else
  442. #if defined(PY_GETRANDOM) || defined(PY_GETENTROPY)
  443. if (HAVE_GETENTRYPY_GETRANDOM_RUNTIME) {
  444. #ifdef PY_GETRANDOM
  445. res = py_getrandom(buffer, size, blocking, raise);
  446. #else
  447. res = py_getentropy(buffer, size, raise);
  448. #endif
  449. if (res < 0) {
  450. return -1;
  451. }
  452. if (res == 1) {
  453. return 0;
  454. }
  455. /* getrandom() or getentropy() function is not available: failed with
  456. ENOSYS or EPERM. Fall back on reading from /dev/urandom. */
  457. } /* end of availability block */
  458. #endif
  459. return dev_urandom(buffer, size, raise);
  460. #endif
  461. }
  462. /* Fill buffer with size pseudo-random bytes from the operating system random
  463. number generator (RNG). It is suitable for most cryptographic purposes
  464. except long living private keys for asymmetric encryption.
  465. On Linux 3.17 and newer, the getrandom() syscall is used in blocking mode:
  466. block until the system urandom entropy pool is initialized (128 bits are
  467. collected by the kernel).
  468. Return 0 on success. Raise an exception and return -1 on error. */
  469. int
  470. _PyOS_URandom(void *buffer, Py_ssize_t size)
  471. {
  472. return pyurandom(buffer, size, 1, 1);
  473. }
  474. /* Fill buffer with size pseudo-random bytes from the operating system random
  475. number generator (RNG). It is not suitable for cryptographic purpose.
  476. On Linux 3.17 and newer (when getrandom() syscall is used), if the system
  477. urandom is not initialized yet, the function returns "weak" entropy read
  478. from /dev/urandom.
  479. Return 0 on success. Raise an exception and return -1 on error. */
  480. int
  481. _PyOS_URandomNonblock(void *buffer, Py_ssize_t size)
  482. {
  483. return pyurandom(buffer, size, 0, 1);
  484. }
  485. PyStatus
  486. _Py_HashRandomization_Init(const PyConfig *config)
  487. {
  488. void *secret = &_Py_HashSecret;
  489. Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
  490. if (_Py_HashSecret_Initialized) {
  491. return _PyStatus_OK();
  492. }
  493. _Py_HashSecret_Initialized = 1;
  494. if (config->use_hash_seed) {
  495. if (config->hash_seed == 0) {
  496. /* disable the randomized hash */
  497. memset(secret, 0, secret_size);
  498. }
  499. else {
  500. /* use the specified hash seed */
  501. lcg_urandom(config->hash_seed, secret, secret_size);
  502. }
  503. }
  504. else {
  505. /* use a random hash seed */
  506. int res;
  507. /* _PyRandom_Init() is called very early in the Python initialization
  508. and so exceptions cannot be used (use raise=0).
  509. _PyRandom_Init() must not block Python initialization: call
  510. pyurandom() is non-blocking mode (blocking=0): see the PEP 524. */
  511. res = pyurandom(secret, secret_size, 0, 0);
  512. if (res < 0) {
  513. return _PyStatus_ERR("failed to get random numbers "
  514. "to initialize Python");
  515. }
  516. }
  517. return _PyStatus_OK();
  518. }
  519. void
  520. _Py_HashRandomization_Fini(void)
  521. {
  522. #ifdef MS_WINDOWS
  523. if (hCryptProv) {
  524. CryptReleaseContext(hCryptProv, 0);
  525. hCryptProv = 0;
  526. }
  527. #else
  528. dev_urandom_close();
  529. #endif
  530. }