blob: 839d7ad9912c753919c7d21016f0ea80567a6af3 [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>
Georg Brandl2daf6ae2012-02-20 19:54:16 +01004#else
Victor Stinner59f7fb22015-03-18 14:39:33 +01005# include <fcntl.h>
6# ifdef HAVE_SYS_STAT_H
7# include <sys/stat.h>
8# endif
Victor Stinnerbae2d622015-10-01 09:47:30 +02009# ifdef HAVE_GETRANDOM
10# include <sys/random.h>
11# elif defined(HAVE_GETRANDOM_SYSCALL)
Victor Stinner59f7fb22015-03-18 14:39:33 +010012# include <sys/syscall.h>
Victor Stinner59f7fb22015-03-18 14:39:33 +010013# endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +010014#endif
15
Benjamin Peterson69e97272012-02-21 11:08:50 -050016#ifdef Py_DEBUG
17int _Py_HashSecret_Initialized = 0;
18#else
19static int _Py_HashSecret_Initialized = 0;
20#endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +010021
22#ifdef MS_WINDOWS
Georg Brandl2daf6ae2012-02-20 19:54:16 +010023static HCRYPTPROV hCryptProv = 0;
24
25static int
26win32_urandom_init(int raise)
27{
Georg Brandl2daf6ae2012-02-20 19:54:16 +010028 /* Acquire context */
Martin v. Löwis3f50bf62013-01-25 14:06:18 +010029 if (!CryptAcquireContext(&hCryptProv, NULL, NULL,
30 PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
Georg Brandl2daf6ae2012-02-20 19:54:16 +010031 goto error;
32
33 return 0;
34
35error:
36 if (raise)
37 PyErr_SetFromWindowsErr(0);
38 else
39 Py_FatalError("Failed to initialize Windows random API (CryptoGen)");
40 return -1;
41}
42
43/* Fill buffer with size pseudo-random bytes generated by the Windows CryptoGen
Victor Stinner4d6a3d62014-12-21 01:16:38 +010044 API. Return 0 on success, or raise an exception and return -1 on error. */
Georg Brandl2daf6ae2012-02-20 19:54:16 +010045static int
46win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise)
47{
48 Py_ssize_t chunk;
49
50 if (hCryptProv == 0)
51 {
52 if (win32_urandom_init(raise) == -1)
53 return -1;
54 }
55
56 while (size > 0)
57 {
58 chunk = size > INT_MAX ? INT_MAX : size;
Victor Stinner0c083462013-11-15 23:26:25 +010059 if (!CryptGenRandom(hCryptProv, (DWORD)chunk, buffer))
Georg Brandl2daf6ae2012-02-20 19:54:16 +010060 {
61 /* CryptGenRandom() failed */
62 if (raise)
63 PyErr_SetFromWindowsErr(0);
64 else
65 Py_FatalError("Failed to initialized the randomized hash "
66 "secret using CryptoGen)");
67 return -1;
68 }
69 buffer += chunk;
70 size -= chunk;
71 }
72 return 0;
73}
Georg Brandl2daf6ae2012-02-20 19:54:16 +010074
Victor Stinnerbae2d622015-10-01 09:47:30 +020075#elif defined(HAVE_GETENTROPY) && !defined(sun)
76#define PY_GETENTROPY 1
77
Victor Stinner4d6a3d62014-12-21 01:16:38 +010078/* Fill buffer with size pseudo-random bytes generated by getentropy().
79 Return 0 on success, or raise an exception and return -1 on error.
Georg Brandl2daf6ae2012-02-20 19:54:16 +010080
Victor Stinner4d6a3d62014-12-21 01:16:38 +010081 If fatal is nonzero, call Py_FatalError() instead of raising an exception
82 on error. */
83static int
84py_getentropy(unsigned char *buffer, Py_ssize_t size, int fatal)
85{
86 while (size > 0) {
87 Py_ssize_t len = Py_MIN(size, 256);
Victor Stinner9aa13312015-03-30 11:18:30 +020088 int res;
89
90 if (!fatal) {
91 Py_BEGIN_ALLOW_THREADS
92 res = getentropy(buffer, len);
93 Py_END_ALLOW_THREADS
94
95 if (res < 0) {
Victor Stinner4d6a3d62014-12-21 01:16:38 +010096 PyErr_SetFromErrno(PyExc_OSError);
97 return -1;
98 }
99 }
Victor Stinner9aa13312015-03-30 11:18:30 +0200100 else {
101 res = getentropy(buffer, len);
102 if (res < 0)
103 Py_FatalError("getentropy() failed");
104 }
105
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100106 buffer += len;
107 size -= len;
108 }
109 return 0;
110}
111
Victor Stinnerbae2d622015-10-01 09:47:30 +0200112#else
Victor Stinner59f7fb22015-03-18 14:39:33 +0100113
Victor Stinner861f0672015-10-01 10:00:23 +0200114/* Issue #25003: Don' use getentropy() on Solaris (available since
115 * Solaris 11.3), it is blocking whereas os.urandom() should not block. */
Victor Stinnerbae2d622015-10-01 09:47:30 +0200116#if defined(HAVE_GETRANDOM) || defined(HAVE_GETRANDOM_SYSCALL)
117#define PY_GETRANDOM 1
118
Victor Stinner59f7fb22015-03-18 14:39:33 +0100119static int
120py_getrandom(void *buffer, Py_ssize_t size, int raise)
121{
Victor Stinnerbae2d622015-10-01 09:47:30 +0200122 /* Is getrandom() supported by the running kernel?
123 * Need Linux kernel 3.17 or newer, or Solaris 11.3 or newer */
Victor Stinner59f7fb22015-03-18 14:39:33 +0100124 static int getrandom_works = 1;
Victor Stinnerbae2d622015-10-01 09:47:30 +0200125 /* Use non-blocking /dev/urandom device. On Linux at boot, the getrandom()
126 * syscall blocks until /dev/urandom is initialized with enough entropy. */
Victor Stinner59f7fb22015-03-18 14:39:33 +0100127 const int flags = 0;
128 int n;
129
130 if (!getrandom_works)
131 return 0;
132
133 while (0 < size) {
Victor Stinner9d242712016-04-12 22:28:49 +0200134#ifdef sun
135 /* Issue #26735: On Solaris, getrandom() is limited to returning up
136 to 1024 bytes */
137 n = Py_MIN(size, 1024);
138#else
139 n = size;
140#endif
Victor Stinner79b74ae2015-03-30 11:16:40 +0200141
Victor Stinner9d242712016-04-12 22:28:49 +0200142 errno = 0;
Victor Stinnerbae2d622015-10-01 09:47:30 +0200143#ifdef HAVE_GETRANDOM
144 if (raise) {
145 Py_BEGIN_ALLOW_THREADS
Victor Stinner9d242712016-04-12 22:28:49 +0200146 n = getrandom(buffer, n, flags);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200147 Py_END_ALLOW_THREADS
148 }
149 else {
Victor Stinner9d242712016-04-12 22:28:49 +0200150 n = getrandom(buffer, n, flags);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200151 }
152#else
153 /* On Linux, use the syscall() function because the GNU libc doesn't
154 * expose the Linux getrandom() syscall yet. See:
Victor Stinner59f7fb22015-03-18 14:39:33 +0100155 * https://sourceware.org/bugzilla/show_bug.cgi?id=17252 */
Victor Stinner79b74ae2015-03-30 11:16:40 +0200156 if (raise) {
157 Py_BEGIN_ALLOW_THREADS
Victor Stinner9d242712016-04-12 22:28:49 +0200158 n = syscall(SYS_getrandom, buffer, n, flags);
Victor Stinner79b74ae2015-03-30 11:16:40 +0200159 Py_END_ALLOW_THREADS
160 }
161 else {
Victor Stinner9d242712016-04-12 22:28:49 +0200162 n = syscall(SYS_getrandom, buffer, n, flags);
Victor Stinner79b74ae2015-03-30 11:16:40 +0200163 }
Victor Stinnerbae2d622015-10-01 09:47:30 +0200164#endif
Victor Stinner79b74ae2015-03-30 11:16:40 +0200165
Victor Stinner59f7fb22015-03-18 14:39:33 +0100166 if (n < 0) {
167 if (errno == ENOSYS) {
168 getrandom_works = 0;
169 return 0;
170 }
171
172 if (errno == EINTR) {
Victor Stinner59f7fb22015-03-18 14:39:33 +0100173 if (PyErr_CheckSignals()) {
174 if (!raise)
175 Py_FatalError("getrandom() interrupted by a signal");
176 return -1;
177 }
178 /* retry getrandom() */
179 continue;
180 }
181
182 if (raise)
183 PyErr_SetFromErrno(PyExc_OSError);
184 else
185 Py_FatalError("getrandom() failed");
186 return -1;
187 }
188
189 buffer += n;
190 size -= n;
191 }
192 return 1;
193}
194#endif
195
Antoine Pitroue472aea2014-04-26 14:33:03 +0200196static struct {
197 int fd;
198 dev_t st_dev;
199 ino_t st_ino;
200} urandom_cache = { -1 };
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100201
Victor Stinner59f7fb22015-03-18 14:39:33 +0100202
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100203/* Read size bytes from /dev/urandom into buffer.
204 Call Py_FatalError() on error. */
205static void
Christian Heimes985ecdc2013-11-20 11:46:18 +0100206dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size)
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100207{
208 int fd;
209 Py_ssize_t n;
210
211 assert (0 < size);
212
Victor Stinnerbae2d622015-10-01 09:47:30 +0200213#ifdef PY_GETRANDOM
Victor Stinner59f7fb22015-03-18 14:39:33 +0100214 if (py_getrandom(buffer, size, 0) == 1)
215 return;
216 /* getrandom() is not supported by the running kernel, fall back
217 * on reading /dev/urandom */
218#endif
219
Victor Stinnerc7cd12d2015-03-19 23:24:45 +0100220 fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
221 if (fd < 0)
222 Py_FatalError("Failed to open /dev/urandom");
223
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100224 while (0 < size)
225 {
226 do {
227 n = read(fd, buffer, (size_t)size);
228 } while (n < 0 && errno == EINTR);
229 if (n <= 0)
230 {
231 /* stop on error or if read(size) returned 0 */
232 Py_FatalError("Failed to read bytes from /dev/urandom");
233 break;
234 }
235 buffer += n;
236 size -= (Py_ssize_t)n;
237 }
238 close(fd);
239}
240
241/* Read size bytes from /dev/urandom into buffer.
242 Return 0 on success, raise an exception and return -1 on error. */
243static int
244dev_urandom_python(char *buffer, Py_ssize_t size)
245{
246 int fd;
247 Py_ssize_t n;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800248 struct _Py_stat_struct st;
Victor Stinnerbae2d622015-10-01 09:47:30 +0200249#ifdef PY_GETRANDOM
Victor Stinner59f7fb22015-03-18 14:39:33 +0100250 int res;
251#endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100252
253 if (size <= 0)
254 return 0;
255
Victor Stinnerbae2d622015-10-01 09:47:30 +0200256#ifdef PY_GETRANDOM
Victor Stinner59f7fb22015-03-18 14:39:33 +0100257 res = py_getrandom(buffer, size, 1);
258 if (res < 0)
259 return -1;
260 if (res == 1)
261 return 0;
262 /* getrandom() is not supported by the running kernel, fall back
263 * on reading /dev/urandom */
264#endif
265
Antoine Pitroue472aea2014-04-26 14:33:03 +0200266 if (urandom_cache.fd >= 0) {
267 /* Does the fd point to the same thing as before? (issue #21207) */
Victor Stinnere134a7f2015-03-30 10:09:31 +0200268 if (_Py_fstat_noraise(urandom_cache.fd, &st)
Antoine Pitroue472aea2014-04-26 14:33:03 +0200269 || st.st_dev != urandom_cache.st_dev
270 || st.st_ino != urandom_cache.st_ino) {
271 /* Something changed: forget the cached fd (but don't close it,
272 since it probably points to something important for some
273 third-party code). */
274 urandom_cache.fd = -1;
275 }
276 }
277 if (urandom_cache.fd >= 0)
278 fd = urandom_cache.fd;
Antoine Pitrou4879a962013-08-31 00:26:02 +0200279 else {
Antoine Pitrou4879a962013-08-31 00:26:02 +0200280 fd = _Py_open("/dev/urandom", O_RDONLY);
Victor Stinnera555cfc2015-03-18 00:22:14 +0100281 if (fd < 0) {
Antoine Pitrou4879a962013-08-31 00:26:02 +0200282 if (errno == ENOENT || errno == ENXIO ||
283 errno == ENODEV || errno == EACCES)
284 PyErr_SetString(PyExc_NotImplementedError,
285 "/dev/urandom (or equivalent) not found");
Victor Stinnera555cfc2015-03-18 00:22:14 +0100286 /* otherwise, keep the OSError exception raised by _Py_open() */
Antoine Pitrou4879a962013-08-31 00:26:02 +0200287 return -1;
288 }
Antoine Pitroue472aea2014-04-26 14:33:03 +0200289 if (urandom_cache.fd >= 0) {
Antoine Pitrou4879a962013-08-31 00:26:02 +0200290 /* urandom_fd was initialized by another thread while we were
291 not holding the GIL, keep it. */
292 close(fd);
Antoine Pitroue472aea2014-04-26 14:33:03 +0200293 fd = urandom_cache.fd;
Antoine Pitrou4879a962013-08-31 00:26:02 +0200294 }
Antoine Pitroue472aea2014-04-26 14:33:03 +0200295 else {
Steve Dowerf2f373f2015-02-21 08:44:05 -0800296 if (_Py_fstat(fd, &st)) {
Antoine Pitroue472aea2014-04-26 14:33:03 +0200297 close(fd);
298 return -1;
299 }
300 else {
301 urandom_cache.fd = fd;
302 urandom_cache.st_dev = st.st_dev;
303 urandom_cache.st_ino = st.st_ino;
304 }
305 }
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100306 }
307
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100308 do {
Victor Stinnerc9382eb2015-03-19 23:36:33 +0100309 n = _Py_read(fd, buffer, (size_t)size);
310 if (n == -1)
311 return -1;
312 if (n == 0) {
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100313 PyErr_Format(PyExc_RuntimeError,
Victor Stinnerc9382eb2015-03-19 23:36:33 +0100314 "Failed to read %zi bytes from /dev/urandom",
315 size);
316 return -1;
317 }
318
319 buffer += n;
320 size -= n;
321 } while (0 < size);
322
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100323 return 0;
324}
Antoine Pitrou4879a962013-08-31 00:26:02 +0200325
326static void
327dev_urandom_close(void)
328{
Antoine Pitroue472aea2014-04-26 14:33:03 +0200329 if (urandom_cache.fd >= 0) {
330 close(urandom_cache.fd);
331 urandom_cache.fd = -1;
Antoine Pitrou4879a962013-08-31 00:26:02 +0200332 }
333}
334
Victor Stinnerbae2d622015-10-01 09:47:30 +0200335#endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100336
337/* Fill buffer with pseudo-random bytes generated by a linear congruent
338 generator (LCG):
339
340 x(n+1) = (x(n) * 214013 + 2531011) % 2^32
341
342 Use bits 23..16 of x(n) to generate a byte. */
343static void
344lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
345{
346 size_t index;
347 unsigned int x;
348
349 x = x0;
350 for (index=0; index < size; index++) {
351 x *= 214013;
352 x += 2531011;
353 /* modulo 2 ^ (8 * sizeof(int)) */
354 buffer[index] = (x >> 16) & 0xff;
355 }
356}
357
Georg Brandlc6a2c9b2013-10-06 18:43:19 +0200358/* Fill buffer with size pseudo-random bytes from the operating system random
Serhiy Storchaka56a6d852014-12-01 18:28:43 +0200359 number generator (RNG). It is suitable for most cryptographic purposes
Georg Brandlc6a2c9b2013-10-06 18:43:19 +0200360 except long living private keys for asymmetric encryption.
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100361
362 Return 0 on success, raise an exception and return -1 on error. */
363int
364_PyOS_URandom(void *buffer, Py_ssize_t size)
365{
366 if (size < 0) {
367 PyErr_Format(PyExc_ValueError,
368 "negative argument not allowed");
369 return -1;
370 }
371 if (size == 0)
372 return 0;
373
374#ifdef MS_WINDOWS
375 return win32_urandom((unsigned char *)buffer, size, 1);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200376#elif defined(PY_GETENTROPY)
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100377 return py_getentropy(buffer, size, 0);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100378#else
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100379 return dev_urandom_python((char*)buffer, size);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100380#endif
381}
382
383void
384_PyRandom_Init(void)
385{
386 char *env;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100387 unsigned char *secret = (unsigned char *)&_Py_HashSecret.uc;
Benjamin Peterson69e97272012-02-21 11:08:50 -0500388 Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
Serhiy Storchakafad85aa2015-11-07 15:42:38 +0200389 Py_BUILD_ASSERT(sizeof(_Py_HashSecret_t) == sizeof(_Py_HashSecret.uc));
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100390
Benjamin Peterson69e97272012-02-21 11:08:50 -0500391 if (_Py_HashSecret_Initialized)
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100392 return;
Benjamin Peterson69e97272012-02-21 11:08:50 -0500393 _Py_HashSecret_Initialized = 1;
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100394
395 /*
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100396 Hash randomization is enabled. Generate a per-process secret,
397 using PYTHONHASHSEED if provided.
398 */
399
400 env = Py_GETENV("PYTHONHASHSEED");
Georg Brandl12897d72012-02-20 23:49:29 +0100401 if (env && *env != '\0' && strcmp(env, "random") != 0) {
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100402 char *endptr = env;
403 unsigned long seed;
404 seed = strtoul(env, &endptr, 10);
405 if (*endptr != '\0'
406 || seed > 4294967295UL
407 || (errno == ERANGE && seed == ULONG_MAX))
408 {
409 Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "
410 "in range [0; 4294967295]");
411 }
412 if (seed == 0) {
413 /* disable the randomized hash */
414 memset(secret, 0, secret_size);
415 }
416 else {
Christian Heimes985ecdc2013-11-20 11:46:18 +0100417 lcg_urandom(seed, secret, secret_size);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100418 }
419 }
420 else {
421#ifdef MS_WINDOWS
Christian Heimes985ecdc2013-11-20 11:46:18 +0100422 (void)win32_urandom(secret, secret_size, 0);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200423#elif defined(PY_GETENTROPY)
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100424 (void)py_getentropy(secret, secret_size, 1);
Christian Heimesaf01f662013-12-21 16:19:10 +0100425#else
Christian Heimes985ecdc2013-11-20 11:46:18 +0100426 dev_urandom_noraise(secret, secret_size);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100427#endif
428 }
429}
Antoine Pitrou4879a962013-08-31 00:26:02 +0200430
431void
432_PyRandom_Fini(void)
433{
Victor Stinnerd50c3f32014-05-02 22:06:44 +0200434#ifdef MS_WINDOWS
435 if (hCryptProv) {
Tim Goldenb8ac3e12014-05-06 13:29:45 +0100436 CryptReleaseContext(hCryptProv, 0);
Victor Stinnerd50c3f32014-05-02 22:06:44 +0200437 hCryptProv = 0;
438 }
Victor Stinnerbae2d622015-10-01 09:47:30 +0200439#elif defined(PY_GETENTROPY)
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100440 /* nothing to clean */
Victor Stinnerd50c3f32014-05-02 22:06:44 +0200441#else
Antoine Pitrou4879a962013-08-31 00:26:02 +0200442 dev_urandom_close();
443#endif
444}