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.

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