1 /* crypto/rand/rand_win.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
4 *
5 * This package is an SSL implementation written
6 * by Eric Young (eay@cryptsoft.com).
7 * The implementation was written so as to conform with Netscapes SSL.
8 *
9 * This library is free for commercial and non-commercial use as long as
10 * the following conditions are aheared to. The following conditions
11 * apply to all code found in this distribution, be it the RC4, RSA,
12 * lhash, DES, etc., code; not just the SSL code. The SSL documentation
13 * included with this distribution is covered by the same copyright terms
14 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15 *
16 * Copyright remains Eric Young's, and as such any Copyright notices in
17 * the code are not to be removed.
18 * If this package is used in a product, Eric Young should be given attribution
19 * as the author of the parts of the library used.
20 * This can be in the form of a textual message at program startup or
21 * in documentation (online or textual) provided with the package.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. All advertising materials mentioning features or use of this software
32 * must display the following acknowledgement:
33 * "This product includes cryptographic software written by
34 * Eric Young (eay@cryptsoft.com)"
35 * The word 'cryptographic' can be left out if the rouines from the library
36 * being used are not cryptographic related :-).
37 * 4. If you include any Windows specific code (or a derivative thereof) from
38 * the apps directory (application code) you must include an acknowledgement:
39 * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40 *
41 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51 * SUCH DAMAGE.
52 *
53 * The licence and distribution terms for any publically available version or
54 * derivative of this code cannot be changed. i.e. this code cannot simply be
55 * copied and put under another distribution licence
56 * [including the GNU Public Licence.]
57 */
58 /* ====================================================================
59 * Copyright (c) 1998-2000 The OpenSSL Project. All rights reserved.
60 *
61 * Redistribution and use in source and binary forms, with or without
62 * modification, are permitted provided that the following conditions
63 * are met:
64 *
65 * 1. Redistributions of source code must retain the above copyright
66 * notice, this list of conditions and the following disclaimer.
67 *
68 * 2. Redistributions in binary form must reproduce the above copyright
69 * notice, this list of conditions and the following disclaimer in
70 * the documentation and/or other materials provided with the
71 * distribution.
72 *
73 * 3. All advertising materials mentioning features or use of this
74 * software must display the following acknowledgment:
75 * "This product includes software developed by the OpenSSL Project
76 * for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77 *
78 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79 * endorse or promote products derived from this software without
80 * prior written permission. For written permission, please contact
81 * openssl-core@openssl.org.
82 *
83 * 5. Products derived from this software may not be called "OpenSSL"
84 * nor may "OpenSSL" appear in their names without prior written
85 * permission of the OpenSSL Project.
86 *
87 * 6. Redistributions of any form whatsoever must retain the following
88 * acknowledgment:
89 * "This product includes software developed by the OpenSSL Project
90 * for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91 *
92 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR
96 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103 * OF THE POSSIBILITY OF SUCH DAMAGE.
104 * ====================================================================
105 *
106 * This product includes cryptographic software written by Eric Young
107 * (eay@cryptsoft.com). This product includes software written by Tim
108 * Hudson (tjh@cryptsoft.com).
109 *
110 */
111
112 #include "cryptlib.h"
113 #include <openssl/rand.h>
114 #include "rand_lcl.h"
115
116 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
117 # include <windows.h>
118 # ifndef _WIN32_WINNT
119 # define _WIN32_WINNT 0x0400
120 # endif
121 #ifndef WINRT_ENABLED // -- GODOT --
122 # include <wincrypt.h>
123 # include <tlhelp32.h>
124 #endif // -- GODOT --
125
126 /*
127 * Limit the time spent walking through the heap, processes, threads and
128 * modules to a maximum of 1000 miliseconds each, unless CryptoGenRandom
129 * failed
130 */
131 # define MAXDELAY 1000
132
133 /*
134 * Intel hardware RNG CSP -- available from
135 * http://developer.intel.com/design/security/rng/redist_license.htm
136 */
137 # define PROV_INTEL_SEC 22
138 # define INTEL_DEF_PROV L"Intel Hardware Cryptographic Service Provider"
139
140 static void readtimer(void);
141 static void readscreen(void);
142
143 /*
144 * It appears like CURSORINFO, PCURSORINFO and LPCURSORINFO are only defined
145 * when WINVER is 0x0500 and up, which currently only happens on Win2000.
146 * Unfortunately, those are typedefs, so they're a little bit difficult to
147 * detect properly. On the other hand, the macro CURSOR_SHOWING is defined
148 * within the same conditional, so it can be use to detect the absence of
149 * said typedefs.
150 */
151
152 # ifndef CURSOR_SHOWING
153 /*
154 * Information about the global cursor.
155 */
156 typedef struct tagCURSORINFO {
157 DWORD cbSize;
158 DWORD flags;
159 HCURSOR hCursor;
160 POINT ptScreenPos;
161 } CURSORINFO, *PCURSORINFO, *LPCURSORINFO;
162
163 # define CURSOR_SHOWING 0x00000001
164 # endif /* CURSOR_SHOWING */
165
166 # if !defined(OPENSSL_SYS_WINCE) && !defined(WINRT_ENABLED) // -- GODOT --
167 typedef BOOL(WINAPI *CRYPTACQUIRECONTEXTW) (HCRYPTPROV *, LPCWSTR, LPCWSTR,
168 DWORD, DWORD);
169 typedef BOOL(WINAPI *CRYPTGENRANDOM) (HCRYPTPROV, DWORD, BYTE *);
170 typedef BOOL(WINAPI *CRYPTRELEASECONTEXT) (HCRYPTPROV, DWORD);
171
172 typedef HWND(WINAPI *GETFOREGROUNDWINDOW) (VOID);
173 typedef BOOL(WINAPI *GETCURSORINFO) (PCURSORINFO);
174 typedef DWORD(WINAPI *GETQUEUESTATUS) (UINT);
175
176 typedef HANDLE(WINAPI *CREATETOOLHELP32SNAPSHOT) (DWORD, DWORD);
177 typedef BOOL(WINAPI *CLOSETOOLHELP32SNAPSHOT) (HANDLE);
178 typedef BOOL(WINAPI *HEAP32FIRST) (LPHEAPENTRY32, DWORD, size_t);
179 typedef BOOL(WINAPI *HEAP32NEXT) (LPHEAPENTRY32);
180 typedef BOOL(WINAPI *HEAP32LIST) (HANDLE, LPHEAPLIST32);
181 typedef BOOL(WINAPI *PROCESS32) (HANDLE, LPPROCESSENTRY32);
182 typedef BOOL(WINAPI *THREAD32) (HANDLE, LPTHREADENTRY32);
183 typedef BOOL(WINAPI *MODULE32) (HANDLE, LPMODULEENTRY32);
184
185 # include <lmcons.h>
186 # include <lmstats.h>
187 # if 1
188 /*
189 * The NET API is Unicode only. It requires the use of the UNICODE macro.
190 * When UNICODE is defined LPTSTR becomes LPWSTR. LMSTR was was added to the
191 * Platform SDK to allow the NET API to be used in non-Unicode applications
192 * provided that Unicode strings were still used for input. LMSTR is defined
193 * as LPWSTR.
194 */
195 typedef NET_API_STATUS(NET_API_FUNCTION *NETSTATGET)
196 (LPWSTR, LPWSTR, DWORD, DWORD, LPBYTE *);
197 typedef NET_API_STATUS(NET_API_FUNCTION *NETFREE) (LPBYTE);
198 # endif /* 1 */
199 # endif /* !OPENSSL_SYS_WINCE */
200
201 #define NOTTOOLONG(start) ((GetTickCount() - (start)) < MAXDELAY)
202
203 #if !defined(WINRT_ENABLED) // -- GODOT --
RAND_poll(void)204 int RAND_poll(void)
205 {
206 MEMORYSTATUS m;
207 HCRYPTPROV hProvider = 0;
208 DWORD w;
209 int good = 0;
210
211 # if defined(OPENSSL_SYS_WINCE)
212 # if defined(_WIN32_WCE) && _WIN32_WCE>=300
213 /*
214 * Even though MSDN says _WIN32_WCE>=210, it doesn't seem to be available
215 * in commonly available implementations prior 300...
216 */
217 {
218 BYTE buf[64];
219 /* poll the CryptoAPI PRNG */
220 /* The CryptoAPI returns sizeof(buf) bytes of randomness */
221 if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL,
222 CRYPT_VERIFYCONTEXT)) {
223 if (CryptGenRandom(hProvider, sizeof(buf), buf))
224 RAND_add(buf, sizeof(buf), sizeof(buf));
225 CryptReleaseContext(hProvider, 0);
226 }
227 }
228 # endif
229 # else /* OPENSSL_SYS_WINCE */
230 /*
231 * None of below libraries are present on Windows CE, which is
232 * why we #ifndef the whole section. This also excuses us from
233 * handling the GetProcAddress issue. The trouble is that in
234 * real Win32 API GetProcAddress is available in ANSI flavor
235 * only. In WinCE on the other hand GetProcAddress is a macro
236 * most commonly defined as GetProcAddressW, which accepts
237 * Unicode argument. If we were to call GetProcAddress under
238 * WinCE, I'd recommend to either redefine GetProcAddress as
239 * GetProcAddressA (there seem to be one in common CE spec) or
240 * implement own shim routine, which would accept ANSI argument
241 * and expand it to Unicode.
242 */
243 {
244 /* load functions dynamically - not available on all systems */
245 HMODULE advapi = LoadLibrary(TEXT("ADVAPI32.DLL"));
246 HMODULE kernel = LoadLibrary(TEXT("KERNEL32.DLL"));
247 HMODULE user = NULL;
248 HMODULE netapi = LoadLibrary(TEXT("NETAPI32.DLL"));
249 CRYPTACQUIRECONTEXTW acquire = NULL;
250 CRYPTGENRANDOM gen = NULL;
251 CRYPTRELEASECONTEXT release = NULL;
252 NETSTATGET netstatget = NULL;
253 NETFREE netfree = NULL;
254 BYTE buf[64];
255
256 if (netapi) {
257 netstatget =
258 (NETSTATGET) GetProcAddress(netapi, "NetStatisticsGet");
259 netfree = (NETFREE) GetProcAddress(netapi, "NetApiBufferFree");
260 }
261
262 if (netstatget && netfree) {
263 LPBYTE outbuf;
264 /*
265 * NetStatisticsGet() is a Unicode only function
266 * STAT_WORKSTATION_0 contains 45 fields and STAT_SERVER_0
267 * contains 17 fields. We treat each field as a source of one
268 * byte of entropy.
269 */
270
271 if (netstatget(NULL, L"LanmanWorkstation", 0, 0, &outbuf) == 0) {
272 RAND_add(outbuf, sizeof(STAT_WORKSTATION_0), 45);
273 netfree(outbuf);
274 }
275 if (netstatget(NULL, L"LanmanServer", 0, 0, &outbuf) == 0) {
276 RAND_add(outbuf, sizeof(STAT_SERVER_0), 17);
277 netfree(outbuf);
278 }
279 }
280
281 if (netapi)
282 FreeLibrary(netapi);
283
284 /*
285 * It appears like this can cause an exception deep within
286 * ADVAPI32.DLL at random times on Windows 2000. Reported by Jeffrey
287 * Altman. Only use it on NT.
288 */
289
290 if (advapi) {
291 /*
292 * If it's available, then it's available in both ANSI
293 * and UNICODE flavors even in Win9x, documentation says.
294 * We favor Unicode...
295 */
296 acquire = (CRYPTACQUIRECONTEXTW) GetProcAddress(advapi,
297 "CryptAcquireContextW");
298 gen = (CRYPTGENRANDOM) GetProcAddress(advapi, "CryptGenRandom");
299 release = (CRYPTRELEASECONTEXT) GetProcAddress(advapi,
300 "CryptReleaseContext");
301 }
302
303 if (acquire && gen && release) {
304 /* poll the CryptoAPI PRNG */
305 /* The CryptoAPI returns sizeof(buf) bytes of randomness */
306 if (acquire(&hProvider, NULL, NULL, PROV_RSA_FULL,
307 CRYPT_VERIFYCONTEXT)) {
308 if (gen(hProvider, sizeof(buf), buf) != 0) {
309 RAND_add(buf, sizeof(buf), 0);
310 good = 1;
311 # if 0
312 printf("randomness from PROV_RSA_FULL\n");
313 # endif
314 }
315 release(hProvider, 0);
316 }
317
318 /* poll the Pentium PRG with CryptoAPI */
319 if (acquire(&hProvider, 0, INTEL_DEF_PROV, PROV_INTEL_SEC, 0)) {
320 if (gen(hProvider, sizeof(buf), buf) != 0) {
321 RAND_add(buf, sizeof(buf), sizeof(buf));
322 good = 1;
323 # if 0
324 printf("randomness from PROV_INTEL_SEC\n");
325 # endif
326 }
327 release(hProvider, 0);
328 }
329 }
330
331 if (advapi)
332 FreeLibrary(advapi);
333
334 if ((!check_winnt() ||
335 !OPENSSL_isservice()) &&
336 (user = LoadLibrary(TEXT("USER32.DLL")))) {
337 GETCURSORINFO cursor;
338 GETFOREGROUNDWINDOW win;
339 GETQUEUESTATUS queue;
340
341 win =
342 (GETFOREGROUNDWINDOW) GetProcAddress(user,
343 "GetForegroundWindow");
344 cursor = (GETCURSORINFO) GetProcAddress(user, "GetCursorInfo");
345 queue = (GETQUEUESTATUS) GetProcAddress(user, "GetQueueStatus");
346
347 if (win) {
348 /* window handle */
349 HWND h = win();
350 RAND_add(&h, sizeof(h), 0);
351 }
352 if (cursor) {
353 /*
354 * unfortunately, its not safe to call GetCursorInfo() on NT4
355 * even though it exists in SP3 (or SP6) and higher.
356 */
357 if (check_winnt() && !check_win_minplat(5))
358 cursor = 0;
359 }
360 if (cursor) {
361 /* cursor position */
362 /* assume 2 bytes of entropy */
363 CURSORINFO ci;
364 ci.cbSize = sizeof(CURSORINFO);
365 if (cursor(&ci))
366 RAND_add(&ci, ci.cbSize, 2);
367 }
368
369 if (queue) {
370 /* message queue status */
371 /* assume 1 byte of entropy */
372 w = queue(QS_ALLEVENTS);
373 RAND_add(&w, sizeof(w), 1);
374 }
375
376 FreeLibrary(user);
377 }
378
379 /*-
380 * Toolhelp32 snapshot: enumerate processes, threads, modules and heap
381 * http://msdn.microsoft.com/library/psdk/winbase/toolhelp_5pfd.htm
382 * (Win 9x and 2000 only, not available on NT)
383 *
384 * This seeding method was proposed in Peter Gutmann, Software
385 * Generation of Practically Strong Random Numbers,
386 * http://www.usenix.org/publications/library/proceedings/sec98/gutmann.html
387 * revised version at http://www.cryptoengines.com/~peter/06_random.pdf
388 * (The assignment of entropy estimates below is arbitrary, but based
389 * on Peter's analysis the full poll appears to be safe. Additional
390 * interactive seeding is encouraged.)
391 */
392
393 if (kernel) {
394 CREATETOOLHELP32SNAPSHOT snap;
395 CLOSETOOLHELP32SNAPSHOT close_snap;
396 HANDLE handle;
397
398 HEAP32FIRST heap_first;
399 HEAP32NEXT heap_next;
400 HEAP32LIST heaplist_first, heaplist_next;
401 PROCESS32 process_first, process_next;
402 THREAD32 thread_first, thread_next;
403 MODULE32 module_first, module_next;
404
405 HEAPLIST32 hlist;
406 HEAPENTRY32 hentry;
407 PROCESSENTRY32 p;
408 THREADENTRY32 t;
409 MODULEENTRY32 m;
410 DWORD starttime = 0;
411
412 snap = (CREATETOOLHELP32SNAPSHOT)
413 GetProcAddress(kernel, "CreateToolhelp32Snapshot");
414 close_snap = (CLOSETOOLHELP32SNAPSHOT)
415 GetProcAddress(kernel, "CloseToolhelp32Snapshot");
416 heap_first = (HEAP32FIRST) GetProcAddress(kernel, "Heap32First");
417 heap_next = (HEAP32NEXT) GetProcAddress(kernel, "Heap32Next");
418 heaplist_first =
419 (HEAP32LIST) GetProcAddress(kernel, "Heap32ListFirst");
420 heaplist_next =
421 (HEAP32LIST) GetProcAddress(kernel, "Heap32ListNext");
422 process_first =
423 (PROCESS32) GetProcAddress(kernel, "Process32First");
424 process_next =
425 (PROCESS32) GetProcAddress(kernel, "Process32Next");
426 thread_first = (THREAD32) GetProcAddress(kernel, "Thread32First");
427 thread_next = (THREAD32) GetProcAddress(kernel, "Thread32Next");
428 module_first = (MODULE32) GetProcAddress(kernel, "Module32First");
429 module_next = (MODULE32) GetProcAddress(kernel, "Module32Next");
430
431 if (snap && heap_first && heap_next && heaplist_first &&
432 heaplist_next && process_first && process_next &&
433 thread_first && thread_next && module_first &&
434 module_next && (handle = snap(TH32CS_SNAPALL, 0))
435 != INVALID_HANDLE_VALUE) {
436 /* heap list and heap walking */
437 /*
438 * HEAPLIST32 contains 3 fields that will change with each
439 * entry. Consider each field a source of 1 byte of entropy.
440 * HEAPENTRY32 contains 5 fields that will change with each
441 * entry. Consider each field a source of 1 byte of entropy.
442 */
443 ZeroMemory(&hlist, sizeof(HEAPLIST32));
444 hlist.dwSize = sizeof(HEAPLIST32);
445 if (good)
446 starttime = GetTickCount();
447 # ifdef _MSC_VER
448 if (heaplist_first(handle, &hlist)) {
449 /*
450 * following discussion on dev ML, exception on WinCE (or
451 * other Win platform) is theoretically of unknown
452 * origin; prevent infinite loop here when this
453 * theoretical case occurs; otherwise cope with the
454 * expected (MSDN documented) exception-throwing
455 * behaviour of Heap32Next() on WinCE.
456 *
457 * based on patch in original message by Tanguy Fautré
458 * (2009/03/02) Subject: RAND_poll() and
459 * CreateToolhelp32Snapshot() stability
460 */
461 int ex_cnt_limit = 42;
462 do {
463 RAND_add(&hlist, hlist.dwSize, 3);
464 __try {
465 ZeroMemory(&hentry, sizeof(HEAPENTRY32));
466 hentry.dwSize = sizeof(HEAPENTRY32);
467 if (heap_first(&hentry,
468 hlist.th32ProcessID,
469 hlist.th32HeapID)) {
470 int entrycnt = 80;
471 do
472 RAND_add(&hentry, hentry.dwSize, 5);
473 while (heap_next(&hentry)
474 && (!good || NOTTOOLONG(starttime))
475 && --entrycnt > 0);
476 }
477 }
478 __except(EXCEPTION_EXECUTE_HANDLER) {
479 /*
480 * ignore access violations when walking the heap
481 * list
482 */
483 ex_cnt_limit--;
484 }
485 } while (heaplist_next(handle, &hlist)
486 && (!good || NOTTOOLONG(starttime))
487 && ex_cnt_limit > 0);
488 }
489 # else
490 if (heaplist_first(handle, &hlist)) {
491 do {
492 RAND_add(&hlist, hlist.dwSize, 3);
493 hentry.dwSize = sizeof(HEAPENTRY32);
494 if (heap_first(&hentry,
495 hlist.th32ProcessID,
496 hlist.th32HeapID)) {
497 int entrycnt = 80;
498 do
499 RAND_add(&hentry, hentry.dwSize, 5);
500 while (heap_next(&hentry)
501 && (!good || NOTTOOLONG(starttime))
502 && --entrycnt > 0);
503 }
504 } while (heaplist_next(handle, &hlist)
505 && (!good || NOTTOOLONG(starttime)));
506 }
507 # endif
508
509 /* process walking */
510 /*
511 * PROCESSENTRY32 contains 9 fields that will change with
512 * each entry. Consider each field a source of 1 byte of
513 * entropy.
514 */
515 p.dwSize = sizeof(PROCESSENTRY32);
516
517 if (good)
518 starttime = GetTickCount();
519 if (process_first(handle, &p))
520 do
521 RAND_add(&p, p.dwSize, 9);
522 while (process_next(handle, &p)
523 && (!good || NOTTOOLONG(starttime)));
524
525 /* thread walking */
526 /*
527 * THREADENTRY32 contains 6 fields that will change with each
528 * entry. Consider each field a source of 1 byte of entropy.
529 */
530 t.dwSize = sizeof(THREADENTRY32);
531 if (good)
532 starttime = GetTickCount();
533 if (thread_first(handle, &t))
534 do
535 RAND_add(&t, t.dwSize, 6);
536 while (thread_next(handle, &t)
537 && (!good || NOTTOOLONG(starttime)));
538
539 /* module walking */
540 /*
541 * MODULEENTRY32 contains 9 fields that will change with each
542 * entry. Consider each field a source of 1 byte of entropy.
543 */
544 m.dwSize = sizeof(MODULEENTRY32);
545 if (good)
546 starttime = GetTickCount();
547 if (module_first(handle, &m))
548 do
549 RAND_add(&m, m.dwSize, 9);
550 while (module_next(handle, &m)
551 && (!good || NOTTOOLONG(starttime)));
552 if (close_snap)
553 close_snap(handle);
554 else
555 CloseHandle(handle);
556
557 }
558
559 FreeLibrary(kernel);
560 }
561 }
562 # endif /* !OPENSSL_SYS_WINCE */
563
564 /* timer data */
565 readtimer();
566
567 /* memory usage statistics */
568 GlobalMemoryStatus(&m);
569 RAND_add(&m, sizeof(m), 1);
570
571 /* process ID */
572 w = GetCurrentProcessId();
573 RAND_add(&w, sizeof(w), 1);
574
575 # if 0
576 printf("Exiting RAND_poll\n");
577 # endif
578
579 return (1);
580 }
581
582 #endif // WINRT_ENABLED // -- GODOT --
583
RAND_event(UINT iMsg,WPARAM wParam,LPARAM lParam)584 int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam)
585 {
586 double add_entropy = 0;
587
588 switch (iMsg) {
589 case WM_KEYDOWN:
590 {
591 static WPARAM key;
592 if (key != wParam)
593 add_entropy = 0.05;
594 key = wParam;
595 }
596 break;
597 case WM_MOUSEMOVE:
598 {
599 static int lastx, lasty, lastdx, lastdy;
600 int x, y, dx, dy;
601
602 x = LOWORD(lParam);
603 y = HIWORD(lParam);
604 dx = lastx - x;
605 dy = lasty - y;
606 if (dx != 0 && dy != 0 && dx - lastdx != 0 && dy - lastdy != 0)
607 add_entropy = .2;
608 lastx = x, lasty = y;
609 lastdx = dx, lastdy = dy;
610 }
611 break;
612 }
613
614 readtimer();
615 RAND_add(&iMsg, sizeof(iMsg), add_entropy);
616 RAND_add(&wParam, sizeof(wParam), 0);
617 RAND_add(&lParam, sizeof(lParam), 0);
618
619 return (RAND_status());
620 }
621
RAND_screen(void)622 void RAND_screen(void)
623 { /* function available for backward
624 * compatibility */
625 RAND_poll();
626 readscreen();
627 }
628
629 /* feed timing information to the PRNG */
readtimer(void)630 static void readtimer(void)
631 {
632 DWORD w;
633 LARGE_INTEGER l;
634 static int have_perfc = 1;
635 # if defined(_MSC_VER) && defined(_M_X86)
636 static int have_tsc = 1;
637 DWORD cyclecount;
638
639 if (have_tsc) {
640 __try {
641 __asm {
642 _emit 0x0f _emit 0x31 mov cyclecount, eax}
643 RAND_add(&cyclecount, sizeof(cyclecount), 1);
644 }
645 __except(EXCEPTION_EXECUTE_HANDLER) {
646 have_tsc = 0;
647 }
648 }
649 # else
650 # define have_tsc 0
651 # endif
652
653 if (have_perfc) {
654 if (QueryPerformanceCounter(&l) == 0)
655 have_perfc = 0;
656 else
657 RAND_add(&l, sizeof(l), 0);
658 }
659
660 if (!have_tsc && !have_perfc) {
661 w = GetTickCount();
662 RAND_add(&w, sizeof(w), 0);
663 }
664 }
665
666 /* feed screen contents to PRNG */
667 /*****************************************************************************
668 *
669 * Created 960901 by Gertjan van Oosten, gertjan@West.NL, West Consulting B.V.
670 *
671 * Code adapted from
672 * <URL:http://support.microsoft.com/default.aspx?scid=kb;[LN];97193>;
673 * the original copyright message is:
674 *
675 * (C) Copyright Microsoft Corp. 1993. All rights reserved.
676 *
677 * You have a royalty-free right to use, modify, reproduce and
678 * distribute the Sample Files (and/or any modified version) in
679 * any way you find useful, provided that you agree that
680 * Microsoft has no warranty obligations or liability for any
681 * Sample Application Files which are modified.
682 */
683
readscreen(void)684 static void readscreen(void)
685 {
686 # if !defined(OPENSSL_SYS_WINCE) && !defined(OPENSSL_SYS_WIN32_CYGWIN) && !defined(WINRT_ENABLED) // -- GODOT --
687 HDC hScrDC; /* screen DC */
688 HBITMAP hBitmap; /* handle for our bitmap */
689 BITMAP bm; /* bitmap properties */
690 unsigned int size; /* size of bitmap */
691 char *bmbits; /* contents of bitmap */
692 int w; /* screen width */
693 int h; /* screen height */
694 int y; /* y-coordinate of screen lines to grab */
695 int n = 16; /* number of screen lines to grab at a time */
696 BITMAPINFOHEADER bi; /* info about the bitmap */
697
698 if (check_winnt() && OPENSSL_isservice() > 0)
699 return;
700
701 /* Get a reference to the screen DC */
702 hScrDC = GetDC(NULL);
703
704 /* Get screen resolution */
705 w = GetDeviceCaps(hScrDC, HORZRES);
706 h = GetDeviceCaps(hScrDC, VERTRES);
707
708 /* Create a bitmap compatible with the screen DC */
709 hBitmap = CreateCompatibleBitmap(hScrDC, w, n);
710
711 /* Get bitmap properties */
712 GetObject(hBitmap, sizeof(bm), (LPSTR)&bm);
713 size = (unsigned int)4 * bm.bmHeight * bm.bmWidth;
714 bi.biSize = sizeof(bi);
715 bi.biWidth = bm.bmWidth;
716 bi.biHeight = bm.bmHeight;
717 bi.biPlanes = 1;
718 bi.biBitCount = 32;
719 bi.biCompression = BI_RGB;
720 bi.biSizeImage = 0;
721 bi.biXPelsPerMeter = 0;
722 bi.biYPelsPerMeter = 0;
723 bi.biClrUsed = 0;
724 bi.biClrImportant = 0;
725
726 bmbits = OPENSSL_malloc(size);
727 if (bmbits) {
728 /* Now go through the whole screen, repeatedly grabbing n lines */
729 for (y = 0; y < h - n; y += n) {
730 unsigned char md[MD_DIGEST_LENGTH];
731
732 /* Copy the bits of the current line range into the buffer */
733 GetDIBits(hScrDC, hBitmap, y, n,
734 bmbits, (LPBITMAPINFO)&bi, DIB_RGB_COLORS);
735
736 /* Get the hash of the bitmap */
737 MD(bmbits, size, md);
738
739 /* Seed the random generator with the hash value */
740 RAND_add(md, MD_DIGEST_LENGTH, 0);
741 }
742
743 OPENSSL_free(bmbits);
744 }
745
746 /* Clean up */
747 DeleteObject(hBitmap);
748 ReleaseDC(NULL, hScrDC);
749 # endif /* !OPENSSL_SYS_WINCE */
750 }
751
752 #endif
753