Jeffrey Altman convinced me this patch was really needed, or there is
[openssl.git] / crypto / rand / rand_win.c
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(WINDOWS) || defined(WIN32)
117 #include <windows.h>
118 #ifndef _WIN32_WINNT
119 # define _WIN32_WINNT 0x0400
120 #endif
121 #include <wincrypt.h>
122 #include <tlhelp32.h>
123
124 /* Intel hardware RNG CSP -- available from
125  * http://developer.intel.com/design/security/rng/redist_license.htm
126  */
127 #define PROV_INTEL_SEC 22
128 #define INTEL_DEF_PROV "Intel Hardware Cryptographic Service Provider"
129
130 static void readtimer(void);
131 static void readscreen(void);
132
133 /* It appears like CURSORINFO, PCURSORINFO and LPCURSORINFO are only defined
134    when WINVER is 0x0500 and up, which currently only happens on Win2000.
135    Unfortunately, those are typedefs, so they're a little bit difficult to
136    detect properly.  On the other hand, the macro CURSOR_SHOWING is defined
137    within the same conditional, so it can be use to detect the absence of said
138    typedefs. */
139
140 #ifndef CURSOR_SHOWING
141 /*
142  * Information about the global cursor.
143  */
144 typedef struct tagCURSORINFO
145 {
146     DWORD   cbSize;
147     DWORD   flags;
148     HCURSOR hCursor;
149     POINT   ptScreenPos;
150 } CURSORINFO, *PCURSORINFO, *LPCURSORINFO;
151
152 #define CURSOR_SHOWING     0x00000001
153 #endif /* CURSOR_SHOWING */
154
155 typedef BOOL (WINAPI *CRYPTACQUIRECONTEXT)(HCRYPTPROV *, LPCTSTR, LPCTSTR,
156                                     DWORD, DWORD);
157 typedef BOOL (WINAPI *CRYPTGENRANDOM)(HCRYPTPROV, DWORD, BYTE *);
158 typedef BOOL (WINAPI *CRYPTRELEASECONTEXT)(HCRYPTPROV, DWORD);
159
160 typedef HWND (WINAPI *GETFOREGROUNDWINDOW)(VOID);
161 typedef BOOL (WINAPI *GETCURSORINFO)(PCURSORINFO);
162 typedef DWORD (WINAPI *GETQUEUESTATUS)(UINT);
163
164 typedef HANDLE (WINAPI *CREATETOOLHELP32SNAPSHOT)(DWORD, DWORD);
165 typedef BOOL (WINAPI *HEAP32FIRST)(LPHEAPENTRY32, DWORD, DWORD);
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
172 int RAND_poll(void)
173 {
174         MEMORYSTATUS m;
175         HCRYPTPROV hProvider = 0;
176         BYTE buf[64];
177         DWORD w;
178         HWND h;
179
180         HMODULE advapi, kernel, user;
181         CRYPTACQUIRECONTEXT acquire;
182         CRYPTGENRANDOM gen;
183         CRYPTRELEASECONTEXT release;
184
185         /* load functions dynamically - not available on all systems */
186         advapi = GetModuleHandle("ADVAPI32.DLL");
187         kernel = GetModuleHandle("KERNEL32.DLL");
188         user = GetModuleHandle("USER32.DLL");
189
190         if (advapi)
191                 {
192                 acquire = (CRYPTACQUIRECONTEXT) GetProcAddress(advapi,
193                         "CryptAcquireContextA");
194                 gen = (CRYPTGENRANDOM) GetProcAddress(advapi,
195                         "CryptGenRandom");
196                 release = (CRYPTRELEASECONTEXT) GetProcAddress(advapi,
197                         "CryptReleaseContext");
198                 }
199
200         if (acquire && gen && release)
201                 {
202                 /* poll the CryptoAPI PRNG */
203                 if (acquire(&hProvider, 0, 0, PROV_RSA_FULL,
204                         CRYPT_VERIFYCONTEXT))
205                         {
206                         if (gen(hProvider, sizeof(buf), buf) != 0)
207                                 {
208                                 RAND_add(buf, sizeof(buf), 0);
209 #ifdef DEBUG
210                                 printf("randomness from PROV_RSA_FULL\n");
211 #endif
212                                 }
213                         release(hProvider, 0); 
214                         }
215                 
216                 /* poll the Pentium PRG with CryptoAPI */
217                 if (acquire(&hProvider, 0, INTEL_DEF_PROV, PROV_INTEL_SEC, 0))
218                         {
219                         if (gen(hProvider, sizeof(buf), buf) != 0)
220                                 {
221                                 RAND_add(buf, sizeof(buf), 0);
222 #ifdef DEBUG
223                                 printf("randomness from PROV_INTEL_SEC\n");
224 #endif
225                                 }
226                         release(hProvider, 0);
227                         }
228                 }
229
230         /* timer data */
231         readtimer();
232         
233         /* memory usage statistics */
234         GlobalMemoryStatus(&m);
235         RAND_add(&m, sizeof(m), 1);
236
237         /* process ID */
238         w = GetCurrentProcessId();
239         RAND_add(&w, sizeof(w), 0);
240
241         if (user)
242                 {
243                 GETCURSORINFO cursor;
244                 GETFOREGROUNDWINDOW win;
245                 GETQUEUESTATUS queue;
246
247                 win = (GETFOREGROUNDWINDOW) GetProcAddress(user, "GetForegroundWindow");
248                 cursor = (GETCURSORINFO) GetProcAddress(user, "GetCursorInfo");
249                 queue = (GETQUEUESTATUS) GetProcAddress(user, "GetQueueStatus");
250
251                 if (win)
252                 {
253                         /* window handle */
254                         h = win();
255                         RAND_add(&h, sizeof(h), 0);
256                 }
257
258                 if (cursor)
259                         {
260                         /* cursor position */
261                         PCURSORINFO p = (PCURSORINFO) buf;
262                         p->cbSize = sizeof(CURSORINFO);
263                         if (cursor(p))
264                              RAND_add(p+sizeof(p->cbSize), p->cbSize-sizeof(p->cbSize), 0);
265                         }
266
267                 if (queue)
268                         {
269                         /* message queue status */
270                         w = queue(QS_ALLEVENTS);
271                         RAND_add(&w, sizeof(w), 0);
272                         }
273                 }
274
275         /* Toolhelp32 snapshot: enumerate processes, threads, modules and heap
276          * http://msdn.microsoft.com/library/psdk/winbase/toolhelp_5pfd.htm
277          * (Win 9x only, not available on NT)
278          *
279          * This seeding method was proposed in Peter Gutmann, Software
280          * Generation of Practically Strong Random Numbers,
281          * http://www.usenix.org/publications/library/proceedings/sec98/gutmann.html
282      * revised version at http://www.cryptoengines.com/~peter/06_random.pdf
283          * (The assignment of entropy estimates below is arbitrary, but based
284          * on Peter's analysis the full poll appears to be safe. Additional
285          * interactive seeding is encouraged.)
286          */
287
288         if (kernel)
289                 {
290                 CREATETOOLHELP32SNAPSHOT snap;
291                 HANDLE handle;
292
293                 HEAP32FIRST heap_first;
294                 HEAP32NEXT heap_next;
295                 HEAP32LIST heaplist_first, heaplist_next;
296                 PROCESS32 process_first, process_next;
297                 THREAD32 thread_first, thread_next;
298                 MODULE32 module_first, module_next;
299
300                 HEAPLIST32 hlist;
301                 HEAPENTRY32 hentry;
302                 PROCESSENTRY32 p;
303                 THREADENTRY32 t;
304                 MODULEENTRY32 m;
305
306                 snap = (CREATETOOLHELP32SNAPSHOT)
307                   GetProcAddress(kernel, "CreateToolhelp32Snapshot");
308                 heap_first = (HEAP32FIRST) GetProcAddress(kernel, "Heap32First");
309                 heap_next = (HEAP32NEXT) GetProcAddress(kernel, "Heap32Next");
310                 heaplist_first = (HEAP32LIST) GetProcAddress(kernel, "Heap32ListFirst");
311                 heaplist_next = (HEAP32LIST) GetProcAddress(kernel, "Heap32ListNext");
312                 process_first = (PROCESS32) GetProcAddress(kernel, "Process32First");
313                 process_next = (PROCESS32) GetProcAddress(kernel, "Process32Next");
314                 thread_first = (THREAD32) GetProcAddress(kernel, "Thread32First");
315                 thread_next = (THREAD32) GetProcAddress(kernel, "Thread32Next");
316                 module_first = (MODULE32) GetProcAddress(kernel, "Module32First");
317                 module_next = (MODULE32) GetProcAddress(kernel, "Module32Next");
318
319                 if (snap && heap_first && heap_next && heaplist_first &&
320                         heaplist_next && process_first && process_next &&
321                         thread_first && thread_next && module_first &&
322                         module_next && (handle = snap(TH32CS_SNAPALL,0))
323                         != NULL)
324                         {
325                         /* heap list and heap walking */
326                         hlist.dwSize = sizeof(HEAPLIST32);              
327                         if (heaplist_first(handle, &hlist))
328                                 do
329                                         {
330                                         RAND_add(&hlist, hlist.dwSize, 0);
331                                         hentry.dwSize = sizeof(HEAPENTRY32);
332                                         if (heap_first(&hentry,
333                                                 hlist.th32ProcessID,
334                                                 hlist.th32HeapID))
335                                                 {
336                                                 int entrycnt = 50;
337                                                 do
338                                                         RAND_add(&hentry,
339                                                                 hentry.dwSize, 0);
340                                                 while (heap_next(&hentry)
341                                                         && --entrycnt > 0);
342                                                 }
343                                         } while (heaplist_next(handle,
344                                                 &hlist));
345
346                         /* process walking */
347                         p.dwSize = sizeof(PROCESSENTRY32);
348                         if (process_first(handle, &p))
349                                 do
350                                         RAND_add(&p, p.dwSize, 0);
351                                 while (process_next(handle, &p));
352                         
353                         /* thread walking */
354                         t.dwSize = sizeof(THREADENTRY32);
355                         if (thread_first(handle, &t))
356                                 do
357                                         RAND_add(&t, t.dwSize, 0);
358                                 while (thread_next(handle, &t));
359                         
360                         /* module walking */
361                         m.dwSize = sizeof(MODULEENTRY32);
362                         if (module_first(handle, &m))
363                                 do
364                                         RAND_add(&m, m.dwSize, 1);
365                                 while (module_next(handle, &m));
366                         
367                         CloseHandle(handle);
368                         }
369                 }
370
371 #ifdef DEBUG
372         printf("Exiting RAND_poll\n");
373 #endif
374
375         return(1);
376 }
377
378 int RAND_event(UINT iMsg, WPARAM wParam, LPARAM lParam)
379         {
380         double add_entropy=0;
381
382         switch (iMsg)
383                 {
384         case WM_KEYDOWN:
385                         {
386                         static WPARAM key;
387                         if (key != wParam)
388                                 add_entropy = 0.05;
389                         key = wParam;
390                         }
391                         break;
392         case WM_MOUSEMOVE:
393                         {
394                         static int lastx,lasty,lastdx,lastdy;
395                         int x,y,dx,dy;
396
397                         x=LOWORD(lParam);
398                         y=HIWORD(lParam);
399                         dx=lastx-x;
400                         dy=lasty-y;
401                         if (dx != 0 && dy != 0 && dx-lastdx != 0 && dy-lastdy != 0)
402                                 add_entropy=.2;
403                         lastx=x, lasty=y;
404                         lastdx=dx, lastdy=dy;
405                         }
406                 break;
407                 }
408
409         readtimer();
410         RAND_add(&iMsg, sizeof(iMsg), add_entropy);
411         RAND_add(&wParam, sizeof(wParam), 0);
412         RAND_add(&lParam, sizeof(lParam), 0);
413  
414         return (RAND_status());
415         }
416
417
418 void RAND_screen(void) /* function available for backward compatibility */
419 {
420         RAND_poll();
421         readscreen();
422 }
423
424
425 /* feed timing information to the PRNG */
426 static void readtimer(void)
427 {
428         DWORD w, cyclecount;
429         LARGE_INTEGER l;
430         static int have_perfc = 1;
431 #ifndef __GNUC__
432         static int have_tsc = 1;
433
434         if (have_tsc) {
435           __try {
436             __asm {
437               rdtsc
438               mov cyclecount, eax
439               }
440             RAND_add(&cyclecount, sizeof(cyclecount), 1);
441           } __except(EXCEPTION_EXECUTE_HANDLER) {
442             have_tsc = 0;
443           }
444         }
445 #else
446 # define have_tsc 0
447 #endif
448
449         if (have_perfc) {
450           if (QueryPerformanceCounter(&l) == 0)
451             have_perfc = 0;
452           else
453             RAND_add(&l, sizeof(l), 0);
454         }
455
456         if (!have_tsc && !have_perfc) {
457           w = GetTickCount();
458           RAND_add(&w, sizeof(w), 0);
459         }
460 }
461
462 /* feed screen contents to PRNG */
463 /*****************************************************************************
464  *
465  * Created 960901 by Gertjan van Oosten, gertjan@West.NL, West Consulting B.V.
466  *
467  * Code adapted from
468  * <URL:http://www.microsoft.com/kb/developr/win_dk/q97193.htm>;
469  * the original copyright message is:
470  *
471  *   (C) Copyright Microsoft Corp. 1993.  All rights reserved.
472  *
473  *   You have a royalty-free right to use, modify, reproduce and
474  *   distribute the Sample Files (and/or any modified version) in
475  *   any way you find useful, provided that you agree that
476  *   Microsoft has no warranty obligations or liability for any
477  *   Sample Application Files which are modified.
478  */
479
480 static void readscreen(void)
481 {
482   HDC           hScrDC;         /* screen DC */
483   HDC           hMemDC;         /* memory DC */
484   HBITMAP       hBitmap;        /* handle for our bitmap */
485   HBITMAP       hOldBitmap;     /* handle for previous bitmap */
486   BITMAP        bm;             /* bitmap properties */
487   unsigned int  size;           /* size of bitmap */
488   char          *bmbits;        /* contents of bitmap */
489   int           w;              /* screen width */
490   int           h;              /* screen height */
491   int           y;              /* y-coordinate of screen lines to grab */
492   int           n = 16;         /* number of screen lines to grab at a time */
493
494   /* Create a screen DC and a memory DC compatible to screen DC */
495   hScrDC = CreateDC("DISPLAY", NULL, NULL, NULL);
496   hMemDC = CreateCompatibleDC(hScrDC);
497
498   /* Get screen resolution */
499   w = GetDeviceCaps(hScrDC, HORZRES);
500   h = GetDeviceCaps(hScrDC, VERTRES);
501
502   /* Create a bitmap compatible with the screen DC */
503   hBitmap = CreateCompatibleBitmap(hScrDC, w, n);
504
505   /* Select new bitmap into memory DC */
506   hOldBitmap = SelectObject(hMemDC, hBitmap);
507
508   /* Get bitmap properties */
509   GetObject(hBitmap, sizeof(BITMAP), (LPSTR)&bm);
510   size = (unsigned int)bm.bmWidthBytes * bm.bmHeight * bm.bmPlanes;
511
512   bmbits = OPENSSL_malloc(size);
513   if (bmbits) {
514     /* Now go through the whole screen, repeatedly grabbing n lines */
515     for (y = 0; y < h-n; y += n)
516         {
517         unsigned char md[MD_DIGEST_LENGTH];
518
519         /* Bitblt screen DC to memory DC */
520         BitBlt(hMemDC, 0, 0, w, n, hScrDC, 0, y, SRCCOPY);
521
522         /* Copy bitmap bits from memory DC to bmbits */
523         GetBitmapBits(hBitmap, size, bmbits);
524
525         /* Get the hash of the bitmap */
526         MD(bmbits,size,md);
527
528         /* Seed the random generator with the hash value */
529         RAND_add(md, MD_DIGEST_LENGTH, 0);
530         }
531
532     OPENSSL_free(bmbits);
533   }
534
535   /* Select old bitmap back into memory DC */
536   hBitmap = SelectObject(hMemDC, hOldBitmap);
537
538   /* Clean up */
539   DeleteObject(hBitmap);
540   DeleteDC(hMemDC);
541   DeleteDC(hScrDC);
542 }
543
544 #else /* Unix version */
545
546 #include <time.h>
547
548 int RAND_poll(void)
549 {
550         unsigned long l;
551         pid_t curr_pid = getpid();
552 #ifdef DEVRANDOM
553         FILE *fh;
554 #endif
555
556 #ifdef DEVRANDOM
557         /* Use a random entropy pool device. Linux, FreeBSD and OpenBSD
558          * have this. Use /dev/urandom if you can as /dev/random may block
559          * if it runs out of random entries.  */
560
561         if ((fh = fopen(DEVRANDOM, "r")) != NULL)
562                 {
563                 unsigned char tmpbuf[ENTROPY_NEEDED];
564                 int n;
565                 
566                 setvbuf(fh, NULL, _IONBF, 0);
567                 n=fread((unsigned char *)tmpbuf,1,ENTROPY_NEEDED,fh);
568                 fclose(fh);
569                 RAND_add(tmpbuf,sizeof tmpbuf,n);
570                 memset(tmpbuf,0,n);
571                 }
572 #endif
573
574         /* put in some default random data, we need more than just this */
575         l=curr_pid;
576         RAND_add(&l,sizeof(l),0);
577         l=getuid();
578         RAND_add(&l,sizeof(l),0);
579
580         l=time(NULL);
581         RAND_add(&l,sizeof(l),0);
582
583 #ifdef DEVRANDOM
584         return 1;
585 #endif
586         return 0;
587 }
588
589 #endif