blob: 9b42d5498c7694996d3a6c875b46393ae80f637e [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) {
134 errno = 0;
Victor Stinner79b74ae2015-03-30 11:16:40 +0200135
Victor Stinnerbae2d622015-10-01 09:47:30 +0200136#ifdef HAVE_GETRANDOM
137 if (raise) {
138 Py_BEGIN_ALLOW_THREADS
139 n = getrandom(buffer, size, flags);
140 Py_END_ALLOW_THREADS
141 }
142 else {
143 n = getrandom(buffer, size, flags);
144 }
145#else
146 /* On Linux, use the syscall() function because the GNU libc doesn't
147 * expose the Linux getrandom() syscall yet. See:
Victor Stinner59f7fb22015-03-18 14:39:33 +0100148 * https://sourceware.org/bugzilla/show_bug.cgi?id=17252 */
Victor Stinner79b74ae2015-03-30 11:16:40 +0200149 if (raise) {
150 Py_BEGIN_ALLOW_THREADS
151 n = syscall(SYS_getrandom, buffer, size, flags);
152 Py_END_ALLOW_THREADS
153 }
154 else {
155 n = syscall(SYS_getrandom, buffer, size, flags);
156 }
Victor Stinnerbae2d622015-10-01 09:47:30 +0200157#endif
Victor Stinner79b74ae2015-03-30 11:16:40 +0200158
Victor Stinner59f7fb22015-03-18 14:39:33 +0100159 if (n < 0) {
160 if (errno == ENOSYS) {
161 getrandom_works = 0;
162 return 0;
163 }
164
165 if (errno == EINTR) {
Victor Stinner59f7fb22015-03-18 14:39:33 +0100166 if (PyErr_CheckSignals()) {
167 if (!raise)
168 Py_FatalError("getrandom() interrupted by a signal");
169 return -1;
170 }
171 /* retry getrandom() */
172 continue;
173 }
174
175 if (raise)
176 PyErr_SetFromErrno(PyExc_OSError);
177 else
178 Py_FatalError("getrandom() failed");
179 return -1;
180 }
181
182 buffer += n;
183 size -= n;
184 }
185 return 1;
186}
187#endif
188
Antoine Pitroue472aea2014-04-26 14:33:03 +0200189static struct {
190 int fd;
191 dev_t st_dev;
192 ino_t st_ino;
193} urandom_cache = { -1 };
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100194
Victor Stinner59f7fb22015-03-18 14:39:33 +0100195
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100196/* Read size bytes from /dev/urandom into buffer.
197 Call Py_FatalError() on error. */
198static void
Christian Heimes985ecdc2013-11-20 11:46:18 +0100199dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size)
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100200{
201 int fd;
202 Py_ssize_t n;
203
204 assert (0 < size);
205
Victor Stinnerbae2d622015-10-01 09:47:30 +0200206#ifdef PY_GETRANDOM
Victor Stinner59f7fb22015-03-18 14:39:33 +0100207 if (py_getrandom(buffer, size, 0) == 1)
208 return;
209 /* getrandom() is not supported by the running kernel, fall back
210 * on reading /dev/urandom */
211#endif
212
Victor Stinnerc7cd12d2015-03-19 23:24:45 +0100213 fd = _Py_open_noraise("/dev/urandom", O_RDONLY);
214 if (fd < 0)
215 Py_FatalError("Failed to open /dev/urandom");
216
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100217 while (0 < size)
218 {
219 do {
220 n = read(fd, buffer, (size_t)size);
221 } while (n < 0 && errno == EINTR);
222 if (n <= 0)
223 {
224 /* stop on error or if read(size) returned 0 */
225 Py_FatalError("Failed to read bytes from /dev/urandom");
226 break;
227 }
228 buffer += n;
229 size -= (Py_ssize_t)n;
230 }
231 close(fd);
232}
233
234/* Read size bytes from /dev/urandom into buffer.
235 Return 0 on success, raise an exception and return -1 on error. */
236static int
237dev_urandom_python(char *buffer, Py_ssize_t size)
238{
239 int fd;
240 Py_ssize_t n;
Steve Dowerf2f373f2015-02-21 08:44:05 -0800241 struct _Py_stat_struct st;
Victor Stinnerbae2d622015-10-01 09:47:30 +0200242#ifdef PY_GETRANDOM
Victor Stinner59f7fb22015-03-18 14:39:33 +0100243 int res;
244#endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100245
246 if (size <= 0)
247 return 0;
248
Victor Stinnerbae2d622015-10-01 09:47:30 +0200249#ifdef PY_GETRANDOM
Victor Stinner59f7fb22015-03-18 14:39:33 +0100250 res = py_getrandom(buffer, size, 1);
251 if (res < 0)
252 return -1;
253 if (res == 1)
254 return 0;
255 /* getrandom() is not supported by the running kernel, fall back
256 * on reading /dev/urandom */
257#endif
258
Antoine Pitroue472aea2014-04-26 14:33:03 +0200259 if (urandom_cache.fd >= 0) {
260 /* Does the fd point to the same thing as before? (issue #21207) */
Victor Stinnere134a7f2015-03-30 10:09:31 +0200261 if (_Py_fstat_noraise(urandom_cache.fd, &st)
Antoine Pitroue472aea2014-04-26 14:33:03 +0200262 || st.st_dev != urandom_cache.st_dev
263 || st.st_ino != urandom_cache.st_ino) {
264 /* Something changed: forget the cached fd (but don't close it,
265 since it probably points to something important for some
266 third-party code). */
267 urandom_cache.fd = -1;
268 }
269 }
270 if (urandom_cache.fd >= 0)
271 fd = urandom_cache.fd;
Antoine Pitrou4879a962013-08-31 00:26:02 +0200272 else {
Antoine Pitrou4879a962013-08-31 00:26:02 +0200273 fd = _Py_open("/dev/urandom", O_RDONLY);
Victor Stinnera555cfc2015-03-18 00:22:14 +0100274 if (fd < 0) {
Antoine Pitrou4879a962013-08-31 00:26:02 +0200275 if (errno == ENOENT || errno == ENXIO ||
276 errno == ENODEV || errno == EACCES)
277 PyErr_SetString(PyExc_NotImplementedError,
278 "/dev/urandom (or equivalent) not found");
Victor Stinnera555cfc2015-03-18 00:22:14 +0100279 /* otherwise, keep the OSError exception raised by _Py_open() */
Antoine Pitrou4879a962013-08-31 00:26:02 +0200280 return -1;
281 }
Antoine Pitroue472aea2014-04-26 14:33:03 +0200282 if (urandom_cache.fd >= 0) {
Antoine Pitrou4879a962013-08-31 00:26:02 +0200283 /* urandom_fd was initialized by another thread while we were
284 not holding the GIL, keep it. */
285 close(fd);
Antoine Pitroue472aea2014-04-26 14:33:03 +0200286 fd = urandom_cache.fd;
Antoine Pitrou4879a962013-08-31 00:26:02 +0200287 }
Antoine Pitroue472aea2014-04-26 14:33:03 +0200288 else {
Steve Dowerf2f373f2015-02-21 08:44:05 -0800289 if (_Py_fstat(fd, &st)) {
Antoine Pitroue472aea2014-04-26 14:33:03 +0200290 close(fd);
291 return -1;
292 }
293 else {
294 urandom_cache.fd = fd;
295 urandom_cache.st_dev = st.st_dev;
296 urandom_cache.st_ino = st.st_ino;
297 }
298 }
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100299 }
300
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100301 do {
Victor Stinnerc9382eb2015-03-19 23:36:33 +0100302 n = _Py_read(fd, buffer, (size_t)size);
303 if (n == -1)
304 return -1;
305 if (n == 0) {
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100306 PyErr_Format(PyExc_RuntimeError,
Victor Stinnerc9382eb2015-03-19 23:36:33 +0100307 "Failed to read %zi bytes from /dev/urandom",
308 size);
309 return -1;
310 }
311
312 buffer += n;
313 size -= n;
314 } while (0 < size);
315
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100316 return 0;
317}
Antoine Pitrou4879a962013-08-31 00:26:02 +0200318
319static void
320dev_urandom_close(void)
321{
Antoine Pitroue472aea2014-04-26 14:33:03 +0200322 if (urandom_cache.fd >= 0) {
323 close(urandom_cache.fd);
324 urandom_cache.fd = -1;
Antoine Pitrou4879a962013-08-31 00:26:02 +0200325 }
326}
327
Victor Stinnerbae2d622015-10-01 09:47:30 +0200328#endif
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100329
330/* Fill buffer with pseudo-random bytes generated by a linear congruent
331 generator (LCG):
332
333 x(n+1) = (x(n) * 214013 + 2531011) % 2^32
334
335 Use bits 23..16 of x(n) to generate a byte. */
336static void
337lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
338{
339 size_t index;
340 unsigned int x;
341
342 x = x0;
343 for (index=0; index < size; index++) {
344 x *= 214013;
345 x += 2531011;
346 /* modulo 2 ^ (8 * sizeof(int)) */
347 buffer[index] = (x >> 16) & 0xff;
348 }
349}
350
Georg Brandlc6a2c9b2013-10-06 18:43:19 +0200351/* Fill buffer with size pseudo-random bytes from the operating system random
Serhiy Storchaka56a6d852014-12-01 18:28:43 +0200352 number generator (RNG). It is suitable for most cryptographic purposes
Georg Brandlc6a2c9b2013-10-06 18:43:19 +0200353 except long living private keys for asymmetric encryption.
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100354
355 Return 0 on success, raise an exception and return -1 on error. */
356int
357_PyOS_URandom(void *buffer, Py_ssize_t size)
358{
359 if (size < 0) {
360 PyErr_Format(PyExc_ValueError,
361 "negative argument not allowed");
362 return -1;
363 }
364 if (size == 0)
365 return 0;
366
367#ifdef MS_WINDOWS
368 return win32_urandom((unsigned char *)buffer, size, 1);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200369#elif defined(PY_GETENTROPY)
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100370 return py_getentropy(buffer, size, 0);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100371#else
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100372 return dev_urandom_python((char*)buffer, size);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100373#endif
374}
375
376void
377_PyRandom_Init(void)
378{
379 char *env;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100380 unsigned char *secret = (unsigned char *)&_Py_HashSecret.uc;
Benjamin Peterson69e97272012-02-21 11:08:50 -0500381 Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
Serhiy Storchakafad85aa2015-11-07 15:42:38 +0200382 Py_BUILD_ASSERT(sizeof(_Py_HashSecret_t) == sizeof(_Py_HashSecret.uc));
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100383
Benjamin Peterson69e97272012-02-21 11:08:50 -0500384 if (_Py_HashSecret_Initialized)
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100385 return;
Benjamin Peterson69e97272012-02-21 11:08:50 -0500386 _Py_HashSecret_Initialized = 1;
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100387
388 /*
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100389 Hash randomization is enabled. Generate a per-process secret,
390 using PYTHONHASHSEED if provided.
391 */
392
393 env = Py_GETENV("PYTHONHASHSEED");
Georg Brandl12897d72012-02-20 23:49:29 +0100394 if (env && *env != '\0' && strcmp(env, "random") != 0) {
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100395 char *endptr = env;
396 unsigned long seed;
397 seed = strtoul(env, &endptr, 10);
398 if (*endptr != '\0'
399 || seed > 4294967295UL
400 || (errno == ERANGE && seed == ULONG_MAX))
401 {
402 Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "
403 "in range [0; 4294967295]");
404 }
405 if (seed == 0) {
406 /* disable the randomized hash */
407 memset(secret, 0, secret_size);
408 }
409 else {
Christian Heimes985ecdc2013-11-20 11:46:18 +0100410 lcg_urandom(seed, secret, secret_size);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100411 }
412 }
413 else {
414#ifdef MS_WINDOWS
Christian Heimes985ecdc2013-11-20 11:46:18 +0100415 (void)win32_urandom(secret, secret_size, 0);
Victor Stinnerbae2d622015-10-01 09:47:30 +0200416#elif defined(PY_GETENTROPY)
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100417 (void)py_getentropy(secret, secret_size, 1);
Christian Heimesaf01f662013-12-21 16:19:10 +0100418#else
Christian Heimes985ecdc2013-11-20 11:46:18 +0100419 dev_urandom_noraise(secret, secret_size);
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100420#endif
421 }
422}
Antoine Pitrou4879a962013-08-31 00:26:02 +0200423
424void
425_PyRandom_Fini(void)
426{
Victor Stinnerd50c3f32014-05-02 22:06:44 +0200427#ifdef MS_WINDOWS
428 if (hCryptProv) {
Tim Goldenb8ac3e12014-05-06 13:29:45 +0100429 CryptReleaseContext(hCryptProv, 0);
Victor Stinnerd50c3f32014-05-02 22:06:44 +0200430 hCryptProv = 0;
431 }
Victor Stinnerbae2d622015-10-01 09:47:30 +0200432#elif defined(PY_GETENTROPY)
Victor Stinner4d6a3d62014-12-21 01:16:38 +0100433 /* nothing to clean */
Victor Stinnerd50c3f32014-05-02 22:06:44 +0200434#else
Antoine Pitrou4879a962013-08-31 00:26:02 +0200435 dev_urandom_close();
436#endif
437}