Class: Msf::Ui::Console::CommandDispatcher::Db

Inherits:
Object
  • Object
show all
Includes:
Msf::Ui::Console::CommandDispatcher, Common, Analyze, Common, Klist
Defined in:
lib/msf/ui/console/command_dispatcher/db.rb

Defined Under Namespace

Modules: Analyze, Common, Klist

Constant Summary collapse

DB_CONFIG_PATH =
'framework/database'
@@workspace_opts =
Rex::Parser::Arguments.new(
  [ '-h', '--help' ] => [ false, 'Help banner.'],
  [ '-a', '--add' ] => [ true, 'Add a workspace.', '<name>'],
  [ '-d', '--delete' ] => [ true, 'Delete a workspace.', '<name>'],
  [ '-D', '--delete-all' ] => [ false, 'Delete all workspaces.'],
  [ '-r', '--rename' ] => [ true, 'Rename a workspace.', '<old> <new>'],
  [ '-l', '--list' ] => [ false, 'List workspaces.'],
  [ '-v', '--list-verbose' ] => [ false, 'List workspaces verbosely.'],
  [ '-S', '--search' ] => [ true, 'Search for a workspace.', '<name>']
)
@@hosts_columns =
[ 'address', 'mac', 'name', 'os_name', 'os_flavor', 'os_sp', 'purpose', 'info', 'comments']
@@hosts_opts =
Rex::Parser::Arguments.new(
  [ '-h', '--help' ] => [ false, 'Show this help information' ],
  [ '-a', '--add' ] => [ true, 'Add the hosts instead of searching', '<host>' ],
  [ '-u', '--up' ] => [ false, 'Only show hosts which are up' ],
  [ '-R', '--rhosts' ] => [ false, 'Set RHOSTS from the results of the search' ],
  [ '-S', '--search' ] => [ true, 'Search string to filter by', '<filter>' ],
  [ '-i', '--info' ] => [ true, 'Change the info of a host', '<info>' ],
  [ '-n', '--name' ] => [ true, 'Change the name of a host', '<name>' ],
  [ '-m', '--comment' ] => [ true, 'Change the comment of a host', '<comment>' ],
  [ '-t', '--tag' ] => [ true, 'Add or specify a tag to a range of hosts', '<tag>' ],
  [ '-T', '--delete-tag' ] => [ true, 'Remove a tag from a range of hosts', '<tag>' ],
  [ '-d', '--delete' ] => [ true, 'Delete the hosts instead of searching', '<hosts>' ],
  [ '-o', '--output' ] => [ true, 'Send output to a file in csv format', '<filename>' ],
  [ '-O', '--order' ] => [ true, 'Order rows by specified column number', '<column id>' ],
  [ '-c', '--columns' ] => [ true, 'Only show the given columns (see list below)', '<columns>' ],
  [ '-C', '--columns-until-restart' ] => [ true, 'Only show the given columns until the next restart (see list below)', '<columns>' ],
)
@@services_columns =
[ 'created_at', 'info', 'name', 'port', 'proto', 'state', 'updated_at' ]
@@services_opts =
Rex::Parser::Arguments.new(
  [ '-a', '--add' ] => [ false, 'Add the services instead of searching.' ],
  [ '-d', '--delete' ] => [ false, 'Delete the services instead of searching.' ],
  [ '-U', '--update' ] => [ false, 'Update data for existing service.' ],
  [ '-u', '--up' ] => [ false, 'Only show services which are up.' ],
  [ '-c', '--column' ] => [ true, 'Only show the given columns.', '<col1,col2>' ],
  [ '-p', '--port' ] => [ true, 'Search for a list of ports.', '<ports>' ],
  [ '-r', '--protocol' ] => [ true, 'Protocol type of the service being added [tcp|udp].', '<protocol>' ],
  [ '-s', '--name' ] => [ true, 'Name of the service to add.', '<name>' ],
  [ '-o', '--output' ] => [ true, 'Send output to a file in csv format.', '<filename>' ],
  [ '-O', '--order' ] => [ true, 'Order rows by specified column number.', '<column id>' ],
  [ '-R', '--rhosts' ] => [ false, 'Set RHOSTS from the results of the search.' ],
  [ '-S', '--search' ] => [ true, 'Search string to filter by.', '<filter>' ],
  [ '-h', '--help' ] => [ false, 'Show this help information.' ]
)
@@vulns_opts =
Rex::Parser::Arguments.new(
  [ '-h', '--help' ] => [ false, 'Show this help information.' ],
  [ '-o', '--output' ] => [ true, 'Send output to a file in csv format.', '<filename>' ],
  [ '-p', '--port' ] => [ true, 'List vulns matching this port spec.', '<port>' ],
  [ '-s', '--service' ] => [ true, 'List vulns matching these service names.', '<name>' ],
  [ '-R', '--rhosts' ] => [ false, 'Set RHOSTS from the results of the search.' ],
  [ '-S', '--search' ] => [ true, 'Search string to filter by.', '<filter>' ],
  [ '-i', '--info' ] => [ false, 'Display vuln information.' ],
  [ '-d', '--delete' ] => [ false, 'Delete vulnerabilities. Not officially supported.' ]
)
@@notes_opts =
Rex::Parser::Arguments.new(
  [ '-a', '--add' ] => [ false, 'Add a note to the list of addresses, instead of listing.' ],
  [ '-d', '--delete' ] => [ false, 'Delete the notes instead of searching.' ],
  [ '-h', '--help' ] => [ false, 'Show this help information.' ],
  [ '-n', '--note' ] => [ true, 'Set the data for a new note (only with -a).', '<note>' ],
  [ '-O', '--order' ] => [ true, 'Order rows by specified column number.', '<column id>' ],
  [ '-o', '--output' ] => [ true, 'Save the notes to a csv file.', '<filename>' ],
  [ '-R', '--rhosts' ] => [ false, 'Set RHOSTS from the results of the search.' ],
  [ '-S', '--search' ] => [ true, 'Search string to filter by.', '<filter>' ],
  [ '-t', '--type' ] => [ true, 'Search for a list of types, or set single type for add.', '<type1,type2>' ],
  [ '-u', '--update' ] => [ false, 'Update a note. Not officially supported.' ]
)
@@loot_opts =
Rex::Parser::Arguments.new(
  [ '-a', '--add' ] => [ false, 'Add loot to the list of addresses, instead of listing.' ],
  [ '-d', '--delete' ] => [ false, 'Delete *all* loot matching host and type.' ],
  [ '-f', '--file' ] => [ true, 'File with contents of the loot to add.', '<filename>' ],
  [ '-i', '--info' ] => [ true, 'Info of the loot to add.', '<info>' ],
  [ '-t', '--type' ] => [ true, 'Search for a list of types.', '<type1,type2>' ],
  [ '-h', '--help' ] => [ false, 'Show this help information.' ],
  [ '-S', '--search' ] => [ true, 'Search string to filter by.', '<filter>' ],
  [ '-u', '--update' ] => [ false, 'Update loot. Not officially supported.' ]
)

Instance Attribute Summary

Attributes included from Msf::Ui::Console::CommandDispatcher

#driver

Attributes included from Rex::Ui::Text::DispatcherShell::CommandDispatcher

#shell, #tab_complete_items

Instance Method Summary collapse

Methods included from Klist

#cmd_klist, #cmd_klist_help, #cmd_klist_tabs, #kerberos_ticket_storage

Methods included from Analyze

#cmd_analyze, #cmd_analyze_help, #cmd_analyze_tabs

Methods included from Common

#active?, #each_host_range_chunk

Methods included from Common

#arg_host_range, #arg_port_range, #index_from_list, #set_rhosts_from_addrs, #show_options, #trim_path

Methods included from Msf::Ui::Console::CommandDispatcher

#active_module, #active_module=, #active_session, #active_session=, #build_range_array, #docs_dir, #framework, #initialize, #log_error, #remove_lines

Methods included from Rex::Ui::Text::DispatcherShell::CommandDispatcher

#cmd_help, #cmd_help_help, #cmd_help_tabs, #deprecated_cmd, #deprecated_help, #docs_dir, #help_to_s, included, #initialize, #print, #print_error, #print_good, #print_line, #print_status, #print_warning, #tab_complete_directory, #tab_complete_filenames, #tab_complete_generic, #tab_complete_source_address, #unknown_command, #update_prompt

Instance Method Details

#add_host_tag(rws, tag_name) ⇒ Object



353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 353

def add_host_tag(rws, tag_name)
  if rws == [nil]
    print_error("In order to add a tag, you must provide a range of hosts")
    return
  end

  opts = Hash.new()
  opts[:workspace] = framework.db.workspace
  opts[:tag_name] = tag_name

  rws.each do |rw|
    rw.each do |ip|
      opts[:address] = ip
      unless framework.db.add_host_tag(opts)
        print_error("Host #{ip} could not be found.")
      end
    end
  end
