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.

465 lines
12 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. static int
  106. py_getrandom(void *buffer, Py_ssize_t size, int raise)
  107. {
  108. /* Is getrandom() supported by the running kernel?
  109. * Need Linux kernel 3.17 or newer, or Solaris 11.3 or newer */
  110. static int getrandom_works = 1;
  111. /* getrandom() on Linux will block if called before the kernel has
  112. * initialized the urandom entropy pool. This will cause Python
  113. * to hang on startup if called very early in the boot process -
  114. * see https://bugs.python.org/issue26839. To avoid this, use the
  115. * GRND_NONBLOCK flag. */
  116. const int flags = GRND_NONBLOCK;
  117. char *dest;
  118. int n;
  119. if (!getrandom_works)
  120. return 0;
  121. dest = buffer;
  122. while (0 < size) {
  123. #ifdef sun
  124. /* Issue #26735: On Solaris, getrandom() is limited to returning up
  125. to 1024 bytes */
  126. n = Py_MIN(size, 1024);
  127. #else
  128. n = size;
  129. #endif
  130. errno = 0;
  131. #ifdef HAVE_GETRANDOM
  132. if (raise) {
  133. Py_BEGIN_ALLOW_THREADS
  134. n = getrandom(dest, n, flags);
  135. Py_END_ALLOW_THREADS
  136. }
  137. else {
  138. n = getrandom(dest, n, flags);
  139. }
  140. #else
  141. /* On Linux, use the syscall() function because the GNU libc doesn't
  142. * expose the Linux getrandom() syscall yet. See:
  143. * https://sourceware.org/bugzilla/show_bug.cgi?id=17252 */
  144. if (raise) {
  145. Py_BEGIN_ALLOW_THREADS
  146. n = syscall(SYS_getrandom, dest, n, flags);
  147. Py_END_ALLOW_THREADS
  148. }
  149. else {
  150. n = syscall(SYS_getrandom, dest, n, flags);
  151. }
  152. #endif
  153. if (n < 0) {
  154. if (errno == ENOSYS) {
  155. getrandom_works = 0;
  156. return 0;
  157. }
  158. if (errno == EAGAIN) {
  159. /* If we failed with EAGAIN, the entropy pool was
  160. * uninitialized. In this case, we return failure to fall
  161. * back to reading from /dev/urandom.
  162. *
  163. * Note: In this case the data read will not be random so
  164. * should not be used for cryptographic purposes. Retaining
  165. * the existing semantics for practical purposes. */
  166. getrandom_works = 0;
  167. return 0;
  168. }
  169. if (errno == EINTR) {
  170. if (PyErr_CheckSignals()) {
  171. if (!raise)
  172. Py_FatalError("getrandom() interrupted by a signal");
  173. return -1;
  174. }
  175. /* retry getrandom() */
  176. continue;
  177. }
  178. if (raise)
  179. PyErr_SetFromErrno(PyExc_OSError);
  180. else
  181. Py_FatalError("getrandom() failed");
  182. return -1;
  183. }
  184. dest += n;
  185. size -= n;
  186. }
  187. return 1;
  188. }
  189. #endif
  190. static struct {
  191. int fd;
  192. dev_t st_dev;
  193. ino_t st_ino;
  194. } urandom_cache = { -1 };
  195. /* Read size bytes from /dev/urandom into buffer.
  196. Call Py_FatalError() on error. */
  197. static void
  198. dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size)
  199. {
  200. int fd;
  201. Py_ssize_t n;
  202. assert (0 < size);
  203. #ifdef PY_GETRANDOM
  204. if (py_getrandom(buffer, size, 0) == 1)
  205. return;
  206. /* getrandom() is not supported by the running kernel, fall back
  207. * on reading /dev/urandom */
  208. #endif
  209. fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
  210. if (fd < 0)
  211. Py_FatalError("Failed to open /dev/urandom");
  212. while (0 < size)
  213. {
  214. do {
  215. n = read(fd, buffer, (size_t)size);
  216. } while (n < 0 && errno == EINTR);
  217. if (n <= 0)
  218. {
  219. /* stop on error or if read(size) returned 0 */
  220. Py_FatalError("Failed to read bytes from /dev/urandom");
  221. break;
  222. }
  223. buffer += n;
  224. size -= (Py_ssize_t)n;
  225. }
  226. close(fd);
  227. }
  228. /* Read size bytes from /dev/urandom into buffer.
  229. Return 0 on success, raise an exception and return -1 on error. */
  230. static int
  231. dev_urandom_python(char *buffer, Py_ssize_t size)
  232. {
  233. int fd;
  234. Py_ssize_t n;
  235. struct _Py_stat_struct st;
  236. #ifdef PY_GETRANDOM
  237. int res;
  238. #endif
  239. if (size <= 0)
  240. return 0;
  241. #ifdef PY_GETRANDOM
  242. res = py_getrandom(buffer, size, 1);
  243. if (res < 0)
  244. return -1;
  245. if (res == 1)
  246. return 0;
  247. /* getrandom() is not supported by the running kernel, fall back
  248. * on reading /dev/urandom */
  249. #endif
  250. if (urandom_cache.fd >= 0) {
  251. /* Does the fd point to the same thing as before? (issue #21207) */
  252. if (_Py_fstat_noraise(urandom_cache.fd, &st)
  253. || st.st_dev != urandom_cache.st_dev
  254. || st.st_ino != urandom_cache.st_ino) {
  255. /* Something changed: forget the cached fd (but don't close it,
  256. since it probably points to something important for some
  257. third-party code). */
  258. urandom_cache.fd = -1;
  259. }
  260. }
  261. if (urandom_cache.fd >= 0)
  262. fd = urandom_cache.fd;
  263. else {
  264. fd = _Py_open("/dev/urandom", O_RDONLY);
  265. if (fd < 0) {
  266. if (errno == ENOENT || errno == ENXIO ||
  267. errno == ENODEV || errno == EACCES)
  268. PyErr_SetString(PyExc_NotImplementedError,
  269. "/dev/urandom (or equivalent) not found");
  270. /* otherwise, keep the OSError exception raised by _Py_open() */
  271. return -1;
  272. }
  273. if (urandom_cache.fd >= 0) {
  274. /* urandom_fd was initialized by another thread while we were
  275. not holding the GIL, keep it. */
  276. close(fd);
  277. fd = urandom_cache.fd;
  278. }
  279. else {
  280. if (_Py_fstat(fd, &st)) {
  281. close(fd);
  282. return -1;
  283. }
  284. else {
  285. urandom_cache.fd = fd;
  286. urandom_cache.st_dev = st.st_dev;
  287. urandom_cache.st_ino = st.st_ino;
  288. }
  289. }
  290. }
  291. do {
  292. n = _Py_read(fd, buffer, (size_t)size);
  293. if (n == -1)
  294. return -1;
  295. if (n == 0) {
  296. PyErr_Format(PyExc_RuntimeError,
  297. "Failed to read %zi bytes from /dev/urandom",
  298. size);
  299. return -1;
  300. }
  301. buffer += n;
  302. size -= n;
  303. } while (0 < size);
  304. return 0;
  305. }
  306. static void
  307. dev_urandom_close(void)
  308. {
  309. if (urandom_cache.fd >= 0) {
  310. close(urandom_cache.fd);
  311. urandom_cache.fd = -1;
  312. }
  313. }
  314. #endif
  315. /* Fill buffer with pseudo-random bytes generated by a linear congruent
  316. generator (LCG):
  317. x(n+1) = (x(n) * 214013 + 2531011) % 2^32
  318. Use bits 23..16 of x(n) to generate a byte. */
  319. static void
  320. lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
  321. {
  322. size_t index;
  323. unsigned int x;
  324. x = x0;
  325. for (index=0; index < size; index++) {
  326. x *= 214013;
  327. x += 2531011;
  328. /* modulo 2 ^ (8 * sizeof(int)) */
  329. buffer[index] = (x >> 16) & 0xff;
  330. }
  331. }
  332. /* Fill buffer with size pseudo-random bytes from the operating system random
  333. number generator (RNG). It is suitable for most cryptographic purposes
  334. except long living private keys for asymmetric encryption.
  335. Return 0 on success, raise an exception and return -1 on error. */
  336. int
  337. _PyOS_URandom(void *buffer, Py_ssize_t size)
  338. {
  339. if (size < 0) {
  340. PyErr_Format(PyExc_ValueError,
  341. "negative argument not allowed");
  342. return -1;
  343. }
  344. if (size == 0)
  345. return 0;
  346. #ifdef MS_WINDOWS
  347. return win32_urandom((unsigned char *)buffer, size, 1);
  348. #elif defined(PY_GETENTROPY)
  349. return py_getentropy(buffer, size, 0);
  350. #else
  351. return dev_urandom_python((char*)buffer, size);
  352. #endif
  353. }
  354. void
  355. _PyRandom_Init(void)
  356. {
  357. char *env;
  358. unsigned char *secret = (unsigned char *)&_Py_HashSecret.uc;
  359. Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
  360. Py_BUILD_ASSERT(sizeof(_Py_HashSecret_t) == sizeof(_Py_HashSecret.uc));
  361. if (_Py_HashSecret_Initialized)
  362. return;
  363. _Py_HashSecret_Initialized = 1;
  364. /*
  365. Hash randomization is enabled. Generate a per-process secret,
  366. using PYTHONHASHSEED if provided.
  367. */
  368. env = Py_GETENV("PYTHONHASHSEED");
  369. if (env && *env != '\0' && strcmp(env, "random") != 0) {
  370. char *endptr = env;
  371. unsigned long seed;
  372. seed = strtoul(env, &endptr, 10);
  373. if (*endptr != '\0'
  374. || seed > 4294967295UL
  375. || (errno == ERANGE && seed == ULONG_MAX))
  376. {
  377. Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "
  378. "in range [0; 4294967295]");
  379. }
  380. if (seed == 0) {
  381. /* disable the randomized hash */
  382. memset(secret, 0, secret_size);
  383. }
  384. else {
  385. lcg_urandom(seed, secret, secret_size);
  386. }
  387. }
  388. else {
  389. #ifdef MS_WINDOWS
  390. (void)win32_urandom(secret, secret_size, 0);
  391. #elif defined(PY_GETENTROPY)
  392. (void)py_getentropy(secret, secret_size, 1);
  393. #else
  394. dev_urandom_noraise(secret, secret_size);
  395. #endif
  396. }
  397. }
  398. void
  399. _PyRandom_Fini(void)
  400. {
  401. #ifdef MS_WINDOWS
  402. if (hCryptProv) {
  403. CryptReleaseContext(hCryptProv, 0);
  404. hCryptProv = 0;
  405. }
  406. #elif defined(PY_GETENTROPY)
  407. /* nothing to clean */
  408. #else
  409. dev_urandom_close();
  410. #endif
  411. }