fa78c06d9ea74b94e5dae315dd8fd4b4e2a56a7d
[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 int RAND_poll(void)
63 {
64     MEMORYSTATUS mst;
65     HCRYPTPROV hProvider = 0;
66     DWORD w;
67     BYTE buf[64];
68
69     /* poll the CryptoAPI PRNG */
70     /* The CryptoAPI returns sizeof(buf) bytes of randomness */
71     if (CryptAcquireContextW(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
72         if (CryptGenRandom(hProvider, sizeof(buf), buf) != 0) {
73             RAND_add(buf, sizeof(buf), sizeof(buf));
74         }
75         CryptReleaseContext(hProvider, 0);
76     }
77
78     /* poll the Pentium PRG with CryptoAPI */
79     if (CryptAcquireContextW(&hProvider, NULL, INTEL_DEF_PROV, PROV_INTEL_SEC, CRYPT_VERIFYCONTEXT)) {
80         if (CryptGenRandom(hProvider, sizeof(buf), buf) != 0) {
81             RAND_add(buf, sizeof(buf), sizeof(buf));
82         }
83         CryptReleaseContext(hProvider, 0);
84     }
85
86     /* timer data */
87     readtimer();
88
89     /* memory usage statistics */
90     GlobalMemoryStatus(&mst);
91     RAND_add(&mst, sizeof(mst), 1);
92
93     /* process ID */
94     w = GetCurrentProcessId();
95     RAND_add(&w, sizeof(w), 1);
96
97     return (1);
98 }
99
100 int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam)
101 {
102     double add_entropy = 0;
103
104     switch (iMsg) {
105     case WM_KEYDOWN:
106         {
107             static WPARAM key;
108             if (key != wParam)
109                 add_entropy = 0.05;
110             key = wParam;
111         }
112         break;
113     case WM_MOUSEMOVE:
114         {
115             static int lastx, lasty, lastdx, lastdy;
116             int x, y, dx, dy;
117
118             x = LOWORD(lParam);
119             y = HIWORD(lParam);
120             dx = lastx - x;
121             dy = lasty - y;
122             if (dx != 0 && dy != 0 && dx - lastdx != 0 && dy - lastdy != 0)
123                 add_entropy = .2;
124             lastx = x, lasty = y;
125             lastdx = dx, lastdy = dy;
126         }
127         break;
128     }
129
130     readtimer();
131     RAND_add(&iMsg, sizeof(iMsg), add_entropy);
132     RAND_add(&wParam, sizeof(wParam), 0);
133     RAND_add(&lParam, sizeof(lParam), 0);
134
135     return (RAND_status());
136 }
137
138 void RAND_screen(void)
139 {                               /* function available for backward
140                                  * compatibility */
141     RAND_poll();
142     readscreen();
143 }
144
145 /* feed timing information to the PRNG */
146 static void readtimer(void)
147 {
148     DWORD w;
149     LARGE_INTEGER l;
150     static int have_perfc = 1;
151 # if defined(_MSC_VER) && defined(_M_X86)
152     static int have_tsc = 1;
153     DWORD cyclecount;
154
155     if (have_tsc) {
156         __try {
157             __asm {
158             _emit 0x0f _emit 0x31 mov cyclecount, eax}
159             RAND_add(&cyclecount, sizeof(cyclecount), 1);
160         }
161         __except(EXCEPTION_EXECUTE_HANDLER) {
162             have_tsc = 0;
163         }
164     }
165 # else
166 #  define have_tsc 0
167 # endif
168
169     if (have_perfc) {
170         if (QueryPerformanceCounter(&l) == 0)
171             have_perfc = 0;
172         else
173             RAND_add(&l, sizeof(l), 0);
174     }
175
176     if (!have_tsc && !have_perfc) {
177         w = GetTickCount();
178         RAND_add(&w, sizeof(w), 0);
179     }
180 }
181
182 /* feed screen contents to PRNG */
183 /*****************************************************************************
184  *
185  * Created 960901 by Gertjan van Oosten, gertjan@West.NL, West Consulting B.V.
186  *
187  * Code adapted from
188  * <URL:http://support.microsoft.com/default.aspx?scid=kb;[LN];97193>;
189  * the original copyright message is:
190  *
191  *   (C) Copyright Microsoft Corp. 1993.  All rights reserved.
192  *
193  *   You have a royalty-free right to use, modify, reproduce and
194  *   distribute the Sample Files (and/or any modified version) in
195  *   any way you find useful, provided that you agree that
196  *   Microsoft has no warranty obligations or liability for any
197  *   Sample Application Files which are modified.
198  */
199
200 static void readscreen(void)
201 {
202 # if !defined(OPENSSL_SYS_WIN32_CYGWIN)
203     HDC hScrDC;                 /* screen DC */
204     HBITMAP hBitmap;            /* handle for our bitmap */
205     BITMAP bm;                  /* bitmap properties */
206     unsigned int size;          /* size of bitmap */
207     char *bmbits;               /* contents of bitmap */
208     int w;                      /* screen width */
209     int h;                      /* screen height */
210     int y;                      /* y-coordinate of screen lines to grab */
211     int n = 16;                 /* number of screen lines to grab at a time */
212     BITMAPINFOHEADER bi;        /* info about the bitmap */
213
214     if (check_winnt() && OPENSSL_isservice() > 0)
215         return;
216
217     /* Get a reference to the screen DC */
218     hScrDC = GetDC(NULL);
219
220     /* Get screen resolution */
221     w = GetDeviceCaps(hScrDC, HORZRES);
222     h = GetDeviceCaps(hScrDC, VERTRES);
223
224     /* Create a bitmap compatible with the screen DC */
225     hBitmap = CreateCompatibleBitmap(hScrDC, w, n);
226
227     /* Get bitmap properties */
228     GetObject(hBitmap, sizeof(BITMAP), (LPSTR) & bm);
229     size = (unsigned int)bm.bmWidthBytes * bm.bmHeight * bm.bmPlanes;
230
231     bi.biSize = sizeof(BITMAPINFOHEADER);
232     bi.biWidth = bm.bmWidth;
233     bi.biHeight = bm.bmHeight;
234     bi.biPlanes = bm.bmPlanes;
235     bi.biBitCount = bm.bmBitsPixel;
236     bi.biCompression = BI_RGB;
237     bi.biSizeImage = 0;
238     bi.biXPelsPerMeter = 0;
239     bi.biYPelsPerMeter = 0;
240     bi.biClrUsed = 0;
241     bi.biClrImportant = 0;
242
243     bmbits = OPENSSL_malloc(size);
244     if (bmbits != NULL) {
245         /* Now go through the whole screen, repeatedly grabbing n lines */
246         for (y = 0; y < h - n; y += n) {
247             unsigned char md[MD_DIGEST_LENGTH];
248
249             /* Copy the bits of the current line range into the buffer */
250             GetDIBits(hScrDC, hBitmap, y, n,
251                       bmbits, (BITMAPINFO *) & bi, DIB_RGB_COLORS);
252
253             /* Get the hash of the bitmap */
254             MD(bmbits, size, md);
255
256             /* Seed the random generator with the hash value */
257             RAND_add(md, MD_DIGEST_LENGTH, 0);
258         }
259
260         OPENSSL_free(bmbits);
261     }
262
263     /* Clean up */
264     DeleteObject(hBitmap);
265     ReleaseDC(NULL, hScrDC);
266 # endif                         /* !OPENSSL_SYS_CYGWIN */
267 }
268
269 #endif