1
mirror of https://github.com/rapid7/metasploit-framework synced 2024-07-18 18:31:41 +02:00

Land #2154, @wchen-r7's msfcli optimizations and refactoring

This commit is contained in:
jvazquez-r7 2013-07-29 16:38:22 -05:00
commit 593363c5f9
9 changed files with 850 additions and 294 deletions

View File

@ -5,25 +5,25 @@ module Msf
# Initialize the module paths
#
# @return [void]
def init_module_paths
def init_module_paths(opts={})
# Ensure the module cache is accurate
self.modules.refresh_cache_from_database
# Initialize the default module search paths
if (Msf::Config.module_directory)
self.modules.add_module_path(Msf::Config.module_directory)
self.modules.add_module_path(Msf::Config.module_directory, opts)
end
# Initialize the user module search path
if (Msf::Config.user_module_directory)
self.modules.add_module_path(Msf::Config.user_module_directory)
self.modules.add_module_path(Msf::Config.user_module_directory, opts)
end
# If additional module paths have been defined globally, then load them.
# They should be separated by semi-colons.
if self.datastore['MsfModulePaths']
self.datastore['MsfModulePaths'].split(";").each { |path|
self.modules.add_module_path(path)
self.modules.add_module_path(path, opts)
}
end
end

View File

@ -53,39 +53,39 @@ module Msf::ModuleManager::Loading
attr_accessor :module_load_error_by_path
# Called when a module is initially loaded such that it can be categorized
# accordingly.
#
# @param class_or_module [Class<Msf::Module>, ::Module] either a module Class
# or a payload Module.
# @param type [String] The module type.
# @param reference_name The module reference name.
# @param info [Hash{String => Array}] additional information about the module
# @option info [Array<String>] 'files' List of paths to the ruby source files
# where +class_or_module+ is defined.
# @option info [Array<String>] 'paths' List of module reference names.
# @option info [String] 'type' The module type, should match positional
# +type+ argument.
# @return [void]
def on_module_load(class_or_module, type, reference_name, info={})
module_set = module_set_by_type[type]
module_set.add_module(class_or_module, reference_name, info)
# Called when a module is initially loaded such that it can be categorized
# accordingly.
#
# @param class_or_module [Class<Msf::Module>, ::Module] either a module Class
# or a payload Module.
# @param type [String] The module type.
# @param reference_name The module reference name.
# @param info [Hash{String => Array}] additional information about the module
# @option info [Array<String>] 'files' List of paths to the ruby source files
# where +class_or_module+ is defined.
# @option info [Array<String>] 'paths' List of module reference names.
# @option info [String] 'type' The module type, should match positional
# +type+ argument.
# @return [void]
def on_module_load(class_or_module, type, reference_name, info={})
module_set = module_set_by_type[type]
module_set.add_module(class_or_module, reference_name, info)
path = info['files'].first
cache_in_memory(
class_or_module,
:path => path,
:reference_name => reference_name,
:type => type
)
path = info['files'].first
cache_in_memory(
class_or_module,
:path => path,
:reference_name => reference_name,
:type => type
)
# Automatically subscribe a wrapper around this module to the necessary
# event providers based on whatever events it wishes to receive.
auto_subscribe_module(class_or_module)
# Automatically subscribe a wrapper around this module to the necessary
# event providers based on whatever events it wishes to receive.
auto_subscribe_module(class_or_module)
# Notify the framework that a module was loaded
framework.events.on_module_load(reference_name, class_or_module)
end
# Notify the framework that a module was loaded
framework.events.on_module_load(reference_name, class_or_module)
end
protected
@ -106,9 +106,10 @@ module Msf::ModuleManager::Loading
# @param [Hash] options
# @option options [Boolean] :force Whether the force loading the modules even if they are unchanged and already
# loaded.
# @option options [Array] :modules An array of regex patterns to search for specific modules
# @return [Hash{String => Integer}] Maps module type to number of modules loaded
def load_modules(path, options={})
options.assert_valid_keys(:force)
options.assert_valid_keys(:force, :whitelist)
count_by_type = {}
@ -122,4 +123,4 @@ module Msf::ModuleManager::Loading
count_by_type
end
end
end

View File