end

#change_host_data(host_ranges, host_data) ⇒ Object

Changes the specified host data

Parameters:

  • host_ranges
    • range of hosts to process

  • host_data
    • hash of host data to be updated



331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 331

def change_host_data(host_ranges, host_data)
  if !host_data || host_data.length != 1
    print_error("A single key-value data hash is required to change the host data")
    return
  end
  attribute = host_data.keys[0]

  if host_ranges == [nil]
    print_error("In order to change the host #{attribute}, you must provide a range of hosts")
    return
  end

  each_host_range_chunk(host_ranges) do |host_search|
    next if host_search && host_search.empty?

    framework.db.hosts(address: host_search).each do |host|
      framework.db.update_host(host_data.merge(id: host.id))
      framework.db.report_note(host: host.address, type: "host.#{attribute}", data: host_data[attribute])
    end
  end
end

#clear_default_dbObject



2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2233

def clear_default_db
  conf = Msf::Config.load
  if conf[DB_CONFIG_PATH] && conf[DB_CONFIG_PATH]['default_db']
    updated_opts = conf[DB_CONFIG_PATH]
    updated_opts.delete('default_db')
    Msf::Config.save(DB_CONFIG_PATH => updated_opts)
    print_line "Cleared the default data service."
  else
    print_line "No default data service was configured."
  end
end

#cmd_db_autopwn(*args) ⇒ Object

:category: Deprecated Commands



1660
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1660

def cmd_db_autopwn(*args); deprecated_cmd; end

#cmd_db_autopwn_helpObject

:category: Deprecated Commands



1647
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1647

def cmd_db_autopwn_help; deprecated_help; end

#cmd_db_connect(*args) ⇒ Object



2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2022

def cmd_db_connect(*args)
  return if not db_check_driver

  opts = {}
  while (arg = args.shift)
    case arg
    when '-h', '--help'
      cmd_db_connect_help
      return
    when '-y', '--yaml'
      opts[:yaml_file] = args.shift
    when '-c', '--cert'
      opts[:cert] = args.shift
    when '-t', '--token'
      opts[:api_token] = args.shift
    when '-l', '--list-services'
      list_saved_data_services
      return
    when '-n', '--name'
      opts[:name] = args.shift
      if opts[:name] =~ /\/|\[|\]/
        print_error "Provided name contains an invalid character. Aborting connection."
        return
      end
    when '--skip-verify'
      opts[:skip_verify] = true
    else
      found_name = ::Msf::DbConnector.data_service_search(name: arg)
      if found_name
        opts = ::Msf::DbConnector.load_db_config(found_name)
      else
        opts[:url] = arg
      end
    end
  end

  if !opts[:url] && !opts[:yaml_file]
    print_error 'A URL or saved data service name is required.'
    print_line
    cmd_db_connect_help
    return
  end

  if opts[:url] =~ /http/
    new_conn_type = 'http'
  else
    new_conn_type = framework.db.driver
  end

  # Currently only able to be connected to one DB at a time
  if framework.db.connection_established?
    # But the http connection still requires a local database to support AR, so we have to allow that
    # Don't allow more than one HTTP service, though
    if new_conn_type != 'http' || framework.db..count >= 2
      print_error('Connection already established. Only one connection is allowed at a time.')
      print_error('Run db_disconnect first if you wish to connect to a different data service.')
      print_line
      print_line 'Current connection information:'
      print_connection_info
      return
    end
  end

  result = Msf::DbConnector.db_connect(framework, opts)
  if result[:error]
    print_error result[:error]
    return
  end

  if result[:result]
    print_status result[:result]
  end
  if framework.db.active
    name = opts[:name]
    if !name || name.empty?
      if found_name
        name = found_name
      elsif result[:data_service_name]
        name = result[:data_service_name]
      else
        name = Rex::Text.rand_text_alphanumeric(8)
      end
    end

    save_db_to_config(framework.db, name)
    @current_data_service = name
  end
end

#cmd_db_connect_helpObject



1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1988

def cmd_db_connect_help
  print_line("   USAGE:")
  print_line("      * Postgres Data Service:")
  print_line("          db_connect <user:[pass]>@<host:[port]>/<database>")
  print_line("        Examples:")
  print_line("          db_connect user@metasploit3")
  print_line("          db_connect user:[email protected]/metasploit3")
  print_line("          db_connect user:[email protected]:1500/metasploit3")
  print_line("          db_connect -y [path/to/database.yml]")
  print_line(" ")
  print_line("      * HTTP Data Service:")
  print_line("          db_connect [options] <http|https>://<host:[port]>")
  print_line("        Examples:")
  print_line("          db_connect http://localhost:8080")
  print_line("          db_connect http://my-super-msf-data.service.com")
  print_line("          db_connect -c ~/cert.pem -t 6a7a74c1a5003802c955ead1bbddd4ab1b05a7f2940b4732d34bfc555bc6e1c5d7611a497b29e8f0 https://localhost:8080")
  print_line("        NOTE: You must be connected to a Postgres data service in order to successfully connect to a HTTP data service.")
  print_line(" ")
  print_line("      Persisting Connections:")
  print_line("        db_connect --name <name to save connection as> [options] <address>")
  print_line("      Examples:")
  print_line("        Saving:     db_connect --name LA-server http://123.123.123.45:1234")
  print_line("        Connecting: db_connect LA-server")
  print_line(" ")
  print_line("   OPTIONS:")
  print_line("       -l,--list-services List the available data services that have been previously saved.")
  print_line("       -y,--yaml          Connect to the data service specified in the provided database.yml file.")
  print_line("       -n,--name          Name used to store the connection. Providing an existing name will overwrite the settings for that connection.")
  print_line("       -c,--cert          Certificate file matching the remote data server's certificate. Needed when using self-signed SSL cert.")
  print_line("       -t,--token         The API token used to authenticate to the remote data service.")
  print_line("       --skip-verify      Skip validating authenticity of server's certificate (NOT RECOMMENDED).")
  print_line("")
end

#cmd_db_disconnect(*args) ⇒ Object



2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2118

def cmd_db_disconnect(*args)
  return if not db_check_driver

  if args[0] == '-h' || args[0] == '--help'
    cmd_db_disconnect_help
    return
  elsif args[0] == '-c' || args[0] == '--clear'
    clear_default_db
    return
  end

  previous_name = framework.db.name
  result = Msf::DbConnector.db_disconnect(framework)

  if result[:error]
    print_error "Unable to disconnect from the data service: #{@current_data_service}"
    print_error result[:error]
  elsif result[:old_data_service_name].nil?
    print_error 'Not currently connected to a data service.'
  else
    print_line "Successfully disconnected from the data service: #{previous_name}."
    @current_data_service = result[:data_service_name]
    if @current_data_service
      print_line "Now connected to: #{@current_data_service}."
    end
  end
end

#cmd_db_disconnect_helpObject



2111
2112
2113
2114
2115
2116
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2111

def cmd_db_disconnect_help
  print_line "Usage:"
  print_line "    db_disconnect              Temporarily disconnects from the currently configured dataservice."
  print_line "    db_disconnect --clear      Clears the default dataservice that msfconsole will use when opened."
  print_line
end

#cmd_db_driver(*args) ⇒ Object

:category: Deprecated Commands

This one deserves a little more explanation than standard deprecation warning, so give the user a better understanding of what’s going on.



1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1668

def cmd_db_driver(*args)
  deprecated_cmd
  print_line
  print_line "Because Metasploit no longer supports databases other than the default"
  print_line "PostgreSQL, there is no longer a need to set the driver. Thus db_driver"
  print_line "is not useful and its functionality has been removed. Usually Metasploit"
  print_line "will already have connected to the database; check db_status to see."
  print_line
  cmd_db_status
end

#cmd_db_driver_helpObject

:category: Deprecated Commands



1649
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1649

def cmd_db_driver_help; deprecated_help; end

#cmd_db_export(*args) ⇒ Object

Export an XML



1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1824

def cmd_db_export(*args)
  return unless active?
::ApplicationRecord.connection_pool.with_connection {

  export_formats = %W{xml pwdump}
  format = 'xml'
  output = nil

  while (arg = args.shift)
    case arg
    when '-h','--help'
      print_line "Usage:"
      print_line "    db_export -f <format> [filename]"
      print_line "    Format can be one of: #{export_formats.join(", ")}"
    when '-f','--format'
      format = args.shift.to_s.downcase
    else
      output = arg
    end
  end

  if not output
    print_error("No output file was specified")
    return
  end

  if not export_formats.include?(format)
    print_error("Unsupported file format: #{format}")
    print_error("Unsupported file format: '#{format}'. Must be one of: #{export_formats.join(", ")}")
    return
  end

  print_status("Starting export of workspace #{framework.db.workspace.name} to #{output} [ #{format} ]...")
  framework.db.run_db_export(output, format)
  print_status("Finished export of workspace #{framework.db.workspace.name} to #{output} [ #{format} ]...")
}
end

