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.

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