blob: 945269a2f6c84c68bc698b1d1cceae3dfaf4c954 [file] [log] [blame]
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001#include "Python.h"
2#ifdef MS_WINDOWS
Victor Stinner59f7fb22015-03-18 14:39:33 +01003# include <windows.h>
Martin Panterd2f87472016-07-29 04:00:44 +00004/* All sample MSDN wincrypt programs include the header below. It is at least
5 * required with Min GW. */
6# include <wincrypt.h>
Georg Brandl2daf6ae2012-02-20 19:54:16 +01007#else
Victor Stinner59f7fb22015-03-18 14:39:33 +01008# include <fcntl.h>
9# ifdef HAVE_SYS_STAT_H
10# include <sys/stat.h>
11# endif
Victor Stinnerdddf4842016-06-07 11:21:42 +020012# ifdef HAVE_LINUX_RANDOM_H
13# include <linux/random.h>
14# endif
Victor Stinnerbae2d622015-10-01 09:47:30 +020015# ifdef HAVE_GETRANDOM
16# include <sys/random.h>
17# elif defined(HAVE_GETRANDOM_SYSCALL)
Victor Stinner59f7fb22015-03-18 14:39:33 +010018# include <sys/syscall.h>
Victor Stinner59f7fb22015-03-18 14:39:33 +010019# endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +010020#endif
21
Benjamin Peterson69e97272012-02-21 11:08:50 -050022#ifdef Py_DEBUG
23int _Py_HashSecret_Initialized = 0;
24#else
25static int _Py_HashSecret_Initialized = 0;
26#endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +010027
28#ifdef MS_WINDOWS
Georg Brandl2daf6ae2012-02-20 19:54:16 +010029static HCRYPTPROV hCryptProv = 0;
30
31static int
32win32_urandom_init(int raise)
33{
Georg Brandl2daf6ae2012-02-20 19:54:16 +010034 /* Acquire context */
Martin v. Löwis3f50bf62013-01-25 14:06:18 +010035 if (!CryptAcquireContext(&hCryptProv, NULL, NULL,
36 PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
Georg Brandl2daf6ae2012-02-20 19:54:16 +010037 goto error;
38
39 return 0;
40
41error:
42 if (raise)
43 PyErr_SetFromWindowsErr(0);
44 else
45 Py_FatalError("Failed to initialize Windows random API (CryptoGen)");
46 return -1;
47}
48
49/* Fill buffer with size pseudo-random bytes generated by the Windows CryptoGen
Victor Stinner4d6a3d62014-12-21 01:16:38 +010050 API. Return 0 on success, or raise an exception and return -1 on error. */
Georg Brandl2daf6ae2012-02-20 19:54:16 +010051static int
52win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise)
53{
54 Py_ssize_t chunk;
55
56 if (hCryptProv == 0)
57 {
58 if (win32_urandom_init(raise) == -1)
59 return -1;
60 }
61
62 while (size > 0)
63 {
64 chunk = size > INT_MAX ? INT_MAX : size;
Victor Stinner0c083462013-11-15 23:26:25 +010065 if (!CryptGenRandom(hCryptProv, (DWORD)chunk, buffer))
Georg Brandl2daf6ae2012-02-20 19:54:16 +010066 {
67 /* CryptGenRandom() failed */
68 if (raise)
69 PyErr_SetFromWindowsErr(0);
70 else
71 Py_FatalError("Failed to initialized the randomized hash "
72 "secret using CryptoGen)");
73 return -1;
74 }
75 buffer += chunk;
76 size -= chunk;
77 }
78 return 0;
79}
Georg Brandl2daf6ae2012-02-20 19:54:16 +010080
Martin Panter39b10252016-06-10 08:07:11 +000081/* Issue #25003: Don't use getentropy() on Solaris (available since
82 * Solaris 11.3), it is blocking whereas os.urandom() should not block. */
Victor Stinnerbae2d622015-10-01 09:47:30 +020083#elif defined(HAVE_GETENTROPY) && !defined(sun)
84#define PY_GETENTROPY 1
85
Victor Stinner4d6a3d62014-12-21 01:16:38 +010086/* Fill buffer with size pseudo-random bytes generated by getentropy().
87 Return 0 on success, or raise an exception and return -1 on error.
Georg Brandl2daf6ae2012-02-20 19:54:16 +010088
Victor Stinner4d6a3d62014-12-21 01:16:38 +010089 If fatal is nonzero, call Py_FatalError() instead of raising an exception
90 on error. */
91static int
92py_getentropy(unsigned char *buffer, Py_ssize_t size, int fatal)
93{
94 while (size > 0) {
95 Py_ssize_t len = Py_MIN(size, 256);
Victor Stinner9aa13312015-03-30 11:18:30 +020096 int res;
97
98 if (!fatal) {
99 Py_BEGIN_ALLOW_THREADS
100 res = getentropy(buffer, len);
101 Py_END_ALLOW_THREADS
102
103 if (res < 0) {
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100104 PyErr_SetFromErrno(PyExc_OSError);
105 return -1;
106 }
107 }
Victor Stinner9aa13312015-03-30 11:18:30 +0200108 else {
109 res = getentropy(buffer, len);
110 if (res < 0)
111 Py_FatalError("getentropy() failed");
112 }
113
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100114 buffer += len;
115 size -= len;
116 }
117 return 0;
118}
119
Victor Stinnerbae2d622015-10-01 09:47:30 +0200120#else
Victor Stinner59f7fb22015-03-18 14:39:33 +0100121
Victor Stinnerbae2d622015-10-01 09:47:30 +0200122#if defined(HAVE_GETRANDOM) || defined(HAVE_GETRANDOM_SYSCALL)
123#define PY_GETRANDOM 1
124
Victor Stinner59f7fb22015-03-18 14:39:33 +0100125static int
126py_getrandom(void *buffer, Py_ssize_t size, int raise)
127{
Victor Stinnerbae2d622015-10-01 09:47:30 +0200128 /* Is getrandom() supported by the running kernel?
129 * Need Linux kernel 3.17 or newer, or Solaris 11.3 or newer */
Victor Stinner59f7fb22015-03-18 14:39:33 +0100130 static int getrandom_works = 1;
Victor Stinnerdddf4842016-06-07 11:21:42 +0200131
132 /* getrandom() on Linux will block if called before the kernel has
133 * initialized the urandom entropy pool. This will cause Python
134 * to hang on startup if called very early in the boot process -
135 * see https://bugs.python.org/issue26839. To avoid this, use the
136 * GRND_NONBLOCK flag. */
137 const int flags = GRND_NONBLOCK;
Victor Stinnercfb19612016-06-08 10:16:50 +0200138
139 char *dest;
Victor Stinnerec721f32016-06-16 23:53:47 +0200140 long n;
Victor Stinner59f7fb22015-03-18 14:39:33 +0100141
142 if (!getrandom_works)
143 return 0;
144
Victor Stinnercfb19612016-06-08 10:16:50 +0200145 dest = buffer;
Victor Stinner59f7fb22015-03-18 14:39:33 +0100146 while (0 < size) {
Victor Stinner9d242712016-04-12 22:28:49 +0200147#ifdef sun
148 /* Issue #26735: On Solaris, getrandom() is limited to returning up
149 to 1024 bytes */
150 n = Py_MIN(size, 1024);
151#else
Victor Stinnerec721f32016-06-16 23:53:47 +0200152 n = Py_MIN(size, LONG_MAX);
Victor Stinner9d242712016-04-12 22:28:49 +0200153#endif
Victor Stinner79b74ae2015-03-30 11:16:40 +0200154
Victor Stinner9d242712016-04-12 22:28:49 +0200155 errno = 0;
Victor Stinnerbae2d622015-10-01 09:47:30 +0200156#ifdef HAVE_GETRANDOM
157 if (raise) {
158 Py_BEGIN_ALLOW_THREADS
Victor Stinnercfb19612016-06-08 10:16:50 +0200159 n = getrandom(dest, n, flags);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200160 Py_END_ALLOW_THREADS
161 }
162 else {
Victor Stinnercfb19612016-06-08 10:16:50 +0200163 n = getrandom(dest, n, flags);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200164 }
165#else
166 /* On Linux, use the syscall() function because the GNU libc doesn't
167 * expose the Linux getrandom() syscall yet. See:
Victor Stinner59f7fb22015-03-18 14:39:33 +0100168 * https://sourceware.org/bugzilla/show_bug.cgi?id=17252 */
Victor Stinner79b74ae2015-03-30 11:16:40 +0200169 if (raise) {
170 Py_BEGIN_ALLOW_THREADS
Victor Stinnercfb19612016-06-08 10:16:50 +0200171 n = syscall(SYS_getrandom, dest, n, flags);
Victor Stinner79b74ae2015-03-30 11:16:40 +0200172 Py_END_ALLOW_THREADS
173 }
174 else {
Victor Stinnercfb19612016-06-08 10:16:50 +0200175 n = syscall(SYS_getrandom, dest, n, flags);
Victor Stinner79b74ae2015-03-30 11:16:40 +0200176 }
Victor Stinnerbae2d622015-10-01 09:47:30 +0200177#endif
Victor Stinner79b74ae2015-03-30 11:16:40 +0200178
Victor Stinner59f7fb22015-03-18 14:39:33 +0100179 if (n < 0) {
180 if (errno == ENOSYS) {
181 getrandom_works = 0;
182 return 0;
183 }
Victor Stinnerdddf4842016-06-07 11:21:42 +0200184 if (errno == EAGAIN) {
185 /* If we failed with EAGAIN, the entropy pool was
186 * uninitialized. In this case, we return failure to fall
187 * back to reading from /dev/urandom.
188 *
189 * Note: In this case the data read will not be random so
190 * should not be used for cryptographic purposes. Retaining
191 * the existing semantics for practical purposes. */
192 getrandom_works = 0;
193 return 0;
194 }
Victor Stinner59f7fb22015-03-18 14:39:33 +0100195
196 if (errno == EINTR) {
Victor Stinner59f7fb22015-03-18 14:39:33 +0100197 if (PyErr_CheckSignals()) {
198 if (!raise)
199 Py_FatalError("getrandom() interrupted by a signal");
200 return -1;
201 }
202 /* retry getrandom() */
203 continue;
204 }
205
206 if (raise)
207 PyErr_SetFromErrno(PyExc_OSError);
208 else
209 Py_FatalError("getrandom() failed");
210 return -1;
211 }
212
Victor Stinnercfb19612016-06-08 10:16:50 +0200213 dest += n;
Victor Stinner59f7fb22015-03-18 14:39:33 +0100214 size -= n;
215 }
216 return 1;
217}
218#endif
219
Antoine Pitroue472aea2014-04-26 14:33:03 +0200220static struct {
221 int fd;
222 dev_t st_dev;
223 ino_t st_ino;
224} urandom_cache = { -1 };
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100225
Victor Stinner59f7fb22015-03-18 14:39:33 +0100226
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100227/* Read size bytes from /dev/urandom into buffer.
228 Call Py_FatalError() on error. */
229static void
Christian Heimes985ecdc2013-11-20 11:46:18 +0100230dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size)
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100231{
232 int fd;
233 Py_ssize_t n;
234
235 assert (0 < size);
236
Victor Stinnerbae2d622015-10-01 09:47:30 +0200237#ifdef PY_GETRANDOM
Victor Stinner59f7fb22015-03-18 14:39:33 +0100238 if (py_getrandom(buffer, size, 0) == 1)
239 return;
240 /* getrandom() is not supported by the running kernel, fall back
241 * on reading /dev/urandom */
242#endif
243
Victor Stinnerc7cd12d2015-03-19 23:24:45 +0100244 fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
245 if (fd < 0)
246 Py_FatalError("Failed to open /dev/urandom");
247
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100248 while (0 < size)
249 {
250 do {
251 n = read(fd, buffer, (size_t)size);
252 } while (n < 0 && errno == EINTR);
253 if (n <= 0)
254 {
255 /* stop on error or if read(size) returned 0 */
256 Py_FatalError("Failed to read bytes from /dev/urandom");
257 break;
258 }
259 buffer += n;
Victor Stinnerc72828b2016-06-14 16:35:49 +0200260 size -= n;
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100261 }
262 close(fd);
263}
264
265/* Read size bytes from /dev/urandom into buffer.
266 Return 0 on success, raise an exception and return -1 on error. */
267static int
268dev_urandom_python(char *buffer, Py_ssize_t size)
269{
270 int fd;
271 Py_ssize_t n;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800272 struct _Py_stat_struct st;
Victor Stinnerbae2d622015-10-01 09:47:30 +0200273#ifdef PY_GETRANDOM
Victor Stinner59f7fb22015-03-18 14:39:33 +0100274 int res;
275#endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100276
277 if (size <= 0)
278 return 0;
279
Victor Stinnerbae2d622015-10-01 09:47:30 +0200280#ifdef PY_GETRANDOM
Victor Stinner59f7fb22015-03-18 14:39:33 +0100281 res = py_getrandom(buffer, size, 1);
282 if (res < 0)
283 return -1;
284 if (res == 1)
285 return 0;
286 /* getrandom() is not supported by the running kernel, fall back
287 * on reading /dev/urandom */
288#endif
289
Antoine Pitroue472aea2014-04-26 14:33:03 +0200290 if (urandom_cache.fd >= 0) {
291 /* Does the fd point to the same thing as before? (issue #21207) */
Victor Stinnere134a7f2015-03-30 10:09:31 +0200292 if (_Py_fstat_noraise(urandom_cache.fd, &st)
Antoine Pitroue472aea2014-04-26 14:33:03 +0200293 || st.st_dev != urandom_cache.st_dev
294 || st.st_ino != urandom_cache.st_ino) {
295 /* Something changed: forget the cached fd (but don't close it,
296 since it probably points to something important for some
297 third-party code). */
298 urandom_cache.fd = -1;
299 }
300 }
301 if (urandom_cache.fd >= 0)
302 fd = urandom_cache.fd;
Antoine Pitrou4879a962013-08-31 00:26:02 +0200303 else {
Antoine Pitrou4879a962013-08-31 00:26:02 +0200304 fd = _Py_open("/dev/urandom", O_RDONLY);
Victor Stinnera555cfc2015-03-18 00:22:14 +0100305 if (fd < 0) {
Antoine Pitrou4879a962013-08-31 00:26:02 +0200306 if (errno == ENOENT || errno == ENXIO ||
307 errno == ENODEV || errno == EACCES)
308 PyErr_SetString(PyExc_NotImplementedError,
309 "/dev/urandom (or equivalent) not found");
Victor Stinnera555cfc2015-03-18 00:22:14 +0100310 /* otherwise, keep the OSError exception raised by _Py_open() */
Antoine Pitrou4879a962013-08-31 00:26:02 +0200311 return -1;
312 }
Antoine Pitroue472aea2014-04-26 14:33:03 +0200313 if (urandom_cache.fd >= 0) {
Antoine Pitrou4879a962013-08-31 00:26:02 +0200314 /* urandom_fd was initialized by another thread while we were
315 not holding the GIL, keep it. */
316 close(fd);
Antoine Pitroue472aea2014-04-26 14:33:03 +0200317 fd = urandom_cache.fd;
Antoine Pitrou4879a962013-08-31 00:26:02 +0200318 }
Antoine Pitroue472aea2014-04-26 14:33:03 +0200319 else {
Steve Dowerf2f373f2015-02-21 08:44:05 -0800320 if (_Py_fstat(fd, &st)) {
Antoine Pitroue472aea2014-04-26 14:33:03 +0200321 close(fd);
322 return -1;
323 }
324 else {
325 urandom_cache.fd = fd;
326 urandom_cache.st_dev = st.st_dev;
327 urandom_cache.st_ino = st.st_ino;
328 }
329 }
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100330 }
331
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100332 do {
Victor Stinnerc9382eb2015-03-19 23:36:33 +0100333 n = _Py_read(fd, buffer, (size_t)size);
334 if (n == -1)
335 return -1;
336 if (n == 0) {
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100337 PyErr_Format(PyExc_RuntimeError,
Victor Stinnerc9382eb2015-03-19 23:36:33 +0100338 "Failed to read %zi bytes from /dev/urandom",
339 size);
340 return -1;
341 }
342
343 buffer += n;
344 size -= n;
345 } while (0 < size);
346
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100347 return 0;
348}
Antoine Pitrou4879a962013-08-31 00:26:02 +0200349
350static void
351dev_urandom_close(void)
352{
Antoine Pitroue472aea2014-04-26 14:33:03 +0200353 if (urandom_cache.fd >= 0) {
354 close(urandom_cache.fd);
355 urandom_cache.fd = -1;
Antoine Pitrou4879a962013-08-31 00:26:02 +0200356 }
357}
358
Victor Stinnerbae2d622015-10-01 09:47:30 +0200359#endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100360
361/* Fill buffer with pseudo-random bytes generated by a linear congruent
362 generator (LCG):
363
364 x(n+1) = (x(n) * 214013 + 2531011) % 2^32
365
366 Use bits 23..16 of x(n) to generate a byte. */
367static void
368lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
369{
370 size_t index;
371 unsigned int x;
372
373 x = x0;
374 for (index=0; index < size; index++) {
375 x *= 214013;
376 x += 2531011;
377 /* modulo 2 ^ (8 * sizeof(int)) */
378 buffer[index] = (x >> 16) & 0xff;
379 }
380}
381
Georg Brandlc6a2c9b2013-10-06 18:43:19 +0200382/* Fill buffer with size pseudo-random bytes from the operating system random
Serhiy Storchaka56a6d852014-12-01 18:28:43 +0200383 number generator (RNG). It is suitable for most cryptographic purposes
Georg Brandlc6a2c9b2013-10-06 18:43:19 +0200384 except long living private keys for asymmetric encryption.
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100385
386 Return 0 on success, raise an exception and return -1 on error. */
387int
388_PyOS_URandom(void *buffer, Py_ssize_t size)
389{
390 if (size < 0) {
391 PyErr_Format(PyExc_ValueError,
392 "negative argument not allowed");
393 return -1;
394 }
395 if (size == 0)
396 return 0;
397
398#ifdef MS_WINDOWS
399 return win32_urandom((unsigned char *)buffer, size, 1);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200400#elif defined(PY_GETENTROPY)
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100401 return py_getentropy(buffer, size, 0);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100402#else
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100403 return dev_urandom_python((char*)buffer, size);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100404#endif
405}
406
407void
408_PyRandom_Init(void)
409{
410 char *env;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100411 unsigned char *secret = (unsigned char *)&_Py_HashSecret.uc;
Benjamin Peterson69e97272012-02-21 11:08:50 -0500412 Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
Serhiy Storchakafad85aa2015-11-07 15:42:38 +0200413 Py_BUILD_ASSERT(sizeof(_Py_HashSecret_t) == sizeof(_Py_HashSecret.uc));
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100414
Benjamin Peterson69e97272012-02-21 11:08:50 -0500415 if (_Py_HashSecret_Initialized)
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100416 return;
Benjamin Peterson69e97272012-02-21 11:08:50 -0500417 _Py_HashSecret_Initialized = 1;
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100418
419 /*
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100420 Hash randomization is enabled. Generate a per-process secret,
421 using PYTHONHASHSEED if provided.
422 */
423
424 env = Py_GETENV("PYTHONHASHSEED");
Georg Brandl12897d72012-02-20 23:49:29 +0100425 if (env && *env != '\0' && strcmp(env, "random") != 0) {
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100426 char *endptr = env;
427 unsigned long seed;
428 seed = strtoul(env, &endptr, 10);
429 if (*endptr != '\0'
430 || seed > 4294967295UL
431 || (errno == ERANGE && seed == ULONG_MAX))
432 {
433 Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "
434 "in range [0; 4294967295]");
435 }
436 if (seed == 0) {
437 /* disable the randomized hash */
438 memset(secret, 0, secret_size);
439 }
440 else {
Christian Heimes985ecdc2013-11-20 11:46:18 +0100441 lcg_urandom(seed, secret, secret_size);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100442 }
443 }
444 else {
445#ifdef MS_WINDOWS
Christian Heimes985ecdc2013-11-20 11:46:18 +0100446 (void)win32_urandom(secret, secret_size, 0);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200447#elif defined(PY_GETENTROPY)
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100448 (void)py_getentropy(secret, secret_size, 1);
Christian Heimesaf01f662013-12-21 16:19:10 +0100449#else
Christian Heimes985ecdc2013-11-20 11:46:18 +0100450 dev_urandom_noraise(secret, secret_size);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100451#endif
452 }
453}
Antoine Pitrou4879a962013-08-31 00:26:02 +0200454
455void
456_PyRandom_Fini(void)
457{
Victor Stinnerd50c3f32014-05-02 22:06:44 +0200458#ifdef MS_WINDOWS
459 if (hCryptProv) {
Tim Goldenb8ac3e12014-05-06 13:29:45 +0100460 CryptReleaseContext(hCryptProv, 0);
Victor Stinnerd50c3f32014-05-02 22:06:44 +0200461 hCryptProv = 0;
462 }
Victor Stinnerbae2d622015-10-01 09:47:30 +0200463#elif defined(PY_GETENTROPY)
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100464 /* nothing to clean */
Victor Stinnerd50c3f32014-05-02 22:06:44 +0200465#else
Antoine Pitrou4879a962013-08-31 00:26:02 +0200466 dev_urandom_close();
467#endif
468}