#cmd_db_export_helpObject



1815
1816
1817
1818
1819
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1815

def cmd_db_export_help
  # Like db_hosts and db_services, this creates a list of columns, so
  # use its -h
  cmd_db_export("-h")
end

#cmd_db_hosts(*args) ⇒ Object

:category: Deprecated Commands



1652
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1652

def cmd_db_hosts(*args); deprecated_cmd(:hosts, *args); end

#cmd_db_hosts_helpObject

:category: Deprecated Commands



1639
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1639

def cmd_db_hosts_help; deprecated_help(:hosts); end

#cmd_db_import(*args) ⇒ Object

Generic import that automatically detects the file type



1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1729

def cmd_db_import(*args)
  return unless active?
  openvas_cert = false
  openvas_dfn = false
::ApplicationRecord.connection_pool.with_connection {
  if args.include?("-h") || ! (args && args.length > 0)
    cmd_db_import_help
    return
  end
  if args.include?("-dfn")
    openvas_dfn = true
  end
  if args.include?("-cert")
    openvas_cert = true
  end
  options = {:openvas_dfn => openvas_dfn, :openvas_cert => openvas_cert}
  args.each { |glob|
    next if (glob.include?("-cert") || glob.include?("-dfn"))
    files = ::Dir.glob(::File.expand_path(glob))
    if files.empty?
      print_error("No such file #{glob}")
      next
    end
    files.each { |filename|
      if (not ::File.readable?(filename))
        print_error("Could not read file #{filename}")
        next
      end
      begin
        warnings = 0
        framework.db.import_file(:filename => filename, :options => options) do |type,data|
          case type
          when :debug
            print_error("DEBUG: #{data.inspect}")
          when :vuln
            inst = data[1] == 1 ? "instance" : "instances"
            print_status("Importing vulnerability '#{data[0]}' (#{data[1]} #{inst})")
          when :filetype
            print_status("Importing '#{data}' data")
          when :parser
            print_status("Import: Parsing with '#{data}'")
          when :address
            print_status("Importing host #{data}")
          when :service
            print_status("Importing service #{data}")
          when :msf_loot
            print_status("Importing loot #{data}")
          when :msf_task
            print_status("Importing task #{data}")
          when :msf_report
            print_status("Importing report #{data}")
          when :pcap_count
            print_status("Import: #{data} packets processed")
          when :record_count
            print_status("Import: #{data[1]} records processed")
          when :warning
            print_error
            data.split("\n").each do |line|
              print_error(line)
            end
            print_error
            warnings += 1
          end
        end
        print_status("Successfully imported #{filename}")

        print_error("Please note that there were #{warnings} warnings") if warnings > 1
        print_error("Please note that there was one warning") if warnings == 1

      rescue Msf::DBImportError => e
        print_error("Failed to import #{filename}: #{$!}")
        elog("Failed to import #{filename}", error: e)
        dlog("Call stack: #{$@.join("\n")}", LEV_3)
        next
      rescue REXML::ParseException => e
        print_error("Failed to import #{filename} due to malformed XML:")
        print_error("#{e.class}: #{e}")
        elog("Failed to import #{filename}", error: e)
        dlog("Call stack: #{$@.join("\n")}", LEV_3)
        next
      end
    }
  }
}
end

#cmd_db_import_helpObject



1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1683

def cmd_db_import_help
  print_line "Usage: db_import <filename> [file2...]"
  print_line
  print_line "Filenames can be globs like *.xml, or **/*.xml which will search recursively"
  print_line "Currently supported file types include:"
  print_line "    Acunetix"
  print_line "    Amap Log"
  print_line "    Amap Log -m"
  print_line "    Appscan"
  print_line "    Burp Session XML"
  print_line "    Burp Issue XML"
  print_line "    CI"
  print_line "    Foundstone"
  print_line "    FusionVM XML"
  print_line "    Group Policy Preferences Credentials"
  print_line "    IP Address List"
  print_line "    IP360 ASPL"
  print_line "    IP360 XML v3"
  print_line "    Libpcap Packet Capture"
  print_line "    Masscan XML"
  print_line "    Metasploit PWDump Export"
  print_line "    Metasploit XML"
  print_line "    Metasploit Zip Export"
  print_line "    Microsoft Baseline Security Analyzer"
  print_line "    NeXpose Simple XML"
  print_line "    NeXpose XML Report"
  print_line "    Nessus NBE Report"
  print_line "    Nessus XML (v1)"
  print_line "    Nessus XML (v2)"
  print_line "    NetSparker XML"
  print_line "    Nikto XML"
  print_line "    Nmap XML"
  print_line "    OpenVAS Report"
  print_line "    OpenVAS XML (optional arguments -cert -dfn)"
  print_line "    Outpost24 XML"
  print_line "    Qualys Asset XML"
  print_line "    Qualys Scan XML"
  print_line "    Retina XML"
  print_line "    Spiceworks CSV Export"
  print_line "    Wapiti XML"
  print_line
end

#cmd_db_import_tabs(str, words) ⇒ Object



1679
1680
1681
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1679

def cmd_db_import_tabs(str, words)
  tab_complete_filenames(str, words)
end

#cmd_db_nmap(*args) ⇒ Object

Import Nmap data from a file



1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1869

def cmd_db_nmap(*args)
  return unless active?
::ApplicationRecord.connection_pool.with_connection {
  if (args.length == 0)
    print_status("Usage: db_nmap [--save | [--help | -h]] [nmap options]")
    return
  end

  save = false
  arguments = []
  while (arg = args.shift)
    case arg
    when '--save'
      save = true
    when '--help', '-h'
      cmd_db_nmap_help
      return
    else
      arguments << arg
    end
  end

  nmap = find_nmap_path
  unless nmap
    print_error("The nmap executable could not be found")
    return
  end

  fd = Rex::Quickfile.new(['msf-db-nmap-', '.xml'], Msf::Config.local_directory)

  begin
    # When executing native Nmap in Cygwin, expand the Cygwin path to a Win32 path
    if(Rex::Compat.is_cygwin and nmap =~ /cygdrive/)
      # Custom function needed because cygpath breaks on 8.3 dirs
      tout = Rex::Compat.cygwin_to_win32(fd.path)
      arguments.push('-oX', tout)
    else
      arguments.push('-oX', fd.path)
    end

    run_nmap(nmap, arguments)

    framework.db.import_nmap_xml_file(:filename => fd.path)

    print_status("Saved NMAP XML results to #{fd.path}") if save
  ensure
    fd.close
    fd.unlink unless save
  end
}
end

#cmd_db_nmap_helpObject



1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1921

def cmd_db_nmap_help
  nmap = find_nmap_path
  unless nmap
    print_error("The nmap executable could not be found")
    return
  end

  stdout, stderr = Open3.capture3([nmap, 'nmap'], '--help')

  stdout.each_line do |out_line|
    next if out_line.strip.empty?
    print_status(out_line.strip)
  end

  stderr.each_line do |err_line|
    next if err_line.strip.empty?
    print_error(err_line.strip)
  end
end

#cmd_db_nmap_tabs(str, words) ⇒ Object



1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1941

def cmd_db_nmap_tabs(str, words)
  nmap = find_nmap_path
  unless nmap
    return
  end

  stdout, stderr = Open3.capture3([nmap, 'nmap'], '--help')
  tabs = []
  stdout.each_line do |out_line|
    if out_line.strip.starts_with?('-')
      tabs.push(out_line.strip.split(':').first)
    end
  end

  stderr.each_line do |err_line|
    next if err_line.strip.empty?
    print_error(err_line.strip)
  end

  return tabs
end

#cmd_db_notes(*args) ⇒ Object

:category: Deprecated Commands



1654
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1654

def cmd_db_notes(*args); deprecated_cmd(:notes, *args); end

#cmd_db_notes_helpObject

:category: Deprecated Commands



1641
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1641

def cmd_db_notes_help; deprecated_help(:notes); end

#cmd_db_rebuild_cache(*args) ⇒ Object



2146
2147
2148
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2146

def cmd_db_rebuild_cache(*args)
  print_line "This command is deprecated with Metasploit 5"
end

#cmd_db_remove(*args) ⇒ Object



2213
2214
2215
2216
2217
2218
2219
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2213

def cmd_db_remove(*args)
  if args[0] == '-h' || args[0] == '--help' || args[0].nil? || args[0].empty?
    cmd_db_remove_help
    return
  end
  delete_db_from_config(args[0])
end

#cmd_db_remove_helpObject



2206
2207
2208
2209
2210
2211
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2206

def cmd_db_remove_help
  print_line "Usage: db_remove <name>"
  print_line
  print_line "Delete the specified saved data service."
  print_line
