Module: NexposeSCCM

Defined in:
lib/nexpose_sccm.rb,
lib/nexpose_sccm/wql.rb,
lib/nexpose_sccm/version.rb,
lib/nexpose_sccm/collection.rb,
lib/nexpose_sccm/connection.rb,
lib/nexpose_sccm/powershell.rb,
lib/nexpose_sccm/data_source.rb,
lib/nexpose_sccm/helpers/pg_helper.rb,
lib/nexpose_sccm/deployment_package.rb,
lib/nexpose_sccm/utilities/nx_logger.rb,
lib/nexpose_sccm/software_update_group.rb,
lib/nexpose_sccm/helpers/nexpose_helper.rb

Defined Under Namespace

Modules: DataSource, Powershell, Wql Classes: Collection, Connection, DeploymentPackage, NxLogger, SoftwareUpdateGroup

Constant Summary collapse

VERSION =
'0.4.0'
VENDOR =
'Microsoft'
PRODUCT =
'SCCM'

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.loggerObject

Returns the value of attribute logger.



285
286
287
# File 'lib/nexpose_sccm.rb', line 285

def logger
  @logger
end

Class Method Details

.generate_updates(settings, input_file = nil) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/nexpose_sccm.rb', line 44

def generate_updates(settings, input_file=nil)
  scope = settings[:sccm][:software_update_group][:scope]
  data_source = settings[:sccm][:data_source]

  if settings[:sccm][:generate_unknown_device_report]
    date = Time.now.strftime('%Y%m%d_%H%M%S')
    report = "devices-not-found-sccm-#{date}.csv"
    report_location = settings[:sccm][:report_location]
    unless File.exist?(File.expand_path(report_location))
      Dir.mkdir(report_location)
    end

    csv_report_contents = Set.new()
  end

  # Get known SCCM devices with details
  sccm_devices = @sccm.get_devices
  ## Get current list of collections
  collections = @sccm.get_collections(sccm_devices)

  ## Initiate the data source connection
  @logger.debug("Logging into Nexpose / DWH")
  @nsc = NexposeSCCM::DataSource::Connection.new(data_source,
                                                 settings[:postgres],
                                                 settings[:nexpose])

  @logger.info("Successfully connected to Data Source #{data_source}")

  sup_data = []
  begin
    query = settings[:queries][scope.to_sym][data_source.to_sym]
    match_for_prompt = query.scan(/'<.*?>'/)

    unless match_for_prompt.nil? || match_for_prompt.empty?
      if !input_file.nil? && File.exist?(input_file)
        inputs = CSV.read(input_file, :headers=>true)
      end

      match_for_prompt.each do |match|
        if !inputs.nil? && inputs.headers.include?(match.gsub("'<",'').gsub(">'",''))
          input = inputs[match.gsub("'<",'').gsub(">'",'')]
        else
          input = prompt("Please provide #{match} to be processed " \
                    "(comma separated for any lists): ").strip.split(',')
        end
        input = input.map{|e| "'#{e}'"}

        query.gsub!(/#{match}/, "#{input.join(',')}")
      end
    end

    @logger.debug("Retrieving Data")
    sup_data = @nsc.fetch_data(query)
  rescue => e
    @logger.error("There was an error running the query. " \
      "Check the scope and data source settings for validity: #{e}")
    exit
  end

  unless sup_data.length > 0
    @logger.debug("No updates returned using query: #{query}")
    @logger.info('No updates to work on. Exiting...')
    exit 0
  end

  ## SUP scopes are defined by the query used to run them.
  @logger.info("Software Update Group scope: #{scope}")

  sugs = {}

  @logger.debug("Getting CI_IDS using scope: #{scope}")

  @logger.info("Looping through output of length #{sup_data.length}")
  sup_data.each do |o|
    unless o.key?(:key)
      @logger.error("Query to pull data from #{data_source} " \
                "does not have the 'key' field, exiting...")
      exit 1
    end

    key = o[settings[:sccm][:software_update_group_key].to_sym]
    collection_key = o[settings[:sccm][:collection_key].to_sym]
    key_ip = o[:ip_address].split(':')[0].strip
    key_hostname = o[:host_name]

    device = sccm_devices.select do |dev|
      (dev.host_name.to_s.casecmp(key_hostname) == 0 unless key_hostname.nil?) ||
        (dev.ip_address.to_a.include?(key_ip) unless key_ip.nil?)
    end.first

    if device.nil?
      if settings[:sccm][:generate_unknown_device_report]
        csv_report_contents << [key_ip, key_hostname]
      end
    else
      collection_name = "Rapid7_#{collection_key}"
      collection_match = collections.select do |collection|
        collection.name.eql?(collection_name)
      end.first

      if collection_match.nil?
        collection_match = NexposeSCCM::Collection.new(collection_name)
        collection_match.members.add(device)
        collections << collection_match
      else
        collection_match.members.add(device)
      end
    end

    unless sugs.key?(key)
      sugs[key] = {
        :ci_ids => [],
        :description => "Scope: #{scope}",
        :name => "Rapid7_#{key}"
      }
    end

    ## Pesky way of grabbing an UUID for the specific microsoft patch until
    ## Nexpose has a better way of making this data available
    nexpose_id = o[:nexpose_id]
    uuid = nil
    begin
      match = nexpose_id.match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/).captures
      uuid = match[0]
    rescue
      @logger.debug('Must be no UUID available, going to next...')
    end
    next if uuid.nil?
    ci_ids = @sccm.get_ci_id(uuid)
    next unless ci_ids.length > 0

    sugs[key][:ci_ids] += ci_ids
  end

  ## Get current list of SUGs for update actions
  @logger.debug("Retrieving current Software Update Groups from SCCM")
  groups = @sccm.get_software_update_groups

  sug_objects=[]
  sug_action_type = settings[:sccm][:software_update_group][:action]
  ## At a minimum, we create Software Update Groups
  sugs.each do |k,v|
    @logger.info("Working on SUP: #{k}")
    match = groups.select { |g| g.name.casecmp(v[:name]) == 0 }
    ## Update if we find matching names
    if sug_action_type.casecmp('update') == 0
      if match.length > 0
        sug = match[0]
        sug.ci_ids = v[:ci_ids]
        sug.description = v[:description]
        res = sug.save(@sccm)
        sug_objects << sug
        if res
          msg = "Successfully updated Software Update Group: #{v[:name]}"
          @logger.debug(msg)
        else
          @logger.error("Error updating Software Update Group: #{v[:name]}")
        end
      end
    end

    if sug_action_type.casecmp('create') == 0 || match.empty?
      ## Create sug if action is create or update didn't work.
      sug = NexposeSCCM::SoftwareUpdateGroup.new(v[:name],
                                                 v[:description],
                                                 v[:ci_ids])
      sug_objects << sug
      res = sug.save(@sccm)
      if res
        msg = "Successfully created Software Update Group: #{v[:name]}"
        @logger.debug(msg)
      else
        @logger.error("Error creating Software Update Group: #{v[:name]}")
      end
    end
  end

  # Save collections with devices
  @logger.debug("Saving Collections")
  collections.each do |collection|
    collection.save(@sccm)
  end

  ## Download/deployment package creation if set to true
  if settings[:sccm].key?(:create_deployment_package) &&
    settings[:sccm][:create_deployment_package]
    @logger.debug("Creating the Deployment Packages")
    sug_objects.each do |sug_object|
      name = sug_object.name
      package_name = "Rapid7-Deployment-Package-#{name}"
      package_path = "#{@sccm.staging}\\#{name}"

      deployment_package = @sccm.get_deployment_package(package_name)
      package_id =
        if deployment_package.empty?
          nil
        else
          deployment_package.first[:package_id]
        end
        #deployment_package.empty? ? nil : deployment_package.first[:package_id]
      package = NexposeSCCM::DeploymentPackage.new(package_name,
                                                   name,
                                                   package_path,
                                                   package_id)

      # Don't process if no ci ids for SUG
      unless sug_object.ci_ids.empty?
        @logger.debug("Saving the Deployment Package: #{package_name}")
        # Save deployment package if enabled and doesn't exist already
        package.save(@sccm) if package.id.nil?

        # Download updates if enabled
        @logger.debug("Downloading the Deployment Package")
        package.download_updates(@sccm) if settings[:sccm][:download_updates]
      end
    end
  end

  # Generate report if configured and content exists
  if settings[:sccm][:generate_unknown_device_report]
    report_length = csv_report_contents.length
    if report_length > 0
      @logger.debug("Creating Unknown Device report")
      CSV.open(report_location + report, 'ab') do |csv|
        csv << ['IP Address','Hostname']
        csv_report_contents.each do |entry|
          csv << entry
        end
      end
    end
    @logger.debug("Unknown Device report length: #{report_length}")
  end

  @logger.info("Nexpose SCCM integration has finished.")
