Module: Msf::Auxiliary::Scanner

Included in:
CNPILOT, EPMP, NATPMP, NTP, Nfs, Redis, UDPScanner, Exploit::Remote::Kerberos::AuthBrute
Defined in:
lib/msf/core/auxiliary/scanner.rb

Overview

This module provides methods for scanning modules

Defined Under Namespace

Classes: AttemptFailed

Instance Method Summary collapse

Instance Method Details

#add_delay_jitter(_delay, _jitter) ⇒ Object



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/msf/core/auxiliary/scanner.rb', line 323

def add_delay_jitter(_delay, _jitter)
  # Introduce the delay
  delay_value = _delay.to_i
  original_value = delay_value
  jitter_value = _jitter.to_i

  # Retrieve the jitter value and delay value
  # Delay = number of milliseconds to wait between each request
  # Jitter = percentage modifier. For example:
  # Delay is 1000ms (i.e. 1 second), Jitter is 50.
  # 50/100 = 0.5; 0.5*1000 = 500. Therefore, the per-request
  # delay will be 1000 +/- a maximum of 500ms.
  if delay_value > 0
    if jitter_value > 0
       rnd = Random.new
       if (rnd.rand(2) == 0)
          delay_value += rnd.rand(jitter_value)
       else
          delay_value -= rnd.rand(jitter_value)
       end
       if delay_value < 0
          delay_value = 0
       end
    end
    final_delay = delay_value.to_f / 1000.0
    vprint_status("Delaying for #{final_delay} second(s) (#{original_value}ms +/- #{jitter_value}ms)")
    sleep final_delay
  end
end

#checkObject



38
39
40
41
42
43
44
45
# File 'lib/msf/core/auxiliary/scanner.rb', line 38

def check
  nmod = replicant
  begin
    nmod.check_host(datastore['RHOST'])
  rescue NoMethodError
    Exploit::CheckCode::Unsupported
  end
end

#fail_with(reason, msg = nil, abort: false) ⇒ Object



353
354
355
356
357
358
359
360
361
# File 'lib/msf/core/auxiliary/scanner.rb', line 353

def fail_with(reason, msg = nil, abort: false)
  if abort
    # raising Failed will case the run to be aborted
    raise Msf::Auxiliary::Failed, "#{reason.to_s}: #{msg}"
  else
    # raising AttemptFailed will cause the run_host / run_batch to be aborted
    raise Msf::Auxiliary::Scanner::AttemptFailed, "#{reason.to_s}: #{msg}"
  end
end

#has_check?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/msf/core/auxiliary/scanner.rb', line 34

def has_check?
  respond_to?(:check_host)
end

#has_fatal_errors?Boolean

Returns:

  • (Boolean)


288
289
290
# File 'lib/msf/core/auxiliary/scanner.rb', line 288

def has_fatal_errors?
  @scan_errors && !@scan_errors.empty?
end

#initialize(info = {}) ⇒ Object

Initializes an instance of a recon auxiliary module



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/msf/core/auxiliary/scanner.rb', line 19

def initialize(info = {})
  super

  register_options([
      Opt::RHOSTS,
      OptInt.new('THREADS', [ true, "The number of concurrent threads (max one per host)", 1 ] )
    ], Auxiliary::Scanner)

  register_advanced_options([
    OptBool.new('ShowProgress', [true, 'Display progress messages during a scan', true]),
    OptInt.new('ShowProgressPercent', [true, 'The interval in percent that progress should be shown', 10])
  ], Auxiliary::Scanner)

end

#peerObject



48
49
50
51
# File 'lib/msf/core/auxiliary/scanner.rb', line 48

def peer
  # IPv4 addr can be 16 chars + 1 for : and + 5 for port
  super.ljust(21)
end

#runObject

The command handler when launched from the console



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
# File 'lib/msf/core/auxiliary/scanner.rb', line 56

