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.

495 lines
13 KiB

  1. #include "Python.h"
  2. #ifdef MS_WINDOWS
  3. # include <windows.h>
  4. /* All sample MSDN wincrypt programs include the header below. It is at least
  5. * required with Min GW. */
  6. # include <wincrypt.h>
  7. #else
  8. # include <fcntl.h>
  9. # ifdef HAVE_SYS_STAT_H
  10. # include <sys/stat.h>
  11. # endif
  12. # ifdef HAVE_LINUX_RANDOM_H
  13. # include <linux/random.h>
  14. # endif
  15. # ifdef HAVE_GETRANDOM
  16. # include <sys/random.h>
  17. # elif defined(HAVE_GETRANDOM_SYSCALL)
  18. # include <sys/syscall.h>
  19. # endif
  20. #endif
  21. #ifdef Py_DEBUG
  22. int _Py_HashSecret_Initialized = 0;
  23. #else
  24. static int _Py_HashSecret_Initialized = 0;
  25. #endif
  26. #ifdef MS_WINDOWS
  27. static HCRYPTPROV hCryptProv = 0;
  28. static int
  29. win32_urandom_init(int raise)
  30. {
  31. /* Acquire context */
  32. if (!CryptAcquireContext(&hCryptProv, NULL, NULL,
  33. PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
  34. goto error;
  35. return 0;
  36. error:
  37. if (raise) {
  38. PyErr_SetFromWindowsErr(0);
  39. }
  40. return -1;
  41. }
  42. /* Fill buffer with size pseudo-random bytes generated by the Windows CryptoGen
  43. API. Return 0 on success, or raise an exception and return -1 on error. */
  44. static int
  45. win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise)
  46. {
  47. Py_ssize_t chunk;
  48. if (hCryptProv == 0)
  49. {
  50. if (win32_urandom_init(raise) == -1) {
  51. return -1;
  52. }
  53. }
  54. while (size > 0)
  55. {
  56. chunk = size > INT_MAX ? INT_MAX : size;
  57. if (!CryptGenRandom(hCryptProv, (DWORD)chunk, buffer))
  58. {
  59. /* CryptGenRandom() failed */
  60. if (raise) {
  61. PyErr_SetFromWindowsErr(0);
  62. }
  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 raise is zero, don't raise an exception on error. */
  77. static int
  78. py_getentropy(char *buffer, Py_ssize_t size, int raise)
  79. {
  80. while (size > 0) {
  81. Py_ssize_t len = Py_MIN(size, 256);
  82. int res;
  83. if (raise) {
  84. Py_BEGIN_ALLOW_THREADS
  85. res = getentropy(buffer, len);
  86. Py_END_ALLOW_THREADS
  87. }
  88. else {
  89. res = getentropy(buffer, len);
  90. }
  91. if (res < 0) {
  92. if (raise) {
  93. PyErr_SetFromErrno(PyExc_OSError);
  94. }
  95. return -1;
  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 (fails with ENOSYS)
  108. or if getrandom(GRND_NONBLOCK) fails with EAGAIN (blocking=0 and system
  109. urandom 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 blocking, int raise)
  115. {
  116. /* Is getrandom() supported by the running kernel? Set to 0 if getrandom()
  117. fails with ENOSYS. Need Linux kernel 3.17 or newer, or Solaris 11.3
  118. or newer */
  119. static int getrandom_works = 1;
  120. int flags;
  121. char *dest;
  122. long n;
  123. if (!getrandom_works) {
  124. return 0;
  125. }
  126. flags = blocking ? 0 : GRND_NONBLOCK;
  127. dest = buffer;
  128. while (0 < size) {
  129. #ifdef sun
  130. /* Issue #26735: On Solaris, getrandom() is limited to returning up
  131. to 1024 bytes */
  132. n = Py_MIN(size, 1024);
  133. #else
  134. n = Py_MIN(size, LONG_MAX);
  135. #endif
  136. errno = 0;
  137. #ifdef HAVE_GETRANDOM
  138. if (raise) {
  139. Py_BEGIN_ALLOW_THREADS
  140. n = getrandom(dest, n, flags);
  141. Py_END_ALLOW_THREADS
  142. }
  143. else {
  144. n = getrandom(dest, n, flags);
  145. }
  146. #else
  147. /* On Linux, use the syscall() function because the GNU libc doesn't
  148. expose the Linux getrandom() syscall yet. See:
  149. https://sourceware.org/bugzilla/show_bug.cgi?id=17252 */
  150. if (raise) {
  151. Py_BEGIN_ALLOW_THREADS
  152. n = syscall(SYS_getrandom, dest, n, flags);
  153. Py_END_ALLOW_THREADS
  154. }
  155. else {
  156. n = syscall(SYS_getrandom, dest, n, flags);
  157. }
  158. #endif
  159. if (n < 0) {
  160. if (errno == ENOSYS) {
  161. getrandom_works = 0;
  162. return 0;
  163. }
  164. /* getrandom(GRND_NONBLOCK) fails with EAGAIN if the system urandom
  165. is not initialiazed yet. For _PyRandom_Init(), we ignore their
  166. error and fall back on reading /dev/urandom which never blocks,
  167. even if the system urandom is not initialized yet. */
  168. if (errno == EAGAIN && !raise && !blocking) {
  169. return 0;
  170. }
  171. if (errno == EINTR) {
  172. if (raise) {
  173. if (PyErr_CheckSignals()) {
  174. return -1;
  175. }
  176. }
  177. /* retry getrandom() if it was interrupted by a signal */
  178. continue;
  179. }
  180. if (raise) {
  181. PyErr_SetFromErrno(PyExc_OSError);
  182. }
  183. return -1;
  184. }
  185. dest += n;
  186. size -= n;
  187. }
  188. return 1;
  189. }
  190. #endif
  191. static struct {
  192. int fd;
  193. dev_t st_dev;
  194. ino_t st_ino;
  195. } urandom_cache = { -1 };
  196. /* Read 'size' random bytes from py_getrandom(). Fall back on reading from
  197. /dev/urandom if getrandom() is not available.
  198. Return 0 on success. Raise an exception (if raise is non-zero) and return -1
  199. on error. */
  200. static int
  201. dev_urandom(char *buffer, Py_ssize_t size, int blocking, int raise)
  202. {
  203. int fd;
  204. Py_ssize_t n;
  205. #ifdef PY_GETRANDOM
  206. int res;
  207. #endif
  208. assert(size > 0);
  209. #ifdef PY_GETRANDOM
  210. res = py_getrandom(buffer, size, blocking, raise);
  211. if (res < 0) {
  212. return -1;
  213. }
  214. if (res == 1) {
  215. return 0;
  216. }
  217. /* getrandom() is not supported by the running kernel, fall back
  218. on reading /dev/urandom */
  219. #endif
  220. if (raise) {
  221. struct _Py_stat_struct st;
  222. if (urandom_cache.fd >= 0) {
  223. /* Does the fd point to the same thing as before? (issue #21207) */
  224. if (_Py_fstat_noraise(urandom_cache.fd, &st)
  225. || st.st_dev != urandom_cache.st_dev
  226. || st.st_ino != urandom_cache.st_ino) {
  227. /* Something changed: forget the cached fd (but don't close it,
  228. since it probably points to something important for some
  229. third-party code). */
  230. urandom_cache.fd = -1;
  231. }
  232. }
  233. if (urandom_cache.fd >= 0)
  234. fd = urandom_cache.fd;
  235. else {
  236. fd = _Py_open("/dev/urandom", O_RDONLY);
  237. if (fd < 0) {
  238. if (errno == ENOENT || errno == ENXIO ||
  239. errno == ENODEV || errno == EACCES)
  240. PyErr_SetString(PyExc_NotImplementedError,
  241. "/dev/urandom (or equivalent) not found");
  242. /* otherwise, keep the OSError exception raised by _Py_open() */
  243. return -1;
  244. }
  245. if (urandom_cache.fd >= 0) {
  246. /* urandom_fd was initialized by another thread while we were
  247. not holding the GIL, keep it. */
  248. close(fd);
  249. fd = urandom_cache.fd;
  250. }
  251. else {
  252. if (_Py_fstat(fd, &st)) {
  253. close(fd);
  254. return -1;
  255. }
  256. else {
  257. urandom_cache.fd = fd;
  258. urandom_cache.st_dev = st.st_dev;
  259. urandom_cache.st_ino = st.st_ino;
  260. }
  261. }
  262. }
  263. do {
  264. n = _Py_read(fd, buffer, (size_t)size);
  265. if (n == -1)
  266. return -1;
  267. if (n == 0) {
  268. PyErr_Format(PyExc_RuntimeError,
  269. "Failed to read %zi bytes from /dev/urandom",
  270. size);
  271. return -1;
  272. }
  273. buffer += n;
  274. size -= n;
  275. } while (0 < size);
  276. }
  277. else {
  278. fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
  279. if (fd < 0) {
  280. return -1;
  281. }
  282. while (0 < size)
  283. {
  284. do {
  285. n = read(fd, buffer, (size_t)size);
  286. } while (n < 0 && errno == EINTR);
  287. if (n <= 0) {
  288. /* stop on error or if read(size) returned 0 */
  289. close(fd);
  290. return -1;
  291. }
  292. buffer += n;
  293. size -= n;
  294. }
  295. close(fd);
  296. }
  297. return 0;
  298. }
  299. static void
  300. dev_urandom_close(void)
  301. {
  302. if (urandom_cache.fd >= 0) {
  303. close(urandom_cache.fd);
  304. urandom_cache.fd = -1;
  305. }
  306. }
  307. #endif
  308. /* Fill buffer with pseudo-random bytes generated by a linear congruent
  309. generator (LCG):
  310. x(n+1) = (x(n) * 214013 + 2531011) % 2^32
  311. Use bits 23..16 of x(n) to generate a byte. */
  312. static void
  313. lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
  314. {
  315. size_t index;
  316. unsigned int x;
  317. x = x0;
  318. for (index=0; index < size; index++) {
  319. x *= 214013;
  320. x += 2531011;
  321. /* modulo 2 ^ (8 * sizeof(int)) */
  322. buffer[index] = (x >> 16) & 0xff;
  323. }
  324. }
  325. /* If raise is zero:
  326. - Don't raise exceptions on error
  327. - Don't call PyErr_CheckSignals() on EINTR (retry directly the interrupted
  328. syscall)
  329. - Don't release the GIL to call syscalls. */
  330. static int
  331. pyurandom(void *buffer, Py_ssize_t size, int blocking, int raise)
  332. {
  333. if (size < 0) {
  334. if (raise) {
  335. PyErr_Format(PyExc_ValueError,
  336. "negative argument not allowed");
  337. }
  338. return -1;
  339. }
  340. if (size == 0) {
  341. return 0;
  342. }
  343. #ifdef MS_WINDOWS
  344. return win32_urandom((unsigned char *)buffer, size, raise);
  345. #elif defined(PY_GETENTROPY)
  346. return py_getentropy(buffer, size, raise);
  347. #else
  348. return dev_urandom(buffer, size, blocking, raise);
  349. #endif
  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. On Linux 3.17 and newer, the getrandom() syscall is used in blocking mode:
  355. block until the system urandom entropy pool is initialized (128 bits are
  356. collected by the kernel).
  357. Return 0 on success. Raise an exception and return -1 on error. */
  358. int
  359. _PyOS_URandom(void *buffer, Py_ssize_t size)
  360. {
  361. return pyurandom(buffer, size, 1, 1);
  362. }
  363. /* Fill buffer with size pseudo-random bytes from the operating system random
  364. number generator (RNG). It is not suitable for cryptographic purpose.
  365. On Linux 3.17 and newer (when getrandom() syscall is used), if the system
  366. urandom is not initialized yet, the function returns "weak" entropy read
  367. from /dev/urandom.
  368. Return 0 on success. Raise an exception and return -1 on error. */
  369. int
  370. _PyOS_URandomNonblock(void *buffer, Py_ssize_t size)
  371. {
  372. return pyurandom(buffer, size, 0, 1);
  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. Py_BUILD_ASSERT(sizeof(_Py_HashSecret_t) == 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. int res;
  410. /* _PyRandom_Init() is called very early in the Python initialization
  411. and so exceptions cannot be used (use raise=0).
  412. _PyRandom_Init() must not block Python initialization: call
  413. pyurandom() is non-blocking mode (blocking=0): see the PEP 524. */
  414. res = pyurandom(secret, secret_size, 0, 0);
  415. if (res < 0) {
  416. Py_FatalError("failed to get random numbers to initialize Python");
  417. }
  418. }
  419. }
  420. void
  421. _PyRandom_Fini(void)
  422. {
  423. #ifdef MS_WINDOWS
  424. if (hCryptProv) {
  425. CryptReleaseContext(hCryptProv, 0);
  426. hCryptProv = 0;
  427. }
  428. #elif defined(PY_GETENTROPY)
  429. /* nothing to clean */
  430. #else
  431. dev_urandom_close();
  432. #endif
  433. }