Class: Msf::Ui::Console::CommandDispatcher::Core

Inherits:
Object
  • Object
show all
Includes:
Msf::Ui::Console::CommandDispatcher
Defined in:
lib/msf/ui/console/command_dispatcher/core.rb

Overview

Command dispatcher for core framework commands, such as module loading, session interaction, and other general things.

Constant Summary collapse

DefangedProhibitedDataStoreElements =

The list of data store elements that cannot be set when in defanged mode.

[ "MsfModulePaths" ]
@@sessions_opts =

Session command options

Rex::Parser::Arguments.new(
"-c" => [ true,  "Run a command on the session given with -i, or all"],
"-h" => [ false, "Help banner"                                    ],
"-i" => [ true,  "Interact with the supplied session ID"          ],
"-l" => [ false, "List all active sessions"                       ],
"-v" => [ false, "List verbose fields"                            ],
"-q" => [ false, "Quiet mode"                                     ],
"-d" => [ true,  "Detach an interactive session"                  ],
"-k" => [ true,  "Terminate session"                              ],
"-K" => [ false, "Terminate all sessions"                         ],
"-s" => [ true,  "Run a script on the session given with -i, or all"],
"-r" => [ false, "Reset the ring buffer for the session given with -i, or all"],
"-u" => [ true,  "Upgrade a win32 shell to a meterpreter session" ])
@@jobs_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ],
"-k" => [ true,  "Terminate the specified job name."              ],
"-K" => [ false, "Terminate all running jobs."                    ],
"-i" => [ true,  "Lists detailed information about a running job."],
"-l" => [ false, "List all running jobs."                         ],
"-v" => [ false, "Print more detailed info.  Use with -i and -l"  ])
@@threads_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ],
"-k" => [ true,  "Terminate the specified thread ID."             ],
"-K" => [ false, "Terminate all non-critical threads."            ],
"-i" => [ true,  "Lists detailed information about a thread."     ],
"-l" => [ false, "List all background threads."                   ],
"-v" => [ false, "Print more detailed info.  Use with -i and -l"  ])
@@connect_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ],
"-p" => [ true,  "List of proxies to use."                        ],
"-C" => [ false, "Try to use CRLF for EOL sequence."              ],
"-c" => [ true,  "Specify which Comm to use."                     ],
"-i" => [ true,  "Send the contents of a file."                   ],
"-P" => [ true,  "Specify source port."                           ],
"-S" => [ true,  "Specify source address."                        ],
"-s" => [ false, "Connect with SSL."                              ],
"-u" => [ false, "Switch to a UDP socket."                        ],
"-w" => [ true,  "Specify connect timeout."                       ],
"-z" => [ false, "Just try to connect, then return."              ])
@@grep_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ],
"-i" => [ false, "Ignore case."                                   ],
"-m" => [ true,  "Stop after arg matches."                        ],
"-v" => [ false, "Invert match."                                  ],
"-A" => [ true,  "Show arg lines of output After a match."        ],
"-B" => [ true,  "Show arg lines of output Before a match."       ],
"-s" => [ true,  "Skip arg lines of output before attempting match."],
"-k" => [ true,  "Keep (include) arg lines at start of output."   ],
"-c" => [ false, "Only print a count of matching lines."          ])
@@search_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ])
@@go_pro_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ])

Instance Attribute Summary

Attributes included from Msf::Ui::Console::CommandDispatcher

#driver

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

#shell, #tab_complete_items

Instance Method Summary collapse

Methods included from Msf::Ui::Console::CommandDispatcher

#active_module, #active_module=, #active_session, #active_session=, #defanged?, #framework, #log_error

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

#cmd_help, #cmd_help_help, #cmd_help_tabs, #deprecated_cmd, #deprecated_commands, #deprecated_help, #help_to_s, #print, #print_error, #print_good, #print_line, #print_status, #print_warning, #tab_complete_filenames, #update_prompt

Constructor Details

#initialize(driver) ⇒ Core

Initializes the datastore cache


148
149
150
151
152
153
154
155
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 148

def initialize(driver)
  super

  @dscache = {}
  @cache_payloads = nil
  @previous_module = nil
  @module_name_stack = []
end

Instance Method Details

#cmd_back(*args) ⇒ Object

Pop the current dispatcher stack context, assuming it isn't pointed at the core or database backend stack context.


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

def cmd_back(*args)
  if (driver.dispatcher_stack.size > 1 and
      driver.current_dispatcher.name != 'Core' and
      driver.current_dispatcher.name != 'Database Backend')
    # Reset the active module if we have one
    if (active_module)

      # Do NOT reset the UI anymore
      # active_module.reset_ui

      # Save the module's datastore so that we can load it later
      # if the module is used again
      @dscache[active_module.fullname] = active_module.datastore.dup

      self.active_module = nil
    end

    # Destack the current dispatcher
    driver.destack_dispatcher

    # Restore the prompt
    prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt
    prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar
    driver.update_prompt("#{prompt}", prompt_char, true)
  end
end

#cmd_back_helpObject


313
314
315
316
317
318
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 313

def cmd_back_help
  print_line "Usage: back"
  print_line
  print_line "Return to the global dispatcher context"
  print_line
end

#cmd_banner(*args) ⇒ Object

Display one of the fabulous banners.


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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 384

def cmd_banner(*args)
  banner  = "%cya" + Banner.to_s + "%clr\n\n"

  if is_apt
    content = [
      "Large pentest? List, sort, group, tag and search your hosts and services\nin Metasploit Pro -- type 'go_pro' to launch it now.",
      "Frustrated with proxy pivoting? Upgrade to layer-2 VPN pivoting with\nMetasploit Pro -- type 'go_pro' to launch it now.",
      "Save your shells from AV! Upgrade to advanced AV evasion using dynamic\nexe templates with Metasploit Pro -- type 'go_pro' to launch it now.",
      "Easy phishing: Set up email templates, landing pages and listeners\nin Metasploit Pro's wizard -- type 'go_pro' to launch it now.",
      "Using notepad to track pentests? Have Metasploit Pro report on hosts,\nservices, sessions and evidence -- type 'go_pro' to launch it now.",
      "Tired of typing 'set RHOSTS'? Click & pwn with Metasploit Pro\n-- type 'go_pro' to launch it now."
    ]
    banner << content.sample # Ruby 1.9-ism!
    banner << "\n\n"
  end

  banner << "       =[ %yelmetasploit v#{Msf::Framework::Version} [core:#{Msf::Framework::VersionCore} api:#{Msf::Framework::VersionAPI}]%clr ]\n"
  banner << "+ -- --=[ "
  banner << "#{framework.stats.num_exploits} exploits - #{framework.stats.num_auxiliary} auxiliary - #{framework.stats.num_post} post ]\n"
  banner << "+ -- --=[ "

  oldwarn = nil
  avdwarn = nil

  banner << "#{framework.stats.num_payloads} payloads - #{framework.stats.num_encoders} encoders - #{framework.stats.num_nops} nops      ]\n"
  if ( ::Msf::Framework::RepoRevision.to_i > 0 and ::Msf::Framework::RepoUpdatedDate)
    tstamp = ::Msf::Framework::RepoUpdatedDate.strftime("%Y.%m.%d")
    banner << "       =[ svn r#{::Msf::Framework::RepoRevision} updated #{::Msf::Framework::RepoUpdatedDaysNote} (#{tstamp})\n"
    if(::Msf::Framework::RepoUpdatedDays > 7)
      oldwarn = []
      oldwarn << "Warning: This copy of the Metasploit Framework was last updated #{::Msf::Framework::RepoUpdatedDaysNote}."
      oldwarn << "         We recommend that you update the framework at least every other day."
      oldwarn << "         For information on updating your copy of Metasploit, please see:"
      oldwarn << "             https://community.rapid7.com/docs/DOC-1306"
      oldwarn << ""
    end
  end

  if ::Msf::Framework::EICARCorrupted
    avdwarn = []
    avdwarn << "Warning: This copy of the Metasploit Framework has been corrupted by an installed anti-virus program."
    avdwarn << "         We recommend that you disable your anti-virus or exclude your Metasploit installation path,"
    avdwarn << "         then restore the removed files from quarantine or reinstall the framework. For more info: "
    avdwarn << "             https://community.rapid7.com/docs/DOC-1273"
    avdwarn << ""
  end

  # We're running a two week survey to gather feedback from users.
  # Let's make sure we reach regular msfconsole users.
  # TODO: Get rid of this sometime after 2014-01-23
  survey_expires = Time.new(2014,"Jan",22,23,59,59,"-05:00")
  if Time.now.to_i < survey_expires.to_i
    banner << "+ -- --=[ Answer Q's about Metasploit and win a WiFi Pineapple Mk5   ]\n"
    banner << "+ -- --=[ http://bit.ly/msfsurvey (Expires #{survey_expires.ctime}) ]\n"
  end

  # Display the banner
  print_line(banner)

  if(oldwarn)
    oldwarn.map{|line| print_line(line) }
  end

  if(avdwarn)
    avdwarn.map{|line| print_error(line) }
  end

end

#cmd_banner_helpObject


374
375
376
377
378
379
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 374

def cmd_banner_help
  print_line "Usage: banner"
  print_line
  print_line "Print a stunning ascii art banner along with version information and module counts"
  print_line
end

#cmd_cd(*args) ⇒ Object

Change the current working directory


361
362
363
364
365
366
367
368
369
370
371
372
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 361

def cmd_cd(*args)
  if(args.length == 0)
    print_error("No path specified")
    return
  end

  begin
    Dir.chdir(args.join(" ").strip)
  rescue ::Exception
    print_error("The specified path does not exist")
  end
end

#cmd_cd_helpObject


351
352
353
354
355
356
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 351

def cmd_cd_help
  print_line "Usage: cd <directory>"
  print_line
  print_line "Change the current working directory"
  print_line
end

#cmd_color(*args) ⇒ Object


182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 182

def cmd_color(*args)
  case args[0]
  when "auto"
    driver.output.auto_color
  when "true"
    driver.output.enable_color
  when "false"
    driver.output.disable_color
  else
    cmd_color_help
    return
  end
  driver.update_prompt
