Module: Rex::Ui::Text::DispatcherShell

Includes:
Resource, Shell
Included in:
Msf::Ui::Console::Driver, Post::HWBridge::Ui::Console, Post::Meterpreter::Ui::Console
Defined in:
lib/rex/ui/text/dispatcher_shell.rb

Overview

The dispatcher shell class is designed to provide a generic means of processing various shell commands that may be located in different modules or chunks of codes. These chunks are referred to as command dispatchers. The only requirement for command dispatchers is that they prefix every method that they wish to be mirrored as a command with the cmd_ prefix.

Defined Under Namespace

Modules: CommandDispatcher

Instance Attribute Summary collapse

Attributes included from Shell

#cont_flag, #cont_prompt, #disable_output, #framework, #hist_last_saved, #histfile, #input, #local_hostname, #local_username, #log_source, #on_command_proc, #on_print_proc, #output, #prompt, #prompt_char, #stop_count, #stop_flag, #tab_complete_proc

Instance Method Summary collapse

Methods included from Shell

#_print_prompt, #format_prompt, #get_input_line, #init_tab_complete, #init_ui, #log_input, #log_output, #parse_line, #print, #print_error, #print_good, #print_line, #print_status, #print_warning, #prompt_yesno, #reset_ui, #run, #set_log_source, #stop, #stopped?, #supports_color?, #unset_log_source, #update_prompt

Methods included from Resource

#load_resource

Instance Attribute Details

#blockedObject

:nodoc:


659
660
661
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 659

def blocked
  @blocked
end

#busyObject

:nodoc:


658
659
660
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 658

def busy
  @busy
end

#dispatcher_stackObject

:nodoc:


656
657
658
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 656

def dispatcher_stack
  @dispatcher_stack
end

#tab_wordsObject

:nodoc:


657
658
659
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 657

def tab_words
  @tab_words
end

Instance Method Details

#append_dispatcher(dispatcher) ⇒ Object

Adds the supplied dispatcher to the end of the dispatcher stack so that it doesn't affect any enstack'd dispatchers.


556
557
558
559
560
561
562
563
564
565
566
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 556

def append_dispatcher(dispatcher)
  inst = dispatcher.new(self)
  self.dispatcher_stack.each { |disp|
    if (disp.name == inst.name)
      raise "Attempting to load already loaded dispatcher #{disp.name}"
    end
  }
  self.dispatcher_stack.push(inst)

  inst
end

#block_command(cmd) ⇒ Object

Block a specific command


612
613
614
615
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 612

def block_command(cmd)
  self.blocked ||= {}
  self.blocked[cmd] = true
end

#blocked_command?(cmd) ⇒ Boolean

Returns nil for an empty set of blocked commands.

Returns:

  • (Boolean)

604
605
606
607
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 604

def blocked_command?(cmd)
  return false if not self.blocked
  self.blocked.has_key?(cmd)
end

#current_dispatcherObject

Returns the current active dispatcher


580
581
582
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 580

def current_dispatcher
  self.dispatcher_stack[0]
end

#destack_dispatcherObject

Pop a dispatcher from the front of the stacker.


548
549
550
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 548

def destack_dispatcher
  self.dispatcher_stack.shift
end

#enstack_dispatcher(dispatcher) ⇒ Object

Push a dispatcher to the front of the stack.


539
540
541
542
543
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 539

def enstack_dispatcher(dispatcher)
  self.dispatcher_stack.unshift(inst = dispatcher.new(self))

  inst
end

#help_to_s(opts = {}) ⇒ Object

Return a readable version of a help banner for all of the enstacked dispatchers.

See CommandDispatcher#help_to_s


590
591
592
593
594
595
596
597
598
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 590

def help_to_s(opts = {})
  str = ''

  dispatcher_stack.reverse.each { |dispatcher|
    str << dispatcher.help_to_s
  }

  return str
end

#initialize(prompt, prompt_char = '>', histfile = nil, framework = nil) ⇒ Object

Initialize the dispatcher shell.


342
343
344
345
346
347
348
349
350
351
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 342

def initialize(prompt, prompt_char = '>', histfile = nil, framework = nil)
  super

  # Initialze the dispatcher array
  self.dispatcher_stack = []

  # Initialize the tab completion array
  self.tab_words = []
  self.on_command_proc = nil
end

#remove_dispatcher(name) ⇒ Object

Removes the supplied dispatcher instance.


571
572
573
574
575
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 571

def remove_dispatcher(name)
  self.dispatcher_stack.delete_if { |inst|
    (inst.name == name)
  }
end

#run_command(dispatcher, method, arguments) ⇒ Object

Runs the supplied command on the given dispatcher.


517
518
519
520
521
522
523
524
525
526
527
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 517

def run_command(dispatcher, method, arguments)
  self.busy = true

  if(blocked_command?(method))
    print_error("The #{method} command has been disabled.")
  else
    dispatcher.send('cmd_' + method, *arguments)
  end
ensure
  self.busy = false
end

#run_single(line, propagate_errors: false) ⇒ Object

Run a single command line.


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
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 'lib/rex/ui/text/dispatcher_shell.rb', line 456

