Class: Msf::DBManager

Inherits:
Object
  • Object
show all
Includes:
ImportMsfXml, Migration, Framework::Offspring
Defined in:
lib/msf/core/db.rb,
lib/msf/core/db_export.rb,
lib/msf/core/db_manager.rb,
lib/msf/core/db_manager/migration.rb,
lib/msf/core/db_manager/import_msf_xml.rb

Overview

The db module provides persistent storage and events. This class should be instantiated LAST as the active_suppport library overrides Kernel.require, slowing down all future code loads.

Defined Under Namespace

Modules: ImportMsfXml, Migration Classes: Export

Constant Summary

Constants included from ImportMsfXml

ImportMsfXml::MSF_WEB_PAGE_TEXT_ELEMENT_NAMES, ImportMsfXml::MSF_WEB_TEXT_ELEMENT_NAMES, ImportMsfXml::MSF_WEB_VULN_TEXT_ELEMENT_NAMES

Instance Attribute Summary collapse

Attributes included from Framework::Offspring

#framework

Attributes included from Migration

#migrated

Instance Method Summary collapse

Methods included from Migration

#migrate

Methods included from ImportMsfXml

#import_msf_web_form_element, #import_msf_web_page_element, #import_msf_web_vuln_element, #import_msf_xml

Constructor Details

#initialize(framework, opts = {}) ⇒ DBManager


63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/msf/core/db_manager.rb', line 63

def initialize(framework, opts = {})

  self.framework = framework
  self.migrated  = false
  self.modules_cached  = false
  self.modules_caching = false

  @usable = false

  # Don't load the database if the user said they didn't need it.
  if (opts['DisableDatabase'])
    self.error = "disabled"
    return
  end

  initialize_database_support
end

Instance Attribute Details

#driverObject

Returns the active driver


49
50
51
# File 'lib/msf/core/db_manager.rb', line 49

def driver
  @driver
end

#driversObject

Returns the list of usable database drivers


46
47
48
# File 'lib/msf/core/db_manager.rb', line 46

def drivers
  @drivers
end

#errorObject

Stores the error message for why the db was not loaded


52
53
54
# File 'lib/msf/core/db_manager.rb', line 52

def error
  @error
end

#modules_cachedObject

Flag to indicate that modules are cached


58
59
60
# File 'lib/msf/core/db_manager.rb', line 58

def modules_cached
  @modules_cached
end

#modules_cachingObject

Flag to indicate that the module cacher is running


61
62
63
# File 'lib/msf/core/db_manager.rb', line 61

def modules_caching
  @modules_caching
end

#sinkObject

Stores a TaskManager for serializing database events


55
56
57
# File 'lib/msf/core/db_manager.rb', line 55

def sink
  @sink
end

#usableObject

Returns true if the prerequisites have been installed


43
44
45
# File 'lib/msf/core/db_manager.rb', line 43

def usable
  @usable
end

Instance Method Details

#activeObject

Returns true if we are ready to load/store data


36
37
38
39
40
# File 'lib/msf/core/db_manager.rb', line 36

def active
  return false if not @usable
  # We have established a connection, some connection is active, and we have run migrations
  (ActiveRecord::Base.connected? && ActiveRecord::Base.connection_pool.connected? && migrated)# rescue false
end

#add_workspace(name) ⇒ Object

Creates a new workspace in the database


247
248
249
250
251
# File 'lib/msf/core/db.rb', line 247

def add_workspace(name)
::ActiveRecord::Base.connection_pool.with_connection {
  ::Mdm::Workspace.find_or_create_by_name(name)
}
end

#checkObject

Determines if the database is functional


225
226
227
228
229
# File 'lib/msf/core/db.rb', line 225

def check
::ActiveRecord::Base.connection_pool.with_connection {
  res = ::Mdm::Host.find(:first)
}
end

#connect(opts = {}) ⇒ Object

Connects this instance to a database


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
# File 'lib/msf/core/db_manager.rb', line 194

def connect(opts={})

  return false if not @usable

  nopts = opts.dup
  if (nopts['port'])
    nopts['port'] = nopts['port'].to_i
  end

  # Prefer the config file's pool setting
  nopts['pool'] ||= 75

  # Prefer the config file's wait_timeout setting too
  nopts['wait_timeout'] ||= 300

  begin
    self.migrated = false
    create_db(nopts)

    # Configure the database adapter
    ActiveRecord::Base.establish_connection(nopts)

    # Migrate the database, if needed
    migrate

    # Set the default workspace
    framework.db.workspace = framework.db.default_workspace

    # Flag that migration has completed
    self.migrated = true
  rescue ::Exception => e
    self.error = e
    elog("DB.connect threw an exception: #{e}")
    dlog("Call stack: #{[email protected]"\n"}", LEV_1)
    return false
  ensure
    # Database drivers can reset our KCODE, do not let them
    $KCODE = 'NONE' if RUBY_VERSION =~ /^1\.8\./
  end

  true
end

#create_db(opts) ⇒ Object

Attempt to create the database

If the database already exists this will fail and we will continue on our merry way, connecting anyway. If it doesn't, we try to create it. If that fails, then it wasn't meant to be and the connect will raise a useful exception so the user won't be in the dark; no need to raise anything at all here.


246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/msf/core/db_manager.rb', line 246

def create_db(opts)
  begin
    case opts["adapter"]
    when 'postgresql'
      # Try to force a connection to be made to the database, if it succeeds
      # then we know we don't need to create it :)
      ActiveRecord::Base.establish_connection(opts)
      # Do the checkout, checkin dance here to make sure this thread doesn't
      # hold on to a connection we don't need
      conn = ActiveRecord::Base.connection_pool.checkout
      ActiveRecord::Base.connection_pool.checkin(conn)
    end
  rescue ::Exception => e
    errstr = e.to_s
    if errstr =~ /does not exist/i or errstr =~ /Unknown database/
      ilog("Database doesn't exist \"#{opts['database']}\", attempting to create it.")
      ActiveRecord::Base.establish_connection(opts.merge('database' => nil))
      ActiveRecord::Base.connection.create_database(opts['database'])
    else
      ilog("Trying to continue despite failed database creation: #{e}")
    end
  end
  ActiveRecord::Base.remove_connection
end

#create_request(host, port, ssl, meth, path, headers, query, body, respcode, resphead, response) ⇒ Object

WMAP Create a request (by hand)


2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
# File 'lib/msf/core/db.rb', line 2806

def create_request(host,port,ssl,meth,path,headers,query,body,respcode,resphead,response)
::ActiveRecord::Base.connection_pool.with_connection {
  req = ::Mdm::WmapRequest.create(
      :host => host,
      :address => host,
      :port => port,
      :ssl => ssl,
      :meth => meth,
      :path => path,
      :headers => headers,
      :query => query,
      :body => body,
      :respcode => respcode,
      :resphead => resphead,
      :response => response
    )
  #framework.events.on_db_request(rec)
}
end

#create_target(host, port, ssl, sel) ⇒ Object

WMAP Create a target


2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
# File 'lib/msf/core/db.rb', line 2788

def create_target(host,port,ssl,sel)
::ActiveRecord::Base.connection_pool.with_connection {
  tar = ::Mdm::WmapTarget.create(
      :host => host,
      :address => host,
      :port => port,
      :ssl => ssl,
      :selected => sel
    )
  #framework.events.on_db_target(rec)
}
end

#creds(wspace = workspace) ⇒ Object

This methods returns a list of all credentials in the database


1249
1250
1251
1252
1253
# File 'lib/msf/core/db.rb', line 1249

def creds(wspace=workspace)
::ActiveRecord::Base.connection_pool.with_connection {
  Mdm::Cred.includes({:service => :host}).where("hosts.workspace_id = ?", wspace.id)
}
end

#default_workspaceObject


232
233
234
235
236
# File 'lib/msf/core/db.rb', line 232

def default_workspace
::ActiveRecord::Base.connection_pool.with_connection {
  ::Mdm::Workspace.default
}
end

#dehex(str) ⇒ Object

If hex notation is present, turn them into a character.


3546
3547
3548
3549
3550
3551
3552
# File 'lib/msf/core/db.rb', line 3546

def dehex(str)
  hexen = str.scan(/\x5cx[0-9a-fA-F]{2}/n)
  hexen.each { |h|
    str.gsub!(h,h[2,2].to_i(16).chr)
  }
  return str
end

#del_host(wspace, address, comm = '') ⇒ Object

Deletes a host and associated data matching this address/comm


1968
1969
1970
1971
1972
1973
1974
# File 'lib/msf/core/db.rb', line 1968

def del_host(wspace, address, comm='')
::ActiveRecord::Base.connection_pool.with_connection {
  address, scope = address.split('%', 2)
  host = wspace.hosts.find_by_address_and_comm(address, comm)
  host.destroy if host
}
end

#del_service(wspace, address, proto, port, comm = '') ⇒ Object

Deletes a port and associated vulns matching this port


1979
1980
1981
1982
1983
1984
1985
1986
1987
# File 'lib/msf/core/db.rb', line 1979

def del_service(wspace, address, proto, port, comm='')

  host = get_host(:workspace => wspace, :address => address)
  return unless host

::ActiveRecord::Base.connection_pool.with_connection {
  host.services.where({:proto => proto, :port => port}).each { |s| s.destroy }
}
end

#delete_all_targetsObject

WMAP This methods deletes all targets from targets table in the database


2767
2768
2769
2770
2771
# File 'lib/msf/core/db.rb', line 2767

def delete_all_targets
::ActiveRecord::Base.connection_pool.with_connection {
  ::Mdm::WmapTarget.delete_all
}
end

#disconnectObject

Disconnects a database session


274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/msf/core/db_manager.rb', line 274

def disconnect
  begin
    ActiveRecord::Base.remove_connection
    self.migrated = false
    self.modules_cached = false
  rescue ::Exception => e
    self.error = e
    elog("DB.disconnect threw an exception: #{e}")
  ensure
    # Database drivers can reset our KCODE, do not let them
    $KCODE = 'NONE' if RUBY_VERSION =~ /^1\.8\./
  end
end

#each_cred(wspace = workspace, &block) ⇒ Object

This method iterates the creds table calling the supplied block with the cred instance of each entry.


1645
1646
1647
1648
1649
1650
1651
# File 'lib/msf/core/db.rb', line 1645

def each_cred(wspace=workspace,&block)
::ActiveRecord::Base.connection_pool.with_connection {
  wspace.creds.each do |cred|
    block.call(cred)
  end
}
end

#each_distinct_target(&block) ⇒ Object

WMAP This method iterates the requests table identifiying possible targets This method wiil be remove on second phase of db merging.


2634
2635
2636
2637
2638
# File 'lib/msf/core/db.rb', line 2634

def each_distinct_target(&block)
  request_distinct_targets.each do |target|
    block.call(target)
  end
end

#each_exploited_host(wspace = workspace, &block) ⇒ Object


1653
1654
1655
1656
1657
1658
1659
# File 'lib/msf/core/db.rb', line 1653

def each_exploited_host(wspace=workspace,&block)
::ActiveRecord::Base.connection_pool.with_connection {
  wspace.exploited_hosts.each do |eh|
    block.call(eh)
  end
}
end

#each_host(wspace = workspace, &block) ⇒ Object

Iterates over the hosts table calling the supplied block with the host instance of each entry.


508
509
510
511
512
513
514
# File 'lib/msf/core/db.rb', line 508

def each_host(wspace=workspace, &block)
::ActiveRecord::Base.connection_pool.with_connection {
  wspace.hosts.each do |host|
    block.call(host)
  end
}
end

#each_loot(wspace = workspace, &block) ⇒ Object

Loot collection

This method iterates the loot table calling the supplied block with the instance of each entry.


2045
2046
2047
2048
2049
2050
2051
# File 'lib/msf/core/db.rb', line 2045

def each_loot(wspace=workspace, &block)
::ActiveRecord::Base.connection_pool.with_connection {
  wspace.loots.each do |note|
    block.call(note)
  end
}
end

#each_note(wspace = workspace, &block) ⇒ Object

This method iterates the notes table calling the supplied block with the note instance of each entry.


1268
1269
1270
1271
1272
1273
1274
# File 'lib/msf/core/db.rb', line 1268

def each_note(wspace=workspace, &block)
::ActiveRecord::Base.connection_pool.with_connection {
  wspace.notes.each do |note|
    block.call(note)
  end
}
end

#each_request(&block) ⇒ Object

WMAP This method iterates the requests table calling the supplied block with the request instance of each entry.


2716
2717
2718
2719
2720
# File 'lib/msf/core/db.rb', line 2716

def each_request(&block)
  requests.each do |request|
    block.call(request)
  end
end

#each_request_target(&block) ⇒ Object

WMAP This method iterates the requests table returning a list of all requests of a specific target


2695
2696
2697
2698
2699
# File 'lib/msf/core/db.rb', line 2695

def each_request_target(&block)
  target_requests('').each do |req|
    block.call(req)
  end
end

#each_request_target_with_body(&block) ⇒ Object

WMAP This method iterates the requests table returning a list of all requests of a specific target


2675
2676
2677
2678
2679
# File 'lib/msf/core/db.rb', line 2675

def each_request_target_with_body(&block)
  target_requests('AND wmap_requests.body IS NOT NULL').each do |req|
    block.call(req)
  end
end

#each_request_target_with_headers(&block) ⇒ Object

WMAP This method iterates the requests table returning a list of all requests of a specific target


2685
2686
2687
2688
2689
# File 'lib/msf/core/db.rb', line 2685

def each_request_target_with_headers(&block)
  target_requests('AND wmap_requests.headers IS NOT NULL').each do |req|
    block.call(req)
  end
end

#each_request_target_with_path(&block) ⇒ Object

WMAP This method iterates the requests table returning a list of all requests of a specific target


2655
2656
2657
2658
2659
# File 'lib/msf/core/db.rb', line 2655

def each_request_target_with_path(&block)
  target_requests('AND wmap_requests.path IS NOT NULL').each do |req|
    block.call(req)
  end
end

#each_request_target_with_query(&block) ⇒ Object

WMAP This method iterates the requests table returning a list of all requests of a specific target


2665
2666
2667
2668
2669
# File 'lib/msf/core/db.rb', line 2665

def each_request_target_with_query(&block)
  target_requests('AND wmap_requests.query IS NOT NULL').each do |req|
    block.call(req)
  end
end

#each_service(wspace = workspace, &block) ⇒ Object

Iterates over the services table calling the supplied block with the service instance of each entry.


628
629
630
631
632
633
634
# File 'lib/msf/core/db.rb', line 628

def each_service(wspace=workspace, &block)
::ActiveRecord::Base.connection_pool.with_connection {
  services(wspace).each do |service|
    block.call(service)
  end
}
end

#each_target(&block) ⇒ Object

WMAP This method iterates the targets table calling the supplied block with the target instance of each entry.


2747
2748
2749
2750
2751
# File 'lib/msf/core/db.rb', line 2747

def each_target(&block)
  targets.each do |target|
    block.call(target)
  end
end

#each_vuln(wspace = workspace, &block) ⇒ Object

This method iterates the vulns table calling the supplied block with the vuln instance of each entry.


1229
1230
1231
1232
1233
1234
1235
# File 'lib/msf/core/db.rb', line 1229

def each_vuln(wspace=workspace,&block)
::ActiveRecord::Base.connection_pool.with_connection {
  wspace.vulns.each do |vulns|
    block.call(vulns)
  end
}
end

#emit(sym, data) {|sym, data| ... } ⇒ Object

A way to sneak the yield back into the db importer. Used by the SAX parsers.

Yields:

  • (sym, data)

6055
6056
6057
# File 'lib/msf/core/db.rb', line 6055

def emit(sym,data,&block)
  yield(sym,data)
end

#events(wspace = workspace) ⇒ Object


2017
2018
2019
2020
2021
# File 'lib/msf/core/db.rb', line 2017

def events(wspace=workspace)
::ActiveRecord::Base.connection_pool.with_connection {
  wspace.events.find :all, :order => 'created_at ASC'
}
end

#exploited_hosts(wspace = workspace) ⇒ Object

This method returns a list of all exploited hosts in the database.