end

#cmd_color_helpObject


175
176
177
178
179
180
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 175

def cmd_color_help
  print_line "Usage: color <'true'|'false'|'auto'>"
  print_line
  print_line "Enable or disable color output."
  print_line
end

#cmd_connect(*args) ⇒ Object

Talk to a host


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
513
514
515
516
517
518
519
520
521
522
523
524
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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 464

def cmd_connect(*args)
  if args.length < 2 or args.include?("-h")
    cmd_connect_help
    return false
  end

  crlf = false
  commval = nil
  fileval = nil
  proxies = nil
  srcaddr = nil
  srcport = nil
  ssl = false
  udp = false
  cto = nil
  justconn = false
  aidx = 0

  @@connect_opts.parse(args) do |opt, idx, val|
    case opt
      when "-C"
        crlf = true
        aidx = idx + 1
      when "-c"
        commval = val
        aidx = idx + 2
      when "-i"
        fileval = val
        aidx = idx + 2
      when "-P"
        srcport = val
        aidx = idx + 2
      when "-p"
        proxies = val
        aidx = idx + 2
      when "-S"
        srcaddr = val
        aidx = idx + 2
      when "-s"
        ssl = true
        aidx = idx + 1
      when "-w"
        cto = val.to_i
        aidx = idx + 2
      when "-u"
        udp = true
        aidx = idx + 1
      when "-z"
        justconn = true
        aidx = idx + 1
    end
  end

  commval = "Local" if commval =~ /local/i

  if fileval
    begin
      raise "Not a file" if File.ftype(fileval) != "file"
      infile = ::File.open(fileval)
    rescue
      print_error("Can't read from '#{fileval}': #{$!}")
      return false
    end
  end

  args = args[aidx .. -1]

  if args.length < 2
    print_error("You must specify a host and port")
    return false
  end

  host = args[0]
  port = args[1]

  comm = nil

  if commval
    begin
      if Rex::Socket::Comm.const_defined?(commval)
        comm = Rex::Socket::Comm.const_get(commval)
      end
    rescue NameError
    end

    if not comm
      session = framework.sessions.get(commval)

      if session.kind_of?(Msf::Session::Comm)
        comm = session
      end
    end

    if not comm
      print_error("Invalid comm '#{commval}' selected")
      return false
    end
  end

  begin
    klass = udp ? ::Rex::Socket::Udp : ::Rex::Socket::Tcp
    sock = klass.create({
      'Comm'      => comm,
      'Proxies'   => proxies,
      'SSL'       => ssl,
      'PeerHost'  => host,
      'PeerPort'  => port,
      'LocalHost' => srcaddr,
      'LocalPort' => srcport,
      'Timeout'   => cto,
      'Context'   => {
        'Msf' => framework
      }
    })
  rescue
    print_error("Unable to connect: #{$!}")
    return false
  end

  print_status("Connected to #{host}:#{port}")

  if justconn
    sock.close
    infile.close if infile
    return true
  end

  cin = infile || driver.input
  cout = driver.output

  begin
    # Console -> Network
    c2n = framework.threads.spawn("ConnectConsole2Network", false, cin, sock) do |input, output|
      while true
        begin
          res = input.gets
          break if not res
          if crlf and (res =~ /^\n$/ or res =~ /[^\r]\n$/)
            res.gsub!(/\n$/, "\r\n")
          end
          output.write res
        rescue ::EOFError, ::IOError
          break
        end
      end
    end

    # Network -> Console
    n2c = framework.threads.spawn("ConnectNetwork2Console", false, sock, cout, c2n) do |input, output, cthr|
      while true
        begin
          res = input.read(65535)
          break if not res
          output.print res
        rescue ::EOFError, ::IOError
          break
        end
      end

      Thread.kill(cthr)
    end

    c2n.join

  rescue ::Interrupt
    c2n.kill
    n2c.kill
  end


  sock.close rescue nil
  infile.close if infile

  true
end

#cmd_connect_helpObject


453
454
455
456
457
458
459
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 453

def cmd_connect_help
  print_line "Usage: connect [options] <host> <port>"
  print_line
  print_line "Communicate with a host, similar to interacting via netcat, taking advantage of"
  print_line "any configured session pivoting."
  print @@connect_opts.usage
end

#cmd_editObject

Edit the currently active module


657
658
659
660
661
662
663
664
665
666
667
668
669
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 657

def cmd_edit
  unless local_editor
    print_error "$VISUAL or $EDITOR must be set first. Try 'export EDITOR=/usr/bin/vim'"
    return
  end
  if active_module
    path = active_module.file_path
    print_status "Launching #{local_editor} #{path}"
    system(local_editor,path)
  else
    print_error "Nothing to edit -- try using a module first."
  end
end

#cmd_edit_helpObject


644
645
646
647
648
649
650
651
652
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 644

def cmd_edit_help
  msg = "Edit the currently active module"
  msg = "#{msg} #{local_editor ? "with #{local_editor}" : "($VISUAL or $EDITOR must be set first)"}."
  print_line "Usage: edit"
  print_line
  print_line msg
  print_line "When done editing, you must reload the module with 'reload' or 'rexploit'."
  print_line
end

#cmd_exit(*args) ⇒ Object Also known as: cmd_quit

Instructs the driver to stop executing.


674
675
676
677
678
679
680
681
682
683
684
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 674

def cmd_exit(*args)
  forced = false
  forced = true if (args[0] and args[0] =~ /-y/i)

  if(framework.sessions.length > 0 and not forced)
    print_status("You have active sessions open, to exit anyway type \"exit -y\"")
    return
  end

  driver.stop
end

#cmd_go_pro(*args) ⇒ Object


2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2929

def cmd_go_pro(*args)
  @@go_pro_opts.parse(args) do |opt, idx, val|
    case opt
    when "-h"
      cmd_go_pro_help
      return false
    end
  end
  unless is_apt
    print_warning "This command is only available on deb package installations, such as Kali Linux."
    return false
  end
  unless is_metasploit_debian_package_installed
    print_warning "You need to install the 'metasploit' package first."
    print_warning "Type 'apt-get install -y metasploit' to do this now, then exit"
    print_warning "and restart msfconsole to try again."
    return false
  end
  # If I've gotten this far, I know that this is apt-installed, the
  # metasploit package is here, and I'm ready to rock.
  if is_metasploit_service_running
    launch_metasploit_browser
  else
    print_status "Starting the Metasploit services. This can take a little time."
    start_metasploit_service
    select(nil,nil,nil,3)
    if is_metasploit_service_running
      launch_metasploit_browser
    else
      print_error "Metasploit services aren't running. Type 'service metasploit start' and try again."
    end
  end
  return true
end

#cmd_go_pro_helpObject


2922
2923
2924
2925
2926
2927
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2922

def cmd_go_pro_help
  print_line "Usage: go_pro"
  print_line
  print_line "Launch the Metasploit web GUI"
  print_line
end

#cmd_grep(*args) ⇒ String?