end

.prompt(*args) ⇒ Object



280
281
282
283
# File 'lib/nexpose_sccm.rb', line 280

def prompt(*args)
  print(*args)
  gets
end

.setup(settings) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/nexpose_sccm.rb', line 14

def setup(settings)
  @logger = NexposeSCCM::NxLogger.instance
  @logger.setup_statistics_collection(NexposeSCCM::VENDOR,
                                      NexposeSCCM::PRODUCT,
                                      NexposeSCCM::VERSION)
  @logger.setup_logging(true,
                        settings[:logging][:log_level],
                        settings[:logging][:log_stdout],
                        settings[:logging][:log_file_rotation],
                        settings[:logging][:log_file_size])
  NexposeSCCM.logger = @logger

  ## Setting up SCCM connection
  @logger.debug("Logging into SCCM")
  sccm = settings[:sccm]
  @sccm = NexposeSCCM::Connection.new(sccm[:protocol],
                                      sccm[:host],
                                      sccm[:port],
                                      sccm[:path],
                                      sccm[:location],
                                      sccm[:user],
                                      sccm[:pass],
                                      sccm[:namespace],
                                      sccm[:staging],
                                      sccm[:no_ssl_peer_verification],
                                      sccm[:ssl_peer_fingerprint])
  ## Logging into SCCM
  @sccm.
end