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.

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