1258
1259
1260
1261
1262
# File 'lib/msf/core/db.rb', line 1258

def exploited_hosts(wspace=workspace)
::ActiveRecord::Base.connection_pool.with_connection {
  wspace.exploited_hosts
}
end

#find_or_create_client(opts) ⇒ Object


1169
1170
1171
# File 'lib/msf/core/db.rb', line 1169

def find_or_create_client(opts)
  report_client(opts)
end

#find_or_create_cred(opts) ⇒ Object

Find or create a credential matching this type/data


1637
1638
1639
# File 'lib/msf/core/db.rb', line 1637

def find_or_create_cred(opts)
  report_auth_info(opts)
end

#find_or_create_host(opts) ⇒ Object

Exactly like report_host but waits for the database to create a host and returns it.


292
293
294
# File 'lib/msf/core/db.rb', line 292

def find_or_create_host(opts)
  report_host(opts)
end

#find_or_create_loot(opts) ⇒ Object

Find or create a loot matching this type/data


2056
2057
2058
# File 'lib/msf/core/db.rb', line 2056

def find_or_create_loot(opts)
  report_loot(opts)
end

#find_or_create_note(opts) ⇒ Object

Find or create a note matching this type/data


1279
1280
1281
# File 'lib/msf/core/db.rb', line 1279

def find_or_create_note(opts)
  report_note(opts)
end

#find_or_create_ref(opts) ⇒ Object

Find or create a reference matching this name


1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
# File 'lib/msf/core/db.rb', line 1884

def find_or_create_ref(opts)
  ret = {}
  ret[:ref] = get_ref(opts[:name])
  return ret[:ref] if ret[:ref]

::ActiveRecord::Base.connection_pool.with_connection {
  ref = ::Mdm::Ref.find_or_initialize_by_name(opts[:name])
  if ref and ref.changed?
    ref.save!
  end
  ret[:ref] = ref
}
end

#find_or_create_report(opts) ⇒ Object

Find or create a task matching this type/data


2178
2179
2180
# File 'lib/msf/core/db.rb', line 2178

def find_or_create_report(opts)
  report_report(opts)
end

#find_or_create_service(opts) ⇒ Object


530
531
532
# File 'lib/msf/core/db.rb', line 530

def find_or_create_service(opts)
  report_service(opts)
end

#find_or_create_task(opts) ⇒ Object

Find or create a task matching this type/data


2121
2122
2123
# File 'lib/msf/core/db.rb', line 2121

def find_or_create_task(opts)
  report_task(opts)
end

#find_or_create_vuln(opts) ⇒ Object

Find or create a vuln matching this service/name


1664
1665
1666
# File 'lib/msf/core/db.rb', line 1664

def find_or_create_vuln(opts)
  report_vuln(opts)
end

#find_qualys_asset_ports(i, host, wspace, hobj, task_id) ⇒ Object

Takes QID numbers and finds the discovered services in a qualys_asset_xml.


5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
# File 'lib/msf/core/db.rb', line 5652

def find_qualys_asset_ports(i,host,wspace,hobj,task_id)
  return unless (i == 82023 || i == 82004)
  proto = i == 82023 ? 'tcp' : 'udp'
  qid = host.elements["VULN_INFO_LIST/VULN_INFO/QID[@id='qid_#{i}']"]
  qid_result = qid.parent.elements["RESULT[@format='table']"] if qid
  hports = qid_result.first.to_s if qid_result
  if hports
    hports.scan(/([0-9]+)\t(.*?)\t.*?\t([^\t\n]*)/) do |match|
      if match[2] == nil or match[2].strip == 'unknown'
        name = match[1].strip
      else
        name = match[2].strip
      end
      handle_qualys(wspace, hobj, match[0].to_s, proto, 0, nil, nil, name, nil, task_id)
    end
  end
end

#find_qualys_asset_vuln_refs(doc) ⇒ Object


5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
# File 'lib/msf/core/db.rb', line 5622

def find_qualys_asset_vuln_refs(doc)
  vuln_refs = {}
  doc.elements.each("/ASSET_DATA_REPORT/GLOSSARY/VULN_DETAILS_LIST/VULN_DETAILS") do |vuln|
    next unless vuln.elements['QID'] && vuln.elements['QID'].first
    qid = vuln.elements['QID'].first.to_s
    vuln_refs[qid] ||= []
    vuln.elements.each('CVE_ID_LIST/CVE_ID') do |ref|
      vuln_refs[qid].push('CVE-' + /C..-([0-9\-]{9})/.match(ref.elements['ID'].text.to_s)[1])
    end
    vuln.elements.each('BUGTRAQ_ID_LIST/BUGTRAQ_ID') do |ref|
      vuln_refs[qid].push('BID-' + ref.elements['ID'].text.to_s)
    end
  end
  return vuln_refs
end

#find_qualys_asset_vulns(host, wspace, hobj, vuln_refs, task_id, &block) ⇒ Object

Pull out vulnerabilities that have at least one matching ref – many “vulns” are not vulns, just audit information.


5640
5641
5642
5643
5644
5645
5646
5647
5648
# File 'lib/msf/core/db.rb', line 5640

def find_qualys_asset_vulns(host,wspace,hobj,vuln_refs,task_id,&block)
  host.elements.each("VULN_INFO_LIST/VULN_INFO") do |vi|
    next unless vi.elements["QID"]
    vi.elements.each("QID") do |qid|
      next if vuln_refs[qid.text].nil? || vuln_refs[qid.text].empty?
      handle_qualys(wspace, hobj, nil, nil, qid.text, nil, vuln_refs[qid.text], nil, nil, task_id)
    end
  end
end

#find_vuln_by_details(details_map, host, service = nil) ⇒ Object


1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
# File 'lib/msf/core/db.rb', line 1841

def find_vuln_by_details(details_map, host, service=nil)

  # Create a modified version of the criteria in order to match against
  # the joined version of the fields

  crit = {}
  details_map.each_pair do |k,v|
    crit[ "vuln_details.#{k}" ] = v
  end

  vuln = nil

  if service
    vuln = service.vulns.find(:first, :include => [:vuln_details], :conditions => crit)
  end

  # Return if we matched based on service
  return vuln if vuln

  # Prevent matches against other services
  crit["vulns.service_id"] = nil if service
  vuln = host.vulns.find(:first, :include => [:vuln_details], :conditions => crit)

  return vuln
end

#find_vuln_by_refs(refs, host, service = nil) ⇒ Object


1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
# File 'lib/msf/core/db.rb', line 1814

def find_vuln_by_refs(refs, host, service=nil)

  vuln = nil

  # Try to find an existing vulnerability with the same service & references
  # If there are multiple matches, choose the one with the most matches
  if service
    refs_ids = refs.map{|x| x.id }
    vuln = service.vulns.find(:all, :include => [:refs], :conditions => { 'refs.id' => refs_ids }).sort { |a,b|
      ( refs_ids - a.refs.map{|x| x.id } ).length <=> ( refs_ids - b.refs.map{|x| x.id } ).length
    }.first
  end

  # Return if we matched based on service
  return vuln if vuln

  # Try to find an existing vulnerability with the same host & references
  # If there are multiple matches, choose the one with the most matches
  refs_ids = refs.map{|x| x.id }
  vuln = host.vulns.find(:all, :include => [:refs], :conditions => { 'service_id' => nil, 'refs.id' => refs_ids }).sort { |a,b|
    ( refs_ids - a.refs.map{|x| x.id } ).length <=> ( refs_ids - b.refs.map{|x| x.id } ).length
  }.first

  return vuln
end

#find_workspace(name) ⇒ Object


238
239
240
241
242
# File 'lib/msf/core/db.rb', line 238

def find_workspace(name)
::ActiveRecord::Base.connection_pool.with_connection {
  ::Mdm::Workspace.find_by_name(name)
}
end

#get_client(opts) ⇒ Object


1160
1161
1162
1163
1164
1165
1166
1167
# File 'lib/msf/core/db.rb', line 1160

def get_client(opts)
::ActiveRecord::Base.connection_pool.with_connection {
  wspace = opts.delete(:workspace) || workspace
  host   = get_host(:workspace => wspace, :host => opts[:host]) || return
  client = host.clients.where({:ua_string => opts[:ua_string]}).first()
  return client
}
end

#get_host(opts) ⇒ Object

Find a host. Performs no database writes.


269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/msf/core/db.rb', line 269

def get_host(opts)
  if opts.kind_of? ::Mdm::Host
    return opts
  elsif opts.kind_of? String
    raise RuntimeError, "This invokation of get_host is no longer supported: #{caller}"
  else
    address = opts[:addr] || opts[:address] || opts[:host] || return
    return address if address.kind_of? ::Mdm::Host
  end
::ActiveRecord::Base.connection_pool.with_connection {
  wspace = opts.delete(:workspace) || workspace
  if wspace.kind_of? String
    wspace = find_workspace(wspace)
  end

  address = normalize_host(address)
  return wspace.hosts.find_by_address(address)
}
end

#get_ref(name) ⇒ Object


1898
1899
1900
1901
1902
# File 'lib/msf/core/db.rb', line 1898

def get_ref(name)
::ActiveRecord::Base.connection_pool.with_connection {
  ::Mdm::Ref.find_by_name(name)
}
end

#get_service(wspace, host, proto, port) ⇒ Object


616
617
618
619
620
621
622
# File 'lib/msf/core/db.rb', line 616

def get_service(wspace, host, proto, port)
::ActiveRecord::Base.connection_pool.with_connection {
  host = get_host(:workspace => wspace, :address => host)
  return if not host
  return host.services.find_by_proto_and_port(proto, port)
}
end

#get_session(opts) ⇒ Object

Returns a session based on opened_time, host address, and workspace (or returns nil)


653
654
655
656
657
658
659
660
661
662
# File 'lib/msf/core/db.rb', line 653

def get_session(opts)
  return if not active
::ActiveRecord::Base.connection_pool.with_connection {
  wspace = opts[:workspace] || opts[:wspace] || workspace
  addr   = opts[:addr] || opts[:address] || opts[:host] || return
  host = get_host(:workspace => wspace, :host => addr)
  time = opts[:opened_at] || opts[:created_at] || opts[:time] || return
  ::Mdm::Session.find_by_host_id_and_opened_at(host.id, time)
}
end

#get_target(id) ⇒ Object

WMAP Find a target matching this id


2777
2778
2779
2780
2781
2782
# File 'lib/msf/core/db.rb', line 2777

def get_target(id)
::ActiveRecord::Base.connection_pool.with_connection {
  target = ::Mdm::WmapTarget.where("id = ?", id).first()
  return target
}
end

#get_vuln(wspace, host, service, name, data = '') ⇒ Object

Raises:

  • (RuntimeError)

1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
# File 'lib/msf/core/db.rb', line 1867

def get_vuln(wspace, host, service, name, data='')
  raise RuntimeError, "Not workspace safe: #{caller.inspect}"
::ActiveRecord::Base.connection_pool.with_connection {
  vuln = nil
  if (service)
    vuln = ::Mdm::Vuln.find.where("name = ? and service_id = ? and host_id = ?", name, service.id, host.id).order("vulns.id DESC").first()
  else
    vuln = ::Mdm::Vuln.find.where("name = ? and host_id = ?", name, host.id).first()
  end

  return vuln
}
end

#has_host?(wspace, addr) ⇒ Boolean

Look for an address across all comms


2010
2011
2012
2013
2014
2015
# File 'lib/msf/core/db.rb', line 2010

def has_host?(wspace,addr)
::ActiveRecord::Base.connection_pool.with_connection {
  address, scope = addr.split('%', 2)
  wspace.hosts.find_by_address(addr)
}
end

#has_ref?(name) ⇒ Boolean

Find a reference matching this name


1992
1993
1994
1995
1996
# File 'lib/msf/core/db.rb', line 1992

def has_ref?(name)
::ActiveRecord::Base.connection_pool.with_connection {
  Mdm::Ref.find_by_name(name)
}
end

#has_vuln?(name) ⇒ Boolean

Find a vulnerability matching this name


2001
2002
2003
2004
2005
# File 'lib/msf/core/db.rb', line 2001

def has_vuln?(name)
::ActiveRecord::Base.connection_pool.with_connection {
  Mdm::Vuln.find_by_name(name)
}
end

#hosts(wspace = workspace, only_up = false, addresses = nil) ⇒ Object

Returns a list of all hosts in the database


519
520
521
522
523
524
525
526
# File 'lib/msf/core/db.rb', line 519

def hosts(wspace = workspace, only_up = false, addresses = nil)
::ActiveRecord::Base.connection_pool.with_connection {
  conditions = {}
  conditions[:state] = [Msf::HostState::Alive, Msf::HostState::Unknown] if only_up
  conditions[:address] = addresses if addresses
  wspace.hosts.where(conditions).order(:address)
}
end

#import(args = {}) {|:filetype, @import_filedata[:type]| ... } ⇒ Object

A dispatcher method that figures out the data's file type, and sends it off to the appropriate importer. Note that import_file_detect will raise an error if the filetype is unknown.

Yields:

  • (:filetype, @import_filedata[:type])

2910
2911
2912
2913
2914
2915
2916
# File 'lib/msf/core/db.rb', line 2910

def import(args={}, &block)
  data = args[:data] || args['data']
  wspace = args[:wspace] || args['wspace'] || workspace
  ftype = import_filetype_detect(data)
  yield(:filetype, @import_filedata[:type]) if block
  self.send "import_#{ftype}".to_sym, args, &block
end

#import_acunetix_noko_stream(args = {}, &block) ⇒ Object


5415
5416
5417
5418
5419
5420
5421
5422
5423
# File 'lib/msf/core/db.rb', line 5415

def import_acunetix_noko_stream(args={},&block)
  if block
    doc = Rex::Parser::AcunetixDocument.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::AcunetixFoundstoneDocument.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_acunetix_xml(args = {}, &block) ⇒ Object


5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
# File 'lib/msf/core/db.rb', line 5375

def import_acunetix_xml(args={}, &block)
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  wspace = args[:wspace] || workspace
  if Rex::Parser.nokogiri_loaded
    parser = "Nokogiri v#{::Nokogiri::VERSION}"
    noko_args = args.dup
    noko_args[:blacklist] = bl
    noko_args[:wspace] = wspace
    if block
      yield(:parser, parser)
      import_acunetix_noko_stream(noko_args) {|type, data| yield type,data}
    else
      import_acunetix_noko_stream(noko_args)
    end
    return true
  else # Sorry
    raise DBImportError.new("Could not import due to missing Nokogiri parser. Try 'gem install nokogiri'.")
  end
end

#import_amap_log(args = {}, &block) ⇒ Object


5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
# File 'lib/msf/core/db.rb', line 5861

