1d764d5f938fcb3f00cdbbf0b76ec46fada868a3
[u/mdw/putty] / noise.c
1 /*
2 * Noise generation for PuTTY's cryptographic random number
3 * generator.
4 */
5
6 #include <windows.h>
7 #ifndef AUTO_WINSOCK
8 #ifdef WINSOCK_TWO
9 #include <winsock2.h>
10 #else
11 #include <winsock.h>
12 #endif
13 #endif
14 #include <stdio.h>
15
16 #include "putty.h"
17 #include "ssh.h"
18 #include "storage.h"
19
20 /*
21 * GetSystemPowerStatus function.
22 */
23 typedef BOOL (WINAPI *gsps_t)(LPSYSTEM_POWER_STATUS);
24 static gsps_t gsps;
25
26 /*
27 * This function is called once, at PuTTY startup, and will do some
28 * seriously silly things like listing directories and getting disk
29 * free space and a process snapshot.
30 */
31
32 void noise_get_heavy(void (*func) (void *, int)) {
33 HANDLE srch;
34 WIN32_FIND_DATA finddata;
35 char winpath[MAX_PATH+3];
36 HMODULE mod;
37
38 GetWindowsDirectory(winpath, sizeof(winpath));
39 strcat(winpath, "\\*");
40 srch = FindFirstFile(winpath, &finddata);
41 if (srch != INVALID_HANDLE_VALUE) {
42 do {
43 func(&finddata, sizeof(finddata));
44 } while (FindNextFile(srch, &finddata));
45 FindClose(srch);
46 }
47
48 read_random_seed(func);
49
50 gsps = NULL;
51 mod = GetModuleHandle("KERNEL32");
52 if (mod) {
53 gsps = (gsps_t)GetProcAddress(mod, "GetSystemPowerStatus");
54 }
55 }
56
57 void random_save_seed(void) {
58 int len;
59 void *data;
60
61 random_get_savedata(&data, &len);
62 write_random_seed(data, len);
63 }
64
65 /*
66 * This function is called every time the random pool needs
67 * stirring, and will acquire the system time in all available
68 * forms and the battery status.
69 */
70 void noise_get_light(void (*func) (void *, int)) {
71 SYSTEMTIME systime;
72 DWORD adjust[2];
73 BOOL rubbish;
74 SYSTEM_POWER_STATUS pwrstat;
75
76 GetSystemTime(&systime);
77 func(&systime, sizeof(systime));
78
79 GetSystemTimeAdjustment(&adjust[0], &adjust[1], &rubbish);
80 func(&adjust, sizeof(adjust));
81
82 /*
83 * Call GetSystemPowerStatus if present.
84 */
85 if (gsps) {
86 if (gsps(&pwrstat))
87 func(&pwrstat, sizeof(pwrstat));
88 }
89 }
90
91 /*
92 * This function is called on every keypress or mouse move, and
93 * will add the current Windows time and performance monitor
94 * counter to the noise pool. It gets the scan code or mouse
95 * position passed in.
96 */
97 void noise_ultralight(DWORD data) {
98 DWORD wintime;
99 LARGE_INTEGER perftime;
100
101 random_add_noise(&data, sizeof(DWORD));
102
103 wintime = GetTickCount();
104 random_add_noise(&wintime, sizeof(DWORD));
105
106 if (QueryPerformanceCounter(&perftime))
107 random_add_noise(&perftime, sizeof(perftime));
108 }