87869985d9f231e85cedf8386dbc0fb5dcc55b5b
[openssl.git] / crypto / rand / rand_win.c
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "internal/cryptlib.h"
11 #include <openssl/rand.h>
12 #include "rand_lcl.h"
13
14 #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32)
15 # include <windows.h>
16 # ifndef _WIN32_WINNT
17 #  define _WIN32_WINNT 0x0400
18 # endif
19 # include <wincrypt.h>
20 # include <tlhelp32.h>
21
22 /*
23  * Limit the time spent walking through the heap, processes, threads and
24  * modules to a maximum of 1000 milliseconds each, unless CryptoGenRandom
25  * failed
26  */
27 # define MAXDELAY 1000
28
29 /*
30  * Intel hardware RNG CSP -- available from
31  * http://developer.intel.com/design/security/rng/redist_license.htm
32  */
33 # define PROV_INTEL_SEC 22
34 # define INTEL_DEF_PROV L"Intel Hardware Cryptographic Service Provider"
35
36 static void readtimer(void);
37 static void readscreen(void);
38
39 /*
40  * It appears like CURSORINFO, PCURSORINFO and LPCURSORINFO are only defined
41  * when WINVER is 0x0500 and up, which currently only happens on Win2000.
42  * Unfortunately, those are typedefs, so they're a little bit difficult to
43  * detect properly.  On the other hand, the macro CURSOR_SHOWING is defined
44  * within the same conditional, so it can be use to detect the absence of
45  * said typedefs.
46  */
47
48 # ifndef CURSOR_SHOWING
49 /*
50  * Information about the global cursor.
51  */
52 typedef struct tagCURSORINFO {
53     DWORD cbSize;
54     DWORD flags;
55     HCURSOR hCursor;
56     POINT ptScreenPos;
57 } CURSORINFO, *PCURSORINFO, *LPCURSORINFO;
58
59 #  define CURSOR_SHOWING     0x00000001
60 # endif                         /* CURSOR_SHOWING */
61
62 # if !defined(OPENSSL_SYS_WINCE)
63 typedef BOOL(WINAPI *CRYPTACQUIRECONTEXTW) (HCRYPTPROV *, LPCWSTR, LPCWSTR,
64                                             DWORD, DWORD);
65 typedef BOOL(WINAPI *CRYPTGENRANDOM) (HCRYPTPROV, DWORD, BYTE *);
66 typedef BOOL(WINAPI *CRYPTRELEASECONTEXT) (HCRYPTPROV, DWORD);
67
68 typedef HWND(WINAPI *GETFOREGROUNDWINDOW) (VOID);
69 typedef BOOL(WINAPI *GETCURSORINFO) (PCURSORINFO);
70 typedef DWORD(WINAPI *GETQUEUESTATUS) (UINT);
71
72 typedef HANDLE(WINAPI *CREATETOOLHELP32SNAPSHOT) (DWORD, DWORD);
73 typedef BOOL(WINAPI *CLOSETOOLHELP32SNAPSHOT) (HANDLE);
74 typedef BOOL(WINAPI *HEAP32FIRST) (LPHEAPENTRY32, DWORD, size_t);
75 typedef BOOL(WINAPI *HEAP32NEXT) (LPHEAPENTRY32);
76 typedef BOOL(WINAPI *HEAP32LIST) (HANDLE, LPHEAPLIST32);
77 typedef BOOL(WINAPI *PROCESS32) (HANDLE, LPPROCESSENTRY32);
78 typedef BOOL(WINAPI *THREAD32) (HANDLE, LPTHREADENTRY32);
79 typedef BOOL(WINAPI *MODULE32) (HANDLE, LPMODULEENTRY32);
80
81 #  include <lmcons.h>
82 #  include <lmstats.h>
83 /*
84  * The NET API is Unicode only.  It requires the use of the UNICODE macro.
85  * When UNICODE is defined LPTSTR becomes LPWSTR.  LMSTR was was added to the
86  * Platform SDK to allow the NET API to be used in non-Unicode applications
87  * provided that Unicode strings were still used for input.  LMSTR is defined
88  * as LPWSTR.
89  */
90 typedef NET_API_STATUS(NET_API_FUNCTION *NETSTATGET)
91  (LPWSTR, LPWSTR, DWORD, DWORD, LPBYTE *);
92 typedef NET_API_STATUS(NET_API_FUNCTION *NETFREE) (LPBYTE);
93 # endif                         /* !OPENSSL_SYS_WINCE */
94
95 int RAND_poll(void)
96 {
97     MEMORYSTATUS mst;
98     HCRYPTPROV hProvider = 0;
99     DWORD w;
100     BYTE buf[64];
101
102     /* poll the CryptoAPI PRNG */
103     /* The CryptoAPI returns sizeof(buf) bytes of randomness */
104     if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
105         if (CryptGenRandom(hProvider, sizeof(buf), buf) != 0) {
106             RAND_add(buf, sizeof(buf), sizeof(buf));
107         }
108         CryptReleaseContext(hProvider, 0);
109     }
110
111     /* poll the Pentium PRG with CryptoAPI */
112     if (CryptAcquireContextW(&hProvider, NULL, INTEL_DEF_PROV, PROV_INTEL_SEC, CRYPT_VERIFYCONTEXT)) {
113         if (CryptGenRandom(hProvider, sizeof(buf), buf) != 0) {
114             RAND_add(buf, sizeof(buf), sizeof(buf));
115         }
116         CryptReleaseContext(hProvider, 0);
117     }
118
119     /* timer data */
120     readtimer();
121
122     /* memory usage statistics */
123     GlobalMemoryStatus(&mst);
124     RAND_add(&mst, sizeof(mst), 1);
125
126     /* process ID */
127     w = GetCurrentProcessId();
128     RAND_add(&w, sizeof(w), 1);
129
130     return (1);
131 }
132
133 int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam)
134 {
135     double add_entropy = 0;
136
137     switch (iMsg) {
138     case WM_KEYDOWN:
139         {
140             static WPARAM key;
141             if (key != wParam)
142                 add_entropy = 0.05;
143             key = wParam;
144         }
145         break;
146     case WM_MOUSEMOVE:
147         {
148             static int lastx, lasty, lastdx, lastdy;
149             int x, y, dx, dy;
150
151             x = LOWORD(lParam);
152             y = HIWORD(lParam);
153             dx = lastx - x;
154             dy = lasty - y;
155             if (dx != 0 && dy != 0 && dx - lastdx != 0 && dy - lastdy != 0)
156                 add_entropy = .2;
157             lastx = x, lasty = y;
158             lastdx = dx, lastdy = dy;
159         }
160         break;
161     }
162
163     readtimer();
164     RAND_add(&iMsg, sizeof(iMsg), add_entropy);
165     RAND_add(&wParam, sizeof(wParam), 0);
166     RAND_add(&lParam, sizeof(lParam), 0);
167
168     return (RAND_status());
169 }
170
171 void RAND_screen(void)
172 {                               /* function available for backward
173                                  * compatibility */
174     RAND_poll();
175     readscreen();
176 }
177
178 /* feed timing information to the PRNG */
179 static void readtimer(void)
180 {
181     DWORD w;
182     LARGE_INTEGER l;
183     static int have_perfc = 1;
184 # if defined(_MSC_VER) && defined(_M_X86)
185     static int have_tsc = 1;
186     DWORD cyclecount;
187
188     if (have_tsc) {
189         __try {
190             __asm {
191             _emit 0x0f _emit 0x31 mov cyclecount, eax}
192             RAND_add(&cyclecount, sizeof(cyclecount), 1);
193         }
194         __except(EXCEPTION_EXECUTE_HANDLER) {
195             have_tsc = 0;
196         }
197     }
198 # else
199 #  define have_tsc 0
200 # endif
201
202     if (have_perfc) {
203         if (QueryPerformanceCounter(&l) == 0)
204             have_perfc = 0;
205         else
206             RAND_add(&l, sizeof(l), 0);
207     }
208
209     if (!have_tsc && !have_perfc) {
210         w = GetTickCount();
211         RAND_add(&w, sizeof(w), 0);
212     }
213 }
214
215 /* feed screen contents to PRNG */
216 /*****************************************************************************
217  *
218  * Created 960901 by Gertjan van Oosten, gertjan@West.NL, West Consulting B.V.
219  *
220  * Code adapted from
221  * <URL:http://support.microsoft.com/default.aspx?scid=kb;[LN];97193>;
222  * the original copyright message is:
223  *
224  *   (C) Copyright Microsoft Corp. 1993.  All rights reserved.
225  *
226  *   You have a royalty-free right to use, modify, reproduce and
227  *   distribute the Sample Files (and/or any modified version) in
228  *   any way you find useful, provided that you agree that
229  *   Microsoft has no warranty obligations or liability for any
230  *   Sample Application Files which are modified.
231  */
232
233 static void readscreen(void)
234 {
235 # if !defined(OPENSSL_SYS_WINCE) && !defined(OPENSSL_SYS_WIN32_CYGWIN)
236     HDC hScrDC;                 /* screen DC */
237     HBITMAP hBitmap;            /* handle for our bitmap */
238     BITMAP bm;                  /* bitmap properties */
239     unsigned int size;          /* size of bitmap */
240     char *bmbits;               /* contents of bitmap */
241     int w;                      /* screen width */
242     int h;                      /* screen height */
243     int y;                      /* y-coordinate of screen lines to grab */
244     int n = 16;                 /* number of screen lines to grab at a time */
245     BITMAPINFOHEADER bi;        /* info about the bitmap */
246
247     if (check_winnt() && OPENSSL_isservice() > 0)
248         return;
249
250     /* Get a reference to the screen DC */
251     hScrDC = GetDC(NULL);
252
253     /* Get screen resolution */
254     w = GetDeviceCaps(hScrDC, HORZRES);
255     h = GetDeviceCaps(hScrDC, VERTRES);
256
257     /* Create a bitmap compatible with the screen DC */
258     hBitmap = CreateCompatibleBitmap(hScrDC, w, n);
259
260     /* Get bitmap properties */
261     GetObject(hBitmap, sizeof(BITMAP), (LPSTR) & bm);
262     size = (unsigned int)bm.bmWidthBytes * bm.bmHeight * bm.bmPlanes;
263
264     bi.biSize = sizeof(BITMAPINFOHEADER);
265     bi.biWidth = bm.bmWidth;
266     bi.biHeight = bm.bmHeight;
267     bi.biPlanes = bm.bmPlanes;
268     bi.biBitCount = bm.bmBitsPixel;
269     bi.biCompression = BI_RGB;
270     bi.biSizeImage = 0;
271     bi.biXPelsPerMeter = 0;
272     bi.biYPelsPerMeter = 0;
273     bi.biClrUsed = 0;
274     bi.biClrImportant = 0;
275
276     bmbits = OPENSSL_malloc(size);
277     if (bmbits != NULL) {
278         /* Now go through the whole screen, repeatedly grabbing n lines */
279         for (y = 0; y < h - n; y += n) {
280             unsigned char md[MD_DIGEST_LENGTH];
281
282             /* Copy the bits of the current line range into the buffer */
283             GetDIBits(hScrDC, hBitmap, y, n,
284                       bmbits, (BITMAPINFO *) & bi, DIB_RGB_COLORS);
285
286             /* Get the hash of the bitmap */
287             MD(bmbits, size, md);
288
289             /* Seed the random generator with the hash value */
290             RAND_add(md, MD_DIGEST_LENGTH, 0);
291         }
292
293         OPENSSL_free(bmbits);
294     }
295
296     /* Clean up */
297     DeleteObject(hBitmap);
298     ReleaseDC(NULL, hScrDC);
299 # endif                         /* !OPENSSL_SYS_WINCE */
300 }
301
302 #endif