CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/tools/modules/module_reference.rb
Views: 1904
1
#!/usr/bin/env ruby
2
3
##
4
# This module requires Metasploit: https://metasploit.com/download
5
# Current source: https://github.com/rapid7/metasploit-framework
6
##
7
8
#
9
# This script lists each module with its references
10
#
11
12
msfbase = __FILE__
13
msfbase = File.expand_path(File.readlink(msfbase), File.dirname(msfbase)) while File.symlink?(msfbase)
14
15
$:.unshift(File.expand_path(File.join(File.dirname(msfbase), '..', '..', 'lib')))
16
require 'msfenv'
17
18
$:.unshift(ENV['MSF_LOCAL_LIB']) if ENV['MSF_LOCAL_LIB']
19
20
require 'rex'
21
require 'uri'
22
23
# See lib/msf/core/module/reference.rb
24
# We gsub '#{in_ctx_val}' with the actual value
25
def types
26
{
27
'ALL' => '',
28
'CVE' => 'https://nvd.nist.gov/vuln/detail/CVE-#{in_ctx_val}',
29
'CWE' => 'http://cwe.mitre.org/data/definitions/#{in_ctx_val}.html',
30
'BID' => 'http://www.securityfocus.com/bid/#{in_ctx_val}',
31
'MSB' => 'https://docs.microsoft.com/en-us/security-updates/SecurityBulletins/#{in_ctx_val}',
32
'EDB' => 'http://www.exploit-db.com/exploits/#{in_ctx_val}',
33
'US-CERT-VU' => 'http://www.kb.cert.org/vuls/id/#{in_ctx_val}',
34
'ZDI' => 'http://www.zerodayinitiative.com/advisories/ZDI-#{in_ctx_val}',
35
'WPVDB' => 'https://wpscan.com/vulnerability/#{in_ctx_val}',
36
'PACKETSTORM' => 'https://packetstormsecurity.com/files/#{in_ctx_val}',
37
'URL' => '#{in_ctx_val}'
38
}
39
end
40
41
STATUS_ALIVE = 'Alive'
42
STATUS_DOWN = 'Down'
43
STATUS_REDIRECT = 'Redirect'
44
STATUS_UNSUPPORTED = 'Unsupported'
45
46
sort = 0
47
filter = 'All'
48
filters = ['all', 'exploit', 'payload', 'post', 'nop', 'encoder', 'auxiliary']
49
type = 'ALL'
50
match = nil
51
check = false
52
save = nil
53
is_url_alive_cache = {}
54
http_timeout = 20
55
$verbose = false
56
57
opts = Rex::Parser::Arguments.new(
58
'-h' => [ false, 'Help menu.' ],
59
'-c' => [ false, 'Check Reference status'],
60
'-s' => [ false, 'Sort by Reference instead of Module Type.'],
61
'-r' => [ false, 'Reverse Sort'],
62
'-f' => [ true, 'Filter based on Module Type [All,Exploit,Payload,Post,NOP,Encoder,Auxiliary] (Default = ALL).'],
63
'-t' => [ true, "Type of Reference to sort by #{types.keys}"],
64
'-x' => [ true, 'String or RegEx to try and match against the Reference Field'],
65
'-o' => [ true, 'Save the results to a file'],
66
'--csv' => [ false, 'Save the results file in CSV format'],
67
'-i' => [ true, 'Set an HTTP timeout'],
68
'-v' => [ false, 'Verbose']
69
)
70
71
flags = []
72
73
opts.parse(ARGV) do |opt, _idx, val|
74
case opt
75
when '-h'
76
puts "\nMetasploit Script for Displaying Module Reference information."
77
puts '=========================================================='
78
puts opts.usage
79
exit
80
when '-c'
81
flags << 'URI Check: Yes'
82
check = true
83
when '-s'
84
flags << 'Order: Sorting by Reference'
85
sort = 1
86
when '-r'
87
flags << 'Order: Reverse Sorting'
88
sort = 2
89
when '-f'
90
unless filters.include?(val.downcase)
91
puts "Invalid Filter Supplied: #{val}"
92
puts "Please use one of these: #{filters.map { |f| f.capitalize }.join(', ')}"
93
exit
94
end
95
flags << "Module Filter: #{val}"
96
filter = val
97
when '-t'
98
val = (val || '').upcase
99
unless types.has_key?(val)
100
puts "Invalid Type Supplied: #{val}"
101
puts "Please use one of these: #{types.keys.inspect}"
102
exit
103
end
104
type = val
105
when '-i'
106
http_timeout = /^\d+/ === val ? val.to_i : 20
107
when '-v'
108
$verbose = true
109
when '-x'
110
flags << "Regex: #{val}"
111
match = Regexp.new(val)
112
when '-o'
113
flags << 'Output to file: Yes'
114
save = val
115
when '--csv'
116
flags << 'Output as CSV'
117
$csv = true
118
end
119
end
120
121
if $csv && save.nil?
122
abort('Error: -o flag required when using CSV output')
123
end
124
125
flags << "Type: #{type}"
126
127
puts flags * ' | '
128
129
def get_ipv4_addr(hostname)
130
Rex::Socket.getaddresses(hostname, false)[0]
131
end
132
133
def vprint_debug(msg = '')
134
print_debug(msg) if $verbose
135
end
136
137
def print_debug(msg = '')
138
warn "[*] #{msg}"
139
end
140
141
def is_url_alive(uri, http_timeout, cache)
142
if cache.key? uri.to_s
143
print_debug("Cached: #{uri} -> #{cache[uri]}")
144
return cache[uri.to_s]
145
end
146
print_debug("Checking: #{uri}")
147
148
begin
149
uri = URI(uri)
150
rhost = get_ipv4_addr(uri.host)
151
rescue SocketError, URI::InvalidURIError => e
152
vprint_debug("#{e.message} in #is_url_alive")
153
return STATUS_DOWN
154
end
155
156
rport = uri.port || 80
157
path = uri.path.blank? ? '/' : uri.path
158
vhost = rport == 80 ? uri.host : "#{uri.host}:#{rport}"
159
if uri.scheme == 'https'
160
cli = ::Rex::Proto::Http::Client.new(rhost, 443, {}, true)
161
else
162
cli = ::Rex::Proto::Http::Client.new(rhost, rport)
163
end
164
165
begin
166
cli.connect(http_timeout)
167
req = cli.request_raw('uri' => path, 'vhost' => vhost)
168
res = cli.send_recv(req, http_timeout)
169
rescue Errno::ECONNRESET, Rex::ConnectionError, Rex::ConnectionRefused, Rex::HostUnreachable, Rex::ConnectionTimeout, Rex::UnsupportedProtocol, ::Timeout::Error, Errno::ETIMEDOUT, ::Exception => e
170
vprint_debug("#{e.message} for #{uri}")
171
cache[uri.to_s] = STATUS_DOWN
172
return STATUS_DOWN
173
ensure
174
cli.close
175
end
176
177
if !res.nil? && res.code.to_s =~ %r{3\d\d}
178
if res.headers['Location']
179
vprint_debug("Redirect: #{uri} redirected to #{res.headers['Location']}")
180
else
181
print_error("Error: Couldn't find redirect location for #{uri}")
182
end
183
cache[uri.to_s] = STATUS_REDIRECT
184
return STATUS_REDIRECT
185
elsif res.nil? || res.body =~ %r{<title>.*not found</title>}i || !res.code.to_s =~ %r{2\d\d}
186
vprint_debug("Down: #{uri} returned a not-found response")
187
cache[uri.to_s] = STATUS_DOWN
188
return STATUS_DOWN
189
end
190
191
vprint_debug("Good: #{uri}")
192
193
cache[uri.to_s] = STATUS_ALIVE
194
STATUS_ALIVE
195
end
196
197
def save_results(path, results)
198
File.open(path, 'wb') do |f|
199
f.write(results)
200
end
201
puts "Results saved to: #{path}"
202
rescue Exception => e
203
puts "Failed to save the file: #{e.message}"
204
end
205
206
# Always disable the database (we never need it just to list module
207
# information).
208
framework_opts = { 'DisableDatabase' => true }
209
210
# If the user only wants a particular module type, no need to load the others
211
if filter.downcase != 'all'
212
framework_opts[:module_types] = [ filter.downcase ]
213
end
214
215
# Initialize the simplified framework instance.
216
$framework = Msf::Simple::Framework.create(framework_opts)
217
218
if check
219
columns = [ 'Module', 'Status', 'Reference' ]
220
else
221
columns = [ 'Module', 'Reference' ]
222
end
223
224
tbl = Rex::Text::Table.new(
225
'Header' => 'Module References',
226
'Indent' => 2,
227
'Columns' => columns
228
)
229
230
bad_refs_count = 0
231
232
$framework.modules.each do |name, mod|
233
if mod.nil?
234
elog("module_reference.rb is unable to load #{name}")
235
next
236
end
237
238
next if match and !(name =~ match)
239
240
x = mod.new
241
x.references.each do |r|
242
ctx_id = r.ctx_id.upcase
243
ctx_val = r.ctx_val
244
next unless type == 'ALL' || type == ctx_id
245
246
if check
247
if types.has_key?(ctx_id)
248
if ctx_id == 'MSB'
249
year = ctx_val[2..3]
250
century = year[0] == '9' ? '19' : '20'
251
new_ctx_val = "#{century}#{year}/#{ctx_val}"
252
uri = types[r.ctx_id.upcase].gsub(/\#{in_ctx_val}/, new_ctx_val)
253
else
254
uri = types[r.ctx_id.upcase].gsub(/\#{in_ctx_val}/, r.ctx_val.to_s)
255
end
256
257
status = is_url_alive(uri, http_timeout, is_url_alive_cache)
258
bad_refs_count += 1 if status == STATUS_DOWN
259
else
260
# The reference ID isn't supported so we don't know how to check this
261
bad_refs_count += 1
262
status = STATUS_UNSUPPORTED
263
end
264
end
265
266
ref = "#{r.ctx_id}-#{r.ctx_val}"
267
new_column = []
268
new_column << x.fullname
269
new_column << status if check
270
new_column << ref
271
tbl << new_column
272
end
273
end
274
275
if sort == 1
276
tbl.sort_rows(1)
277
end
278
279
if sort == 2
280
tbl.sort_rows(1)
281
tbl.rows.reverse
282
end
283
284
puts
285
puts tbl.to_s
286
puts
287
288
puts "Number of bad references found: #{bad_refs_count}" if check
289
save_results(save, $csv.nil? ? tbl.to_s : tbl.to_csv) if save
290
291