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.

600 lines
17 KiB

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