Class: Msf::Ui::Console::Driver

Inherits:
Driver
  • Object
show all
Includes:
FrameworkEventManager, Rex::Ui::Text::DispatcherShell
Defined in:
lib/msf/ui/console/driver.rb

Overview

This class implements a user interface driver on a console interface.

Constant Summary collapse

ConfigCore =
"framework/core"
ConfigGroup =
"framework/ui/console"
DefaultPrompt =
"%undmsf%clr"
DefaultPromptChar =
"%clr>"

Instance Attribute Summary collapse

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

#blocked, #busy, #dispatcher_stack, #tab_words

Attributes included from Rex::Ui::Text::Shell

#disable_output, #input, #on_command_proc, #on_print_proc, #output

Instance Method Summary collapse

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

#append_dispatcher, #block_command, #blocked_command?, #current_dispatcher, #destack_dispatcher, #enstack_dispatcher, #help_to_s, #remove_dispatcher, #run_command, #run_single, #tab_complete, #tab_complete_helper, #tab_complete_stub, #unblock_command

Methods included from Rex::Ui::Text::Shell

#init_tab_complete, #init_ui, #print, #print_error, #print_good, #print_line, #print_status, #print_warning, #reset_ui, #run, #set_log_source, #stopped?, #tab_complete, #unset_log_source, #update_prompt

Methods included from FrameworkEventManager

#deregister_event_handlers, #on_session_close, #on_session_open, #register_event_handlers

Methods included from SessionEvent

#on_session_close, #on_session_command, #on_session_download, #on_session_filedelete, #on_session_interact, #on_session_open, #on_session_output, #on_session_upload

Methods inherited from Driver

#cleanup, #run

Constructor Details

#initialize(prompt = DefaultPrompt, prompt_char = DefaultPromptChar, opts = {}) ⇒ Driver

Initializes a console driver instance with the supplied prompt string and prompt character. The optional hash can take extra values that will serve to initialize the console driver.

The optional hash values can include:

AllowCommandPassthru

Whether or not unknown commands should be passed through and executed by the local system.

RealReadline

Whether or to use the system Readline or the RBReadline (default)

HistFile

Name of a file to store command history


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
# File 'lib/msf/ui/console/driver.rb', line 62

