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.

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