end

#cmd_db_save(*args) ⇒ Object



2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2157

def cmd_db_save(*args)
  while (arg = args.shift)
    case arg
      when '-h', '--help'
        cmd_db_save_help
        return
    end
  end

  if !framework.db.active || !@current_data_service
    print_error "Not currently connected to a data service that can be saved."
    return
  end

  begin
    Msf::Config.save(DB_CONFIG_PATH => { 'default_db' => @current_data_service })
    print_line "Successfully saved data service as default: #{@current_data_service}"
  rescue ArgumentError => e
    print_error e.message
  end
end

#cmd_db_save_helpObject



2150
2151
2152
2153
2154
2155
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2150

def cmd_db_save_help
  print_line "Usage: db_save"
  print_line
  print_line "Save the current data service connection as the default to reconnect on startup."
  print_line
end

#cmd_db_services(*args) ⇒ Object

:category: Deprecated Commands



1658
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1658

def cmd_db_services(*args); deprecated_cmd(:services, *args); end

#cmd_db_services_helpObject

:category: Deprecated Commands



1645
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1645

def cmd_db_services_help; deprecated_help(:services); end

#cmd_db_stats(*args) ⇒ Object



749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 749

def cmd_db_stats(*args)
  return unless active?
  print_line "Session Type: #{db_connection_info(framework)}"

  current_workspace = framework.db.workspace
  example_workspaces = ::Mdm::Workspace.order(id: :desc)
  ordered_workspaces = ([current_workspace] + example_workspaces).uniq.sort_by(&:id)

  tbl = Rex::Text::Table.new(
  'Indent'  => 2,
  'Header'  => "Database Stats",
  'Columns' =>
    [
      "IsTarget",
      "ID",
      "Name",
      "Hosts",
      "Services",
      "Services per Host",
      "Vulnerabilities",
      "Vulns per Host",
      "Notes",
      "Creds",
      "Kerberos Cache"
    ],
  'SortIndex' => 1,
  'ColProps' => {
    'IsTarget' => {
      'Stylers' => [Msf::Ui::Console::TablePrint::RowIndicatorStyler.new],
      'ColumnStylers' => [Msf::Ui::Console::TablePrint::OmitColumnHeader.new],
      'Width' => 2
    }
  }
  )

  total_hosts = 0
  total_services = 0
  total_vulns = 0
  total_notes = 0
  total_creds = 0
  total_tickets = 0

  ordered_workspaces.map do |workspace|

    hosts = workspace.hosts.count
    services = workspace.services.count
    vulns = workspace.vulns.count
    notes = workspace.notes.count
    creds = framework.db.creds(workspace: workspace.name).count # workspace.creds.count.to_fs(:delimited) is always 0 for whatever reason
    kerbs = ticket_search([nil], nil, :workspace => workspace).count

    total_hosts += hosts
    total_services += services
    total_vulns += vulns
    total_notes += notes
    total_creds += creds
    total_tickets += kerbs

    tbl << [
      current_workspace.id == workspace.id,
      workspace.id,
      workspace.name,
      hosts.to_fs(:delimited),
      services.to_fs(:delimited),
      hosts > 0 ? (services.to_f / hosts).truncate(2) : 0,
      vulns.to_fs(:delimited),
      hosts > 0 ? (vulns.to_f / hosts).truncate(2) : 0,
      notes.to_fs(:delimited),
      creds.to_fs(:delimited),
      kerbs.to_fs(:delimited)
    ]
  end

  # total row
  tbl << [
    "",
    "Total",
    ordered_workspaces.length.to_fs(:delimited),
    total_hosts.to_fs(:delimited),
    total_services.to_fs(:delimited),
    total_hosts > 0 ? (total_services.to_f / total_hosts).truncate(2) : 0,
    total_vulns,
    total_hosts > 0 ? (total_vulns.to_f / total_hosts).truncate(2) : 0,
    total_notes,
    total_creds.to_fs(:delimited),
    total_tickets.to_fs(:delimited)
  ]

  print_line tbl.to_s
end

#cmd_db_status(*args) ⇒ Object

Is everything working?



1977
1978
1979
1980
1981
1982
1983
1984
1985
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1977

def cmd_db_status(*args)
  return if not db_check_driver

  if framework.db.connection_established?
    print_connection_info
  else
    print_status("#{framework.db.driver} selected, no connection")
  end
end

#cmd_db_vulns(*args) ⇒ Object

:category: Deprecated Commands



1656
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1656

def cmd_db_vulns(*args); deprecated_cmd(:vulns, *args); end

#cmd_db_vulns_helpObject

:category: Deprecated Commands



1643
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1643

def cmd_db_vulns_help; deprecated_help(:vulns); end

#cmd_hosts(*args) ⇒ Object



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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 426

def cmd_hosts(*args)
  return unless active?
  onlyup = false
  set_rhosts = false
  mode = []
  delete_count = 0

  rhosts = []
  host_ranges = []
  search_term = nil

  order_by = nil
  info_data = nil
  name_data = nil
  comment_data = nil
  tag_name = nil

  output = nil
  default_columns = [
      'address',
      'arch',
      'comm',
      'comments',
      'created_at',
      'cred_count',
      'detected_arch',
      'exploit_attempt_count',
      'host_detail_count',
      'info',
      'mac',
      'name',
      'note_count',
      'os_family',
      'os_flavor',
      'os_lang',
      'os_name',
      'os_sp',
      'purpose',
      'scope',
      'service_count',
      'state',
      'updated_at',
      'virtual_host',
      'vuln_count',
      'workspace_id']

  default_columns << 'tags' # Special case
  virtual_columns = [ 'svcs', 'vulns', 'workspace', 'tags' ]

  col_search = @@hosts_columns

  default_columns.delete_if {|v| (v[-2,2] == "id")}
  @@hosts_opts.parse(args) do |opt, idx, val|
    case opt
    when '-h', '--help'
      print_line "Usage: hosts [ options ] [addr1 addr2 ...]"
      print_line
      print @@hosts_opts.usage
      print_line
      print_line "Available columns: #{default_columns.join(", ")}"
      print_line
      return
    when '-a', '--add'
      mode << :add
      arg_host_range(val, host_ranges)
    when '-d', '--delete'
      mode << :delete
      arg_host_range(val, host_ranges)
    when '-u', '--up'
      onlyup = true
    when '-o'
      output = val
      output = ::File.expand_path(output)
    when '-R', '--rhosts'
      set_rhosts = true
    when '-S', '--search'
      search_term = val
    when '-i', '--info'
      mode << :new_info
      info_data = val
    when '-n', '--name'
      mode << :new_name
      name_data = val
    when '-m', '--comment'
      mode << :new_comment
      comment_data = val
    when '-t', '--tag'
      mode << :tag
      tag_name = val
    when '-T', '--delete-tag'
      mode << :delete_tag
      tag_name = val
    when '-c', '-C'
      list = val
      if(!list)
        print_error("Invalid column list")
        return
      end
      col_search = list.strip().split(",")
      col_search.each { |c|
        if not default_columns.include?(c) and not virtual_columns.include?(c)
          all_columns = default_columns + virtual_columns
          print_error("Invalid column list. Possible values are (#{all_columns.join("|")})")
          return
        end
      }
      if opt == '-C'
        @@hosts_columns = col_search
      end
    when '-O'
      if (order_by = val.to_i - 1) < 0
        print_error('Please specify a column number starting from 1')
        return
      end
    else
      # Anything that wasn't an option is a host to search for
      unless (arg_host_range(val, host_ranges))
        return
      end
    end
  end

  if col_search
    col_names = col_search
  else
    col_names = default_columns + virtual_columns
  end

  mode << :search if mode.empty?

  if mode == [:add]
    host_ranges.each do |range|
      range.each do |address|
        host = framework.db.find_or_create_host(:host => address)
        print_status("Time: #{host.created_at} Host: host=#{host.address}")
      end
    end
    return
  end

  cp_hsh = {}
  col_names.map do |col|
    cp_hsh[col] = { 'MaxChar' => 52 }
  end
  # If we got here, we're searching.  Delete implies search
  tbl = Rex::Text::Table.new(
    {
      'Header'  => "Hosts",
      'Columns' => col_names,
      'ColProps' => cp_hsh,
      'SortIndex' => order_by
    })

  # Sentinel value meaning all
  host_ranges.push(nil) if host_ranges.empty?

  case
  when mode == [:new_info]
      change_host_data(host_ranges, info: info_data)
    return
  when mode == [:new_name]
      change_host_data(host_ranges, name: name_data)
    return
  when mode == [:new_comment]
      change_host_data(host_ranges, comments: comment_data)
    return
  when mode == [:tag]
    begin
      add_host_tag(host_ranges, tag_name)
    rescue => e
      if e.message.include?('Validation failed')
        print_error(e.message)
      else
        raise e
      end
    end
    return
  when mode == [:delete_tag]
    begin
      delete_host_tag(host_ranges, tag_name)
    rescue => e
      if e.message.include?('Validation failed')
        print_error(e.message)
      else
        raise e
      end
    end
    return
  end

  matched_host_ids = []
  each_host_range_chunk(host_ranges) do |host_search|
    next if host_search && host_search.empty?

    framework.db.hosts(address: host_search, non_dead: onlyup, search_term: search_term).each do |host|
      matched_host_ids << host.id
      columns = col_names.map do |n|
        # Deal with the special cases
        if virtual_columns.include?(n)
          case n
          when "svcs";      host.service_count
          when "vulns";     host.vuln_count
          when "workspace"; host.workspace.name
          when "tags"
            found_tags = find_host_tags(framework.db.workspace, host.id)
            tag_names = found_tags.map(&:name).join(', ')
            tag_names
          end
        # Otherwise, it's just an attribute
        else
          host[n] || ""
        end
      end

      tbl << columns
      if set_rhosts
        addr = (host.scope.to_s != "" ? host.address + '%' + host.scope : host.address)
        rhosts << addr
      end
    end

    if mode == [:delete]
      result = framework.db.delete_host(ids: matched_host_ids)
      delete_count += result.size
    end
  end

  if output
    print_status("Wrote hosts to #{output}")
    ::File.open(output, "wb") { |ofd|
      ofd.write(tbl.to_csv)
    }
  else
    print_line
    print_line(tbl.to_s)
  end

  # Finally, handle the case where the user wants the resulting list
  # of hosts to go into RHOSTS.
  set_rhosts_from_addrs(rhosts.uniq) if set_rhosts

  print_status("Deleted #{delete_count} hosts") if delete_count > 0
