Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rapid7
GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/msf/ui/console/command_dispatcher/exploit.rb
19715 views
1
# -*- coding: binary -*-
2
module Msf
3
module Ui
4
module Console
5
module CommandDispatcher
6
7
###
8
#
9
# Exploit module command dispatcher.
10
#
11
###
12
class Exploit
13
14
include Msf::Ui::Console::ModuleCommandDispatcher
15
include Msf::Ui::Console::ModuleArgumentParsing
16
include Msf::Ui::Console::ModuleOptionTabCompletion
17
18
#
19
# Returns the hash of exploit module specific commands.
20
#
21
def commands
22
super.update({
23
"exploit" => "Launch an exploit attempt",
24
"rcheck" => "Reloads the module and checks if the target is vulnerable",
25
"rexploit" => "Reloads the module and launches an exploit attempt",
26
"run" => "Alias for exploit",
27
"recheck" => "Alias for rcheck",
28
"rerun" => "Alias for rexploit",
29
"reload" => "Just reloads the module"
30
})
31
end
32
33
#
34
# Returns the name of the command dispatcher.
35
#
36
def name
37
"Exploit"
38
end
39
40
#
41
# Launches an exploitation single attempt.
42
#
43
def exploit_single(mod, opts, &block)
44
begin
45
session = mod.exploit_simple(opts, &block)
46
rescue ::Interrupt
47
raise $!
48
rescue ::Msf::OptionValidateError => e
49
::Msf::Ui::Formatter::OptionValidateError.print_error(mod, e)
50
rescue ::Exception => e
51
print_error("Exploit exception (#{mod.refname}): #{e.class} #{e}")
52
if e.class.to_s != 'Msf::OptionValidateError'
53
print_error("Call stack:")
54
e.backtrace.each do |line|
55
break if line =~ /lib.msf.base.simple/
56
print_error(" #{line}")
57
end
58
end
59
end
60
61
return session
62
end
63
64
#
65
# Tab completion for the run command
66
#
67
def cmd_run_tabs(str, words)
68
fmt = {
69
'-e' => [ framework.encoders.module_refnames ],
70
'-f' => [ nil ],
71
'-h' => [ nil ],
72
'-j' => [ nil ],
73
'-J' => [ nil ],
74
'-n' => [ framework.nops.module_refnames ],
75
'-o' => [ true ],
76
'-p' => [ framework.payloads.module_refnames ],
77
'-r' => [ nil ],
78
'-t' => [ true ],
79
'-z' => [ nil ]
80
}
81
flags = tab_complete_generic(fmt, str, words)
82
options = tab_complete_option(active_module, str, words)
83
flags + options
84
end
85
86
#
87
# Tab completion for the exploit command
88
#
89
alias cmd_exploit_tabs cmd_run_tabs
90
91
#
92
# Launches exploitation attempts.
93
#
94
def cmd_exploit(*args, opts: {})
95
if (args.include?('-r') || args.include?('--reload-libs')) && !opts[:previously_reloaded]
96
driver.run_single('reload_lib -a')
97
end
98
99
return false unless (args = parse_exploit_opts(args))
100
101
any_session = false
102
force = args[:force] || false
103
104
minrank = RankingName.invert[framework.datastore['MinimumRank']] || 0
105
if minrank > mod.rank
106
if force
107
print_status("Forcing #{mod.refname} to run despite MinimumRank '#{framework.datastore['MinimumRank']}'")
108
ilog("Forcing #{mod.refname} to run despite MinimumRank '#{framework.datastore['MinimumRank']}'", 'core')
109
else
110
print_error("This exploit is below the minimum rank, '#{framework.datastore['MinimumRank']}'.")
111
print_error("If you really want to run it, do 'exploit -f' or")
112
print_error("setg MinimumRank to something lower ('manual' is")
113
print_error("the lowest and would allow running all exploits).")
114
return
115
end
116
end
117
118
mod_with_opts = mod.replicant
119
mod_with_opts.datastore.import_options_from_hash(args[:datastore_options])
120
rhosts = mod_with_opts.datastore['RHOSTS']
121
has_rhosts_option = mod.options.include?('RHOSTS') ||
122
mod.options.include?('RHOST') ||
123
mod.options.include?('rhost') ||
124
mod.options.include?('rhosts')
125
126
opts = {
127
'Action' => args[:action],
128
'Encoder' => args[:encoder] || mod_with_opts.datastore['ENCODER'],
129
'Payload' => args[:payload] || mod_with_opts.datastore['PAYLOAD'],
130
'Target' => args[:target] || mod_with_opts.datastore['TARGET'],
131
'Nop' => args[:nop] || mod_with_opts.datastore['NOP'],
132
'LocalInput' => driver.input,
133
'LocalOutput' => driver.output,
134
'RunAsJob' => args[:jobify] || mod_with_opts.passive?,
135
'Background' => args[:background] || false,
136
'Force' => force,
137
'Quiet' => args[:quiet] || false
138
}
139
140
driver.run_single('reload_lib -a') if args[:reload_libs]
141
142
if rhosts && has_rhosts_option && !mod.class.included_modules.include?(Msf::Auxiliary::MultipleTargetHosts)
143
rhosts_walker = Msf::RhostsWalker.new(rhosts, mod_with_opts.datastore)
144
rhosts_walker_count = rhosts_walker.count
145
rhosts_walker = rhosts_walker.to_enum
146
end
147
148
run_mod = nil
149
150
# For multiple targets exploit attempts.
151
if rhosts_walker && rhosts_walker_count > 1
152
opts[:multi] = true
153
rhosts_walker.with_index do |datastore, index|
154
nmod = mod_with_opts.replicant
155
nmod.datastore.merge!(datastore)
156
# If rhost is the last target, let exploit handler stop.
157
is_last_target = (index + 1) == rhosts_walker_count
158
opts["multi"] = false if is_last_target
159
# Catch the interrupt exception to stop the whole module during exploit
160
begin
161
print_status("Exploiting target #{datastore['RHOSTS']}")
162
session = exploit_single(nmod, opts) { |mod| run_mod = mod }
163
rescue ::Interrupt
164
print_status("Stopping exploiting current target #{datastore['RHOSTS']}...")
165
print_status("Control-C again to force quit exploiting all targets.")
166
begin
167
Rex.sleep(1)
168
rescue ::Interrupt
169
raise $!
170
end
171
end
172
# If we were given a session, report it.
173
if session
174
print_status("Session #{session.sid} created in the background.")
175
any_session = true
176
end
177
end
178
# For single target or no rhosts option.
179
else
180
nmod = mod_with_opts.replicant
181
if rhosts_walker && rhosts_walker_count == 1
182
nmod.datastore.merge!(rhosts_walker.next)
183
end
184
session = exploit_single(nmod, opts) { |mod| run_mod = mod }
185
# If we were given a session, let's see what we can do with it
186
if session
187
any_session = true
188
if !opts['Background'] && session.interactive?
189
# If we aren't told to run in the background and the session can be
190
# interacted with, start interacting with it by issuing the session
191
# interaction command.
192
print_line
193
194
driver.run_single("sessions -q -i #{session.sid}")
195
# Otherwise, log that we created a session
196
else
197
# Otherwise, log that we created a session
198
print_status("Session #{session.sid} created in the background.")
199
end
200
201
elsif opts['RunAsJob'] && nmod.job_id
202
# Indicate if he exploit as a job, indicate such so the user doesn't
203
# wonder what's up.
204
print_status("Exploit running as background job #{nmod.job_id}.")
205
# Worst case, the exploit ran but we got no session, bummer.
206
end
207
end
208
209
# If we didn't get any session and exploit ended launch.
210
unless any_session || run_mod&.error.is_a?(Msf::OptionValidateError)
211
# If we didn't run a payload handler for this exploit it doesn't
212
# make sense to complain to the user that we didn't get a session
213
unless mod_with_opts.datastore["DisablePayloadHandler"]
214
fail_msg = 'Exploit completed, but no session was created.'
215
print_status(fail_msg)
216
begin
217
framework.events.on_session_fail(fail_msg)
218
rescue ::Exception => e
219
wlog("Exception in on_session_open event handler: #{e.class}: #{e}")
220
wlog("Call Stack\n#{e.backtrace.join("\n")}")
221
end
222
end
223
end
224
end
225
226
alias cmd_run cmd_exploit
227
228
def cmd_exploit_help
229
print_module_run_or_check_usage(command: :run, options: @@exploit_opts)
230
end
231
232
alias cmd_run_help cmd_exploit_help
233
234
#
235
# Reloads an exploit module and checks the target to see if it's
236
# vulnerable.
237
#
238
def cmd_rcheck(*args)
239
opts = {}
240
if args.include?('-r') || args.include?('--reload-libs')
241
driver.run_single('reload_lib -a')
242
opts[:previously_reloaded] = true
243
end
244
245
reload()
246
247
cmd_check(*args, opts: opts)
248
end
249
250
alias cmd_recheck cmd_rcheck
251
252
#
253
# Reloads an exploit module and launches an exploit.
254
#
255
def cmd_rexploit(*args)
256
opts = {}
257
if args.include?('-r') || args.include?('--reload-libs')
258
driver.run_single('reload_lib -a')
259
opts[:previously_reloaded] = true
260
end
261
262
return cmd_rexploit_help if args.include?('-h') || args.include?('--help')
263
264
# Stop existing job and reload the module
265
if reload(true)
266
# Delegate to the exploit command unless the reload failed
267
cmd_exploit(*args, opts: opts)
268
end
269
end
270
271
alias cmd_rerun cmd_rexploit
272
alias cmd_rerun_tabs cmd_run_tabs
273
alias cmd_rexploit_tabs cmd_exploit_tabs
274
275
def cmd_rexploit_help
276
print_module_run_or_check_usage(
277
command: :rexploit,
278
description: 'Reloads a module, stopping any associated job, and launches an exploitation attempt.',
279
options: @@exploit_opts
280
)
281
end
282
283
alias cmd_rerun_help cmd_rexploit_help
284
285
# Select a reasonable default payload and minimally configure it
286
# @param [Msf::Module] mod
287
def self.choose_payload(mod)
288
Msf::Payload.choose_payload(mod)
289
end
290
291
end
292
293
end end end end
294
295