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.

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