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.

409 lines
10 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_GETRANDOM_SYSCALL
  10. # include <sys/syscall.h>
  11. # endif
  12. #endif
  13. #ifdef Py_DEBUG
  14. int _Py_HashSecret_Initialized = 0;
  15. #else
  16. static int _Py_HashSecret_Initialized = 0;
  17. #endif
  18. #ifdef MS_WINDOWS
  19. static HCRYPTPROV hCryptProv = 0;
  20. static int
  21. win32_urandom_init(int raise)
  22. {
  23. /* Acquire context */
  24. if (!CryptAcquireContext(&hCryptProv, NULL, NULL,
  25. PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
  26. goto error;
  27. return 0;
  28. error:
  29. if (raise)
  30. PyErr_SetFromWindowsErr(0);
  31. else
  32. Py_FatalError("Failed to initialize Windows random API (CryptoGen)");
  33. return -1;
  34. }
  35. /* Fill buffer with size pseudo-random bytes generated by the Windows CryptoGen
  36. API. Return 0 on success, or raise an exception and return -1 on error. */
  37. static int
  38. win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise)
  39. {
  40. Py_ssize_t chunk;
  41. if (hCryptProv == 0)
  42. {
  43. if (win32_urandom_init(raise) == -1)
  44. return -1;
  45. }
  46. while (size > 0)
  47. {
  48. chunk = size > INT_MAX ? INT_MAX : size;
  49. if (!CryptGenRandom(hCryptProv, (DWORD)chunk, buffer))
  50. {
  51. /* CryptGenRandom() failed */
  52. if (raise)
  53. PyErr_SetFromWindowsErr(0);
  54. else
  55. Py_FatalError("Failed to initialized the randomized hash "
  56. "secret using CryptoGen)");
  57. return -1;
  58. }
  59. buffer += chunk;
  60. size -= chunk;
  61. }
  62. return 0;
  63. }
  64. #elif HAVE_GETENTROPY
  65. /* Fill buffer with size pseudo-random bytes generated by getentropy().
  66. Return 0 on success, or raise an exception and return -1 on error.
  67. If fatal is nonzero, call Py_FatalError() instead of raising an exception
  68. on error. */
  69. static int
  70. py_getentropy(unsigned char *buffer, Py_ssize_t size, int fatal)
  71. {
  72. while (size > 0) {
  73. Py_ssize_t len = Py_MIN(size, 256);
  74. int res = getentropy(buffer, len);
  75. if (res < 0) {
  76. if (fatal) {
  77. Py_FatalError("getentropy() failed");
  78. }
  79. else {
  80. PyErr_SetFromErrno(PyExc_OSError);
  81. return -1;
  82. }
  83. }
  84. buffer += len;
  85. size -= len;
  86. }
  87. return 0;
  88. }
  89. #else /* !HAVE_GETENTROPY */
  90. #ifdef HAVE_GETRANDOM_SYSCALL
  91. static int
  92. py_getrandom(void *buffer, Py_ssize_t size, int raise)
  93. {
  94. /* is getrandom() supported by the running kernel?
  95. * need Linux kernel 3.17 or later */
  96. static int getrandom_works = 1;
  97. /* Use /dev/urandom, block if the kernel has no entropy */
  98. const int flags = 0;
  99. int n;
  100. if (!getrandom_works)
  101. return 0;
  102. while (0 < size) {
  103. errno = 0;
  104. /* Use syscall() because the libc doesn't expose getrandom() yet, see:
  105. * https://sourceware.org/bugzilla/show_bug.cgi?id=17252 */
  106. if (raise) {
  107. Py_BEGIN_ALLOW_THREADS
  108. n = syscall(SYS_getrandom, buffer, size, flags);
  109. Py_END_ALLOW_THREADS
  110. }
  111. else {
  112. n = syscall(SYS_getrandom, buffer, size, flags);
  113. }
  114. if (n < 0) {
  115. if (errno == ENOSYS) {
  116. getrandom_works = 0;
  117. return 0;
  118. }
  119. if (errno == EINTR) {
  120. /* Note: EINTR should not occur with flags=0 */
  121. if (PyErr_CheckSignals()) {
  122. if (!raise)
  123. Py_FatalError("getrandom() interrupted by a signal");
  124. return -1;
  125. }
  126. /* retry getrandom() */
  127. continue;
  128. }
  129. if (raise)
  130. PyErr_SetFromErrno(PyExc_OSError);
  131. else
  132. Py_FatalError("getrandom() failed");
  133. return -1;
  134. }
  135. buffer += n;
  136. size -= n;
  137. }
  138. return 1;
  139. }
  140. #endif
  141. static struct {
  142. int fd;
  143. dev_t st_dev;
  144. ino_t st_ino;
  145. } urandom_cache = { -1 };
  146. /* Read size bytes from /dev/urandom into buffer.
  147. Call Py_FatalError() on error. */
  148. static void
  149. dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size)
  150. {
  151. int fd;
  152. Py_ssize_t n;
  153. assert (0 < size);
  154. #ifdef HAVE_GETRANDOM_SYSCALL
  155. if (py_getrandom(buffer, size, 0) == 1)
  156. return;
  157. /* getrandom() is not supported by the running kernel, fall back
  158. * on reading /dev/urandom */
  159. #endif
  160. fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
  161. if (fd < 0)
  162. Py_FatalError("Failed to open /dev/urandom");
  163. while (0 < size)
  164. {
  165. do {
  166. n = read(fd, buffer, (size_t)size);
  167. } while (n < 0 && errno == EINTR);
  168. if (n <= 0)
  169. {
  170. /* stop on error or if read(size) returned 0 */
  171. Py_FatalError("Failed to read bytes from /dev/urandom");
  172. break;
  173. }
  174. buffer += n;
  175. size -= (Py_ssize_t)n;
  176. }
  177. close(fd);
  178. }
  179. /* Read size bytes from /dev/urandom into buffer.
  180. Return 0 on success, raise an exception and return -1 on error. */
  181. static int
  182. dev_urandom_python(char *buffer, Py_ssize_t size)
  183. {
  184. int fd;
  185. Py_ssize_t n;
  186. struct _Py_stat_struct st;
  187. #ifdef HAVE_GETRANDOM_SYSCALL
  188. int res;
  189. #endif
  190. if (size <= 0)
  191. return 0;
  192. #ifdef HAVE_GETRANDOM_SYSCALL
  193. res = py_getrandom(buffer, size, 1);
  194. if (res < 0)
  195. return -1;
  196. if (res == 1)
  197. return 0;
  198. /* getrandom() is not supported by the running kernel, fall back
  199. * on reading /dev/urandom */
  200. #endif
  201. if (urandom_cache.fd >= 0) {
  202. /* Does the fd point to the same thing as before? (issue #21207) */
  203. if (_Py_fstat_noraise(urandom_cache.fd, &st)
  204. || st.st_dev != urandom_cache.st_dev
  205. || st.st_ino != urandom_cache.st_ino) {
  206. /* Something changed: forget the cached fd (but don't close it,
  207. since it probably points to something important for some
  208. third-party code). */
  209. urandom_cache.fd = -1;
  210. }
  211. }
  212. if (urandom_cache.fd >= 0)
  213. fd = urandom_cache.fd;
  214. else {
  215. fd = _Py_open("/dev/urandom", O_RDONLY);
  216. if (fd < 0) {
  217. if (errno == ENOENT || errno == ENXIO ||
  218. errno == ENODEV || errno == EACCES)
  219. PyErr_SetString(PyExc_NotImplementedError,
  220. "/dev/urandom (or equivalent) not found");
  221. /* otherwise, keep the OSError exception raised by _Py_open() */
  222. return -1;
  223. }
  224. if (urandom_cache.fd >= 0) {
  225. /* urandom_fd was initialized by another thread while we were
  226. not holding the GIL, keep it. */
  227. close(fd);
  228. fd = urandom_cache.fd;
  229. }
  230. else {
  231. if (_Py_fstat(fd, &st)) {
  232. close(fd);
  233. return -1;
  234. }
  235. else {
  236. urandom_cache.fd = fd;
  237. urandom_cache.st_dev = st.st_dev;
  238. urandom_cache.st_ino = st.st_ino;
  239. }
  240. }
  241. }
  242. do {
  243. n = _Py_read(fd, buffer, (size_t)size);
  244. if (n == -1)
  245. return -1;
  246. if (n == 0) {
  247. PyErr_Format(PyExc_RuntimeError,
  248. "Failed to read %zi bytes from /dev/urandom",
  249. size);
  250. return -1;
  251. }
  252. buffer += n;
  253. size -= n;
  254. } while (0 < size);
  255. return 0;
  256. }
  257. static void
  258. dev_urandom_close(void)
  259. {
  260. if (urandom_cache.fd >= 0) {
  261. close(urandom_cache.fd);
  262. urandom_cache.fd = -1;
  263. }
  264. }
  265. #endif /* HAVE_GETENTROPY */
  266. /* Fill buffer with pseudo-random bytes generated by a linear congruent
  267. generator (LCG):
  268. x(n+1) = (x(n) * 214013 + 2531011) % 2^32
  269. Use bits 23..16 of x(n) to generate a byte. */
  270. static void
  271. lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
  272. {
  273. size_t index;
  274. unsigned int x;
  275. x = x0;
  276. for (index=0; index < size; index++) {
  277. x *= 214013;
  278. x += 2531011;
  279. /* modulo 2 ^ (8 * sizeof(int)) */
  280. buffer[index] = (x >> 16) & 0xff;
  281. }
  282. }
  283. /* Fill buffer with size pseudo-random bytes from the operating system random
  284. number generator (RNG). It is suitable for most cryptographic purposes
  285. except long living private keys for asymmetric encryption.
  286. Return 0 on success, raise an exception and return -1 on error. */
  287. int
  288. _PyOS_URandom(void *buffer, Py_ssize_t size)
  289. {
  290. if (size < 0) {
  291. PyErr_Format(PyExc_ValueError,
  292. "negative argument not allowed");
  293. return -1;
  294. }
  295. if (size == 0)
  296. return 0;
  297. #ifdef MS_WINDOWS
  298. return win32_urandom((unsigned char *)buffer, size, 1);
  299. #elif HAVE_GETENTROPY
  300. return py_getentropy(buffer, size, 0);
  301. #else
  302. return dev_urandom_python((char*)buffer, size);
  303. #endif
  304. }
  305. void
  306. _PyRandom_Init(void)
  307. {
  308. char *env;
  309. unsigned char *secret = (unsigned char *)&_Py_HashSecret.uc;
  310. Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
  311. assert(secret_size == sizeof(_Py_HashSecret.uc));
  312. if (_Py_HashSecret_Initialized)
  313. return;
  314. _Py_HashSecret_Initialized = 1;
  315. /*
  316. Hash randomization is enabled. Generate a per-process secret,
  317. using PYTHONHASHSEED if provided.
  318. */
  319. env = Py_GETENV("PYTHONHASHSEED");
  320. if (env && *env != '\0' && strcmp(env, "random") != 0) {
  321. char *endptr = env;
  322. unsigned long seed;
  323. seed = strtoul(env, &endptr, 10);
  324. if (*endptr != '\0'
  325. || seed > 4294967295UL
  326. || (errno == ERANGE && seed == ULONG_MAX))
  327. {
  328. Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "
  329. "in range [0; 4294967295]");
  330. }
  331. if (seed == 0) {
  332. /* disable the randomized hash */
  333. memset(secret, 0, secret_size);
  334. }
  335. else {
  336. lcg_urandom(seed, secret, secret_size);
  337. }
  338. }
  339. else {
  340. #ifdef MS_WINDOWS
  341. (void)win32_urandom(secret, secret_size, 0);
  342. #elif HAVE_GETENTROPY
  343. (void)py_getentropy(secret, secret_size, 1);
  344. #else
  345. dev_urandom_noraise(secret, secret_size);
  346. #endif
  347. }
  348. }
  349. void
  350. _PyRandom_Fini(void)
  351. {
  352. #ifdef MS_WINDOWS
  353. if (hCryptProv) {
  354. CryptReleaseContext(hCryptProv, 0);
  355. hCryptProv = 0;
  356. }
  357. #elif HAVE_GETENTROPY
  358. /* nothing to clean */
  359. #else
  360. dev_urandom_close();
  361. #endif
  362. }