def initialize(prompt = DefaultPrompt, prompt_char = DefaultPromptChar, opts = {})

  # Choose a readline library before calling the parent
  rl = false
  rl_err = nil
  begin
    if(opts['RealReadline'])
      require 'readline'
      rl = true
    end
  rescue ::LoadError
    rl_err = $!
  end

  # Default to the RbReadline wrapper
  require 'readline_compatible' if(not rl)

  histfile = opts['HistFile'] || Msf::Config.history_file

  # Initialize attributes
  self.framework = opts['Framework'] || Msf::Simple::Framework.create(opts)

  if self.framework.datastore['Prompt']
    prompt = self.framework.datastore['Prompt']
    prompt_char = self.framework.datastore['PromptChar'] || DefaultPromptChar
  end

  # Call the parent
  super(prompt, prompt_char, histfile, framework)

  # Temporarily disable output
  self.disable_output = true

  # Load pre-configuration
  load_preconfig

  # Initialize the user interface to use a different input and output
  # handle if one is supplied
  input = opts['LocalInput']
  input ||= Rex::Ui::Text::Input::Stdio.new

  if (opts['LocalOutput'])
    if (opts['LocalOutput'].kind_of?(String))
      output = Rex::Ui::Text::Output::File.new(opts['LocalOutput'])
    else
      output = opts['LocalOutput']
    end
  else
    output = Rex::Ui::Text::Output::Stdio.new
  end

  init_ui(input, output)
  init_tab_complete

  # Add the core command dispatcher as the root of the dispatcher
  # stack
  enstack_dispatcher(CommandDispatcher::Core)

  # Report readline error if there was one..
  if not rl_err.nil?
    print_error("***")
    print_error("* WARNING: Unable to load readline: #{rl_err}")
    print_error("* Falling back to RbReadLine")
    print_error("***")
  end


  # Add the database dispatcher if it is usable
  if (framework.db.usable)
    require 'msf/ui/console/command_dispatcher/db'
    enstack_dispatcher(CommandDispatcher::Db)
  else
    print_error("***")
    if framework.db.error == "disabled"
      print_error("* WARNING: Database support has been disabled")
    else
      print_error("* WARNING: No database support: #{framework.db.error.class} #{framework.db.error}")
    end
    print_error("***")
  end

  begin
    require 'openssl'
  rescue ::LoadError
    print_error("***")
    print_error("* WARNING: No OpenSSL support. This is required by meterpreter payloads and many exploits")
    print_error("* Please install the ruby-openssl package (apt-get install libopenssl-ruby on Debian/Ubuntu")
    print_error("***")
  end

  # Register event handlers
  register_event_handlers

  # Re-enable output
  self.disable_output = false

  # Whether or not command passthru should be allowed
  self.command_passthru = (opts['AllowCommandPassthru'] == false) ? false : true

  # Disables "dangerous" functionality of the console
  @defanged = opts['Defanged'] == true

  # If we're defanged, then command passthru should be disabled
  if @defanged
    self.command_passthru = false
  end

  # Parse any specified database.yml file
  if framework.db.usable and not opts['SkipDatabaseInit']

    # Append any migration paths necessary to bring the database online
    if opts['DatabaseMigrationPaths']
      opts['DatabaseMigrationPaths'].each do |migrations_path|
        ActiveRecord::Migrator.migrations_paths << migrations_path
      end
    end

    # Look for our database configuration in the following places, in order:
    # command line arguments
    # environment variable
    # configuration directory (usually ~/.msf3)
    dbfile = opts['DatabaseYAML']
    dbfile ||= ENV["MSF_DATABASE_CONFIG"]
    dbfile ||= File.join(Msf::Config.get_config_root, "database.yml")
    if (dbfile and File.exists? dbfile)
      if File.readable?(dbfile)
        dbinfo = YAML.load(File.read(dbfile))
        dbenv  = opts['DatabaseEnv'] || "production"
        db     = dbinfo[dbenv]
      else
        print_error("Warning, #{dbfile} is not readable. Try running as root or chmod.")
      end
      if not db
        print_error("No database definition for environment #{dbenv}")
      else
        if not framework.db.connect(db)
          if framework.db.error.to_s =~ /RubyGem version.*pg.*0\.11/i
            print_error("***")
            print_error("*")
            print_error("* Metasploit now requires version 0.11 or higher of the 'pg' gem for database support")
            print_error("* There a three ways to accomplish this upgrade:")
            print_error("* 1. If you run Metasploit with your system ruby, simply upgrade the gem:")
            print_error("*    $ rvmsudo gem install pg ")
            print_error("* 2. Use the Community Edition web interface to apply a Software Update")
            print_error("* 3. Uninstall, download the latest version, and reinstall Metasploit")
            print_error("*")
            print_error("***")
            print_error("")
            print_error("")
          end

          print_error("Failed to connect to the database: #{framework.db.error}")
        else
          self.framework.modules.refresh_cache_from_database

          if self.framework.modules.cache_empty?
            print_status("The initial module cache will be built in the background, this can take 2-5 minutes...")
          end
        end
      end
    end
  end

  # Initialize the module paths only if we didn't get passed a Framework instance
  unless opts['Framework']
    # Configure the framework module paths
    self.framework.init_module_paths
    self.framework.modules.add_module_path(opts['ModulePath']) if opts['ModulePath']

    # Rebuild the module cache in a background thread
    self.framework.threads.spawn("ModuleCacheRebuild", true) do
      self.framework.modules.refresh_cache_from_module_files
    end
  end

  # Load console-specific configuration (after module paths are added)
  load_config(opts['Config'])

  # Process things before we actually display the prompt and get rocking
  on_startup(opts)

  # Process the resource script
  if opts['Resource'] and opts['Resource'].kind_of? Array
    opts['Resource'].each { |r|
      load_resource(r)
    }
  else
    # If the opt is nil here, we load ~/.msf3/msfconsole.rc
    load_resource(opts['Resource'])
  end

  # Process any additional startup commands
  if opts['XCommands'] and opts['XCommands'].kind_of? Array
    opts['XCommands'].each { |c|
      run_single(c)
    }
  end