def run
  @show_progress = datastore['ShowProgress']
  @show_percent  = datastore['ShowProgressPercent'].to_i

  if self.respond_to?(:session) && session
    datastore['RHOSTS'] = session.address
  end

  rhosts_walker  = Msf::RhostsWalker.new(self.datastore['RHOSTS'], self.datastore).to_enum
  @range_count   = rhosts_walker.count || 0
  @range_done    = 0
  @range_percent = 0

  threads_max = datastore['THREADS'].to_i
  @thread_list = []
  @scan_errors = []

  res = Queue.new
  results = Hash.new

  #
  # Sanity check threading given different conditions
  #

  if datastore['CPORT'].to_i != 0 && threads_max > 1
    print_error("Warning: A maximum of one thread is possible when a source port is set (CPORT)")
    print_error("Thread count has been adjusted to 1")
    threads_max = 1
  end

  if(Rex::Compat.is_windows)
    if(threads_max > 16)
      print_error("Warning: The Windows platform cannot reliably support more than 16 threads")
      print_error("Thread count has been adjusted to 16")
      threads_max = 16
    end
  end

  if(Rex::Compat.is_cygwin)
    if(threads_max > 200)
      print_error("Warning: The Cygwin platform cannot reliably support more than 200 threads")
      print_error("Thread count has been adjusted to 200")
      threads_max = 200
    end
  end

  begin

  if (self.respond_to?('run_host'))
    loop do
      # Stop scanning if we hit a fatal error
      break if has_fatal_errors?

      # Spawn threads for each host
      while (@thread_list.length < threads_max)

        # Stop scanning if we hit a fatal error
        break if has_fatal_errors?

        begin
          datastore = rhosts_walker.next
        rescue StopIteration
          datastore = nil
        end
        break unless datastore

        @thread_list << framework.threads.spawn("ScannerHost(#{self.refname})-#{datastore['RHOST']}", false, datastore.dup) do |thr_datastore|
          targ = thr_datastore['RHOST']
          nmod = self.replicant
          nmod.datastore = thr_datastore

          begin
            res << { targ => nmod.run_host(targ) }
          rescue ::Rex::BindFailed
            if datastore['CHOST']
              @scan_errors << "The source IP (CHOST) value of #{datastore['CHOST']} was not usable"
            end
          rescue Msf::Auxiliary::Scanner::AttemptFailed => e
            nmod.vprint_error("#{e}")
          rescue ::Rex::ConnectionError, ::Rex::ConnectionProxyError, ::Errno::ECONNRESET, ::Errno::EINTR, ::Rex::TimeoutError, ::Timeout::Error, ::EOFError
          rescue ::Interrupt,::NoMethodError, ::RuntimeError, ::ArgumentError, ::NameError
            raise $!
          rescue ::Exception => e
            print_status("Error: #{targ}: #{e.class} #{e.message}")
            elog("Error running against host #{targ}", error: e)
          ensure
            nmod.cleanup
          end
        end
      end

      # Do as much of this work as possible while other threads are running
      while !res.empty?
        results.merge! res.pop
      end

      # Stop scanning if we hit a fatal error
      break if has_fatal_errors?

      # Exit once we run out of hosts
      if(@thread_list.length == 0)
        break
      end

      # Attempt to wait for the oldest thread for a second,
      # remove any finished threads from the list
      # and continue on.
      tla = @thread_list.length
      @thread_list.first.join(1)
      @thread_list.delete_if { |t| not t.alive? }
      tlb = @thread_list.length

      @range_done += (tla - tlb)
      scanner_show_progress() if @show_progress
    end

    scanner_handle_fatal_errors
    return results
  end

  if (self.respond_to?('run_batch'))

    if (! self.respond_to?('run_batch_size'))
      print_status("This module needs to export run_batch_size()")
      return
    end

    size = run_batch_size()

    rhosts_walker = Msf::RhostsWalker.new(self.datastore['RHOSTS'], self.datastore).to_enum

    while(true)
      nohosts = false

      # Stop scanning if we hit a fatal error
      break if has_fatal_errors?

      while (@thread_list.length < threads_max)

        batch = []

        # Create batches from each set
        while (batch.length < size)
          begin
            datastore = rhosts_walker.next
          rescue StopIteration
            datastore = nil
          end
          if (not datastore)
            nohosts = true
            break
          end
          batch << datastore['RHOST']
        end

        # Create a thread for each batch
        if (batch.length > 0)
          thread = framework.threads.spawn("ScannerBatch(#{self.refname})", false, batch) do |bat|
            nmod = self.replicant
            mybatch = bat.dup
            begin
              nmod.run_batch(mybatch)
            rescue ::Rex::BindFailed
              if datastore['CHOST']
                @scan_errors << "The source IP (CHOST) value of #{datastore['CHOST']} was not usable"
              end
            rescue Msf::Auxiliary::Scanner::AttemptFailed => e
              print_error("#{e}")
            rescue ::Rex::ConnectionError, ::Rex::ConnectionProxyError, ::Errno::ECONNRESET, ::Errno::EINTR, ::Rex::TimeoutError, ::Timeout::Error
            rescue ::Interrupt,::NoMethodError, ::RuntimeError, ::ArgumentError, ::NameError
              raise $!
            rescue ::Exception => e
              print_status("Error: #{mybatch[0]}-#{mybatch[-1]}: #{e}")
            ensure
              nmod.cleanup
            end
          end
          thread[:batch_size] = batch.length
          @thread_list << thread
        end

        # Exit once we run out of hosts
        if (@thread_list.length == 0 or nohosts)
          break
        end
      end

      # Stop scanning if we hit a fatal error
      break if has_fatal_errors?

      # Exit if there are no more pending threads
      if (@thread_list.length == 0)
        break
      end

      # Attempt to wait for the oldest thread for a second,
      # remove any finished threads from the list
      # and continue on.
      tla = 0
      @thread_list.map {|t| tla += t[:batch_size] if t[:batch_size] }
      @thread_list.first.join(1)
      @thread_list.delete_if { |t| not t.alive? }
      tlb = 0
      @thread_list.map {|t| tlb += t[:batch_size] if t[:batch_size] }

      @range_done += tla - tlb
      scanner_show_progress() if @show_progress
    end

    scanner_handle_fatal_errors
    return
  end

  print_error("This module defined no run_host or run_batch methods")

  rescue ::Interrupt
    print_status("Caught interrupt from the console...")
    return
  ensure
    seppuko!()
  end
