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/lib/msf/ui/console/command_dispatcher/exploit.rb
Views: 11784
# -*- coding: binary -*-1module Msf2module Ui3module Console4module CommandDispatcher56###7#8# Exploit module command dispatcher.9#10###11class Exploit1213include Msf::Ui::Console::ModuleCommandDispatcher14include Msf::Ui::Console::ModuleArgumentParsing15include Msf::Ui::Console::ModuleOptionTabCompletion1617#18# Returns the hash of exploit module specific commands.19#20def commands21super.update({22"exploit" => "Launch an exploit attempt",23"rcheck" => "Reloads the module and checks if the target is vulnerable",24"rexploit" => "Reloads the module and launches an exploit attempt",25"run" => "Alias for exploit",26"recheck" => "Alias for rcheck",27"rerun" => "Alias for rexploit",28"reload" => "Just reloads the module"29})30end3132#33# Returns the name of the command dispatcher.34#35def name36"Exploit"37end3839#40# Launches an exploitation single attempt.41#42def exploit_single(mod, opts)43begin44session = mod.exploit_simple(opts)45rescue ::Interrupt46raise $!47rescue ::Msf::OptionValidateError => e48::Msf::Ui::Formatter::OptionValidateError.print_error(mod, e)49rescue ::Exception => e50print_error("Exploit exception (#{mod.refname}): #{e.class} #{e}")51if e.class.to_s != 'Msf::OptionValidateError'52print_error("Call stack:")53e.backtrace.each do |line|54break if line =~ /lib.msf.base.simple/55print_error(" #{line}")56end57end58end5960return session61end6263#64# Tab completion for the run command65#66def cmd_run_tabs(str, words)67fmt = {68'-e' => [ framework.encoders.module_refnames ],69'-f' => [ nil ],70'-h' => [ nil ],71'-j' => [ nil ],72'-J' => [ nil ],73'-n' => [ framework.nops.module_refnames ],74'-o' => [ true ],75'-p' => [ framework.payloads.module_refnames ],76'-r' => [ nil ],77'-t' => [ true ],78'-z' => [ nil ]79}80flags = tab_complete_generic(fmt, str, words)81options = tab_complete_option(active_module, str, words)82flags + options83end8485#86# Tab completion for the exploit command87#88alias cmd_exploit_tabs cmd_run_tabs8990#91# Launches exploitation attempts.92#93def cmd_exploit(*args, opts: {})94if (args.include?('-r') || args.include?('--reload-libs')) && !opts[:previously_reloaded]95driver.run_single('reload_lib -a')96end9798return false unless (args = parse_exploit_opts(args))99100any_session = false101force = args[:force] || false102103minrank = RankingName.invert[framework.datastore['MinimumRank']] || 0104if minrank > mod.rank105if force106print_status("Forcing #{mod.refname} to run despite MinimumRank '#{framework.datastore['MinimumRank']}'")107ilog("Forcing #{mod.refname} to run despite MinimumRank '#{framework.datastore['MinimumRank']}'", 'core')108else109print_error("This exploit is below the minimum rank, '#{framework.datastore['MinimumRank']}'.")110print_error("If you really want to run it, do 'exploit -f' or")111print_error("setg MinimumRank to something lower ('manual' is")112print_error("the lowest and would allow running all exploits).")113return114end115end116117mod_with_opts = mod.replicant118mod_with_opts.datastore.import_options_from_hash(args[:datastore_options])119rhosts = mod_with_opts.datastore['RHOSTS']120has_rhosts_option = mod.options.include?('RHOSTS') ||121mod.options.include?('RHOST') ||122mod.options.include?('rhost') ||123mod.options.include?('rhosts')124125opts = {126'Encoder' => args[:encoder] || mod_with_opts.datastore['ENCODER'],127'Payload' => args[:payload] || mod_with_opts.datastore['PAYLOAD'],128'Target' => args[:target] || mod_with_opts.datastore['TARGET'],129'Nop' => args[:nop] || mod_with_opts.datastore['NOP'],130'LocalInput' => driver.input,131'LocalOutput' => driver.output,132'RunAsJob' => args[:jobify] || mod_with_opts.passive?,133'Background' => args[:background] || false,134'Force' => force,135'Quiet' => args[:quiet] || false136}137138begin139mod_with_opts.validate140rescue ::Msf::OptionValidateError => e141::Msf::Ui::Formatter::OptionValidateError.print_error(mod_with_opts, e)142return false143end144145driver.run_single('reload_lib -a') if args[:reload_libs]146147if rhosts && has_rhosts_option148rhosts_walker = Msf::RhostsWalker.new(rhosts, mod_with_opts.datastore)149rhosts_walker_count = rhosts_walker.count150rhosts_walker = rhosts_walker.to_enum151end152153# For multiple targets exploit attempts.154if rhosts_walker && rhosts_walker_count > 1155opts[:multi] = true156rhosts_walker.with_index do |datastore, index|157nmod = mod_with_opts.replicant158nmod.datastore.merge!(datastore)159# If rhost is the last target, let exploit handler stop.160is_last_target = (index + 1) == rhosts_walker_count161opts["multi"] = false if is_last_target162# Catch the interrupt exception to stop the whole module during exploit163begin164print_status("Exploiting target #{datastore['RHOSTS']}")165session = exploit_single(nmod, opts)166rescue ::Interrupt167print_status("Stopping exploiting current target #{datastore['RHOSTS']}...")168print_status("Control-C again to force quit exploiting all targets.")169begin170Rex.sleep(1)171rescue ::Interrupt172raise $!173end174end175# If we were given a session, report it.176if session177print_status("Session #{session.sid} created in the background.")178any_session = true179end180end181# For single target or no rhosts option.182else183nmod = mod_with_opts.replicant184if rhosts_walker && rhosts_walker_count == 1185nmod.datastore.merge!(rhosts_walker.next)186end187session = exploit_single(nmod, opts)188# If we were given a session, let's see what we can do with it189if session190any_session = true191if !opts['Background'] && session.interactive?192# If we aren't told to run in the background and the session can be193# interacted with, start interacting with it by issuing the session194# interaction command.195print_line196197driver.run_single("sessions -q -i #{session.sid}")198# Otherwise, log that we created a session199else200# Otherwise, log that we created a session201print_status("Session #{session.sid} created in the background.")202end203204elsif opts['RunAsJob'] && nmod.job_id205# Indicate if he exploit as a job, indicate such so the user doesn't206# wonder what's up.207print_status("Exploit running as background job #{nmod.job_id}.")208# Worst case, the exploit ran but we got no session, bummer.209end210end211212# If we didn't get any session and exploit ended launch.213unless any_session214# If we didn't run a payload handler for this exploit it doesn't215# make sense to complain to the user that we didn't get a session216unless mod_with_opts.datastore["DisablePayloadHandler"]217fail_msg = 'Exploit completed, but no session was created.'218print_status(fail_msg)219begin220framework.events.on_session_fail(fail_msg)221rescue ::Exception => e222wlog("Exception in on_session_open event handler: #{e.class}: #{e}")223wlog("Call Stack\n#{e.backtrace.join("\n")}")224end225end226end227end228229alias cmd_run cmd_exploit230231def cmd_exploit_help232print_module_run_or_check_usage(command: :run, options: @@exploit_opts)233end234235alias cmd_run_help cmd_exploit_help236237#238# Reloads an exploit module and checks the target to see if it's239# vulnerable.240#241def cmd_rcheck(*args)242opts = {}243if args.include?('-r') || args.include?('--reload-libs')244driver.run_single('reload_lib -a')245opts[:previously_reloaded] = true246end247248reload()249250cmd_check(*args, opts: opts)251end252253alias cmd_recheck cmd_rcheck254255#256# Reloads an exploit module and launches an exploit.257#258def cmd_rexploit(*args)259opts = {}260if args.include?('-r') || args.include?('--reload-libs')261driver.run_single('reload_lib -a')262opts[:previously_reloaded] = true263end264265return cmd_rexploit_help if args.include?('-h') || args.include?('--help')266267# Stop existing job and reload the module268if reload(true)269# Delegate to the exploit command unless the reload failed270cmd_exploit(*args, opts: opts)271end272end273274alias cmd_rerun cmd_rexploit275alias cmd_rerun_tabs cmd_run_tabs276alias cmd_rexploit_tabs cmd_exploit_tabs277278def cmd_rexploit_help279print_module_run_or_check_usage(280command: :rexploit,281description: 'Reloads a module, stopping any associated job, and launches an exploitation attempt.',282options: @@exploit_opts283)284end285286alias cmd_rerun_help cmd_rexploit_help287288# Select a reasonable default payload and minimally configure it289# @param [Msf::Module] mod290def self.choose_payload(mod)291Msf::Payload.choose_payload(mod)292end293294end295296end end end end297298299