end

#cmd_hosts_helpObject



319
320
321
322
323
324
325
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 319

def cmd_hosts_help
  # This command does some lookups for the list of appropriate column
  # names, so instead of putting all the usage stuff here like other
  # help methods, just use it's "-h" so we don't have to recreating
  # that list
  cmd_hosts("-h")
end

#cmd_hosts_tabs(str, words) ⇒ Object

Tab completion for the hosts command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 300

def cmd_hosts_tabs(str, words)
  if words.length == 1
    return @@hosts_opts.option_keys.select { |opt| opt.start_with?(str) }
  end

  case words[-1]
  when '-c', '--columns', '-C', '--columns-until-restart'
    return @@hosts_columns
  when '-o', '--output'
    return tab_complete_filenames(str, words)
  end

  if @@hosts_opts.arg_required?(words[-1])
    return []
  end

  return @@hosts_opts.option_keys.select { |opt| opt.start_with?(str) }
end

#cmd_loot(*args) ⇒ Object



1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1483

def cmd_loot(*args)
  return unless active?

  mode = :search
  host_ranges = []
  types = nil
  delete_count = 0
  search_term = nil
  file = nil
  name = nil
  info = nil
  filename = nil

  @@loot_opts.parse(args) do |opt, idx, val|
    case opt
    when '-a', '--add'
      mode = :add
    when '-d', '--delete'
      mode = :delete
    when '-f', '--file'
      filename = val
      if(!filename)
        print_error("Can't make loot with no filename")
        return
      end
      if (!File.exist?(filename) or !File.readable?(filename))
        print_error("Can't read file")
        return
      end
    when '-i', '--info'
      info = val
      if(!info)
        print_error("Can't make loot with no info")
        return
      end
    when '-t', '--type'
      typelist = val
      if(!typelist)
        print_error("Invalid type list")
        return
      end
      types = typelist.strip().split(",")
    when '-S', '--search'
      search_term = val
    when '-u', '--update' # TODO: This is currently undocumented because it's not officially supported.
      mode = :update
    when '-h', '--help'
      cmd_loot_help
      return
    else
      # Anything that wasn't an option is a host to search for
      unless (arg_host_range(val, host_ranges))
        return
      end
    end
  end

  tbl = Rex::Text::Table.new({
      'Header'  => "Loot",
      'Columns' => [ 'host', 'service', 'type', 'name', 'content', 'info', 'path' ],
      # For now, don't perform any word wrapping on the loot table as it breaks the workflow of
      # copying paths and pasting them into applications
      'WordWrap' => false,
    })

  # Sentinel value meaning all
  host_ranges.push(nil) if host_ranges.empty?

  if mode == :add
    if host_ranges.compact.empty?
      print_error('Address list required')
      return
    end
    if info.nil?
      print_error("Info required")
      return
    end
    if filename.nil?
      print_error("Loot file required")
      return
    end
    if types.nil? or types.size != 1
      print_error("Exactly one loot type is required")
      return
    end
    type = types.first
    name = File.basename(filename)
    file = File.open(filename, "rb")
    contents = file.read
    host_ranges.each do |range|
      range.each do |host|
        lootfile = framework.db.find_or_create_loot(:type => type, :host => host, :info => info, :data => contents, :path => filename, :name => name)
        print_status("Added loot for #{host} (#{lootfile})")
      end
    end
    return
  end

  matched_loot_ids = []
  loots = []
  if host_ranges.compact.empty?
    loots = loots + framework.db.loots(workspace: framework.db.workspace, search_term: search_term)
  else
    each_host_range_chunk(host_ranges) do |host_search|
      next if host_search && host_search.empty?

      loots = loots + framework.db.loots(workspace: framework.db.workspace, hosts: { address: host_search }, search_term: search_term)
    end
  end

  loots.each do |loot|
    row = []
    # TODO: This is just a temp implementation of update for the time being since it did not exist before.
    # It should be updated to not pass all of the attributes attached to the object, only the ones being updated.
    if mode == :update
      begin
        loot.info = info if info
        if types && types.size > 1
          print_error "May only pass 1 type when performing an update."
          next
        end
        loot.ltype = types.first if types
        framework.db.update_loot(loot.as_json.symbolize_keys)
      rescue => e
        elog "There was an error updating loot with ID #{loot.id}: #{e.message}"
        next
      end
    end
    row.push (loot.host && loot.host.address) ? loot.host.address : ""
    if (loot.service)
      svc = (loot.service.name ? loot.service.name : "#{loot.service.port}/#{loot.service.proto}")
      row.push svc
    else
      row.push ""
    end
    row.push(loot.ltype)
    row.push(loot.name || "")
    row.push(loot.content_type)
    row.push(loot.info || "")
    row.push(loot.path)

    tbl << row
    matched_loot_ids << loot.id
  end

  if (mode == :delete)
    result = framework.db.delete_loot(ids: matched_loot_ids)
    delete_count = result.size
  end

  print_line
  print_line(tbl.to_s)
  print_status("Deleted #{delete_count} loots") if delete_count > 0
end

#cmd_loot_helpObject



1462
1463
1464
1465
1466
1467
1468
1469
1470
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1462

def cmd_loot_help
  print_line "Usage: loot [options]"
  print_line " Info: loot [-h] [addr1 addr2 ...] [-t <type1,type2>]"
  print_line "  Add: loot -f [fname] -i [info] -a [addr1 addr2 ...] -t [type]"
  print_line "  Del: loot -d [addr1 addr2 ...]"
  print_line
  print @@loot_opts.usage
  print_line
end

#cmd_loot_tabs(str, words) ⇒ Object

Tab completion for the loot command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always



1456
1457
1458
1459
1460
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1456

def cmd_loot_tabs(str, words)
  if words.length == 1
    @@loot_opts.option_keys.select { |opt| opt.start_with?(str) }
  end
end

#cmd_notes(*args) ⇒ Object



1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1243

def cmd_notes(*args)
  return unless active?
