2
0

rand_win.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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. #include "cryptlib.h"
  112. #include <openssl/rand.h>
  113. #include "rand_lcl.h"
  114. #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
  115. # include <windows.h>
  116. # ifndef _WIN32_WINNT
  117. # define _WIN32_WINNT 0x0400
  118. # endif
  119. # include <wincrypt.h>
  120. # include <tlhelp32.h>
  121. /*
  122. * Limit the time spent walking through the heap, processes, threads and
  123. * modules to a maximum of 1000 miliseconds each, unless CryptoGenRandom
  124. * failed
  125. */
  126. # define MAXDELAY 1000
  127. /*
  128. * Intel hardware RNG CSP -- available from
  129. * http://developer.intel.com/design/security/rng/redist_license.htm
  130. */
  131. # define PROV_INTEL_SEC 22
  132. # define INTEL_DEF_PROV L"Intel Hardware Cryptographic Service Provider"
  133. static void readtimer(void);
  134. static void readscreen(void);
  135. /*
  136. * It appears like CURSORINFO, PCURSORINFO and LPCURSORINFO are only defined
  137. * when WINVER is 0x0500 and up, which currently only happens on Win2000.
  138. * Unfortunately, those are typedefs, so they're a little bit difficult to
  139. * detect properly. On the other hand, the macro CURSOR_SHOWING is defined
  140. * within the same conditional, so it can be use to detect the absence of
  141. * said typedefs.
  142. */
  143. # ifndef CURSOR_SHOWING
  144. /*
  145. * Information about the global cursor.
  146. */
  147. typedef struct tagCURSORINFO {
  148. DWORD cbSize;
  149. DWORD flags;
  150. HCURSOR hCursor;
  151. POINT ptScreenPos;
  152. } CURSORINFO, *PCURSORINFO, *LPCURSORINFO;
  153. # define CURSOR_SHOWING 0x00000001
  154. # endif /* CURSOR_SHOWING */
  155. # if !defined(OPENSSL_SYS_WINCE)
  156. typedef BOOL(WINAPI *CRYPTACQUIRECONTEXTW) (HCRYPTPROV *, LPCWSTR, LPCWSTR,
  157. DWORD, DWORD);
  158. typedef BOOL(WINAPI *CRYPTGENRANDOM) (HCRYPTPROV, DWORD, BYTE *);
  159. typedef BOOL(WINAPI *CRYPTRELEASECONTEXT) (HCRYPTPROV, DWORD);
  160. typedef HWND(WINAPI *GETFOREGROUNDWINDOW) (VOID);
  161. typedef BOOL(WINAPI *GETCURSORINFO) (PCURSORINFO);
  162. typedef DWORD(WINAPI *GETQUEUESTATUS) (UINT);
  163. typedef HANDLE(WINAPI *CREATETOOLHELP32SNAPSHOT) (DWORD, DWORD);
  164. typedef BOOL(WINAPI *CLOSETOOLHELP32SNAPSHOT) (HANDLE);
  165. typedef BOOL(WINAPI *HEAP32FIRST) (LPHEAPENTRY32, DWORD, size_t);
  166. typedef BOOL(WINAPI *HEAP32NEXT) (LPHEAPENTRY32);
  167. typedef BOOL(WINAPI *HEAP32LIST) (HANDLE, LPHEAPLIST32);
  168. typedef BOOL(WINAPI *PROCESS32) (HANDLE, LPPROCESSENTRY32);
  169. typedef BOOL(WINAPI *THREAD32) (HANDLE, LPTHREADENTRY32);
  170. typedef BOOL(WINAPI *MODULE32) (HANDLE, LPMODULEENTRY32);
  171. # include <lmcons.h>
  172. # include <lmstats.h>
  173. # if 1
  174. /*
  175. * The NET API is Unicode only. It requires the use of the UNICODE macro.
  176. * When UNICODE is defined LPTSTR becomes LPWSTR. LMSTR was was added to the
  177. * Platform SDK to allow the NET API to be used in non-Unicode applications
  178. * provided that Unicode strings were still used for input. LMSTR is defined
  179. * as LPWSTR.
  180. */
  181. typedef NET_API_STATUS(NET_API_FUNCTION *NETSTATGET)
  182. (LPWSTR, LPWSTR, DWORD, DWORD, LPBYTE *);
  183. typedef NET_API_STATUS(NET_API_FUNCTION *NETFREE) (LPBYTE);
  184. # endif /* 1 */
  185. # endif /* !OPENSSL_SYS_WINCE */
  186. int RAND_poll(void)
  187. {
  188. MEMORYSTATUS m;
  189. HCRYPTPROV hProvider = 0;
  190. DWORD w;
  191. int good = 0;
  192. # if defined(OPENSSL_SYS_WINCE)
  193. # if defined(_WIN32_WCE) && _WIN32_WCE>=300
  194. /*
  195. * Even though MSDN says _WIN32_WCE>=210, it doesn't seem to be available
  196. * in commonly available implementations prior 300...
  197. */
  198. {
  199. BYTE buf[64];
  200. /* poll the CryptoAPI PRNG */
  201. /* The CryptoAPI returns sizeof(buf) bytes of randomness */
  202. if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL,
  203. CRYPT_VERIFYCONTEXT)) {
  204. if (CryptGenRandom(hProvider, sizeof(buf), buf))
  205. RAND_add(buf, sizeof(buf), sizeof(buf));
  206. CryptReleaseContext(hProvider, 0);
  207. }
  208. }
  209. # endif
  210. # else /* OPENSSL_SYS_WINCE */
  211. /*
  212. * None of below libraries are present on Windows CE, which is
  213. * why we #ifndef the whole section. This also excuses us from
  214. * handling the GetProcAddress issue. The trouble is that in
  215. * real Win32 API GetProcAddress is available in ANSI flavor
  216. * only. In WinCE on the other hand GetProcAddress is a macro
  217. * most commonly defined as GetProcAddressW, which accepts
  218. * Unicode argument. If we were to call GetProcAddress under
  219. * WinCE, I'd recommend to either redefine GetProcAddress as
  220. * GetProcAddressA (there seem to be one in common CE spec) or
  221. * implement own shim routine, which would accept ANSI argument
  222. * and expand it to Unicode.
  223. */
  224. {
  225. /* load functions dynamically - not available on all systems */
  226. HMODULE advapi = LoadLibrary(TEXT("ADVAPI32.DLL"));
  227. HMODULE kernel = LoadLibrary(TEXT("KERNEL32.DLL"));
  228. HMODULE user = NULL;
  229. HMODULE netapi = LoadLibrary(TEXT("NETAPI32.DLL"));
  230. CRYPTACQUIRECONTEXTW acquire = NULL;
  231. CRYPTGENRANDOM gen = NULL;
  232. CRYPTRELEASECONTEXT release = NULL;
  233. NETSTATGET netstatget = NULL;
  234. NETFREE netfree = NULL;
  235. BYTE buf[64];
  236. if (netapi) {
  237. netstatget =
  238. (NETSTATGET) GetProcAddress(netapi, "NetStatisticsGet");
  239. netfree = (NETFREE) GetProcAddress(netapi, "NetApiBufferFree");
  240. }
  241. if (netstatget && netfree) {
  242. LPBYTE outbuf;
  243. /*
  244. * NetStatisticsGet() is a Unicode only function
  245. * STAT_WORKSTATION_0 contains 45 fields and STAT_SERVER_0
  246. * contains 17 fields. We treat each field as a source of one
  247. * byte of entropy.
  248. */
  249. if (netstatget(NULL, L"LanmanWorkstation", 0, 0, &outbuf) == 0) {
  250. RAND_add(outbuf, sizeof(STAT_WORKSTATION_0), 45);
  251. netfree(outbuf);
  252. }
  253. if (netstatget(NULL, L"LanmanServer", 0, 0, &outbuf) == 0) {
  254. RAND_add(outbuf, sizeof(STAT_SERVER_0), 17);
  255. netfree(outbuf);
  256. }
  257. }
  258. if (netapi)
  259. FreeLibrary(netapi);
  260. /*
  261. * It appears like this can cause an exception deep within
  262. * ADVAPI32.DLL at random times on Windows 2000. Reported by Jeffrey
  263. * Altman. Only use it on NT.
  264. */
  265. if (advapi) {
  266. /*
  267. * If it's available, then it's available in both ANSI
  268. * and UNICODE flavors even in Win9x, documentation says.
  269. * We favor Unicode...
  270. */
  271. acquire = (CRYPTACQUIRECONTEXTW) GetProcAddress(advapi,
  272. "CryptAcquireContextW");
  273. gen = (CRYPTGENRANDOM) GetProcAddress(advapi, "CryptGenRandom");
  274. release = (CRYPTRELEASECONTEXT) GetProcAddress(advapi,
  275. "CryptReleaseContext");
  276. }
  277. if (acquire && gen && release) {
  278. /* poll the CryptoAPI PRNG */
  279. /* The CryptoAPI returns sizeof(buf) bytes of randomness */
  280. if (acquire(&hProvider, NULL, NULL, PROV_RSA_FULL,
  281. CRYPT_VERIFYCONTEXT)) {
  282. if (gen(hProvider, sizeof(buf), buf) != 0) {
  283. RAND_add(buf, sizeof(buf), 0);
  284. good = 1;
  285. # if 0
  286. printf("randomness from PROV_RSA_FULL\n");
  287. # endif
  288. }
  289. release(hProvider, 0);
  290. }
  291. /* poll the Pentium PRG with CryptoAPI */
  292. if (acquire(&hProvider, 0, INTEL_DEF_PROV, PROV_INTEL_SEC, 0)) {
  293. if (gen(hProvider, sizeof(buf), buf) != 0) {
  294. RAND_add(buf, sizeof(buf), sizeof(buf));
  295. good = 1;
  296. # if 0
  297. printf("randomness from PROV_INTEL_SEC\n");
  298. # endif
  299. }
  300. release(hProvider, 0);
  301. }
  302. }
  303. if (advapi)
  304. FreeLibrary(advapi);
  305. if ((!check_winnt() ||
  306. !OPENSSL_isservice()) &&
  307. (user = LoadLibrary(TEXT("USER32.DLL")))) {
  308. GETCURSORINFO cursor;
  309. GETFOREGROUNDWINDOW win;
  310. GETQUEUESTATUS queue;
  311. win =
  312. (GETFOREGROUNDWINDOW) GetProcAddress(user,
  313. "GetForegroundWindow");
  314. cursor = (GETCURSORINFO) GetProcAddress(user, "GetCursorInfo");
  315. queue = (GETQUEUESTATUS) GetProcAddress(user, "GetQueueStatus");
  316. if (win) {
  317. /* window handle */
  318. HWND h = win();
  319. RAND_add(&h, sizeof(h), 0);
  320. }
  321. if (cursor) {
  322. /*
  323. * unfortunately, its not safe to call GetCursorInfo() on NT4
  324. * even though it exists in SP3 (or SP6) and higher.
  325. */
  326. if (check_winnt() && !check_win_minplat(5))
  327. cursor = 0;
  328. }
  329. if (cursor) {
  330. /* cursor position */
  331. /* assume 2 bytes of entropy */
  332. CURSORINFO ci;
  333. ci.cbSize = sizeof(CURSORINFO);
  334. if (cursor(&ci))
  335. RAND_add(&ci, ci.cbSize, 2);
  336. }
  337. if (queue) {
  338. /* message queue status */
  339. /* assume 1 byte of entropy */
  340. w = queue(QS_ALLEVENTS);
  341. RAND_add(&w, sizeof(w), 1);
  342. }
  343. FreeLibrary(user);
  344. }
  345. /*-
  346. * Toolhelp32 snapshot: enumerate processes, threads, modules and heap
  347. * http://msdn.microsoft.com/library/psdk/winbase/toolhelp_5pfd.htm
  348. * (Win 9x and 2000 only, not available on NT)
  349. *
  350. * This seeding method was proposed in Peter Gutmann, Software
  351. * Generation of Practically Strong Random Numbers,
  352. * http://www.usenix.org/publications/library/proceedings/sec98/gutmann.html
  353. * revised version at http://www.cryptoengines.com/~peter/06_random.pdf
  354. * (The assignment of entropy estimates below is arbitrary, but based
  355. * on Peter's analysis the full poll appears to be safe. Additional
  356. * interactive seeding is encouraged.)
  357. */
  358. if (kernel) {
  359. CREATETOOLHELP32SNAPSHOT snap;
  360. CLOSETOOLHELP32SNAPSHOT close_snap;
  361. HANDLE handle;
  362. HEAP32FIRST heap_first;
  363. HEAP32NEXT heap_next;
  364. HEAP32LIST heaplist_first, heaplist_next;
  365. PROCESS32 process_first, process_next;
  366. THREAD32 thread_first, thread_next;
  367. MODULE32 module_first, module_next;
  368. HEAPLIST32 hlist;
  369. HEAPENTRY32 hentry;
  370. PROCESSENTRY32 p;
  371. THREADENTRY32 t;
  372. MODULEENTRY32 m;
  373. DWORD starttime = 0;
  374. snap = (CREATETOOLHELP32SNAPSHOT)
  375. GetProcAddress(kernel, "CreateToolhelp32Snapshot");
  376. close_snap = (CLOSETOOLHELP32SNAPSHOT)
  377. GetProcAddress(kernel, "CloseToolhelp32Snapshot");
  378. heap_first = (HEAP32FIRST) GetProcAddress(kernel, "Heap32First");
  379. heap_next = (HEAP32NEXT) GetProcAddress(kernel, "Heap32Next");
  380. heaplist_first =
  381. (HEAP32LIST) GetProcAddress(kernel, "Heap32ListFirst");
  382. heaplist_next =
  383. (HEAP32LIST) GetProcAddress(kernel, "Heap32ListNext");
  384. process_first =
  385. (PROCESS32) GetProcAddress(kernel, "Process32First");
  386. process_next =
  387. (PROCESS32) GetProcAddress(kernel, "Process32Next");
  388. thread_first = (THREAD32) GetProcAddress(kernel, "Thread32First");
  389. thread_next = (THREAD32) GetProcAddress(kernel, "Thread32Next");
  390. module_first = (MODULE32) GetProcAddress(kernel, "Module32First");
  391. module_next = (MODULE32) GetProcAddress(kernel, "Module32Next");
  392. if (snap && heap_first && heap_next && heaplist_first &&
  393. heaplist_next && process_first && process_next &&
  394. thread_first && thread_next && module_first &&
  395. module_next && (handle = snap(TH32CS_SNAPALL, 0))
  396. != INVALID_HANDLE_VALUE) {
  397. /* heap list and heap walking */
  398. /*
  399. * HEAPLIST32 contains 3 fields that will change with each
  400. * entry. Consider each field a source of 1 byte of entropy.
  401. * HEAPENTRY32 contains 5 fields that will change with each
  402. * entry. Consider each field a source of 1 byte of entropy.
  403. */
  404. ZeroMemory(&hlist, sizeof(HEAPLIST32));
  405. hlist.dwSize = sizeof(HEAPLIST32);
  406. if (good)
  407. starttime = GetTickCount();
  408. # ifdef _MSC_VER
  409. if (heaplist_first(handle, &hlist)) {
  410. /*
  411. * following discussion on dev ML, exception on WinCE (or
  412. * other Win platform) is theoretically of unknown
  413. * origin; prevent infinite loop here when this
  414. * theoretical case occurs; otherwise cope with the
  415. * expected (MSDN documented) exception-throwing
  416. * behaviour of Heap32Next() on WinCE.
  417. *
  418. * based on patch in original message by Tanguy Fautré
  419. * (2009/03/02) Subject: RAND_poll() and
  420. * CreateToolhelp32Snapshot() stability
  421. */
  422. int ex_cnt_limit = 42;
  423. do {
  424. RAND_add(&hlist, hlist.dwSize, 3);
  425. __try {
  426. ZeroMemory(&hentry, sizeof(HEAPENTRY32));
  427. hentry.dwSize = sizeof(HEAPENTRY32);
  428. if (heap_first(&hentry,
  429. hlist.th32ProcessID,
  430. hlist.th32HeapID)) {
  431. int entrycnt = 80;
  432. do
  433. RAND_add(&hentry, hentry.dwSize, 5);
  434. while (heap_next(&hentry)
  435. && (!good
  436. || (GetTickCount() - starttime) <
  437. MAXDELAY)
  438. && --entrycnt > 0);
  439. }
  440. }
  441. __except(EXCEPTION_EXECUTE_HANDLER) {
  442. /*
  443. * ignore access violations when walking the heap
  444. * list
  445. */
  446. ex_cnt_limit--;
  447. }
  448. } while (heaplist_next(handle, &hlist)
  449. && (!good
  450. || (GetTickCount() - starttime) < MAXDELAY)
  451. && ex_cnt_limit > 0);
  452. }
  453. # else
  454. if (heaplist_first(handle, &hlist)) {
  455. do {
  456. RAND_add(&hlist, hlist.dwSize, 3);
  457. hentry.dwSize = sizeof(HEAPENTRY32);
  458. if (heap_first(&hentry,
  459. hlist.th32ProcessID,
  460. hlist.th32HeapID)) {
  461. int entrycnt = 80;
  462. do
  463. RAND_add(&hentry, hentry.dwSize, 5);
  464. while (heap_next(&hentry)
  465. && --entrycnt > 0);
  466. }
  467. } while (heaplist_next(handle, &hlist)
  468. && (!good
  469. || (GetTickCount() - starttime) < MAXDELAY));
  470. }
  471. # endif
  472. /* process walking */
  473. /*
  474. * PROCESSENTRY32 contains 9 fields that will change with
  475. * each entry. Consider each field a source of 1 byte of
  476. * entropy.
  477. */
  478. p.dwSize = sizeof(PROCESSENTRY32);
  479. if (good)
  480. starttime = GetTickCount();
  481. if (process_first(handle, &p))
  482. do
  483. RAND_add(&p, p.dwSize, 9);
  484. while (process_next(handle, &p)
  485. && (!good
  486. || (GetTickCount() - starttime) < MAXDELAY));
  487. /* thread walking */
  488. /*
  489. * THREADENTRY32 contains 6 fields that will change with each
  490. * entry. Consider each field a source of 1 byte of entropy.
  491. */
  492. t.dwSize = sizeof(THREADENTRY32);
  493. if (good)
  494. starttime = GetTickCount();
  495. if (thread_first(handle, &t))
  496. do
  497. RAND_add(&t, t.dwSize, 6);
  498. while (thread_next(handle, &t)
  499. && (!good
  500. || (GetTickCount() - starttime) < MAXDELAY));
  501. /* module walking */
  502. /*
  503. * MODULEENTRY32 contains 9 fields that will change with each
  504. * entry. Consider each field a source of 1 byte of entropy.
  505. */
  506. m.dwSize = sizeof(MODULEENTRY32);
  507. if (good)
  508. starttime = GetTickCount();
  509. if (module_first(handle, &m))
  510. do
  511. RAND_add(&m, m.dwSize, 9);
  512. while (module_next(handle, &m)
  513. && (!good
  514. || (GetTickCount() - starttime) < MAXDELAY));
  515. if (close_snap)
  516. close_snap(handle);
  517. else
  518. CloseHandle(handle);
  519. }
  520. FreeLibrary(kernel);
  521. }
  522. }
  523. # endif /* !OPENSSL_SYS_WINCE */
  524. /* timer data */
  525. readtimer();
  526. /* memory usage statistics */
  527. GlobalMemoryStatus(&m);
  528. RAND_add(&m, sizeof(m), 1);
  529. /* process ID */
  530. w = GetCurrentProcessId();
  531. RAND_add(&w, sizeof(w), 1);
  532. # if 0
  533. printf("Exiting RAND_poll\n");
  534. # endif
  535. return (1);
  536. }
  537. int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam)
  538. {
  539. double add_entropy = 0;
  540. switch (iMsg) {
  541. case WM_KEYDOWN:
  542. {
  543. static WPARAM key;
  544. if (key != wParam)
  545. add_entropy = 0.05;
  546. key = wParam;
  547. }
  548. break;
  549. case WM_MOUSEMOVE:
  550. {
  551. static int lastx, lasty, lastdx, lastdy;
  552. int x, y, dx, dy;
  553. x = LOWORD(lParam);
  554. y = HIWORD(lParam);
  555. dx = lastx - x;
  556. dy = lasty - y;
  557. if (dx != 0 && dy != 0 && dx - lastdx != 0 && dy - lastdy != 0)
  558. add_entropy = .2;
  559. lastx = x, lasty = y;
  560. lastdx = dx, lastdy = dy;
  561. }
  562. break;
  563. }
  564. readtimer();
  565. RAND_add(&iMsg, sizeof(iMsg), add_entropy);
  566. RAND_add(&wParam, sizeof(wParam), 0);
  567. RAND_add(&lParam, sizeof(lParam), 0);
  568. return (RAND_status());
  569. }
  570. void RAND_screen(void)
  571. { /* function available for backward
  572. * compatibility */
  573. RAND_poll();
  574. readscreen();
  575. }
  576. /* feed timing information to the PRNG */
  577. static void readtimer(void)
  578. {
  579. DWORD w;
  580. LARGE_INTEGER l;
  581. static int have_perfc = 1;
  582. # if defined(_MSC_VER) && defined(_M_X86)
  583. static int have_tsc = 1;
  584. DWORD cyclecount;
  585. if (have_tsc) {
  586. __try {
  587. __asm {
  588. _emit 0x0f _emit 0x31 mov cyclecount, eax}
  589. RAND_add(&cyclecount, sizeof(cyclecount), 1);
  590. }
  591. __except(EXCEPTION_EXECUTE_HANDLER) {
  592. have_tsc = 0;
  593. }
  594. }
  595. # else
  596. # define have_tsc 0
  597. # endif
  598. if (have_perfc) {
  599. if (QueryPerformanceCounter(&l) == 0)
  600. have_perfc = 0;
  601. else
  602. RAND_add(&l, sizeof(l), 0);
  603. }
  604. if (!have_tsc && !have_perfc) {
  605. w = GetTickCount();
  606. RAND_add(&w, sizeof(w), 0);
  607. }
  608. }
  609. /* feed screen contents to PRNG */
  610. /*****************************************************************************
  611. *
  612. * Created 960901 by Gertjan van Oosten, gertjan@West.NL, West Consulting B.V.
  613. *
  614. * Code adapted from
  615. * <URL:http://support.microsoft.com/default.aspx?scid=kb;[LN];97193>;
  616. * the original copyright message is:
  617. *
  618. * (C) Copyright Microsoft Corp. 1993. All rights reserved.
  619. *
  620. * You have a royalty-free right to use, modify, reproduce and
  621. * distribute the Sample Files (and/or any modified version) in
  622. * any way you find useful, provided that you agree that
  623. * Microsoft has no warranty obligations or liability for any
  624. * Sample Application Files which are modified.
  625. */
  626. static void readscreen(void)
  627. {
  628. # if !defined(OPENSSL_SYS_WINCE) && !defined(OPENSSL_SYS_WIN32_CYGWIN)
  629. HDC hScrDC; /* screen DC */
  630. HDC hMemDC; /* memory DC */
  631. HBITMAP hBitmap; /* handle for our bitmap */
  632. HBITMAP hOldBitmap; /* handle for previous bitmap */
  633. BITMAP bm; /* bitmap properties */
  634. unsigned int size; /* size of bitmap */
  635. char *bmbits; /* contents of bitmap */
  636. int w; /* screen width */
  637. int h; /* screen height */
  638. int y; /* y-coordinate of screen lines to grab */
  639. int n = 16; /* number of screen lines to grab at a time */
  640. if (check_winnt() && OPENSSL_isservice() > 0)
  641. return;
  642. /* Create a screen DC and a memory DC compatible to screen DC */
  643. hScrDC = CreateDC(TEXT("DISPLAY"), NULL, NULL, NULL);
  644. hMemDC = CreateCompatibleDC(hScrDC);
  645. /* Get screen resolution */
  646. w = GetDeviceCaps(hScrDC, HORZRES);
  647. h = GetDeviceCaps(hScrDC, VERTRES);
  648. /* Create a bitmap compatible with the screen DC */
  649. hBitmap = CreateCompatibleBitmap(hScrDC, w, n);
  650. /* Select new bitmap into memory DC */
  651. hOldBitmap = SelectObject(hMemDC, hBitmap);
  652. /* Get bitmap properties */
  653. GetObject(hBitmap, sizeof(BITMAP), (LPSTR) & bm);
  654. size = (unsigned int)bm.bmWidthBytes * bm.bmHeight * bm.bmPlanes;
  655. bmbits = OPENSSL_malloc(size);
  656. if (bmbits) {
  657. /* Now go through the whole screen, repeatedly grabbing n lines */
  658. for (y = 0; y < h - n; y += n) {
  659. unsigned char md[MD_DIGEST_LENGTH];
  660. /* Bitblt screen DC to memory DC */
  661. BitBlt(hMemDC, 0, 0, w, n, hScrDC, 0, y, SRCCOPY);
  662. /* Copy bitmap bits from memory DC to bmbits */
  663. GetBitmapBits(hBitmap, size, bmbits);
  664. /* Get the hash of the bitmap */
  665. MD(bmbits, size, md);
  666. /* Seed the random generator with the hash value */
  667. RAND_add(md, MD_DIGEST_LENGTH, 0);
  668. }
  669. OPENSSL_free(bmbits);
  670. }
  671. /* Select old bitmap back into memory DC */
  672. hBitmap = SelectObject(hMemDC, hOldBitmap);
  673. /* Clean up */
  674. DeleteObject(hBitmap);
  675. DeleteDC(hMemDC);
  676. DeleteDC(hScrDC);
  677. # endif /* !OPENSSL_SYS_WINCE */
  678. }
  679. #endif