Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 1 | #include "Python.h" |
| 2 | #ifdef MS_WINDOWS |
| 3 | #include <windows.h> |
| 4 | #else |
| 5 | #include <fcntl.h> |
| 6 | #endif |
| 7 | |
Benjamin Peterson | 26da920 | 2012-02-21 11:08:50 -0500 | [diff] [blame] | 8 | #ifdef Py_DEBUG |
| 9 | int _Py_HashSecret_Initialized = 0; |
| 10 | #else |
| 11 | static int _Py_HashSecret_Initialized = 0; |
| 12 | #endif |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 13 | |
| 14 | #ifdef MS_WINDOWS |
| 15 | typedef BOOL (WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv,\ |
| 16 | LPCSTR pszContainer, LPCSTR pszProvider, DWORD dwProvType,\ |
| 17 | DWORD dwFlags ); |
| 18 | typedef BOOL (WINAPI *CRYPTGENRANDOM)(HCRYPTPROV hProv, DWORD dwLen,\ |
| 19 | BYTE *pbBuffer ); |
| 20 | |
| 21 | static CRYPTGENRANDOM pCryptGenRandom = NULL; |
| 22 | /* This handle is never explicitly released. Instead, the operating |
| 23 | system will release it when the process terminates. */ |
| 24 | static HCRYPTPROV hCryptProv = 0; |
| 25 | |
| 26 | static int |
| 27 | win32_urandom_init(int raise) |
| 28 | { |
| 29 | HINSTANCE hAdvAPI32 = NULL; |
| 30 | CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL; |
| 31 | |
| 32 | /* Obtain handle to the DLL containing CryptoAPI. This should not fail. */ |
| 33 | hAdvAPI32 = GetModuleHandle("advapi32.dll"); |
| 34 | if(hAdvAPI32 == NULL) |
| 35 | goto error; |
| 36 | |
| 37 | /* Obtain pointers to the CryptoAPI functions. This will fail on some early |
| 38 | versions of Win95. */ |
| 39 | pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress( |
| 40 | hAdvAPI32, "CryptAcquireContextA"); |
| 41 | if (pCryptAcquireContext == NULL) |
| 42 | goto error; |
| 43 | |
| 44 | pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress(hAdvAPI32, |
| 45 | "CryptGenRandom"); |
| 46 | if (pCryptGenRandom == NULL) |
| 47 | goto error; |
| 48 | |
| 49 | /* Acquire context */ |
| 50 | if (! pCryptAcquireContext(&hCryptProv, NULL, NULL, |
| 51 | PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) |
| 52 | goto error; |
| 53 | |
| 54 | return 0; |
| 55 | |
| 56 | error: |
| 57 | if (raise) |
| 58 | PyErr_SetFromWindowsErr(0); |
| 59 | else |
| 60 | Py_FatalError("Failed to initialize Windows random API (CryptoGen)"); |
| 61 | return -1; |
| 62 | } |
| 63 | |
| 64 | /* Fill buffer with size pseudo-random bytes generated by the Windows CryptoGen |
| 65 | API. Return 0 on success, or -1 on error. */ |
| 66 | static int |
| 67 | win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise) |
| 68 | { |
| 69 | Py_ssize_t chunk; |
| 70 | |
| 71 | if (hCryptProv == 0) |
| 72 | { |
| 73 | if (win32_urandom_init(raise) == -1) |
| 74 | return -1; |
| 75 | } |
| 76 | |
| 77 | while (size > 0) |
| 78 | { |
| 79 | chunk = size > INT_MAX ? INT_MAX : size; |
| 80 | if (!pCryptGenRandom(hCryptProv, chunk, buffer)) |
| 81 | { |
| 82 | /* CryptGenRandom() failed */ |
| 83 | if (raise) |
| 84 | PyErr_SetFromWindowsErr(0); |
| 85 | else |
| 86 | Py_FatalError("Failed to initialized the randomized hash " |
| 87 | "secret using CryptoGen)"); |
| 88 | return -1; |
| 89 | } |
| 90 | buffer += chunk; |
| 91 | size -= chunk; |
| 92 | } |
| 93 | return 0; |
| 94 | } |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 95 | |
Martin Panter | 7740c40 | 2016-06-10 08:07:11 +0000 | [diff] [blame] | 96 | /* Issue #25003: Don't use getentropy() on Solaris (available since |
Victor Stinner | a87633e | 2015-10-01 09:57:26 +0200 | [diff] [blame] | 97 | * Solaris 11.3), it is blocking whereas os.urandom() should not block. */ |
| 98 | #elif defined(HAVE_GETENTROPY) && !defined(sun) |
| 99 | #define PY_GETENTROPY 1 |
| 100 | |
Benjamin Peterson | 27c269a | 2014-12-26 11:09:00 -0600 | [diff] [blame] | 101 | /* Fill buffer with size pseudo-random bytes generated by getentropy(). |
| 102 | Return 0 on success, or raise an exception and return -1 on error. |
| 103 | If fatal is nonzero, call Py_FatalError() instead of raising an exception |
| 104 | on error. */ |
| 105 | static int |
| 106 | py_getentropy(unsigned char *buffer, Py_ssize_t size, int fatal) |
| 107 | { |
| 108 | while (size > 0) { |
Serhiy Storchaka | e8d750c | 2015-02-16 08:05:10 +0200 | [diff] [blame] | 109 | Py_ssize_t len = size < 256 ? size : 256; |
Victor Stinner | e993245 | 2015-03-30 11:22:13 +0200 | [diff] [blame] | 110 | int res; |
| 111 | |
| 112 | if (!fatal) { |
| 113 | Py_BEGIN_ALLOW_THREADS |
| 114 | res = getentropy(buffer, len); |
| 115 | Py_END_ALLOW_THREADS |
| 116 | |
| 117 | if (res < 0) { |
Benjamin Peterson | 27c269a | 2014-12-26 11:09:00 -0600 | [diff] [blame] | 118 | PyErr_SetFromErrno(PyExc_OSError); |
| 119 | return -1; |
| 120 | } |
| 121 | } |
Victor Stinner | e993245 | 2015-03-30 11:22:13 +0200 | [diff] [blame] | 122 | else { |
| 123 | res = getentropy(buffer, len); |
| 124 | if (res < 0) |
| 125 | Py_FatalError("getentropy() failed"); |
| 126 | } |
| 127 | |
Benjamin Peterson | 27c269a | 2014-12-26 11:09:00 -0600 | [diff] [blame] | 128 | buffer += len; |
| 129 | size -= len; |
| 130 | } |
| 131 | return 0; |
| 132 | } |
| 133 | #endif |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 134 | |
| 135 | #ifdef __VMS |
| 136 | /* Use openssl random routine */ |
| 137 | #include <openssl/rand.h> |
| 138 | static int |
| 139 | vms_urandom(unsigned char *buffer, Py_ssize_t size, int raise) |
| 140 | { |
| 141 | if (RAND_pseudo_bytes(buffer, size) < 0) { |
| 142 | if (raise) { |
| 143 | PyErr_Format(PyExc_ValueError, |
| 144 | "RAND_pseudo_bytes"); |
| 145 | } else { |
| 146 | Py_FatalError("Failed to initialize the randomized hash " |
| 147 | "secret using RAND_pseudo_bytes"); |
| 148 | } |
| 149 | return -1; |
| 150 | } |
| 151 | return 0; |
| 152 | } |
| 153 | #endif /* __VMS */ |
| 154 | |
| 155 | |
| 156 | #if !defined(MS_WINDOWS) && !defined(__VMS) |
| 157 | |
Benjamin Peterson | 57057a6 | 2014-08-28 12:30:00 -0400 | [diff] [blame] | 158 | static struct { |
| 159 | int fd; |
| 160 | dev_t st_dev; |
| 161 | ino_t st_ino; |
| 162 | } urandom_cache = { -1 }; |
| 163 | |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 164 | /* Read size bytes from /dev/urandom into buffer. |
| 165 | Call Py_FatalError() on error. */ |
| 166 | static void |
Benjamin Peterson | 57057a6 | 2014-08-28 12:30:00 -0400 | [diff] [blame] | 167 | dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size) |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 168 | { |
| 169 | int fd; |
| 170 | Py_ssize_t n; |
| 171 | |
| 172 | assert (0 < size); |
| 173 | |
| 174 | fd = open("/dev/urandom", O_RDONLY); |
| 175 | if (fd < 0) |
| 176 | Py_FatalError("Failed to open /dev/urandom"); |
| 177 | |
| 178 | while (0 < size) |
| 179 | { |
| 180 | do { |
| 181 | n = read(fd, buffer, (size_t)size); |
| 182 | } while (n < 0 && errno == EINTR); |
| 183 | if (n <= 0) |
| 184 | { |
| 185 | /* stop on error or if read(size) returned 0 */ |
| 186 | Py_FatalError("Failed to read bytes from /dev/urandom"); |
| 187 | break; |
| 188 | } |
| 189 | buffer += n; |
| 190 | size -= (Py_ssize_t)n; |
| 191 | } |
| 192 | close(fd); |
| 193 | } |
| 194 | |
| 195 | /* Read size bytes from /dev/urandom into buffer. |
| 196 | Return 0 on success, raise an exception and return -1 on error. */ |
| 197 | static int |
| 198 | dev_urandom_python(char *buffer, Py_ssize_t size) |
| 199 | { |
| 200 | int fd; |
| 201 | Py_ssize_t n; |
Benjamin Peterson | 57057a6 | 2014-08-28 12:30:00 -0400 | [diff] [blame] | 202 | struct stat st; |
Victor Stinner | e0a0bd6 | 2015-02-24 14:30:43 +0100 | [diff] [blame] | 203 | int attr; |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 204 | |
| 205 | if (size <= 0) |
| 206 | return 0; |
| 207 | |
Benjamin Peterson | 57057a6 | 2014-08-28 12:30:00 -0400 | [diff] [blame] | 208 | if (urandom_cache.fd >= 0) { |
| 209 | /* Does the fd point to the same thing as before? (issue #21207) */ |
| 210 | if (fstat(urandom_cache.fd, &st) |
| 211 | || st.st_dev != urandom_cache.st_dev |
| 212 | || st.st_ino != urandom_cache.st_ino) { |
| 213 | /* Something changed: forget the cached fd (but don't close it, |
| 214 | since it probably points to something important for some |
| 215 | third-party code). */ |
| 216 | urandom_cache.fd = -1; |
| 217 | } |
| 218 | } |
| 219 | if (urandom_cache.fd >= 0) |
| 220 | fd = urandom_cache.fd; |
| 221 | else { |
| 222 | Py_BEGIN_ALLOW_THREADS |
| 223 | fd = open("/dev/urandom", O_RDONLY); |
| 224 | Py_END_ALLOW_THREADS |
| 225 | if (fd < 0) |
| 226 | { |
| 227 | if (errno == ENOENT || errno == ENXIO || |
| 228 | errno == ENODEV || errno == EACCES) |
| 229 | PyErr_SetString(PyExc_NotImplementedError, |
| 230 | "/dev/urandom (or equivalent) not found"); |
| 231 | else |
| 232 | PyErr_SetFromErrno(PyExc_OSError); |
| 233 | return -1; |
| 234 | } |
Victor Stinner | e0a0bd6 | 2015-02-24 14:30:43 +0100 | [diff] [blame] | 235 | |
| 236 | /* try to make the file descriptor non-inheritable, ignore errors */ |
| 237 | attr = fcntl(fd, F_GETFD); |
| 238 | if (attr >= 0) { |
| 239 | attr |= FD_CLOEXEC; |
| 240 | (void)fcntl(fd, F_SETFD, attr); |
| 241 | } |
| 242 | |
Benjamin Peterson | 57057a6 | 2014-08-28 12:30:00 -0400 | [diff] [blame] | 243 | if (urandom_cache.fd >= 0) { |
| 244 | /* urandom_fd was initialized by another thread while we were |
| 245 | not holding the GIL, keep it. */ |
| 246 | close(fd); |
| 247 | fd = urandom_cache.fd; |
| 248 | } |
| 249 | else { |
| 250 | if (fstat(fd, &st)) { |
| 251 | PyErr_SetFromErrno(PyExc_OSError); |
| 252 | close(fd); |
| 253 | return -1; |
| 254 | } |
| 255 | else { |
| 256 | urandom_cache.fd = fd; |
| 257 | urandom_cache.st_dev = st.st_dev; |
| 258 | urandom_cache.st_ino = st.st_ino; |
| 259 | } |
| 260 | } |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 261 | } |
| 262 | |
| 263 | Py_BEGIN_ALLOW_THREADS |
| 264 | do { |
| 265 | do { |
| 266 | n = read(fd, buffer, (size_t)size); |
| 267 | } while (n < 0 && errno == EINTR); |
| 268 | if (n <= 0) |
| 269 | break; |
| 270 | buffer += n; |
| 271 | size -= (Py_ssize_t)n; |
| 272 | } while (0 < size); |
| 273 | Py_END_ALLOW_THREADS |
| 274 | |
| 275 | if (n <= 0) |
| 276 | { |
| 277 | /* stop on error or if read(size) returned 0 */ |
| 278 | if (n < 0) |
| 279 | PyErr_SetFromErrno(PyExc_OSError); |
| 280 | else |
| 281 | PyErr_Format(PyExc_RuntimeError, |
| 282 | "Failed to read %zi bytes from /dev/urandom", |
| 283 | size); |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 284 | return -1; |
| 285 | } |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 286 | return 0; |
| 287 | } |
Benjamin Peterson | 57057a6 | 2014-08-28 12:30:00 -0400 | [diff] [blame] | 288 | |
| 289 | static void |
| 290 | dev_urandom_close(void) |
| 291 | { |
| 292 | if (urandom_cache.fd >= 0) { |
| 293 | close(urandom_cache.fd); |
| 294 | urandom_cache.fd = -1; |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 299 | #endif /* !defined(MS_WINDOWS) && !defined(__VMS) */ |
| 300 | |
| 301 | /* Fill buffer with pseudo-random bytes generated by a linear congruent |
| 302 | generator (LCG): |
| 303 | |
| 304 | x(n+1) = (x(n) * 214013 + 2531011) % 2^32 |
| 305 | |
| 306 | Use bits 23..16 of x(n) to generate a byte. */ |
| 307 | static void |
| 308 | lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size) |
| 309 | { |
| 310 | size_t index; |
| 311 | unsigned int x; |
| 312 | |
| 313 | x = x0; |
| 314 | for (index=0; index < size; index++) { |
| 315 | x *= 214013; |
| 316 | x += 2531011; |
| 317 | /* modulo 2 ^ (8 * sizeof(int)) */ |
| 318 | buffer[index] = (x >> 16) & 0xff; |
| 319 | } |
| 320 | } |
| 321 | |
Georg Brandl | c0edade | 2013-10-06 18:43:19 +0200 | [diff] [blame] | 322 | /* Fill buffer with size pseudo-random bytes from the operating system random |
Serhiy Storchaka | 0f8f784 | 2014-12-01 18:16:30 +0200 | [diff] [blame] | 323 | number generator (RNG). It is suitable for most cryptographic purposes |
Georg Brandl | c0edade | 2013-10-06 18:43:19 +0200 | [diff] [blame] | 324 | except long living private keys for asymmetric encryption. |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 325 | |
| 326 | Return 0 on success, raise an exception and return -1 on error. */ |
| 327 | int |
| 328 | _PyOS_URandom(void *buffer, Py_ssize_t size) |
| 329 | { |
| 330 | if (size < 0) { |
| 331 | PyErr_Format(PyExc_ValueError, |
| 332 | "negative argument not allowed"); |
| 333 | return -1; |
| 334 | } |
| 335 | if (size == 0) |
| 336 | return 0; |
| 337 | |
| 338 | #ifdef MS_WINDOWS |
| 339 | return win32_urandom((unsigned char *)buffer, size, 1); |
Victor Stinner | a87633e | 2015-10-01 09:57:26 +0200 | [diff] [blame] | 340 | #elif defined(PY_GETENTROPY) |
Benjamin Peterson | 27c269a | 2014-12-26 11:09:00 -0600 | [diff] [blame] | 341 | return py_getentropy(buffer, size, 0); |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 342 | #else |
| 343 | # ifdef __VMS |
| 344 | return vms_urandom((unsigned char *)buffer, size, 1); |
| 345 | # else |
| 346 | return dev_urandom_python((char*)buffer, size); |
| 347 | # endif |
| 348 | #endif |
| 349 | } |
| 350 | |
| 351 | void |
| 352 | _PyRandom_Init(void) |
| 353 | { |
| 354 | char *env; |
| 355 | void *secret = &_Py_HashSecret; |
Benjamin Peterson | 26da920 | 2012-02-21 11:08:50 -0500 | [diff] [blame] | 356 | Py_ssize_t secret_size = sizeof(_Py_HashSecret_t); |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 357 | |
Benjamin Peterson | 26da920 | 2012-02-21 11:08:50 -0500 | [diff] [blame] | 358 | if (_Py_HashSecret_Initialized) |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 359 | return; |
Benjamin Peterson | 26da920 | 2012-02-21 11:08:50 -0500 | [diff] [blame] | 360 | _Py_HashSecret_Initialized = 1; |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 361 | |
| 362 | /* |
| 363 | By default, hash randomization is disabled, and only |
| 364 | enabled if PYTHONHASHSEED is set to non-empty or if |
| 365 | "-R" is provided at the command line: |
| 366 | */ |
| 367 | if (!Py_HashRandomizationFlag) { |
| 368 | /* Disable the randomized hash: */ |
| 369 | memset(secret, 0, secret_size); |
| 370 | return; |
| 371 | } |
| 372 | |
| 373 | /* |
| 374 | Hash randomization is enabled. Generate a per-process secret, |
| 375 | using PYTHONHASHSEED if provided. |
| 376 | */ |
| 377 | |
| 378 | env = Py_GETENV("PYTHONHASHSEED"); |
| 379 | if (env && *env != '\0' && strcmp(env, "random") != 0) { |
| 380 | char *endptr = env; |
| 381 | unsigned long seed; |
| 382 | seed = strtoul(env, &endptr, 10); |
| 383 | if (*endptr != '\0' |
| 384 | || seed > 4294967295UL |
| 385 | || (errno == ERANGE && seed == ULONG_MAX)) |
| 386 | { |
| 387 | Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer " |
| 388 | "in range [0; 4294967295]"); |
| 389 | } |
| 390 | if (seed == 0) { |
| 391 | /* disable the randomized hash */ |
| 392 | memset(secret, 0, secret_size); |
| 393 | } |
| 394 | else { |
| 395 | lcg_urandom(seed, (unsigned char*)secret, secret_size); |
| 396 | } |
| 397 | } |
| 398 | else { |
| 399 | #ifdef MS_WINDOWS |
| 400 | (void)win32_urandom((unsigned char *)secret, secret_size, 0); |
Benjamin Peterson | 27c269a | 2014-12-26 11:09:00 -0600 | [diff] [blame] | 401 | #elif __VMS |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 402 | vms_urandom((unsigned char *)secret, secret_size, 0); |
Victor Stinner | a87633e | 2015-10-01 09:57:26 +0200 | [diff] [blame] | 403 | #elif defined(PY_GETENTROPY) |
Benjamin Peterson | 27c269a | 2014-12-26 11:09:00 -0600 | [diff] [blame] | 404 | (void)py_getentropy(secret, secret_size, 1); |
| 405 | #else |
| 406 | dev_urandom_noraise(secret, secret_size); |
Barry Warsaw | 1e13eb0 | 2012-02-20 20:42:21 -0500 | [diff] [blame] | 407 | #endif |
| 408 | } |
| 409 | } |
Benjamin Peterson | 57057a6 | 2014-08-28 12:30:00 -0400 | [diff] [blame] | 410 | |
| 411 | void |
| 412 | _PyRandom_Fini(void) |
| 413 | { |
| 414 | #ifdef MS_WINDOWS |
| 415 | if (hCryptProv) { |
| 416 | CryptReleaseContext(hCryptProv, 0); |
| 417 | hCryptProv = 0; |
| 418 | } |
Victor Stinner | a87633e | 2015-10-01 09:57:26 +0200 | [diff] [blame] | 419 | #elif defined(PY_GETENTROPY) |
Benjamin Peterson | 27c269a | 2014-12-26 11:09:00 -0600 | [diff] [blame] | 420 | /* nothing to clean */ |
Benjamin Peterson | 57057a6 | 2014-08-28 12:30:00 -0400 | [diff] [blame] | 421 | #else |
| 422 | dev_urandom_close(); |
| 423 | #endif |
| 424 | } |