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.

338 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("/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 stat 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 (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. Py_BEGIN_ALLOW_THREADS
  144. fd = _Py_open("/dev/urandom", O_RDONLY);
  145. Py_END_ALLOW_THREADS
  146. if (fd < 0)
  147. {
  148. if (errno == ENOENT || errno == ENXIO ||
  149. errno == ENODEV || errno == EACCES)
  150. PyErr_SetString(PyExc_NotImplementedError,
  151. "/dev/urandom (or equivalent) not found");
  152. else
  153. PyErr_SetFromErrno(PyExc_OSError);
  154. return -1;
  155. }
  156. if (urandom_cache.fd >= 0) {
  157. /* urandom_fd was initialized by another thread while we were
  158. not holding the GIL, keep it. */
  159. close(fd);
  160. fd = urandom_cache.fd;
  161. }
  162. else {
  163. if (fstat(fd, &st)) {
  164. PyErr_SetFromErrno(PyExc_OSError);
  165. close(fd);
  166. return -1;
  167. }
  168. else {
  169. urandom_cache.fd = fd;
  170. urandom_cache.st_dev = st.st_dev;
  171. urandom_cache.st_ino = st.st_ino;
  172. }
  173. }
  174. }
  175. Py_BEGIN_ALLOW_THREADS
  176. do {
  177. do {
  178. n = read(fd, buffer, (size_t)size);
  179. } while (n < 0 && errno == EINTR);
  180. if (n <= 0)
  181. break;
  182. buffer += n;
  183. size -= (Py_ssize_t)n;
  184. } while (0 < size);
  185. Py_END_ALLOW_THREADS
  186. if (n <= 0)
  187. {
  188. /* stop on error or if read(size) returned 0 */
  189. if (n < 0)
  190. PyErr_SetFromErrno(PyExc_OSError);
  191. else
  192. PyErr_Format(PyExc_RuntimeError,
  193. "Failed to read %zi bytes from /dev/urandom",
  194. size);
  195. return -1;
  196. }
  197. return 0;
  198. }
  199. static void
  200. dev_urandom_close(void)
  201. {
  202. if (urandom_cache.fd >= 0) {
  203. close(urandom_cache.fd);
  204. urandom_cache.fd = -1;
  205. }
  206. }
  207. #endif /* HAVE_GETENTROPY */
  208. /* Fill buffer with pseudo-random bytes generated by a linear congruent
  209. generator (LCG):
  210. x(n+1) = (x(n) * 214013 + 2531011) % 2^32
  211. Use bits 23..16 of x(n) to generate a byte. */
  212. static void
  213. lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
  214. {
  215. size_t index;
  216. unsigned int x;
  217. x = x0;
  218. for (index=0; index < size; index++) {
  219. x *= 214013;
  220. x += 2531011;
  221. /* modulo 2 ^ (8 * sizeof(int)) */
  222. buffer[index] = (x >> 16) & 0xff;
  223. }
  224. }
  225. /* Fill buffer with size pseudo-random bytes from the operating system random
  226. number generator (RNG). It is suitable for most cryptographic purposes
  227. except long living private keys for asymmetric encryption.
  228. Return 0 on success, raise an exception and return -1 on error. */
  229. int
  230. _PyOS_URandom(void *buffer, Py_ssize_t size)
  231. {
  232. if (size < 0) {
  233. PyErr_Format(PyExc_ValueError,
  234. "negative argument not allowed");
  235. return -1;
  236. }
  237. if (size == 0)
  238. return 0;
  239. #ifdef MS_WINDOWS
  240. return win32_urandom((unsigned char *)buffer, size, 1);
  241. #elif HAVE_GETENTROPY
  242. return py_getentropy(buffer, size, 0);
  243. #else
  244. return dev_urandom_python((char*)buffer, size);
  245. #endif
  246. }
  247. void
  248. _PyRandom_Init(void)
  249. {
  250. char *env;
  251. unsigned char *secret = (unsigned char *)&_Py_HashSecret.uc;
  252. Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
  253. assert(secret_size == sizeof(_Py_HashSecret.uc));
  254. if (_Py_HashSecret_Initialized)
  255. return;
  256. _Py_HashSecret_Initialized = 1;
  257. /*
  258. Hash randomization is enabled. Generate a per-process secret,
  259. using PYTHONHASHSEED if provided.
  260. */
  261. env = Py_GETENV("PYTHONHASHSEED");
  262. if (env && *env != '\0' && strcmp(env, "random") != 0) {
  263. char *endptr = env;
  264. unsigned long seed;
  265. seed = strtoul(env, &endptr, 10);
  266. if (*endptr != '\0'
  267. || seed > 4294967295UL
  268. || (errno == ERANGE && seed == ULONG_MAX))
  269. {
  270. Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "
  271. "in range [0; 4294967295]");
  272. }
  273. if (seed == 0) {
  274. /* disable the randomized hash */
  275. memset(secret, 0, secret_size);
  276. }
  277. else {
  278. lcg_urandom(seed, secret, secret_size);
  279. }
  280. }
  281. else {
  282. #ifdef MS_WINDOWS
  283. (void)win32_urandom(secret, secret_size, 0);
  284. #elif HAVE_GETENTROPY
  285. (void)py_getentropy(secret, secret_size, 1);
  286. #else
  287. dev_urandom_noraise(secret, secret_size);
  288. #endif
  289. }
  290. }
  291. void
  292. _PyRandom_Fini(void)
  293. {
  294. #ifdef MS_WINDOWS
  295. if (hCryptProv) {
  296. CryptReleaseContext(hCryptProv, 0);
  297. hCryptProv = 0;
  298. }
  299. #elif HAVE_GETENTROPY
  300. /* nothing to clean */
  301. #else
  302. dev_urandom_close();
  303. #endif
  304. }