bootstrap_hash.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. #include "Python.h"
  2. #include "pycore_initconfig.h"
  3. #include "pycore_fileutils.h" // _Py_fstat_noraise()
  4. #include "pycore_runtime.h" // _PyRuntime
  5. #ifdef MS_WINDOWS
  6. # include <windows.h>
  7. # include <bcrypt.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. /* Fill buffer with size pseudo-random bytes generated by the Windows CryptoGen
  41. API. Return 0 on success, or raise an exception and return -1 on error. */
  42. static int
  43. win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise)
  44. {
  45. while (size > 0)
  46. {
  47. DWORD chunk = (DWORD)Py_MIN(size, PY_DWORD_MAX);
  48. NTSTATUS status = BCryptGenRandom(NULL, buffer, chunk, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
  49. if (!BCRYPT_SUCCESS(status)) {
  50. /* BCryptGenRandom() failed */
  51. if (raise) {
  52. PyErr_SetFromWindowsErr(0);
  53. }
  54. return -1;
  55. }
  56. buffer += chunk;
  57. size -= chunk;
  58. }
  59. return 0;
  60. }
  61. #else /* !MS_WINDOWS */
  62. #if defined(HAVE_GETRANDOM) || defined(HAVE_GETRANDOM_SYSCALL)
  63. #define PY_GETRANDOM 1
  64. /* Call getrandom() to get random bytes:
  65. - Return 1 on success
  66. - Return 0 if getrandom() is not available (failed with ENOSYS or EPERM),
  67. or if getrandom(GRND_NONBLOCK) failed with EAGAIN (system urandom not
  68. initialized yet) and raise=0.
  69. - Raise an exception (if raise is non-zero) and return -1 on error:
  70. if getrandom() failed with EINTR, raise is non-zero and the Python signal
  71. handler raised an exception, or if getrandom() failed with a different
  72. error.
  73. getrandom() is retried if it failed with EINTR: interrupted by a signal. */
  74. static int
  75. py_getrandom(void *buffer, Py_ssize_t size, int blocking, int raise)
  76. {
  77. /* Is getrandom() supported by the running kernel? Set to 0 if getrandom()
  78. failed with ENOSYS or EPERM. Need Linux kernel 3.17 or newer, or Solaris
  79. 11.3 or newer */
  80. static int getrandom_works = 1;
  81. int flags;
  82. char *dest;
  83. long n;
  84. if (!getrandom_works) {
  85. return 0;
  86. }
  87. flags = blocking ? 0 : GRND_NONBLOCK;
  88. dest = buffer;
  89. while (0 < size) {
  90. #if defined(__sun) && defined(__SVR4)
  91. /* Issue #26735: On Solaris, getrandom() is limited to returning up
  92. to 1024 bytes. Call it multiple times if more bytes are
  93. requested. */
  94. n = Py_MIN(size, 1024);
  95. #else
  96. n = Py_MIN(size, LONG_MAX);
  97. #endif
  98. errno = 0;
  99. #ifdef HAVE_GETRANDOM
  100. if (raise) {
  101. Py_BEGIN_ALLOW_THREADS
  102. n = getrandom(dest, n, flags);
  103. Py_END_ALLOW_THREADS
  104. }
  105. else {
  106. n = getrandom(dest, n, flags);
  107. }
  108. # ifdef _Py_MEMORY_SANITIZER
  109. if (n > 0) {
  110. __msan_unpoison(dest, n);
  111. }
  112. # endif
  113. #else
  114. /* On Linux, use the syscall() function because the GNU libc doesn't
  115. expose the Linux getrandom() syscall yet. See:
  116. https://sourceware.org/bugzilla/show_bug.cgi?id=17252 */
  117. if (raise) {
  118. Py_BEGIN_ALLOW_THREADS
  119. n = syscall(SYS_getrandom, dest, n, flags);
  120. Py_END_ALLOW_THREADS
  121. }
  122. else {
  123. n = syscall(SYS_getrandom, dest, n, flags);
  124. }
  125. # ifdef _Py_MEMORY_SANITIZER
  126. if (n > 0) {
  127. __msan_unpoison(dest, n);
  128. }
  129. # endif
  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 initialized 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. #if defined(__APPLE__) && defined(__has_attribute) && __has_attribute(availability)
  178. static int
  179. py_getentropy(char *buffer, Py_ssize_t size, int raise)
  180. __attribute__((availability(macos,introduced=10.12)))
  181. __attribute__((availability(ios,introduced=10.0)))
  182. __attribute__((availability(tvos,introduced=10.0)))
  183. __attribute__((availability(watchos,introduced=3.0)));
  184. #endif
  185. static int
  186. py_getentropy(char *buffer, Py_ssize_t size, int raise)
  187. {
  188. /* Is getentropy() supported by the running kernel? Set to 0 if
  189. getentropy() failed with ENOSYS or EPERM. */
  190. static int getentropy_works = 1;
  191. if (!getentropy_works) {
  192. return 0;
  193. }
  194. while (size > 0) {
  195. /* getentropy() is limited to returning up to 256 bytes. Call it
  196. multiple times if more bytes are requested. */
  197. Py_ssize_t len = Py_MIN(size, 256);
  198. int res;
  199. if (raise) {
  200. Py_BEGIN_ALLOW_THREADS
  201. res = getentropy(buffer, len);
  202. Py_END_ALLOW_THREADS
  203. }
  204. else {
  205. res = getentropy(buffer, len);
  206. }
  207. if (res < 0) {
  208. /* ENOSYS: the syscall is not supported by the running kernel.
  209. EPERM: the syscall is blocked by a security policy (ex: SECCOMP)
  210. or something else. */
  211. if (errno == ENOSYS || errno == EPERM) {
  212. getentropy_works = 0;
  213. return 0;
  214. }
  215. if (errno == EINTR) {
  216. if (raise) {
  217. if (PyErr_CheckSignals()) {
  218. return -1;
  219. }
  220. }
  221. /* retry getentropy() if it was interrupted by a signal */
  222. continue;
  223. }
  224. if (raise) {
  225. PyErr_SetFromErrno(PyExc_OSError);
  226. }
  227. return -1;
  228. }
  229. buffer += len;
  230. size -= len;
  231. }
  232. return 1;
  233. }
  234. #endif /* defined(HAVE_GETENTROPY) && !(defined(__sun) && defined(__SVR4)) */
  235. #define urandom_cache (_PyRuntime.pyhash_state.urandom_cache)
  236. /* Read random bytes from the /dev/urandom device:
  237. - Return 0 on success
  238. - Raise an exception (if raise is non-zero) and return -1 on error
  239. Possible causes of errors:
  240. - open() failed with ENOENT, ENXIO, ENODEV, EACCES: the /dev/urandom device
  241. was not found. For example, it was removed manually or not exposed in a
  242. chroot or container.
  243. - open() failed with a different error
  244. - fstat() failed
  245. - read() failed or returned 0
  246. read() is retried if it failed with EINTR: interrupted by a signal.
  247. The file descriptor of the device is kept open between calls to avoid using
  248. many file descriptors when run in parallel from multiple threads:
  249. see the issue #18756.
  250. st_dev and st_ino fields of the file descriptor (from fstat()) are cached to
  251. check if the file descriptor was replaced by a different file (which is
  252. likely a bug in the application): see the issue #21207.
  253. If the file descriptor was closed or replaced, open a new file descriptor
  254. but don't close the old file descriptor: it probably points to something
  255. important for some third-party code. */
  256. static int
  257. dev_urandom(char *buffer, Py_ssize_t size, int raise)
  258. {
  259. int fd;
  260. Py_ssize_t n;
  261. if (raise) {
  262. struct _Py_stat_struct st;
  263. int fstat_result;
  264. if (urandom_cache.fd >= 0) {
  265. Py_BEGIN_ALLOW_THREADS
  266. fstat_result = _Py_fstat_noraise(urandom_cache.fd, &st);
  267. Py_END_ALLOW_THREADS
  268. /* Does the fd point to the same thing as before? (issue #21207) */
  269. if (fstat_result
  270. || st.st_dev != urandom_cache.st_dev
  271. || st.st_ino != urandom_cache.st_ino) {
  272. /* Something changed: forget the cached fd (but don't close it,
  273. since it probably points to something important for some
  274. third-party code). */
  275. urandom_cache.fd = -1;
  276. }
  277. }
  278. if (urandom_cache.fd >= 0)
  279. fd = urandom_cache.fd;
  280. else {
  281. fd = _Py_open("/dev/urandom", O_RDONLY);
  282. if (fd < 0) {
  283. if (errno == ENOENT || errno == ENXIO ||
  284. errno == ENODEV || errno == EACCES) {
  285. PyErr_SetString(PyExc_NotImplementedError,
  286. "/dev/urandom (or equivalent) not found");
  287. }
  288. /* otherwise, keep the OSError exception raised by _Py_open() */
  289. return -1;
  290. }
  291. if (urandom_cache.fd >= 0) {
  292. /* urandom_fd was initialized by another thread while we were
  293. not holding the GIL, keep it. */
  294. close(fd);
  295. fd = urandom_cache.fd;
  296. }
  297. else {
  298. if (_Py_fstat(fd, &st)) {
  299. close(fd);
  300. return -1;
  301. }
  302. else {
  303. urandom_cache.fd = fd;
  304. urandom_cache.st_dev = st.st_dev;
  305. urandom_cache.st_ino = st.st_ino;
  306. }
  307. }
  308. }
  309. do {
  310. n = _Py_read(fd, buffer, (size_t)size);
  311. if (n == -1)
  312. return -1;
  313. if (n == 0) {
  314. PyErr_Format(PyExc_RuntimeError,
  315. "Failed to read %zi bytes from /dev/urandom",
  316. size);
  317. return -1;
  318. }
  319. buffer += n;
  320. size -= n;
  321. } while (0 < size);
  322. }
  323. else {
  324. fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
  325. if (fd < 0) {
  326. return -1;
  327. }
  328. while (0 < size)
  329. {
  330. do {
  331. n = read(fd, buffer, (size_t)size);
  332. } while (n < 0 && errno == EINTR);
  333. if (n <= 0) {
  334. /* stop on error or if read(size) returned 0 */
  335. close(fd);
  336. return -1;
  337. }
  338. buffer += n;
  339. size -= n;
  340. }
  341. close(fd);
  342. }
  343. return 0;
  344. }
  345. static void
  346. dev_urandom_close(void)
  347. {
  348. if (urandom_cache.fd >= 0) {
  349. close(urandom_cache.fd);
  350. urandom_cache.fd = -1;
  351. }
  352. }
  353. #undef urandom_cache
  354. #endif /* !MS_WINDOWS */
  355. /* Fill buffer with pseudo-random bytes generated by a linear congruent
  356. generator (LCG):
  357. x(n+1) = (x(n) * 214013 + 2531011) % 2^32
  358. Use bits 23..16 of x(n) to generate a byte. */
  359. static void
  360. lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
  361. {
  362. size_t index;
  363. unsigned int x;
  364. x = x0;
  365. for (index=0; index < size; index++) {
  366. x *= 214013;
  367. x += 2531011;
  368. /* modulo 2 ^ (8 * sizeof(int)) */
  369. buffer[index] = (x >> 16) & 0xff;
  370. }
  371. }
  372. /* Read random bytes:
  373. - Return 0 on success
  374. - Raise an exception (if raise is non-zero) and return -1 on error
  375. Used sources of entropy ordered by preference, preferred source first:
  376. - BCryptGenRandom() on Windows
  377. - getrandom() function (ex: Linux and Solaris): call py_getrandom()
  378. - getentropy() function (ex: OpenBSD): call py_getentropy()
  379. - /dev/urandom device
  380. Read from the /dev/urandom device if getrandom() or getentropy() function
  381. is not available or does not work.
  382. Prefer getrandom() over getentropy() because getrandom() supports blocking
  383. and non-blocking mode: see the PEP 524. Python requires non-blocking RNG at
  384. startup to initialize its hash secret, but os.urandom() must block until the
  385. system urandom is initialized (at least on Linux 3.17 and newer).
  386. Prefer getrandom() and getentropy() over reading directly /dev/urandom
  387. because these functions don't need file descriptors and so avoid ENFILE or
  388. EMFILE errors (too many open files): see the issue #18756.
  389. Only the getrandom() function supports non-blocking mode.
  390. Only use RNG running in the kernel. They are more secure because it is
  391. harder to get the internal state of a RNG running in the kernel land than a
  392. RNG running in the user land. The kernel has a direct access to the hardware
  393. and has access to hardware RNG, they are used as entropy sources.
  394. Note: the OpenSSL RAND_pseudo_bytes() function does not automatically reseed
  395. its RNG on fork(), two child processes (with the same pid) generate the same
  396. random numbers: see issue #18747. Kernel RNGs don't have this issue,
  397. they have access to good quality entropy sources.
  398. If raise is zero:
  399. - Don't raise an exception on error
  400. - Don't call the Python signal handler (don't call PyErr_CheckSignals()) if
  401. a function fails with EINTR: retry directly the interrupted function
  402. - Don't release the GIL to call functions.
  403. */
  404. static int
  405. pyurandom(void *buffer, Py_ssize_t size, int blocking, int raise)
  406. {
  407. #if defined(PY_GETRANDOM) || defined(PY_GETENTROPY)
  408. int res;
  409. #endif
  410. if (size < 0) {
  411. if (raise) {
  412. PyErr_Format(PyExc_ValueError,
  413. "negative argument not allowed");
  414. }
  415. return -1;
  416. }
  417. if (size == 0) {
  418. return 0;
  419. }
  420. #ifdef MS_WINDOWS
  421. return win32_urandom((unsigned char *)buffer, size, raise);
  422. #else
  423. #if defined(PY_GETRANDOM) || defined(PY_GETENTROPY)
  424. if (HAVE_GETENTRYPY_GETRANDOM_RUNTIME) {
  425. #ifdef PY_GETRANDOM
  426. res = py_getrandom(buffer, size, blocking, raise);
  427. #else
  428. res = py_getentropy(buffer, size, raise);
  429. #endif
  430. if (res < 0) {
  431. return -1;
  432. }
  433. if (res == 1) {
  434. return 0;
  435. }
  436. /* getrandom() or getentropy() function is not available: failed with
  437. ENOSYS or EPERM. Fall back on reading from /dev/urandom. */
  438. } /* end of availability block */
  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. PyStatus
  467. _Py_HashRandomization_Init(const PyConfig *config)
  468. {
  469. void *secret = &_Py_HashSecret;
  470. Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
  471. if (_Py_HashSecret_Initialized) {
  472. return _PyStatus_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 _PyStatus_ERR("failed to get random numbers "
  495. "to initialize Python");
  496. }
  497. }
  498. return _PyStatus_OK();
  499. }
  500. void
  501. _Py_HashRandomization_Fini(void)
  502. {
  503. #ifndef MS_WINDOWS
  504. dev_urandom_close();
  505. #endif
  506. }