bootstrap_hash.c 18 KB

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