blob: ad2c389bc899cb83e324c979043eded6ca526f41 [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
Benjamin Peterson493ac1b2017-01-01 22:29:36 -060015# if defined(HAVE_SYS_RANDOM_H) && (defined(HAVE_GETRANDOM) || defined(HAVE_GETENTROPY))
Victor Stinnerbae2d622015-10-01 09:47:30 +020016# include <sys/random.h>
Ned Deily7ae41122016-11-12 16:35:48 -050017# endif
18# if !defined(HAVE_GETRANDOM) && defined(HAVE_GETRANDOM_SYSCALL)
Victor Stinner59f7fb22015-03-18 14:39:33 +010019# include <sys/syscall.h>
Victor Stinner59f7fb22015-03-18 14:39:33 +010020# endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +010021#endif
22
Benjamin Peterson69e97272012-02-21 11:08:50 -050023#ifdef Py_DEBUG
24int _Py_HashSecret_Initialized = 0;
25#else
26static int _Py_HashSecret_Initialized = 0;
27#endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +010028
29#ifdef MS_WINDOWS
Georg Brandl2daf6ae2012-02-20 19:54:16 +010030static HCRYPTPROV hCryptProv = 0;
31
32static int
33win32_urandom_init(int raise)
34{
Georg Brandl2daf6ae2012-02-20 19:54:16 +010035 /* Acquire context */
Martin v. Löwis3f50bf62013-01-25 14:06:18 +010036 if (!CryptAcquireContext(&hCryptProv, NULL, NULL,
37 PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
Georg Brandl2daf6ae2012-02-20 19:54:16 +010038 goto error;
39
40 return 0;
41
42error:
Victor Stinner4bad3b62016-08-16 15:23:58 +020043 if (raise) {
Georg Brandl2daf6ae2012-02-20 19:54:16 +010044 PyErr_SetFromWindowsErr(0);
Victor Stinner4bad3b62016-08-16 15:23:58 +020045 }
Georg Brandl2daf6ae2012-02-20 19:54:16 +010046 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 {
Victor Stinner4bad3b62016-08-16 15:23:58 +020058 if (win32_urandom_init(raise) == -1) {
Georg Brandl2daf6ae2012-02-20 19:54:16 +010059 return -1;
Victor Stinner4bad3b62016-08-16 15:23:58 +020060 }
Georg Brandl2daf6ae2012-02-20 19:54:16 +010061 }
62
63 while (size > 0)
64 {
65 chunk = size > INT_MAX ? INT_MAX : size;
Victor Stinner0c083462013-11-15 23:26:25 +010066 if (!CryptGenRandom(hCryptProv, (DWORD)chunk, buffer))
Georg Brandl2daf6ae2012-02-20 19:54:16 +010067 {
68 /* CryptGenRandom() failed */
Victor Stinner4bad3b62016-08-16 15:23:58 +020069 if (raise) {
Georg Brandl2daf6ae2012-02-20 19:54:16 +010070 PyErr_SetFromWindowsErr(0);
Victor Stinner4bad3b62016-08-16 15:23:58 +020071 }
Georg Brandl2daf6ae2012-02-20 19:54:16 +010072 return -1;
73 }
74 buffer += chunk;
75 size -= chunk;
76 }
77 return 0;
78}
Georg Brandl2daf6ae2012-02-20 19:54:16 +010079
Victor Stinnerdcdb60e2017-01-06 11:16:20 +010080#else /* !MS_WINDOWS */
81
Victor Stinner2f796432017-01-06 11:26:01 +010082#if defined(HAVE_GETRANDOM) || defined(HAVE_GETRANDOM_SYSCALL)
Victor Stinnerbae2d622015-10-01 09:47:30 +020083#define PY_GETRANDOM 1
84
Victor Stinner6974cf22016-08-16 18:46:38 +020085/* Call getrandom()
86 - Return 1 on success
Victor Stinner6d8bc462016-09-20 22:46:02 +020087 - Return 0 if getrandom() syscall is not available (failed with ENOSYS or
88 EPERM) or if getrandom(GRND_NONBLOCK) failed with EAGAIN (system urandom
Victor Stinneraf597322016-09-20 22:26:18 +020089 not initialized yet) and raise=0.
Victor Stinner6974cf22016-08-16 18:46:38 +020090 - Raise an exception (if raise is non-zero) and return -1 on error:
91 getrandom() failed with EINTR and the Python signal handler raised an
92 exception, or getrandom() failed with a different error. */
Victor Stinner59f7fb22015-03-18 14:39:33 +010093static int
Victor Stinnere66987e2016-09-06 16:33:52 -070094py_getrandom(void *buffer, Py_ssize_t size, int blocking, int raise)
Victor Stinner59f7fb22015-03-18 14:39:33 +010095{
Victor Stinnere66987e2016-09-06 16:33:52 -070096 /* Is getrandom() supported by the running kernel? Set to 0 if getrandom()
Victor Stinner6d8bc462016-09-20 22:46:02 +020097 failed with ENOSYS or EPERM. Need Linux kernel 3.17 or newer, or Solaris
Victor Stinneraf597322016-09-20 22:26:18 +020098 11.3 or newer */
Victor Stinner59f7fb22015-03-18 14:39:33 +010099 static int getrandom_works = 1;
Victor Stinnere66987e2016-09-06 16:33:52 -0700100 int flags;
Victor Stinnercfb19612016-06-08 10:16:50 +0200101 char *dest;
Victor Stinnerec721f32016-06-16 23:53:47 +0200102 long n;
Victor Stinner59f7fb22015-03-18 14:39:33 +0100103
Victor Stinner6974cf22016-08-16 18:46:38 +0200104 if (!getrandom_works) {
Victor Stinner59f7fb22015-03-18 14:39:33 +0100105 return 0;
Victor Stinner6974cf22016-08-16 18:46:38 +0200106 }
Victor Stinner59f7fb22015-03-18 14:39:33 +0100107
Victor Stinnere66987e2016-09-06 16:33:52 -0700108 flags = blocking ? 0 : GRND_NONBLOCK;
Victor Stinnercfb19612016-06-08 10:16:50 +0200109 dest = buffer;
Victor Stinner59f7fb22015-03-18 14:39:33 +0100110 while (0 < size) {
Victor Stinner9d242712016-04-12 22:28:49 +0200111#ifdef sun
112 /* Issue #26735: On Solaris, getrandom() is limited to returning up
113 to 1024 bytes */
114 n = Py_MIN(size, 1024);
115#else
Victor Stinnerec721f32016-06-16 23:53:47 +0200116 n = Py_MIN(size, LONG_MAX);
Victor Stinner9d242712016-04-12 22:28:49 +0200117#endif
Victor Stinner79b74ae2015-03-30 11:16:40 +0200118
Victor Stinner9d242712016-04-12 22:28:49 +0200119 errno = 0;
Victor Stinnerbae2d622015-10-01 09:47:30 +0200120#ifdef HAVE_GETRANDOM
121 if (raise) {
122 Py_BEGIN_ALLOW_THREADS
Victor Stinnercfb19612016-06-08 10:16:50 +0200123 n = getrandom(dest, n, flags);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200124 Py_END_ALLOW_THREADS
125 }
126 else {
Victor Stinnercfb19612016-06-08 10:16:50 +0200127 n = getrandom(dest, n, flags);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200128 }
129#else
130 /* On Linux, use the syscall() function because the GNU libc doesn't
Victor Stinner6974cf22016-08-16 18:46:38 +0200131 expose the Linux getrandom() syscall yet. See:
132 https://sourceware.org/bugzilla/show_bug.cgi?id=17252 */
Victor Stinner79b74ae2015-03-30 11:16:40 +0200133 if (raise) {
134 Py_BEGIN_ALLOW_THREADS
Victor Stinnercfb19612016-06-08 10:16:50 +0200135 n = syscall(SYS_getrandom, dest, n, flags);
Victor Stinner79b74ae2015-03-30 11:16:40 +0200136 Py_END_ALLOW_THREADS
137 }
138 else {
Victor Stinnercfb19612016-06-08 10:16:50 +0200139 n = syscall(SYS_getrandom, dest, n, flags);
Victor Stinner79b74ae2015-03-30 11:16:40 +0200140 }
Victor Stinnerbae2d622015-10-01 09:47:30 +0200141#endif
Victor Stinner79b74ae2015-03-30 11:16:40 +0200142
Victor Stinner59f7fb22015-03-18 14:39:33 +0100143 if (n < 0) {
Victor Stinneraf597322016-09-20 22:26:18 +0200144 /* ENOSYS: getrandom() syscall not supported by the kernel (but
Victor Stinner6d8bc462016-09-20 22:46:02 +0200145 * maybe supported by the host which built Python). EPERM:
146 * getrandom() syscall blocked by SECCOMP or something else. */
147 if (errno == ENOSYS || errno == EPERM) {
Victor Stinner59f7fb22015-03-18 14:39:33 +0100148 getrandom_works = 0;
149 return 0;
150 }
Victor Stinner6974cf22016-08-16 18:46:38 +0200151
Victor Stinnere66987e2016-09-06 16:33:52 -0700152 /* getrandom(GRND_NONBLOCK) fails with EAGAIN if the system urandom
153 is not initialiazed yet. For _PyRandom_Init(), we ignore their
154 error and fall back on reading /dev/urandom which never blocks,
155 even if the system urandom is not initialized yet. */
156 if (errno == EAGAIN && !raise && !blocking) {
Victor Stinnerdddf4842016-06-07 11:21:42 +0200157 return 0;
158 }
Victor Stinner59f7fb22015-03-18 14:39:33 +0100159
160 if (errno == EINTR) {
Victor Stinnercecdd962016-08-16 15:19:09 +0200161 if (raise) {
162 if (PyErr_CheckSignals()) {
163 return -1;
164 }
Victor Stinner59f7fb22015-03-18 14:39:33 +0100165 }
Victor Stinnercecdd962016-08-16 15:19:09 +0200166
167 /* retry getrandom() if it was interrupted by a signal */
Victor Stinner59f7fb22015-03-18 14:39:33 +0100168 continue;
169 }
170
Victor Stinner4bad3b62016-08-16 15:23:58 +0200171 if (raise) {
Victor Stinner59f7fb22015-03-18 14:39:33 +0100172 PyErr_SetFromErrno(PyExc_OSError);
Victor Stinner4bad3b62016-08-16 15:23:58 +0200173 }
Victor Stinner59f7fb22015-03-18 14:39:33 +0100174 return -1;
175 }
176
Victor Stinnercfb19612016-06-08 10:16:50 +0200177 dest += n;
Victor Stinner59f7fb22015-03-18 14:39:33 +0100178 size -= n;
179 }
180 return 1;
181}
Victor Stinner2f796432017-01-06 11:26:01 +0100182
183#elif defined(HAVE_GETENTROPY)
184#define PY_GETENTROPY 1
185
186/* Fill buffer with size pseudo-random bytes generated by getentropy().
187 Return 1 on success, or raise an exception and return -1 on error.
188
189 If raise is zero, don't raise an exception on error. */
190static int
191py_getentropy(char *buffer, Py_ssize_t size, int raise)
192{
193 while (size > 0) {
194 Py_ssize_t len = Py_MIN(size, 256);
195 int res;
196
197 if (raise) {
198 Py_BEGIN_ALLOW_THREADS
199 res = getentropy(buffer, len);
200 Py_END_ALLOW_THREADS
201 }
202 else {
203 res = getentropy(buffer, len);
204 }
205
206 if (res < 0) {
207 if (raise) {
208 PyErr_SetFromErrno(PyExc_OSError);
209 }
210 return -1;
211 }
212
213 buffer += len;
214 size -= len;
215 }
216 return 1;
217}
218#endif /* defined(HAVE_GETENTROPY) && !defined(sun) */
Victor Stinnerdcdb60e2017-01-06 11:16:20 +0100219
Victor Stinner59f7fb22015-03-18 14:39:33 +0100220
Antoine Pitroue472aea2014-04-26 14:33:03 +0200221static struct {
222 int fd;
223 dev_t st_dev;
224 ino_t st_ino;
225} urandom_cache = { -1 };
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100226
Victor Stinnera49a2072017-01-06 11:17:52 +0100227/* Read random bytes from the /dev/urandom device:
Victor Stinner6974cf22016-08-16 18:46:38 +0200228
Victor Stinnera49a2072017-01-06 11:17:52 +0100229 - Return 0 on success
230 - Raise an exception (if raise is non-zero) and return -1 on error
231
232 Possible causes of errors:
233
234 - open() failed with ENOENT, ENXIO, ENODEV, EACCES: the /dev/urandom device
235 was not found. For example, it was removed manually or not exposed in a
236 chroot or container.
237 - open() failed with a different error
238 - fstat() failed
239 - read() failed or returned 0
240
241 read() is retried if it failed with EINTR: interrupted by a signal.
242
243 The file descriptor of the device is kept open between calls to avoid using
244 many file descriptors when run in parallel from multiple threads:
245 see the issue #18756.
246
247 st_dev and st_ino fields of the file descriptor (from fstat()) are cached to
248 check if the file descriptor was replaced by a different file (which is
249 likely a bug in the application): see the issue #21207.
250
251 If the file descriptor was closed or replaced, open a new file descriptor
252 but don't close the old file descriptor: it probably points to something
253 important for some third-party code. */
Victor Stinner4bad3b62016-08-16 15:23:58 +0200254static int
Victor Stinnera49a2072017-01-06 11:17:52 +0100255dev_urandom(char *buffer, Py_ssize_t size, int raise)
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100256{
257 int fd;
258 Py_ssize_t n;
Victor Stinner6974cf22016-08-16 18:46:38 +0200259
260 if (raise) {
261 struct _Py_stat_struct st;
262
Antoine Pitroue472aea2014-04-26 14:33:03 +0200263 if (urandom_cache.fd >= 0) {
Victor Stinner6974cf22016-08-16 18:46:38 +0200264 /* Does the fd point to the same thing as before? (issue #21207) */
265 if (_Py_fstat_noraise(urandom_cache.fd, &st)
266 || st.st_dev != urandom_cache.st_dev
267 || st.st_ino != urandom_cache.st_ino) {
268 /* Something changed: forget the cached fd (but don't close it,
269 since it probably points to something important for some
270 third-party code). */
271 urandom_cache.fd = -1;
272 }
Antoine Pitrou4879a962013-08-31 00:26:02 +0200273 }
Victor Stinner6974cf22016-08-16 18:46:38 +0200274 if (urandom_cache.fd >= 0)
275 fd = urandom_cache.fd;
Antoine Pitroue472aea2014-04-26 14:33:03 +0200276 else {
Victor Stinner6974cf22016-08-16 18:46:38 +0200277 fd = _Py_open("/dev/urandom", O_RDONLY);
278 if (fd < 0) {
279 if (errno == ENOENT || errno == ENXIO ||
280 errno == ENODEV || errno == EACCES)
281 PyErr_SetString(PyExc_NotImplementedError,
282 "/dev/urandom (or equivalent) not found");
283 /* otherwise, keep the OSError exception raised by _Py_open() */
Antoine Pitroue472aea2014-04-26 14:33:03 +0200284 return -1;
285 }
Victor Stinner6974cf22016-08-16 18:46:38 +0200286 if (urandom_cache.fd >= 0) {
287 /* urandom_fd was initialized by another thread while we were
288 not holding the GIL, keep it. */
289 close(fd);
290 fd = urandom_cache.fd;
291 }
Antoine Pitroue472aea2014-04-26 14:33:03 +0200292 else {
Victor Stinner6974cf22016-08-16 18:46:38 +0200293 if (_Py_fstat(fd, &st)) {
294 close(fd);
295 return -1;
296 }
297 else {
298 urandom_cache.fd = fd;
299 urandom_cache.st_dev = st.st_dev;
300 urandom_cache.st_ino = st.st_ino;
301 }
Antoine Pitroue472aea2014-04-26 14:33:03 +0200302 }
303 }
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100304
Victor Stinner6974cf22016-08-16 18:46:38 +0200305 do {
306 n = _Py_read(fd, buffer, (size_t)size);
307 if (n == -1)
308 return -1;
309 if (n == 0) {
310 PyErr_Format(PyExc_RuntimeError,
311 "Failed to read %zi bytes from /dev/urandom",
312 size);
313 return -1;
314 }
315
316 buffer += n;
317 size -= n;
318 } while (0 < size);
319 }
320 else {
321 fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
322 if (fd < 0) {
Victor Stinnerc9382eb2015-03-19 23:36:33 +0100323 return -1;
324 }
325
Victor Stinner6974cf22016-08-16 18:46:38 +0200326 while (0 < size)
327 {
328 do {
329 n = read(fd, buffer, (size_t)size);
330 } while (n < 0 && errno == EINTR);
Victor Stinnerc9382eb2015-03-19 23:36:33 +0100331
Victor Stinner6974cf22016-08-16 18:46:38 +0200332 if (n <= 0) {
333 /* stop on error or if read(size) returned 0 */
Victor Stinner3ee933f2016-08-16 18:27:44 +0200334 close(fd);
Victor Stinner6974cf22016-08-16 18:46:38 +0200335 return -1;
336 }
337
338 buffer += n;
339 size -= n;
340 }
341 close(fd);
342 }
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100343 return 0;
344}
Antoine Pitrou4879a962013-08-31 00:26:02 +0200345
346static void
347dev_urandom_close(void)
348{
Antoine Pitroue472aea2014-04-26 14:33:03 +0200349 if (urandom_cache.fd >= 0) {
350 close(urandom_cache.fd);
351 urandom_cache.fd = -1;
Antoine Pitrou4879a962013-08-31 00:26:02 +0200352 }
353}
Victor Stinnerdcdb60e2017-01-06 11:16:20 +0100354#endif /* !MS_WINDOWS */
Antoine Pitrou4879a962013-08-31 00:26:02 +0200355
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100356
357/* Fill buffer with pseudo-random bytes generated by a linear congruent
358 generator (LCG):
359
360 x(n+1) = (x(n) * 214013 + 2531011) % 2^32
361
362 Use bits 23..16 of x(n) to generate a byte. */
363static void
364lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
365{
366 size_t index;
367 unsigned int x;
368
369 x = x0;
370 for (index=0; index < size; index++) {
371 x *= 214013;
372 x += 2531011;
373 /* modulo 2 ^ (8 * sizeof(int)) */
374 buffer[index] = (x >> 16) & 0xff;
375 }
376}
377
Victor Stinnera49a2072017-01-06 11:17:52 +0100378/* Read random bytes:
379
380 - Return 0 on success
381 - Raise an exception (if raise is non-zero) and return -1 on error
382
383 Used sources of entropy ordered by preference, preferred source first:
384
385 - CryptGenRandom() on Windows
Victor Stinnera49a2072017-01-06 11:17:52 +0100386 - getrandom() function (ex: Linux and Solaris): call py_getrandom()
Victor Stinner2f796432017-01-06 11:26:01 +0100387 - getentropy() function (ex: OpenBSD): call py_getentropy()
Victor Stinnera49a2072017-01-06 11:17:52 +0100388 - /dev/urandom device
389
390 Read from the /dev/urandom device if getrandom() or getentropy() function
391 is not available or does not work.
392
Victor Stinner2f796432017-01-06 11:26:01 +0100393 Prefer getrandom() over getentropy() because getrandom() supports blocking
394 and non-blocking mode: see the PEP 524. Python requires non-blocking RNG at
395 startup to initialize its hash secret, but os.urandom() must block until the
396 system urandom is initialized (at least on Linux 3.17 and newer).
397
Victor Stinnera49a2072017-01-06 11:17:52 +0100398 Prefer getrandom() and getentropy() over reading directly /dev/urandom
399 because these functions don't need file descriptors and so avoid ENFILE or
400 EMFILE errors (too many open files): see the issue #18756.
401
402 Only the getrandom() function supports non-blocking mode.
403
404 Only use RNG running in the kernel. They are more secure because it is
405 harder to get the internal state of a RNG running in the kernel land than a
406 RNG running in the user land. The kernel has a direct access to the hardware
407 and has access to hardware RNG, they are used as entropy sources.
408
409 Note: the OpenSSL RAND_pseudo_bytes() function does not automatically reseed
410 its RNG on fork(), two child processes (with the same pid) generate the same
411 random numbers: see issue #18747. Kernel RNGs don't have this issue,
412 they have access to good quality entropy sources.
413
414 If raise is zero:
415
416 - Don't raise an exception on error
417 - Don't call the Python signal handler (don't call PyErr_CheckSignals()) if
418 a function fails with EINTR: retry directly the interrupted function
419 - Don't release the GIL to call functions.
420*/
Victor Stinner4bad3b62016-08-16 15:23:58 +0200421static int
Victor Stinnere66987e2016-09-06 16:33:52 -0700422pyurandom(void *buffer, Py_ssize_t size, int blocking, int raise)
Victor Stinner4bad3b62016-08-16 15:23:58 +0200423{
Victor Stinnera49a2072017-01-06 11:17:52 +0100424#if defined(PY_GETRANDOM) || defined(PY_GETENTROPY)
425 int res;
426#endif
427
Victor Stinner4bad3b62016-08-16 15:23:58 +0200428 if (size < 0) {
429 if (raise) {
430 PyErr_Format(PyExc_ValueError,
431 "negative argument not allowed");
432 }
433 return -1;
434 }
435
436 if (size == 0) {
437 return 0;
438 }
439
440#ifdef MS_WINDOWS
441 return win32_urandom((unsigned char *)buffer, size, raise);
Victor Stinner4bad3b62016-08-16 15:23:58 +0200442#else
Victor Stinnera49a2072017-01-06 11:17:52 +0100443
444#if defined(PY_GETRANDOM) || defined(PY_GETENTROPY)
Victor Stinner2f796432017-01-06 11:26:01 +0100445#ifdef PY_GETRANDOM
Victor Stinnera49a2072017-01-06 11:17:52 +0100446 res = py_getrandom(buffer, size, blocking, raise);
Victor Stinner2f796432017-01-06 11:26:01 +0100447#else
448 res = py_getentropy(buffer, size, raise);
Victor Stinnera49a2072017-01-06 11:17:52 +0100449#endif
450 if (res < 0) {
451 return -1;
452 }
453 if (res == 1) {
454 return 0;
455 }
456 /* getrandom() or getentropy() function is not available: failed with
457 ENOSYS or EPERM. Fall back on reading from /dev/urandom. */
458#endif
459
460 return dev_urandom(buffer, size, raise);
Victor Stinner4bad3b62016-08-16 15:23:58 +0200461#endif
462}
463
Georg Brandlc6a2c9b2013-10-06 18:43:19 +0200464/* Fill buffer with size pseudo-random bytes from the operating system random
Serhiy Storchaka56a6d852014-12-01 18:28:43 +0200465 number generator (RNG). It is suitable for most cryptographic purposes
Georg Brandlc6a2c9b2013-10-06 18:43:19 +0200466 except long living private keys for asymmetric encryption.
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100467
Victor Stinnere66987e2016-09-06 16:33:52 -0700468 On Linux 3.17 and newer, the getrandom() syscall is used in blocking mode:
469 block until the system urandom entropy pool is initialized (128 bits are
470 collected by the kernel).
471
472 Return 0 on success. Raise an exception and return -1 on error. */
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100473int
474_PyOS_URandom(void *buffer, Py_ssize_t size)
475{
Victor Stinnere66987e2016-09-06 16:33:52 -0700476 return pyurandom(buffer, size, 1, 1);
477}
478
479/* Fill buffer with size pseudo-random bytes from the operating system random
480 number generator (RNG). It is not suitable for cryptographic purpose.
481
482 On Linux 3.17 and newer (when getrandom() syscall is used), if the system
483 urandom is not initialized yet, the function returns "weak" entropy read
484 from /dev/urandom.
485
486 Return 0 on success. Raise an exception and return -1 on error. */
487int
488_PyOS_URandomNonblock(void *buffer, Py_ssize_t size)
489{
490 return pyurandom(buffer, size, 0, 1);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100491}
492
493void
494_PyRandom_Init(void)
495{
496 char *env;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100497 unsigned char *secret = (unsigned char *)&_Py_HashSecret.uc;
Benjamin Peterson69e97272012-02-21 11:08:50 -0500498 Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
Serhiy Storchakafad85aa2015-11-07 15:42:38 +0200499 Py_BUILD_ASSERT(sizeof(_Py_HashSecret_t) == sizeof(_Py_HashSecret.uc));
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100500
Benjamin Peterson69e97272012-02-21 11:08:50 -0500501 if (_Py_HashSecret_Initialized)
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100502 return;
Benjamin Peterson69e97272012-02-21 11:08:50 -0500503 _Py_HashSecret_Initialized = 1;
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100504
505 /*
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100506 Hash randomization is enabled. Generate a per-process secret,
507 using PYTHONHASHSEED if provided.
508 */
509
510 env = Py_GETENV("PYTHONHASHSEED");
Georg Brandl12897d72012-02-20 23:49:29 +0100511 if (env && *env != '\0' && strcmp(env, "random") != 0) {
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100512 char *endptr = env;
513 unsigned long seed;
514 seed = strtoul(env, &endptr, 10);
515 if (*endptr != '\0'
516 || seed > 4294967295UL
517 || (errno == ERANGE && seed == ULONG_MAX))
518 {
519 Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "
520 "in range [0; 4294967295]");
521 }
522 if (seed == 0) {
523 /* disable the randomized hash */
524 memset(secret, 0, secret_size);
525 }
526 else {
Christian Heimes985ecdc2013-11-20 11:46:18 +0100527 lcg_urandom(seed, secret, secret_size);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100528 }
529 }
530 else {
Victor Stinner4bad3b62016-08-16 15:23:58 +0200531 int res;
532
533 /* _PyRandom_Init() is called very early in the Python initialization
Victor Stinnere66987e2016-09-06 16:33:52 -0700534 and so exceptions cannot be used (use raise=0).
535
536 _PyRandom_Init() must not block Python initialization: call
537 pyurandom() is non-blocking mode (blocking=0): see the PEP 524. */
538 res = pyurandom(secret, secret_size, 0, 0);
Victor Stinner4bad3b62016-08-16 15:23:58 +0200539 if (res < 0) {
540 Py_FatalError("failed to get random numbers to initialize Python");
541 }
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100542 }
543}
Antoine Pitrou4879a962013-08-31 00:26:02 +0200544
545void
546_PyRandom_Fini(void)
547{
Victor Stinnerd50c3f32014-05-02 22:06:44 +0200548#ifdef MS_WINDOWS
549 if (hCryptProv) {
Tim Goldenb8ac3e12014-05-06 13:29:45 +0100550 CryptReleaseContext(hCryptProv, 0);
Victor Stinnerd50c3f32014-05-02 22:06:44 +0200551 hCryptProv = 0;
552 }
553#else
Antoine Pitrou4879a962013-08-31 00:26:02 +0200554 dev_urandom_close();
555#endif
556}