end

Instance Attribute Details

#active_moduleObject

The active module associated with the driver.


602
603
604
# File 'lib/msf/ui/console/driver.rb', line 602

def active_module
  @active_module
end

#active_resourceObject

The active resource file being processed by the driver


610
611
612
# File 'lib/msf/ui/console/driver.rb', line 610

def active_resource
  @active_resource
end

#active_sessionObject

The active session associated with the driver.


606
607
608
# File 'lib/msf/ui/console/driver.rb', line 606

def active_session
  @active_session
end

#command_passthruObject

Whether or not commands can be passed through.


598
599
600
# File 'lib/msf/ui/console/driver.rb', line 598

def command_passthru
  @command_passthru
end

#frameworkObject

The framework instance associated with this driver.


594
595
596
# File 'lib/msf/ui/console/driver.rb', line 594

def framework
  @framework
end

Instance Method Details

#defanged?Boolean

If defanged is true, dangerous functionality, such as exploitation, irb, and command shell passthru is disabled. In this case, an exception is raised.


617
618
619
620
621
# File 'lib/msf/ui/console/driver.rb', line 617

def defanged?
  if @defanged
    raise DefangedException
  end
end

#junit_error(tname, ftype, data = nil) ⇒ Object

Emit a new jUnit XML output file representing an error


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
# File 'lib/msf/ui/console/driver.rb', line 279

def junit_error(tname, ftype, data = nil)

  if not @junit_output_path
    raise RuntimeError, "No output path, call junit_setup() first"
  end

  data ||= framework.inspect.to_s

  e = REXML::Element.new("testsuite")

  c = REXML::Element.new("testcase")
  c.attributes["classname"] = "msfrc"
  c.attributes["name"]  = tname

  f = REXML::Element.new("failure")
  f.attributes["type"] = ftype

  f.text = data
  c << f
  e << c

  bname = ("msfrpc_#{tname}").gsub(/[^A-Za-z0-9\.\_]/, '')
  bname << "_" + Digest::MD5.hexdigest(tname)

  fname = ::File.join(@junit_output_path, "#{bname}.xml")
  cnt   = 0
  while ::File.exists?( fname )
    cnt  += 1
    fname = ::File.join(@junit_output_path, "#{bname}_#{cnt}.xml")
  end

  ::File.open(fname, "w") do |fd|
    fd.write(e.to_s)
  end

  print_error("Test Error: #{tname} - #{ftype} - #{data}")
end

#junit_fatal_error(tname, ftype, data) ⇒ Object

Emit a jUnit XML output file and throw a fatal exception


357
358
359
360
361
# File 'lib/msf/ui/console/driver.rb', line 357

def junit_fatal_error(tname, ftype, data)
  junit_error(tname, ftype, data)
  print_error("Exiting")
  run_single("exit -y")
end

#junit_pass(tname) ⇒ Object

Emit a new jUnit XML output file representing a success


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
351
# File 'lib/msf/ui/console/driver.rb', line 320

