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.

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