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.

488 lines
13 KiB

  1. #include "Python.h"
  2. #ifdef MS_WINDOWS
  3. # include <windows.h>
  4. #else
  5. # include <fcntl.h>
  6. # ifdef HAVE_SYS_STAT_H
  7. # include <sys/stat.h>
  8. # endif
  9. # ifdef HAVE_LINUX_RANDOM_H
  10. # include <linux/random.h>
  11. # endif
  12. # ifdef HAVE_GETRANDOM
  13. # include <sys/random.h>
  14. # elif defined(HAVE_GETRANDOM_SYSCALL)
  15. # include <sys/syscall.h>
  16. # endif
  17. #endif
  18. #ifdef Py_DEBUG
  19. int _Py_HashSecret_Initialized = 0;
  20. #else
  21. static int _Py_HashSecret_Initialized = 0;
  22. #endif
  23. #ifdef MS_WINDOWS
  24. static HCRYPTPROV hCryptProv = 0;
  25. static int
  26. win32_urandom_init(int raise)
  27. {
  28. /* Acquire context */
  29. if (!CryptAcquireContext(&hCryptProv, NULL, NULL,
  30. PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
  31. goto error;
  32. return 0;
  33. error:
  34. if (raise)
  35. PyErr_SetFromWindowsErr(0);
  36. else
  37. Py_FatalError("Failed to initialize Windows random API (CryptoGen)");
  38. return -1;
  39. }
  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. Py_ssize_t chunk;
  46. if (hCryptProv == 0)
  47. {
  48. if (win32_urandom_init(raise) == -1)
  49. return -1;
  50. }
  51. while (size > 0)
  52. {
  53. chunk = size > INT_MAX ? INT_MAX : size;
  54. if (!CryptGenRandom(hCryptProv, (DWORD)chunk, buffer))
  55. {
  56. /* CryptGenRandom() failed */
  57. if (raise)
  58. PyErr_SetFromWindowsErr(0);
  59. else
  60. Py_FatalError("Failed to initialized the randomized hash "
  61. "secret using CryptoGen)");
  62. return -1;
  63. }
  64. buffer += chunk;
  65. size -= chunk;
  66. }
  67. return 0;
  68. }
  69. /* Issue #25003: Don't use getentropy() on Solaris (available since
  70. * Solaris 11.3), it is blocking whereas os.urandom() should not block. */
  71. #elif defined(HAVE_GETENTROPY) && !defined(sun)
  72. #define PY_GETENTROPY 1
  73. /* Fill buffer with size pseudo-random bytes generated by getentropy().
  74. Return 0 on success, or raise an exception and return -1 on error.
  75. If fatal is nonzero, call Py_FatalError() instead of raising an exception
  76. on error. */
  77. static int
  78. py_getentropy(unsigned char *buffer, Py_ssize_t size, int fatal)
  79. {
  80. while (size > 0) {
  81. Py_ssize_t len = Py_MIN(size, 256);
  82. int res;
  83. if (!fatal) {
  84. Py_BEGIN_ALLOW_THREADS
  85. res = getentropy(buffer, len);
  86. Py_END_ALLOW_THREADS
  87. if (res < 0) {
  88. PyErr_SetFromErrno(PyExc_OSError);
  89. return -1;
  90. }
  91. }
  92. else {
  93. res = getentropy(buffer, len);
  94. if (res < 0)
  95. Py_FatalError("getentropy() failed");
  96. }
  97. buffer += len;
  98. size -= len;
  99. }
  100. return 0;
  101. }
  102. #else
  103. #if defined(HAVE_GETRANDOM) || defined(HAVE_GETRANDOM_SYSCALL)
  104. #define PY_GETRANDOM 1
  105. /* Call getrandom()
  106. - Return 1 on success
  107. - Return 0 if getrandom() syscall is not available (failed with ENOSYS or
  108. EPERM) or if getrandom(GRND_NONBLOCK) failed with EAGAIN (system urandom
  109. not initialized yet) and raise=0.
  110. - Raise an exception (if raise is non-zero) and return -1 on error:
  111. getrandom() failed with EINTR and the Python signal handler raised an
  112. exception, or getrandom() failed with a different error. */
  113. static int
  114. py_getrandom(void *buffer, Py_ssize_t size, int raise)
  115. {
  116. /* Is getrandom() supported by the running kernel? Set to 0 if getrandom()
  117. failed with ENOSYS or EPERM. Need Linux kernel 3.17 or newer, or Solaris
  118. 11.3 or newer */
  119. static int getrandom_works = 1;
  120. /* getrandom() on Linux will block if called before the kernel has
  121. * initialized the urandom entropy pool. This will cause Python
  122. * to hang on startup if called very early in the boot process -
  123. * see https://bugs.python.org/issue26839. To avoid this, use the
  124. * GRND_NONBLOCK flag. */
  125. const int flags = GRND_NONBLOCK;
  126. long n;
  127. if (!getrandom_works) {
  128. return 0;
  129. }
  130. while (0 < size) {
  131. #ifdef sun
  132. /* Issue #26735: On Solaris, getrandom() is limited to returning up
  133. to 1024 bytes */
  134. n = Py_MIN(size, 1024);
  135. #else
  136. n = Py_MIN(size, LONG_MAX);
  137. #endif
  138. errno = 0;
  139. #ifdef HAVE_GETRANDOM
  140. if (raise) {
  141. Py_BEGIN_ALLOW_THREADS
  142. n = getrandom(buffer, n, flags);
  143. Py_END_ALLOW_THREADS
  144. }
  145. else {
  146. n = getrandom(buffer, n, flags);
  147. }
  148. #else
  149. /* On Linux, use the syscall() function because the GNU libc doesn't
  150. * expose the Linux getrandom() syscall yet. See:
  151. * https://sourceware.org/bugzilla/show_bug.cgi?id=17252 */
  152. if (raise) {
  153. Py_BEGIN_ALLOW_THREADS
  154. n = syscall(SYS_getrandom, buffer, n, flags);
  155. Py_END_ALLOW_THREADS
  156. }
  157. else {
  158. n = syscall(SYS_getrandom, buffer, n, flags);
  159. }
  160. #endif
  161. if (n < 0) {
  162. /* ENOSYS: getrandom() syscall not supported by the kernel (but
  163. * maybe supported by the host which built Python). EPERM:
  164. * getrandom() syscall blocked by SECCOMP or something else. */
  165. if (errno == ENOSYS || errno == EPERM) {
  166. getrandom_works = 0;
  167. return 0;
  168. }
  169. if (errno == EAGAIN) {
  170. /* getrandom(GRND_NONBLOCK) fails with EAGAIN if the system
  171. urandom is not initialiazed yet. In this case, fall back on
  172. reading from /dev/urandom.
  173. Note: In this case the data read will not be random so
  174. should not be used for cryptographic purposes. Retaining
  175. the existing semantics for practical purposes. */
  176. getrandom_works = 0;
  177. return 0;
  178. }
  179. if (errno == EINTR) {
  180. if (PyErr_CheckSignals()) {
  181. if (!raise) {
  182. Py_FatalError("getrandom() interrupted by a signal");
  183. }
  184. return -1;
  185. }
  186. /* retry getrandom() */
  187. continue;
  188. }
  189. if (raise) {
  190. PyErr_SetFromErrno(PyExc_OSError);
  191. }
  192. else {
  193. Py_FatalError("getrandom() failed");
  194. }
  195. return -1;
  196. }
  197. buffer += n;
  198. size -= n;
  199. }
  200. return 1;
  201. }
  202. #endif
  203. static struct {
  204. int fd;
  205. dev_t st_dev;
  206. ino_t st_ino;
  207. } urandom_cache = { -1 };
  208. /* Read 'size' random bytes from py_getrandom(). Fall back on reading from
  209. /dev/urandom if getrandom() is not available.
  210. Call Py_FatalError() on error. */
  211. static void
  212. dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size)
  213. {
  214. int fd;
  215. Py_ssize_t n;
  216. assert (0 < size);
  217. #ifdef PY_GETRANDOM
  218. if (py_getrandom(buffer, size, 0) == 1) {
  219. return;
  220. }
  221. /* getrandom() failed with ENOSYS or EPERM,
  222. fall back on reading /dev/urandom */
  223. #endif
  224. fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
  225. if (fd < 0) {
  226. Py_FatalError("Failed to open /dev/urandom");
  227. }
  228. while (0 < size)
  229. {
  230. do {
  231. n = read(fd, buffer, (size_t)size);
  232. } while (n < 0 && errno == EINTR);
  233. if (n <= 0) {
  234. /* read() failed or returned 0 bytes */
  235. Py_FatalError("Failed to read bytes from /dev/urandom");
  236. break;
  237. }
  238. buffer += n;
  239. size -= n;
  240. }
  241. close(fd);
  242. }
  243. /* Read 'size' random bytes from py_getrandom(). Fall back on reading from
  244. /dev/urandom if getrandom() is not available.
  245. Return 0 on success. Raise an exception and return -1 on error. */
  246. static int
  247. dev_urandom_python(char *buffer, Py_ssize_t size)
  248. {
  249. int fd;
  250. Py_ssize_t n;
  251. struct _Py_stat_struct st;
  252. #ifdef PY_GETRANDOM
  253. int res;
  254. #endif
  255. if (size <= 0)
  256. return 0;
  257. #ifdef PY_GETRANDOM
  258. res = py_getrandom(buffer, size, 1);
  259. if (res < 0) {
  260. return -1;
  261. }
  262. if (res == 1) {
  263. return 0;
  264. }
  265. /* getrandom() failed with ENOSYS or EPERM,
  266. fall back on reading /dev/urandom */
  267. #endif
  268. if (urandom_cache.fd >= 0) {
  269. /* Does the fd point to the same thing as before? (issue #21207) */
  270. if (_Py_fstat_noraise(urandom_cache.fd, &st)
  271. || st.st_dev != urandom_cache.st_dev
  272. || st.st_ino != urandom_cache.st_ino) {
  273. /* Something changed: forget the cached fd (but don't close it,
  274. since it probably points to something important for some
  275. third-party code). */
  276. urandom_cache.fd = -1;
  277. }
  278. }
  279. if (urandom_cache.fd >= 0)
  280. fd = urandom_cache.fd;
  281. else {
  282. fd = _Py_open("/dev/urandom", O_RDONLY);
  283. if (fd < 0) {
  284. if (errno == ENOENT || errno == ENXIO ||
  285. errno == ENODEV || errno == EACCES)
  286. PyErr_SetString(PyExc_NotImplementedError,
  287. "/dev/urandom (or equivalent) not found");
  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. }
  314. if (n == 0) {
  315. PyErr_Format(PyExc_RuntimeError,
  316. "Failed to read %zi bytes from /dev/urandom",
  317. size);
  318. return -1;
  319. }
  320. buffer += n;
  321. size -= n;
  322. } while (0 < size);
  323. return 0;
  324. }
  325. static void
  326. dev_urandom_close(void)
  327. {
  328. if (urandom_cache.fd >= 0) {
  329. close(urandom_cache.fd);
  330. urandom_cache.fd = -1;
  331. }
  332. }
  333. #endif
  334. /* Fill buffer with pseudo-random bytes generated by a linear congruent
  335. generator (LCG):
  336. x(n+1) = (x(n) * 214013 + 2531011) % 2^32
  337. Use bits 23..16 of x(n) to generate a byte. */
  338. static void
  339. lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
  340. {
  341. size_t index;
  342. unsigned int x;
  343. x = x0;
  344. for (index=0; index < size; index++) {
  345. x *= 214013;
  346. x += 2531011;
  347. /* modulo 2 ^ (8 * sizeof(int)) */
  348. buffer[index] = (x >> 16) & 0xff;
  349. }
  350. }
  351. /* Fill buffer with size pseudo-random bytes from the operating system random
  352. number generator (RNG). It is suitable for most cryptographic purposes
  353. except long living private keys for asymmetric encryption.
  354. Return 0 on success, raise an exception and return -1 on error. */
  355. int
  356. _PyOS_URandom(void *buffer, Py_ssize_t size)
  357. {
  358. if (size < 0) {
  359. PyErr_Format(PyExc_ValueError,
  360. "negative argument not allowed");
  361. return -1;
  362. }
  363. if (size == 0)
  364. return 0;
  365. #ifdef MS_WINDOWS
  366. return win32_urandom((unsigned char *)buffer, size, 1);
  367. #elif defined(PY_GETENTROPY)
  368. return py_getentropy(buffer, size, 0);
  369. #else
  370. return dev_urandom_python((char*)buffer, size);
  371. #endif
  372. }
  373. void
  374. _PyRandom_Init(void)
  375. {
  376. char *env;
  377. unsigned char *secret = (unsigned char *)&_Py_HashSecret.uc;
  378. Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
  379. assert(secret_size == sizeof(_Py_HashSecret.uc));
  380. if (_Py_HashSecret_Initialized)
  381. return;
  382. _Py_HashSecret_Initialized = 1;
  383. /*
  384. Hash randomization is enabled. Generate a per-process secret,
  385. using PYTHONHASHSEED if provided.
  386. */
  387. env = Py_GETENV("PYTHONHASHSEED");
  388. if (env && *env != '\0' && strcmp(env, "random") != 0) {
  389. char *endptr = env;
  390. unsigned long seed;
  391. seed = strtoul(env, &endptr, 10);
  392. if (*endptr != '\0'
  393. || seed > 4294967295UL
  394. || (errno == ERANGE && seed == ULONG_MAX))
  395. {
  396. Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "
  397. "in range [0; 4294967295]");
  398. }
  399. if (seed == 0) {
  400. /* disable the randomized hash */
  401. memset(secret, 0, secret_size);
  402. }
  403. else {
  404. lcg_urandom(seed, secret, secret_size);
  405. }
  406. }
  407. else {
  408. #ifdef MS_WINDOWS
  409. (void)win32_urandom(secret, secret_size, 0);
  410. #elif defined(PY_GETENTROPY)
  411. (void)py_getentropy(secret, secret_size, 1);
  412. #else
  413. dev_urandom_noraise(secret, secret_size);
  414. #endif
  415. }
  416. }
  417. void
  418. _PyRandom_Fini(void)
  419. {
  420. #ifdef MS_WINDOWS
  421. if (hCryptProv) {
  422. CryptReleaseContext(hCryptProv, 0);
  423. hCryptProv = 0;
  424. }
  425. #elif defined(PY_GETENTROPY)
  426. /* nothing to clean */
  427. #else
  428. dev_urandom_close();
  429. #endif
  430. }