@ -12,8 +12,10 @@ module Msf::ModuleManager::ModulePaths
# Adds a path to be searched for new modules.
#
# @param [String] path
# @param [Hash] opts
# @option opts [Array] whitelist An array of regex patterns to search for specific modules
# @return (see Msf::Modules::Loader::Base#load_modules)
def add_module_path(path)
def add_module_path(path, opts={})
nested_paths = []
# remove trailing file separator
@ -51,7 +53,7 @@ module Msf::ModuleManager::ModulePaths
# Load all of the modules from the nested paths
count_by_type = {}
nested_paths.each { |path|
path_count_by_type = load_modules(path, :force => false)
path_count_by_type = load_modules(path, opts.merge({:force => false}))
# merge hashes
path_count_by_type.each do |type, path_count|
@ -74,4 +76,4 @@ module Msf::ModuleManager::ModulePaths
protected
attr_accessor :module_paths # :nodoc:
end
end

View File

@ -27,10 +27,12 @@ class Msf::Modules::Loader::Archive < Msf::Modules::Loader::Base
# Yields the module_reference_name for each module file in the Fastlib archive at path.
#
# @param path [String] The path to the Fastlib archive file.
# @param opts [Hash] Additional options
# @yield (see Msf::Modules::Loader::Base#each_module_reference_name)
# @yieldparam (see Msf::Modules::Loader::Base#each_module_reference_name)
# @return (see Msf::Modules::Loader::Base#each_module_reference_name)
def each_module_reference_name(path)
def each_module_reference_name(path, opts={})
whitelist = opts[:whitelist] || []
entries = ::FastLib.list(path)
entries.each do |entry|
@ -45,11 +47,22 @@ class Msf::Modules::Loader::Archive < Msf::Modules::Loader::Base
next
end
if module_path?(entry)
# The module_reference_name doesn't have a file extension
module_reference_name = module_reference_name_from_path(entry)
if whitelist.empty?
yield path, type, module_reference_name
if module_path?(entry)
# The module_reference_name doesn't have a file extension
module_reference_name = module_reference_name_from_path(entry)
yield path, type, module_reference_name
end
else
whitelist.each do |pattern|
if entry =~ pattern
yield path, type, module_reference_name
else
next
end
end
end
end
end

View File

@ -248,16 +248,25 @@ class Msf::Modules::Loader::Base
# @param [Hash] options
# @option options [Boolean] force (false) Whether to force loading of
# the module even if the module has not changed.
# @option options [Array] whitelist An array of regex patterns to search for specific modules
# @return [Hash{String => Integer}] Maps module type to number of
# modules loaded
def load_modules(path, options={})
options.assert_valid_keys(:force)
options.assert_valid_keys(:force, :whitelist)
force = options[:force]
count_by_type = {}
recalculate_by_type = {}
each_module_reference_name(path) do |parent_path, type, module_reference_name|
# This is used to avoid loading the same thing twice
loaded_items = []
each_module_reference_name(path, options) do |parent_path, type, module_reference_name|
# In msfcli mode, if a module is already loaded, avoid loading it again
next if loaded_items.include?(module_reference_name) and options[:whitelist]
# Keep track of loaded modules in msfcli mode
loaded_items << module_reference_name if options[:whitelist]
load_module(
parent_path,
type,
@ -649,4 +658,3 @@ class Msf::Modules::Loader::Base
usable
end
end

View File

@ -18,12 +18,14 @@ class Msf::Modules::Loader::Directory < Msf::Modules::Loader::Base
# Yields the module_reference_name for each module file found under the directory path.
#
# @param [String] path The path to the directory.
# @param [Array] modules An array of regex patterns to search for specific modules
# @yield (see Msf::Modules::Loader::Base#each_module_reference_name)
# @yieldparam [String] path The path to the directory.
# @yieldparam [String] type The type correlated with the directory under path.
# @yieldparam module_reference_name (see Msf::Modules::Loader::Base#each_module_reference_name)
# @return (see Msf::Modules::Loader::Base#each_module_reference_name)
def each_module_reference_name(path)
def each_module_reference_name(path, opts={})
whitelist = opts[:whitelist] || []
::Dir.foreach(path) do |entry|
if entry.downcase == '.svn'
next
@ -49,7 +51,24 @@ class Msf::Modules::Loader::Directory < Msf::Modules::Loader::Base
# The module_reference_name doesn't have a file extension
module_reference_name = module_reference_name_from_path(relative_entry_descendant_path)
yield path, type, module_reference_name
# If the modules argument is set, this means we only want to load specific ones instead
# of loading everything to memory - see msfcli.
if whitelist.empty?
# Load every module we see, which is the default behavior.
yield path, type, module_reference_name
else
whitelist.each do |pattern|
# We have to use entry_descendant_path to see if this is the module we want, because
# this is easier to identify the module type just by looking at the file path.
# For example, if module_reference_name is used (or a parsed relative path), you can't
# really tell if php/generic is a NOP module, a payload, or an encoder.
if entry_descendant_path =~ pattern
yield path, type, module_reference_name
else
next
end
end
end
end
end
end
@ -76,18 +95,18 @@ class Msf::Modules::Loader::Directory < Msf::Modules::Loader::Base
module_content = ''
begin
# force to read in binary mode so Pro modules won't be truncated on Windows
File.open(full_path, 'rb') do |f|
# Pass the size of the file as it leads to faster reads due to fewer buffer resizes. Greatest effect on Windows.
# @see http://www.ruby-forum.com/topic/209005
# @see https://github.com/ruby/ruby/blob/ruby_1_8_7/io.c#L1205
# @see https://github.com/ruby/ruby/blob/ruby_1_9_3/io.c#L2038
module_content = f.read(f.stat.size)
end
# force to read in binary mode so Pro modules won't be truncated on Windows
File.open(full_path, 'rb') do |f|
# Pass the size of the file as it leads to faster reads due to fewer buffer resizes. Greatest effect on Windows.
# @see http://www.ruby-forum.com/topic/209005
# @see https://github.com/ruby/ruby/blob/ruby_1_8_7/io.c#L1205
# @see https://github.com/ruby/ruby/blob/ruby_1_9_3/io.c#L2038
module_content = f.read(f.stat.size)
end
rescue Errno::ENOENT => error
load_error(full_path, error)
load_error(full_path, error)
end
module_content
end
end
end

760
msfcli
View File

@ -1,14 +1,10 @@
#!/usr/bin/env ruby
# -*- coding: binary -*-
#
# $Id$
#
# This user interface allows users to interact with the framework through a
# command line interface (CLI) rather than having to use a prompting console
# or web-based interface.
#
# $Revision$
#
msfbase = __FILE__
while File.symlink?(msfbase)
@ -18,245 +14,545 @@ end
$:.unshift(File.expand_path(File.join(File.dirname(msfbase), 'lib')))
require 'rex'
Indent = ' '
class Msfcli
def initialize(args)
@args = {}
@indent = ' '
@framework = nil
def usage (str = nil, extra = nil)
tbl = Rex::Ui::Text::Table.new(
'Header' => "Usage: #{$0} <exploit_name> <option=value> [mode]",
'Indent' => 4,
'Columns' => ['Mode', 'Description']
)
@args[:module_name] = args.shift # First argument should be the module name
@args[:mode] = args.pop || 'h' # Last argument should be the mode
@args[:params] = args # Whatever is in the middle should be the params
tbl << ['(H)elp', "You're looking at it baby!"]
tbl << ['(S)ummary', 'Show information about this module']
tbl << ['(O)ptions', 'Show available options for this module']
tbl << ['(A)dvanced', 'Show available advanced options for this module']
tbl << ['(I)DS Evasion', 'Show available ids evasion options for this module']
tbl << ['(P)ayloads', 'Show available payloads for this module']
tbl << ['(T)argets', 'Show available targets for this exploit module']
tbl << ['(AC)tions', 'Show available actions for this auxiliary module']
tbl << ['(C)heck', 'Run the check routine of the selected module']
tbl << ['(E)xecute', 'Execute the selected module']
$stdout.puts "Error: #{str}\n\n" if str
$stdout.puts tbl.to_s + "\n"
$stdout.puts extra + "\n" if extra
exit
end
# Handle the help option before loading modules
exploit_name = ARGV.shift
exploit = nil
module_class = "exploit"
if(exploit_name == "-h")
usage()
else
$:.unshift(ENV['MSF_LOCAL_LIB']) if ENV['MSF_LOCAL_LIB']
require 'fastlib'
require 'msfenv'
require 'msf/ui'
require 'msf/base'
end
# Initialize the simplified framework instance.
$stderr.puts "[*] Please wait while we load the module tree..."
$framework = Msf::Simple::Framework.create
if ($framework.modules.module_load_error_by_path.length > 0)
print("Warning: The following modules could not be loaded!\n\n")
$framework.modules.module_load_error_by_path.each do |path, error|
print("\t#{path}: #{error}\n\n")
end
end
if (not exploit_name)
ext = ''
tbl = Rex::Ui::Text::Table.new(
'Header' => 'Exploits',
'Indent' => 4,
'Columns' => [ 'Name', 'Description' ])
$framework.exploits.each_module { |name, mod|
tbl << [ 'exploit/' + name, mod.new.name ]
}
ext << tbl.to_s + "\n"
tbl = Rex::Ui::Text::Table.new(
'Header' => 'Auxiliary',
'Indent' => 4,
'Columns' => [ 'Name', 'Description' ])
$framework.auxiliary.each_module { |name, mod|
tbl << [ 'auxiliary/' + name, mod.new.name ]
}
ext << tbl.to_s + "\n"
usage(nil, ext)
end
# Process special var/val pairs...
Msf::Ui::Common.process_cli_arguments($framework, ARGV)
# Determine what type of module it is
case exploit_name
when /exploit\/(.*)/
exploit = $framework.exploits.create($1)
module_class = 'exploit'
when /auxiliary\/(.*)/
exploit = $framework.auxiliary.create($1)
module_class = 'auxiliary'
else
exploit = $framework.exploits.create(exploit_name)
if exploit == nil
# Try falling back on aux modules
exploit = $framework.auxiliary.create(exploit_name)
module_class = 'auxiliary'
end
end
if (exploit == nil)
usage("Invalid module: #{exploit_name}")
end
exploit.init_ui(
Rex::Ui::Text::Input::Stdio.new,
Rex::Ui::Text::Output::Stdio.new
)
# Evalulate the command (default to "help")
mode = ARGV.pop || 'h'
# Import options
begin
exploit.datastore.import_options_from_s(ARGV.join('_|_'), '_|_')
rescue Rex::ArgumentParseError => e
puts "[!] Error: #{e.message}\n\n"
exit
end
# Initialize associated modules
payload = nil
encoder = nil
nop = nil
if (exploit.datastore['PAYLOAD'])
payload = $framework.payloads.create(exploit.datastore['PAYLOAD'])
if (payload != nil)
payload.datastore.import_options_from_s(ARGV.join('_|_'), '_|_')
end
end
if (exploit.datastore['ENCODER'])
encoder = $framework.encoders.create(exploit.datastore['ENCODER'])
if (encoder != nil)
encoder.datastore.import_options_from_s(ARGV.join('_|_'), '_|_')
end
end
if (exploit.datastore['NOP'])
nop = $framework.nops.create(exploit.datastore['NOP'])
if (nop != nil)
nop.datastore.import_options_from_s(ARGV.join('_|_'), '_|_')
end
end
case mode.downcase
when 'h'
usage
when "s"
$stdout.puts("\n" + Msf::Serializer::ReadableText.dump_module(exploit, Indent))
$stdout.puts("\n" + Msf::Serializer::ReadableText.dump_module(payload, Indent)) if payload
$stdout.puts("\n" + Msf::Serializer::ReadableText.dump_module(encoder, Indent)) if encoder
$stdout.puts("\n" + Msf::Serializer::ReadableText.dump_module(nop, Indent)) if nop
when "o"
$stdout.puts("\n" + Msf::Serializer::ReadableText.dump_options(exploit, Indent))
$stdout.puts("\nPayload:\n\n" + Msf::Serializer::ReadableText.dump_options(payload, Indent)) if payload
$stdout.puts("\nEncoder:\n\n" + Msf::Serializer::ReadableText.dump_options(encoder, Indent)) if encoder
$stdout.puts("\nNOP\n\n" + Msf::Serializer::ReadableText.dump_options(nop, Indent)) if nop
when "a"
$stdout.puts("\n" + Msf::Serializer::ReadableText.dump_advanced_options(exploit, Indent))
$stdout.puts("\nPayload:\n\n" + Msf::Serializer::ReadableText.dump_advanced_options(payload, Indent)) if payload
$stdout.puts("\nEncoder:\n\n" + Msf::Serializer::ReadableText.dump_advanced_options(encoder, Indent)) if encoder
$stdout.puts("\nNOP:\n\n" + Msf::Serializer::ReadableText.dump_advanced_options(nop, Indent)) if nop
when "i"
$stdout.puts("\n" + Msf::Serializer::ReadableText.dump_evasion_options(exploit, Indent))
$stdout.puts("\nPayload:\n\n" + Msf::Serializer::ReadableText.dump_evasion_options(payload, Indent)) if payload
$stdout.puts("\nEncoder:\n\n" + Msf::Serializer::ReadableText.dump_evasion_options(encoder, Indent)) if encoder
$stdout.puts("\nNOP:\n\n" + Msf::Serializer::ReadableText.dump_evasion_options(nop, Indent)) if nop
when "p"
if (module_class == 'exploit')
$stdout.puts("\n" + Msf::Serializer::ReadableText.dump_compatible_payloads(exploit, Indent, "Compatible payloads"))
else
$stdout.puts("\nError: This type of module does not support payloads")
if @args[:module_name] =~ /^exploit(s)*\//i
@args[:module_name] = @args[:module_name].split('/')
@args[:module_name] = @args[:module_name][1, @args[:module_name].length] * "/"
end
when "t"
if (module_class == 'exploit')
$stdout.puts("\n" + Msf::Serializer::ReadableText.dump_exploit_targets(exploit, Indent))
else
$stdout.puts("\nError: This type of module does not support targets")
end
#
# Returns a usage Rex table
#
def usage (str = nil, extra = nil)
tbl = Rex::Ui::Text::Table.new(
'Header' => "Usage: #{$0} <exploit_name> <option=value> [mode]",
'Indent' => 4,
'Columns' => ['Mode', 'Description']
)
tbl << ['(H)elp', "You're looking at it baby!"]
tbl << ['(S)ummary', 'Show information about this module']
tbl << ['(O)ptions', 'Show available options for this module']
tbl << ['(A)dvanced', 'Show available advanced options for this module']
tbl << ['(I)DS Evasion', 'Show available ids evasion options for this module']
tbl << ['(P)ayloads', 'Show available payloads for this module']
tbl << ['(T)argets', 'Show available targets for this exploit module']
tbl << ['(AC)tions', 'Show available actions for this auxiliary module']
tbl << ['(C)heck', 'Run the check routine of the selected module']
tbl << ['(E)xecute', 'Execute the selected module']
tbl.to_s
$stdout.puts "Error: #{str}\n\n" if str
$stdout.puts tbl.to_s + "\n"
$stdout.puts "Examples:" + "\n"
$stdout.puts "msfcli multi/handler payload=windows/meterpreter/reverse_tcp lhost=IP E" + "\n"
$stdout.puts "msfcli auxiliary/scanner/http/http_version rhosts=IP encoder= post= nop= E" + "\n"
$stdout.puts extra + "\n" if extra
$stdout.puts
end
#
# Loads up everything in framework, and then returns the module list
#
def dump_module_list
# This is what happens if the user doesn't specify a module name:
# msfcli will end up loading EVERYTHING to memory to show you a help
# menu plus a list of modules available. Really expensive if you ask me.
$stdout.puts "[*] Please wait while we load the module tree..."
framework = Msf::Simple::Framework.create
ext = ''
tbl = Rex::Ui::Text::Table.new(
'Header' => 'Exploits',
'Indent' => 4,
'Columns' => [ 'Name', 'Description' ])
framework.exploits.each_module { |name, mod|
tbl << [ 'exploit/' + name, mod.new.name ]
}
ext << tbl.to_s + "\n"
tbl = Rex::Ui::Text::Table.new(
'Header' => 'Auxiliary',
'Indent' => 4,
'Columns' => [ 'Name', 'Description' ])
framework.auxiliary.each_module { |name, mod|
tbl << [ 'auxiliary/' + name, mod.new.name ]
}
ext << tbl.to_s + "\n"
ext
end
#
# Payload naming style is kind of inconsistent, so instead of
# finding the exact path name, we provide the most educated guess (whitelist)
# based on platform/stage type/session type/payload name suffix/etc.
#
def guess_payload_name(p)
matches = []
payload = p.split('/')
platform = payload[0]
suffix = payload[-1]
stage_types = ['singles', 'stagers', 'stages']
session_types = ['meterpreter', 'shell']
arch = ''
# Rule out some possibilities
if p =~ /meterpreter/i
session_types.delete('shell')
stage_types.delete('singles')
end
when "ac"
if (module_class == 'auxiliary')
$stdout.puts("\n" + Msf::Serializer::ReadableText.dump_auxiliary_actions(exploit, Indent))
else
$stdout.puts("\nError: This type of module does not support actions")
if p =~ /shell\/.+$/i
session_types.delete('meterpreter')
stage_types.delete('singles')
end
when "c"
if (module_class == 'exploit')
begin
if (code = exploit.check_simple(
'LocalInput' => Rex::Ui::Text::Input::Stdio.new,
'LocalOutput' => Rex::Ui::Text::Output::Stdio.new))
stat = (code == Msf::Exploit::CheckCode::Vulnerable) ? '[+]' : '[*]'
$stdout.puts("#{stat} #{code[1]}")
else
$stderr.puts("Check failed: The state could not be determined.")
end
rescue
$stderr.puts("Check failed: #{$!}")
end
else
$stdout.puts("\nError: This type of module does not support the check feature")
if p =~ /x64/i
arch = 'x64'
elsif p =~ /x86/i
arch = 'x86'
end
when "e"
con = Msf::Ui::Console::Driver.new(
Msf::Ui::Console::Driver::DefaultPrompt,
Msf::Ui::Console::Driver::DefaultPromptChar,
{
'Framework' => $framework
}
)
con.run_single("use #{module_class}/#{exploit.refname}")
ARGV.each do |arg|
k,v = arg.split("=", 2)
con.run_single("set #{k} #{v}")
end
con.run_single("exploit")
# If we have sessions or jobs, keep running
if $framework.sessions.length > 0 or $framework.jobs.length > 0
con.run
# Determine if the payload is staged. If it is, then
# we need to load that staged module too.
if session_types.include?('shell') and stage_types.include?('stages')
if arch == 'x64'
matches << /stages\/#{platform}\/x64\/shell/
elsif arch == 'x86'
matches << /stages\/#{platform}\/x86\/shell/
else
con.run_single("quit")
matches << /stages\/#{platform}\/shell/
end
elsif session_types.include?('meterpreter') and stage_types.include?('stages')
if arch == 'x64'
matches << /stages\/#{platform}\/x64\/meterpreter/
elsif arch == 'x86'
matches << /stages\/#{platform}\/x86\/meterpreter/
else
matches << /stages\/#{platform}\/meterpreter/
end
end
# Guess the second possible match
stage_types *= "|"
session_types *= "|"
if arch == 'x64'
matches << /payloads\/(#{stage_types})\/#{platform}\/x64\/.*(#{suffix})\.rb$/
elsif arch == 'x86'
matches << /payloads\/(#{stage_types})\/#{platform}\/x86\/.*(#{suffix})\.rb$/
else
matches << /payloads\/(#{stage_types})\/#{platform}\/.*(#{suffix})\.rb$/
end
matches
end
#
# Returns a whitelist for encoder modules
#
def guess_encoder_name(e)
[/encoders\/#{e}/]
end
#
# Returns a whitelist for nop modules
#
def guess_nop_name(n)
[/nops\/#{n}/]
end
#
# Returns a whitelist for post modules
#
def guess_post_name(p)
[/post\/#{p}/]
end
#
# Returns possible patterns like exploit/aux, encoders, nops we want to
# load to the whitelist.
#
def generate_whitelist
whitelist = []
whitelist << /#{@args[:module_name]}/ # Add exploit
# nil = not set, empty = manually set to load nothing
encoder_val = nil
nops_val = nil
post_val = nil
payload_param = ''
junk_args = []
@args[:params].each { |args|
var, val = args.split('=', 2)
case var.downcase
when 'payload'
payload_param = val
if val.empty?
junk_args << args
else
whitelist.concat(guess_payload_name(val))
end
when 'encoder'
encoder_val = val
if val.empty?
junk_args << args
else
whitelist.concat(guess_encoder_name(val))
end
when 'nop'
nops_val = val
if val.empty?
junk_args << args
else
whitelist.concat(guess_nop_name(val))
end
when 'post'
post_val = val
if val.empty?
junk_args << args
else
whitelist.concat(guess_post_name(val))
end
end
}
# Cleanup empty args
junk_args.each { |args| @args[:params].delete(args) }
# If it's an exploit and no payload set, load them all.
if @args[:module_name] !~ /auxiliary\// and payload_param.empty?
whitelist << /payloads\/.+/
end
# Add post modules list if not set
if post_val.nil?
whitelist << /post\/.+/
end
# Add default encoders if not set
# This one is needed no matter what
whitelist << /encoders\/generic\/*/
if encoder_val.nil?
if payload_param =~ /^.+\.x64.+/
whitelist << /encoders\/x64\/.+/
elsif payload_param =~ /^.+\.x86.+/
whitelist << /encoders\/x86\/.+/
else
whitelist << /encoders\/.+/
end
end
# Add default NOP modules if not set
if nops_val.nil?
whitelist << /nops\/.+/
end
whitelist
end
#
# Initializes exploit/payload/encoder/nop modules.
#
def init_modules
@framework = Msf::Simple::Framework.create({'DeferModuleLoads'=>true})
$stdout.puts "[*] Initializing modules..."
module_name = @args[:module_name]
modules = {
:module => nil, # aux or exploit instance
:payload => nil, # payload instance
:encoder => nil, # encoder instance
:nop => nil # nop instance
}
whitelist = generate_whitelist
# Load up all the possible modules, this is where things get slow again
@framework.init_module_paths({:whitelist=>whitelist})
if (@framework.modules.module_load_error_by_path.length > 0)
print("Warning: The following modules could not be loaded!\n\n")
@framework.modules.module_load_error_by_path.each do |path, error|
print("\t#{path}: #{error}\n\n")
end
else
usage("Invalid mode #{mode}")
return {}
end
# Determine what type of module it is
if module_name =~ /exploit\/(.*)/
modules[:module] = @framework.exploits.create($1)
elsif module_name =~ /auxiliary\/(.*)/
modules[:module] = @framework.auxiliary.create($1)
else
modules[:module] = @framework.exploits.create(module_name)
if modules[:module].nil?
# Try falling back on aux modules
modules[:module] = @framework.auxiliary.create(module_name)
end
end
if modules[:module].nil?
# Still nil? Ok then, probably invalid
return {}
end
modules[:module].init_ui(
Rex::Ui::Text::Input::Stdio.new,
Rex::Ui::Text::Output::Stdio.new
)
# Import options
begin
modules[:module].datastore.import_options_from_s(@args[:params].join('_|_'), '_|_')
rescue Rex::ArgumentParseError => e
raise e
end
# Create the payload to use
if (modules[:module].datastore['PAYLOAD'])
modules[:payload] = @framework.payloads.create(modules[:module].datastore['PAYLOAD'])
if modules[:payload]
modules[:payload].datastore.import_options_from_s(@args[:params].join('_|_'), '_|_')
end
end
# Create the encoder to use
if modules[:module].datastore['ENCODER']
modules[:encoder] = @framework.encoders.create(modules[:module].datastore['ENCODER'])
if modules[:encoder]
modules[:encoder].datastore.import_options_from_s(@args[:params].join('_|_'), '_|_')
end
end
# Create the NOP to use
if modules[:module].datastore['NOP']
modules[:nop] = @framework.nops.create(modules[:module].datastore['NOP'])
if modules[:nop]
modules[:nop].datastore.import_options_from_s(@args[:params].join('_|_'), '_|_')
end
end
modules
end
def show_summary(m)
readable = Msf::Serializer::ReadableText
$stdout.puts("\n" + readable.dump_module(m[:module], @indent))
$stdout.puts("\n" + readable.dump_module(m[:payload], @indent)) if m[:payload]
$stdout.puts("\n" + readable.dump_module(m[:encoder], @indent)) if m[:encoder]
$stdout.puts("\n" + readable.dump_module(m[:nop], @indent)) if m[:nop]
end
def show_options(m)
readable = Msf::Serializer::ReadableText
$stdout.puts("\n" + readable.dump_options(m[:module], @indent))
$stdout.puts("\nPayload:\n\n" + readable.dump_options(m[:payload], @indent)) if m[:payload]
$stdout.puts("\nEncoder:\n\n" + readable.dump_options(m[:encoder], @indent)) if m[:encoder]
$stdout.puts("\nNOP\n\n" + readable.dump_options(m[:nop], @indent)) if m[:nop]
end
def show_advanced(m)
readable = Msf::Serializer::ReadableText
$stdout.puts("\n" + readable.dump_advanced_options(m[:module], @indent))
$stdout.puts("\nPayload:\n\n" + readable.dump_advanced_options(m[:payload], @indent)) if m[:payload]
$stdout.puts("\nEncoder:\n\n" + readable.dump_advanced_options(m[:encoder], @indent)) if m[:encoder]
$stdout.puts("\nNOP:\n\n" + readable.dump_advanced_options(m[:nop], @indent)) if m[:nop]
end
def show_ids_evasion(m)
readable = Msf::Serializer::ReadableText
$stdout.puts("\n" + readable.dump_evasion_options(m[:module], @indent))
$stdout.puts("\nPayload:\n\n" + readable.dump_evasion_options(m[:payload], @indent)) if m[:payload]
$stdout.puts("\nEncoder:\n\n" + readable.dump_evasion_options(m[:encoder], @indent)) if m[:encoder]
$stdout.puts("\nNOP:\n\n" + readable.dump_evasion_options(m[:nop], @indent)) if m[:nop]
end
def show_payloads(m)
readable = Msf::Serializer::ReadableText
txt = "Compatible payloads"
$stdout.puts("\n" + readable.dump_compatible_payloads(m[:module], @indent, txt))
end
def show_targets(m)
readable = Msf::Serializer::ReadableText
$stdout.puts("\n" + readable.dump_exploit_targets(m[:module], @indent))
end
def show_actions(m)
readable = Msf::Serializer::ReadableText
$stdout.puts("\n" + readable.dump_auxiliary_actions(m[:module], @indent))
end
def show_check(m)
begin
if (code = m[:module].check_simple(
'LocalInput' => Rex::Ui::Text::Input::Stdio.new,
'LocalOutput' => Rex::Ui::Text::Output::Stdio.new))
stat = (code == Msf::Exploit::CheckCode::Vulnerable) ? '[+]' : '[*]'
$stdout.puts("#{stat} #{code[1]}")
else
$stderr.puts("Check failed: The state could not be determined.")
end
rescue
$stderr.puts("Check failed: #{$!}")
end
end
def execute_module(m)
con = Msf::Ui::Console::Driver.new(
Msf::Ui::Console::Driver::DefaultPrompt,
Msf::Ui::Console::Driver::DefaultPromptChar,
{
'Framework' => @framework,
# When I use msfcli, chances are I want speed, so ASCII art fanciness
# probably isn't much of a big deal for me.
'DisableBanner' => true
})
module_class = (m[:module].fullname =~ /^auxiliary/ ? 'auxiliary' : 'exploit')
con.run_single("use #{module_class}/#{m[:module].refname}")
# Assign console parameters
@args[:params].each do |arg|
k,v = arg.split("=", 2)
con.run_single("set #{k} #{v}")
end
# Run the exploit
con.run_single("exploit")
# If we have sessions or jobs, keep running
if @framework.sessions.length > 0 or @framework.jobs.length > 0
con.run
else
con.run_single("quit")
end
end
#
# Selects a mode chosen by the user and run it
#
def engage_mode(modules)
case @args[:mode].downcase
when 'h'
usage
when "s"
show_summary(modules)
when "o"
show_options(modules)
when "a"
show_advanced(modules)
when "i"
show_ids_evasion(modules)
when "p"
if modules[:module].file_path =~ /auxiliary\//i
$stdout.puts("\nError: This type of module does not support payloads")
else
show_payloads(modules)
end
when "t"
puts
if modules[:module].file_path =~ /auxiliary\//i
$stdout.puts("\nError: This type of module does not support targets")
else
show_targets(modules)
end
when "ac"
if modules[:module].file_path =~ /auxiliary\//i
show_actions(modules)
else
$stdout.puts("\nError: This type of module does not support actions")
end
when "c"
show_check(modules)
when "e"
execute_module(modules)
else
usage("Invalid mode #{@args[:mode]}")
end
end
def run!
if @args[:module_name] == "-h"
usage()
exit
end
$:.unshift(ENV['MSF_LOCAL_LIB']) if ENV['MSF_LOCAL_LIB']
require 'fastlib'
require 'msfenv'
require 'msf/ui'
require 'msf/base'
if @args[:module_name].nil?
ext = dump_module_list
usage(nil, ext)
exit
end
begin
modules = init_modules
rescue Rex::ArgumentParseError => e
puts "[!] Error: #{e.message}\n\n"
exit
end
if modules[:module].nil?
usage("Invalid module: #{@args[:module_name]}")
exit
end
# Process special var/val pairs...
Msf::Ui::Common.process_cli_arguments(@framework, @args[:params])
engage_mode(modules)
$stdout.puts
end
end
$stdout.puts
if __FILE__ == $PROGRAM_NAME
cli = Msfcli.new(ARGV)
cli.run!
end

211
spec/msfcli_spec.rb Normal file
View File

@ -0,0 +1,211 @@
require 'spec_helper'
load Metasploit::Framework.root.join('msfcli').to_path
require 'fastlib'
require 'msfenv'
require 'msf/ui'
require 'msf/base'
describe Msfcli do
# Get stdout:
# http://stackoverflow.com/questions/11349270/test-output-to-command-line-with-rspec
def get_stdout(&block)
out = $stdout
$stdout = fake = StringIO.new
begin
yield
ensure
$stdout = out
end
fake.string
end
context "Class methods" do
context ".usage" do
it "should see a help menu" do
out = get_stdout {
cli = Msfcli.new([])
cli.usage
}
out.should =~ /Usage/
end
end
#
# This one is slow because we're loading all modules
#
context ".dump_module_list" do
it "it should dump a list of modules" do
tbl = ''
stdout = get_stdout {
cli = Msfcli.new([])
tbl = cli.dump_module_list
}
tbl.should =~ /Exploits/ and stdout.should =~ /Please wait/
end
end
context ".guess_payload_name" do
cli = Msfcli.new([])
it "should contain matches nedded for windows/meterpreter/reverse_tcp" do
m = cli.guess_payload_name('windows/meterpreter/reverse_tcp')
m.should eq([/stages\/windows\/meterpreter/, /payloads\/(stagers|stages)\/windows\/.*(reverse_tcp)\.rb$/])
end
it "should contain matches needed for windows/shell/reverse_tcp" do
m = cli.guess_payload_name('windows/shell/reverse_tcp')
m.should eq([/stages\/windows\/shell/, /payloads\/(stagers|stages)\/windows\/.*(reverse_tcp)\.rb$/])
end
it "should contain matches needed for windows/shell_reverse_tcp" do
m = cli.guess_payload_name('windows/shell_reverse_tcp')
m.should eq([/stages\/windows\/shell/, /payloads\/(singles|stagers|stages)\/windows\/.*(shell_reverse_tcp)\.rb$/])
end
it "should contain matches needed for php/meterpreter_reverse_tcp" do
m = cli.guess_payload_name('php/meterpreter_reverse_tcp')
m.should eq([/stages\/php\/meterpreter/, /payloads\/(stagers|stages)\/php\/.*(meterpreter_reverse_tcp)\.rb$/])
end
it "should contain matches needed for linux/x86/meterpreter/reverse_tcp" do
m = cli.guess_payload_name('linux/x86/meterpreter/reverse_tcp')
m.should eq([/stages\/linux\/x86\/meterpreter/, /payloads\/(stagers|stages)\/linux\/x86\/.*(reverse_tcp)\.rb$/])
end
it "should contain matches needed for java/meterpreter/reverse_tcp" do
m = cli.guess_payload_name('java/meterpreter/reverse_tcp')
m.should eq([/stages\/java\/meterpreter/, /payloads\/(stagers|stages)\/java\/.*(reverse_tcp)\.rb$/])
end
it "should contain matches needed for cmd/unix/reverse" do
m = cli.guess_payload_name('cmd/unix/reverse')
m.should eq([/stages\/cmd\/shell/, /payloads\/(singles|stagers|stages)\/cmd\/.*(reverse)\.rb$/])
end
it "should contain matches needed for bsd/x86/shell_reverse_tcp" do
m = cli.guess_payload_name('bsd/x86/shell_reverse_tcp')
m.should eq([/stages\/bsd\/x86\/shell/, /payloads\/(singles|stagers|stages)\/bsd\/x86\/.*(shell_reverse_tcp)\.rb$/])
end
end
context ".guess_encoder_name" do
cli = Msfcli.new([])
it "should contain a match for x86/shikata_ga_nai" do
encoder = 'x86/shikata_ga_nai'
m = cli.guess_encoder_name(encoder)
m.should eq([/encoders\/#{encoder}/])
end
end
context ".guess_nop_name" do
cli = Msfcli.new([])
it "should contain a match for guess_nop_name" do
nop = 'x86/single_byte'
m = cli.guess_nop_name(nop)
m.should eq([/nops\/#{nop}/])
end
end
context ".generate_whitelist" do
it "should generate a whitelist for windows/meterpreter/reverse_tcp with default options" do
args = 'multi/handler payload=windows/meterpreter/reverse_tcp lhost=127.0.0.1 E'
cli = Msfcli.new(args.split(' '))
list = cli.generate_whitelist.map { |e| e.to_s }
answer = [
/multi\/handler/,
/stages\/windows\/meterpreter/,
/payloads\/(stagers|stages)\/windows\/.*(reverse_tcp)\.rb$/,
/post\/.+/,
/encoders\/generic\/*/,
/encoders\/.+/,
/nops\/.+/
].map { |e| e.to_s }
list.should eq(answer)
end
it "should generate a whitelist for windows/meterpreter/reverse_tcp with options: encoder='' post='' nop=''" do
args = "multi/handler payload=windows/meterpreter/reverse_tcp lhost=127.0.0.1 encoder='' post='' nop='' E"
cli = Msfcli.new(args.split(' '))
list = cli.generate_whitelist.map { |e| e.to_s }
answer = [
/multi\/handler/,
/stages\/windows\/meterpreter/,
/payloads\/(stagers|stages)\/windows\/.*(reverse_tcp)\.rb$/,
/encoders\/''/,
/post\/''/,
/nops\/''/,
/encoders\/generic\/*/
].map { |e| e.to_s }
list.should eq(answer)
end
it "should generate a whitelist for windows/meterpreter/reverse_tcp with options: encoder= post= nop=" do
args = "multi/handler payload=windows/meterpreter/reverse_tcp lhost=127.0.0.1 encoder= post= nop= E"
cli = Msfcli.new(args.split(' '))
list = cli.generate_whitelist.map { |e| e.to_s }
answer = [
/multi\/handler/,
/stages\/windows\/meterpreter/,
/payloads\/(stagers|stages)\/windows\/.*(reverse_tcp)\.rb$/,
/encoders\/generic\/*/
].map { |e| e.to_s }
list.should eq(answer)
end
end
context ".init_modules" do
it "should have multi/handler module initialized" do
args = "multi/handler payload=windows/meterpreter/reverse_tcp lhost=127.0.0.1 E"
m = ''
stdout = get_stdout {
cli = Msfcli.new(args.split(' '))
m = cli.init_modules
}
m[:module].class.to_s.should =~ /^Msf::Modules::/
end
it "should have my payload windows/meterpreter/reverse_tcp initialized" do
args = "multi/handler payload=windows/meterpreter/reverse_tcp lhost=127.0.0.1 E"
m = ''
stdout = get_stdout {
cli = Msfcli.new(args.split(' '))
m = cli.init_modules
}
m[:payload].class.to_s.should =~ /<Class:/
end
it "should have my modules initialized with the correct parameters" do
args = "multi/handler payload=windows/meterpreter/reverse_tcp lhost=127.0.0.1 E"
m = ''
stdout = get_stdout {
cli = Msfcli.new(args.split(' '))
m = cli.init_modules
}
m[:module].datastore['lhost'].should eq("127.0.0.1")
end
it "should give me an empty hash as a result of an invalid module name" do
args = "WHATEVER payload=windows/meterpreter/reverse_tcp lhost=127.0.0.1 E"
m = ''
stdout = get_stdout {
cli = Msfcli.new(args.split(' '))
m = cli.init_modules
}
m.should eq({})
end
end
end
end

View File

@ -14,6 +14,10 @@ shared_examples_for 'Msf::Simple::Framework::ModulePaths' do
nil
end
let(:options) do
{}
end
before(:each) do
# create the framework first so that it's initialization's call
# to init_module_paths doesn't get captured.
@ -38,7 +42,8 @@ shared_examples_for 'Msf::Simple::Framework::ModulePaths' do
it 'should add Msf::Config.module_directory to module paths' do
framework.modules.should_receive(:add_module_path).with(
module_directory
module_directory,
options
)
init_module_paths
@ -54,7 +59,8 @@ shared_examples_for 'Msf::Simple::Framework::ModulePaths' do
it 'should add Msf::Config.user_module_directory to module paths' do
framework.modules.should_receive(:add_module_path).with(
user_module_directory
user_module_directory,
options
)
init_module_paths
@ -82,7 +88,7 @@ shared_examples_for 'Msf::Simple::Framework::ModulePaths' do
it 'should add each module path' do
module_paths.each do |module_path|
framework.modules.should_receive(:add_module_path).with(module_path)
framework.modules.should_receive(:add_module_path).with(module_path, options)
end
init_module_paths