Path: blob/master/tools/modules/module_reference.rb
56016 views
#!/usr/bin/env ruby12##3# This module requires Metasploit: https://metasploit.com/download4# Current source: https://github.com/rapid7/metasploit-framework5##67#8# This script lists each module with its references9#1011msfbase = __FILE__12msfbase = File.expand_path(File.readlink(msfbase), File.dirname(msfbase)) while File.symlink?(msfbase)1314$:.unshift(File.expand_path(File.join(File.dirname(msfbase), '..', '..', 'lib')))15require 'msfenv'1617$:.unshift(ENV['MSF_LOCAL_LIB']) if ENV['MSF_LOCAL_LIB']1819require 'rex'20require 'uri'2122# See lib/msf/core/module/reference.rb23# We gsub '#{in_ctx_val}' with the actual value24def types25{26'ALL' => '',27'CVE' => 'https://nvd.nist.gov/vuln/detail/CVE-#{in_ctx_val}',28'CWE' => 'http://cwe.mitre.org/data/definitions/#{in_ctx_val}.html',29'BID' => 'http://www.securityfocus.com/bid/#{in_ctx_val}',30'MSB' => 'https://docs.microsoft.com/en-us/security-updates/SecurityBulletins/#{in_ctx_val}',31'EDB' => 'http://www.exploit-db.com/exploits/#{in_ctx_val}',32'US-CERT-VU' => 'http://www.kb.cert.org/vuls/id/#{in_ctx_val}',33'ZDI' => 'http://www.zerodayinitiative.com/advisories/ZDI-#{in_ctx_val}',34'WPVDB' => 'https://wpscan.com/vulnerability/#{in_ctx_val}',35'PACKETSTORM' => 'https://packetstormsecurity.com/files/#{in_ctx_val}',36'GHSA' => 'https://github.com/advisories/#{in_ctx_val}',37'OSV' => 'https://osv.dev/vulnerability/#{in_ctx_val}',38'URL' => '#{in_ctx_val}'39}40end4142STATUS_ALIVE = 'Alive'43STATUS_DOWN = 'Down'44STATUS_REDIRECT = 'Redirect'45STATUS_UNSUPPORTED = 'Unsupported'4647sort = 048filter = 'All'49filters = ['all', 'exploit', 'payload', 'post', 'nop', 'encoder', 'auxiliary']50type = 'ALL'51match = nil52check = false53save = nil54is_url_alive_cache = {}55http_timeout = 2056$verbose = false5758opts = Rex::Parser::Arguments.new(59'-h' => [ false, 'Help menu.' ],60'-c' => [ false, 'Check Reference status'],61'-s' => [ false, 'Sort by Reference instead of Module Type.'],62'-r' => [ false, 'Reverse Sort'],63'-f' => [ true, 'Filter based on Module Type [All,Exploit,Payload,Post,NOP,Encoder,Auxiliary] (Default = ALL).'],64'-t' => [ true, "Type of Reference to sort by #{types.keys}"],65'-x' => [ true, 'String or RegEx to try and match against the Reference Field'],66'-o' => [ true, 'Save the results to a file'],67'--csv' => [ false, 'Save the results file in CSV format'],68'-i' => [ true, 'Set an HTTP timeout'],69'-v' => [ false, 'Verbose']70)7172flags = []7374opts.parse(ARGV) do |opt, _idx, val|75case opt76when '-h'77puts "\nMetasploit Script for Displaying Module Reference information."78puts '=========================================================='79puts opts.usage80exit81when '-c'82flags << 'URI Check: Yes'83check = true84when '-s'85flags << 'Order: Sorting by Reference'86sort = 187when '-r'88flags << 'Order: Reverse Sorting'89sort = 290when '-f'91unless filters.include?(val.downcase)92puts "Invalid Filter Supplied: #{val}"93puts "Please use one of these: #{filters.map { |f| f.capitalize }.join(', ')}"94exit95end96flags << "Module Filter: #{val}"97filter = val98when '-t'99val = (val || '').upcase100unless types.has_key?(val)101puts "Invalid Type Supplied: #{val}"102puts "Please use one of these: #{types.keys.inspect}"103exit104end105type = val106when '-i'107http_timeout = /^\d+/ === val ? val.to_i : 20108when '-v'109$verbose = true110when '-x'111flags << "Regex: #{val}"112match = Regexp.new(val)113when '-o'114flags << 'Output to file: Yes'115save = val116when '--csv'117flags << 'Output as CSV'118$csv = true119end120end121122if $csv && save.nil?123abort('Error: -o flag required when using CSV output')124end125126flags << "Type: #{type}"127128puts flags * ' | '129130def get_ipv4_addr(hostname)131Rex::Socket.getaddresses(hostname, false)[0]132end133134def vprint_debug(msg = '')135print_debug(msg) if $verbose136end137138def print_debug(msg = '')139warn "[*] #{msg}"140end141142def is_url_alive(uri, http_timeout, cache)143if cache.key? uri.to_s144print_debug("Cached: #{uri} -> #{cache[uri]}")145return cache[uri.to_s]146end147print_debug("Checking: #{uri}")148149begin150uri = URI(uri)151rhost = get_ipv4_addr(uri.host)152rescue SocketError, URI::InvalidURIError => e153vprint_debug("#{e.message} in #is_url_alive")154return STATUS_DOWN155end156157rport = uri.port || 80158path = uri.path.blank? ? '/' : uri.path159vhost = rport == 80 ? uri.host : "#{uri.host}:#{rport}"160if uri.scheme == 'https'161cli = ::Rex::Proto::Http::Client.new(rhost, 443, {}, true)162else163cli = ::Rex::Proto::Http::Client.new(rhost, rport)164end165166begin167cli.connect(http_timeout)168req = cli.request_raw('uri' => path, 'vhost' => vhost)169res = cli.send_recv(req, http_timeout)170rescue Errno::ECONNRESET, Rex::ConnectionError, Rex::ConnectionRefused, Rex::HostUnreachable, Rex::ConnectionTimeout, Rex::UnsupportedProtocol, ::Timeout::Error, Errno::ETIMEDOUT, ::Exception => e171vprint_debug("#{e.message} for #{uri}")172cache[uri.to_s] = STATUS_DOWN173return STATUS_DOWN174ensure175cli.close176end177178if !res.nil? && res.code.to_s =~ %r{3\d\d}179if res.headers['Location']180vprint_debug("Redirect: #{uri} redirected to #{res.headers['Location']}")181else182print_error("Error: Couldn't find redirect location for #{uri}")183end184cache[uri.to_s] = STATUS_REDIRECT185return STATUS_REDIRECT186elsif res.nil? || res.body =~ %r{<title>.*not found</title>}i || !res.code.to_s =~ %r{2\d\d}187vprint_debug("Down: #{uri} returned a not-found response")188cache[uri.to_s] = STATUS_DOWN189return STATUS_DOWN190end191192vprint_debug("Good: #{uri}")193194cache[uri.to_s] = STATUS_ALIVE195STATUS_ALIVE196end197198def save_results(path, results)199File.open(path, 'wb') do |f|200f.write(results)201end202puts "Results saved to: #{path}"203rescue Exception => e204puts "Failed to save the file: #{e.message}"205end206207# Always disable the database (we never need it just to list module208# information).209framework_opts = { 'DisableDatabase' => true }210211# If the user only wants a particular module type, no need to load the others212if filter.downcase != 'all'213framework_opts[:module_types] = [ filter.downcase ]214end215216# Initialize the simplified framework instance.217$framework = Msf::Simple::Framework.create(framework_opts)218219if check220columns = [ 'Module', 'Status', 'Reference' ]221else222columns = [ 'Module', 'Reference' ]223end224225tbl = Rex::Text::Table.new(226'Header' => 'Module References',227'Indent' => 2,228'Columns' => columns229)230231bad_refs_count = 0232233$framework.modules.each do |name, mod|234if mod.nil?235elog("module_reference.rb is unable to load #{name}")236next237end238239next if match and !(name =~ match)240241x = mod.new242x.references.each do |r|243ctx_id = r.ctx_id.upcase244ctx_val = r.ctx_val245next unless type == 'ALL' || type == ctx_id246247if check248if types.has_key?(ctx_id)249if ctx_id == 'MSB'250year = ctx_val[2..3]251century = year[0] == '9' ? '19' : '20'252new_ctx_val = "#{century}#{year}/#{ctx_val}"253uri = types[r.ctx_id.upcase].gsub(/\#{in_ctx_val}/, new_ctx_val)254else255uri = types[r.ctx_id.upcase].gsub(/\#{in_ctx_val}/, r.ctx_val.to_s)256end257258status = is_url_alive(uri, http_timeout, is_url_alive_cache)259bad_refs_count += 1 if status == STATUS_DOWN260else261# The reference ID isn't supported so we don't know how to check this262bad_refs_count += 1263status = STATUS_UNSUPPORTED264end265end266267ref = "#{r.ctx_id}-#{r.ctx_val}"268new_column = []269new_column << x.fullname270new_column << status if check271new_column << ref272tbl << new_column273end274end275276if sort == 1277tbl.sort_rows(1)278end279280if sort == 2281tbl.sort_rows(1)282tbl.rows.reverse283end284285puts286puts tbl.to_s287puts288289puts "Number of bad references found: #{bad_refs_count}" if check290save_results(save, $csv.nil? ? tbl.to_s : tbl.to_csv) if save291292293