end

#scanner_handle_fatal_errorsObject



292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/msf/core/auxiliary/scanner.rb', line 292

def scanner_handle_fatal_errors
  return unless has_fatal_errors?
  return unless @thread_list

  # First kill any running threads
  @thread_list.each {|t| t.kill if t.alive? }

  # Show the unique errors triggered by the scan
  uniq_errors = @scan_errors.uniq
  uniq_errors.each do |emsg|
    print_error("Fatal: #{emsg}")
  end
  print_error("Scan terminated due to #{uniq_errors.size} fatal error(s)")
end

#scanner_progressObject



307
308
309
310
# File 'lib/msf/core/auxiliary/scanner.rb', line 307

def scanner_progress
  return 0 unless @range_done and @range_count
  pct = (@range_done / @range_count.to_f) * 100
end

#scanner_show_progressObject



312
313
314
315
316
317
318
319
320
321
# File 'lib/msf/core/auxiliary/scanner.rb', line 312

def scanner_show_progress
  # it should already be in the process of shutting down if there are fatal errors
  return if has_fatal_errors?
  pct = scanner_progress
  if pct >= (@range_percent + @show_percent)
    @range_percent = @range_percent + @show_percent
    tdlen = @range_count.to_s.length
    print_status(sprintf("Scanned %#{tdlen}d of %d hosts (%d%% complete)", @range_done, @range_count, pct))
  end
end

#seppuko!Object



279
280
281
282
283
284
285
286
# File 'lib/msf/core/auxiliary/scanner.rb', line 279

def seppuko!
  @thread_list.each do |t|
    begin
      t.kill if t.alive?
    rescue ::Exception
    end
  end
end