blob: ad8993d9533eebf4416395136300ee3057e13a5a [file] [log] [blame]
Barry Warsaw1e13eb02012-02-20 20:42:21 -05001#include "Python.h"
2#ifdef MS_WINDOWS
3#include <windows.h>
4#else
5#include <fcntl.h>
6#endif
7
Benjamin Peterson26da9202012-02-21 11:08:50 -05008#ifdef Py_DEBUG
9int _Py_HashSecret_Initialized = 0;
10#else
11static int _Py_HashSecret_Initialized = 0;
12#endif
Barry Warsaw1e13eb02012-02-20 20:42:21 -050013
14#ifdef MS_WINDOWS
15typedef BOOL (WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv,\
16 LPCSTR pszContainer, LPCSTR pszProvider, DWORD dwProvType,\
17 DWORD dwFlags );
18typedef BOOL (WINAPI *CRYPTGENRANDOM)(HCRYPTPROV hProv, DWORD dwLen,\
19 BYTE *pbBuffer );
20
21static CRYPTGENRANDOM pCryptGenRandom = NULL;
22/* This handle is never explicitly released. Instead, the operating
23 system will release it when the process terminates. */
24static HCRYPTPROV hCryptProv = 0;
25
26static int
27win32_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
56error:
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. */
66static int
67win32_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 Warsaw1e13eb02012-02-20 20:42:21 -050095
Benjamin Peterson27c269a2014-12-26 11:09:00 -060096#elif HAVE_GETENTROPY
97/* Fill buffer with size pseudo-random bytes generated by getentropy().
98 Return 0 on success, or raise an exception and return -1 on error.
99 If fatal is nonzero, call Py_FatalError() instead of raising an exception
100 on error. */
101static int
102py_getentropy(unsigned char *buffer, Py_ssize_t size, int fatal)
103{
104 while (size > 0) {
Serhiy Storchakae8d750c2015-02-16 08:05:10 +0200105 Py_ssize_t len = size < 256 ? size : 256;
Benjamin Peterson27c269a2014-12-26 11:09:00 -0600106 int res = getentropy(buffer, len);
107 if (res < 0) {
108 if (fatal) {
109 Py_FatalError("getentropy() failed");
110 }
111 else {
112 PyErr_SetFromErrno(PyExc_OSError);
113 return -1;
114 }
115 }
116 buffer += len;
117 size -= len;
118 }
119 return 0;
120}
121#endif
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500122
123#ifdef __VMS
124/* Use openssl random routine */
125#include <openssl/rand.h>
126static int
127vms_urandom(unsigned char *buffer, Py_ssize_t size, int raise)
128{
129 if (RAND_pseudo_bytes(buffer, size) < 0) {
130 if (raise) {
131 PyErr_Format(PyExc_ValueError,
132 "RAND_pseudo_bytes");
133 } else {
134 Py_FatalError("Failed to initialize the randomized hash "
135 "secret using RAND_pseudo_bytes");
136 }
137 return -1;
138 }
139 return 0;
140}
141#endif /* __VMS */
142
143
144#if !defined(MS_WINDOWS) && !defined(__VMS)
145
Benjamin Peterson57057a62014-08-28 12:30:00 -0400146static struct {
147 int fd;
148 dev_t st_dev;
149 ino_t st_ino;
150} urandom_cache = { -1 };
151
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500152/* Read size bytes from /dev/urandom into buffer.
153 Call Py_FatalError() on error. */
154static void
Benjamin Peterson57057a62014-08-28 12:30:00 -0400155dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500156{
157 int fd;
158 Py_ssize_t n;
159
160 assert (0 < size);
161
162 fd = open("/dev/urandom", O_RDONLY);
163 if (fd < 0)
164 Py_FatalError("Failed to open /dev/urandom");
165
166 while (0 < size)
167 {
168 do {
169 n = read(fd, buffer, (size_t)size);
170 } while (n < 0 && errno == EINTR);
171 if (n <= 0)
172 {
173 /* stop on error or if read(size) returned 0 */
174 Py_FatalError("Failed to read bytes from /dev/urandom");
175 break;
176 }
177 buffer += n;
178 size -= (Py_ssize_t)n;
179 }
180 close(fd);
181}
182
183/* Read size bytes from /dev/urandom into buffer.
184 Return 0 on success, raise an exception and return -1 on error. */
185static int
186dev_urandom_python(char *buffer, Py_ssize_t size)
187{
188 int fd;
189 Py_ssize_t n;
Benjamin Peterson57057a62014-08-28 12:30:00 -0400190 struct stat st;
Victor Stinnere0a0bd62015-02-24 14:30:43 +0100191 int attr;
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500192
193 if (size <= 0)
194 return 0;
195
Benjamin Peterson57057a62014-08-28 12:30:00 -0400196 if (urandom_cache.fd >= 0) {
197 /* Does the fd point to the same thing as before? (issue #21207) */
198 if (fstat(urandom_cache.fd, &st)
199 || st.st_dev != urandom_cache.st_dev
200 || st.st_ino != urandom_cache.st_ino) {
201 /* Something changed: forget the cached fd (but don't close it,
202 since it probably points to something important for some
203 third-party code). */
204 urandom_cache.fd = -1;
205 }
206 }
207 if (urandom_cache.fd >= 0)
208 fd = urandom_cache.fd;
209 else {
210 Py_BEGIN_ALLOW_THREADS
211 fd = open("/dev/urandom", O_RDONLY);
212 Py_END_ALLOW_THREADS
213 if (fd < 0)
214 {
215 if (errno == ENOENT || errno == ENXIO ||
216 errno == ENODEV || errno == EACCES)
217 PyErr_SetString(PyExc_NotImplementedError,
218 "/dev/urandom (or equivalent) not found");
219 else
220 PyErr_SetFromErrno(PyExc_OSError);
221 return -1;
222 }
Victor Stinnere0a0bd62015-02-24 14:30:43 +0100223
224 /* try to make the file descriptor non-inheritable, ignore errors */
225 attr = fcntl(fd, F_GETFD);
226 if (attr >= 0) {
227 attr |= FD_CLOEXEC;
228 (void)fcntl(fd, F_SETFD, attr);
229 }
230
Benjamin Peterson57057a62014-08-28 12:30:00 -0400231 if (urandom_cache.fd >= 0) {
232 /* urandom_fd was initialized by another thread while we were
233 not holding the GIL, keep it. */
234 close(fd);
235 fd = urandom_cache.fd;
236 }
237 else {
238 if (fstat(fd, &st)) {
239 PyErr_SetFromErrno(PyExc_OSError);
240 close(fd);
241 return -1;
242 }
243 else {
244 urandom_cache.fd = fd;
245 urandom_cache.st_dev = st.st_dev;
246 urandom_cache.st_ino = st.st_ino;
247 }
248 }
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500249 }
250
251 Py_BEGIN_ALLOW_THREADS
252 do {
253 do {
254 n = read(fd, buffer, (size_t)size);
255 } while (n < 0 && errno == EINTR);
256 if (n <= 0)
257 break;
258 buffer += n;
259 size -= (Py_ssize_t)n;
260 } while (0 < size);
261 Py_END_ALLOW_THREADS
262
263 if (n <= 0)
264 {
265 /* stop on error or if read(size) returned 0 */
266 if (n < 0)
267 PyErr_SetFromErrno(PyExc_OSError);
268 else
269 PyErr_Format(PyExc_RuntimeError,
270 "Failed to read %zi bytes from /dev/urandom",
271 size);
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500272 return -1;
273 }
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500274 return 0;
275}
Benjamin Peterson57057a62014-08-28 12:30:00 -0400276
277static void
278dev_urandom_close(void)
279{
280 if (urandom_cache.fd >= 0) {
281 close(urandom_cache.fd);
282 urandom_cache.fd = -1;
283 }
284}
285
286
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500287#endif /* !defined(MS_WINDOWS) && !defined(__VMS) */
288
289/* Fill buffer with pseudo-random bytes generated by a linear congruent
290 generator (LCG):
291
292 x(n+1) = (x(n) * 214013 + 2531011) % 2^32
293
294 Use bits 23..16 of x(n) to generate a byte. */
295static void
296lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)
297{
298 size_t index;
299 unsigned int x;
300
301 x = x0;
302 for (index=0; index < size; index++) {
303 x *= 214013;
304 x += 2531011;
305 /* modulo 2 ^ (8 * sizeof(int)) */
306 buffer[index] = (x >> 16) & 0xff;
307 }
308}
309
Georg Brandlc0edade2013-10-06 18:43:19 +0200310/* Fill buffer with size pseudo-random bytes from the operating system random
Serhiy Storchaka0f8f7842014-12-01 18:16:30 +0200311 number generator (RNG). It is suitable for most cryptographic purposes
Georg Brandlc0edade2013-10-06 18:43:19 +0200312 except long living private keys for asymmetric encryption.
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500313
314 Return 0 on success, raise an exception and return -1 on error. */
315int
316_PyOS_URandom(void *buffer, Py_ssize_t size)
317{
318 if (size < 0) {
319 PyErr_Format(PyExc_ValueError,
320 "negative argument not allowed");
321 return -1;
322 }
323 if (size == 0)
324 return 0;
325
326#ifdef MS_WINDOWS
327 return win32_urandom((unsigned char *)buffer, size, 1);
Benjamin Peterson27c269a2014-12-26 11:09:00 -0600328#elif HAVE_GETENTROPY
329 return py_getentropy(buffer, size, 0);
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500330#else
331# ifdef __VMS
332 return vms_urandom((unsigned char *)buffer, size, 1);
333# else
334 return dev_urandom_python((char*)buffer, size);
335# endif
336#endif
337}
338
339void
340_PyRandom_Init(void)
341{
342 char *env;
343 void *secret = &_Py_HashSecret;
Benjamin Peterson26da9202012-02-21 11:08:50 -0500344 Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500345
Benjamin Peterson26da9202012-02-21 11:08:50 -0500346 if (_Py_HashSecret_Initialized)
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500347 return;
Benjamin Peterson26da9202012-02-21 11:08:50 -0500348 _Py_HashSecret_Initialized = 1;
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500349
350 /*
351 By default, hash randomization is disabled, and only
352 enabled if PYTHONHASHSEED is set to non-empty or if
353 "-R" is provided at the command line:
354 */
355 if (!Py_HashRandomizationFlag) {
356 /* Disable the randomized hash: */
357 memset(secret, 0, secret_size);
358 return;
359 }
360
361 /*
362 Hash randomization is enabled. Generate a per-process secret,
363 using PYTHONHASHSEED if provided.
364 */
365
366 env = Py_GETENV("PYTHONHASHSEED");
367 if (env && *env != '\0' && strcmp(env, "random") != 0) {
368 char *endptr = env;
369 unsigned long seed;
370 seed = strtoul(env, &endptr, 10);
371 if (*endptr != '\0'
372 || seed > 4294967295UL
373 || (errno == ERANGE && seed == ULONG_MAX))
374 {
375 Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "
376 "in range [0; 4294967295]");
377 }
378 if (seed == 0) {
379 /* disable the randomized hash */
380 memset(secret, 0, secret_size);
381 }
382 else {
383 lcg_urandom(seed, (unsigned char*)secret, secret_size);
384 }
385 }
386 else {
387#ifdef MS_WINDOWS
388 (void)win32_urandom((unsigned char *)secret, secret_size, 0);
Benjamin Peterson27c269a2014-12-26 11:09:00 -0600389#elif __VMS
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500390 vms_urandom((unsigned char *)secret, secret_size, 0);
Benjamin Peterson27c269a2014-12-26 11:09:00 -0600391#elif HAVE_GETENTROPY
392 (void)py_getentropy(secret, secret_size, 1);
393#else
394 dev_urandom_noraise(secret, secret_size);
Barry Warsaw1e13eb02012-02-20 20:42:21 -0500395#endif
396 }
397}
Benjamin Peterson57057a62014-08-28 12:30:00 -0400398
399void
400_PyRandom_Fini(void)
401{
402#ifdef MS_WINDOWS
403 if (hCryptProv) {
404 CryptReleaseContext(hCryptProv, 0);
405 hCryptProv = 0;
406 }
Benjamin Peterson27c269a2014-12-26 11:09:00 -0600407#elif HAVE_GETENTROPY
408 /* nothing to clean */
Benjamin Peterson57057a62014-08-28 12:30:00 -0400409#else
410 dev_urandom_close();
411#endif
412}