]>
Commit | Line | Data |
---|---|---|
3ec97ca4 DM |
1 | #include "Python.h"\r |
2 | #ifdef MS_WINDOWS\r | |
3 | #include <windows.h>\r | |
4 | #else\r | |
5 | #include <fcntl.h>\r | |
6 | #endif\r | |
7 | \r | |
8 | #ifdef Py_DEBUG\r | |
9 | int _Py_HashSecret_Initialized = 0;\r | |
10 | #else\r | |
11 | static int _Py_HashSecret_Initialized = 0;\r | |
12 | #endif\r | |
13 | \r | |
14 | #ifdef MS_WINDOWS\r | |
15 | typedef BOOL (WINAPI *CRYPTACQUIRECONTEXTA)(HCRYPTPROV *phProv,\\r | |
16 | LPCSTR pszContainer, LPCSTR pszProvider, DWORD dwProvType,\\r | |
17 | DWORD dwFlags );\r | |
18 | typedef BOOL (WINAPI *CRYPTGENRANDOM)(HCRYPTPROV hProv, DWORD dwLen,\\r | |
19 | BYTE *pbBuffer );\r | |
20 | \r | |
21 | static CRYPTGENRANDOM pCryptGenRandom = NULL;\r | |
22 | /* This handle is never explicitly released. Instead, the operating\r | |
23 | system will release it when the process terminates. */\r | |
24 | static HCRYPTPROV hCryptProv = 0;\r | |
25 | \r | |
26 | static int\r | |
27 | win32_urandom_init(int raise)\r | |
28 | {\r | |
29 | HINSTANCE hAdvAPI32 = NULL;\r | |
30 | CRYPTACQUIRECONTEXTA pCryptAcquireContext = NULL;\r | |
31 | \r | |
32 | /* Obtain handle to the DLL containing CryptoAPI. This should not fail. */\r | |
33 | hAdvAPI32 = GetModuleHandle("advapi32.dll");\r | |
34 | if(hAdvAPI32 == NULL)\r | |
35 | goto error;\r | |
36 | \r | |
37 | /* Obtain pointers to the CryptoAPI functions. This will fail on some early\r | |
38 | versions of Win95. */\r | |
39 | pCryptAcquireContext = (CRYPTACQUIRECONTEXTA)GetProcAddress(\r | |
40 | hAdvAPI32, "CryptAcquireContextA");\r | |
41 | if (pCryptAcquireContext == NULL)\r | |
42 | goto error;\r | |
43 | \r | |
44 | pCryptGenRandom = (CRYPTGENRANDOM)GetProcAddress(hAdvAPI32,\r | |
45 | "CryptGenRandom");\r | |
46 | if (pCryptGenRandom == NULL)\r | |
47 | goto error;\r | |
48 | \r | |
49 | /* Acquire context */\r | |
50 | if (! pCryptAcquireContext(&hCryptProv, NULL, NULL,\r | |
51 | PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))\r | |
52 | goto error;\r | |
53 | \r | |
54 | return 0;\r | |
55 | \r | |
56 | error:\r | |
57 | if (raise)\r | |
58 | PyErr_SetFromWindowsErr(0);\r | |
59 | else\r | |
60 | Py_FatalError("Failed to initialize Windows random API (CryptoGen)");\r | |
61 | return -1;\r | |
62 | }\r | |
63 | \r | |
64 | /* Fill buffer with size pseudo-random bytes generated by the Windows CryptoGen\r | |
65 | API. Return 0 on success, or -1 on error. */\r | |
66 | static int\r | |
67 | win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise)\r | |
68 | {\r | |
69 | Py_ssize_t chunk;\r | |
70 | \r | |
71 | if (hCryptProv == 0)\r | |
72 | {\r | |
73 | if (win32_urandom_init(raise) == -1)\r | |
74 | return -1;\r | |
75 | }\r | |
76 | \r | |
77 | while (size > 0)\r | |
78 | {\r | |
79 | chunk = size > INT_MAX ? INT_MAX : size;\r | |
80 | if (!pCryptGenRandom(hCryptProv, chunk, buffer))\r | |
81 | {\r | |
82 | /* CryptGenRandom() failed */\r | |
83 | if (raise)\r | |
84 | PyErr_SetFromWindowsErr(0);\r | |
85 | else\r | |
86 | Py_FatalError("Failed to initialized the randomized hash "\r | |
87 | "secret using CryptoGen)");\r | |
88 | return -1;\r | |
89 | }\r | |
90 | buffer += chunk;\r | |
91 | size -= chunk;\r | |
92 | }\r | |
93 | return 0;\r | |
94 | }\r | |
95 | \r | |
96 | #elif HAVE_GETENTROPY\r | |
97 | /* Fill buffer with size pseudo-random bytes generated by getentropy().\r | |
98 | Return 0 on success, or raise an exception and return -1 on error.\r | |
99 | If fatal is nonzero, call Py_FatalError() instead of raising an exception\r | |
100 | on error. */\r | |
101 | static int\r | |
102 | py_getentropy(unsigned char *buffer, Py_ssize_t size, int fatal)\r | |
103 | {\r | |
104 | while (size > 0) {\r | |
105 | Py_ssize_t len = size < 256 ? size : 256;\r | |
106 | int res;\r | |
107 | \r | |
108 | if (!fatal) {\r | |
109 | Py_BEGIN_ALLOW_THREADS\r | |
110 | res = getentropy(buffer, len);\r | |
111 | Py_END_ALLOW_THREADS\r | |
112 | \r | |
113 | if (res < 0) {\r | |
114 | PyErr_SetFromErrno(PyExc_OSError);\r | |
115 | return -1;\r | |
116 | }\r | |
117 | }\r | |
118 | else {\r | |
119 | res = getentropy(buffer, len);\r | |
120 | if (res < 0)\r | |
121 | Py_FatalError("getentropy() failed");\r | |
122 | }\r | |
123 | \r | |
124 | buffer += len;\r | |
125 | size -= len;\r | |
126 | }\r | |
127 | return 0;\r | |
128 | }\r | |
129 | #endif\r | |
130 | \r | |
131 | #ifdef __VMS\r | |
132 | /* Use openssl random routine */\r | |
133 | #include <openssl/rand.h>\r | |
134 | static int\r | |
135 | vms_urandom(unsigned char *buffer, Py_ssize_t size, int raise)\r | |
136 | {\r | |
137 | if (RAND_pseudo_bytes(buffer, size) < 0) {\r | |
138 | if (raise) {\r | |
139 | PyErr_Format(PyExc_ValueError,\r | |
140 | "RAND_pseudo_bytes");\r | |
141 | } else {\r | |
142 | Py_FatalError("Failed to initialize the randomized hash "\r | |
143 | "secret using RAND_pseudo_bytes");\r | |
144 | }\r | |
145 | return -1;\r | |
146 | }\r | |
147 | return 0;\r | |
148 | }\r | |
149 | #endif /* __VMS */\r | |
150 | \r | |
151 | \r | |
152 | #if !defined(MS_WINDOWS) && !defined(__VMS)\r | |
153 | \r | |
154 | static struct {\r | |
155 | int fd;\r | |
156 | dev_t st_dev;\r | |
157 | ino_t st_ino;\r | |
158 | } urandom_cache = { -1 };\r | |
159 | \r | |
160 | /* Read size bytes from /dev/urandom into buffer.\r | |
161 | Call Py_FatalError() on error. */\r | |
162 | static void\r | |
163 | dev_urandom_noraise(unsigned char *buffer, Py_ssize_t size)\r | |
164 | {\r | |
165 | int fd;\r | |
166 | Py_ssize_t n;\r | |
167 | \r | |
168 | assert (0 < size);\r | |
169 | \r | |
170 | fd = open("/dev/urandom", O_RDONLY);\r | |
171 | if (fd < 0)\r | |
172 | Py_FatalError("Failed to open /dev/urandom");\r | |
173 | \r | |
174 | while (0 < size)\r | |
175 | {\r | |
176 | do {\r | |
177 | n = read(fd, buffer, (size_t)size);\r | |
178 | } while (n < 0 && errno == EINTR);\r | |
179 | if (n <= 0)\r | |
180 | {\r | |
181 | /* stop on error or if read(size) returned 0 */\r | |
182 | Py_FatalError("Failed to read bytes from /dev/urandom");\r | |
183 | break;\r | |
184 | }\r | |
185 | buffer += n;\r | |
186 | size -= (Py_ssize_t)n;\r | |
187 | }\r | |
188 | close(fd);\r | |
189 | }\r | |
190 | \r | |
191 | /* Read size bytes from /dev/urandom into buffer.\r | |
192 | Return 0 on success, raise an exception and return -1 on error. */\r | |
193 | static int\r | |
194 | dev_urandom_python(char *buffer, Py_ssize_t size)\r | |
195 | {\r | |
196 | int fd;\r | |
197 | Py_ssize_t n;\r | |
198 | struct stat st;\r | |
199 | int attr;\r | |
200 | \r | |
201 | if (size <= 0)\r | |
202 | return 0;\r | |
203 | \r | |
204 | if (urandom_cache.fd >= 0) {\r | |
205 | /* Does the fd point to the same thing as before? (issue #21207) */\r | |
206 | if (fstat(urandom_cache.fd, &st)\r | |
207 | || st.st_dev != urandom_cache.st_dev\r | |
208 | || st.st_ino != urandom_cache.st_ino) {\r | |
209 | /* Something changed: forget the cached fd (but don't close it,\r | |
210 | since it probably points to something important for some\r | |
211 | third-party code). */\r | |
212 | urandom_cache.fd = -1;\r | |
213 | }\r | |
214 | }\r | |
215 | if (urandom_cache.fd >= 0)\r | |
216 | fd = urandom_cache.fd;\r | |
217 | else {\r | |
218 | Py_BEGIN_ALLOW_THREADS\r | |
219 | fd = open("/dev/urandom", O_RDONLY);\r | |
220 | Py_END_ALLOW_THREADS\r | |
221 | if (fd < 0)\r | |
222 | {\r | |
223 | if (errno == ENOENT || errno == ENXIO ||\r | |
224 | errno == ENODEV || errno == EACCES)\r | |
225 | PyErr_SetString(PyExc_NotImplementedError,\r | |
226 | "/dev/urandom (or equivalent) not found");\r | |
227 | else\r | |
228 | PyErr_SetFromErrno(PyExc_OSError);\r | |
229 | return -1;\r | |
230 | }\r | |
231 | \r | |
232 | /* try to make the file descriptor non-inheritable, ignore errors */\r | |
233 | attr = fcntl(fd, F_GETFD);\r | |
234 | if (attr >= 0) {\r | |
235 | attr |= FD_CLOEXEC;\r | |
236 | (void)fcntl(fd, F_SETFD, attr);\r | |
237 | }\r | |
238 | \r | |
239 | if (urandom_cache.fd >= 0) {\r | |
240 | /* urandom_fd was initialized by another thread while we were\r | |
241 | not holding the GIL, keep it. */\r | |
242 | close(fd);\r | |
243 | fd = urandom_cache.fd;\r | |
244 | }\r | |
245 | else {\r | |
246 | if (fstat(fd, &st)) {\r | |
247 | PyErr_SetFromErrno(PyExc_OSError);\r | |
248 | close(fd);\r | |
249 | return -1;\r | |
250 | }\r | |
251 | else {\r | |
252 | urandom_cache.fd = fd;\r | |
253 | urandom_cache.st_dev = st.st_dev;\r | |
254 | urandom_cache.st_ino = st.st_ino;\r | |
255 | }\r | |
256 | }\r | |
257 | }\r | |
258 | \r | |
259 | Py_BEGIN_ALLOW_THREADS\r | |
260 | do {\r | |
261 | do {\r | |
262 | n = read(fd, buffer, (size_t)size);\r | |
263 | } while (n < 0 && errno == EINTR);\r | |
264 | if (n <= 0)\r | |
265 | break;\r | |
266 | buffer += n;\r | |
267 | size -= (Py_ssize_t)n;\r | |
268 | } while (0 < size);\r | |
269 | Py_END_ALLOW_THREADS\r | |
270 | \r | |
271 | if (n <= 0)\r | |
272 | {\r | |
273 | /* stop on error or if read(size) returned 0 */\r | |
274 | if (n < 0)\r | |
275 | PyErr_SetFromErrno(PyExc_OSError);\r | |
276 | else\r | |
277 | PyErr_Format(PyExc_RuntimeError,\r | |
278 | "Failed to read %zi bytes from /dev/urandom",\r | |
279 | size);\r | |
280 | return -1;\r | |
281 | }\r | |
282 | return 0;\r | |
283 | }\r | |
284 | \r | |
285 | static void\r | |
286 | dev_urandom_close(void)\r | |
287 | {\r | |
288 | if (urandom_cache.fd >= 0) {\r | |
289 | close(urandom_cache.fd);\r | |
290 | urandom_cache.fd = -1;\r | |
291 | }\r | |
292 | }\r | |
293 | \r | |
294 | \r | |
295 | #endif /* !defined(MS_WINDOWS) && !defined(__VMS) */\r | |
296 | \r | |
297 | /* Fill buffer with pseudo-random bytes generated by a linear congruent\r | |
298 | generator (LCG):\r | |
299 | \r | |
300 | x(n+1) = (x(n) * 214013 + 2531011) % 2^32\r | |
301 | \r | |
302 | Use bits 23..16 of x(n) to generate a byte. */\r | |
303 | static void\r | |
304 | lcg_urandom(unsigned int x0, unsigned char *buffer, size_t size)\r | |
305 | {\r | |
306 | size_t index;\r | |
307 | unsigned int x;\r | |
308 | \r | |
309 | x = x0;\r | |
310 | for (index=0; index < size; index++) {\r | |
311 | x *= 214013;\r | |
312 | x += 2531011;\r | |
313 | /* modulo 2 ^ (8 * sizeof(int)) */\r | |
314 | buffer[index] = (x >> 16) & 0xff;\r | |
315 | }\r | |
316 | }\r | |
317 | \r | |
318 | /* Fill buffer with size pseudo-random bytes from the operating system random\r | |
319 | number generator (RNG). It is suitable for most cryptographic purposes\r | |
320 | except long living private keys for asymmetric encryption.\r | |
321 | \r | |
322 | Return 0 on success, raise an exception and return -1 on error. */\r | |
323 | int\r | |
324 | _PyOS_URandom(void *buffer, Py_ssize_t size)\r | |
325 | {\r | |
326 | if (size < 0) {\r | |
327 | PyErr_Format(PyExc_ValueError,\r | |
328 | "negative argument not allowed");\r | |
329 | return -1;\r | |
330 | }\r | |
331 | if (size == 0)\r | |
332 | return 0;\r | |
333 | \r | |
334 | #ifdef MS_WINDOWS\r | |
335 | return win32_urandom((unsigned char *)buffer, size, 1);\r | |
336 | #elif HAVE_GETENTROPY\r | |
337 | return py_getentropy(buffer, size, 0);\r | |
338 | #else\r | |
339 | # ifdef __VMS\r | |
340 | return vms_urandom((unsigned char *)buffer, size, 1);\r | |
341 | # else\r | |
342 | return dev_urandom_python((char*)buffer, size);\r | |
343 | # endif\r | |
344 | #endif\r | |
345 | }\r | |
346 | \r | |
347 | void\r | |
348 | _PyRandom_Init(void)\r | |
349 | {\r | |
350 | char *env;\r | |
351 | void *secret = &_Py_HashSecret;\r | |
352 | Py_ssize_t secret_size = sizeof(_Py_HashSecret_t);\r | |
353 | \r | |
354 | if (_Py_HashSecret_Initialized)\r | |
355 | return;\r | |
356 | _Py_HashSecret_Initialized = 1;\r | |
357 | \r | |
358 | /*\r | |
359 | By default, hash randomization is disabled, and only\r | |
360 | enabled if PYTHONHASHSEED is set to non-empty or if\r | |
361 | "-R" is provided at the command line:\r | |
362 | */\r | |
363 | if (!Py_HashRandomizationFlag) {\r | |
364 | /* Disable the randomized hash: */\r | |
365 | memset(secret, 0, secret_size);\r | |
366 | return;\r | |
367 | }\r | |
368 | \r | |
369 | /*\r | |
370 | Hash randomization is enabled. Generate a per-process secret,\r | |
371 | using PYTHONHASHSEED if provided.\r | |
372 | */\r | |
373 | \r | |
374 | env = Py_GETENV("PYTHONHASHSEED");\r | |
375 | if (env && *env != '\0' && strcmp(env, "random") != 0) {\r | |
376 | char *endptr = env;\r | |
377 | unsigned long seed;\r | |
378 | seed = strtoul(env, &endptr, 10);\r | |
379 | if (*endptr != '\0'\r | |
380 | || seed > 4294967295UL\r | |
381 | || (errno == ERANGE && seed == ULONG_MAX))\r | |
382 | {\r | |
383 | Py_FatalError("PYTHONHASHSEED must be \"random\" or an integer "\r | |
384 | "in range [0; 4294967295]");\r | |
385 | }\r | |
386 | if (seed == 0) {\r | |
387 | /* disable the randomized hash */\r | |
388 | memset(secret, 0, secret_size);\r | |
389 | }\r | |
390 | else {\r | |
391 | lcg_urandom(seed, (unsigned char*)secret, secret_size);\r | |
392 | }\r | |
393 | }\r | |
394 | else {\r | |
395 | #ifdef MS_WINDOWS\r | |
396 | (void)win32_urandom((unsigned char *)secret, secret_size, 0);\r | |
397 | #elif __VMS\r | |
398 | vms_urandom((unsigned char *)secret, secret_size, 0);\r | |
399 | #elif HAVE_GETENTROPY\r | |
400 | (void)py_getentropy(secret, secret_size, 1);\r | |
401 | #else\r | |
402 | dev_urandom_noraise(secret, secret_size);\r | |
403 | #endif\r | |
404 | }\r | |
405 | }\r | |
406 | \r | |
407 | void\r | |
408 | _PyRandom_Fini(void)\r | |
409 | {\r | |
410 | #ifdef MS_WINDOWS\r | |
411 | if (hCryptProv) {\r | |
412 | CryptReleaseContext(hCryptProv, 0);\r | |
413 | hCryptProv = 0;\r | |
414 | }\r | |
415 | #elif HAVE_GETENTROPY\r | |
416 | /* nothing to clean */\r | |
417 | #else\r | |
418 | dev_urandom_close();\r | |
419 | #endif\r | |
420 | }\r |