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.

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