::ApplicationRecord.connection_pool.with_connection {
  mode = :search
  data = nil
  types = nil
  set_rhosts = false

  host_ranges = []
  rhosts      = []
  search_term = nil
  output_file = nil
  delete_count = 0
  order_by = nil

  @@notes_opts.parse(args) do |opt, idx, val|
    case opt
    when '-a', '--add'
      mode = :add
    when '-d', '--delete'
      mode = :delete
    when '-n', '--note'
      data = val
      if(!data)
        print_error("Can't make a note with no data")
        return
      end
    when '-t', '--type'
      typelist = val
      if(!typelist)
        print_error("Invalid type list")
        return
      end
      types = typelist.strip().split(",")
    when '-R', '--rhosts'
      set_rhosts = true
    when '-S', '--search'
      search_term = val
    when '-o', '--output'
      output_file = val
      output_file = ::File.expand_path(output_file)
    when '-O'
      if (order_by = val.to_i - 1) < 0
        print_error('Please specify a column number starting from 1')
        return
      end
    when '-u', '--update'  # TODO: This is currently undocumented because it's not officially supported.
      mode = :update
    when '-h', '--help'
      cmd_notes_help
      return
    else
      # Anything that wasn't an option is a host to search for
      unless (arg_host_range(val, host_ranges))
        return
      end
    end
  end

  if mode == :add
    if host_ranges.compact.empty?
      print_error("Host address or range required")
      return
    end

    if types.nil? || types.size != 1
      print_error("Exactly one type is required")
      return
    end

    if data.nil?
      print_error("Data required")
      return
    end

    type = types.first
    host_ranges.each { |range|
      range.each { |addr|
        note = framework.db.find_or_create_note(host: addr, type: type, data: data)
        break if not note
        print_status("Time: #{note.created_at} Note: host=#{addr} type=#{note.ntype} data=#{note.data}")
      }
    }
    return
  end

  if mode == :update
    if !types.nil? && types.size != 1
      print_error("Exactly one type is required")
      return
    end

    if types.nil? && data.nil?
      print_error("Update requires data or type")
      return
    end
  end

  note_list = []
  if host_ranges.compact.empty?
    # No host specified - collect all notes
    opts = {search_term: search_term}
    opts[:ntype] = types if mode != :update && types && !types.empty?
    note_list = framework.db.notes(opts)
  else
    # Collect notes of specified hosts
    each_host_range_chunk(host_ranges) do |host_search|
      next if host_search && host_search.empty?

      opts = {hosts: {address: host_search}, workspace: framework.db.workspace, search_term: search_term}
      opts[:ntype] = types if mode != :update && types && !types.empty?
      note_list.concat(framework.db.notes(opts))
    end
  end

  # Now display them
  table = Rex::Text::Table.new(
    'Header'  => 'Notes',
    'Indent'  => 1,
    'Columns' => ['Time', 'Host', 'Service', 'Port', 'Protocol', 'Type', 'Data'],
    'SortIndex' => order_by
  )

  matched_note_ids = []
  note_list.each do |note|
    if mode == :update
      begin
        update_opts = {id: note.id}
        unless types.nil?
          note.ntype = types.first
          update_opts[:ntype] = types.first
        end

        unless data.nil?
          note.data = data
          update_opts[:data] = data
        end

        framework.db.update_note(update_opts)
      rescue => e
        elog "There was an error updating note with ID #{note.id}: #{e.message}"
        next
      end
    end

    matched_note_ids << note.id

    row = []
    row << note.created_at

    if note.host
      host = note.host
      row << host.address
      if set_rhosts
        addr = (host.scope.to_s != "" ? host.address + '%' + host.scope : host.address)
        rhosts << addr
      end
    else
      row << ''
    end

    if note.service
      row << note.service.name || ''
      row << note.service.port || ''
      row << note.service.proto || ''
    else
      row << '' # For the Service field
      row << '' # For the Port field
      row << '' # For the Protocol field
    end

    row << note.ntype
    row << note.data.inspect
    table << row
  end

  if mode == :delete
    result = framework.db.delete_note(ids: matched_note_ids)
    delete_count = result.size
  end

  if output_file
    save_csv_notes(output_file, table)
  else
    print_line
    print_line(table.to_s)
  end

  # Finally, handle the case where the user wants the resulting list
  # of hosts to go into RHOSTS.
  set_rhosts_from_addrs(rhosts.uniq) if set_rhosts

  print_status("Deleted #{delete_count} notes") if delete_count > 0
}
end

#cmd_notes_helpObject



1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1218

def cmd_notes_help
  print_line "Usage: notes [-h] [-t <type1,type2>] [-n <data string>] [-a] [addr range]"
  print_line
  print @@notes_opts.usage
  print_line
  print_line "Examples:"
  print_line "  notes --add -t apps -n 'winzip' 10.1.1.34 10.1.20.41"
  print_line "  notes -t smb.fingerprint 10.1.1.34 10.1.20.41"
  print_line "  notes -S 'nmap.nse.(http|rtsp)'"
  print_line
end

#cmd_notes_tabs(str, words) ⇒ Object

Tab completion for the notes command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always



1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1203

def cmd_notes_tabs(str, words)
  if words.length == 1
    return @@notes_opts.option_keys.select { |opt| opt.start_with?(str) }
  end

  case words[-1]
  when '-O', '--order'
    return []
  when '-o', '--output'
    return tab_complete_filenames(str, words)
  end

  []
end

#cmd_services(*args) ⇒ Object



840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 840

def cmd_services(*args)
  return unless active?
  mode = :search
  onlyup = false
  output_file = nil
  set_rhosts = false
  col_search = ['port', 'proto', 'name', 'state', 'info']

  names = nil
  order_by = nil
  proto = nil
  host_ranges  = []
  port_ranges  = []
  rhosts       = []
  delete_count = 0
  search_term  = nil
  opts         = {}

  @@services_opts.parse(args) do |opt, idx, val|
    case opt
    when '-a', '--add'
      mode = :add
    when '-d', '--delete'
      mode = :delete
    when '-U', '--update'
      mode = :update
    when '-u', '--up'
      onlyup = true
    when '-c'
      list = val
      if(!list)
        print_error("Invalid column list")
        return
      end
      col_search = list.strip().split(",")
      col_search.each { |c|
        if not @@services_columns.include? c
          print_error("Invalid column list. Possible values are (#{@@services_columns.join("|")})")
          return
        end
      }
    when '-p'
      unless (arg_port_range(val, port_ranges, true))
        return
      end
    when '-r'
      proto = val
      if (!proto)
        print_status("Invalid protocol")
        return
      end
      proto = proto.strip
    when '-s'
      namelist = val
      if (!namelist)
        print_error("Invalid name list")
        return
      end
      names = namelist.strip().split(",")
    when '-o'
      output_file = val
      if (!output_file)
        print_error("Invalid output filename")
        return
      end
      output_file = ::File.expand_path(output_file)
    when '-O'
      if (order_by = val.to_i - 1) < 0
        print_error('Please specify a column number starting from 1')
        return
      end
    when '-R', '--rhosts'
      set_rhosts = true
    when '-S', '--search'
      search_term = val
      opts[:search_term] = search_term
    when '-h', '--help'
      cmd_services_help
      return
    else
      # Anything that wasn't an option is a host to search for
      unless (arg_host_range(val, host_ranges))
        return
      end
    end
  end

  ports = port_ranges.flatten.uniq

  if mode == :add
    # Can only deal with one port and one service name at a time
    # right now.  Them's the breaks.
    if ports.length != 1
      print_error("Exactly one port required")
      return
    end
    if host_ranges.empty?
      print_error("Host address or range required")
      return
    end
    host_ranges.each do |range|
      range.each do |addr|
        info = {
            :host => addr,
            :port => ports.first.to_i
        }
        info[:proto] = proto.downcase if proto
        info[:name]  = names.first.downcase if names and names.first

        svc = framework.db.find_or_create_service(info)
        print_status("Time: #{svc.created_at} Service: host=#{svc.host.address} port=#{svc.port} proto=#{svc.proto} name=#{svc.name}")
      end
    end
    return
  end

  # If we got here, we're searching.  Delete implies search
  col_names = @@services_columns
  if col_search
    col_names = col_search
  end
  tbl = Rex::Text::Table.new({
                                 'Header'    => "Services",
                                 'Columns'   => ['host'] + col_names,
                                 'SortIndex' => order_by
                             })

  # Sentinel value meaning all
  host_ranges.push(nil) if host_ranges.empty?
  ports = nil if ports.empty?
  matched_service_ids = []

  each_host_range_chunk(host_ranges) do |host_search|
    next if host_search && host_search.empty?
    opts[:workspace] = framework.db.workspace
    opts[:hosts] = {address: host_search} if !host_search.nil?
    opts[:port] = ports if ports
    framework.db.services(opts).each do |service|

      unless service.state == 'open'
        next if onlyup
      end

      host = service.host
      matched_service_ids << service.id

      if mode == :update
        service.name = names.first if names
        service.proto = proto if proto
        service.port = ports.first if ports
        framework.db.update_service(service.as_json.symbolize_keys)
      end

      columns = [host.address] + col_names.map { |n| service[n].to_s || "" }
      tbl << columns
      if set_rhosts
        addr = (host.scope.to_s != "" ? host.address + '%' + host.scope : host.address )
        rhosts << addr
      end
    end
  end

  if (mode == :delete)
    result = framework.db.delete_service(ids: matched_service_ids)
    delete_count += result.size
  end

  if (output_file == nil)
    print_line(tbl.to_s)
  else
    # create the output file
    ::File.open(output_file, "wb") { |f| f.write(tbl.to_csv) }
    print_status("Wrote services to #{output_file}")
  end

  # Finally, handle the case where the user wants the resulting list
  # of hosts to go into RHOSTS.
  set_rhosts_from_addrs(rhosts.uniq) if set_rhosts

  print_status("Deleted #{delete_count} services") if delete_count > 0

