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.

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