Greps the output of another console command, usage is similar the shell grep command grep [options] pattern other_cmd [other command's args], similar to the shell's grep [options] pattern file however it also includes -k to keep lines and -s to skip lines. grep -k 5 is useful for keeping table headers

Parameters:

  • args (Array<String>)

    Args to the grep command minimally including a pattern & a command to search

Returns:

  • (String, nil)

    Results matching the regular expression given


2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2545

def cmd_grep(*args)
  return cmd_grep_help if args.length < 2
  match_mods = {:insensitive => false}
  output_mods = {:count => false, :invert => false}
  @@grep_opts.parse(args.dup) do |opt, idx, val|
    case opt
      when "-h"
        return cmd_grep_help
      when "-m"
        # limit to arg matches
        match_mods[:max] = val.to_i
        # delete opt and val from args list
        args.shift(2)
      when "-A"
        # also return arg lines after a match
        output_mods[:after] = val.to_i
        # delete opt and val from args list
        args.shift(2)
      when "-B"
        # also return arg lines before a match
        output_mods[:before] = val.to_i
        # delete opt and val from args list
        args.shift(2)
      when "-v"
        # invert match
        match_mods[:invert] = true
        # delete opt from args list
        args.shift
      when "-i"
        # case insensitive
        match_mods[:insensitive] = true
        args.shift
      when "-c"
        # just count matches
        output_mods[:count] = true
        args.shift
      when "-k"
        # keep arg number of lines at the top of the output, useful for commands with table headers in output
        output_mods[:keep] = val.to_i
        args.shift(2)
      when "-s"
        # skip arg number of lines at the top of the output, useful for avoiding undesirable matches
        output_mods[:skip] = val.to_i
        args.shift(2)
    end
  end
  # after deleting parsed options, the only args left should be the pattern, the cmd to run, and cmd args
  pattern = args.shift
  if match_mods[:insensitive]
    rx = Regexp.new(pattern, true)
  else
    rx = Regexp.new(pattern)
  end
  cmd = args.join(" ")

  # get a ref to the current console driver
  orig_driver = self.driver
  # redirect output after saving the old ones and getting a new output buffer to use for redirect
  orig_driver_output = orig_driver.output
  orig_driver_input = orig_driver.input

  # we use a rex buffer but add a write method to the instance, which is
  # required in order to be valid $stdout
  temp_output = Rex::Ui::Text::Output::Buffer.new
  temp_output.extend Rex::Ui::Text::Output::Buffer::Stdout

  orig_driver.init_ui(orig_driver_input,temp_output)
  # run the desired command to be grepped
  orig_driver.run_single(cmd)
  # restore original output
  orig_driver.init_ui(orig_driver_input,orig_driver_output)
  # restore the prompt so we don't get "msf >  >".
  prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt
  prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar
  mod = active_module
  if mod # if there is an active module, give them the fanciness they have come to expect
    driver.update_prompt("#{prompt} #{mod.type}(%bld%red#{mod.shortname}%clr) ", prompt_char, true)
  else
    driver.update_prompt("#{prompt}", prompt_char, true)
  end

  # dump the command's output so we can grep it
  cmd_output = temp_output.dump_buffer

  # Bail if the command failed
  if cmd_output =~ /Unknown command:/
    print_error("Unknown command: #{args[0]}.")
    return false
  end
  # put lines into an array so we can access them more easily and split('\n') doesn't work on the output obj.
  all_lines = cmd_output.lines.select {|line| line}
  # control matching based on remaining match_mods (:insensitive was already handled)
  if match_mods[:invert]
    statement = 'not line =~ rx'
  else
    statement = 'line =~ rx'
  end

  our_lines = []
  count = 0
  all_lines.each_with_index do |line, line_num|
    next if (output_mods[:skip] and line_num < output_mods[:skip])
    our_lines << line if (output_mods[:keep] and line_num < output_mods[:keep])
    # we don't wan't to keep processing if we have a :max and we've reached it already (not counting skips/keeps)
    break if match_mods[:max] and count >= match_mods[:max]
    if eval statement
      count += 1
      # we might get a -A/after and a -B/before at the same time
      our_lines += retrieve_grep_lines(all_lines,line_num,output_mods[:before], output_mods[:after])
    end
  end

  # now control output based on remaining output_mods such as :count
  return print_status(count.to_s) if output_mods[:count]
  our_lines.each {|line| print line}
end

#cmd_grep_helpObject


2530
2531
2532
2533
2534
2535
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2530

def cmd_grep_help
  print_line "Usage: grep [options] pattern cmd"
  print_line
  print_line "Grep the results of a console command (similar to Linux grep command)"
  print(@@grep_opts.usage())
end

#cmd_grep_tabs(str, words) ⇒ Object

Tab completion for the grep command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


2669
2670
2671
2672
2673
2674
2675
2676
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2669

def cmd_grep_tabs(str, words)
  tabs = @@grep_opts.fmt.keys || [] # default to use grep's options
  # if not an opt, use normal tab comp.
  # @todo uncomment out next line when tab_completion normalization is complete RM7649 or
  # replace with new code that permits "nested" tab completion
  # tabs = driver.get_all_commands if (str and str =~ /\w/)
  tabs
end

#cmd_info(*args) ⇒ Object

Displays information about one or more module.


714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 714

def cmd_info(*args)
  if (args.length == 0)
    if (active_module)
      print(Serializer::ReadableText.dump_module(active_module))
      return true
    else
      cmd_info_help
      return false
    end
  elsif args.include? "-h"
    cmd_info_help
    return false
  end

  args.each { |name|
    mod = framework.modules.create(name)

    if (mod == nil)
      print_error("Invalid module: #{name}")
    else
      print(Serializer::ReadableText.dump_module(mod))
    end
  }
end

#cmd_info_helpObject


703
704
705
706
707
708
709
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 703

def cmd_info_help
  print_line "Usage: info <module name> [mod2 mod3 ...]"
  print_line
  print_line "Queries the supplied module or modules for information. If no module is given,"
  print_line "show info for the currently active module."
  print_line
end

#cmd_info_tabs(str, words) ⇒ Object

Tab completion for the info command (same as use)

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


746
747
748
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 746

def cmd_info_tabs(str, words)
  cmd_use_tabs(str, words)
end

#cmd_irb(*args) ⇒ Object

Goes into IRB scripting mode


760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 760

def cmd_irb(*args)
  defanged?

  print_status("Starting IRB shell...\n")

  begin
    Rex::Ui::Text::IrbShell.new(binding).run
  rescue
    print_error("Error during IRB: #{$!}\n\n#{[email protected].join("\n")}")
  end

  # Reset tab completion
  if (driver.input.supports_readline)
    driver.input.reset_tab_completion
  end
end

#cmd_irb_helpObject


750
751
752
753
754
755
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 750

def cmd_irb_help
  print_line "Usage: irb"
  print_line
  print_line "Drop into an interactive Ruby environment"
  print_line
end

#cmd_jobs(*args) ⇒ Object

Displays and manages running jobs for the active instance of the framework.


788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 788

def cmd_jobs(*args)
  # Make the default behavior listing all jobs if there were no options
  # or the only option is the verbose flag
  if (args.length == 0 or args == ["-v"])
    args.unshift("-l")
  end

  verbose = false
  dump_list = false
  dump_info = false
  job_id = nil

  # Parse the command options
  @@jobs_opts.parse(args) { |opt, idx, val|
    case opt
      when "-v"
        verbose = true
      when "-l"
        dump_list = true

      # Terminate the supplied job name
      when "-k"
        if (not framework.jobs.has_key?(val))
          print_error("No such job")
        else
          print_line("Stopping job: #{val}...")
          framework.jobs.stop_job(val)
        end
      when "-K"
        print_line("Stopping all jobs...")
        framework.jobs.each_key do |i|
          framework.jobs.stop_job(i)
        end
      when "-i"
        # Defer printing anything until the end of option parsing
        # so we can check for the verbose flag.
        dump_info = true
        job_id = val
      when "-h"
        cmd_jobs_help
        return false
    end
  }

  if (dump_list)
    print("\n" + Serializer::ReadableText.dump_jobs(framework, verbose) + "\n")
  end
  if (dump_info)
    if (job_id and framework.jobs[job_id.to_s])
      job = framework.jobs[job_id.to_s]
      mod = job.ctx[0]

      output  = "\n"
      output += "Name: #{mod.name}"
      output += ", started at #{job.start_time}" if job.start_time
      print_line(output)

      if (mod.options.has_options?)
        show_options(mod)
      end

      if (verbose)
        mod_opt = Serializer::ReadableText.dump_advanced_options(mod,'   ')
        print_line("\nModule advanced options:\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
      end
    else
      print_line("Invalid Job ID")
    end
  end
end

#cmd_jobs_helpObject


777
778
779
780
781
782
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 777

def cmd_jobs_help
  print_line "Usage: jobs [options]"
  print_line
  print_line "Active job manipulation and interaction."
  print @@jobs_opts.usage()
end

#cmd_jobs_tabs(str, words) ⇒ Object

Tab completion for the jobs command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


866
867
868
869
870
871
872
873
874
875
876
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 866

def cmd_jobs_tabs(str, words)
  if words.length == 1
    return @@jobs_opts.fmt.keys
  end

  if @@jobs_opts.fmt[words[1]][0] and (words.length == 2)
    return framework.jobs.keys
  end

  []
end

#cmd_kill(*args) ⇒ Object


885
886
887
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 885

def cmd_kill(*args)
  cmd_jobs("-k", *args)
end

#cmd_kill_helpObject


878
879
880
881
882
883
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 878

def cmd_kill_help
  print_line "Usage: kill <job1> [job2 ...]"
  print_line
  print_line "Equivalent to 'jobs -k job1 -k job2 ...'"
  print @@jobs_opts.usage()
end

#cmd_kill_tabs(str, words) ⇒ Object

Tab completion for the kill command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


896
897
898
899
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 896

def cmd_kill_tabs(str, words)
  return [] if words.length > 1
  framework.jobs.keys
end

#cmd_load(*args) ⇒ Object

Loads a plugin from the supplied path. If no absolute path is supplied, the framework root plugin directory is used.


1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1044

def cmd_load(*args)
  defanged?

  if (args.length == 0)
    cmd_load_help
    return false
  end

  # Default to the supplied argument path.
  path = args.shift
  opts  = {
    'LocalInput'    => driver.input,
    'LocalOutput'   => driver.output,
    'ConsoleDriver' => driver
    }

  # Parse any extra options that should be passed to the plugin
  args.each { |opt|
    k, v = opt.split(/\=/)

    opts[k] = v if (k and v)
  }

  # If no absolute path was supplied, check the base and user plugin directories
  if (path !~ /#{File::SEPARATOR}/)
    plugin_file_name = path

    # If the plugin isn't in the user directory (~/.msf3/plugins/), use the base
    path = Msf::Config.user_plugin_directory + File::SEPARATOR + plugin_file_name
    if not File.exists?( path  + ".rb" )
      # If the following "path" doesn't exist it will be caught when we attempt to load
      path = Msf::Config.plugin_directory + File::SEPARATOR + plugin_file_name
    end

  end

  # Load that plugin!
  begin
    if (inst = framework.plugins.load(path, opts))
      print_status("Successfully loaded plugin: #{inst.name}")
    end
  rescue ::Exception => e
    elog("Error loading plugin #{path}: #{e}\n\n#{e.backtrace.join("\n")}", src = 'core', level = 0, from = caller)
    print_error("Failed to load plugin from #{path}: #{e}")
  end
end

#cmd_load_helpObject


1030
1031
1032
1033
1034
1035
1036
1037
1038
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1030

def cmd_load_help
  print_line "Usage: load <path> [var=val var=val ...]"
  print_line
  print_line "Loads a plugin from the supplied path.  If path is not absolute, first looks"
  print_line "in the user's plugin directory (#{Msf::Config.user_plugin_directory}) then"
  print_line "in the framework root plugin directory (#{Msf::Config.plugin_directory})."
  print_line "The optional var=val options are custom parameters that can be passed to plugins."
  print_line
end

#cmd_load_tabs(str, words) ⇒ Object

Tab completion for the load command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1098

def cmd_load_tabs(str, words)
  tabs = []

  if (not words[1] or not words[1].match(/^\//))
    # then let's start tab completion in the scripts/resource directories
    begin
      [
        Msf::Config.user_plugin_directory,
        Msf::Config.plugin_directory
      ].each do |dir|
        next if not ::File.exist? dir
        tabs += ::Dir.new(dir).find_all { |e|
          path = dir + File::SEPARATOR + e
          ::File.file?(path) and File.readable?(path)
        }
      end
    rescue Exception
    end
  else
    tabs += tab_complete_filenames(str,words)
  end
  return tabs.map{|e| e.sub(/.rb/, '')}

end

#cmd_loadpath(*args) ⇒ Object

Adds one or more search paths.


1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1342

def cmd_loadpath(*args)
  defanged?

  if (args.length == 0 or args.include? "-h")
    cmd_loadpath_help
    return true
  end

  totals    = {}
  overall   = 0
  curr_path = nil

  begin
    # Walk the list of supplied search paths attempting to add each one
    # along the way
    args.each { |path|
      curr_path = path

      # Load modules, but do not consult the cache
      if (counts = framework.modules.add_module_path(path))
        counts.each_pair { |type, count|
          totals[type] = (totals[type]) ? (totals[type] + count) : count

          overall += count
        }
      end
    }
  rescue NameError, RuntimeError
    log_error("Failed to add search path #{curr_path}: #{$!}")
    return true
  end

  added = "Loaded #{overall} modules:\n"

  totals.each_pair { |type, count|
    added << "    #{count} #{type}#{count != 1 ? 's' : ''}\n"
  }

  print(added)
end

#cmd_loadpath_helpObject


1331
1332
1333
1334
1335
1336
1337
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1331

def cmd_loadpath_help
  print_line "Usage: loadpath </path/to/modules>"
  print_line
  print_line "Loads modules from the given directory which should contain subdirectories for"
  print_line "module types, e.g. /path/to/modules/exploits"
  print_line
end

#cmd_loadpath_tabs(str, words) ⇒ Object

Tab completion for the loadpath command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1390

def cmd_loadpath_tabs(str, words)
  return [] if words.length > 1

  # This custom completion might better than Readline's... We'll leave it for now.
  #tab_complete_filenames(str,words)

  paths = []
  if (File.directory?(str))
    paths = Dir.entries(str)
    paths = paths.map { |f|
      if File.directory? File.join(str,f)
        File.join(str,f)
      end
    }
    paths.delete_if { |f| f.nil? or File.basename(f) == '.' or File.basename(f) == '..' }
  else
    d = Dir.glob(str + "*").map { |f| f if File.directory?(f) }
    d.delete_if { |f| f.nil? or f == '.' or f == '..' }
    # If there's only one possibility, descend to the next level
    if (1 == d.length)
      paths = Dir.entries(d[0])
      paths = paths.map { |f|
        if File.directory? File.join(d[0],f)
          File.join(d[0],f)
        end
      }
      paths.delete_if { |f| f.nil? or File.basename(f) == '.' or File.basename(f) == '..' }
    else
      paths = d
    end
  end
  paths.sort!
  return paths
end

#cmd_makerc(*args) ⇒ Object

Saves commands executed since the ui started to the specified msfrc file


305
306
307
308
309
310
311
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 305

def cmd_makerc(*args)
  if args.empty?
    cmd_makerc_help
    return false
  end
  driver.save_recent_history(args[0])
end

#cmd_makerc_helpObject


295
296
297
298
299
300
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 295

def cmd_makerc_help
  print_line "Usage: makerc <output rc file>"
  print_line
  print_line "Save the commands executed since startup to the specified file."
  print_line
end

#cmd_popm(*args) ⇒ Object

Command to dequeque a module from the module stack


2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2468

def cmd_popm(*args)
  if (args.count > 1 or not args[0].respond_to?("to_i"))
    return self.cmd_popm_help
  elsif args.count == 1
    # then pop 'n' items off the stack, but don't change the active module
    if args[0].to_i >= @module_name_stack.count
      # in case they pass in a number >= the length of @module_name_stack
      @module_name_stack = []
      print_status("The module stack is empty")
    else
      @module_name_stack.pop[args[0]]
    end
  else #then just pop the array and make that the active module
    pop = @module_name_stack.pop
    if pop
      return self.cmd_use(pop)
    else
      print_error("There isn't anything to pop, the module stack is empty")
    end
  end
end

#cmd_popm_helpObject

Help for the 'popm' command


2493
2494
2495
2496
2497
2498
2499
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2493

def cmd_popm_help
  print_line "Usage: popm [n]"
  print_line
  print_line "pop the latest module off of the module stack and make it the active module"
  print_line "or pop n modules off the stack, but don't change the active module"
  print_line
end

#cmd_previousObject

Command to take to the previously active module


2405
2406
2407
2408
2409
2410
2411
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2405

def cmd_previous()
  if @previous_module
    self.cmd_use(@previous_module.fullname)
  else
    print_error("There isn't a previous module at the moment")
  end
end

#cmd_previous_helpObject

Help for the 'previous' command


2416
2417
2418
2419
2420
2421
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2416

def cmd_previous_help
  print_line "Usage: previous"
  print_line
  print_line "Set the previously loaded module as the current module"
  print_line
end

#cmd_pushm(*args) ⇒ Object

Command to enqueque a module on the module stack


2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2426

def cmd_pushm(*args)
  # could check if each argument is a valid module, but for now let them hang themselves
  if args.count > 0
    args.each do |arg|
      @module_name_stack.push(arg)
      # Note new modules are appended to the array and are only module (full)names
    end
  else #then just push the active module
    if active_module
      #print_status "Pushing the active module"
      @module_name_stack.push(active_module.fullname)
    else
      print_error("There isn't an active module and you didn't specify a module to push")
      return self.cmd_pushm_help
    end
  end
end

#cmd_pushm_helpObject

Help for the 'pushm' command


2458
2459
2460
2461
2462
2463
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2458

def cmd_pushm_help
  print_line "Usage: pushm [module1 [,module2, module3...]]"
  print_line
  print_line "push current active module or specified modules onto the module stack"
  print_line
end

#cmd_pushm_tabs(str, words) ⇒ Object

Tab completion for the pushm command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


2451
2452
2453
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2451

def cmd_pushm_tabs(str, words)
  tab_complete_module(str, words)
end

#cmd_reload_all(*args) ⇒ Object

Reload all module paths that we are aware of


208
209
210
211
212
213
214
215
216
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 208

def cmd_reload_all(*args)
  if args.length > 0
    cmd_reload_all_help
    return
  end
  print_status("Reloading modules from all module paths...")
  framework.modules.reload_modules
  cmd_banner()
end

#cmd_reload_all_helpObject


197
198
199
200
201
202
203
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 197

def cmd_reload_all_help
  print_line "Usage: reload_all"
  print_line
  print_line "Reload all modules from all configured module paths.  This may take awhile."
  print_line "See also: loadpath"
  print_line
end

#cmd_resource(*args) ⇒ Object


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

def cmd_resource(*args)
  if args.empty?
    cmd_resource_help
    return false
  end

  args.each do |res|
    good_res = nil
    if (File.file? res and File.readable? res)
      good_res = res
    elsif
      # let's check to see if it's in the scripts/resource dir (like when tab completed)
      [
        ::Msf::Config.script_directory + File::SEPARATOR + "resource",
        ::Msf::Config.user_script_directory + File::SEPARATOR + "resource"
      ].each do |dir|
        res_path = dir + File::SEPARATOR + res
        if (File.file?(res_path) and File.readable?(res_path))
          good_res = res_path
          break
        end
      end
    end
    if good_res
      driver.load_resource(good_res)
    else
      print_error("#{res} is not a valid resource file")
      next
    end
  end
end

#cmd_resource_helpObject


218
219
220
221
222
223
224
225
226
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 218

def cmd_resource_help
  print_line "Usage: resource path1 [path2 ...]"
  print_line
  print_line "Run the commands stored in the supplied files.  Resource files may also contain"
  print_line "ruby code between <ruby></ruby> tags."
  print_line
  print_line "See also: makerc"
  print_line
end

#cmd_resource_tabs(str, words) ⇒ Object

Tab completion for the resource command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


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

def cmd_resource_tabs(str, words)
  tabs = []
  #return tabs if words.length > 1
  if ( str and str =~ /^#{Regexp.escape(File::SEPARATOR)}/ )
    # then you are probably specifying a full path so let's just use normal file completion
    return tab_complete_filenames(str,words)
  elsif (not words[1] or not words[1].match(/^\//))
    # then let's start tab completion in the scripts/resource directories
    begin
      [
        ::Msf::Config.script_directory + File::SEPARATOR + "resource",
        ::Msf::Config.user_script_directory + File::SEPARATOR + "resource",
        "."
      ].each do |dir|
        next if not ::File.exist? dir
        tabs += ::Dir.new(dir).find_all { |e|
          path = dir + File::SEPARATOR + e
          ::File.file?(path) and File.readable?(path)
        }
      end
    rescue Exception
    end
  else
    tabs += tab_complete_filenames(str,words)
  end
  return tabs
end

#cmd_route(*args) ⇒ Object

This method handles the route command which allows a user to specify which session a given subnet should route through.


1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1135

def cmd_route(*args)
  if (args.length == 0)
    cmd_route_help
    return false
  end

  arg = args.shift
  case arg

  when "add", "remove", "del"
    if (args.length < 3)
      print_error("Missing arguments to route #{arg}.")
      return false
    end

    # Satisfy check to see that formatting is correct
    unless Rex::Socket::RangeWalker.new(args[0]).length == 1
      print_error "Invalid IP Address"
      return false
    end

    unless Rex::Socket::RangeWalker.new(args[1]).length == 1
      print_error "Invalid Subnet mask"
      return false
    end

    gw = nil

    # Satisfy case problems
    args[2] = "Local" if (args[2] =~ /local/i)

    begin
      # If the supplied gateway is a global Comm, use it.
      if (Rex::Socket::Comm.const_defined?(args[2]))
        gw = Rex::Socket::Comm.const_get(args[2])
      end
    rescue NameError
    end

    # If we still don't have a gateway, check if it's a session.
    if ((gw == nil) and
        (session = framework.sessions.get(args[2])) and
        (session.kind_of?(Msf::Session::Comm)))
      gw = session
    elsif (gw == nil)
      print_error("Invalid gateway specified.")
      return false
    end

    if arg == "remove" or arg == "del"
      worked = Rex::Socket::SwitchBoard.remove_route(args[0], args[1], gw)
      if worked
        print_status("Route removed")
      else
        print_error("Route not found")
      end
    else
      worked = Rex::Socket::SwitchBoard.add_route(args[0], args[1], gw)
      if worked
        print_status("Route added")
      else
        print_error("Route already exists")
      end
    end

  when "get"
    if (args.length == 0)
      print_error("You must supply an IP address.")
      return false
    end

    comm = Rex::Socket::SwitchBoard.best_comm(args[0])

    if ((comm) and
        (comm.kind_of?(Msf::Session)))
      print_line("#{args[0]} routes through: Session #{comm.sid}")
    else
      print_line("#{args[0]} routes through: Local")
    end


  when "flush"
    Rex::Socket::SwitchBoard.flush_routes

  when "print"
    tbl =	Table.new(
      Table::Style::Default,
      'Header'  => "Active Routing Table",
      'Prefix'  => "\n",
      'Postfix' => "\n",
      'Columns' =>
        [
          'Subnet',
          'Netmask',
          'Gateway',
        ],
      'ColProps' =>
        {
          'Subnet'  => { 'MaxWidth' => 17 },
          'Netmask' => { 'MaxWidth' => 17 },
        })

    Rex::Socket::SwitchBoard.each { |route|

      if (route.comm.kind_of?(Msf::Session))
        gw = "Session #{route.comm.sid}"
      else
        gw = route.comm.name.split(/::/)[-1]
      end

      tbl << [ route.subnet, route.netmask, gw ]
    }

    print(tbl.to_s)
  else
    cmd_route_help
  end
end

#cmd_route_helpObject


1123
1124
1125
1126
1127
1128
1129
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1123

def cmd_route_help
  print_line "Usage: route [add/remove/get/flush/print] subnet netmask [comm/sid]"
  print_line
  print_line "Route traffic destined to a given subnet through a supplied session."
  print_line "The default comm is Local."
  print_line
end

#cmd_route_tabs(str, words) ⇒ Object

Tab completion for the route command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1261

def cmd_route_tabs(str, words)
  if words.length == 1
    return %w{add remove get flush print}
  end

  ret = []
  case words[1]
  when "remove", "del"
    Rex::Socket::SwitchBoard.each { |route|
      case words.length
      when 2
        ret << route.subnet
      when 3
        if route.subnet == words[2]
          ret << route.netmask
        end
      when 4
        if route.subnet == words[2]
          ret << route.comm.sid.to_s if route.comm.kind_of? Msf::Session
        end
      end
    }
    ret
  when "add"
    # We can't really complete the subnet and netmask args without
    # diving pretty deep into all sessions, so just be content with
    # completing sids for the last arg
    if words.length == 4
      ret = framework.sessions.keys.map { |k| k.to_s }
    end
  # The "get" command takes one arg, but we can't complete it either...
  end

  ret
end

#cmd_save(*args) ⇒ Object

Saves the active datastore contents to disk for automatic use across restarts of the console.


1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1310

def cmd_save(*args)
  defanged?

  # Save the console config
  driver.save_config

  # Save the framework's datastore
  begin
    framework.save_config

    if (active_module)
      active_module.save_config
    end
  rescue
    log_error("Save failed: #{$!}")
    return false
  end

  print_line("Saved configuration to: #{Msf::Config.config_file}")
end

#cmd_save_helpObject


1297
1298
1299
1300
1301
1302
1303
1304
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1297

def cmd_save_help
  print_line "Usage: save"
  print_line
  print_line "Save the active datastore contents to disk for automatic use across restarts of the console"
  print_line
  print_line "The configuration is stored in #{Msf::Config.config_file}"
  print_line
end

#cmd_search(*args) ⇒ Object

Searches modules for specific keywords


1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1452

def cmd_search(*args)
  match   = ''
  @@search_opts.parse(args) { |opt, idx, val|
    case opt
    when "-t"
      print_error("Deprecated option.  Use type:#{val} instead")
      cmd_search_help
      return
    when "-h"
      cmd_search_help
      return
    else
      match += val + " "
    end
  }

  if framework.db and framework.db.migrated and framework.db.modules_cached
    search_modules_sql(match)
    return
  end

  print_warning("Database not connected or cache not built, using slow search")

  tbl = generate_module_table("Matching Modules")
  [
    framework.exploits,
    framework.auxiliary,
    framework.post,
    framework.payloads,
    framework.nops,
    framework.encoders
  ].each do |mset|
    mset.each do |m|
      o = mset.create(m[0]) rescue nil

      # Expected if modules are loaded without the right pre-requirements
      next if not o

      if not o.search_filter(match)
        tbl << [ o.fullname, o.disclosure_date.to_s, o.rank_to_s, o.name ]
      end
    end
  end
  print_line(tbl.to_s)

end

#cmd_search_helpObject


1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1425

def cmd_search_help
  print_line "Usage: search [keywords]"
  print_line
  print_line "Keywords:"
  {
    'app'      => 'Modules that are client or server attacks',
    'author'   => 'Modules written by this author',
    'bid'      => 'Modules with a matching Bugtraq ID',
    'cve'      => 'Modules with a matching CVE ID',
    'edb'      => 'Modules with a matching Exploit-DB ID',
    'name'     => 'Modules with a matching descriptive name',
    'osvdb'    => 'Modules with a matching OSVDB ID',
    'platform' => 'Modules affecting this platform',
    'ref'      => 'Modules with a matching ref',
    'type'     => 'Modules of a specific type (exploit, auxiliary, or post)',
  }.each_pair do |keyword, description|
    print_line "  #{keyword.ljust 10}:  #{description}"
  end
  print_line
  print_line "Examples:"
  print_line "  search cve:2009 type:exploit app:client"
  print_line
end

#cmd_search_tabs(str, words) ⇒ Object

Tab completion for the search command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1518

def cmd_search_tabs(str, words)
  if words.length == 1
    return @@search_opts.fmt.keys
  end

  case (words[-1])
  when "-r"
    return RankingName.sort.map{|r| r[1]}
  when "-t"
    return %w{auxiliary encoder exploit nop payload post}
  end

  []
end

#cmd_sessions(*args) ⇒ Object

Provides an interface to the sessions currently active in the framework.


1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1582

def cmd_sessions(*args)
  begin
  method  = nil
  quiet   = false
  verbose = false
  sid     = nil
  cmds    = []
  script  = nil
  reset_ring = false

  # any arguments that don't correspond to an option or option arg will
  # be put in here
  extra   = []

  # Parse the command options
  @@sessions_opts.parse(args) { |opt, idx, val|
    case opt
      when "-q"
        quiet = true

      # Run a command on all sessions, or the session given with -i
      when "-c"
        method = 'cmd'
        if (val)
          cmds << val
        end

      when "-v"
        verbose = true

      # Do something with the supplied session identifier instead of
      # all sessions.
      when "-i"
        sid = val

      # Display the list of active sessions
      when "-l"
        method = 'list'

      when "-k"
        method = 'kill'
        sid = val if val
        if not sid
          print_error("Specify a session to kill")
          return false
        end

      when "-K"
        method = 'killall'

      when "-d"
        method = 'detach'
        sid = val

      # Run a script on all meterpreter sessions
      when "-s"
        if  not script
          method = 'scriptall'
          script = val
        end

      # Upload and exec to the specific command session
      when "-u"
        method = 'upexec'
        sid = val

      # Reset the ring buffer read pointer
      when "-r"
        reset_ring = true
        method = 'reset_ring'

      # Display help banner
      when "-h"
        cmd_sessions_help
        return false
      else
        extra << val
    end
  }

  if sid and not framework.sessions.get(sid)
    print_error("Invalid session id")
    return false
  end

  if method.nil? and sid
    method = 'interact'
  end

  # Now, perform the actual method
  case method

    when 'cmd'
      if (cmds.length < 1)
        print_error("No command specified!")
        return false
      end
      cmds.each do |cmd|
        if sid
          sessions = [ sid ]
        else
          sessions = framework.sessions.keys.sort
        end
        sessions.each do |s|
          session = framework.sessions.get(s)
          print_status("Running '#{cmd}' on #{session.type} session #{s} (#{session.session_host})")

          if (session.type == "meterpreter")
            # If session.sys is nil, dont even try..
            if not (session.sys)
              print_error("Session #{s} does not have stdapi loaded, skipping...")
              next
            end
            c, c_args = cmd.split(' ', 2)
            begin
              process = session.sys.process.execute(c, c_args,
                {
                  'Channelized' => true,
                  'Hidden'      => true
                })
            rescue ::Rex::Post::Meterpreter::RequestError
              print_error("Failed: #{$!.class} #{$!}")
            end
            if process and process.channel and (data = process.channel.read)
              print_line(data)
            end
          elsif session.type == "shell"
            if (output = session.shell_command(cmd))
              print_line(output)
            end
          end
          # If the session isn't a meterpreter or shell type, it
          # could be a VNC session (which can't run commands) or
          # something custom (which we don't know how to run
          # commands on), so don't bother.
        end
      end

    when 'kill'
      if ((session = framework.sessions.get(sid)))
        print_status("Killing session #{sid}")
        session.kill
      else
        print_error("Invalid session identifier: #{sid}")
      end

    when 'killall'
      print_status("Killing all sessions...")
      framework.sessions.each_sorted do |s|
        if ((session = framework.sessions.get(s)))
          session.kill
        end
      end

    when 'detach'
      if ((session = framework.sessions.get(sid)))
        print_status("Detaching session #{sid}")
        if (session.interactive?)
          session.detach()
        end
      else
        print_error("Invalid session identifier: #{sid}")
      end

    when 'interact'
      if ((session = framework.sessions.get(sid)))
        if (session.interactive?)
          print_status("Starting interaction with #{session.name}...\n") if (quiet == false)

          self.active_session = session

          session.interact(driver.input.dup, driver.output)

          self.active_session = nil

          if (driver.input.supports_readline)
            driver.input.reset_tab_completion
          end

        else
          print_error("Session #{sid} is non-interactive.")
        end
      else
        print_error("Invalid session identifier: #{sid}")
      end

    when 'scriptall'
      if (script.nil?)
        print_error("No script specified!")
        return false
      end

      script_paths = {}
      script_paths['meterpreter'] = Msf::Sessions::Meterpreter.find_script_path(script)
      script_paths['shell'] = Msf::Sessions::CommandShell.find_script_path(script)

      if sid
        print_status("Running script #{script} on session #{sid}...")
        sessions = [ sid ]
      else
        print_status("Running script #{script} on all sessions...")
        sessions = framework.sessions.keys.sort
      end

      sessions.each do |s|
        if ((session = framework.sessions.get(s)))
          if (script_paths[session.type])
            print_status("Session #{s} (#{session.session_host}):")
            begin
              session.execute_file(script_paths[session.type], extra)
            rescue ::Exception => e
              log_error("Error executing script: #{e.class} #{e}")
            end
          end
        end
      end

    when 'upexec'
      if ((session = framework.sessions.get(sid)))
        if (session.interactive?)
          if (session.type == "shell") # XXX: check for windows?
            session.init_ui(driver.input, driver.output)
            session.execute_script('spawn_meterpreter', nil)
            session.reset_ui
          else
            print_error("Session #{sid} is not a command shell session.")
          end
        else
          print_error("Session #{sid} is non-interactive.")
        end
      else
        print_error("Invalid session identifier: #{sid}")
      end

    when 'reset_ring'
      sessions = sid ? [ sid ] : framework.sessions.keys
      sessions.each do |sidx|
        s = framework.sessions[sidx]
        next if not (s and s.respond_to?(:ring_seq))
        s.reset_ring_sequence
        print_status("Reset the ring buffer pointer for Session #{sidx}")
      end

    when 'list',nil
      print_line
      print(Serializer::ReadableText.dump_sessions(framework, :verbose => verbose))
      print_line
  end

  rescue IOError, EOFError, Rex::StreamClosedError
    print_status("Session stream closed.")
  rescue ::Interrupt
    raise $!
  rescue ::Exception
    log_error("Session manipulation failed: #{$!} #{$!.backtrace.inspect}")
  end

  # Reset the active session
  self.active_session = nil

  return true
end

#cmd_sessions_helpObject


1572
1573
1574
1575
1576
1577
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1572

def cmd_sessions_help
  print_line "Usage: sessions [options]"
  print_line
  print_line "Active session manipulation and interaction."
  print(@@sessions_opts.usage())
end

#cmd_sessions_tabs(str, words) ⇒ Object

Tab completion for the sessions command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1852

def cmd_sessions_tabs(str, words)
  if words.length == 1
    return @@sessions_opts.fmt.keys
  end

  case words[-1]
  when "-i", "-k", "-d", "-u"
    return framework.sessions.keys.map { |k| k.to_s }

  when "-c"
    # Can't really complete commands hehe

  when "-s"
    # XXX: Complete scripts

  end

  []
end

#cmd_set(*args) ⇒ Object

Sets a name to a value in a context aware environment.


1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1886

def cmd_set(*args)

  # Figure out if these are global variables
  global = false

  if (args[0] == '-g')
    args.shift
    global = true
  end

  # Decide if this is an append operation
  append = false

  if (args[0] == '-a')
    args.shift
    append = true
  end

  # Determine which data store we're operating on
  if (active_module and global == false)
    datastore = active_module.datastore
  else
    global = true
    datastore = self.framework.datastore
  end

  # Dump the contents of the active datastore if no args were supplied
  if (args.length == 0)
    # If we aren't dumping the global data store, then go ahead and
    # dump it first
    if (!global)
      print("\n" +
        Msf::Serializer::ReadableText.dump_datastore(
          "Global", framework.datastore))
    end

    # Dump the active datastore
    print("\n" +
      Msf::Serializer::ReadableText.dump_datastore(
        (global) ? "Global" : "Module: #{active_module.refname}",
        datastore) + "\n")
    return true
  elsif (args.length == 1)
    if (not datastore[args[0]].nil?)
      print_line("#{args[0]} => #{datastore[args[0]]}")
      return true
    else
      print_error("Unknown variable")
      cmd_set_help
      return false
    end
  end

  # Set the supplied name to the supplied value
  name  = args[0]
  value = args[1, args.length-1].join(' ')
  if (name.upcase == "TARGET")
    # Different targets can have different architectures and platforms
    # so we need to rebuild the payload list whenever the target
    # changes.
    @cache_payloads = nil
  end

  # Security check -- make sure the data store element they are setting
  # is not prohibited
  if global and DefangedProhibitedDataStoreElements.include?(name)
    defanged?
  end

  # If the driver indicates that the value is not valid, bust out.
  if (driver.on_variable_set(global, name, value) == false)
    print_error("The value specified for #{name} is not valid.")
    return true
  end

  if append
    datastore[name] = datastore[name] + value
  else
    datastore[name] = value
  end

  print_line("#{name} => #{datastore[name]}")
end

#cmd_set_helpObject


1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1872

def cmd_set_help
  print_line "Usage: set [option] [value]"
  print_line
  print_line "Set the given option to value.  If value is omitted, print the current value."
  print_line "If both are omitted, print options that are currently set."
  print_line
  print_line "If run from a module context, this will set the value in the module's"
  print_line "datastore.  Use -g to operate on the global datastore"
  print_line
end

#cmd_set_tabs(str, words) ⇒ Object

Tab completion for the set command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1977

def cmd_set_tabs(str, words)

  # A value has already been specified
  return [] if words.length > 2

  # A value needs to be specified
  if words.length == 2
    return tab_complete_option(str, words)
  end

  res = cmd_unset_tabs(str, words) || [ ]
  # There needs to be a better way to register global options, but for
  # now all we have is an ad-hoc list of opts that the shell treats
  # specially.
  res += %w{
    ConsoleLogging
    LogLevel
    MinimumRank
    SessionLogging
    TimestampOutput
    Prompt
    PromptChar
    PromptTimeFormat
  }
  mod = active_module

  if (not mod)
    return res
  end

  mod.options.sorted.each { |e|
    name, opt = e
    res << name
  }

  # Exploits provide these three default options
  if (mod.exploit?)
    res << 'PAYLOAD'
    res << 'NOP'
    res << 'TARGET'
  end
  if (mod.exploit? or mod.payload?)
    res << 'ENCODER'
  end

  if (mod.auxiliary?)
    res << "ACTION"
  end

  if (mod.exploit? and mod.datastore['PAYLOAD'])
    p = framework.payloads.create(mod.datastore['PAYLOAD'])
    if (p)
      p.options.sorted.each { |e|
        name, opt = e
        res << name
      }
    end
  end

  return res
end

#cmd_setg(*args) ⇒ Object

Sets the supplied variables in the global datastore.


2049
2050
2051
2052
2053
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2049

def cmd_setg(*args)
  args.unshift('-g')

  cmd_set(*args)
end

#cmd_setg_helpObject


2039
2040
2041
2042
2043
2044
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2039

def cmd_setg_help
  print_line "Usage: setg [option] [value]"
  print_line
  print_line "Exactly like set -g, set a value in the global datastore."
  print_line
end

#cmd_setg_tabs(str, words) ⇒ Object

Tab completion for the setg command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


2062
2063
2064
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2062

def cmd_setg_tabs(str, words)
  cmd_set_tabs(str, words)
end

#cmd_show(*args) ⇒ Object

Displays the list of modules based on their type, or all modules if no type is provided.


2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2078

def cmd_show(*args)
  mod = self.active_module

  args << "all" if (args.length == 0)

  args.each { |type|
    case type
      when '-h'
        cmd_show_help
      when 'all'
        show_encoders
        show_nops
        show_exploits
        show_payloads
        show_auxiliary
        show_post
        show_plugins
      when 'encoders'
        show_encoders
      when 'nops'
        show_nops
      when 'exploits'
        show_exploits
      when 'payloads'
        show_payloads
      when 'auxiliary'
        show_auxiliary
      when 'post'
        show_post
      when 'options'
        if (mod)
          show_options(mod)
        else
          show_global_options
        end
      when 'advanced'
        if (mod)
          show_advanced_options(mod)
        else
          print_error("No module selected.")
        end
      when 'evasion'
        if (mod)
          show_evasion_options(mod)
        else
          print_error("No module selected.")
        end
      when 'sessions'
        if (active_module and active_module.respond_to?(:compatible_sessions))
          sessions = active_module.compatible_sessions
        else
          sessions = framework.sessions.keys.sort
        end
        print_line
        print(Serializer::ReadableText.dump_sessions(framework, :session_ids => sessions))
        print_line
      when "plugins"
        show_plugins
      when "targets"
        if (mod and mod.exploit?)
          show_targets(mod)
        else
          print_error("No exploit module selected.")
        end
      when "actions"
        if (mod and (mod.auxiliary? or mod.post?))
          show_actions(mod)
        else
          print_error("No auxiliary module selected.")
        end

      else
        print_error("Invalid parameter \"#{type}\", use \"show -h\" for more information")
    end
  }
end

#cmd_show_helpObject


2066
2067
2068
2069
2070
2071
2072
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2066

def cmd_show_help
  global_opts = %w{all encoders nops exploits payloads auxiliary plugins options}
  print_status("Valid parameters for the \"show\" command are: #{global_opts.join(", ")}")

  module_opts = %w{ advanced evasion targets actions }
  print_status("Additional module-specific parameters are: #{module_opts.join(", ")}")
end

#cmd_show_tabs(str, words) ⇒ Object

Tab completion for the show command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2162

def cmd_show_tabs(str, words)
  return [] if words.length > 1

  res = %w{all encoders nops exploits payloads auxiliary post plugins options}
  if (active_module)
    res.concat(%w{ advanced evasion targets actions })
    if (active_module.respond_to? :compatible_sessions)
      res << "sessions"
    end
  end
  return res
end

#cmd_sleep(*args) ⇒ Object

Causes process to pause for the specified number of seconds


698
699
700
701
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 698

def cmd_sleep(*args)
  return if not (args and args.length == 1)
  Rex::ThreadSafe.sleep(args[0].to_f)
end

#cmd_sleep_helpObject


688
689
690
691
692
693
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 688

def cmd_sleep_help
  print_line "Usage: sleep <seconds>"
  print_line
  print_line "Do nothing the specified number of seconds.  This is useful in rc scripts."
  print_line
end

#cmd_spool(*args) ⇒ Object


1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1541

def cmd_spool(*args)
  if args.include?('-h') or args.empty?
    cmd_spool_help
    return
  end

  color = driver.output.config[:color]

  if args[0] == "off"
    driver.init_ui(driver.input, Rex::Ui::Text::Output::Stdio.new)
    msg = "Spooling is now disabled"
  else
    driver.init_ui(driver.input, Rex::Ui::Text::Output::Tee.new(args[0]))
    msg = "Spooling to file #{args[0]}..."
  end

  # Restore color and prompt
  driver.output.config[:color] = color
  prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt
  if active_module
    # intentionally += and not << because we don't want to modify
    # datastore or the constant DefaultPrompt
    prompt += " #{active_module.type}(%bld%red#{active_module.shortname}%clr)"
  end
  prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar
  driver.update_prompt("#{prompt} ", prompt_char, true)

  print_status(msg)
  return
end

#cmd_spool_helpObject


1533
1534
1535
1536
1537
1538
1539
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1533

def cmd_spool_help
  print_line "Usage: spool <off>|<filename>"
  print_line
  print_line "Example:"
  print_line "  spool /tmp/console.log"
  print_line
end

#cmd_threads(*args) ⇒ Object

Displays and manages running background threads


911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 911

def cmd_threads(*args)
  # Make the default behavior listing all jobs if there were no options
  # or the only option is the verbose flag
  if (args.length == 0 or args == ["-v"])
    args.unshift("-l")
  end

  verbose = false
  dump_list = false
  dump_info = false
  thread_id = nil

  # Parse the command options
  @@threads_opts.parse(args) { |opt, idx, val|
    case opt
      when "-v"
        verbose = true
      when "-l"
        dump_list = true

      # Terminate the supplied thread id
      when "-k"
        val = val.to_i
        if not framework.threads[val]
          print_error("No such thread")
        else
          print_line("Terminating thread: #{val}...")
          framework.threads.kill(val)
        end
      when "-K"
        print_line("Killing all non-critical threads...")
        framework.threads.each_index do |i|
          t = framework.threads[i]
          next if not t
          next if t[:tm_crit]
          framework.threads.kill(i)
        end
      when "-i"
        # Defer printing anything until the end of option parsing
        # so we can check for the verbose flag.
        dump_info = true
        thread_id = val.to_i
      when "-h"
        cmd_threads_help
        return false
    end
  }

  if (dump_list)
    tbl = Table.new(
      Table::Style::Default,
      'Header'  => "Background Threads",
      'Prefix'  => "\n",
      'Postfix' => "\n",
      'Columns' =>
        [
          'ID',
          'Status',
          'Critical',
          'Name',
          'Started'
        ]
    )

    framework.threads.each_index do |i|
      t = framework.threads[i]
      next if not t
      tbl << [ i.to_s, t.status || "dead", t[:tm_crit] ? "True" : "False", t[:tm_name].to_s, t[:tm_time].to_s ]
    end
    print(tbl.to_s)
  end

  if (dump_info)
    thread = framework.threads[thread_id]

    if (thread)
      output  = "\n"
      output += "  ID: #{thread_id}\n"
      output += "Name: #{thread[:tm_name]}\n"
      output += "Info: #{thread.status || "dead"}\n"
      output += "Crit: #{thread[:tm_crit] ? "True" : "False"}\n"
      output += "Time: #{thread[:tm_time].to_s}\n"

      if (verbose)
        output += "\n"
        output += "Thread Source\n"
        output += "=============\n"
        thread[:tm_call].each do |c|
          output += "      #{c.to_s}\n"
        end
        output += "\n"
      end

      print(output +"\n")
    else
      print_line("Invalid Thread ID")
    end
  end
end

#cmd_threads_helpObject


901
902
903
904
905
906
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 901

def cmd_threads_help
  print_line "Usage: threads [options]"
  print_line
  print_line "Background thread management."
  print_line @@threads_opts.usage()
end

#cmd_threads_tabs(str, words) ⇒ Object

Tab completion for the threads command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1018

def cmd_threads_tabs(str, words)
  if words.length == 1
    return @@threads_opts.fmt.keys
  end

  if @@threads_opts.fmt[words[1]][0] and (words.length == 2)
    return framework.threads.each_index.map{ |idx| idx.to_s }
  end

  []
end

#cmd_unload(*args) ⇒ Object

Unloads a plugin by its name.


2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2186

def cmd_unload(*args)
  if (args.length == 0)
    cmd_unload_help
    return false
  end

  # Walk the plugins array
  framework.plugins.each { |plugin|
    # Unload the plugin if it matches the name we're searching for
    if (plugin.name == args[0])
      print("Unloading plugin #{args[0]}...")
      framework.plugins.unload(plugin)
      print_line("unloaded.")
      break
    end
  }
end

#cmd_unload_helpObject


2175
2176
2177
2178
2179
2180
2181
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2175

def cmd_unload_help
  print_line "Usage: unload <plugin name>"
  print_line
  print_line "Unloads a plugin by its symbolic name.  Use 'show plugins' to see a list of"
  print_line "currently loaded plugins."
  print_line
end

#cmd_unload_tabs(str, words) ⇒ Object

Tab completion for the unload command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


2211
2212
2213
2214
2215
2216
2217
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2211

def cmd_unload_tabs(str, words)
  return [] if words.length > 1

  tabs = []
  framework.plugins.each { |k| tabs.push(k.name) }
  return tabs
end

#cmd_unset(*args) ⇒ Object

Unsets a value if it's been set.


2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2231

def cmd_unset(*args)

  # Figure out if these are global variables
  global = false

  if (args[0] == '-g')
    args.shift
    global = true
  end

  # Determine which data store we're operating on
  if (active_module and global == false)
    datastore = active_module.datastore
  else
    datastore = framework.datastore
  end

  # No arguments?  No cookie.
  if (args.length == 0)
    cmd_unset_help
    return false
  end

  # If all was specified, then flush all of the entries
  if args[0] == 'all'
    print_line("Flushing datastore...")

    # Re-import default options into the module's datastore
    if (active_module and global == false)
      active_module.import_defaults
    # Or simply clear the global datastore
    else
      datastore.clear
    end

    return true
  end

  while ((val = args.shift))
    if (driver.on_variable_unset(global, val) == false)
      print_error("The variable #{val} cannot be unset at this time.")
      next
    end

    print_line("Unsetting #{val}...")

    datastore.delete(val)
  end
end

#cmd_unset_helpObject Also known as: cmd_unsetg_help


2219
2220
2221
2222
2223
2224
2225
2226
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2219

def cmd_unset_help
  print_line "Usage: unset [-g] var1 var2 var3 ..."
  print_line
  print_line "The unset command is used to unset one or more variables."
  print_line "To flush all entires, specify 'all' as the variable name."
  print_line "With -g, operates on global datastore variables."
  print_line
end

#cmd_unset_tabs(str, words) ⇒ Object

Tab completion for the unset command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


2288
2289
2290
2291
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2288

def cmd_unset_tabs(str, words)
  datastore = active_module ? active_module.datastore : self.framework.datastore
  datastore.keys
end

#cmd_unsetg(*args) ⇒ Object

Unsets variables in the global data store.


2303
2304
2305
2306
2307
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2303

def cmd_unsetg(*args)
  args.unshift('-g')

  cmd_unset(*args)
end

#cmd_unsetg_tabs(str, words) ⇒ Object

Tab completion for the unsetg command

at least 1 when tab completion has reached this stage since the command itself has been completed

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


2316
2317
2318
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2316

def cmd_unsetg_tabs(str, words)
  self.framework.datastore.keys
end

#cmd_use(*args) ⇒ Object

Uses a module.


2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2332

def cmd_use(*args)
  if (args.length == 0)
    cmd_use_help
    return false
  end

  # Try to create an instance of the supplied module name
  mod_name = args[0]

  begin
    if ((mod = framework.modules.create(mod_name)) == nil)
      print_error("Failed to load module: #{mod_name}")
      return false
    end
  rescue Rex::AmbiguousArgumentError => info
    print_error(info.to_s)
  rescue NameError => info
    log_error("The supplied module name is ambiguous: #{$!}.")
  end

  return false if (mod == nil)

  # Enstack the command dispatcher for this module type
  dispatcher = nil

  case mod.type
    when MODULE_ENCODER
      dispatcher = Msf::Ui::Console::CommandDispatcher::Encoder
    when MODULE_EXPLOIT
      dispatcher = Msf::Ui::Console::CommandDispatcher::Exploit
    when MODULE_NOP
      dispatcher = Msf::Ui::Console::CommandDispatcher::Nop
    when MODULE_PAYLOAD
      dispatcher = Msf::Ui::Console::CommandDispatcher::Payload
    when MODULE_AUX
      dispatcher = Msf::Ui::Console::CommandDispatcher::Auxiliary
    when MODULE_POST
      dispatcher = Msf::Ui::Console::CommandDispatcher::Post
    else
      print_error("Unsupported module type: #{mod.type}")
      return false
  end

  # If there's currently an active module, enqueque it and go back
  if (active_module)
    @previous_module = active_module
    cmd_back()
  end

  if (dispatcher != nil)
    driver.enstack_dispatcher(dispatcher)
  end

  # Update the active module
  self.active_module = mod

  # If a datastore cache exists for this module, then load it up
  if @dscache[active_module.fullname]
    active_module.datastore.update(@dscache[active_module.fullname])
  end

  @cache_payloads = nil
  mod.init_ui(driver.input, driver.output)

  # Update the command prompt
  prompt = framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt
  prompt_char = framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar
  driver.update_prompt("#{prompt} #{mod.type}(%bld%red#{mod.shortname}%clr) ", prompt_char, true)
end

#cmd_use_helpObject


2322
2323
2324
2325
2326
2327
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2322

def cmd_use_help
  print_line "Usage: use module_name"
  print_line
  print_line "The use command is used to interact with a module of a given name."
  print_line
end

#cmd_use_tabs(str, words) ⇒ Object

Tab completion for the use command

at least 1 when tab completion has reached this stage since the command itself has been completd

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

    the previously completed words on the command line. words is always


2508
2509
2510
2511
2512
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2508

def cmd_use_tabs(str, words)
  return [] if words.length > 1

  tab_complete_module(str, words)
end

#cmd_version(*args) ⇒ Object

Returns the revision of the framework and console library


2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2517

def cmd_version(*args)
  svn_console_version = "$Revision: 15168 $"
  svn_metasploit_version = Msf::Framework::Revision.match(/ (.+?) \$/)[1] rescue nil
  if svn_metasploit_version
    print_line("Framework: #{Msf::Framework::Version}.#{svn_metasploit_version}")
  else
    print_line("Framework: #{Msf::Framework::Version}")
  end
  print_line("Console  : #{Msf::Framework::Version}.#{svn_console_version.match(/ (.+?) \$/)[1]}")

  return true
end

#commandsObject

Returns the list of commands supported by this command dispatcher


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

def commands
  {
    "?"        => "Help menu",
    "back"     => "Move back from the current context",
    "banner"   => "Display an awesome metasploit banner",
    "cd"       => "Change the current working directory",
    "connect"  => "Communicate with a host",
    "color"    => "Toggle color",
    "exit"     => "Exit the console",
    "edit"     => "Edit the current module with $VISUAL or $EDITOR",
    "go_pro"   => "Launch Metasploit web GUI",
    "grep"     => "Grep the output of another command",
    "help"     => "Help menu",
    "info"     => "Displays information about one or more module",
    "irb"      => "Drop into irb scripting mode",
    "jobs"     => "Displays and manages jobs",
    "kill"     => "Kill a job",
    "load"     => "Load a framework plugin",
    "loadpath" => "Searches for and loads modules from a path",
    "popm"     => "Pops the latest module off the stack and makes it active",
    "pushm"    => "Pushes the active or list of modules onto the module stack",
    "previous" => "Sets the previously loaded module as the current module",
    "quit"     => "Exit the console",
    "resource" => "Run the commands stored in a file",
    "makerc"   => "Save commands entered since start to a file",
    "reload_all" => "Reloads all modules from all defined module paths",
    "route"    => "Route traffic through a session",
    "save"     => "Saves the active datastores",
    "search"   => "Searches module names and descriptions",
    "sessions" => "Dump session listings and display information about sessions",
    "set"      => "Sets a variable to a value",
    "setg"     => "Sets a global variable to a value",
    "show"     => "Displays modules of a given type, or all modules",
    "sleep"    => "Do nothing for the specified number of seconds",
    "threads"  => "View and manipulate background threads",
    "unload"   => "Unload a framework plugin",
    "unset"    => "Unsets one or more variables",
    "unsetg"   => "Unsets one or more global variables",
    "use"      => "Selects a module by name",
    "version"  => "Show the framework and console library version numbers",
    "spool"    => "Write console output into a file as well the screen"
  }
end

#local_editorObject


640
641
642
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 640

def local_editor
  Rex::Compat.getenv('VISUAL') || Rex::Compat.getenv('EDITOR') || '/usr/bin/vim'
end

#msfbase_dirObject

Indicates the base dir where Metasploit Framework is installed.


165
166
167
168
169
170
171
172
173
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 165

def msfbase_dir
  base = __FILE__
  while File.symlink?(base)
    base = File.expand_path(File.readlink(base), File.dirname(base))
  end
  File.expand_path(
    File.join(File.dirname(base), "..","..","..","..","..")
  )
end

#nameObject

Returns the name of the command dispatcher.


160
161
162
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 160

def name
  "Core"
end

#option_values_actionsObject

Provide valid action options for the current auxiliary module


2848
2849
2850
2851
2852
2853
2854
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2848

def option_values_actions
  res = []
  if (active_module.actions)
    active_module.actions.each { |i| res << i.name }
  end
  return res
end

#option_values_dispatch(o, str, words) ⇒ Object

Provide possible option values based on type


2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2749

def option_values_dispatch(o, str, words)

  res = []
  res << o.default.to_s if o.default

  case o.class.to_s

    when 'Msf::OptAddress'
      case o.name.upcase
        when 'RHOST'
          option_values_target_addrs().each do |addr|
            res << addr
          end
        when 'LHOST'
          rh = self.active_module.datastore["RHOST"]
          if rh and not rh.empty?
            res << Rex::Socket.source_address(rh)
          else
            res << Rex::Socket.source_address()
          end
        else
      end

    when 'Msf::OptAddressRange'

      case str
        when /\/$/
          res << str+'32'
          res << str+'24'
          res << str+'16'
        when /\-$/
          res << str+str[0, str.length - 1]
        else
          option_values_target_addrs().each do |addr|
            res << addr+'/32'
            res << addr+'/24'
            res << addr+'/16'
          end
      end

    when 'Msf::OptPort'
      case o.name.upcase
        when 'RPORT'
        option_values_target_ports().each do |port|
          res << port
        end
      end

      if (res.empty?)
        res << (rand(65534)+1).to_s
      end

    when 'Msf::OptEnum'
      o.enums.each do |val|
        res << val
      end
    when 'Msf::OptPath'
      files = tab_complete_filenames(str,words)
      res += files if files
  end

  return res
end

#option_values_encodersObject

Provide valid encoders options for the current exploit or payload


2866
2867
2868
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2866

def option_values_encoders
  framework.encoders.map { |refname, mod| refname }
end

#option_values_nopsObject

Provide valid nops options for the current exploit


2859
2860
2861
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2859

def option_values_nops
  framework.nops.map { |refname, mod| refname }
end

#option_values_payloadsObject

Provide valid payload options for the current exploit


2816
2817
2818
2819
2820
2821
2822
2823
2824
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2816

def option_values_payloads
  return @cache_payloads if @cache_payloads

  @cache_payloads = active_module.compatible_payloads.map { |refname, payload|
    refname
  }

  @cache_payloads
end

#option_values_sessionsObject

Provide valid session options for the current post-exploit module


2829
2830
2831
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2829

def option_values_sessions
  active_module.compatible_sessions.map { |sid| sid.to_s }
end

#option_values_target_addrsObject

Provide the target addresses


2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2873

def option_values_target_addrs
  res = [ ]
  res << Rex::Socket.source_address()
  return res if not framework.db.active

  # List only those hosts with matching open ports?
  mport = self.active_module.datastore['RPORT']
  if (mport)
    mport = mport.to_i
    hosts = {}
    framework.db.each_service(framework.db.workspace) do |service|
      if (service.port == mport)
        hosts[ service.host.address ] = true
      end
    end

    hosts.keys.each do |host|
      res << host
    end

  # List all hosts in the database
  else
    framework.db.each_host(framework.db.workspace) do |host|
      res << host.address
    end
  end

  return res
end

#option_values_target_portsObject

Provide the target ports


2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2906

def option_values_target_ports
  res = [ ]
  return res if not framework.db.active
  return res if not self.active_module.datastore['RHOST']
  host = framework.db.has_host?(framework.db.workspace, self.active_module.datastore['RHOST'])
  return res if not host

  framework.db.each_service(framework.db.workspace) do |service|
    if (service.host_id == host.id)
      res << service.port.to_s
    end
  end

  return res
end

#option_values_targetsObject

Provide valid target options for the current exploit


2836
2837
2838
2839
2840
2841
2842
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2836

def option_values_targets
  res = []
  if (active_module.targets)
    1.upto(active_module.targets.length) { |i| res << (i-1).to_s }
  end
  return res
end

#search_modules_sql(search_string) ⇒ void

This method returns an undefined value.

Prints table of modules matching the search_string.

Parameters:

  • search_string (String)

    a string of space separated keyword pairs or free form text.


1503
1504
1505
1506
1507
1508
1509
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1503

def search_modules_sql(search_string)
  tbl = generate_module_table("Matching Modules")
  framework.db.search_modules(search_string).each do |o|
    tbl << [ o.fullname, o.disclosure_date.to_s, RankingName[o.rank].to_s, o.name ]
  end
  print_line(tbl.to_s)
end

#tab_complete_module(str, words) ⇒ Object

Tab complete module names


2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2681

def tab_complete_module(str, words)
  res = []
  framework.modules.module_types.each do |mtyp|
    mset = framework.modules.module_names(mtyp)
    mset.each do |mref|
      res << mtyp + '/' + mref
    end
  end

  return res.sort
end

#tab_complete_option(str, words) ⇒ Object

Provide tab completion for option values


2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2697

def tab_complete_option(str, words)
  opt = words[1]
  res = []
  mod = active_module

  # With no active module, we have nothing to compare
  if (not mod)
    return res
  end

  # Well-known option names specific to exploits
  if (mod.exploit?)
    return option_values_payloads() if opt.upcase == 'PAYLOAD'
    return option_values_targets()  if opt.upcase == 'TARGET'
    return option_values_nops()     if opt.upcase == 'NOPS'
    return option_values_encoders() if opt.upcase == 'StageEncoder'
  end

  # Well-known option names specific to auxiliaries
  if (mod.auxiliary?)
    return option_values_actions() if opt.upcase == 'ACTION'
  end

  # The ENCODER option works for payloads and exploits
  if ((mod.exploit? or mod.payload?) and opt.upcase == 'ENCODER')
    return option_values_encoders()
  end

  # Well-known option names specific to post-exploitation
  if (mod.post? or mod.exploit?)
    return option_values_sessions() if opt.upcase == 'SESSION'
  end

  # Is this option used by the active module?
  if (mod.options.include?(opt))
    res.concat(option_values_dispatch(mod.options[opt], str, words))
  end

  # How about the selected payload?
  if (mod.exploit? and mod.datastore['PAYLOAD'])
    p = framework.payloads.create(mod.datastore['PAYLOAD'])
    if (p and p.options.include?(opt))
      res.concat(option_values_dispatch(p.options[opt], str, words))
    end
  end

  return res
end