end

#cmd_services_helpObject



697
698
699
700
701
702
703
704
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 697

def cmd_services_help
  print_line "Usage: services [-h] [-u] [-a] [-r <proto>] [-p <port1,port2>] [-s <name1,name2>] [-o <filename>] [addr1 addr2 ...]"
  print_line
  print @@services_opts.usage
  print_line
  print_line "Available columns: #{@@services_columns.join(", ")}"
  print_line
end

#cmd_services_tabs(str, words) ⇒ Object

Tab completion for the services command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always



676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 676

def cmd_services_tabs(str, words)
  if words.length == 1
    return @@services_opts.option_keys.select { |opt| opt.start_with?(str) }
  end

  case words[-1]
  when '-c', '--column'
    return @@services_columns
  when '-O', '--order'
    return []
  when '-o', '--output'
    return tab_complete_filenames(str, words)
  when '-p', '--port'
    return []
  when '-r', '--protocol'
    return []
  end

  []
end

#cmd_vulns(*args) ⇒ Object



1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1063

def cmd_vulns(*args)
  return unless active?

  default_columns = ['Timestamp', 'Host', 'Name', 'References']
  host_ranges = []
  port_ranges = []
  svcs        = []
  rhosts      = []

  search_term = nil
  show_info   = false
  set_rhosts  = false
  output_file = nil
  delete_count = 0

  mode = nil

  @@vulns_opts.parse(args) do |opt, idx, val|
    case opt
    when '-d', '--delete' # TODO: This is currently undocumented because it's not officially supported.
      mode = :delete
    when '-h', '--help'
      cmd_vulns_help
      return
    when '-o', '--output'
      output_file = val
      if output_file
        output_file = File.expand_path(output_file)
      else
        print_error("Invalid output filename")
        return
      end
    when '-p', '--port'
      unless (arg_port_range(val, port_ranges, true))
        return
      end
    when '-s', '--service'
      service = val
      if (!service)
        print_error("Argument required for -s")
        return
      end
      svcs = service.split(/[\s]*,[\s]*/)
    when '-R', '--rhosts'
      set_rhosts = true
    when '-S', '--search'
      search_term = val
    when '-i', '--info'
      show_info = true
    else
      # Anything that wasn't an option is a host to search for
      unless (arg_host_range(val, host_ranges))
        return
      end
    end
  end

  if show_info
    default_columns << 'Information'
  end

  # add sentinel value meaning all if empty
  host_ranges.push(nil) if host_ranges.empty?
  # normalize
  ports = port_ranges.flatten.uniq
  svcs.flatten!
  tbl = Rex::Text::Table.new(
      'Header' => 'Vulnerabilities',
      'Columns' => default_columns
  )

  matched_vuln_ids = []
  vulns = []
  if host_ranges.compact.empty?
    vulns = framework.db.vulns({:search_term => search_term})
  else
    each_host_range_chunk(host_ranges) do |host_search|
      next if host_search && host_search.empty?

      vulns.concat(framework.db.vulns({:hosts => { :address => host_search }, :search_term => search_term }))
    end
  end

  vulns.each do |vuln|
    reflist = vuln.refs.map {|r| r.name}
    if (vuln.service)
      # Skip this one if the user specified a port and it
      # doesn't match.
      next unless ports.empty? or ports.include? vuln.service.port
      # Same for service names
      next unless svcs.empty? or svcs.include?(vuln.service.name)
    else
      # This vuln has no service, so it can't match
      next unless ports.empty? and svcs.empty?
    end

    matched_vuln_ids << vuln.id

    row = []
    row << vuln.created_at
    row << vuln.host.address
    row << vuln.name
    row << reflist.join(',')
    if show_info
      row << vuln.info
    end
    tbl << row

    if set_rhosts
      addr = (vuln.host.scope.to_s != "" ? vuln.host.address + '%' + vuln.host.scope : vuln.host.address)
      rhosts << addr
    end
  end

  if mode == :delete
    result = framework.db.delete_vuln(ids: matched_vuln_ids)
    delete_count = result.size
  end

  if output_file
    File.write(output_file, tbl.to_csv)
    print_status("Wrote vulnerability information to #{output_file}")
  else
    print_line
    print_line(tbl.to_s)
  end

  # Finally, handle the case where the user wants the resulting list
  # of hosts to go into RHOSTS.
  set_rhosts_from_addrs(rhosts.uniq) if set_rhosts

  print_status("Deleted #{delete_count} vulnerabilities") if delete_count > 0
end

#cmd_vulns_helpObject



1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1039

def cmd_vulns_help
  print_line "Print all vulnerabilities in the database"
  print_line
  print_line "Usage: vulns [addr range]"
  print_line
  print @@vulns_opts.usage
  print_line
  print_line "Examples:"
  print_line "  vulns -p 1-65536          # only vulns with associated services"
  print_line "  vulns -p 1-65536 -s http  # identified as http on any port"
  print_line
end

#cmd_vulns_tabs(str, words) ⇒ Object

Tab completion for the vulns command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always



1029
1030
1031
1032
1033
1034
1035
1036
1037
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1029

def cmd_vulns_tabs(str, words)
  if words.length == 1
    return @@vulns_opts.option_keys.select { |opt| opt.start_with?(str) }
  end
  case words[-1]
  when '-o', '--output'
    return tab_complete_filenames(str, words)
  end
end

#cmd_workspace(*args) ⇒ Object



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
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 111

def cmd_workspace(*args)
  return unless active?

  state = :nil

  list = false
  verbose = false
  names = []
  search_term = nil

  @@workspace_opts.parse(args) do |opt, idx, val|
    case opt
    when '-h', '--help'
      cmd_workspace_help
      return
    when '-a', '--add'
      return cmd_workspace_help unless state == :nil

      state = :adding
      names << val if !val.nil?
    when '-d', '--del'
      return cmd_workspace_help unless state == :nil

      state = :deleting
      names << val if !val.nil?
    when '-D', '--delete-all'
      return cmd_workspace_help unless state == :nil

      state = :delete_all
    when '-r', '--rename'
      return cmd_workspace_help unless state == :nil

      state = :renaming
      names << val if !val.nil?
    when '-v', '--verbose'
      verbose = true
    when '-l', '--list'
      list = true
    when '-S', '--search'
      search_term = val
    else
      names << val if !val.nil?
    end
  end

  if state == :adding and names
    # Add workspaces
    wspace = nil
    names.each do |name|
      wspace = framework.db.workspaces(name: name).first
      if wspace
        print_status("Workspace '#{wspace.name}' already existed, switching to it.")
      else
        wspace = framework.db.add_workspace(name)
        print_status("Added workspace: #{wspace.name}")
      end
    end
    framework.db.workspace = wspace
    print_status("Workspace: #{framework.db.workspace.name}")
  elsif state == :deleting and names
    ws_ids_to_delete = []
    starting_ws = framework.db.workspace
    names.uniq.each do |n|
      ws = framework.db.workspaces(name: n).first
      ws_ids_to_delete << ws.id if ws
    end
    if ws_ids_to_delete.count > 0
      deleted = framework.db.delete_workspaces(ids: ws_ids_to_delete)
      process_deleted_workspaces(deleted, starting_ws)
    else
      print_status("No workspaces matching the given name(s) were found.")
    end
  elsif state == :delete_all
    ws_ids_to_delete = []
    starting_ws = framework.db.workspace
    framework.db.workspaces.each do |ws|
      ws_ids_to_delete << ws.id
    end
    deleted = framework.db.delete_workspaces(ids: ws_ids_to_delete)
    process_deleted_workspaces(deleted, starting_ws)
  elsif state == :renaming
    if names.length != 2
      print_error("Wrong number of arguments to rename")
      return
    end

    ws_to_update = framework.db.find_workspace(names.first)
    unless ws_to_update
      print_error("Workspace '#{names.first}' does not exist")
      return
    end
    opts = {
        id: ws_to_update.id,
        name: names.last
    }
    begin
      updated_ws = framework.db.update_workspace(opts)
      if updated_ws
        framework.db.workspace = updated_ws if names.first == framework.db.workspace.name
        print_status("Renamed workspace '#{names.first}' to '#{updated_ws.name}'")
      else
        print_error "There was a problem updating the workspace. Setting to the default workspace."
        framework.db.workspace = framework.db.default_workspace
        return
      end
      if names.first == Msf::DBManager::Workspace::DEFAULT_WORKSPACE_NAME
        print_status("Recreated default workspace")
      end
    rescue => e
      print_error "Failed to rename workspace: #{e.message}"
    end

  elsif !names.empty?
    name = names.last
    # Switch workspace
    workspace = framework.db.find_workspace(name)
    if workspace
      framework.db.workspace = workspace
      print_status("Workspace: #{workspace.name}")
    else
      print_error("Workspace not found: #{name}")
      return
    end
  else
    current_workspace = framework.db.workspace

    unless verbose
      current = nil
      framework.db.workspaces.sort_by {|s| s.name}.each do |s|
        if s.name == current_workspace.name
          current = s.name
        else
          print_line("  #{s.name}")
        end
      end
      print_line("%red* #{current}%clr") unless current.nil?
      return
    end
    col_names = %w{current name hosts services vulns creds loots notes}

    tbl = Rex::Text::Table.new(
      'Header'     => 'Workspaces',
      'Columns'    => col_names,
      'SortIndex'  => -1,
      'SearchTerm' => search_term
    )

    framework.db.workspaces.each do |ws|
      tbl << [
        current_workspace.name == ws.name ? '*' : '',
        ws.name,
        framework.db.hosts(workspace: ws.name).count,
        framework.db.services(workspace: ws.name).count,
        framework.db.vulns(workspace: ws.name).count,
        framework.db.creds(workspace: ws.name).count,
        framework.db.loots(workspace: ws.name).count,
        framework.db.notes(workspace: ws.name).count
      ]
    end

    print_line
    print_line(tbl.to_s)
  end