def junit_pass(tname)

  if not @junit_output_path
    raise RuntimeError, "No output path, call junit_setup() first"
  end

  # Generate the structure of a test case run
  e = REXML::Element.new("testsuite")
  c = REXML::Element.new("testcase")
  c.attributes["classname"] = "msfrc"
  c.attributes["name"]  = tname
  e << c

  # Generate a unique name
  bname = ("msfrpc_#{tname}").gsub(/[^A-Za-z0-9\.\_]/, '')
  bname << "_" + Digest::MD5.hexdigest(tname)

  # Generate the output path, allow multiple test with the same name
  fname = ::File.join(@junit_output_path, "#{bname}.xml")
  cnt   = 0
  while ::File.exists?( fname )
    cnt  += 1
    fname = ::File.join(@junit_output_path, "#{bname}_#{cnt}.xml")
  end

  # Write to our test output location, as specified with junit_setup
  ::File.open(fname, "w") do |fd|
    fd.write(e.to_s)
  end

  print_good("Test Pass: #{tname}")
end

#junit_setup(output_path) ⇒ Object

Configure a default output path for jUnit XML output


264
265
266
267
268
269
270
271
272
273
274
# File 'lib/msf/ui/console/driver.rb', line 264

def junit_setup(output_path)
  output_path = ::File.expand_path(output_path)

  ::FileUtils.mkdir_p(output_path)
  @junit_output_path = output_path
  @junit_error_count = 0
  print_status("Test Output: #{output_path}")

  # We need at least one test success in order to pass
  junit_pass("framework_loaded")
end

#load_config(path = nil) ⇒ Object

Loads configuration for the console.


385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
# File 'lib/msf/ui/console/driver.rb', line 385

def load_config(path=nil)
  begin
    conf = Msf::Config.load(path)
  rescue
    wlog("Failed to load configuration: #{$!}")
    return
  end

  # If we have configuration, process it
  if (conf.group?(ConfigGroup))
    conf[ConfigGroup].each_pair { |k, v|
      case k.downcase
        when "activemodule"
          run_single("use #{v}")
      end
    }
  end
end

#load_preconfigObject

Loads configuration that needs to be analyzed before the framework instance is created.


367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/msf/ui/console/driver.rb', line 367

def load_preconfig
  begin
    conf = Msf::Config.load
  rescue
    wlog("Failed to load configuration: #{$!}")
    return
  end

  if (conf.group?(ConfigCore))
    conf[ConfigCore].each_pair { |k, v|
      on_variable_set(true, k, v)
    }
  end
end

#load_resource(path = nil) ⇒ Object

Processes the resource script file for the console.


426
427
428
429
430
431
432
433
434
435
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
# File 'lib/msf/ui/console/driver.rb', line 426

def load_resource(path=nil)
  path ||= File.join(Msf::Config.config_directory, 'msfconsole.rc')
  return if not ::File.readable?(path)
  resource_file = ::File.read(path)

  self.active_resource = resource_file

  # Process ERB directives first
  print_status "Processing #{path} for ERB directives."
  erb = ERB.new(resource_file)
  processed_resource = erb.result(binding)

  lines = processed_resource.each_line.to_a
  bindings = {}
  while lines.length > 0

    line = lines.shift
    break if not line
    line.strip!
    next if line.length == 0
    next if line =~ /^#/

    # Pretty soon, this is going to need an XML parser :)
    # TODO: case matters for the tag and for binding names
    if line =~ /<ruby/
      if line =~ /\s+binding=(?:'(\w+)'|"(\w+)")(>|\s+)/
        bin = ($~[1] || $~[2])
        bindings[bin] = binding unless bindings.has_key? bin
        bin = bindings[bin]
      else
        bin = binding
      end
      buff = ''
      while lines.length > 0
        line = lines.shift
        break if not line
        break if line =~ /<\/ruby>/
        buff << line
      end
      if ! buff.empty?
        print_status("resource (#{path})> Ruby Code (#{buff.length} bytes)")
        begin
          eval(buff, bin)
        rescue ::Interrupt
          raise $!
        rescue ::Exception => e
          print_error("resource (#{path})> Ruby Error: #{e.class} #{e} #{e.backtrace}")
        end
      end
    else
      print_line("resource (#{path})> #{line}")
      run_single(line)
    end
  end

  self.active_resource = nil
end

#on_startup(opts = {}) ⇒ Object

Called before things actually get rolling such that banners can be displayed, scripts can be processed, and other fun can be had.


