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.

480 lines
12 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. - Raise an exception (if raise is non-zero) and return -1 on error:
  109. getrandom() failed with EINTR and the Python signal handler raised an
  110. exception, or getrandom() failed with a different error. */
  111. static int
  112. py_getrandom(void *buffer, Py_ssize_t size, int raise)
  113. {
  114. /* Is getrandom() supported by the running kernel?
  115. Need Linux kernel 3.17 or newer, or Solaris 11.3 or newer */
  116. static int getrandom_works = 1;
  117. /* getrandom() on Linux will block if called before the kernel has
  118. initialized the urandom entropy pool. This will cause Python
  119. to hang on startup if called very early in the boot process -
  120. see https://bugs.python.org/issue26839. To avoid this, use the
  121. GRND_NONBLOCK flag. */
  122. const int flags = GRND_NONBLOCK;
  123. char *dest;
  124. long n;
  125. if (!getrandom_works) {
  126. return 0;
  127. }
  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. if (errno == ENOSYS) {
  162. getrandom_works = 0;
  163. return 0;
  164. }
  165. if (errno == EAGAIN) {
  166. /* If we failed with EAGAIN, the entropy pool was
  167. uninitialized. In this case, we return failure to fall
  168. back to reading from /dev/urandom.
  169. Note: In this case the data read will not be random so
  170. should not be used for cryptographic purposes. Retaining
  171. the existing semantics for practical purposes. */
  172. getrandom_works = 0;
  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 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 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, raise);
  215. if (res < 0) {
  216. return -1;
  217. }
  218. if (res == 1) {
  219. return 0;
  220. }
  221. /* getrandom() is not supported by the running kernel, fall back
  222. 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 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, 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. Return 0 on success, raise an exception and return -1 on error. */
  359. int
  360. _PyOS_URandom(void *buffer, Py_ssize_t size)
  361. {
  362. return pyurandom(buffer, size, 1);
  363. }
  364. void
  365. _PyRandom_Init(void)
  366. {
  367. char *env;
  368. unsigned char *secret = (unsigned char *)&_Py_HashSecret.uc;
  369. Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
  370. Py_BUILD_ASSERT(sizeof(_Py_HashSecret_t) == sizeof(_Py_HashSecret.uc));
  371. if (_Py_HashSecret_Initialized)
  372. return;
  373. _Py_HashSecret_Initialized = 1;
  374. /*
  375. Hash randomization is enabled. Generate a per-process secret,
  376. using PYTHONHASHSEED if provided.
  377. */
  378. env = Py_GETENV("PYTHONHASHSEED");
  379. if (env && *env != '\0' && strcmp(env, "random") != 0) {
  380. char *endptr = env;
  381. unsigned long seed;
  382. seed = strtoul(env, &endptr, 10);
  383. if (*endptr != '\0'
  384. || seed > 4294967295UL
  385. || (errno == ERANGE && seed == ULONG_MAX))
  386. {
  387. Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "
  388. "in range [0; 4294967295]");
  389. }
  390. if (seed == 0) {
  391. /* disable the randomized hash */
  392. memset(secret, 0, secret_size);
  393. }
  394. else {
  395. lcg_urandom(seed, secret, secret_size);
  396. }
  397. }
  398. else {
  399. int res;
  400. /* _PyRandom_Init() is called very early in the Python initialization
  401. and so exceptions cannot be used (use raise=0). */
  402. res = pyurandom(secret, secret_size, 0);
  403. if (res < 0) {
  404. Py_FatalError("failed to get random numbers to initialize Python");
  405. }
  406. }
  407. }
  408. void
  409. _PyRandom_Fini(void)
  410. {
  411. #ifdef MS_WINDOWS
  412. if (hCryptProv) {
  413. CryptReleaseContext(hCryptProv, 0);
  414. hCryptProv = 0;
  415. }
  416. #elif defined(PY_GETENTROPY)
  417. /* nothing to clean */
  418. #else
  419. dev_urandom_close();
  420. #endif
  421. }