nexpose_sourcefire 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: cef7e30e1d14532223faf481eb8a33ca038386b8
4
+ data.tar.gz: ffa7de21150cdb104954baeef8b82740d16a41f2
5
+ SHA512:
6
+ metadata.gz: 7c5004beb3f54df13b944185d0fdadbb2d124baaed03a757272cc07231e10f32c0c7a11257ec7ec73b80e67f9eaa2b5a8742b57245c8bf3c896c7467e9762987
7
+ data.tar.gz: 4fe6994e3c82719caa232f3712a85591d59f36a07fdb3ce3ad691901e7b0c4bd95a6be6de7e15f5cf11609c7a7ff94a838e504087a22de841a1e712ae78d5c27
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in sourcefire.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 JJCassidy-R7
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # SourcefireRuby
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/sourcefire_ruby`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'sourcefire_ruby'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install sourcefire_ruby
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/sourcefire_ruby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
36
+
37
+
38
+ ## License
39
+
40
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
41
+
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env ruby
2
+ require 'sourcefire_connector'
3
+ require 'sourcefire/nx_logger'
4
+ require 'sourcefire/version'
5
+ require 'yaml'
6
+
7
+ CONFIG_PATH = File.join(File.dirname(__FILE__), '../lib/sourcefire/config/rapid7_sourcefire.config')
8
+
9
+ # Obtain Nexpose settings from Environment Variables.
10
+ configuration_settings = begin
11
+ YAML.load_file(CONFIG_PATH)
12
+ rescue ArgumentError => e
13
+ raise "Could not parse YAML #{CONFIG_PATH} : #{e.message}"
14
+ end
15
+
16
+ raise 'Must configure nexpose settings before starting' if ENV['NEXPOSE_URL'].nil? ||
17
+ ENV['NEXPOSE_USERNAME'].nil? ||
18
+ ENV['NEXPOSE_PASSWORD'].nil?
19
+ raise 'Must configure SourceFire settings before starting' if ENV['SOURCEFIRE_ADDR'].nil? ||
20
+ ENV['SOURCEFIRE_PORT'].nil? ||
21
+ ENV['SOURCEFIRE_PKCS12_PASSWORD'].nil?
22
+
23
+ log = Sourcefire::NxLogger.instance
24
+ log.setup_statistics_collection(Sourcefire::PRODUCT, Sourcefire::VENDOR, Sourcefire::VERSION)
25
+ logging_enabled = configuration_settings[:options][:logging_enabled] || false
26
+ log.setup_logging(logging_enabled,
27
+ configuration_settings[:options][:log_level])
28
+
29
+ configuration_settings[:nexpose_address] = ENV['NEXPOSE_URL']
30
+ configuration_settings[:nexpose_username] = ENV['NEXPOSE_USERNAME']
31
+ configuration_settings[:nexpose_password] = ENV['NEXPOSE_PASSWORD']
32
+ configuration_settings[:nexpose_port] = ENV['NEXPOSE_PORT']
33
+ configuration_settings[:sourcefire_address] = ENV['SOURCEFIRE_ADDR']
34
+ configuration_settings[:sourcefire_port] = ENV['SOURCEFIRE_PORT']
35
+ configuration_settings[:sourcefire_pkcs12_password] = ENV['SOURCEFIRE_PKCS12_PASSWORD']
36
+
37
+ # Initialize and start the integration
38
+ r7sfc = Sourcefire::Rapid7SourceFireConnector.new
39
+ r7sfc.setup(configuration_settings)
40
+ r7sfc.start
@@ -0,0 +1,19 @@
1
+ ---
2
+ # This configuration file defines all the particular options necessary to run the service.
3
+ # Fields marked (M) are mandatory.
4
+ #
5
+ # Service options:
6
+ :options:
7
+ # (M) Enables logging to the log directory.
8
+ :logging_enabled: true
9
+ # (M) Sets the log level threshold for output.
10
+ :log_level: info
11
+ # Filters to specific sites one per line, leave empty to generate for all sites.
12
+ :sites:
13
+ - '1'
14
+ # Determines if generated files (Nexpose CSV report and SourceFire ready CSV) should be kept after run is complete
15
+ :keep_csv: N
16
+ # Absolute location of the SourceFire pkcs12 file
17
+ :p12_location: '/an/absolute/location/file.pkcs12'
18
+ # Timeout in seconds. The number of seconds the GEM waits for a response from Nexpose before exiting.
19
+ :timeout: 10800
@@ -0,0 +1,57 @@
1
+ module Sourcefire
2
+ class ReportOps
3
+ require_relative 'nx_logger'
4
+ require_relative 'queries'
5
+ require 'nexpose'
6
+ require 'csv'
7
+ include Nexpose
8
+
9
+ # Logs in to Nexpose using the url, username and password.
10
+ def login(url=nil, username=nil, password=nil, timeout=nil, port=nil)
11
+ raise 'Nexpose connection must be set in environment variables.' if url.nil? || username.nil? || password.nil?
12
+ @log = Sourcefire::NxLogger.instance
13
+ @log.log_message('Setting up Nexpose connection...')
14
+ @timeout = timeout
15
+ @nsc = if port != nil
16
+ Nexpose::Connection.new(url, username, password, port)
17
+ else
18
+ Nexpose::Connection.new(url, username, password)
19
+ end
20
+ @nsc.login
21
+ @log.log_message('Nexpose connection established.')
22
+ @log.on_connect(url, port || 3780, @nsc.session_id, "{}")
23
+ @nsc
24
+ end
25
+
26
+ def site_id_listing
27
+ @log.log_message('Generating site ID list...')
28
+ site_ids = Array.new
29
+ @nsc.list_sites.each { |site| site_ids << site.id }
30
+ @log.log_message("Site ID list generation complete. Resulting list is <#{site_ids}>")
31
+ site_ids
32
+ end
33
+
34
+ def vulnerability_listing
35
+ @log.log_message('Generating vulnerability list...')
36
+ @nsc.list_vulns
37
+ end
38
+
39
+ def ad_hoc_report_request(query, site_ids, save_file, report_config = Nexpose::AdhocReportConfig.new(nil, 'sql'))
40
+ @log.log_message("Setting up Ad-Hoc query request. Sites to query are <#{site_ids}> and report results file is <#{save_file.path}>.")
41
+ report_config.add_filter('version', '1.1.0')
42
+ report_config.add_filter('query', query)
43
+ site_ids.each { |site_id| report_config.add_filter('site', site_id) }
44
+ @log.log_message('Sending query request to Nexpose...')
45
+ report_output = report_config.generate(@nsc, @timeout)
46
+ @log.log_message("Parsing report response and saving to file <#{save_file.path}>")
47
+ csv_output = CSV.parse(report_output.chomp, headers: :first_row)
48
+ save_file.puts(csv_output)
49
+ end
50
+
51
+ def generate_sourcefire_nexpose_report(report_file, sites_to_query=nil)
52
+ sites_to_query = site_id_listing if sites_to_query.nil? || sites_to_query.empty?
53
+ @log.log_message("Generating report on the following sites #{sites_to_query}")
54
+ self.ad_hoc_report_request(Queries.sf_host_vuln_info, sites_to_query, report_file)
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,150 @@
1
+ require 'fileutils'
2
+ require 'json'
3
+ require 'net/http'
4
+ require 'singleton'
5
+
6
+ module Sourcefire
7
+ class NxLogger
8
+ include Singleton
9
+ attr_accessor :options, :statistic_key, :product, :logger_file
10
+ LOG_PATH = "./logs/rapid7_%s.log"
11
+ KEY_FORMAT = "external.integration.%s"
12
+ PRODUCT_FORMAT = "%s_%s"
13
+
14
+ DEFAULT_LOG = 'integration'
15
+ PRODUCT_RANGE = 3..30
16
+ KEY_RANGE = 3..15
17
+
18
+ ENDPOINT = '/data/external/statistic/'
19
+
20
+ def initialize()
21
+ @logger_file = get_log_path product
22
+ setup_logging(true, 'info')
23
+ end
24
+
25
+ def setup_statistics_collection(vendor, product_name, gem_version)
26
+ #Remove illegal characters
27
+ vendor.to_s.gsub!('-', '_')
28
+ product_name.to_s.gsub!('-', '_')
29
+
30
+ begin
31
+ @statistic_key = get_statistic_key vendor
32
+ @product = get_product product_name, gem_version
33
+ rescue => e
34
+ #Continue
35
+ end
36
+ end
37
+
38
+ def setup_logging(enabled, log_level)
39
+ unless enabled || @log.nil?
40
+ log_message('Logging disabled.')
41
+ return
42
+ end
43
+ log_level ||= 'info'
44
+ @logger_file = get_log_path product
45
+
46
+ require 'logger'
47
+ directory = File.dirname(@logger_file)
48
+ FileUtils.mkdir_p(directory) unless File.directory?(directory)
49
+ io = IO.for_fd(IO.sysopen(@logger_file, 'a'))
50
+ io.autoclose = false
51
+ io.sync = true
52
+ @log = Logger.new(io, 'weekly')
53
+ @log.level = if log_level.casecmp('info') == 0
54
+ Logger::INFO
55
+ else
56
+ Logger::DEBUG
57
+ end
58
+ log_message("Logging enabled at level <#{log_level}>")
59
+ end
60
+
61
+ # Logs an info message
62
+ def log_message(message)
63
+ @log.info(message) unless @log.nil?
64
+ end
65
+
66
+ # Logs a debug message
67
+ def log_debug_message(message)
68
+ @log.debug(message) unless @log.nil?
69
+ end
70
+
71
+ # Logs an error message
72
+ def log_error_message(message)
73
+ @log.error(message) unless @log.nil?
74
+ end
75
+
76
+ # Logs a warn message
77
+ def log_warn_message(message)
78
+ @log.warn(message) unless @log.nil?
79
+ end
80
+
81
+ def log_stat_message(message)
82
+ end
83
+
84
+ def get_log_path(product)
85
+ product.downcase! unless product.nil?
86
+ File.join(File.dirname(__FILE__), LOG_PATH % (product || DEFAULT_LOG))
87
+ end
88
+
89
+ def get_statistic_key(vendor)
90
+ if vendor.nil? || vendor.length < KEY_RANGE.min
91
+ log_stat_message("Vendor length is below minimum of <#{KEY_RANGE}>")
92
+ return nil
93
+ end
94
+
95
+ KEY_FORMAT % vendor[0...KEY_RANGE.max].downcase
96
+ end
97
+
98
+ def get_product(product, version)
99
+ return nil if (product.nil? || version.nil?)
100
+ product = (PRODUCT_FORMAT % [product, version])[0...PRODUCT_RANGE.max]
101
+
102
+ if product.length < PRODUCT_RANGE.min
103
+ log_stat_message("Product length below minimum <#{PRODUCT_RANGE.min}>.")
104
+ return nil
105
+ end
106
+ product.downcase
107
+ end
108
+
109
+ def generate_payload(statistic_value='')
110
+ payload = {'statistic-key' => @statistic_key,
111
+ 'statistic-value' => statistic_value,
112
+ 'product' => @product}
113
+ JSON.generate(payload)
114
+ end
115
+
116
+ def send(nexpose_address, nexpose_port, session_id, payload)
117
+ header = {'Content-Type' => 'application/json',
118
+ 'nexposeCCSessionID' => session_id,
119
+ 'Cookie' => "nexposeCCSessionID=#{session_id}"}
120
+ req = Net::HTTP::Put.new(ENDPOINT, header)
121
+ req.body = payload
122
+ http_instance = Net::HTTP.new(nexpose_address, nexpose_port)
123
+ http_instance.use_ssl = true
124
+ http_instance.verify_mode = OpenSSL::SSL::VERIFY_NONE
125
+ response = http_instance.start { |http| http.request(req) }
126
+ log_stat_message "Received code #{response.code} from Nexpose console."
127
+ log_stat_message "Received message #{response.msg} from Nexpose console."
128
+ log_stat_message 'Finished sending statistics data to Nexpose.'
129
+ response.code
130
+ end
131
+
132
+ def on_connect(nexpose_address, nexpose_port, session_id, value)
133
+ log_stat_message 'Sending statistics data to Nexpose'
134
+
135
+ if @product.nil? || @statistic_key.nil?
136
+ log_stat_message('Invalid product name and/or statistics key.')
137
+ log_stat_message('Statistics collection not enabled.')
138
+ return
139
+ end
140
+
141
+ begin
142
+ payload = generate_payload value
143
+ send(nexpose_address, nexpose_port, session_id, payload)
144
+ rescue => e
145
+ #Let the program continue
146
+ end
147
+ end
148
+
149
+ end
150
+ end
@@ -0,0 +1,67 @@
1
+ require 'openssl'
2
+
3
+ module Sourcefire
4
+ class PkcsOps
5
+ attr_accessor :key, :cert
6
+ @key
7
+ @cert
8
+ def extract_pkcs_12(pkcs_file, password = nil)
9
+ if password.nil? || password.empty?
10
+ p12 = OpenSSL::PKCS12.new(File.read(pkcs_file))
11
+ else
12
+ p12 = OpenSSL::PKCS12.new(File.read(pkcs_file), password)
13
+ end
14
+ @key = p12.key
15
+ @cert = p12.certificate
16
+ end
17
+
18
+ def key_to_file(file_name, strip_header_footer = false)
19
+ processed_key = strip_header_footer ? p12_data_to_split_string(@key) {|data| data.to_a[1..-2].join} : @key
20
+ File.open(file_name, 'w') {|f| processed_key.nil? ? f.write('No Key Data!') : f.write(processed_key) }
21
+ end
22
+
23
+ def raw_cert_to_file(file_name, strip_header_footer = false)
24
+ processed_cert = strip_header_footer ? p12_data_to_split_string(@cert) {|data| data.to_a[1..-2].join} : @cert
25
+ File.open(file_name, 'w') {|f| processed_cert.nil? ? f.write('No Cert Data!') : f.write(processed_cert) }
26
+ end
27
+
28
+ def cert_pem_to_file(file_name, strip_header_footer = false)
29
+ processed_cert = strip_header_footer ? p12_data_to_split_string(@cert.to_pem) {|data| data.to_a[1..-2].join} : @cert
30
+ File.open(file_name, 'w') {|f| processed_cert.nil? ? f.write('No Cert Data!') : f.write(processed_cert) }
31
+ end
32
+
33
+ def cert_der_to_file(file_name, strip_header_footer = false)
34
+ processed_cert = strip_header_footer ? p12_data_to_split_string(@cert.to_der) {|data| data.to_a[1..-2].join} : @cert
35
+ File.open(file_name, 'w') {|f| processed_cert.nil? ? f.write('No Cert Data!') : f.write(processed_cert) }
36
+ end
37
+
38
+ def key(strip_header_footer = false)
39
+ processed_key = strip_header_footer ? p12_data_to_split_string(@key) {|data| data.to_a[1..-2].join} : @key
40
+ processed_key.nil? ? 'No Key Data!' : processed_key
41
+ end
42
+
43
+ def raw_cert(strip_header_footer = false)
44
+ processed_cert = strip_header_footer ? p12_data_to_split_string(@cert) {|data| data.to_a[1..-2].join} : @cert
45
+ processed_cert.nil? ? 'No Cert Data!' : processed_cert
46
+ end
47
+
48
+ def cert_pem(strip_header_footer = false)
49
+ processed_cert = strip_header_footer ? p12_data_to_split_string(@cert.to_pem) {|data| data.to_a[1..-2].join} : @cert
50
+ processed_cert.nil? ? 'No Cert Data!' : processed_cert
51
+ end
52
+
53
+ def cert_der(strip_header_footer = false)
54
+ processed_cert = strip_header_footer ? p12_data_to_split_string(@cert.to_der) {|data| data.to_a[1..-2].join} : @cert
55
+ processed_cert.nil? ? 'No Cert Data!' : processed_cert
56
+ end
57
+
58
+ def cert_public_key(strip_header_footer = false)
59
+ strip_header_footer ? p12_data_to_split_string(@cert.public_key) {|data| data.to_a[1..-2].join} : @cert.public_key
60
+ end
61
+
62
+ private
63
+ def p12_data_to_split_string(data)
64
+ yield data.to_s.strip.lines
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,15 @@
1
+ module Sourcefire
2
+ module Queries
3
+ def self.sf_host_vuln_info(options = {})
4
+ "SELECT favi.asset_id as asset_id, da.ip_address, favi.port, favi.protocol_id, dv.title, dv.vulnerability_id, dv.nexpose_id, string_agg(DISTINCT '<' || dvr.source || ':' || dvr.reference,'>') || '>' as references, dv.severity_score, dv.pci_severity_score, round((dv.cvss_score)::numeric,1) as cvss_score, dv.cvss_vector
5
+ FROM fact_vulnerability fa
6
+ JOIN dim_vulnerability dv USING (vulnerability_id)
7
+ LEFT OUTER JOIN dim_vulnerability_reference dvr USING (vulnerability_id)
8
+ LEFT OUTER JOIN fact_asset_vulnerability_instance favi USING (vulnerability_id)
9
+ LEFT OUTER JOIN dim_asset da USING (asset_id)
10
+ WHERE affected_assets > 0
11
+ GROUP BY da.ip_address, dv.title, favi.port, dv.vulnerability_id, dv.severity, dv.pci_severity_score, dv.cvss_score, dv.cvss_vector, favi.asset_id, favi.protocol_id, dv.nexpose_id, dv.severity_score
12
+ ORDER BY da.ip_address ASC"
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,5 @@
1
+ module Sourcefire
2
+ PRODUCT = 'Sourcefire'
3
+ VENDOR = 'Sourcefire'
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,277 @@
1
+ require_relative 'sourcefire/nx_logger'
2
+ require_relative 'sourcefire/p12_utils'
3
+ require_relative 'sourcefire/nexpose_helper'
4
+ require 'openssl'
5
+ require 'socket'
6
+ require 'csv'
7
+
8
+ module Sourcefire
9
+ class Rapid7SourceFireConnector
10
+
11
+ def setup(config_options)
12
+ @config = config_options
13
+ @log = Sourcefire::NxLogger.instance
14
+ end
15
+
16
+ def start
17
+ puts "Nexpose Report Processing Starting"
18
+
19
+ # Create a new Nexpose connection
20
+ nxro = Sourcefire::ReportOps.new
21
+ nxro.login(@config[:nexpose_address],@config[:nexpose_username],
22
+ @config[:nexpose_password], @config[:options][:timeout],
23
+ @config[:nexpose_port])
24
+
25
+ #Generate the required data from Nexpose
26
+ time = Time.now.to_i
27
+ report_file = File.open("nexpose_report_#{time}.csv", 'w')
28
+ puts "Site ID: #{@config[:options][:sites].join(', ')}"
29
+ puts 'Generating report.'
30
+ nxro.generate_sourcefire_nexpose_report(report_file, @config[:options][:sites])
31
+ puts 'Report generation complete.'
32
+
33
+ #Process the Nexpose results.report("name:") { TESTS.times { } }ort into SourceFire format
34
+ processed_report_file = File.open("processed_nexpose_report_#{time}.csv", 'w')
35
+ data_sets = process_nexpose_data(report_file, processed_report_file)
36
+
37
+ #Establish connection with Sourcefire
38
+ puts "Connecting to Sourcefire: #{@config[:sourcefire_address]}"
39
+ ssl_socket = connect_to_sourcefire
40
+
41
+ #Send the Data to SourceFire
42
+ send_processed_data(data_sets, ssl_socket)
43
+
44
+ #Cleanup
45
+ ssl_socket.close
46
+ if(@config[:options][:keep_csv] == 'N')
47
+ File.delete(processed_report_file)
48
+ File.delete(report_file)
49
+ end
50
+ @log.log_message('Finished processing. Exiting...')
51
+ end
52
+
53
+ def get_assets(report_file)
54
+ assets = []
55
+ current_asset = nil
56
+ current_ip = nil
57
+
58
+ CSV.foreach(report_file, headers: true) do |row|
59
+ if current_asset.nil?
60
+ current_asset = "AddHost,#{row['ip_address']}\n"
61
+ current_ip = row['ip_address']
62
+ end
63
+
64
+ if row['ip_address'] == current_ip
65
+ sf_csv = ""
66
+ sf_csv << "AddScanResult,#{row['ip_address']},\"NeXpose\",#{generate_vuln_id(row['nexpose_id'])},"
67
+ (row['port'].to_i == -1) ? sf_csv << ',' : sf_csv << "#{row['port']},"
68
+ (row['protocol_id'].to_i == -1) ? sf_csv << ',' : sf_csv << "#{row['protocol_id']},"
69
+ sf_csv << "\"#{row['title'].tr('"', "'")}\","
70
+ sf_csv << "\"NeXpose ID: #{row['nexpose_id'].tr('"', "'")}; References: #{row['references'] ? row['references'].scan(/<(.*?:.*?)>/).join(' ').downcase.tr('"', "'") : row['references']}; Severity: #{row['severity_score']}; PCI Severity: #{row['pci_severity_score']}; CVSS Score: #{row['cvss_score']}; CVSS Vector: (#{row['cvss_vector']})\","
71
+ row['references'].nil? ?
72
+ sf_csv << "\"cve_ids: \"," :
73
+ sf_csv << "\"cve_ids: #{row['references'].scan(/<CVE:(.*?)>/).join(' ').tr('"', "'")}\","
74
+ sf_csv << "\"bugtraq_ids: \"\n"
75
+
76
+ current_asset += sf_csv
77
+ next
78
+ end
79
+
80
+ #Next asset
81
+ assets << current_asset
82
+ current_asset = nil
83
+ current_asset_id = nil
84
+ redo
85
+ end
86
+
87
+ assets << current_asset + "ScanFlush\n" unless current_asset.nil?
88
+ @log.log_message("Total of #{assets.count} assets")
89
+ assets
90
+ end
91
+
92
+ def process_nexpose_data(report_file, processed_report_file)
93
+ max_data_size = 524288
94
+
95
+ @log.log_message('Creating data sets')
96
+ header = "SetSource,NeXpose Scan Report\n"
97
+ footer = "ScanFlush"
98
+
99
+ puts 'Processing vulnerability list.'
100
+ assets = get_assets(report_file)
101
+
102
+ ssl_socket = connect_to_sourcefire
103
+ ssl_socket.write([2,4].pack('NN'))
104
+ ssl_socket.write([1].pack('N'))
105
+ msg_details = read_from_socket(ssl_socket)
106
+ if msg_details.kind_of?(Array)
107
+ @log.log_message("Got a message of type <#{msg_details[0]}> and size <#{msg_details[1]}>")
108
+ max_size = read_from_socket(ssl_socket, msg_details[1], msg_details[0])
109
+ @log.log_message("Max message length is <#{max_size}>")
110
+ max_data_size = max_size.first
111
+ end
112
+ ssl_socket.close
113
+
114
+ data_sets = []
115
+ current_data_set = nil
116
+
117
+ assets.each do |asset|
118
+ if data_sets[-1].nil?
119
+ data_sets << header.dup + asset
120
+ elsif (data_sets[-1].to_s + asset + footer).bytesize < max_data_size
121
+ data_sets[-1] += asset
122
+ else
123
+ data_sets << header.dup + asset
124
+ end
125
+ end
126
+
127
+ if data_sets.count == 0
128
+ @log.log_message("No data found. Returning <0> assets.")
129
+ return []
130
+ end
131
+
132
+ #mark the overall scan finish
133
+ data_sets[-1] = data_sets.last + footer
134
+
135
+ @log.log_message("Number of batches to submit: #{data_sets.count}")
136
+ puts 'Nexpose report processing complete.'
137
+ data_sets
138
+ end
139
+
140
+ def process_nexpose_data_alt(report_file, processed_report_file)
141
+ max_data_size = 524288
142
+
143
+ assets = get_assets(report_file)
144
+ header = "SetSource,NeXpose Scan Report\n"
145
+ footer = "ScanFlush"
146
+ assets[0] = header + assets.first
147
+ assets[-1] = assets.last + footer
148
+
149
+ assets
150
+ end
151
+
152
+ def generate_vuln_id(vuln_title)
153
+ vuln_id = ''
154
+ md5_title = Digest::MD5::hexdigest(vuln_title)
155
+ md5_title[0..7].chars.map { |ch|
156
+ if (ch != '0') && (ch.to_i == 0)
157
+ vuln_id += (ch.ord - 'a'.ord + 1).to_s
158
+ else
159
+ vuln_id +=ch
160
+ end
161
+ }
162
+ vuln_id
163
+ end
164
+
165
+ def connect_to_sourcefire()
166
+ @log.log_message('Establishing connection to SourceFire...')
167
+ p12_utils = Sourcefire::PkcsOps.new
168
+ p12_utils.extract_pkcs_12(@config[:options][:p12_location], @config[:sourcefire_pkcs12_password])
169
+
170
+ ctx = OpenSSL::SSL::SSLContext.new()
171
+ ctx.cert = p12_utils.cert
172
+ ctx.key = p12_utils.key
173
+
174
+ @log.log_message('Parsed cert and key from pkcs file. Creating socket...')
175
+ socket = TCPSocket.new(@config[:sourcefire_address],@config[:sourcefire_port])
176
+ @log.log_message('Socket connection established. Initiating SSL handshake...')
177
+ ssl_socket = OpenSSL::SSL::SSLSocket.new(socket, ctx)
178
+ ssl_socket.sync_close = true
179
+ ssl_socket.sync = true
180
+ ssl_socket.connect
181
+
182
+ @log.log_message('SSL connection established! Returning socket.')
183
+
184
+ ssl_socket
185
+ end
186
+
187
+ def send_processed_data(data_sets, ssl_socket)
188
+ overall_data_size = 0
189
+
190
+ file = File.open("update_sets.csv", 'w')
191
+ data_sets.each { |data| file.puts(data) }
192
+ file.close
193
+
194
+ @log.log_message('Starting to transmit data to SourceFire...')
195
+
196
+ #Send the data
197
+ number_of_commands = 0
198
+ count = 0
199
+ response = ''
200
+ data_sets.each do |data|
201
+ count += 1
202
+
203
+ #Inform SourceFire of the type of data.
204
+ ssl_socket.write([2,4].pack('NN'))
205
+ ssl_socket.write([1].pack('N'))
206
+
207
+ #Send the data type and size
208
+ ssl_socket.write([3,data.bytesize].pack('NN'))
209
+
210
+ progress = "[#{((count-1)*100/Float(data_sets.count)).round(2)}%]"
211
+ message_log = "Sending #{count.to_s.rjust(3, ' ')}/#{data_sets.count} #{progress}: Sending #{data.bytesize} bytes to socket."
212
+ @log.log_message(message_log)
213
+ print "\r#{message_log}"
214
+ print
215
+
216
+ ssl_socket.write(data)
217
+ ssl_socket.flush
218
+ msg_details = read_from_socket(ssl_socket)
219
+
220
+ if msg_details.kind_of?(Array)
221
+ @log.log_message("Got a message of type <#{msg_details[0]}> and size <#{msg_details[1]}>")
222
+ response = read_from_socket(ssl_socket, msg_details[1], msg_details[0])
223
+ @log.log_message("Message is <#{response}>")
224
+ end
225
+
226
+ #get the response
227
+ msg_details = read_from_socket(ssl_socket)
228
+ response = ''
229
+ if msg_details.kind_of?(Array)
230
+ @log.log_message("Got a message of type <#{msg_details[0]}> and size <#{msg_details[1]}>")
231
+ response = read_from_socket(ssl_socket, msg_details[1], msg_details[0])
232
+ @log.log_message("Message is <#{response}>")
233
+ response = response.kind_of?(Array) ? response.first : response.to_s
234
+ current_number_of_commands = response.to_s.scan(/\d+/).first.to_s.to_i
235
+ number_of_commands += current_number_of_commands
236
+ if current_number_of_commands > 0
237
+ @log.log_message("Sent #{current_number_of_commands} commands for latest batch to Sourcefire console.")
238
+ end
239
+ end
240
+ end
241
+
242
+ print "\rSent #{data_sets.count.to_s.rjust(3, ' ')}/#{data_sets.count} [100%]#{' '*40}"
243
+ @log.log_message("Sent #{number_of_commands} commands total to Sourcefire console.")
244
+ @log.log_message('Data transmission complete.')
245
+ puts "\nProcessing complete."
246
+ response
247
+ end
248
+
249
+ def read_from_socket(ssl_socket, read_size=nil, msg_type = nil)
250
+ readable = IO.select([ssl_socket], nil, nil, 10)
251
+ if readable.nil?
252
+ @log.log_message('No response from server.')
253
+ return
254
+ end
255
+ readable[0].each do |socket|
256
+ next unless socket == ssl_socket
257
+
258
+ if read_size.nil?
259
+ data = ssl_socket.read_nonblock(10_000)
260
+ type = data[0..3].unpack('N')
261
+ read_size = data[4..7].unpack('N')
262
+ return [type[0],read_size[0]]
263
+ end
264
+
265
+ begin
266
+ data = ssl_socket.read_nonblock(read_size)
267
+ return data.unpack('N') if msg_type == 1
268
+ return data
269
+ rescue IO::WaitReadable
270
+ @log.log_message("Waiting for data of length <#{read_size}>")
271
+ IO.select([ssl_socket], nil, nil, 10)
272
+ retry
273
+ end
274
+ end
275
+ end
276
+ end
277
+ end
metadata ADDED
@@ -0,0 +1,102 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: nexpose_sourcefire
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - JJ Cassidy
8
+ - David Valente
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2015-12-11 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: bundler
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - "~>"
19
+ - !ruby/object:Gem::Version
20
+ version: '1.10'
21
+ type: :development
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - "~>"
26
+ - !ruby/object:Gem::Version
27
+ version: '1.10'
28
+ - !ruby/object:Gem::Dependency
29
+ name: rake
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - "~>"
33
+ - !ruby/object:Gem::Version
34
+ version: '10.0'
35
+ type: :development
36
+ prerelease: false
37
+ version_requirements: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - "~>"
40
+ - !ruby/object:Gem::Version
41
+ version: '10.0'
42
+ - !ruby/object:Gem::Dependency
43
+ name: nexpose
44
+ requirement: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - "~>"
47
+ - !ruby/object:Gem::Version
48
+ version: '0.9'
49
+ type: :runtime
50
+ prerelease: false
51
+ version_requirements: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - "~>"
54
+ - !ruby/object:Gem::Version
55
+ version: '0.9'
56
+ description: This GEM allows enables the importing of Nexpose host and vulnerability
57
+ data into SourceFire
58
+ email:
59
+ - integrations_support@rapid7.com
60
+ executables:
61
+ - nexpose_sourcefire
62
+ extensions: []
63
+ extra_rdoc_files: []
64
+ files:
65
+ - CODE_OF_CONDUCT.md
66
+ - Gemfile
67
+ - LICENSE.txt
68
+ - README.md
69
+ - Rakefile
70
+ - bin/nexpose_sourcefire
71
+ - lib/sourcefire/config/rapid7_sourcefire.config
72
+ - lib/sourcefire/nexpose_helper.rb
73
+ - lib/sourcefire/nx_logger.rb
74
+ - lib/sourcefire/p12_utils.rb
75
+ - lib/sourcefire/queries.rb
76
+ - lib/sourcefire/version.rb
77
+ - lib/sourcefire_connector.rb
78
+ homepage: http://www.rapid7.com
79
+ licenses:
80
+ - MIT
81
+ metadata: {}
82
+ post_install_message:
83
+ rdoc_options: []
84
+ require_paths:
85
+ - lib
86
+ required_ruby_version: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '1.9'
91
+ required_rubygems_version: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ requirements: []
97
+ rubyforge_project:
98
+ rubygems_version: 2.4.3
99
+ signing_key:
100
+ specification_version: 4
101
+ summary: Nexpose SourceFire Integration GEM
102
+ test_files: []