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.

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