Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/modules/post/multi/recon/local_exploit_suggester.rb
Views: 11784
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Post67include Msf::Auxiliary::Report89def initialize(info = {})10super(11update_info(12info,13'Name' => 'Multi Recon Local Exploit Suggester',14'Description' => %q{15This module suggests local meterpreter exploits that can be used.1617The exploits are suggested based on the architecture and platform18that the user has a shell opened as well as the available exploits19in meterpreter.2021It's important to note that not all local exploits will be fired.22Exploits are chosen based on these conditions: session type,23platform, architecture, and required default options.24},25'License' => MSF_LICENSE,26'Author' => [ 'sinn3r', 'Mo' ],27'Platform' => all_platforms,28'SessionTypes' => [ 'meterpreter', 'shell' ]29)30)31register_options [32Msf::OptInt.new('SESSION', [ true, 'The session to run this module on' ]),33Msf::OptBool.new('SHOWDESCRIPTION', [true, 'Displays a detailed description for the available exploits', false])34]3536register_advanced_options(37[38Msf::OptBool.new('ValidateArch', [true, 'Validate architecture', true]),39Msf::OptBool.new('ValidatePlatform', [true, 'Validate platform', true]),40Msf::OptBool.new('ValidateMeterpreterCommands', [true, 'Validate Meterpreter commands', false]),41Msf::OptString.new('Colors', [false, 'Valid, Invalid and Ignored colors for module checks (unset to disable)', 'grn/red/blu'])42]43)44end4546def all_platforms47Msf::Module::Platform.subclasses.collect { |c| c.realname.downcase }48end4950def session_arch51# Prefer calling native arch when available, as most LPEs will require this (e.g. x86, x64) as opposed to Java/Python Meterpreter's values (e.g. Java, Python)52session.respond_to?(:native_arch) ? session.native_arch : session.arch53end5455def is_module_arch?(mod)56mod_arch = mod.target.arch || mod.arch57mod_arch.include?(session_arch)58end5960def is_module_wanted?(mod)61mod[:result][:incompatibility_reasons].empty?62end6364def is_session_type?(mod)65# There are some modules that do not define any compatible session types.66# We could assume that means the module can run on all session types,67# Or we could consider that as incorrect module metadata.68mod.session_types.include?(session.type)69end7071def is_module_platform?(mod)72platform_obj = Msf::Module::Platform.find_platform session.platform73return false if mod.target.nil?7475module_platforms = mod.target.platform ? mod.target.platform.platforms : mod.platform.platforms76module_platforms.include? platform_obj77rescue ArgumentError => e78# When not found, find_platform raises an ArgumentError79elog('Could not find a platform', error: e)80return false81end8283def has_required_module_options?(mod)84get_all_missing_module_options(mod).empty?85end8687def get_all_missing_module_options(mod)88missing_options = []89mod.options.each_pair do |option_name, option|90missing_options << option_name if option.required && option.default.nil? && mod.datastore[option_name].blank?91end92missing_options93end9495def valid_incompatibility_reasons(mod, verify_reasons)96# As we can potentially ignore some `reasons` (e.g. accepting arch values which are, on paper, not compatible),97# this keeps track of valid reasons why we will not consider the module that we are evaluating to be valid.98valid_reasons = []99valid_reasons << "Missing required module options (#{get_all_missing_module_options(mod).join('. ')})" unless verify_reasons[:has_required_module_options]100101incompatible_opts = []102incompatible_opts << 'architecture' unless verify_reasons[:is_module_arch]103incompatible_opts << 'platform' unless verify_reasons[:is_module_platform]104incompatible_opts << 'session type' unless verify_reasons[:is_session_type]105valid_reasons << "Not Compatible (#{incompatible_opts.join(', ')})" if incompatible_opts.any?106107valid_reasons << 'Missing/unloadable Meterpreter commands' if verify_reasons[:missing_meterpreter_commands].any?108valid_reasons109end110111def set_module_options(mod)112datastore.each_pair do |k, v|113mod.datastore[k] = v114end115if !mod.datastore['SESSION'] && session.present?116mod.datastore['SESSION'] = session.sid117end118end119120def set_module_target(mod)121session_platform = Msf::Module::Platform.find_platform(session.platform)122target_index = mod.targets.find_index do |target|123# If the target doesn't define its own compatible platforms or architectures, default to the parent (module) values.124target_platforms = target.platform&.platforms || mod.platform.platforms125target_architectures = target.arch || mod.arch126127target_platforms.include?(session_platform) && target_architectures.include?(session_arch)128end129mod.datastore['Target'] = target_index if target_index130end131132def setup133return unless session134135print_status "Collecting local exploits for #{session.session_type}..."136137setup_validation_options138setup_color_options139140# Collects exploits into an array141@local_exploits = []142exploit_refnames = framework.exploits.module_refnames143exploit_refnames.each_with_index do |name, index|144print "%bld%blu[*]%clr Collecting exploit #{index + 1} / #{exploit_refnames.count}\r"145mod = framework.exploits.create name146next unless mod147148set_module_options mod149set_module_target mod150151verify_result = verify_mod(mod)152@local_exploits << { module: mod, result: verify_result } if verify_result[:has_check]153end154end155156def verify_mod(mod)157return { has_check: false } unless mod.is_a?(Msf::Exploit::Local) && mod.has_check?158159result = {160has_check: true,161is_module_platform: (@validate_platform ? is_module_platform?(mod) : true),162is_module_arch: (@validate_arch ? is_module_arch?(mod) : true),163has_required_module_options: has_required_module_options?(mod),164missing_meterpreter_commands: (@validate_meterpreter_commands && session.type == 'meterpreter') ? meterpreter_session_incompatibility_reasons(session) : [],165is_session_type: is_session_type?(mod)166}167result[:incompatibility_reasons] = valid_incompatibility_reasons(mod, result)168result169end170171def setup_validation_options172@validate_arch = datastore['ValidateArch']173@validate_platform = datastore['ValidatePlatform']174@validate_meterpreter_commands = datastore['ValidateMeterpreterCommands']175end176177def setup_color_options178@valid_color, @invalid_color, @ignored_color =179(datastore['Colors'] || '').split('/')180181@valid_color = "%#{@valid_color}" unless @valid_color.blank?182@invalid_color = "%#{@invalid_color}" unless @invalid_color.blank?183@ignored_color = "%#{@ignored_color}" unless @ignored_color.blank?184end185186def show_found_exploits187unless datastore['VERBOSE']188print_status "#{@local_exploits.length} exploit checks are being tried..."189return190end191192vprint_status "The following #{@local_exploits.length} exploit checks are being tried:"193@local_exploits.each do |x|194vprint_status x[:module].fullname195end196end197198def run199runnable_exploits = @local_exploits.select { |mod| is_module_wanted?(mod) }200if runnable_exploits.empty?201print_error 'No suggestions available.'202vprint_line203vprint_session_info204vprint_status unwanted_modules_table(@local_exploits.reject { |mod| is_module_wanted?(mod) })205return206end207208show_found_exploits209results = runnable_exploits.map.with_index do |mod, index|210print "%bld%blu[*]%clr Running check method for exploit #{index + 1} / #{runnable_exploits.count}\r"211begin212checkcode = mod[:module].check213rescue StandardError => e214elog("#Local Exploit Suggester failed with: #{e.class} when using #{mod[:module].shortname}", error: e)215vprint_error "Check with module #{mod[:module].fullname} failed with error #{e.class}"216next { module: mod[:module], errors: ['The check raised an exception.'] }217end218219if checkcode.nil?220vprint_error "Check failed with #{mod[:module].fullname} for unknown reasons"221next { module: mod[:module], errors: ['The check failed for unknown reasons.'] }222end223224# See def is_check_interesting?225unless is_check_interesting? checkcode226vprint_status "#{mod[:module].fullname}: #{checkcode.message}"227next { module: mod[:module], errors: [checkcode.message] }228end229230# Prints the full name and the checkcode message for the exploit231print_good "#{mod[:module].fullname}: #{checkcode.message}"232233# If the datastore option is true, a detailed description will show234if datastore['SHOWDESCRIPTION']235# Formatting for the description text236Rex::Text.wordwrap(Rex::Text.compress(mod[:module].description), 2, 70).split(/\n/).each do |line|237print_line line238end239end240241next { module: mod[:module], checkcode: checkcode.message }242end243244print_line245print_status valid_modules_table(results)246247vprint_line248vprint_session_info249vprint_status unwanted_modules_table(@local_exploits.reject { |mod| is_module_wanted?(mod) })250251report_data = []252results.each do |result|253report_data << [result[:module].fullname, result[:checkcode]] if result[:checkcode]254end255report_note(256host: session.session_host,257type: 'local.suggested_exploits',258data: report_data259)260end261262def valid_modules_table(results)263name_styler = ::Msf::Ui::Console::TablePrint::CustomColorStyler.new264check_styler = ::Msf::Ui::Console::TablePrint::CustomColorStyler.new265266# Split all the results by their checkcode.267# We want the modules that returned a checkcode to be at the top.268checkcode_rows, without_checkcode_rows = results.partition { |result| result[:checkcode] }269rows = (checkcode_rows + without_checkcode_rows).map.with_index do |result, index|270color = result[:checkcode] ? @valid_color : @invalid_color271check_res = result.fetch(:checkcode) { result[:errors].join('. ') }272name_styler.merge!({ result[:module].fullname => color })273check_styler.merge!({ check_res => color })274275[276index + 1,277result[:module].fullname,278result[:checkcode] ? 'Yes' : 'No',279check_res280]281end282283Rex::Text::Table.new(284'Header' => "Valid modules for session #{session.sid}:",285'Indent' => 1,286'Columns' => [ '#', 'Name', 'Potentially Vulnerable?', 'Check Result' ],287'SortIndex' => -1,288'WordWrap' => false, # Don't wordwrap as it messes up coloured output when it is broken up into more than one line289'ColProps' => {290'Name' => {291'Stylers' => [name_styler]292},293'Potentially Vulnerable?' => {294'Stylers' => [::Msf::Ui::Console::TablePrint::CustomColorStyler.new({ 'Yes' => @valid_color, 'No' => @invalid_color })]295},296'Check Result' => {297'Stylers' => [check_styler]298}299},300'Rows' => rows301)302end303304def unwanted_modules_table(unwanted_modules)305arch_styler = ::Msf::Ui::Console::TablePrint::CustomColorStyler.new306platform_styler = ::Msf::Ui::Console::TablePrint::CustomColorStyler.new307session_type_styler = ::Msf::Ui::Console::TablePrint::CustomColorStyler.new308309rows = unwanted_modules.map.with_index do |mod, index|310platforms = mod[:module].target.platform&.platforms&.any? ? mod[:module].target.platform.platforms : mod[:module].platform.platforms311platforms ||= []312arch = mod[:module].target.arch&.any? ? mod[:module].target.arch : mod[:module].arch313arch ||= []314315arch.each do |a|316if a != session_arch317if @validate_arch318color = @invalid_color319else320color = @ignored_color321end322else323color = @valid_color324end325326arch_styler.merge!({ a.to_s => color })327end328329platforms.each do |module_platform|330if module_platform != ::Msf::Module::Platform.find_platform(session.platform)331if @validate_platform332color = @invalid_color333else334color = @ignored_color335end336else337color = @valid_color338end339340platform_styler.merge!({ module_platform.realname => color })341end342343mod[:module].session_types.each do |session_type|344color = session_type == session.type ? @valid_color : @invalid_color345session_type_styler.merge!(session_type.to_s => color)346end347348[349index + 1,350mod[:module].fullname,351mod[:result][:incompatibility_reasons].join('. '),352platforms.map(&:realname).sort.join(', '),353arch.any? ? arch.sort.join(', ') : 'No defined architectures',354mod[:module].session_types.any? ? mod[:module].session_types.sort.join(', ') : 'No defined session types'355]356end357358Rex::Text::Table.new(359'Header' => "Incompatible modules for session #{session.sid}:",360'Indent' => 1,361'Columns' => [ '#', 'Name', 'Reasons', 'Platform', 'Architecture', 'Session Type' ],362'WordWrap' => false,363'ColProps' => {364'Architecture' => {365'Stylers' => [arch_styler]366},367'Platform' => {368'Stylers' => [platform_styler]369},370'Session Type' => {371'Stylers' => [session_type_styler]372}373},374'Rows' => rows375)376end377378def vprint_session_info379vprint_status 'Current Session Info:'380vprint_status "Session Type: #{session.type}"381vprint_status "Architecture: #{session_arch}"382vprint_status "Platform: #{session.platform}"383end384385def is_check_interesting?(checkcode)386[387Msf::Exploit::CheckCode::Vulnerable,388Msf::Exploit::CheckCode::Appears,389Msf::Exploit::CheckCode::Detected390].include? checkcode391end392393def print_status(msg = '')394super(session ? "#{session.session_host} - #{msg}" : msg)395end396397def print_good(msg = '')398super(session ? "#{session.session_host} - #{msg}" : msg)399end400401def print_error(msg = '')402super(session ? "#{session.session_host} - #{msg}" : msg)403end404end405406407