525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/msf/ui/console/driver.rb', line 525

def on_startup(opts = {})
  # Check for modules that failed to load
  if framework.modules.module_load_error_by_path.length > 0
    print_error("WARNING! The following modules could not be loaded!")

    framework.modules.module_load_error_by_path.each do |path, error|
      print_error("\t#{path}: #{error}")
    end
  end

  framework.events.on_ui_start(Msf::Framework::Revision)

  run_single("banner") unless opts['DisableBanner']

  opts["Plugins"].each do |plug|
    run_single("load '#{plug}'")
  end if opts["Plugins"]

  self.on_command_proc = Proc.new { |command| framework.events.on_ui_command(command) }
end

#on_variable_set(glob, var, val) ⇒ Object

Called when a variable is set to a specific value. This allows the console to do extra processing, such as enabling logging or doing some other kind of task. If this routine returns false it will indicate that the variable is not being set to a valid value.


552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
# File 'lib/msf/ui/console/driver.rb', line 552

def on_variable_set(glob, var, val)
  case var.downcase
    when "payload"

      if (framework and framework.payloads.valid?(val) == false)
        return false
      elsif (active_module)
        active_module.datastore.clear_non_user_defined
      elsif (framework)
        framework.datastore.clear_non_user_defined
      end
    when "sessionlogging"
      handle_session_logging(val) if (glob)
    when "consolelogging"
      handle_console_logging(val) if (glob)
    when "loglevel"
      handle_loglevel(val) if (glob)
    when "prompt"
      update_prompt(val, framework.datastore['PromptChar'] || DefaultPromptChar, true)
    when "promptchar"
      update_prompt(framework.datastore['Prompt'], val, true)
  end
end

#on_variable_unset(glob, var) ⇒ Object

Called when a variable is unset. If this routine returns false it is an indication that the variable should not be allowed to be unset.


580
581
582
583
584
585
586
587
588
589
# File 'lib/msf/ui/console/driver.rb', line 580

def on_variable_unset(glob, var)
  case var.downcase
    when "sessionlogging"
      handle_session_logging('0') if (glob)
    when "consolelogging"
      handle_console_logging('0') if (glob)
    when "loglevel"
      handle_loglevel(nil) if (glob)
  end
end

#save_configObject

Saves configuration for the console.


407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/msf/ui/console/driver.rb', line 407

def save_config
  # Build out the console config group
  group = {}

  if (active_module)
    group['ActiveModule'] = active_module.fullname
  end

  # Save it
  begin
    Msf::Config.save(ConfigGroup => group)
  rescue ::Exception
    print_error("Failed to save console config: #{$!}")
  end
end

#save_recent_history(path) ⇒ Object

Saves the recent history to the specified file


487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/msf/ui/console/driver.rb', line 487

def save_recent_history(path)
  num = Readline::HISTORY.length - hist_last_saved - 1

  tmprc = ""
  num.times { |x|
    tmprc << Readline::HISTORY[hist_last_saved + x] + "\n"
  }

  if tmprc.length > 0
    print_status("Saving last #{num} commands to #{path} ...")
    save_resource(tmprc, path)
  else
    print_error("No commands to save!")
  end

  # Always update this, even if we didn't save anything. We do this
  # so that we don't end up saving the "makerc" command itself.
  self.hist_last_saved = Readline::HISTORY.length
end

#save_resource(data, path = nil) ⇒ Object

Creates the resource script file for the console.


510
511
512
513
514
515
516
517
518
519
# File 'lib/msf/ui/console/driver.rb', line 510

def save_resource(data, path=nil)
  path ||= File.join(Msf::Config.config_directory, 'msfconsole.rc')

  begin
    rcfd = File.open(path, 'w')
    rcfd.write(data)
    rcfd.close
  rescue ::Exception
  end
end

#stopObject


623
624
625
626
# File 'lib/msf/ui/console/driver.rb', line 623

def stop
  framework.events.on_ui_stop()
  super
end