def import_amap_log(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []

  data.each_line do |line|
    next if line =~ /^#/
    next if line !~ /^Protocol on ([^:]+):([^\x5c\x2f]+)[\x5c\x2f](tcp|udp) matches (.*)$/n
    addr   = $1
    next if bl.include? addr
    port   = $2.to_i
    proto  = $3.downcase
    name   = $4
    host = find_or_create_host(:workspace => wspace, :host => addr, :state => Msf::HostState::Alive, :task => args[:task])
    next if not host
    yield(:address,addr) if block
    info = {
      :workspace => wspace,
      :task => args[:task],
      :host => host,
      :proto => proto,
      :port => port
    }
    if name != "unidentified"
      info[:name] = name
    end
    service = find_or_create_service(info)
  end
end

#import_amap_log_file(args = {}) ⇒ Object


5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
# File 'lib/msf/core/db.rb', line 5843

def import_amap_log_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace
  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end

  case import_filetype_detect(data)
  when :amap_log
    import_amap_log(args.merge(:data => data))
  when :amap_mlog
    import_amap_mlog(args.merge(:data => data))
  else
    raise DBImportError.new("Could not determine file type")
  end
end

#import_amap_mlog(args = {}, &block) ⇒ Object


5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
# File 'lib/msf/core/db.rb', line 5891

def import_amap_mlog(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []

  data.each_line do |line|
    next if line =~ /^#/
    r = line.split(':')
    next if r.length < 6

    addr   = r[0]
    next if bl.include? addr
    port   = r[1].to_i
    proto  = r[2].downcase
    status = r[3]
    name   = r[5]
    next if status != "open"

    host = find_or_create_host(:workspace => wspace, :host => addr, :state => Msf::HostState::Alive, :task => args[:task])
    next if not host
    yield(:address,addr) if block
    info = {
      :workspace => wspace,
      :task => args[:task],
      :host => host,
      :proto => proto,
      :port => port
    }
    if name != "unidentified"
      info[:name] = name
    end
    service = find_or_create_service(info)
  end
end

#import_appscan_noko_stream(args = {}, &block) ⇒ Object


5446
5447
5448
5449
5450
5451
5452
5453
5454
# File 'lib/msf/core/db.rb', line 5446

def import_appscan_noko_stream(args={},&block)
  if block
    doc = Rex::Parser::AppscanDocument.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::AppscanDocument.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_appscan_xml(args = {}, &block) ⇒ Object


5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
# File 'lib/msf/core/db.rb', line 5426

def import_appscan_xml(args={}, &block)
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  wspace = args[:wspace] || workspace
  if Rex::Parser.nokogiri_loaded
    parser = "Nokogiri v#{::Nokogiri::VERSION}"
    noko_args = args.dup
    noko_args[:blacklist] = bl
    noko_args[:wspace] = wspace
    if block
      yield(:parser, parser)
      import_appscan_noko_stream(noko_args) {|type, data| yield type,data}
    else
      import_appscan_noko_stream(noko_args)
    end
    return true
  else # Sorry
    raise DBImportError.new("Could not import due to missing Nokogiri parser. Try 'gem install nokogiri'.")
  end
end

#import_burp_session_noko_stream(args = {}, &block) ⇒ Object


5477
5478
5479
5480
5481
5482
5483
5484
5485
# File 'lib/msf/core/db.rb', line 5477

def import_burp_session_noko_stream(args={},&block)
  if block
    doc = Rex::Parser::BurpSessionDocument.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::BurpSessionDocument.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_burp_session_xml(args = {}, &block) ⇒ Object


5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
# File 'lib/msf/core/db.rb', line 5456

def import_burp_session_xml(args={}, &block)
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  wspace = args[:wspace] || workspace
  if Rex::Parser.nokogiri_loaded
    # Rex::Parser.reload("burp_session_nokogiri.rb")
    parser = "Nokogiri v#{::Nokogiri::VERSION}"
    noko_args = args.dup
    noko_args[:blacklist] = bl
    noko_args[:wspace] = wspace
    if block
      yield(:parser, parser)
      import_burp_session_noko_stream(noko_args) {|type, data| yield type,data}
    else
      import_burp_session_noko_stream(noko_args)
    end
    return true
  else # Sorry
    raise DBImportError.new("Could not import due to missing Nokogiri parser. Try 'gem install nokogiri'.")
  end
end

#import_ci_noko_stream(args, &block) ⇒ Object


5926
5927
5928
5929
5930
5931
5932
5933
5934
# File 'lib/msf/core/db.rb', line 5926

def import_ci_noko_stream(args, &block)
  if block
    doc = Rex::Parser::CIDocument.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::CI.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_ci_xml(args = {}, &block) ⇒ Object


5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
# File 'lib/msf/core/db.rb', line 5395

def import_ci_xml(args={}, &block)
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  wspace = args[:wspace] || workspace
  if Rex::Parser.nokogiri_loaded
    parser = "Nokogiri v#{::Nokogiri::VERSION}"
    noko_args = args.dup
    noko_args[:blacklist] = bl
    noko_args[:wspace] = wspace
    if block
      yield(:parser, parser)
      import_ci_noko_stream(noko_args) {|type, data| yield type,data}
    else
      import_ci_noko_stream(noko_args)
    end
    return true
  else # Sorry
    raise DBImportError.new("Could not import due to missing Nokogiri parser. Try 'gem install nokogiri'.")
  end
end

#import_file(args = {}, &block) ⇒ Object

Generic importer that automatically determines the file type being imported. Since this looks for vendor-specific strings in the given file, there shouldn't be any false detections, but no guarantees.


2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
# File 'lib/msf/core/db.rb', line 2873

def import_file(args={}, &block)
  filename = args[:filename] || args['filename']
  wspace = args[:wspace] || args['wspace'] || workspace
  @import_filedata            = {}
  @import_filedata[:filename] = filename

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(4)
  end
  if data.nil?
    raise DBImportError.new("Zero-length file")
  end

  case data[0,4]
  when "PK\x03\x04"
    data = Zip::ZipFile.open(filename)
  when "\xd4\xc3\xb2\xa1", "\xa1\xb2\xc3\xd4"
    data = PacketFu::PcapFile.new(:filename => filename)
  else
    ::File.open(filename, 'rb') do |f|
      sz = f.stat.size
      data = f.read(sz)
    end
  end
  if block
    import(args.merge(:data => data)) { |type,data| yield type,data }
  else
    import(args.merge(:data => data))
  end

end

#import_filetype_detect(data) ⇒ Object

Returns one of: :nexpose_simplexml :nexpose_rawxml :nmap_xml :openvas_xml :nessus_xml :nessus_xml_v2 :qualys_scan_xml, :qualys_asset_xml, :msf_xml :nessus_nbe :amap_mlog :amap_log :ip_list, :msf_zip, :libpcap, :foundstone_xml, :acunetix_xml, :appscan_xml :burp_session, :ip360_xml_v3, :ip360_aspl_xml, :nikto_xml, :outpost24_xml If there is no match, an error is raised instead.

Raises:


2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
# File 'lib/msf/core/db.rb', line 2923

def import_filetype_detect(data)

  if data and data.kind_of? Zip::ZipFile
    if data.entries.empty?
      raise DBImportError.new("The zip file provided is empty.")
    end

    @import_filedata ||= {}
    @import_filedata[:zip_filename] = File.split(data.to_s).last
    @import_filedata[:zip_basename] = @import_filedata[:zip_filename].gsub(/\.zip$/,"")
    @import_filedata[:zip_entry_names] = data.entries.map {|x| x.name}

    xml_files = @import_filedata[:zip_entry_names].grep(/^(.*)\.xml$/)

    # TODO This check for our zip export should be more extensive
    if xml_files.empty?
      raise DBImportError.new("The zip file provided is not a Metasploit Zip Export")
    end

    @import_filedata[:zip_xml] = xml_files.first
    @import_filedata[:type] = "Metasploit Zip Export"

    return :msf_zip
  end

  if data and data.kind_of? PacketFu::PcapFile
    # Don't check for emptiness here because unlike other formats, we
    # haven't read any actual data in yet, only magic bytes to discover
    # that this is indeed a pcap file.
    #raise DBImportError.new("The pcap file provided is empty.") if data.body.empty?
    @import_filedata ||= {}
    @import_filedata[:type] = "Libpcap Packet Capture"
    return :libpcap
  end

  # This is a text string, lets make sure its treated as binary
  data = data.unpack("C*").pack("C*")
  if data and data.to_s.strip.length == 0
    raise DBImportError.new("The data provided to the import function was empty")
  end

  # Parse the first line or 4k of data from the file
  di = data.index("\n") || 4096

  firstline = data[0, di]
  @import_filedata ||= {}
  if (firstline.index("<NeXposeSimpleXML"))
    @import_filedata[:type] = "NeXpose Simple XML"
    return :nexpose_simplexml
  elsif (firstline.index("<FusionVM"))
    @import_filedata[:type] = "FusionVM XML"
    return :fusionvm_xml
  elsif (firstline.index("<NexposeReport"))
    @import_filedata[:type] = "NeXpose XML Report"
    return :nexpose_rawxml
  elsif (firstline.index("Name,Manufacturer,Device Type,Model,IP Address,Serial Number,Location,Operating System"))
    @import_filedata[:type] = "Spiceworks CSV Export"
    return :spiceworks_csv
  elsif (firstline.index("<scanJob>"))
    @import_filedata[:type] = "Retina XML"
    return :retina_xml
  elsif (firstline.index(/<get_reports_response status=['"]200['"] status_text=['"]OK['"]>/))
    @import_filedata[:type] = "OpenVAS XML"
    return :openvas_new_xml
  elsif (firstline.index(/<report id=['"]/))
    @import_filedata[:type] = "OpenVAS XML"
    return :openvas_new_xml
  elsif (firstline.index("<NessusClientData>"))
    @import_filedata[:type] = "Nessus XML (v1)"
    return :nessus_xml
  elsif (firstline.index("<SecScan ID="))
    @import_filedata[:type] = "Microsoft Baseline Security Analyzer"
    return :mbsa_xml
  elsif (data[0,1024] =~ /<!ATTLIST\s+items\s+burpVersion/)
    @import_filedata[:type] = "Burp Session XML"
    return :burp_session_xml
  elsif (firstline.index("<?xml"))
    # it's xml, check for root tags we can handle
    line_count = 0
    data.each_line { |line|
      line =~ /<([a-zA-Z0-9\-\_]+)[ >]/

      case $1
      when "niktoscan"
        @import_filedata[:type] = "Nikto XML"
        return :nikto_xml
      when "nmaprun"
        @import_filedata[:type] = "Nmap XML"
        return :nmap_xml
      when "openvas-report"
        @import_filedata[:type] = "OpenVAS Report"
        return :openvas_xml
      when "NessusClientData"
        @import_filedata[:type] = "Nessus XML (v1)"
        return :nessus_xml
      when "NessusClientData_v2"
        @import_filedata[:type] = "Nessus XML (v2)"
        return :nessus_xml_v2
      when "SCAN"
        @import_filedata[:type] = "Qualys Scan XML"
        return :qualys_scan_xml
      when "report"
        @import_filedata[:type] = "Wapiti XML"
        return :wapiti_xml
      when "ASSET_DATA_REPORT"
        @import_filedata[:type] = "Qualys Asset XML"
        return :qualys_asset_xml
      when /MetasploitExpressV[1234]/
        @import_filedata[:type] = "Metasploit XML"
        return :msf_xml
      when /MetasploitV4/
        @import_filedata[:type] = "Metasploit XML"
        return :msf_xml
      when /netsparker/
        @import_filedata[:type] = "NetSparker XML"
        return :netsparker_xml
      when /audits?/ # <audit> and <audits> are both valid for nCircle. wtfmate.
        @import_filedata[:type] = "IP360 XML v3"
        return :ip360_xml_v3
      when /ontology/
        @import_filedata[:type] = "IP360 ASPL"
        return :ip360_aspl_xml
      when /ReportInfo/
        @import_filedata[:type] = "Foundstone"
        return :foundstone_xml
      when /ScanGroup/
        @import_filedata[:type] = "Acunetix"
        return :acunetix_xml
      when /AppScanInfo/ # Actually the second line
        @import_filedata[:type] = "Appscan"
        return :appscan_xml
      when "entities"
        if  line =~ /creator.*\x43\x4f\x52\x45\x20\x49\x4d\x50\x41\x43\x54/ni
          @import_filedata[:type] = "CI"
          return :ci_xml
        end
      when "main"
        @import_filedata[:type] = "Outpost24 XML"
        return :outpost24_xml
      else
        # Give up if we haven't hit the root tag in the first few lines
        break if line_count > 10
      end
      line_count += 1
    }
  elsif (firstline.index("timestamps|||scan_start"))
    @import_filedata[:type] = "Nessus NBE Report"
    # then it's a nessus nbe
    return :nessus_nbe
  elsif (firstline.index("# amap v"))
    # then it's an amap mlog
    @import_filedata[:type] = "Amap Log -m"
    return :amap_mlog
  elsif (firstline.index("amap v"))
    # then it's an amap log
    @import_filedata[:type] = "Amap Log"
    return :amap_log
  elsif ipv46_validator(firstline)
    # then its an IP list
    @import_filedata[:type] = "IP Address List"
    return :ip_list
  elsif (data[0,1024].index("<netsparker"))
    @import_filedata[:type] = "NetSparker XML"
    return :netsparker_xml
  elsif (firstline.index("# Metasploit PWDump Export"))
    # then it's a Metasploit PWDump export
    @import_filedata[:type] = "msf_pwdump"
    return :msf_pwdump
  end

  raise DBImportError.new("Could not automatically determine file type")
end

#import_foundstone_noko_stream(args = {}, &block) ⇒ Object


5365
5366
5367
5368
5369
5370
5371
5372
5373
# File 'lib/msf/core/db.rb', line 5365

def import_foundstone_noko_stream(args={},&block)
  if block
    doc = Rex::Parser::FoundstoneDocument.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::FoundstoneDocument.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_foundstone_xml(args = {}, &block) ⇒ Object


5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
# File 'lib/msf/core/db.rb', line 5345

def import_foundstone_xml(args={}, &block)
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  wspace = args[:wspace] || workspace
  if Rex::Parser.nokogiri_loaded
    parser = "Nokogiri v#{::Nokogiri::VERSION}"
    noko_args = args.dup
    noko_args[:blacklist] = bl
    noko_args[:wspace] = wspace
    if block
      yield(:parser, parser)
      import_foundstone_noko_stream(noko_args) {|type, data| yield type,data}
    else
      import_foundstone_noko_stream(noko_args)
    end
    return true
  else # Sorry
    raise DBImportError.new("Could not import due to missing Nokogiri parser. Try 'gem install nokogiri'.")
  end
end

#import_fusionvm_xml(args = {}) ⇒ Object


4678
4679
4680
4681
4682
4683
4684
# File 'lib/msf/core/db.rb', line 4678

def import_fusionvm_xml(args={})
  args[:wspace] ||= workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  doc = Rex::Parser::FusionVMDocument.new(args,self)
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_ip360_aspl_xml(args = {}) {|:notice, "Saved the IP360 ASPL database to #{base}..."| ... } ⇒ Object

Import IP360's ASPL database

Yields:

  • (:notice, "Saved the IP360 ASPL database to #{base}...")

5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
# File 'lib/msf/core/db.rb', line 5491

def import_ip360_aspl_xml(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []

  if not data.index("<ontology")
    raise DBImportError.new("The ASPL file does not appear to be valid or may still be compressed")
  end

  base = ::File.join(Msf::Config.config_directory, "data", "ncircle")
  ::FileUtils.mkdir_p(base)
  ::File.open(::File.join(base, "ip360.aspl"), "wb") do |fd|
    fd.write(data)
  end
  yield(:notice, "Saved the IP360 ASPL database to #{base}...")
end

#import_ip360_xml_file(args = {}) ⇒ Object

Import IP360 XML v3 output


5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
# File 'lib/msf/core/db.rb', line 5125

def import_ip360_xml_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_ip360_xml_v3(args.merge(:data => data))
end

#import_ip360_xml_v3(args = {}, &block) ⇒ Object

Import IP360's xml output


5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
# File 'lib/msf/core/db.rb', line 5512

def import_ip360_xml_v3(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []

  # @aspl = {'vulns' => {'name' => { }, 'cve' => { }, 'bid' => { } }
  # 'oses' => {'name' } }

  aspl_path  = nil
  aspl_paths = [
    ::File.join(Msf::Config.config_directory, "data", "ncircle", "ip360.aspl"),
    ::File.join(Msf::Config.data_directory, "ncircle", "ip360.aspl")
  ]

  aspl_paths.each do |tpath|
    next if not (::File.exist?(tpath) and ::File.readable?(tpath))
    aspl_path = tpath
    break
  end

  if not aspl_path
    raise DBImportError.new("The nCircle IP360 ASPL file is not present.\n    Download ASPL from nCircle VNE | Administer | Support | Resources, unzip it, and import it first")
  end

  # parse nCircle ASPL file
  aspl = ""
  ::File.open(aspl_path, "rb") do |f|
    aspl = f.read(f.stat.size)
  end

  @asplhash = nil
  parser = Rex::Parser::IP360ASPLXMLStreamParser.new
  parser.on_found_aspl = Proc.new { |asplh|
    @asplhash = asplh
  }
  REXML::Document.parse_stream(aspl, parser)

  # nCircle has some quotes escaped which causes the parser to break
  # we don't need these lines so just replace \" with "
  data.gsub!(/\\"/,'"')

  # parse nCircle Scan Output
  parser = Rex::Parser::IP360XMLStreamParser.new
  parser.on_found_host = Proc.new { |host|
    hobj = nil
    addr = host['addr'] || host['hname']

    next unless ipv46_validator(addr) # Catches SCAN-ERROR, among others.

    if bl.include? addr
      next
    else
      yield(:address,addr) if block
    end

    os = host['os']
    hname = host['hname']
    mac = host['mac']

    host_hash = {
      :workspace => wspace,
      :host => addr,
      :task => args[:task]
    }
    host_hash[:name] = hname.to_s.strip if hname
    host_hash[:mac]  = mac.to_s.strip.upcase if mac

    hobj = report_host(host_hash)

    yield(:os, os) if block
    if os
      report_note(
        :workspace => wspace,
        :task => args[:task],
        :host => hobj,
        :type => 'host.os.ip360_fingerprint',
        :data => {
          :os => @asplhash['oses'][os].to_s.strip
        }
      )
    end

    host['apps'].each do |item|
      port = item['port'].to_s
      proto = item['proto'].to_s

      handle_ip360_v3_svc(wspace, hobj, port, proto, hname, args[:task])
    end


    host['vulns'].each do |item|
      vulnid = item['vulnid'].to_s
      port = item['port'].to_s
      proto = item['proto'] || "tcp"
      vulnname = @asplhash['vulns']['name'][vulnid]
      cves = @asplhash['vulns']['cve'][vulnid]
      bids = @asplhash['vulns']['bid'][vulnid]

      yield(:port, port) if block

      handle_ip360_v3_vuln(wspace, hobj, port, proto, hname, vulnid, vulnname, cves, bids, args[:task])

    end

    yield(:end, hname) if block
  }

  REXML::Document.parse_stream(data, parser)
end

#import_ip_list(args = {}, &block) ⇒ Object


5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
# File 'lib/msf/core/db.rb', line 5827

def import_ip_list(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []

  data.each_line do |ip|
    ip.strip!
    if bl.include? ip
      next
    else
      yield(:address,ip) if block
    end
    host = find_or_create_host(:workspace => wspace, :host=> ip, :state => Msf::HostState::Alive, :task => args[:task])
  end
end

#import_ip_list_file(args = {}) ⇒ Object


5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
# File 'lib/msf/core/db.rb', line 5816

def import_ip_list_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_ip_list(args.merge(:data => data))
end

#import_libpcap(args = {}, &block) ⇒ Object

The libpcap file format is handled by PacketFu for data extraction. TODO: Make this its own mixin, and possibly extend PacketFu to do better stream analysis on the fly.


3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
# File 'lib/msf/core/db.rb', line 3216

def import_libpcap(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  # seen_hosts is only used for determining when to yield an address. Once we get
  # some packet analysis going, the values will have all sorts of info. The plan
  # is to ru through all the packets as a first pass and report host and service,
  # then, once we have everything parsed, we can reconstruct sessions and ngrep
  # out things like authentication sequences, examine ttl's and window sizes, all
  # kinds of crazy awesome stuff like that.
  seen_hosts = {}
  decoded_packets = 0
  last_count = 0
  data.read_packet_bytes do |p|
    if (decoded_packets >= last_count + 1000) and block
      yield(:pcap_count, decoded_packets)
      last_count = decoded_packets
    end
    decoded_packets += 1

    pkt = PacketFu::Packet.parse(p) rescue next # Just silently skip bad packets

    next unless pkt.is_ip? # Skip anything that's not IP. Technically, not Ethernet::Ip
    next if pkt.is_tcp? && (pkt.tcp_src == 0 || pkt.tcp_dst == 0) # Skip port 0
    next if pkt.is_udp? && (pkt.udp_src == 0 || pkt.udp_dst == 0) # Skip port 0
    saddr = pkt.ip_saddr
    daddr = pkt.ip_daddr

    # Handle blacklists and obviously useless IP addresses, and report the host.
    next if (bl | [saddr,daddr]).size == bl.size # Both hosts are blacklisted, skip everything.
    unless( bl.include?(saddr) || rfc3330_reserved(saddr))
      yield(:address,saddr) if block and !seen_hosts.keys.include?(saddr)
      unless seen_hosts[saddr]
        report_host(
            :workspace => wspace,
            :host      => saddr,
            :state     => Msf::HostState::Alive,
            :task      => args[:task]
        )
      end
      seen_hosts[saddr] ||= []

    end
    unless( bl.include?(daddr) || rfc3330_reserved(daddr))
      yield(:address,daddr) if block and !seen_hosts.keys.include?(daddr)
      unless seen_hosts[daddr]
        report_host(
            :workspace => wspace,
            :host      => daddr,
            :state     => Msf::HostState::Alive,
            :task      => args[:task]
        )
      end
      seen_hosts[daddr] ||= []
    end

    if pkt.is_tcp? # First pass on TCP packets
      if (pkt.tcp_flags.syn == 1 and pkt.tcp_flags.ack == 1) or # Oh, this kills me
        pkt.tcp_src < 1024 # If it's a low port, assume it's a proper service.
        if seen_hosts[saddr]
          unless seen_hosts[saddr].include? [pkt.tcp_src,"tcp"]
            report_service(
                :workspace => wspace, :host => saddr,
                :proto     => "tcp", :port => pkt.tcp_src,
                :state     => Msf::ServiceState::Open,
                :task      => args[:task]
            )
            seen_hosts[saddr] << [pkt.tcp_src,"tcp"]
            yield(:service,"%s:%d/%s" % [saddr,pkt.tcp_src,"tcp"])
          end
        end
      end
    elsif pkt.is_udp? # First pass on UDP packets
      if pkt.udp_src == pkt.udp_dst # Very basic p2p detection.
        [saddr,daddr].each do |xaddr|
          if seen_hosts[xaddr]
            unless seen_hosts[xaddr].include? [pkt.udp_src,"udp"]
              report_service(
                  :workspace => wspace, :host => xaddr,
                  :proto     => "udp", :port => pkt.udp_src,
                  :state     => Msf::ServiceState::Open,
                  :task      => args[:task]
              )
              seen_hosts[xaddr] << [pkt.udp_src,"udp"]
              yield(:service,"%s:%d/%s" % [xaddr,pkt.udp_src,"udp"])
            end
          end
        end
      elsif pkt.udp_src < 1024 # Probably a service
        if seen_hosts[saddr]
          unless seen_hosts[saddr].include? [pkt.udp_src,"udp"]
            report_service(
                :workspace => wspace, :host => saddr,
                :proto     => "udp", :port => pkt.udp_src,
                :state     => Msf::ServiceState::Open,
                :task      => args[:task]
            )
            seen_hosts[saddr] << [pkt.udp_src,"udp"]
            yield(:service,"%s:%d/%s" % [saddr,pkt.udp_src,"udp"])
          end
        end
      end
    end # tcp or udp

    inspect_single_packet(pkt,wspace,args[:task])

  end # data.body.map

  # Right about here, we should have built up some streams for some stream analysis.
  # Not sure what form that will take, but people like shoving many hundreds of
  # thousands of packets through this thing, so it'll need to be memory efficient.

end

#import_libpcap_file(args = {}) ⇒ Object


3205
3206
3207
3208
3209
3210
3211
# File 'lib/msf/core/db.rb', line 3205

def import_libpcap_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = PacketFu::PcapFile.new(:filename => filename)
  import_libpcap(args.merge(:data => data))
end

#import_mbsa_noko_stream(args = {}, &block) ⇒ Object


5335
5336
5337
5338
5339
5340
5341
5342
5343
# File 'lib/msf/core/db.rb', line 5335

def import_mbsa_noko_stream(args={},&block)
  if block
    doc = Rex::Parser::MbsaDocument.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::MbsaDocument.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_mbsa_xml(args = {}, &block) ⇒ Object


5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
# File 'lib/msf/core/db.rb', line 5315

def import_mbsa_xml(args={}, &block)
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  wspace = args[:wspace] || workspace
  if Rex::Parser.nokogiri_loaded
    parser = "Nokogiri v#{::Nokogiri::VERSION}"
    noko_args = args.dup
    noko_args[:blacklist] = bl
    noko_args[:wspace] = wspace
    if block
      yield(:parser, parser)
      import_mbsa_noko_stream(noko_args) {|type, data| yield type,data}
    else
      import_mbsa_noko_stream(noko_args)
    end
    return true
  else # Sorry
    raise DBImportError.new("Could not import due to missing Nokogiri parser. Try 'gem install nokogiri'.")
  end
end

#import_msf_collateral(args = {}, &block) ⇒ Object

Imports loot, tasks, and reports from an MSF ZIP report. XXX: This function is stupidly long. It needs to be refactored.


3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
# File 'lib/msf/core/db.rb', line 3658

def import_msf_collateral(args={}, &block)
  data = ::File.open(args[:filename], "rb") {|f| f.read(f.stat.size)}
  wspace = args[:wspace] || args['wspace'] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  basedir = args[:basedir] || args['basedir'] || ::File.join(Msf::Config.data_directory, "msf")

  allow_yaml = false
  btag = nil

  doc = rexmlify(data)
  if doc.elements["MetasploitExpressV1"]
    m_ver = 1
    allow_yaml = true
    btag = "MetasploitExpressV1"
  elsif doc.elements["MetasploitExpressV2"]
    m_ver = 2
    allow_yaml = true
    btag = "MetasploitExpressV2"
  elsif doc.elements["MetasploitExpressV3"]
    m_ver = 3
    btag = "MetasploitExpressV3"
  elsif doc.elements["MetasploitExpressV4"]
    m_ver = 4
    btag = "MetasploitExpressV4"
  elsif doc.elements["MetasploitV4"]
    m_ver = 4
    btag = "MetasploitV4"
  else
    m_ver = nil
  end
  unless m_ver and btag
    raise DBImportError.new("Unsupported Metasploit XML document format")
  end

  host_info = {}
  doc.elements.each("/#{btag}/hosts/host") do |host|
    host_info[host.elements["id"].text.to_s.strip] = nils_for_nulls(host.elements["address"].text.to_s.strip)
  end

  # Import Loot
  doc.elements.each("/#{btag}/loots/loot") do |loot|
    next if bl.include? host_info[loot.elements["host-id"].text.to_s.strip]
    loot_info              = {}
    loot_info[:host]       = host_info[loot.elements["host-id"].text.to_s.strip]
    loot_info[:workspace]  = args[:wspace]
    loot_info[:ctype]      = nils_for_nulls(loot.elements["content-type"].text.to_s.strip)
    loot_info[:info]       = nils_for_nulls(unserialize_object(loot.elements["info"], allow_yaml))
    loot_info[:ltype]      = nils_for_nulls(loot.elements["ltype"].text.to_s.strip)
    loot_info[:name]       = nils_for_nulls(loot.elements["name"].text.to_s.strip)
    loot_info[:created_at] = nils_for_nulls(loot.elements["created-at"].text.to_s.strip)
    loot_info[:updated_at] = nils_for_nulls(loot.elements["updated-at"].text.to_s.strip)
    loot_info[:name]       = nils_for_nulls(loot.elements["name"].text.to_s.strip)
    loot_info[:orig_path]  = nils_for_nulls(loot.elements["path"].text.to_s.strip)
    loot_info[:task]       = args[:task]
    tmp = args[:ifd][:zip_tmp]
    loot_info[:orig_path].gsub!(/^\./,tmp) if loot_info[:orig_path]
    if !loot.elements["service-id"].text.to_s.strip.empty?
      unless loot.elements["service-id"].text.to_s.strip == "NULL"
        loot_info[:service] = loot.elements["service-id"].text.to_s.strip
      end
    end

    # Only report loot if we actually have it.
    # TODO: Copypasta. Seperate this out.
    if ::File.exists? loot_info[:orig_path]
      loot_dir = ::File.join(basedir,"loot")
      loot_file = ::File.split(loot_info[:orig_path]).last
      if ::File.exists? loot_dir
        unless (::File.directory?(loot_dir) && ::File.writable?(loot_dir))
          raise DBImportError.new("Could not move files to #{loot_dir}")
        end
      else
        ::FileUtils.mkdir_p(loot_dir)
      end
      new_loot = ::File.join(loot_dir,loot_file)
      loot_info[:path] = new_loot
      if ::File.exists?(new_loot)
        ::File.unlink new_loot # Delete it, and don't report it.
      else
        report_loot(loot_info) # It's new, so report it.
      end
      ::FileUtils.copy(loot_info[:orig_path], new_loot)
      yield(:msf_loot, new_loot) if block
    end
  end

  # Import Tasks
  doc.elements.each("/#{btag}/tasks/task") do |task|
    task_info = {}
    task_info[:workspace] = args[:wspace]
    # Should user be imported (original) or declared (the importing user)?
    task_info[:user] = nils_for_nulls(task.elements["created-by"].text.to_s.strip)
    task_info[:desc] = nils_for_nulls(task.elements["description"].text.to_s.strip)
    task_info[:info] = nils_for_nulls(unserialize_object(task.elements["info"], allow_yaml))
    task_info[:mod] = nils_for_nulls(task.elements["module"].text.to_s.strip)
    task_info[:options] = nils_for_nulls(task.elements["options"].text.to_s.strip)
    task_info[:prog] = nils_for_nulls(task.elements["progress"].text.to_s.strip).to_i
    task_info[:created_at] = nils_for_nulls(task.elements["created-at"].text.to_s.strip)
    task_info[:updated_at] = nils_for_nulls(task.elements["updated-at"].text.to_s.strip)
    if !task.elements["completed-at"].text.to_s.empty?
      task_info[:completed_at] = nils_for_nulls(task.elements["completed-at"].text.to_s.strip)
    end
    if !task.elements["error"].text.to_s.empty?
      task_info[:error] = nils_for_nulls(task.elements["error"].text.to_s.strip)
    end
    if !task.elements["result"].text.to_s.empty?
      task_info[:result] = nils_for_nulls(task.elements["result"].text.to_s.strip)
    end
    task_info[:orig_path] = nils_for_nulls(task.elements["path"].text.to_s.strip)
    tmp = args[:ifd][:zip_tmp]
    task_info[:orig_path].gsub!(/^\./,tmp) if task_info[:orig_path]

    # Only report a task if we actually have it.
    # TODO: Copypasta. Seperate this out.
    if ::File.exists? task_info[:orig_path]
      tasks_dir = ::File.join(basedir,"tasks")
      task_file = ::File.split(task_info[:orig_path]).last
      if ::File.exists? tasks_dir
        unless (::File.directory?(tasks_dir) && ::File.writable?(tasks_dir))
          raise DBImportError.new("Could not move files to #{tasks_dir}")
        end
      else
        ::FileUtils.mkdir_p(tasks_dir)
      end
      new_task = ::File.join(tasks_dir,task_file)
      task_info[:path] = new_task
      if ::File.exists?(new_task)
        ::File.unlink new_task # Delete it, and don't report it.
      else
        report_task(task_info) # It's new, so report it.
      end
      ::FileUtils.copy(task_info[:orig_path], new_task)
      yield(:msf_task, new_task) if block
    end
  end

  # Import Reports
  doc.elements.each("/#{btag}/reports/report") do |report|
    tmp = args[:ifd][:zip_tmp]
    report_info              = {}
    report_info[:workspace]  = args[:wspace]
    # Should user be imported (original) or declared (the importing user)?
    report_info[:user]       = nils_for_nulls(report.elements["created-by"].text.to_s.strip)
    report_info[:options]    = nils_for_nulls(report.elements["options"].text.to_s.strip)
    report_info[:rtype]      = nils_for_nulls(report.elements["rtype"].text.to_s.strip)
    report_info[:created_at] = nils_for_nulls(report.elements["created-at"].text.to_s.strip)
    report_info[:updated_at] = nils_for_nulls(report.elements["updated-at"].text.to_s.strip)
    report_info[:orig_path]  = nils_for_nulls(report.elements["path"].text.to_s.strip)
    report_info[:task]       = args[:task]
    report_info[:orig_path].gsub!(/^\./, tmp) if report_info[:orig_path]

    # Only report a report if we actually have it.
    # TODO: Copypasta. Seperate this out.
    if ::File.exists? report_info[:orig_path]
      reports_dir = ::File.join(basedir,"reports")
      report_file = ::File.split(report_info[:orig_path]).last
      if ::File.exists? reports_dir
        unless (::File.directory?(reports_dir) && ::File.writable?(reports_dir))
          raise DBImportError.new("Could not move files to #{reports_dir}")
        end
      else
        ::FileUtils.mkdir_p(reports_dir)
      end
      new_report = ::File.join(reports_dir,report_file)
      report_info[:path] = new_report
      if ::File.exists?(new_report)
        ::File.unlink new_report
      else
        report_report(report_info)
      end
      ::FileUtils.copy(report_info[:orig_path], new_report)
      yield(:msf_report, new_report) if block
    end
  end

end

#import_msf_file(args = {}) ⇒ Object

Import a Metasploit XML file.


3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
# File 'lib/msf/core/db.rb', line 3573

def import_msf_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_msf_xml(args.merge(:data => data))
end

#import_msf_pwdump(args = {}, &block) ⇒ Object

Metasploit PWDump Export

This file format is generated by the db_export -f pwdump and the Metasploit Express and Pro report types of “PWDump.”

This particular block scheme is temporary, since someone is bound to want to import gigantic lists, so we'll want a stream parser eventually (just like the other non-nmap formats).

The file format is: # 1.2.3.4:23/tcp (telnet) username password user2 px01ax02ss2 <BLANK> pass3 user3 <BLANK>

smbuser:sid:lmhash:nthash:

Note the leading hash for the host:port line. Note also all usernames and passwords must be in 7-bit ASCII (character sequences of “x01” will be interpolated – this includes spaces, which must be notated as “x20”. Blank usernames or passwords should be <BLANK>.


3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
# File 'lib/msf/core/db.rb', line 3463

def import_msf_pwdump(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  last_host = nil

  addr  = nil
  port  = nil
  proto = nil
  sname = nil
  ptype = nil
  active = false # Are there cases where imported creds are good? I just hate trusting the import right away.

  data.each_line do |line|
    case line
    when /^[\s]*#/ # Comment lines
      if line[/^#[\s]*([0-9.]+):([0-9]+)(\x2f(tcp|udp))?[\s]*(\x28([^\x29]*)\x29)?/n]
        addr = $1
        port = $2
        proto = $4
        sname = $6
      end
    when /^[\s]*Warning:/
      # Discard warning messages.
      next

    # SMB Hash
    when /^[\s]*([^\s:]+):[0-9]+:([A-Fa-f0-9]+:[A-Fa-f0-9]+):[^\s]*$/
      user = ([nil, "<BLANK>"].include?($1)) ? "" : $1
      pass = ([nil, "<BLANK>"].include?($2)) ? "" : $2
      ptype = "smb_hash"

    # SMB Hash
    when /^[\s]*([^\s:]+):([0-9]+):NO PASSWORD\*+:NO PASSWORD\*+[^\s]*$/
      user = ([nil, "<BLANK>"].include?($1)) ? "" : $1
      pass = ""
      ptype = "smb_hash"

    # SMB Hash with cracked plaintext, or just plain old plaintext
    when /^[\s]*([^\s:]+):(.+):[A-Fa-f0-9]*:[A-Fa-f0-9]*:::$/
      user = ([nil, "<BLANK>"].include?($1)) ? "" : $1
      pass = ([nil, "<BLANK>"].include?($2)) ? "" : $2
      ptype = "password"

    # Must be a user pass
    when /^[\s]*([\x21-\x7f]+)[\s]+([\x21-\x7f]+)?/n
      user = ([nil, "<BLANK>"].include?($1)) ? "" : dehex($1)
      pass = ([nil, "<BLANK>"].include?($2)) ? "" : dehex($2)
      ptype = "password"
    else # Some unknown line not broken by a space.
      next
    end

    next unless [addr,port,user,pass].compact.size == 4
    next unless ipv46_validator(addr) # Skip Malformed addrs
    next unless port[/^[0-9]+$/] # Skip malformed ports
    if bl.include? addr
      next
    else
      yield(:address,addr) if block and addr != last_host
      last_host = addr
    end

    cred_info = {
      :host      => addr,
      :port      => port,
      :user      => user,
      :pass      => pass,
      :type      => ptype,
      :workspace => wspace,
      :task      => args[:task]
    }
    cred_info[:proto] = proto if proto
    cred_info[:sname] = sname if sname
    cred_info[:active] = active

    report_auth_info(cred_info)
    user = pass = ptype = nil
  end

end

#import_msf_zip(args = {}, &block) ⇒ Object

Import a Metasploit Express ZIP file. Note that this requires a fair bit of filesystem manipulation, and is very much tied up with the Metasploit Express ZIP file format export (for obvious reasons). In the event directories exist, they will be reused. If target files exist, they will be overwritten.

XXX: Refactor so it's not quite as sanity-blasting.


3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
# File 'lib/msf/core/db.rb', line 3591

def import_msf_zip(args={}, &block)
  data = args[:data]
  wpsace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []

  new_tmp = ::File.join(Dir::tmpdir,"msf","imp_#{Rex::Text::rand_text_alphanumeric(4)}",@import_filedata[:zip_basename])
  if ::File.exists? new_tmp
    unless (::File.directory?(new_tmp) && ::File.writable?(new_tmp))
      raise DBImportError.new("Could not extract zip file to #{new_tmp}")
    end
  else
    FileUtils.mkdir_p(new_tmp)
  end
  @import_filedata[:zip_tmp] = new_tmp

  # Grab the list of unique basedirs over all entries.
  @import_filedata[:zip_tmp_subdirs] = @import_filedata[:zip_entry_names].map {|x| ::File.split(x)}.map {|x| x[0]}.uniq.reject {|x| x == "."}

  # mkdir all of the base directores we just pulled out, if they don't
  # already exist
  @import_filedata[:zip_tmp_subdirs].each {|sub|
    tmp_subdirs = ::File.join(@import_filedata[:zip_tmp],sub)
    if File.exists? tmp_subdirs
      unless (::File.directory?(tmp_subdirs) && File.writable?(tmp_subdirs))
        # if it exists but we can't write to it, give up
        raise DBImportError.new("Could not extract zip file to #{tmp_subdirs}")
      end
    else
      ::FileUtils.mkdir(tmp_subdirs)
    end
  }

  data.entries.each do |e|
    target = ::File.join(@import_filedata[:zip_tmp],e.name)
    data.extract(e,target)
    if target =~ /^.*.xml$/
      target_data = ::File.open(target, "rb") {|f| f.read 1024}
      if import_filetype_detect(target_data) == :msf_xml
        @import_filedata[:zip_extracted_xml] = target
      end
    end
  end

  # This will kick the newly-extracted XML file through
  # the import_file process all over again.
  if @import_filedata[:zip_extracted_xml]
    new_args = args.dup
    new_args[:filename] = @import_filedata[:zip_extracted_xml]
    new_args[:data] = nil
    new_args[:ifd] = @import_filedata.dup
    if block
      import_file(new_args, &block)
    else
      import_file(new_args)
    end
  end

  # Kick down to all the MSFX ZIP specific items
  if block
    import_msf_collateral(new_args, &block)
  else
    import_msf_collateral(new_args)
  end
end

#import_nessus_nbe(args = {}, &block) ⇒ Object

There is no place the NBE actually stores the plugin name used to scan. You get “Security Note” or “Security Warning,” and that's it.


5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
# File 'lib/msf/core/db.rb', line 5035

def import_nessus_nbe(args={}, &block)
  nbe_data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []

  nbe_copy = nbe_data.dup
  # First pass, just to build the address map.
  addr_map = {}

  # Cache host objects before passing into handle_nessus()
  hobj_map = {}

  nbe_copy.each_line do |line|
    r = line.split('|')
    next if r[0] != 'results'
    next if r[4] != "12053"
    data = r[6]
    addr,hname = data.match(/([0-9\x2e]+) resolves as (.+)\x2e\\n/n)[1,2]
    addr_map[hname] = addr
  end

  nbe_data.each_line do |line|
    r = line.split('|')
    next if r[0] != 'results'
    hname = r[2]
    if addr_map[hname]
      addr = addr_map[hname]
    else
      addr = hname # Must be unresolved, probably an IP address.
    end
    port = r[3]
    nasl = r[4]
    type = r[5]
    data = r[6]

    # If there's no resolution, or if it's malformed, skip it.
    next unless ipv46_validator(addr)

    if bl.include? addr
      next
    else
      yield(:address,addr) if block
    end

    hobj_map[ addr ] ||= report_host(:host => addr, :workspace => wspace, :task => args[:task])

    # Match the NBE types with the XML severity ratings
    case type
    # log messages don't actually have any data, they are just
    # complaints about not being able to perform this or that test
    # because such-and-such was missing
    when "Log Message"; next
    when "Security Hole"; severity = 3
    when "Security Warning"; severity = 2
    when "Security Note"; severity = 1
    # a severity 0 means there's no extra data, it's just an open port
    else; severity = 0
    end
    if nasl == "11936"
      os = data.match(/The remote host is running (.*)\\n/)[1]
      report_note(
        :workspace => wspace,
        :task => args[:task],
        :host => hobj_map[ addr ],
        :type => 'host.os.nessus_fingerprint',
        :data => {
          :os => os.to_s.strip
        }
      )
    end

    next if nasl.to_s.strip.empty?
    plugin_name = nil # NBE doesn't ever populate this
    handle_nessus(wspace, hobj_map[ addr ], port, nasl, plugin_name, severity, data)
  end
end

#import_nessus_nbe_file(args = {}) ⇒ Object

Import Nessus NBE files


5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
# File 'lib/msf/core/db.rb', line 5022

def import_nessus_nbe_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_nessus_nbe(args.merge(:data => data))
end

#import_nessus_xml(args = {}, &block) ⇒ Object


5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
# File 'lib/msf/core/db.rb', line 5157

def import_nessus_xml(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []

  doc = rexmlify(data)
  doc.elements.each('/NessusClientData/Report/ReportHost') do |host|
    hobj = nil
    addr = nil
    hname = nil
    os = nil
    # If the name is resolved, the Nessus plugin for DNS
    # resolution should be there. If not, fall back to the
    # HostName
    host.elements.each('ReportItem') do |item|
      next unless item.elements['pluginID'].text == "12053"
      addr = item.elements['data'].text.match(/([0-9\x2e]+) resolves as/n)[1]
      hname = host.elements['HostName'].text
    end
    addr ||= host.elements['HostName'].text
    next unless ipv46_validator(addr) # Skip resolved names and SCAN-ERROR.
    if bl.include? addr
      next
    else
      yield(:address,addr) if block
    end

    hinfo = {
      :workspace => wspace,
      :host => addr,
      :task => args[:task]
    }

    # Record the hostname
    hinfo.merge!(:name => hname.to_s.strip) if hname
    hobj = report_host(hinfo)
    report_import_note(wspace,hobj)

    # Record the OS
    os ||= host.elements["os_name"]
    if os
      report_note(
        :workspace => wspace,
        :task => args[:task],
        :host => hobj,
        :type => 'host.os.nessus_fingerprint',
        :data => {
          :os => os.text.to_s.strip
        }
      )
    end

    host.elements.each('ReportItem') do |item|
      nasl = item.elements['pluginID'].text
      plugin_name = item.elements['pluginName'].text
      port = item.elements['port'].text
      data = item.elements['data'].text
      severity = item.elements['severity'].text

      handle_nessus(wspace, hobj, port, nasl, plugin_name, severity, data, args[:task])
    end
  end
end

#import_nessus_xml_file(args = {}) ⇒ Object

Import Nessus XML v1 and v2 output

Old versions of openvas exported this as well


5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
# File 'lib/msf/core/db.rb', line 5141

def import_nessus_xml_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end

  if data.index("NessusClientData_v2")
    import_nessus_xml_v2(args.merge(:data => data))
  else
    import_nessus_xml(args.merge(:data => data))
  end
end

#import_nessus_xml_v2(args = {}, &block) ⇒ Object


5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
# File 'lib/msf/core/db.rb', line 5221

def import_nessus_xml_v2(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []

  #@host = {
      #'hname'             => nil,
      #'addr'              => nil,
      #'mac'               => nil,
      #'os'                => nil,
      #'ports'             => [ 'port' => {    'port'               => nil,
      #         'svc_name'              => nil,
      #         'proto'               => nil,
      #         'severity'              => nil,
      #         'nasl'                => nil,
      #         'description'           => nil,
      #         'cve'                   => [],
      #         'bid'                   => [],
      #         'xref'                  => []
      #       }
      #     ]
      #}
  parser = Rex::Parser::NessusXMLStreamParser.new
  parser.on_found_host = Proc.new { |host|

    hobj = nil
    addr = host['addr'] || host['hname']

    next unless ipv46_validator(addr) # Catches SCAN-ERROR, among others.

    if bl.include? addr
      next
    else
      yield(:address,addr) if block
    end

    os = host['os']
    hname = host['hname']
    mac = host['mac']

    host_info = {
      :workspace => wspace,
      :host => addr,
      :task => args[:task]
    }
    host_info[:name] = hname.to_s.strip if hname
    # Short mac, protect against Nessus's habit of saving multiple macs
    # We can't use them anyway, so take just the first.
    host_info[:mac]  = mac.to_s.strip.upcase.split(/\s+/).first if mac

    hobj = report_host(host_info)
    report_import_note(wspace,hobj)

    os = host['os']
    yield(:os,os) if block
    if os
      report_note(
        :workspace => wspace,
        :task => args[:task],
        :host => hobj,
        :type => 'host.os.nessus_fingerprint',
        :data => {
          :os => os.to_s.strip
        }
      )
    end

    host['ports'].each do |item|
      next if item['port'] == 0
      msf = nil
      nasl = item['nasl'].to_s
      nasl_name = item['nasl_name'].to_s
      port = item['port'].to_s
      proto = item['proto'] || "tcp"
      sname = item['svc_name']
      severity = item['severity']
      description = item['description']
      cve = item['cve']
      bid = item['bid']
      xref = item['xref']
      msf = item['msf']

      yield(:port,port) if block

      handle_nessus_v2(wspace, hobj, port, proto, sname, nasl, nasl_name, severity, description, cve, bid, xref, msf, args[:task])

    end
    yield(:end,hname) if block
  }

  REXML::Document.parse_stream(data, parser)

end

#import_netsparker_xml(args = {}, &block) ⇒ Object

Process NetSparker XML


4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
# File 'lib/msf/core/db.rb', line 4304

def import_netsparker_xml(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  addr = nil
  parser = Rex::Parser::NetSparkerXMLStreamParser.new
  parser.on_found_vuln = Proc.new do |vuln|
    data = {:workspace => wspace}

    # Parse the URL
    url  = vuln['url']
    return if not url

    # Crack the URL into a URI
    uri = URI(url) rescue nil
    return if not uri

    # Resolve the host and cache the IP
    if not addr
      baddr = Rex::Socket.addr_aton(uri.host) rescue nil
      if baddr
        addr = Rex::Socket.addr_ntoa(baddr)
        yield(:address, addr) if block
      end
    end

    # Bail early if we have no IP address
    if not addr
      raise Interrupt, "Not a valid IP address"
    end

    if bl.include?(addr)
      raise Interrupt, "IP address is on the blacklist"
    end

    data[:host]  = addr
    data[:vhost] = uri.host
    data[:port]  = uri.port
    data[:ssl]   = (uri.scheme == "ssl")

    body = nil
    # First report a web page
    if vuln['response']
      headers = {}
      code    = 200
      head,body = vuln['response'].to_s.split(/\r?\n\r?\n/, 2)
      if body

        if head =~ /^HTTP\d+\.\d+\s+(\d+)\s*/
          code = $1.to_i
        end

        headers = {}
        head.split(/\r?\n/).each do |line|
          hname,hval = line.strip.split(/\s*:\s*/, 2)
          next if hval.to_s.strip.empty?
          headers[hname.downcase] ||= []
          headers[hname.downcase] << hval
        end

        info = {
          :path     => uri.path,
          :query    => uri.query,
          :code     => code,
          :body     => body,
          :headers  => headers,
          :task     => args[:task]
        }
        info.merge!(data)

        if headers['content-type']
          info[:ctype] = headers['content-type'][0]
        end

        if headers['set-cookie']
          info[:cookie] = headers['set-cookie'].join("\n")
        end

        if headers['authorization']
          info[:auth] = headers['authorization'].join("\n")
        end

        if headers['location']
          info[:location] = headers['location'][0]
        end

        if headers['last-modified']
          info[:mtime] = headers['last-modified'][0]
        end

        # Report the web page to the database
        report_web_page(info)

        yield(:web_page, url) if block
      end
    end # End web_page reporting


    details = netsparker_vulnerability_map(vuln)

    method = netsparker_method_map(vuln)
    pname  = netsparker_pname_map(vuln)
    params = netsparker_params_map(vuln)

    proof  = ''

    if vuln['info'] and vuln['info'].length > 0
      proof << vuln['info'].map{|x| "#{x[0]}: #{x[1]}\n" }.join + "\n"
    end

    if proof.empty?
      if body
        proof << body + "\n"
      else
        proof << vuln['response'].to_s + "\n"
      end
    end

    if params.empty? and pname
      params = [[pname, vuln['vparam_name'].to_s]]
    end

    info = {
      # XXX: There is a :request attr in the model, but report_web_vuln
      # doesn't seem to know about it, so this gets ignored.
      #:request  => vuln['request'],
      :path        => uri.path,
      :query       => uri.query,
      :method      => method,
      :params      => params,
      :pname       => pname.to_s,
      :proof       => proof,
      :risk        => details[:risk],
      :name        => details[:name],
      :blame       => details[:blame],
      :category    => details[:category],
      :description => details[:description],
      :confidence  => details[:confidence],
      :task        => args[:task]
    }
    info.merge!(data)

    next if vuln['type'].to_s.empty?

    report_web_vuln(info)
    yield(:web_vuln, url) if block
  end

  # We throw interrupts in our parser when the job is hopeless
  begin
    REXML::Document.parse_stream(data, parser)
  rescue ::Interrupt => e
    wlog("The netsparker_xml_import() job was interrupted: #{e}")
  end
end

#import_netsparker_xml_file(args = {}) ⇒ Object

Process a NetSparker XML file


4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
# File 'lib/msf/core/db.rb', line 4292

def import_netsparker_xml_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_netsparker_xml(args.merge(:data => data))
end

#import_nexpose_noko_stream(args, &block) ⇒ Object


4711
4712
4713
4714
4715
4716
4717
4718
4719
# File 'lib/msf/core/db.rb', line 4711

def import_nexpose_noko_stream(args, &block)
  if block
    doc = Rex::Parser::NexposeSimpleDocument.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::NexposeSimpleDocument.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_nexpose_raw_noko_stream(args, &block) ⇒ Object


4701
4702
4703
4704
4705
4706
4707
4708
4709
# File 'lib/msf/core/db.rb', line 4701

def import_nexpose_raw_noko_stream(args, &block)
  if block
    doc = Rex::Parser::NexposeRawDocument.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::NexposeRawDocument.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_nexpose_rawxml(args = {}, &block) ⇒ Object


3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
# File 'lib/msf/core/db.rb', line 3991

def import_nexpose_rawxml(args={}, &block)
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  wspace = args[:wspace] || workspace
  if Rex::Parser.nokogiri_loaded
    parser = "Nokogiri v#{::Nokogiri::VERSION}"
    noko_args = args.dup
    noko_args[:blacklist] = bl
    noko_args[:wspace] = wspace
    if block
      yield(:parser, parser)
      import_nexpose_raw_noko_stream(noko_args) {|type, data| yield type,data}
    else
      import_nexpose_raw_noko_stream(noko_args)
    end
    return true
  end
  data = args[:data]

  # Use a stream parser instead of a tree parser so we can deal with
  # huge results files without running out of memory.
  parser = Rex::Parser::NexposeXMLStreamParser.new

  # Since all the Refs have to be in the database before we can use them
  # in a Vuln, we store all the hosts until we finish parsing and only
  # then put everything in the database.  This is memory-intensive for
  # large files, but should be much less so than a tree parser.
  #
  # This method is also considerably faster than parsing through the tree
  # looking for references every time we hit a vuln.
  hosts = []
  vulns = []

  # The callback merely populates our in-memory table of hosts and vulns
  parser.callback = Proc.new { |type, value|
    case type
    when :host
      # XXX: Blacklist should be checked here instead of saving a
      # host we're just going to throw away later
      hosts.push(value)
    when :vuln
      value["id"] = value["id"].downcase if value["id"]
      vulns.push(value)
    end
  }

  REXML::Document.parse_stream(data, parser)

  vuln_refs = nexpose_refs_to_struct(vulns)
  hosts.each do |host|
    if bl.include? host["addr"]
      next
    else
      yield(:address,host["addr"]) if block
    end
    nexpose_host_from_rawxml(host, vuln_refs, wspace)
  end
end

#import_nexpose_rawxml_file(args = {}) ⇒ Object

Nexpose Raw XML


3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
# File 'lib/msf/core/db.rb', line 3980

def import_nexpose_rawxml_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_nexpose_rawxml(args.merge(:data => data))
end

#import_nexpose_simplexml(args = {}, &block) ⇒ Object


3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
# File 'lib/msf/core/db.rb', line 3840

def import_nexpose_simplexml(args={}, &block)
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  wspace = args[:wspace] || workspace
  if Rex::Parser.nokogiri_loaded
    parser = "Nokogiri v#{::Nokogiri::VERSION}"
    noko_args = args.dup
    noko_args[:blacklist] = bl
    noko_args[:wspace] = wspace
    if block
      yield(:parser, parser)
      import_nexpose_noko_stream(noko_args) {|type, data| yield type,data}
    else
      import_nexpose_noko_stream(noko_args)
    end
    return true
  end
  data = args[:data]

  doc = rexmlify(data)
  doc.elements.each('/NeXposeSimpleXML/devices/device') do |dev|
    addr = dev.attributes['address'].to_s
    if bl.include? addr
      next
    else
      yield(:address,addr) if block
    end

    fprint = {}

    dev.elements.each('fingerprint/description') do |str|
      fprint[:desc] = str.text.to_s.strip
    end
    dev.elements.each('fingerprint/vendor') do |str|
      fprint[:vendor] = str.text.to_s.strip
    end
    dev.elements.each('fingerprint/family') do |str|
      fprint[:family] = str.text.to_s.strip
    end
    dev.elements.each('fingerprint/product') do |str|
      fprint[:product] = str.text.to_s.strip
    end
    dev.elements.each('fingerprint/version') do |str|
      fprint[:version] = str.text.to_s.strip
    end
    dev.elements.each('fingerprint/architecture') do |str|
      fprint[:arch] = str.text.to_s.upcase.strip
    end

    conf = {
      :workspace => wspace,
      :host      => addr,
      :state     => Msf::HostState::Alive,
      :task      => args[:task]
    }

    host = report_host(conf)
    report_import_note(wspace, host)

    report_note(
      :workspace => wspace,
      :host      => host,
      :type      => 'host.os.nexpose_fingerprint',
      :data      => fprint,
      :task      => args[:task]
    )

    # Load vulnerabilities not associated with a service
    dev.elements.each('vulnerabilities/vulnerability') do |vuln|
      vid  = vuln.attributes['id'].to_s.downcase
      refs = process_nexpose_data_sxml_refs(vuln)
      next if not refs
      report_vuln(
        :workspace => wspace,
        :host      => host,
        :name      => 'NEXPOSE-' + vid,
        :info      => vid,
        :refs      => refs,
        :task      => args[:task]
      )
    end

    # Load the services
    dev.elements.each('services/service') do |svc|
      sname = svc.attributes['name'].to_s
      sprot = svc.attributes['protocol'].to_s.downcase
      sport = svc.attributes['port'].to_s.to_i
      next if sport == 0

      name = sname.split('(')[0].strip
      info = ''

      svc.elements.each('fingerprint/description') do |str|
        info = str.text.to_s.strip
      end

      if(sname.downcase != '<unknown>')
        report_service(
            :workspace => wspace,
            :host      => host,
            :proto     => sprot,
            :port      => sport,
            :name      => name,
            :info      => info,
            :task      => args[:task]
        )
      else
        report_service(
            :workspace => wspace,
            :host      => host,
            :proto     => sprot,
            :port      => sport,
            :info      => info,
            :task      => args[:task]
        )
      end

      # Load vulnerabilities associated with this service
      svc.elements.each('vulnerabilities/vulnerability') do |vuln|
        vid  = vuln.attributes['id'].to_s.downcase
        refs = process_nexpose_data_sxml_refs(vuln)
        next if not refs
        report_vuln(
            :workspace => wspace,
            :host      => host,
            :port      => sport,
            :proto     => sprot,
            :name      => 'NEXPOSE-' + vid,
            :info      => vid,
            :refs      => refs,
            :task      => args[:task]
        )
      end
    end
  end
end

#import_nexpose_simplexml_file(args = {}) ⇒ Object

Nexpose Simple XML

XXX At some point we'll want to make this a stream parser for dealing with large results files


3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
# File 'lib/msf/core/db.rb', line 3561

def import_nexpose_simplexml_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_nexpose_simplexml(args.merge(:data => data))
end

#import_nikto_xml(args = {}, &block) ⇒ Object

Imports Nikto scan data from -Format xml as notes.


3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
# File 'lib/msf/core/db.rb', line 3109

def import_nikto_xml(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  doc = rexmlify(data)
  doc.elements.each do |f|
    f.elements.each('scandetails') do |host|
      # Get host information
      addr = host.attributes['targetip']
      next if not addr
      if bl.include? addr
        next
      else
        yield(:address,addr) if block
      end
      # Get service information
      port = host.attributes['targetport']
      next if port.to_i == 0
      uri = URI.parse(host.attributes['sitename']) rescue nil
      next unless uri and uri.scheme
      # Collect and report scan descriptions.
      host.elements.each do |item|
        if item.elements['description']
          desc_text = item.elements['description'].text
          next if desc_text.nil? or desc_text.empty?
          desc_data = {
              :workspace => wspace,
              :host      => addr,
              :type      => "service.nikto.scan.description",
              :data      => desc_text,
              :proto     => "tcp",
              :port      => port.to_i,
              :sname     => uri.scheme,
              :update    => :unique_data,
              :task      => args[:task]
          }
          # Always report it as a note.
          report_note(desc_data)
          # Sometimes report it as a vuln, too.
          # XXX: There's a Vuln.info field but nothing reads from it? See Bug #5837
          if item.attributes['osvdbid'].to_i != 0
            desc_data[:refs] = ["OSVDB-#{item.attributes['osvdbid']}"]
            desc_data[:name] = "NIKTO-#{item.attributes['id']}"
            desc_data.delete(:data)
            desc_data.delete(:type)
            desc_data.delete(:update)
            report_vuln(desc_data)
          end
        end
      end
    end
  end
end

#import_nmap_noko_stream(args, &block) ⇒ Object


4721
4722
4723
4724
4725
4726
4727
4728
4729
# File 'lib/msf/core/db.rb', line 4721

def import_nmap_noko_stream(args, &block)
  if block
    doc = Rex::Parser::NmapDocument.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::NmapDocument.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_nmap_xml(args = {}) {|:parser, parser.class.name| ... } ⇒ Object

If you have Nokogiri installed, you'll be shunted over to that. Otherwise, you'll hit the old NmapXMLStreamParser.

Yields:

  • (:parser, parser.class.name)

4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
# File 'lib/msf/core/db.rb', line 4733

def import_nmap_xml(args={}, &block)
  return nil if args[:data].nil? or args[:data].empty?
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []

  if Rex::Parser.nokogiri_loaded
    noko_args = args.dup
    noko_args[:blacklist] = bl
    noko_args[:wspace] = wspace
    if block
      yield(:parser, "Nokogiri v#{::Nokogiri::VERSION}")
      import_nmap_noko_stream(noko_args) {|type, data| yield type,data }
    else
      import_nmap_noko_stream(noko_args)
    end
    return true
  end

  # XXX: Legacy nmap xml parser starts here.

  fix_services = args[:fix_services]
  data = args[:data]

  # Use a stream parser instead of a tree parser so we can deal with
  # huge results files without running out of memory.
  parser = Rex::Parser::NmapXMLStreamParser.new
  yield(:parser, parser.class.name) if block

  # Whenever the parser pulls a host out of the nmap results, store
  # it, along with any associated services, in the database.
  parser.on_found_host = Proc.new { |h|
    hobj = nil
    data = {:workspace => wspace}
    if (h["addrs"].has_key?("ipv4"))
      addr = h["addrs"]["ipv4"]
    elsif (h["addrs"].has_key?("ipv6"))
      addr = h["addrs"]["ipv6"]
    else
      # Can't report it if it doesn't have an IP
      raise RuntimeError, "At least one IPv4 or IPv6 address is required"
    end
    next if bl.include? addr
    data[:host] = addr
    if (h["addrs"].has_key?("mac"))
      data[:mac] = h["addrs"]["mac"]
    end
    data[:state] = (h["status"] == "up") ? Msf::HostState::Alive : Msf::HostState::Dead
    data[:task] = args[:task]

    if ( h["reverse_dns"] )
      data[:name] = h["reverse_dns"]
    end

    # Only report alive hosts with ports to speak of.
    if(data[:state] != Msf::HostState::Dead)
      if h["ports"].size > 0
        if fix_services
          port_states = h["ports"].map {|p| p["state"]}.reject {|p| p == "filtered"}
          next if port_states.compact.empty?
        end
        yield(:address,data[:host]) if block
        hobj = report_host(data)
        report_import_note(wspace,hobj)
      end
    end

    if( h["os_vendor"] )
      note = {
        :workspace => wspace,
        :host => hobj || addr,
        :type => 'host.os.nmap_fingerprint',
        :task => args[:task],
        :data => {
          :os_vendor   => h["os_vendor"],
          :os_family   => h["os_family"],
          :os_version  => h["os_version"],
          :os_accuracy => h["os_accuracy"]
        }
      }

      if(h["os_match"])
        note[:data][:os_match] = h['os_match']
      end

      report_note(note)
    end

    if (h["last_boot"])
      report_note(
        :workspace => wspace,
        :host => hobj || addr,
        :type => 'host.last_boot',
        :task => args[:task],
        :data => {
          :time => h["last_boot"]
        }
      )
    end

    if (h["trace"])
      hops = []
      h["trace"]["hops"].each do |hop|
        hops << {
          "ttl"     => hop["ttl"].to_i,
          "address" => hop["ipaddr"].to_s,
          "rtt"     => hop["rtt"].to_f,
          "name"    => hop["host"].to_s
        }
      end
      report_note(
        :workspace => wspace,
        :host => hobj || addr,
        :type => 'host.nmap.traceroute',
        :task => args[:task],
        :data => {
          'port'  => h["trace"]["port"].to_i,
          'proto' => h["trace"]["proto"].to_s,
          'hops'  => hops
        }
      )
    end


    # Put all the ports, regardless of state, into the db.
    h["ports"].each { |p|
      # Localhost port results are pretty unreliable -- if it's
      # unknown, it's no good (possibly Windows-only)
      if (
        p["state"] == "unknown" &&
        h["status_reason"] == "localhost-response"
      )
        next
      end
      extra = ""
      extra << p["product"]   + " " if p["product"]
      extra << p["version"]   + " " if p["version"]
      extra << p["extrainfo"] + " " if p["extrainfo"]

      data = {}
      data[:workspace] = wspace
      if fix_services
        data[:proto] = nmap_msf_service_map(p["protocol"])
      else
        data[:proto] = p["protocol"].downcase
      end
      data[:port]  = p["portid"].to_i
      data[:state] = p["state"]
      data[:host]  = hobj || addr
      data[:info]  = extra if not extra.empty?
      data[:task]  = args[:task]
      if p["name"] != "unknown"
        data[:name] = p["name"]
      end
      report_service(data)
    }
    #Parse the scripts output
    if h["scripts"]
      h["scripts"].each do |key,val|
        if key == "smb-check-vulns"
          if val =~ /MS08-067: VULNERABLE/
            vuln_info = {
              :workspace => wspace,
              :task => args[:task],
              :host =>  hobj || addr,
              :port => 445,
              :proto => 'tcp',
              :name => 'MS08-067',
              :info => 'Microsoft Windows Server Service Crafted RPC Request Handling Unspecified Remote Code Execution',
              :refs =>['CVE-2008-4250',
                'BID-31874',
                'OSVDB-49243',
                'CWE-94',
                'MSFT-MS08-067',
                'MSF-Microsoft Server Service Relative Path Stack Corruption',
                'NSS-34476']
            }
            report_vuln(vuln_info)
          end
          if val =~ /MS06-025: VULNERABLE/
            vuln_info = {
              :workspace => wspace,
              :task => args[:task],
              :host =>  hobj || addr,
              :port => 445,
              :proto => 'tcp',
              :name => 'MS06-025',
              :info => 'Vulnerability in Routing and Remote Access Could Allow Remote Code Execution',
              :refs =>['CVE-2006-2370',
                'CVE-2006-2371',
                'BID-18325',
                'BID-18358',
                'BID-18424',
                'OSVDB-26436',
                'OSVDB-26437',
                'MSFT-MS06-025',
                'MSF-Microsoft RRAS Service RASMAN Registry Overflow',
                'NSS-21689']
            }
            report_vuln(vuln_info)
          end
          # This one has NOT been  Tested , remove this comment if confirmed working
          if val =~ /MS07-029: VULNERABLE/
            vuln_info = {
              :workspace => wspace,
              :task => args[:task],
              :host =>  hobj || addr,
              :port => 445,
              :proto => 'tcp',
              :name => 'MS07-029',
              :info => 'Vulnerability in Windows DNS RPC Interface Could Allow Remote Code Execution',
              # Add more refs based on nessus/nexpose .. results
              :refs =>['CVE-2007-1748',
                'OSVDB-34100',
                'MSF-Microsoft DNS RPC Service extractQuotedChar()',
                'NSS-25168']
            }
            report_vuln(vuln_info)
          end
        end
      end
    end
  }

  # XXX: Legacy nmap xml parser ends here.

  REXML::Document.parse_stream(data, parser)
end

#import_nmap_xml_file(args = {}) ⇒ Object

Import Nmap's -oX xml output


4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
# File 'lib/msf/core/db.rb', line 4690

def import_nmap_xml_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_nmap_xml(args.merge(:data => data))
end

#import_openvas_new_xml(args = {}, &block) ⇒ Object


3195
3196
3197
3198
3199
3200
3201
3202
3203
# File 'lib/msf/core/db.rb', line 3195

def import_openvas_new_xml(args={}, &block)
  if block
    doc = Rex::Parser::OpenVASDocument.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::OpenVASDocument.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_openvas_new_xml_file(args = {}) ⇒ Object


3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
# File 'lib/msf/core/db.rb', line 3184

def import_openvas_new_xml_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_wapiti_xml(args.merge(:data => data))
end

#import_openvas_xml(args = {}, &block) ⇒ Object

Of course they had to change the nessus format.

Raises:


5115
5116
5117
5118
5119
5120
# File 'lib/msf/core/db.rb', line 5115

def import_openvas_xml(args={}, &block)
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  raise DBImportError.new("No OpenVAS XML support. Please submit a patch to msfdev[at]metasploit.com")
end

#import_outpost24_noko_stream(args = {}, &block) ⇒ Object


5956
5957
5958
5959
5960
5961
5962
5963
5964
# File 'lib/msf/core/db.rb', line 5956

def import_outpost24_noko_stream(args={},&block)
  if block
    doc = Rex::Parser::Outpost24Document.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::Outpost24Document.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_outpost24_xml(args = {}, &block) ⇒ Object


5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
# File 'lib/msf/core/db.rb', line 5936

def import_outpost24_xml(args={}, &block)
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  wspace = args[:wspace] || workspace
  if Rex::Parser.nokogiri_loaded
    parser = "Nokogiri v#{::Nokogiri::VERSION}"
    noko_args = args.dup
    noko_args[:blacklist] = bl
    noko_args[:wspace] = wspace
    if block
      yield(:parser, parser)
      import_outpost24_noko_stream(noko_args) {|type, data| yield type,data}
    else
      import_outpost24_noko_stream(noko_args)
    end
    return true
  else # Sorry
    raise DBImportError.new("Could not import due to missing Nokogiri parser. Try 'gem install nokogiri'.")
  end
end

#import_qualys_asset_xml(args = {}, &block) ⇒ Object

Import Qualys's Asset Data Report format


5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
# File 'lib/msf/core/db.rb', line 5673

def import_qualys_asset_xml(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  doc = rexmlify(data)
  vuln_refs = find_qualys_asset_vuln_refs(doc)

  # 2nd pass, actually grab the hosts.
  doc.elements.each("/ASSET_DATA_REPORT/HOST_LIST/HOST") do |host|
    hobj = nil
    addr = host.elements["IP"].text if host.elements["IP"]
    next unless validate_ips(addr)
    if bl.include? addr
      next
    else
      yield(:address,addr) if block
    end
    hname = ( # Prefer NetBIOS over DNS
      (host.elements["NETBIOS"].text if host.elements["NETBIOS"]) ||
       (host.elements["DNS"].text if host.elements["DNS"]) ||
       "" )
    hobj = report_host(:workspace => wspace, :host => addr, :name => hname, :state => Msf::HostState::Alive, :task => args[:task])
    report_import_note(wspace,hobj)

    if host.elements["OPERATING_SYSTEM"]
      hos = host.elements["OPERATING_SYSTEM"].text
      report_note(
        :workspace => wspace,
        :task => args[:task],
        :host => hobj,
        :type => 'host.os.qualys_fingerprint',
        :data => { :os => hos }
      )
    end

    # Report open ports.
    find_qualys_asset_ports(82023,host,wspace,hobj, args[:task]) # TCP
    find_qualys_asset_ports(82004,host,wspace,hobj, args[:task]) # UDP

    # Report vulns
    find_qualys_asset_vulns(host,wspace,hobj,vuln_refs, args[:task],&block)

  end # host

end

#import_qualys_scan_xml(args = {}, &block) ⇒ Object


5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
# File 'lib/msf/core/db.rb', line 5733

def import_qualys_scan_xml(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []


  doc = rexmlify(data)
  doc.elements.each('/SCAN/IP') do |host|
    hobj = nil
    addr  = host.attributes['value']
    if bl.include? addr
      next
    else
      yield(:address,addr) if block
    end
    hname = host.attributes['name'] || ''

    hobj = report_host(:workspace => wspace, :host => addr, :name => hname, :state => Msf::HostState::Alive, :task => args[:task])
    report_import_note(wspace,hobj)

    if host.elements["OS"]
      hos = host.elements["OS"].text
      report_note(
        :workspace => wspace,
        :task => args[:task],
        :host => hobj,
        :type => 'host.os.qualys_fingerprint',
        :data => {
          :os => hos
        }
      )
    end

    # Open TCP Services List (Qualys ID 82023)
    services_tcp = host.elements["SERVICES/CAT/SERVICE[@number='82023']/RESULT"]
    if services_tcp
      services_tcp.text.scan(/([0-9]+)\t(.*?)\t.*?\t([^\t\n]*)/) do |match|
        if match[2] == nil or match[2].strip == 'unknown'
          name = match[1].strip
        else
          name = match[2].strip
        end
        handle_qualys(wspace, hobj, match[0].to_s, 'tcp', 0, nil, nil, name, nil, args[:task])
      end
    end
    # Open UDP Services List (Qualys ID 82004)
    services_udp = host.elements["SERVICES/CAT/SERVICE[@number='82004']/RESULT"]
    if services_udp
      services_udp.text.scan(/([0-9]+)\t(.*?)\t.*?\t([^\t\n]*)/) do |match|
        if match[2] == nil or match[2].strip == 'unknown'
          name = match[1].strip
        else
          name = match[2].strip
        end
        handle_qualys(wspace, hobj, match[0].to_s, 'udp', 0, nil, nil, name, nil, args[:task])
      end
    end

    # VULNS are confirmed, PRACTICES are unconfirmed vulnerabilities
    host.elements.each('VULNS/CAT | PRACTICES/CAT') do |cat|
      port = cat.attributes['port']
      protocol = cat.attributes['protocol']
      cat.elements.each('VULN | PRACTICE') do |vuln|
        refs = []
        qid = vuln.attributes['number']
        severity = vuln.attributes['severity']
        title = vuln.elements['TITLE'].text.to_s
        vuln.elements.each('VENDOR_REFERENCE_LIST/VENDOR_REFERENCE') do |ref|
          refs.push(ref.elements['ID'].text.to_s)
        end
        vuln.elements.each('CVE_ID_LIST/CVE_ID') do |ref|
          refs.push('CVE-' + /C..-([0-9\-]{9})/.match(ref.elements['ID'].text.to_s)[1])
        end
        vuln.elements.each('BUGTRAQ_ID_LIST/BUGTRAQ_ID') do |ref|
          refs.push('BID-' + ref.elements['ID'].text.to_s)
        end

        handle_qualys(wspace, hobj, port, protocol, qid, severity, refs, nil,title, args[:task])
      end
    end
  end
end

#import_qualys_scan_xml_file(args = {}) ⇒ Object

Import Qualys' Scan xml output


5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
# File 'lib/msf/core/db.rb', line 5722

def import_qualys_scan_xml_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_qualys_scan_xml(args.merge(:data => data))
end

#import_retina_xml(args = {}) {|:warning, msg| ... } ⇒ Object

Process Retina XML

Yields:

  • (:warning, msg)

4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
# File 'lib/msf/core/db.rb', line 4211

def import_retina_xml(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  msg =  "Warning: The Retina XML format does not associate vulnerabilities with the\n"
  msg << "specific service on which they were found.\n"
  msg << "This makes it impossible to correlate exploits to discovered vulnerabilities\n"
  msg << "in a reliable fashion."

  yield(:warning,msg) if block

  parser = Rex::Parser::RetinaXMLStreamParser.new
  parser.on_found_host = Proc.new do |host|
    hobj = nil
    data = {:workspace => wspace}
    addr = host['address']
    next if not addr

    next if bl.include? addr
    data[:host] = addr

    if host['mac']
      data[:mac] = host['mac']
    end

    data[:state] = Msf::HostState::Alive

    if host['hostname']
      data[:name] = host['hostname']
    end

    if host['netbios']
      data[:name] = host['netbios']
    end

    yield(:address, data[:host]) if block

    # Import Host
    hobj = report_host(data)
    report_import_note(wspace, hobj)

    # Import OS fingerprint
    if host["os"]
      note = {
          :workspace => wspace,
          :host      => addr,
          :type      => 'host.os.retina_fingerprint',
          :task      => args[:task],
          :data      => {
              :os => host["os"]
          }
      }
      report_note(note)
    end

    # Import vulnerabilities
    host['vulns'].each do |vuln|
      refs = vuln['refs'].map{|v| v.join("-")}
      refs << "RETINA-#{vuln['rthid']}" if vuln['rthid']

      vuln_info = {
          :workspace => wspace,
          :host      => addr,
          :name      => vuln['name'],
          :info      => vuln['description'],
          :refs      => refs,
          :task      => args[:task]
      }

      report_vuln(vuln_info)
    end
  end

  REXML::Document.parse_stream(data, parser)
end

#import_retina_xml_file(args = {}) ⇒ Object

Process a Retina XML file


4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
# File 'lib/msf/core/db.rb', line 4199

def import_retina_xml_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_retina_xml(args.merge(:data => data))
end

#import_spiceworks_csv(args = {}, &block) ⇒ Object


3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
# File 'lib/msf/core/db.rb', line 3403

def import_spiceworks_csv(args={}, &block)
  data = args[:data]
  wspace = args[:wspace] || workspace
  bl = validate_ips(args[:blacklist]) ? args[:blacklist].split : []
  CSV.parse(data) do |row|
    next unless (["Name", "Manufacturer", "Device Type"] & row).empty? #header
    name = row[0]
    manufacturer = row[1]
    device = row[2]
    model = row[3]
    ip = row[4]
    serialno = row[5]
    location = row[6]
    os = row[7]

    next unless ip
    next if bl.include? ip

    conf = {
    :workspace => wspace,
    :host      => ip,
    :name      => name,
    :task      => args[:task]
    }

    conf[:os_name] = os if os

    info = []
    info << "Serial Number: #{serialno}" unless (serialno.blank? or serialno == name)
    info << "Location: #{location}" unless location.blank?
    conf[:info] = info.join(", ") unless info.empty?

    host = report_host(conf)
    report_import_note(wspace, host)
  end
end

#import_wapiti_xml(args = {}, &block) ⇒ Object


3174
3175
3176
3177
3178
3179
3180
3181
3182
# File 'lib/msf/core/db.rb', line 3174

def import_wapiti_xml(args={}, &block)
  if block
    doc = Rex::Parser::WapitiDocument.new(args,framework.db) {|type, data| yield type,data }
  else
    doc = Rex::Parser::WapitiDocument.new(args,self)
  end
  parser = ::Nokogiri::XML::SAX::Parser.new(doc)
  parser.parse(args[:data])
end

#import_wapiti_xml_file(args = {}) ⇒ Object


3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
# File 'lib/msf/core/db.rb', line 3163

def import_wapiti_xml_file(args={})
  filename = args[:filename]
  wspace = args[:wspace] || workspace

  data = ""
  ::File.open(filename, 'rb') do |f|
    data = f.read(f.stat.size)
  end
  import_wapiti_xml(args.merge(:data => data))
end

#initialize_database_supportObject

Do what is necessary to load our database support


84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/msf/core/db_manager.rb', line 84

def initialize_database_support
  begin
    # Database drivers can reset our KCODE, do not let them
    $KCODE = 'NONE' if RUBY_VERSION =~ /^1\.8\./

    require "active_record"

    initialize_metasploit_data_models

    @usable = true

  rescue ::Exception => e
    self.error = e
    elog("DB is not enabled due to load error: #{e}")
    return false
  end

  # Only include Mdm if we're not using Metasploit commercial versions
  # If Mdm::Host is defined, the dynamically created classes
  # are already in the object space
  begin
    unless defined? Mdm::Host
      MetasploitDataModels.require_models
    end
  rescue NameError => e
    warn_about_rubies
    raise e
  end

  #
  # Determine what drivers are available
  #
  initialize_drivers

  #
  # Instantiate the database sink
  #
  initialize_sink

  true
end

#initialize_driversObject

Scan through available drivers


129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/msf/core/db_manager.rb', line 129

def initialize_drivers
  self.drivers = []
  tdrivers = %W{ postgresql }
  tdrivers.each do |driver|
    begin
      ActiveRecord::Base.default_timezone = :utc
      ActiveRecord::Base.establish_connection(:adapter => driver)
      if(self.respond_to?("driver_check_#{driver}"))
        self.send("driver_check_#{driver}")
      end
      ActiveRecord::Base.remove_connection
      self.drivers << driver
    rescue ::Exception
    end
  end

  if(not self.drivers.empty?)
    self.driver = self.drivers[0]
  end

  # Database drivers can reset our KCODE, do not let them
  $KCODE = 'NONE' if RUBY_VERSION =~ /^1\.8\./
end

#initialize_metasploit_data_modelsvoid

This method returns an undefined value.

Loads Metasploit Data Models and adds its migrations to migrations paths.


156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/msf/core/db_manager.rb', line 156

def initialize_metasploit_data_models
  # Provide access to ActiveRecord models shared w/ commercial versions
  require "metasploit_data_models"

  metasploit_data_model_migrations_pathname = MetasploitDataModels.root.join(
      'db',
      'migrate'
  )
  metasploit_data_model_migrations_path = metasploit_data_model_migrations_pathname.to_s

  # Since ActiveRecord::Migrator.migrations_paths can persist between
  # instances of Msf::DBManager, such as in specs,
  # metasploit_data_models_migrations_path may already be part of
  # migrations_paths, in which case it should not be added or multiple
  # migrations with the same version number errors will occur.
  unless ActiveRecord::Migrator.migrations_paths.include? metasploit_data_model_migrations_path
    ActiveRecord::Migrator.migrations_paths << metasploit_data_model_migrations_path
  end
end

#initialize_sinkObject

Create a new database sink and initialize it


179
180
181
182
# File 'lib/msf/core/db_manager.rb', line 179

def initialize_sink
  self.sink = TaskManager.new(framework)
  self.sink.start
end

#inspect_single_packet(pkt, wspace, task = nil) ⇒ Object

Do all the single packet analysis we can while churning through the pcap the first time. Multiple packet inspection will come later, where we can do stream analysis, compare requests and responses, etc.


3333
3334
3335
3336
3337
# File 'lib/msf/core/db.rb', line 3333

def inspect_single_packet(pkt,wspace,task=nil)
  if pkt.is_tcp? or pkt.is_udp?
    inspect_single_packet_http(pkt,wspace,task)
  end
end

#inspect_single_packet_http(pkt, wspace, task = nil) ⇒ Object

Checks for packets that are headed towards port 80, are tcp, contain an HTTP/1.0 line, contains an Authorization line, contains a b64-encoded credential, and extracts it. Reports this credential and solidifies the service as HTTP.


3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
# File 'lib/msf/core/db.rb', line 3342

def inspect_single_packet_http(pkt,wspace,task=nil)
  # First, check the server side (data from port 80).
  if pkt.is_tcp? and pkt.tcp_src == 80 and !pkt.payload.nil? and !pkt.payload.empty?
    if pkt.payload =~ /^HTTP\x2f1\x2e[01]/n
      http_server_match = pkt.payload.match(/\nServer:\s+([^\r\n]+)[\r\n]/n)
      if http_server_match.kind_of?(MatchData) and http_server_match[1]
        report_service(
            :workspace => wspace,
            :host      => pkt.ip_saddr,
            :port      => pkt.tcp_src,
            :proto     => "tcp",
            :name      => "http",
            :info      => http_server_match[1],
            :state     => Msf::ServiceState::Open,
            :task      => task
        )
        # That's all we want to know from this service.
        return :something_significant
      end
    end
  end

  # Next, check the client side (data to port 80)
  if pkt.is_tcp? and pkt.tcp_dst == 80 and !pkt.payload.nil? and !pkt.payload.empty?
    if pkt.payload.match(/[\x00-\x20]HTTP\x2f1\x2e[10]/n)
      auth_match = pkt.payload.match(/\nAuthorization:\s+Basic\s+([A-Za-z0-9=\x2b]+)/n)
      if auth_match.kind_of?(MatchData) and auth_match[1]
        b64_cred = auth_match[1]
      else
        return false
      end
      # If we're this far, we can surmise that at least the client is a web browser,
      # he thinks the server is HTTP and he just made an authentication attempt. At
      # this point, we'll just believe everything the packet says -- validation ought
      # to come later.
      user,pass = b64_cred.unpack("m*").first.split(/:/,2)
      report_service(
          :workspace => wspace,
          :host      => pkt.ip_daddr,
          :port      => pkt.tcp_dst,
          :proto     => "tcp",
          :name      => "http",
          :task      => task
      )
      report_auth_info(
          :workspace => wspace,
          :host      => pkt.ip_daddr,
          :port      => pkt.tcp_dst,
          :proto     => "tcp",
          :type      => "password",
          :active    => true, # Once we can build a stream, determine if the auth was successful. For now, assume it is.
          :user      => user,
          :pass      => pass,
          :task      => task
      )
      # That's all we want to know from this service.
      return :something_significant
    end
  end
end

#ipv46_validator(addr) ⇒ Object


191
192
193
# File 'lib/msf/core/db.rb', line 191

def ipv46_validator(addr)
  ipv4_validator(addr) or ipv6_validator(addr)
end

#ipv4_validator(addr) ⇒ Object


195
196
197
198
# File 'lib/msf/core/db.rb', line 195

def ipv4_validator(addr)
  return false unless addr.kind_of? String
  Rex::Socket.is_ipv4?(addr)
end

#ipv6_validator(addr) ⇒ Object


200
201
202
# File 'lib/msf/core/db.rb', line 200

def ipv6_validator(addr)
  Rex::Socket.is_ipv6?(addr)
end

#loots(wspace = workspace) ⇒ Object

This methods returns a list of all loot in the database


2112
2113
2114
2115
2116
# File 'lib/msf/core/db.rb', line 2112

def loots(wspace=workspace)
::ActiveRecord::Base.connection_pool.with_connection {
  wspace.loots
}
end

#match_values(values) ⇒ Arrray<String>

Wraps values in '%' for Arel::Prediciation#matches_any and other match* methods that map to SQL 'LIKE' or 'ILIKE'


528
529
530
531
532
533
534
# File 'lib/msf/core/db_manager.rb', line 528

def match_values(values)
  wrapped_values = values.collect { |value|
    "%#{value}%"
  }

  wrapped_values
end

#module_to_details_hash(m) ⇒ Object


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
# File 'lib/msf/core/db_manager.rb', line 436

def module_to_details_hash(m)
  res  = {}
  bits = []

  res[:mtime]    = ::File.mtime(m.file_path) rescue Time.now
  res[:file]     = m.file_path
  res[:mtype]    = m.type
  res[:name]     = m.name.to_s
  res[:refname]  = m.refname
  res[:fullname] = m.fullname
  res[:rank]     = m.rank.to_i
  res[:license]  = m.license.to_s

  res[:description] = m.description.to_s.strip

  m.arch.map{ |x|
    bits << [ :arch, { :name => x.to_s } ]
  }

  m.platform.platforms.map{ |x|
    bits << [ :platform, { :name => x.to_s.split('::').last.downcase } ]
  }

  m.author.map{|x|
    bits << [ :author, { :name => x.to_s } ]
  }

  m.references.map do |r|
    bits << [ :ref, { :name => [r.ctx_id.to_s, r.ctx_val.to_s].join("-") } ]
  end

  res[:privileged] = m.privileged?


  if m.disclosure_date
    begin
      res[:disclosure_date] = m.disclosure_date.to_datetime.to_time
    rescue ::Exception
      res.delete(:disclosure_date)
    end
  end

  if(m.type == "exploit")

    m.targets.each_index do |i|
      bits << [ :target, { :index => i, :name => m.targets[i].name.to_s } ]
      if m.targets[i].platform
        m.targets[i].platform.platforms.each do |name|
          bits << [ :platform, { :name => name.to_s.split('::').last.downcase } ]
        end
      end
      if m.targets[i].arch
        bits << [ :arch, { :name => m.targets[i].arch.to_s } ]
      end
    end

    if (m.default_target)
      res[:default_target] = m.default_target
    end

    # Some modules are a combination, which means they are actually aggressive
    res[:stance] = m.stance.to_s.index("aggressive") ? "aggressive" : "passive"


    m.class.mixins.each do |x|
       bits << [ :mixin, { :name => x.to_s } ]
    end
  end

  if(m.type == "auxiliary")

    m.actions.each_index do |i|
      bits << [ :action, { :name => m.actions[i].name.to_s } ]
    end

    if (m.default_action)
      res[:default_action] = m.default_action.to_s
    end

    res[:stance] = m.passive? ? "passive" : "aggressive"
  end

  res[:bits] = bits.uniq

  res
end

#msf_import_timestamps(opts, obj) ⇒ Object

Handles timestamps from Metasploit Express/Pro imports.


2854
2855
2856
2857
2858
2859
2860
# File 'lib/msf/core/db.rb', line 2854

def msf_import_timestamps(opts,obj)
  obj.created_at = opts["created_at"] if opts["created_at"]
  obj.created_at = opts[:created_at] if opts[:created_at]
  obj.updated_at = opts["updated_at"] ? opts["updated_at"] : obj.created_at
  obj.updated_at = opts[:updated_at] ? opts[:updated_at] : obj.created_at
  return obj
end

#netsparker_method_map(vuln) ⇒ Object


4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
# File 'lib/msf/core/db.rb', line 4460

def netsparker_method_map(vuln)
  case vuln['vparam_type']
  when "FullQueryString"
    "GET"
  when "Querystring"
    "GET"
  when "Post"
    "POST"
  when "RawUrlInjection"
    "GET"
  else
    "GET"
  end
end

#netsparker_params_map(vuln) ⇒ Object


4484
4485
4486
# File 'lib/msf/core/db.rb', line 4484

def netsparker_params_map(vuln)
  []
end

#netsparker_pname_map(vuln) ⇒ Object


4475
4476
4477
4478
4479
4480
4481
4482
# File 'lib/msf/core/db.rb', line 4475

def netsparker_pname_map(vuln)
  case vuln['vparam_name']
  when "URI-BASED", "Query Based"
    "PATH"
  else
    vuln['vparam_name']
  end
end

#netsparker_vulnerability_map(vuln) ⇒ Object


4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
# File 'lib/msf/core/db.rb', line 4488

def netsparker_vulnerability_map(vuln)
  res = {
    :risk => 1,
    :name  => 'Information Disclosure',
    :blame => 'System Administrator',
    :category => 'info',
    :description => "This is an information leak",
    :confidence => 100
  }

  # Risk is a value from 1-5 indicating the severity of the issue
  # Examples: 1, 4, 5

  # Name is a descriptive name for this vulnerability.
  # Examples: XSS, ReflectiveXSS, PersistentXSS

  # Blame indicates who is at fault for the vulnerability
  # Examples: App Developer, Server Developer, System Administrator

  # Category indicates the general class of vulnerability
  # Examples: info, xss, sql, rfi, lfi, cmd

  # Description is a textual summary of the vulnerability
  # Examples: "A reflective cross-site scripting attack"
  #             "The web server leaks the internal IP address"
  #             "The cookie is not set to HTTP-only"

  #
  # Confidence is a value from 1 to 100 indicating how confident the
  # software is that the results are valid.
  # Examples: 100, 90, 75, 15, 10, 0

  case vuln['type'].to_s
  when "ApacheDirectoryListing"
    res = {
      :risk => 1,
      :name  => 'Directory Listing',
      :blame => 'System Administrator',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "ApacheMultiViewsEnabled"
    res = {
      :risk => 1,
      :name  => 'Apache MultiViews Enabled',
      :blame => 'System Administrator',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "ApacheVersion"
    res = {
      :risk => 1,
      :name  => 'Web Server Version',
      :blame => 'System Administrator',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "PHPVersion"
    res = {
      :risk => 1,
      :name  => 'PHP Module Version',
      :blame => 'System Administrator',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "AutoCompleteEnabled"
    res = {
      :risk => 1,
      :name  => 'Form AutoComplete Enabled',
      :blame => 'App Developer',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "CookieNotMarkedAsHttpOnly"
    res = {
      :risk => 1,
      :name  => 'Cookie Not HttpOnly',
      :blame => 'App Developer',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "EmailDisclosure"
    res = {
      :risk => 1,
      :name  => 'Email Address Disclosure',
      :blame => 'App Developer',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "ForbiddenResource"
    res = {
      :risk => 1,
      :name  => 'Forbidden Resource',
      :blame => 'App Developer',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "FileUploadFound"
    res = {
      :risk => 1,
      :name  => 'File Upload Form',
      :blame => 'App Developer',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "PasswordOverHTTP"
    res = {
      :risk => 2,
      :name  => 'Password Over HTTP',
      :blame => 'App Developer',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "MySQL5Identified"
    res = {
      :risk => 1,
      :name  => 'MySQL 5 Identified',
      :blame => 'App Developer',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "PossibleInternalWindowsPathLeakage"
    res = {
      :risk => 1,
      :name  => 'Path Leakage - Windows',
      :blame => 'App Developer',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "PossibleInternalUnixPathLeakage"
    res = {
      :risk => 1,
      :name  => 'Path Leakage - Unix',
      :blame => 'App Developer',
      :category => 'info',
      :description => "",
      :confidence => 100
    }
  when "PossibleXSS", "LowPossibilityPermanentXSS", "XSS", "PermanentXSS"
    conf = 100
    conf = 25  if vuln['type'].to_s == "LowPossibilityPermanentXSS"
    conf = 50  if vuln['type'].to_s == "PossibleXSS"
    res = {
      :risk => 3,
      :name  => 'Cross-Site Scripting',
      :blame => 'App Developer',
      :category => 'xss',
      :description => "",
      :confidence => conf
    }

  when "ConfirmedBlindSQLInjection", "ConfirmedSQLInjection", "HighlyPossibleSqlInjection", "DatabaseErrorMessages"
    conf = 100
    conf = 90  if vuln['type'].to_s == "HighlyPossibleSqlInjection"
    conf = 25  if vuln['type'].to_s == "DatabaseErrorMessages"
    res = {
      :risk => 5,
      :name  => 'SQL Injection',
      :blame => 'App Developer',
      :category => 'sql',
      :description => "",
      :confidence => conf
    }
  else
  conf = 100
  res = {
    :risk => 1,
    :name  => vuln['type'].to_s,
    :blame => 'App Developer',
    :category => 'info',
    :description => "",
    :confidence => conf
  }
  end

  res
end

#nexpose_host_from_rawxml(h, vstructs, wspace, task = nil) ⇒ Object

Takes a Host object, an array of vuln structs (generated by nexpose_refs_to_struct()), and a workspace, and reports the vulns on that host.


4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
# File 'lib/msf/core/db.rb', line 4087

def nexpose_host_from_rawxml(h, vstructs, wspace,task=nil)
  hobj = nil
  data = {:workspace => wspace}
  if h["addr"]
    addr = h["addr"]
  else
    # Can't report it if it doesn't have an IP
    return
  end
  data[:host] = addr
  if (h["hardware-address"])
    # Put colons between each octet of the MAC address
    data[:mac] = h["hardware-address"].gsub(':', '').scan(/../).join(':')
  end
  data[:state] = (h["status"] == "alive") ? Msf::HostState::Alive : Msf::HostState::Dead

  # Since we only have one name field per host in the database, just
  # take the first one.
  if (h["names"] and h["names"].first)
    data[:name] = h["names"].first
  end

  if (data[:state] != Msf::HostState::Dead)
    hobj = report_host(data)
    report_import_note(wspace, hobj)
  end

  if h["notes"]
    note = {
        :workspace => wspace,
        :host      => (hobj || addr),
        :type      => "host.vuln.nexpose_keys",
        :data      => {},
        :mode      => :unique_data,
        :task      => task
    }
    h["notes"].each do |v,k|
      note[:data][v] ||= []
      next if note[:data][v].include? k
      note[:data][v] << k
    end
    report_note(note)
  end

  if h["os_family"]
    note = {
        :workspace => wspace,
        :host      => hobj || addr,
        :type      => 'host.os.nexpose_fingerprint',
        :task      => task,
        :data      => {
            :family    => h["os_family"],
            :certainty => h["os_certainty"]
        }
    }
    note[:data][:vendor]  = h["os_vendor"]  if h["os_vendor"]
    note[:data][:product] = h["os_product"] if h["os_product"]
    note[:data][:version] = h["os_version"] if h["os_version"]
    note[:data][:arch]    = h["arch"]       if h["arch"]

    report_note(note)
  end

  h["endpoints"].each { |p|
    extra = ""
    extra << p["product"] + " " if p["product"]
    extra << p["version"] + " " if p["version"]

    # Skip port-0 endpoints
    next if p["port"].to_i == 0

    # XXX This should probably be handled in a more standard way
    # extra << "(" + p["certainty"] + " certainty) " if p["certainty"]

    data             = {}
    data[:workspace] = wspace
    data[:proto]     = p["protocol"].downcase
    data[:port]      = p["port"].to_i
    data[:state]     = p["status"]
    data[:host]      = hobj || addr
    data[:info]      = extra if not extra.empty?
    data[:task]      = task
    if p["name"] != "<unknown>"
      data[:name] = p["name"]
    end
    report_service(data)
  }

  h["vulns"].each_pair { |k,v|

    next if v["status"] !~ /^vulnerable/
    vstruct = vstructs.select {|vs| vs.id.to_s.downcase == v["id"].to_s.downcase}.first
    next unless vstruct
    data             = {}
    data[:workspace] = wspace
    data[:host]      = hobj || addr
    data[:proto]     = v["protocol"].downcase if v["protocol"]
    data[:port]      = v["port"].to_i if v["port"]
    data[:name]      = "NEXPOSE-"