end

#cmd_workspace_helpObject



104
105
106
107
108
109
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 104

def cmd_workspace_help
  print_line "Usage:"
  print_line "    workspace          List workspaces"
  print_line "    workspace [name]   Switch workspace"
  print_line @@workspace_opts.usage
end

#cmd_workspace_tabs(str, words) ⇒ Object



289
290
291
292
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 289

def cmd_workspace_tabs(str, words)
  return [] unless active?
  framework.db.workspaces.map(&:name) if (words & ['-a','--add']).empty?
end

#commandsObject

Returns the hash of commands supported by this dispatcher.



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
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 35

def commands
  base = {
    "db_connect"       => "Connect to an existing data service",
    "db_disconnect"    => "Disconnect from the current data service",
    "db_status"        => "Show the current data service status",
    "db_save"          => "Save the current data service connection as the default to reconnect on startup",
    "db_remove"        => "Remove the saved data service entry"
  }

  more = {
    "workspace"     => "Switch between database workspaces",
    "hosts"         => "List all hosts in the database",
    "services"      => "List all services in the database",
    "vulns"         => "List all vulnerabilities in the database",
    "notes"         => "List all notes in the database",
    "loot"          => "List all loot in the database",
    "klist"         => "List Kerberos tickets in the database",
    "db_import"     => "Import a scan result file (filetype will be auto-detected)",
    "db_export"     => "Export a file containing the contents of the database",
    "db_nmap"       => "Executes nmap and records the output automatically",
    "db_rebuild_cache" => "Rebuilds the database-stored module cache (deprecated)",
    "analyze"       => "Analyze database information about a specific address or address range",
    "db_stats"         => "Show statistics for the database"
  }

  # Always include commands that only make sense when connected.
  # This avoids the problem of them disappearing unexpectedly if the
  # database dies or times out.  See #1923

  base.merge(more)
end

#db_check_driverObject

Database management



1966
1967
1968
1969
1970
1971
1972
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1966

def db_check_driver
  unless framework.db.driver
    print_error("No database driver installed.")
    return false
  end
  true
end

#db_connection_info(framework) ⇒ Object



724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 724

def db_connection_info(framework)
  unless framework.db.connection_established?
    return "#{framework.db.driver} selected, no connection"
  end

  cdb = ''
  if framework.db.driver == 'http'
    cdb = framework.db.name
  else
    ::ApplicationRecord.connection_pool.with_connection do |conn|
      if conn.respond_to?(:current_database)
        cdb = conn.current_database
      end
    end
  end

  if cdb.empty?
    output = "Connected Database Name could not be extracted. DB Connection type: #{framework.db.driver}."
  else
    output = "Connected to #{cdb}. Connection type: #{framework.db.driver}."
  end

  output
end

#db_find_tools(tools) ⇒ Object



2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2245

def db_find_tools(tools)
  missed  = []
  tools.each do |name|
    if(! Rex::FileUtils.find_full_path(name))
      missed << name
    end
  end
  if(not missed.empty?)
    print_error("This database command requires the following tools to be installed: #{missed.join(", ")}")
    return
  end
  true
end

#delete_db_from_config(db_name) ⇒ Object



2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2221

def delete_db_from_config(db_name)
  conf = Msf::Config.load
  db_path = "#{DB_CONFIG_PATH}/#{db_name}"
  if conf[db_path]
    clear_default_db if conf[DB_CONFIG_PATH]['default_db'] && conf[DB_CONFIG_PATH]['default_db'] == db_name
    Msf::Config.delete_group(db_path)
    print_line "Successfully deleted data service: #{db_name}"
  else
    print_line "Unable to locate saved data service with name #{db_name}."
  end
end

#delete_host_tag(rws, tag_name) ⇒ Object



381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 381

def delete_host_tag(rws, tag_name)
  opts = Hash.new()
  opts[:workspace] = framework.db.workspace
  opts[:tag_name] = tag_name

  # This will be the case if no IP was passed in, and we are just trying to delete all
  # instances of a given tag within the database.
  if rws == [nil]
    wspace = Msf::Util::DBManager.process_opts_workspace(opts, framework)
    wspace.hosts.each do |host|
      opts[:address] = host.address
      framework.db.delete_host_tag(opts)
    end
  else
    rws.each do |rw|
      rw.each do |ip|
        opts[:address] = ip
        unless framework.db.delete_host_tag(opts)
          print_error("Host #{ip} could not be found.")
        end
      end
    end
  end
end

#deprecated_commandsObject



67
68
69
70
71
72
73
74
75
76
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 67

def deprecated_commands
  [
    "db_autopwn",
    "db_driver",
    "db_hosts",
    "db_notes",
    "db_services",
    "db_vulns",
  ]
end

#find_host_tags(workspace, host_id) ⇒ Object



373
374
375
376
377
378
379
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 373

def find_host_tags(workspace, host_id)
  opts = Hash.new()
  opts[:workspace] = workspace
  opts[:id] = host_id

  framework.db.get_host_tags(opts)
end

#find_nmap_pathObject



1862
1863
1864
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1862

def find_nmap_path
  Rex::FileUtils.find_full_path("nmap") || Rex::FileUtils.find_full_path("nmap.exe")
end

#load_config(path = nil) ⇒ Object

Attempts to connect to the previously configured database, and additionally keeps track of the currently loaded data service.



82
83
84
85
86
87
88
89
90
91
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 82

def load_config(path = nil)
  result = Msf::DbConnector.db_connect_from_config(framework, path)

  if result[:error]
    print_error(result[:error])
  end
  if result[:data_service_name]
    @current_data_service = result[:data_service_name]
  end
end

#nameObject

The dispatcher’s name.



28
29
30
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 28

def name
  "Database Backend"
end

#process_deleted_workspaces(deleted_workspaces, starting_ws) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 276

def process_deleted_workspaces(deleted_workspaces, starting_ws)
  deleted_workspaces.each do |ws|
    print_status "Deleted workspace: #{ws.name}"
    if ws.name == Msf::DBManager::Workspace::DEFAULT_WORKSPACE_NAME
      framework.db.workspace = framework.db.default_workspace
      print_status 'Recreated the default workspace'
    elsif ws == starting_ws
      framework.db.workspace = framework.db.default_workspace
      print_status "Switched to workspace: #{framework.db.workspace.name}"
    end
  end
end

#save_csv_notes(fpath, table) ⇒ Object



1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 1439

def save_csv_notes(fpath, table)
  begin
    File.open(fpath, 'wb') do |f|
      f.write(table.to_csv)
    end
    print_status("Wrote notes to #{fpath}")
  rescue Errno::EACCES => e
    print_error("Unable to save notes. #{e.message}")
  end
end

#save_db_to_config(database, database_name) ⇒ Object



2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
# File 'lib/msf/ui/console/command_dispatcher/db.rb', line 2179

def save_db_to_config(database, database_name)
  if database_name =~ /\/|\[|\]/
    raise ArgumentError, 'Data service name contains an invalid character.'
  end
  config_path = "#{DB_CONFIG_PATH}/#{database_name}"
  config_opts = {}
  if !database.is_local?
    begin
      config_opts['url'] = database.endpoint
      if database.https_opts
        config_opts['cert'] = database.https_opts[:cert] if database.https_opts[:cert]
        config_opts['skip_verify'] = true if database.https_opts[:skip_verify]
      end
      if database.api_token
        config_opts['api_token'] = database.api_token
      end
      Msf::Config.save(config_path => config_opts)
    rescue => e
      print_error "There was an error saving the data service configuration: #{e.message}"
    end
  else
    url = Msf::DbConnector.build_postgres_url
    config_opts['url'] = url
    Msf::Config.save(config_path => config_opts)
  end
end