def run_single(line, propagate_errors: false)
  arguments = parse_line(line)
  method    = arguments.shift
  found     = false
  error     = false

  # If output is disabled output will be nil
  output.reset_color if (output)

  if (method)
    entries = dispatcher_stack.length

    dispatcher_stack.each { |dispatcher|
      next if not dispatcher.respond_to?('commands')

      begin
        if (dispatcher.commands.has_key?(method) or dispatcher.deprecated_commands.include?(method))
          self.on_command_proc.call(line.strip) if self.on_command_proc
          run_command(dispatcher, method, arguments)
          found = true
        end
      rescue ::Interrupt
        found = true
        print_error("#{method}: Interrupted")
        raise if propagate_errors
      rescue OptionParser::ParseError => e
        print_error("#{method}: #{e.message}")
        raise if propagate_errors
      rescue
        error = $!

        print_error(
          "Error while running command #{method}: #{$!}" +
          "\n\nCall stack:\n#{[email protected].join("\n")}")

        raise if propagate_errors
      rescue ::Exception => e
        error = $!

        print_error(
          "Error while running command #{method}: #{$!}")

        raise if propagate_errors
      end

      # If the dispatcher stack changed as a result of this command,
      # break out
      break if (dispatcher_stack.length != entries)
    }

    if (found == false and error == false)
      unknown_command(method, line)
    end
  end

  return found
end

#shellsplitex(line) ⇒ Object

Split a line as Shellwords.split would however instead of raising an ArgumentError on unbalanced quotes return the remainder of the string as if the last character were the closing quote.


630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 630

def shellsplitex(line)
  quote = nil
  words = []
  field = String.new
  line.scan(/\G\s*(?>([^\s\\\'\"]+)|'([^\']*)'|"((?:[^\"\\]|\\.)*)"|(\\.?)|(\S))(\s|\z)?/m) do
    |word, sq, dq, esc, garbage, sep|
    if garbage
      if quote.nil?
        quote = garbage
      else
        field << garbage
      end
      next
    end

    field << (word || sq || (dq && dq.gsub(/\\([$`"\\\n])/, '\\1')) || esc.gsub(/\\(.)/, '\\1'))
    field << sep unless quote.nil?
    if quote.nil? && sep
      words << field
      field = String.new
    end
  end
  words << field unless quote.nil?
  {:quote => quote, :words => words}
end

#tab_complete(str) ⇒ Object

This method accepts the entire line of text from the Readline routine, stores all completed words, and passes the partial word to the real tab completion function. This works around a design problem in the Readline module and depends on the Readline.basic_word_break_characters variable being set to x00


360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 360

def tab_complete(str)
  # Check trailing whitespace so we can tell 'x' from 'x '
  str_match = str.match(/[^\\]([\\]{2})*\s+$/)
  str_trail = (str_match.nil?) ? '' : str_match[0]

  split_str = shellsplitex(str)
  # Split the line up by whitespace into words

  # Append an empty word if we had trailing whitespace
  split_str[:words] << '' if str_trail.length > 0

  # Place the word list into an instance variable
  self.tab_words = split_str[:words]

  # Pop the last word and pass it to the real method
  tab_complete_stub(self.tab_words.pop, quote: split_str[:quote])
end

#tab_complete_helper(dispatcher, str, words) ⇒ Object

Provide command-specific tab completion


436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 436

def tab_complete_helper(dispatcher, str, words)
  items = []

  tabs_meth = "cmd_#{words[0]}_tabs"
  # Is the user trying to tab complete one of our commands?
  if (dispatcher.commands.include?(words[0]) and dispatcher.respond_to?(tabs_meth))
    res = dispatcher.send(tabs_meth, str, words)
    return [] if res.nil?
    items.concat(res)
  else
    # Avoid the default completion list for known commands
    return []
  end

  return items
end

#tab_complete_stub(str, quote: nil) ⇒ Object

Performs tab completion of a command, if supported Current words can be found in self.tab_words


381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 381

def tab_complete_stub(str, quote: nil)
  items = []

  return nil if not str

  # puts "Words(#{tab_words.join(", ")}) Partial='#{str}'"

  # Next, try to match internal command or value completion
  # Enumerate each entry in the dispatcher stack
  dispatcher_stack.each { |dispatcher|

    # If no command is set and it supports commands, add them all
    if (tab_words.empty? and dispatcher.respond_to?('commands'))
      items.concat(dispatcher.commands.keys)
    end

    # If the dispatcher exports a tab completion function, use it
    if(dispatcher.respond_to?('tab_complete_helper'))
      res = dispatcher.tab_complete_helper(str, tab_words)
    else
      res = tab_complete_helper(dispatcher, str, tab_words)
    end

    if (res.nil?)
      # A nil response indicates no optional arguments
      return [''] if items.empty?
    else
      # Otherwise we add the completion items to the list
      items.concat(res)
    end
  }

  # Verify that our search string is a valid regex
  begin
    Regexp.compile(str,Regexp::IGNORECASE)
  rescue RegexpError
    str = Regexp.escape(str)
  end

  # @todo - This still doesn't fix some Regexp warnings:
  # ./lib/rex/ui/text/dispatcher_shell.rb:171: warning: regexp has `]' without escape

  # Match based on the partial word
  items.find_all { |word|
    word.downcase.start_with?(str.downcase) || word =~ /^#{str}/i
  # Prepend the rest of the command (or it all gets replaced!)
  }.map { |word|
    word = quote.nil? ? word.gsub(' ', '\ ') : quote.dup << word << quote.dup
    tab_words.dup.push(word).join(' ')
  }
end

#unblock_command(cmd) ⇒ Object

Unblock a specific command


620
621
622
623
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 620

def unblock_command(cmd)
  self.blocked || return
  self.blocked.delete(cmd)
end

#unknown_command(method, line) ⇒ Object

If the command is unknown…


532
533
534
# File 'lib/rex/ui/text/dispatcher_shell.rb', line 532

def unknown_command(method, line)
  print_error("Unknown command: #{method}.")
end