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

Inherits:
Object
  • Object
show all
Includes:
Msf::Ui::Console::CommandDispatcher, Common, ModuleOptionTabCompletion
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

@@sessions_opts =

Session command options

Rex::Parser::Arguments.new(
["-c", "--command"]              => [ true,  "Run a command on the session given with -i, or all", "<command>"               ],
["-C", "--meterpreter-command"]  => [ true,  "Run a Meterpreter Command on the session given with -i, or all", "<command>"   ],
["-h", "--help"]                 => [ false, "Help banner"                                                                   ],
["-i", "--interact"]             => [ true,  "Interact with the supplied session ID", "<id>"                                 ],
["-l", "--list"]                 => [ false, "List all active sessions"                                                      ],
["-v", "--list-verbose"]         => [ false, "List all active sessions in verbose mode"                                      ],
["-d", "--list-inactive"]        => [ false, "List all inactive sessions"                                                    ],
["-q", "--quiet"]                => [ false, "Quiet mode"                                                                    ],
["-k", "--kill"]                 => [ true,  "Terminate sessions by session ID and/or range", "<id>"                         ],
["-K", "--kill-all"]             => [ false, "Terminate all sessions"                                                        ],
["-s", "--script"]               => [ true,  "Run a script or module on the session given with -i, or all", "<script>"       ],
["-u", "--upgrade"]              => [ true,  "Upgrade a shell to a meterpreter session on many platforms", "<id>"            ],
["-t", "--timeout"]              => [ true,  "Set a response timeout (default: 15)", "<seconds>"                             ],
["-S", "--search"]               => [ true,  "Row search filter.", "<filter>"                                                ],
["-x", "--list-extended"]        => [ false, "Show extended information in the session table"                                ],
["-n", "--name"]                 => [ true,  "Name or rename a session by ID", "<id> <name>"                                 ])
@@threads_opts =
Rex::Parser::Arguments.new(
["-h", "--help"]            => [ false, "Help banner."                                           ],
["-k", "--kill"]            => [ true,  "Terminate the specified thread ID.", "<id>"             ],
["-K", "--kill-all"]        => [ false, "Terminate all non-critical threads."                    ],
["-i", "--info"]            => [ true,  "Lists detailed information about a thread.", "<id>"     ],
["-l", "--list"] => [ false, "List all background threads."                           ],
["-v", "--verbose"]         => [ false, "Print more detailed info.  Use with -i and -l"          ])
@@tip_opts =
Rex::Parser::Arguments.new(
["-h", "--help"] => [ false, "Help banner."                                   ])
@@debug_opts =
Rex::Parser::Arguments.new(
["-h", "--help"]            => [ false, "Help banner."                                   ],
["-d", "--datastore"]       => [ false, "Display the datastore information."             ],
["-c", "--commands"] => [ false, "Display command history."                       ],
["-e", "--errors"]     => [ false, "Display the most recent Error and Stack Trace." ],
["-l", "--logs"]            => [ false, "Display the most recent logs."                  ],
["-v", "--version"]         => [ false, "Display versions and install info."             ],
["-s", "--database"]           => [ false, "Display database statistics."                   ])
@@connect_opts =
Rex::Parser::Arguments.new(
["-h", "--help"]           => [ false, "Help banner."                                                ],
["-p", "--proxies"]        => [ true,  "List of proxies to use.", "<proxies>"                        ],
["-C", "--crlf"]           => [ false, "Try to use CRLF for EOL sequence."                           ],
["-c", "--comm"]           => [ true,  "Specify which Comm to use.", "<comm>"                        ],
["-i", "--send-contents"]  => [ true,  "Send the contents of a file.", "<file>"                      ],
["-P", "--source-port"]    => [ true,  "Specify source port.", "<port>"                              ],
["-S", "--source-address"] => [ true,  "Specify source address.", "<address>"                        ],
["-s", "--ssl"]            => [ false, "Connect with SSL."                                           ],
["-u", "--udp"]            => [ false, "Switch to a UDP socket."                                     ],
["-w", "--timeout"]        => [ true,  "Specify connect timeout.", "<seconds>"                       ],
["-z", "--try-connection"] => [ false, "Just try to connect, then return."                           ])
@@history_opts =
Rex::Parser::Arguments.new(
["-h", "--help"]            => [ false, "Help banner."                                   ],
["-a", "--all-commands"]    => [ false, "Show all commands in history."                  ],
["-n"] => [ true,  "Show the last n commands.", "<num>"             ],
["-c", "--clear"]           => [ false, "Clear command history and history file."        ])
@@save_opts =
Rex::Parser::Arguments.new(
["-h", "--help"]           => [ false, "Help banner."                                                                   ],
["-r", "--reload-default"] => [ false, "Reload default options for the active module."                                  ],
["-l", "--load"]           => [ false, "Load the saved options for the active module."                                  ],
["-d", "--delete-all"]     => [ false, "Delete saved options for all modules from the config file."                     ])
@@setg_opts =

set command options

Rex::Parser::Arguments.new(
  ["-h", "--help"] => [ false, "Help banner."],
  ["-c", "--clear"] => [ false, "Clear the values, explicitly setting to nil (default)"]
)
@@set_opts =
@@setg_opts.merge(
  ["-g", "--global"] => [ false, "Operate on global datastore variables"]
)
@@unsetg_opts =

unset command options

Rex::Parser::Arguments.new(
  ["-h", "--help"] => [ false, "Help banner."],
)
@@unset_opts =
@@unsetg_opts.merge(
  ["-g", "--global"] => [ false, "Operate on global datastore variables"]
)

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 ModuleOptionTabCompletion

#option_values_actions, #option_values_dispatch, #option_values_encoders, #option_values_nops, #option_values_payloads, #option_values_sessions, #option_values_target_addrs, #option_values_target_ports, #option_values_targets, #tab_complete_datastore_names, #tab_complete_module_datastore_names, #tab_complete_option, #tab_complete_option_names, #tab_complete_option_values, #tab_complete_source_interface

Methods included from Common

#arg_host_range, #arg_port_range, #index_from_list, #set_rhosts_from_addrs, #show_options, #trim_path

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

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

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

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

Constructor Details

#initialize(driver) ⇒ Core

Initializes the datastore cache



156
157
158
159
160
161
162
163
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 156

def initialize(driver)
  super

  @cache_payloads = nil
  @previous_module = nil
  @previous_target = nil
  @history_limit = 100
end

Instance Method Details

#cmd_banner(*args) ⇒ Object

Display one of the fabulous banners.



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 247

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

  stats       = framework.stats
  version     = "%yelmetasploit v#{Metasploit::Framework::VERSION}%clr",
  exp_aux_pos = "#{stats.num_exploits} exploits - #{stats.num_auxiliary} auxiliary - #{stats.num_post} post",
  pay_enc_nop = "#{stats.num_payloads} payloads - #{stats.num_encoders} encoders - #{stats.num_nops} nops",
  eva         = "#{stats.num_evasion} evasion",
  padding     = 48

  banner << ("       =[ %-#{padding+8}s]\n" % version)
  banner << ("+ -- --=[ %-#{padding}s]\n" % exp_aux_pos)
  banner << ("+ -- --=[ %-#{padding}s]\n" % pay_enc_nop)
  banner << ("+ -- --=[ %-#{padding}s]\n" % eva)

  banner << "\n"
  banner << Rex::Text.wordwrap('Metasploit Documentation: https://docs.metasploit.com/', indent = 0, cols = 60)

  # Display the banner
  print_line(banner)

end

#cmd_banner_helpObject



237
238
239
240
241
242
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 237

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



220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 220

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



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

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

#cmd_cd_tabs(str, words) ⇒ Object



233
234
235
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 233

def cmd_cd_tabs(str, words)
  tab_complete_directory(str, words)
end

#cmd_color(*args) ⇒ Object



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

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
end

#cmd_color_helpObject



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

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

#cmd_color_tabs(str, words) ⇒ Object

Tab completion for the color 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



205
206
207
208
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 205

def cmd_color_tabs(str, words)
  return [] if words.length > 1
  %w[auto true false]
end

#cmd_connect(*args) ⇒ Object

Talk to a host



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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 412

def cmd_connect(*args)
  if args.length < 2 or args.include?("-h") or args.include?("--help")
    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

  _, lhost, lport = sock.getlocalname()
  print_status("Connected to #{host}:#{port} (via: #{lhost}:#{lport})")

  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

  c2n.join
  n2c.join

  sock.close rescue nil
  infile.close if infile

  true
end

#cmd_connect_helpObject



401
402
403
404
405
406
407
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 401

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_connect_tabs(str, words) ⇒ Object

Tab completion for the connect 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



386
387
388
389
390
391
392
393
394
395
396
397
398
399
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 386

def cmd_connect_tabs(str, words)
  if words.length == 1
    return @@connect_opts.option_keys.select do |opt|
      opt.start_with?(str) && !words.include?(opt)
    end
  end

  case words[-1]
  when '-c', '--comm'
    # Rex::Socket::Comm
  end

  []
end

#cmd_debug(*args) ⇒ Object

Display information useful for debugging errors.



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 343

def cmd_debug(*args)
  if args.empty?
    print_line Debug.all(framework, driver)
    return
  end

  if args.include?("-h") || args.include?("--help")
    cmd_debug_help
  else
    output = ""
    @@debug_opts.parse(args) do |opt|
      case opt
      when '-d'
        output << Debug.datastore(framework, driver)
      when '-c'
        output << Debug.history(driver)
      when '-e'
        output << Debug.errors
      when '-l'
        output << Debug.logs
      when '-v'
        output << Debug.versions(framework)
      when '-s'
        output << Debug.database_configuration(framework)
      end
    end

    if output.empty?
      print_line("Valid argument was not given.")
      cmd_debug_help
    else
      output = Debug.preamble + output
      print_line output
    end
  end
end

#cmd_debug_helpObject



331
332
333
334
335
336
337
338
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 331

def cmd_debug_help
  print_line "Usage: debug [options]"
  print_line
  print_line("Print a set of information in a Markdown format to be included when opening an Issue on Github. " +
               "This information helps us fix problems you encounter and should be included when you open a new issue: " +
               Debug.issue_link)
  print @@debug_opts.usage
end

#cmd_debug_tabs(str, words) ⇒ Object

Tab completion for the debug 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



321
322
323
324
325
326
327
328
329
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 321

def cmd_debug_tabs(str, words)
  if words.length >= 1
    return @@debug_opts.option_keys.select do |opt|
      opt.start_with?(str) && !words.include?(opt)
    end
  end

  []
end

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

Instructs the driver to stop executing.



594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 594

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
  elsif(driver.confirm_exit and not forced)
    print("Are you sure you want to exit Metasploit? [y/N]: ")
    response = gets.downcase.chomp
    if(response == "y" || response == "yes")
      driver.stop
    else
      return
    end
  end

  driver.stop
end

#cmd_features(*args) ⇒ Object

This method handles the features command which allows a user to opt into enabling features that are not yet released to everyone by default.



644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 644

def cmd_features(*args)
  args << 'print' if args.empty?

  action, *rest = args
  case action
  when 'set'
    feature_name, value = rest

    unless framework.features.exists?(feature_name)
      print_warning("Feature name '#{feature_name}' is not available. Either it has been removed, integrated by default, or does not exist in this version of Metasploit.")
      print_warning("Currently supported features: #{framework.features.names.join(', ')}") if framework.features.all.any?
      print_warning('There are currently no features to toggle.') if framework.features.all.empty?
      return
    end

    unless %w[true false].include?(value)
      print_warning('Please specify true or false to configure this feature.')
      return
    end

    framework.features.set(feature_name, value == 'true')
    print_line("#{feature_name} => #{value}")
    # Some flags may require a full console restart
    if framework.features.requires_restart?(feature_name)
      print_warning("Run the #{Msf::Ui::Tip.highlight("save")} command and restart the console for this feature to take effect.")
    else
      # Reload the current module, as feature flags may impact the available module options etc
      driver.run_single("reload") if driver.active_module
    end
  when 'print'
    if framework.features.all.empty?
      print_line 'There are no features to enable at this time. Either the features have been removed, or integrated by default.'
      return
    end

    features_table = Table.new(
      Table::Style::Default,
      'Header' => 'Features table',
      'Prefix' => "\n",
      'Postfix' => "\n",
      'Columns' => [
        '#',
        'Name',
        'Enabled',
        'Description',
      ]
    )

    framework.features.all.each.with_index do |feature, index|
      features_table << [
        index,
        feature[:name],
        feature[:enabled].to_s,
        feature[:description]
      ]
    end

    print_line features_table.to_s
  else
    cmd_features_help
  end
rescue StandardError => e
  elog(e)
  print_error(e.message)
end

#cmd_features_helpObject



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 616

def cmd_features_help
  print_line <<~CMD_FEATURE_HELP
    Enable or disable unreleased features that Metasploit supports

    Usage:
      features set feature_name [true/false]
      features print

    Subcommands:
      set - Enable or disable a given feature
      print - show all available features and their current configuration

    Examples:
      View available features:
        features print

      Enable a feature:
        features set new_feature true

      Disable a feature:
        features set new_feature false
  CMD_FEATURE_HELP
end

#cmd_features_tabs(_str, words) ⇒ Object

Tab completion for the features 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



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

def cmd_features_tabs(_str, words)
  if words.length == 1
    return %w[set print]
  end

  _command_name, action, *rest = words
  ret = []
  case action
  when 'set'
    feature_name, _value = rest

    if framework.features.exists?(feature_name)
      ret += %w[true false]
    else
      ret += framework.features.names
    end
  end

  ret
end

#cmd_get(*args) ⇒ Object

Gets a value if it’s been set.



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

def cmd_get(*args)

  # Figure out if these are global variables
  global = false

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

  # No arguments?  No cookie.
  if args.empty?
    global ? cmd_getg_help : cmd_get_help
    return false
  end

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

  args.each { |var| print_line("#{var} => #{datastore[var]}") }
end

#cmd_get_helpObject



2108
2109
2110
2111
2112
2113
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2108

def cmd_get_help
  print_line "Usage: get var1 [var2 ...]"
  print_line
  print_line "The get command is used to get the value of one or more variables."
  print_line
end

#cmd_get_tabs(str, words) ⇒ Object

Tab completion for the get 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



2151
2152
2153
2154
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2151

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

#cmd_getg(*args) ⇒ Object

Gets variables in the global data store.



2166
2167
2168
2169
2170
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2166

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

  cmd_get(*args)
end

#cmd_getg_helpObject



2156
2157
2158
2159
2160
2161
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2156

def cmd_getg_help
  print_line "Usage: getg var1 [var2 ...]"
  print_line
  print_line "Exactly like get -g, get global variables"
  print_line
end

#cmd_getg_tabs(str, words) ⇒ Object

Tab completion for the getg 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



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

def cmd_getg_tabs(str, words)
  self.framework.datastore.keys
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



2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2388

def cmd_grep(*args)
  match_mods = {:insensitive => false}
  output_mods = {:count => false, :invert => false}

  opts = OptionParser.new do |opts|
    opts.banner = "Usage: grep [OPTIONS] [--] PATTERN CMD..."
    opts.separator "Grep the results of a console command (similar to Linux grep command)"
    opts.separator ""

    opts.on '-m num', '--max-count num', 'Stop after num matches.', Integer do |max|
      match_mods[:max] = max
    end
    opts.on '-A num', '--after-context num', 'Show num lines of output after a match.', Integer do |num|
      output_mods[:after] = num
    end
    opts.on '-B num', '--before-context num', 'Show num lines of output before a match.', Integer do |num|
      output_mods[:before] = num
    end
    opts.on '-C num', '--context num', 'Show num lines of output around a match.', Integer do |num|
      output_mods[:before] = output_mods[:after] = num
    end
    opts.on '-v', '--[no-]invert-match', 'Invert match.' do |invert|
      match_mods[:invert] = invert
    end
    opts.on '-i', '--[no-]ignore-case', 'Ignore case.' do |insensitive|
      match_mods[:insensitive] = insensitive
    end
    opts.on '-c', '--count', 'Only print a count of matching lines.' do |count|
      output_mods[:count] = count
    end
    opts.on '-k num', '--keep-header num', 'Keep (include) num lines at start of output', Integer do |num|
      output_mods[:keep] = num
    end
    opts.on '-s num', '--skip-header num', 'Skip num lines of output before attempting match.', Integer do |num|
      output_mods[:skip] = num
    end
    opts.on '-h', '--help', 'Help banner.' do
      return print(remove_lines(opts.help, '--generate-completions'))
    end

    # Internal use
    opts.on '--generate-completions str', 'Return possible tab completions for given string.' do |str|
      return opts.candidate str
    end
  end

  # OptionParser#order allows us to take the rest of the line for the command
  pattern, *rest = opts.order(args)
  cmd = Shellwords.shelljoin(rest)
  return print(opts.help) if !pattern || cmd.empty?

  rx = Regexp.new(pattern, match_mods[:insensitive])

  # redirect output after saving the old one and getting a new output buffer to use for redirect
  orig_output = driver.output

  # 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

  driver.init_ui(driver.input, temp_output)
  # run the desired command to be grepped
  driver.run_single(cmd)
  # restore original output
  driver.init_ui(driver.input, orig_output)

  # 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: '#{rest[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



2376
2377
2378
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2376

def cmd_grep_help
  cmd_grep '-h'
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



2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2498

def cmd_grep_tabs(str, words)
  str = '-' if str.empty? # default to use grep's options
  tabs = cmd_grep '--generate-completions', str

  # 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_history(*args) ⇒ Object



737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 737

def cmd_history(*args)
  length = Readline::HISTORY.length

  if length < @history_limit
    limit = length
  else
    limit = @history_limit
  end

  @@history_opts.parse(args) do |opt, idx, val|
    case opt
    when '-a'
      limit = length
    when '-n'
      return cmd_history_help unless val && val.match(/\A[-+]?\d+\z/)
      if length < val.to_i
        limit = length
      else
        limit = val.to_i
      end
    when '-c'
      if Readline::HISTORY.respond_to?(:clear)
        Readline::HISTORY.clear
      elsif defined?(RbReadline)
        RbReadline.clear_history
      else
        print_error('Could not clear history, skipping file')
        return false
      end

      # Portable file truncation?
      if File.writable?(Msf::Config.history_file)
        File.write(Msf::Config.history_file, '')
      end

      print_good('Command history and history file cleared')

      return true
    when '-h'
      cmd_history_help
      return false
    end
  end

  start   = length - limit
  pad_len = length.to_s.length

  (start..length-1).each do |pos|
    cmd_num = (pos + 1).to_s
    print_line "#{cmd_num.ljust(pad_len)}  #{Readline::HISTORY[pos]}"
  end
end

#cmd_history_helpObject



790
791
792
793
794
795
796
797
798
799
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 790

def cmd_history_help
  print_line "Usage: history [options]"
  print_line
  print_line "Shows the command history."
  print_line
  print_line "If -n is not set, only the last #{@history_limit} commands will be shown."
  print_line 'If -c is specified, the command history and history file will be cleared.'
  print_line 'Start commands with a space to avoid saving them to history.'
  print @@history_opts.usage
end

#cmd_history_tabs(str, words) ⇒ Object



801
802
803
804
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 801

def cmd_history_tabs(str, words)
  return [] if words.length > 1
  @@history_opts.option_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.



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

def cmd_load(*args)
  case args[0]
  when '-l'
    list_plugins
  when '-h', nil, ''
    cmd_load_help
  when '-s'
    framework.plugins.each{ |p| print_line p.name }
  else
    load_plugin(args)
  end
end

#cmd_load_helpObject



949
950
951
952
953
954
955
956
957
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 949

def cmd_load_help
  print_line "Usage: load <option> [var=val var=val ...]"
  print_line
  print_line "Loads a plugin from the supplied path."
  print_line "For a list of built-in plugins, do: load -l"
  print_line "For a list of loaded plugins, do: load -s"
  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



1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1038

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/, '')} - framework.plugins.map(&:name)
end

#cmd_repeat(*args) ⇒ Object

Repeats (loops) a given list of commands



2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2516

def cmd_repeat(*args)
  looper = method :loop

  opts = OptionParser.new do |opts|
    opts.banner = 'Usage: repeat [OPTIONS] COMMAND...'
    opts.separator 'Repeat (loop) a ;-separated list of msfconsole commands indefinitely, or for a'
    opts.separator 'number of iterations or a certain amount of time.'
    opts.separator ''

    opts.on '-t SECONDS', '--time SECONDS', 'Number of seconds to repeat COMMAND...', Integer do |n|
      looper = ->(&block) do
        # While CLOCK_MONOTONIC is a Linux thing, Ruby emulates it for *BSD, MacOS, and Windows
        ending_time = Process.clock_gettime(Process::CLOCK_MONOTONIC, :second) + n
        while Process.clock_gettime(Process::CLOCK_MONOTONIC, :second) < ending_time
          block.call
        end
      end
    end

    opts.on '-n TIMES', '--number TIMES', 'Number of times to repeat COMMAND..', Integer do |n|
      looper = n.method(:times)
    end

    opts.on '-h', '--help', 'Help banner.' do
      return print(remove_lines(opts.help, '--generate-completions'))
    end

    # Internal use
    opts.on '--generate-completions str', 'Return possible tab completions for given string.' do |str|
      return opts.candidate str
    end
  end

  cmds = opts.order(args).slice_when do |prev, _|
    # If the last character of a shellword was a ';' it's probably to
    # delineate commands and we can remove it
    prev[-1] == ';' && prev[-1] = ''
  end.map do |c|
    Shellwords.shelljoin(c)
  end

  # Print help if we have no commands, or all the commands are empty
  return cmd_repeat '-h' if cmds.all? &:empty?

  begin
    looper.call do
      cmds.each do |c|
        driver.run_single c, propagate_errors: true
      end
    end
  rescue ::Exception
    # Stop looping on exception
    nil
  end
end

#cmd_repeat_helpObject



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

def cmd_repeat_help
  cmd_repeat '-h'
end

#cmd_repeat_tabs(str, words) ⇒ Object

Almost the exact same as grep



2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2573

def cmd_repeat_tabs(str, words)
  str = '-' if str.empty? # default to use repeat's options
  tabs = cmd_repeat '--generate-completions', str

  # 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_route(*args) ⇒ Object

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



1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1098

def cmd_route(*args)
  begin
    args << 'print' if args.length == 0

    action = args.shift
    case action
    when "add", "remove", "del"
      subnet = args.shift
      subnet, cidr_mask = subnet.split("/")

      if Rex::Socket.is_ip_addr?(args.first)
        netmask = args.shift
      elsif Rex::Socket.is_ip_addr?(subnet)
        cidr_mask ||= Rex::Socket.is_ipv6?(subnet) ? 128 : 32
        netmask = Rex::Socket.addr_ctoa(cidr_mask, v6: Rex::Socket.is_ipv6?(subnet))
      end

      netmask = args.shift if netmask.nil?
      gateway_name = args.shift

      if (subnet.nil? || netmask.nil? || gateway_name.nil?)
        print_error("Missing arguments to route #{action}.")
        return false
      end

      case gateway_name
      when /local/i
        gateway = Rex::Socket::Comm::Local
      when /^(-1|[0-9]+)$/
        session = framework.sessions.get(gateway_name)
        if session.kind_of?(Msf::Session::Comm)
          gateway = session
        elsif session.nil?
          print_error("Not a session: #{gateway_name}")
          return false
        else
          print_error("Cannot route through the specified session (not a Comm)")
          return false
        end
      else
        print_error("Invalid gateway")
        return false
      end

      msg = "Route "
      if action == "remove" or action == "del"
        worked = Rex::Socket::SwitchBoard.remove_route(subnet, netmask, gateway)
        msg << (worked ? "removed" : "not found")
      else
        worked = Rex::Socket::SwitchBoard.add_route(subnet, netmask, gateway)
        msg << (worked ? "added" : "already exists")
      end
      print_status(msg)

    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"
      # IPv4 Table
      tbl_ipv4 = Table.new(
        Table::Style::Default,
        'Header'  => "IPv4 Active Routing Table",
        'Prefix'  => "\n",
        'Postfix' => "\n",
        'Columns' =>
          [
            'Subnet',
            'Netmask',
            'Gateway',
          ],
        'ColProps' =>
          {
            'Subnet'  => { 'Width' => 17 },
            'Netmask' => { 'Width' => 17 },
          })

      # IPv6 Table
      tbl_ipv6 = Table.new(
        Table::Style::Default,
        'Header'  => "IPv6 Active Routing Table",
        'Prefix'  => "\n",
        'Postfix' => "\n",
        'Columns' =>
          [
            'Subnet',
            'Netmask',
            'Gateway',
          ],
        'ColProps' =>
          {
            'Subnet'  => { 'Width' => 17 },
            'Netmask' => { 'Width' => 17 },
          })

      # Populate Route Tables
      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_ipv4 << [ route.subnet, route.netmask, gw ] if Rex::Socket.is_ipv4?(route.netmask)
        tbl_ipv6 << [ route.subnet, route.netmask, gw ] if Rex::Socket.is_ipv6?(route.netmask)
      }

      # Print Route Tables
      print(tbl_ipv4.to_s) if tbl_ipv4.rows.length > 0
      print(tbl_ipv6.to_s) if tbl_ipv6.rows.length > 0

      if (tbl_ipv4.rows.length + tbl_ipv6.rows.length) < 1
        print_status("There are currently no routes defined.")
      elsif (tbl_ipv4.rows.length < 1) && (tbl_ipv6.rows.length > 0)
        print_status("There are currently no IPv4 routes defined.")
      elsif (tbl_ipv4.rows.length > 0) && (tbl_ipv6.rows.length < 1)
        print_status("There are currently no IPv6 routes defined.")
      end

    else
      cmd_route_help
    end
  rescue => error
    elog(error)
    print_error(error.message)
  end
end

#cmd_route_helpObject



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

def cmd_route_help
  print_line "Route traffic destined to a given subnet through a supplied session."
  print_line
  print_line "Usage:"
  print_line "  route [add/remove] subnet netmask [comm/sid]"
  print_line "  route [add/remove] cidr [comm/sid]"
  print_line "  route [get] <host or network>"
  print_line "  route [flush]"
  print_line "  route [print]"
  print_line
  print_line "Subcommands:"
  print_line "  add - make a new route"
  print_line "  remove - delete a route; 'del' is an alias"
  print_line "  flush - remove all routes"
  print_line "  get - display the route for a given target"
  print_line "  print - show all active routes"
  print_line
  print_line "Examples:"
  print_line "  Add a route for all hosts from 192.168.0.0 to 192.168.0.255 through session 1"
  print_line "    route add 192.168.0.0 255.255.255.0 1"
  print_line "    route add 192.168.0.0/24 1"
  print_line
  print_line "  Delete the above route"
  print_line "    route remove 192.168.0.0/24 1"
  print_line "    route del 192.168.0.0 255.255.255.0 1"
  print_line
  print_line "  Display the route that would be used for the given host or network"
  print_line "    route get 192.168.0.11"
  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



1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1247

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

Deletes or saves the active datastore contents to disk for automatic use across restarts of the console.



1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1308

def cmd_save(*args)
  if args.include?('-h') || args.include?('--help')
    cmd_save_help
    return false
  end

  if args.empty?
    # Save config for current module
    # Save the console config
    driver.save_config

    begin
      FeatureManager.instance.save_config
    rescue StandardException => e
      elog(e)
    end

    # 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

  @@save_opts.parse(args) do |opt|
    case opt
    when '-d'
      # Delete all saved options for modules from the config file.
      # No framework options will be deleted.
      begin
        ini = Rex::Parser::Ini.new(::Msf::Config.config_file)

        ini.delete_if { |k, _v| !k.start_with?('framework') }

        ini.to_file(::Msf::Config.config_file)
      rescue StandardError
        print_error("Failed to delete console config: #{$!}")
      end

      if active_module
        active_module.import_defaults
      end
      print_line('Deleted saved configs for all modules.')
    when '-r'
      active_module.import_defaults
      print_line('Reloaded default options.')
    when '-l'
      active_module.load_config
      print_line("Loaded config from #{Msf::Config.config_file}.")
    when '-h'
      cmd_save_help
      return false
    else
      print_line("Unknown option: #{opt}")
      print(@@save_opts.usage)
    end
  end
end

#cmd_save_helpObject

Print save help information



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

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

#cmd_save_tabs(str, words) ⇒ Object

Tab completion for the save 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



1289
1290
1291
1292
1293
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1289

def cmd_save_tabs(str, words)
  if words.length == 1
    @@save_opts.option_keys.select { |opt| opt.start_with?(str) }
  end
end

#cmd_sessions(*args) ⇒ Object

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



1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
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
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
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
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1423

def cmd_sessions(*args)
  begin
  method   = nil
  quiet    = false
  show_active = false
  show_inactive = false
  show_extended = false
  verbose  = false
  sid      = nil
  cmds     = []
  script   = nil
  response_timeout = 15
  search_term = nil
  session_name = nil
  has_script_arguments = false

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

  if args.length == 1 && args[0] =~ /-?\d+/
    method = 'interact'
    sid = args[0].to_i
  else
    # Parse the command options
    @@sessions_opts.parse(args) do |opt, idx, val|
      next if has_script_arguments

      case opt
      when "-q", "--quiet"
        quiet = true
      # Run a command on all sessions, or the session given with -i
      when "-c", "--command"
        method = 'cmd'
        cmds << val if val
      when "-C", "--meterpreter-command"
          method = 'meterp-cmd'
          cmds << val if val
      # Display the list of inactive sessions
      when "-d", "--list-inactive"
        show_inactive = true
        method = 'list_inactive'
      when "-x", "--list-extended"
        show_extended = true
      when "-v", "--list-verbose"
        verbose = true
      # Do something with the supplied session identifier instead of
      # all sessions.
      when "-i", "--interact"
        sid = val
      # Display the list of active sessions
      when "-l", "--list"
        show_active = true
        method = 'list'
      when "-k", "--kill"
        method = 'kill'
        sid = val || false
      when "-K", "--kill-all"
        method = 'killall'
      # Run a script or module on specified sessions
      when "-s", "--script"
        unless script
          method = 'script'
          script = val
          # Assume any parameter after the script name is a flag/argument we want to pass to the script itself.
          extra += args[(idx + 1)..-1]
          has_script_arguments = true
        end
      # Upload and exec to the specific command session
      when "-u", "--upgrade"
        method = 'upexec'
        sid = val || false
      # Search for specific session
      when "-S", "--search"
        search_term = val
      # Display help banner
      when "-h", "--help"
        cmd_sessions_help
        return false
      when "-t", "--timeout"
        if val.to_s =~ /^\d+$/
          response_timeout = val.to_i
        end
      when "-n", "--name"
        method = 'name'
        session_name = val
      else
        extra << val
      end
    end
  end

  if !method && sid
    method = 'interact'
  end

  unless sid.nil? || method == 'interact'
    session_list = build_range_array(sid)
    if session_list.blank?
      print_error("Please specify valid session identifier(s)")
      return false
    end
  end

  if show_inactive && !framework.db.active
    print_warning("Database not connected; list of inactive sessions unavailable")
  end

  last_known_timeout = nil

  # 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 = session_list
      else
        sessions = framework.sessions.keys.sort
      end
      if sessions.blank?
        print_error("Please specify valid session identifier(s) using -i")
        return false
      end
      sessions.each do |s|
        session = verify_session(s)
        next unless session
        print_status("Running '#{cmd}' on #{session.type} session #{s} (#{session.session_host})")
        if session.respond_to?(:response_timeout)
          last_known_timeout = session.response_timeout
          session.response_timeout = response_timeout
        end

        begin
          if session.type == 'meterpreter'
            # If session.sys is nil, dont even try..
            unless session.sys
              print_error("Session #{s} does not have stdapi loaded, skipping...")
              next
            end
            c, c_args = cmd.split(' ', 2)
            begin
              data = session.sys.process.capture_output(c, c_args,
              {
                'Channelized' => true,
                'Subshell'    => true,
                'Hidden'      => true
              }, response_timeout)
              print_line(data) unless data.blank?
            rescue ::Rex::Post::Meterpreter::RequestError
              print_error("Failed: #{$!.class} #{$!}")
            rescue Rex::TimeoutError
              print_error("Operation timed out")
            end
          elsif session.type == 'shell' || session.type == 'powershell'
            output = session.shell_command(cmd)
            print_line(output) if output
          end
        ensure
          # Restore timeout for each session
          if session.respond_to?(:response_timeout) && last_known_timeout
            session.response_timeout = last_known_timeout
          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 'meterp-cmd'
      if cmds.length < 1
        print_error("No command specified!")
        return false
      end

      if sid
        sessions = session_list
      else
        sessions = framework.sessions.keys.sort
      end
      if sessions.blank?
        print_error("Please specify valid session identifier(s) using -i")
        return false
      end

      cmds.each do |cmd|
        sessions.each do |session|
          session = verify_session(session)
          unless session.type == 'meterpreter'
            print_error "Session ##{session.sid} is not a Meterpreter shell. Skipping..."
            next
          end

          next unless session
          print_status("Running '#{cmd}' on #{session.type} session #{session.sid} (#{session.session_host})")
          if session.respond_to?(:response_timeout)
            last_known_timeout = session.response_timeout
            session.response_timeout = response_timeout
          end

          output = session.run_cmd(cmd, driver.output)
        end
      end
  when 'kill'
    print_status("Killing the following session(s): #{session_list.join(', ')}")
    session_list.each do |sess_id|
      session = framework.sessions.get(sess_id)
      if session
        if session.respond_to?(:response_timeout)
          last_known_timeout = session.response_timeout
          session.response_timeout = response_timeout
        end
        print_status("Killing session #{sess_id}")
        begin
          session.kill
        ensure
          if session.respond_to?(:response_timeout) && last_known_timeout
            session.response_timeout = last_known_timeout
          end
        end
      else
        print_error("Invalid session identifier: #{sess_id}")
      end
    end
  when 'killall'
    print_status("Killing all sessions...")
    framework.sessions.each_sorted.reverse_each do |s|
      session = framework.sessions.get(s)
      if session
        if session.respond_to?(:response_timeout)
          last_known_timeout = session.response_timeout
          session.response_timeout = response_timeout
        end
        begin
          session.kill
        ensure
          if session.respond_to?(:response_timeout) && last_known_timeout
            session.response_timeout = last_known_timeout
          end
        end
      end
    end
  when 'interact'
    while sid
      session = verify_session(sid)
      if session
        if session.respond_to?(:response_timeout)
          last_known_timeout = session.response_timeout
          session.response_timeout = response_timeout
        end
        print_status("Starting interaction with #{session.name}...\n") unless quiet
        begin
          self.active_session = session
          sid = session.interact(driver.input.dup, driver.output)
          self.active_session = nil
          driver.input.reset_tab_completion if driver.input.supports_readline
        ensure
          if session.respond_to?(:response_timeout) && last_known_timeout
            session.response_timeout = last_known_timeout
          end
        end
      else
        sid = nil
      end
    end
  when 'script'
    unless script
      print_error("No script or module specified!")
      return false
    end
    sessions = sid ? session_list : framework.sessions.keys.sort

    sessions.each do |sess_id|
      session = verify_session(sess_id, true)
      # @TODO: Not interactive sessions can or cannot have scripts run on them?
      if session == false # specifically looking for false
        # if verify_session returned false, sess_id is valid, but not interactive
        session = framework.sessions.get(sess_id)
      end
      if session
        if session.respond_to?(:response_timeout)
          last_known_timeout = session.response_timeout
          session.response_timeout = response_timeout
        end
        begin
          print_status("Session #{sess_id} (#{session.session_host}):")
          print_status("Running #{script} on #{session.type} session" +
                        " #{sess_id} (#{session.session_host})")
          begin
            session.execute_script(script, *extra)
          rescue ::Exception => e
            log_error("Error executing script or module: #{e.class} #{e}")
          end
        ensure
          if session.respond_to?(:response_timeout) && last_known_timeout
            session.response_timeout = last_known_timeout
          end
        end
      else
        print_error("Invalid session identifier: #{sess_id}")
      end
    end
  when 'upexec'
    print_status("Executing 'post/multi/manage/shell_to_meterpreter' on " +
                  "session(s): #{session_list}")
    session_list.each do |sess_id|
      session = verify_session(sess_id)
      if session
        if session.respond_to?(:response_timeout)
          last_known_timeout = session.response_timeout
          session.response_timeout = response_timeout
        end
        begin
          session.init_ui(driver.input, driver.output)
          session.execute_script('post/multi/manage/shell_to_meterpreter')
          session.reset_ui
        ensure
          if session.respond_to?(:response_timeout) && last_known_timeout
            session.response_timeout = last_known_timeout
          end
        end
      end

      if session_list.count > 1
        print_status("Sleeping 5 seconds to allow the previous handler to finish..")
        sleep(5)
      end
    end
  when 'list', 'list_inactive', nil
    print_line
    print(Serializer::ReadableText.dump_sessions(framework, show_active: show_active, show_inactive: show_inactive, show_extended: show_extended, verbose: verbose, search_term: search_term))
    print_line
  when 'name'
    if session_name.blank?
      print_error('Please specify a valid session name')
      return false
    end

    sessions = sid ? session_list : nil

    if sessions.nil? || sessions.empty?
      print_error("Please specify valid session identifier(s) using -i")
      return false
    end

    sessions.each do |s|
      if framework.sessions[s].respond_to?(:name=)
        framework.sessions[s].name = session_name
        print_status("Session #{s} named to #{session_name}")
      else
        print_error("Session #{s} cannot be named")
      end
    end
  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

  true
end

#cmd_sessions_helpObject



1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1409

def cmd_sessions_help
  print_line('Usage: sessions [options] or sessions [id]')
  print_line
  print_line('Active session manipulation and interaction.')
  print(@@sessions_opts.usage)
  print_line
  print_line('Many options allow specifying session ranges using commas and dashes.')
  print_line('For example:  sessions -s checkvm -i 1,3-5  or  sessions -k 1-2,5,6')
  print_line
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



1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1802

def cmd_sessions_tabs(str, words)
  if words.length == 1
    return @@sessions_opts.option_keys.select { |opt| opt.start_with?(str) }
  end

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

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

  when "-s", "--search"
    # XXX: Complete scripts

  end

  []
end

#cmd_set(*args) ⇒ Object

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



1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
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
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1839

def cmd_set(*args)
  # Figure out if these are global variables
  global = false
  append = false
  clear = false

  # Manually parse options to allow users to set the strings
  # such as `-g` in a datastore value
  loop do
    if args[0] == '-g' || args[0] == '--global'
      args.shift
      global = true
    elsif args[0] == '-a'
      args.shift
      append = true
    elsif (args[0] == '-c' || args[0] == '--clear') && framework.features.enabled?(Msf::FeatureManager::DATASTORE_FALLBACKS)
      args.shift
      clear = true
    else
      break
    end
  end

  valid_options = []
  # Determine which data store we're operating on
  if (active_module and global == false)
    datastore = active_module.datastore

    tab_complete_option_names(active_module, '', []).each do |opt_name|
      valid_options << opt_name
      option = active_module.options[opt_name]
      next unless option

      # aliases that are defined for backwards compatibility are not tab completed but are still valid option names
      valid_options += active_module.options[opt_name].aliases
    end
  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 && !clear
    if global || valid_options.any? { |vo| vo.casecmp?(args[0]) }
      print_line("#{args[0]} => #{datastore[args[0]]}")
      return true
    else
      message = "Unknown datastore option: #{args[0]}."
      suggestion = DidYouMean::SpellChecker.new(dictionary: valid_options).correct(args[0]).first
      message << " Did you mean #{suggestion}?" if suggestion
      print_error(message)
      cmd_set_help
      return false
    end
  end

  # Set the supplied name to the supplied value
  name, *values_array = args
  if clear
    value = nil
  elsif name.casecmp?('RHOST') || name.casecmp?('RHOSTS')
    # Wrap any values which contain spaces in quotes to ensure it's parsed correctly later
    value = values_array.map { |value| value.include?(' ') ? "\"#{value}\"" : value }.join(' ')
  else
    value = values_array.join(' ')
  end

  # Set PAYLOAD
  if name.upcase == 'PAYLOAD' && active_module && (active_module.exploit? || active_module.evasion?) && !clear
    value = trim_path(value, 'payload')

    index_from_list(payload_show_results, value) do |mod|
      return false unless mod && mod.respond_to?(:first)

      # [name, class] from payload_show_results
      value = mod.first
    end
  end

  unless global || valid_options.any? { |vo| vo.casecmp?(name) }
    message = "Unknown datastore option: #{name}."
    suggestion = DidYouMean::SpellChecker.new(dictionary: valid_options).correct(name).first
    message << " Did you mean #{suggestion}?" if suggestion
    print_warning(message)
  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 false
  end

  # Save the old value before changing it, in case we need to compare it
  old_value = datastore[name]

  begin
    if append
      datastore[name] = datastore[name] + value
    else
      datastore[name] = value
    end
  rescue Msf::OptionValidateError => e
    print_error(e.message)
    elog('Exception encountered in cmd_set', error: e)
  end

  # Set PAYLOAD from TARGET
  if name.upcase == 'TARGET' && active_module && (active_module.exploit? || active_module.evasion?)
    active_module.import_target_defaults
  end

  # If the new SSL value already set in datastore[name] is different from the old value, warn the user
  if name.casecmp('SSL') == 0 && datastore[name] != old_value
    print_warning("Changing the SSL option's value may require changing RPORT!")
  end

  if name.casecmp?('SessionTlvLogging')
    # Check if we need to append the default filename if user provided an output directory
    if datastore[name].start_with?('file:')
      pathname = ::Pathname.new(datastore[name].split('file:').last)
      if ::File.directory?(pathname)
        datastore[name] = ::File.join(datastore[name], 'sessiontlvlogging.txt')
      end
    end

    framework.sessions.each { |_index, session| session.initialize_tlv_logging(datastore[name]) if session.type.casecmp? 'meterpreter' }
  end

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

#cmd_set_helpObject



1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1822

def cmd_set_help
  print_line "Usage: set [options] [name] [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
  print_line "If setting a PAYLOAD, this command can take an index from `show payloads'."
  print @@set_opts.usage if framework.features.enabled?(Msf::FeatureManager::DATASTORE_FALLBACKS)
  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



1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1995

def cmd_set_tabs(str, words)
  # A value has already been specified
  if words.length > 3
    return []
  elsif words.length == 3 and words[1] != '-g' and words[1] != '--global'
    return []
  end

  # A value needs to be specified, show tab completion options where possible
  if words.length == 3 or (words.length == 2 and words[1][0] != '-')
    return tab_complete_option_values(active_module, str, words, opt: words[-1])
  end

  option_names = tab_complete_option_names(active_module, str, words)
  if words.length == 1
    # Only the command has been provided, offer options which immediately follow the command
    options = @@set_opts.option_keys.select { |opt| opt.start_with?(str) }
    return options + option_names
  end

  option_names
end

#cmd_setg(*args) ⇒ Object

Sets the supplied variables in the global datastore.



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

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

  cmd_set(*args)
end

#cmd_setg_helpObject



2018
2019
2020
2021
2022
2023
2024
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2018

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 @@setg_opts.usage if framework.features.enabled?(Msf::FeatureManager::DATASTORE_FALLBACKS)
  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



2060
2061
2062
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2060

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

#cmd_sleep(*args) ⇒ Object

Causes process to pause for the specified number of seconds



816
817
818
819
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 816

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

#cmd_sleep_helpObject



806
807
808
809
810
811
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 806

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



1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1387

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
  driver.output.config[:color] = color

  print_status(msg)
end

#cmd_spool_helpObject



1375
1376
1377
1378
1379
1380
1381
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1375

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_spool_tabs(str, words) ⇒ Object



1383
1384
1385
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1383

def cmd_spool_tabs(str, words)
  tab_complete_filenames(str, words)
end

#cmd_threads(*args) ⇒ Object

Displays and manages running background threads



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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 831

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



821
822
823
824
825
826
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 821

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



937
938
939
940
941
942
943
944
945
946
947
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 937

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

  if words.length == 2 && @@threads_opts.include?(words[1]) && @@threads_opts.arg_required?(words[1])
    return framework.threads.each_index.map{ |idx| idx.to_s }
  end

  []
end

#cmd_tips(*args) ⇒ Object Also known as: cmd_tip

Display useful productivity tips to the user.



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 296

def cmd_tips(*args)
  if args.include?("-h") || args.include?("--help")
    cmd_tip_help
  else
    tbl = Table.new(
      Table::Style::Default,
      'Columns' => %w[Id Tip]
    )

    Tip.all.each_with_index do |tip, index|
      tbl << [ index, tip ]
    end

    print(tbl.to_s)
  end
end

#cmd_tips_helpObject Also known as: cmd_tip_help



284
285
286
287
288
289
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 284

def cmd_tips_help
  print_line "Usage: tips [options]"
  print_line
  print_line "Print a useful list of productivity tips on how to use Metasploit"
  print @@tip_opts.usage
end

#cmd_tips_tabs(str, words) ⇒ Object

Tab completion for the tips 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



276
277
278
279
280
281
282
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 276

def cmd_tips_tabs(str, words)
  if words.length == 1
    return @@tip_opts.option_keys.select { |opt| opt.start_with?(str) }
  end

  []
end

#cmd_unload(*args) ⇒ Object

Unloads a plugin by its name.



2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2076

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

  # Find a plugin within the plugins array
  plugin = framework.plugins.find { |p| p.name.downcase == args[0].downcase }

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

#cmd_unload_helpObject



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

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



2100
2101
2102
2103
2104
2105
2106
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2100

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.



2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2204

def cmd_unset(*args)
  if framework.features.enabled?(Msf::FeatureManager::DATASTORE_FALLBACKS)
    return cmd_unset_with_fallbacks(*args)
  end

  # 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



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

def cmd_unset_help
  if framework.features.enabled?(Msf::FeatureManager::DATASTORE_FALLBACKS)
    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
  else
    print_line "Usage: unset [options] var1 var2 var3 ..."
    print_line
    print_line "The unset command is used to unset one or more variables which have been set by the user."
    print_line "To update all entries, specify 'all' as the variable name."
    print @@unset_opts.usage
    print_line
  end
end

#cmd_unset_tabs(str, words) ⇒ Object

Tab completion for the unset command

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 at least 1 when tab completion has reached this stage since the command itself has been completed.



2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2033

def cmd_unset_tabs(str, words)
  datastore_names = tab_complete_module_datastore_names(active_module, str, words)
  if words.length == 1
    # Only the command has been provided, offer options which immediately follow the command
    options = @@unset_opts.option_keys.select { |opt| opt.start_with?(str) }
    return options + datastore_names
  end

  datastore_names
end

#cmd_unset_with_fallbacks(*args) ⇒ Object

Unsets a value if it’s been set, resetting the value back to a default value



2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2260

def cmd_unset_with_fallbacks(*args)
  if args.include?('-h') || args.include?('--help')
    cmd_unset_help
    return
  end

  # Figure out if these are global variables
  global = false

  @@unset_opts.parse(args) do |opt, idx, val|
    case opt
    when '-g'
      global = true
    end
  end

  variable_names = args.reject { |arg| arg.start_with?('-') }

  # No variable names? No cookie.
  if variable_names.empty?
    cmd_unset_help
    return false
  end

  # Determine which data store we're operating on
  if active_module && !global
    datastore = active_module.datastore
  else
    datastore = framework.datastore
  end

  is_all_variables = variable_names[0] == 'all'
  if is_all_variables
    variable_names = datastore.keys
    variable_names += Msf::DataStore::GLOBAL_KEYS if global
    variable_names += ['PAYLOAD'] if !global && active_module && (active_module.exploit? || active_module.evasion?)
    variable_names = variable_names.uniq(&:downcase)
  end

  print_line("Unsetting datastore...") if is_all_variables

  variable_names.each do |variable_name|
    if driver.on_variable_unset(global, variable_name) == false
      print_error("The variable #{variable_name} cannot be unset at this time.") # unless variable_name.casecmp?('PAYLOAD')
      next
    end

    print_line("Unsetting #{variable_name}...") unless is_all_variables
    datastore.unset(variable_name)
  end

  # Do a final pass over the datastore. If a user has unset a variable - but it continues to have a value either through
  # option defaults, or being globally set it might be confusing to users. In this scenario, log out a helpful message.
  #
  # i.e. the scenario of a user unsetting 'RHOSTS', but the value continues to inherit from the global framework datastore.
  unless is_all_variables
    variable_names.each do |variable_name|
      search_result = datastore.search_for(variable_name)
      if search_result.fallback?
        print_warning(
          "Variable #{variable_name.inspect} unset - but will continue to use #{search_result.fallback_key.inspect} as a fallback preference. " \
            "If this is not desired, either run #{Msf::Ui::Tip.highlight("set #{variable_name} new_value")} or #{Msf::Ui::Tip.highlight("unset #{search_result.fallback_key}")}"
        )
      elsif !global && search_result.global?
        print_warning(
          "Variable #{variable_name.inspect} unset - but will continue to use the globally set value as a preference. " \
            "If this is not desired, either run #{Msf::Ui::Tip.highlight("set --clear #{variable_name}")} or #{Msf::Ui::Tip.highlight("unsetg #{variable_name}")}"
        )
      elsif !search_result.value.nil?
        print_warning(
          "Variable #{variable_name.inspect} unset - but will use a default value still. " \
            "If this is not desired, set it to a new value or attempt to clear it with #{Msf::Ui::Tip.highlight("set --clear #{variable_name}")}"
        )
      end
    end
  end
end

#cmd_unsetg(*args) ⇒ Object

Unsets variables in the global data store.



2349
2350
2351
2352
2353
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2349

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



2362
2363
2364
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2362

def cmd_unsetg_tabs(str, words)
  tab_complete_datastore_names(framework.datastore, str, words)
end

#cmd_version(*args) ⇒ Object

Returns the revision of the framework and console library



2371
2372
2373
2374
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2371

def cmd_version(*args)
  print_line("Framework: #{Msf::Framework::Version}")
  print_line("Console  : #{Msf::Framework::Version}")
end

#commandsObject

Returns the list of commands supported by this command dispatcher



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 119

def commands
  {
    "?"          => "Help menu",
    "banner"     => "Display an awesome metasploit banner",
    "cd"         => "Change the current working directory",
    "connect"    => "Communicate with a host",
    "color"      => "Toggle color",
    "debug"      => "Display information useful for debugging",
    "exit"       => "Exit the console",
    "features"   => "Display the list of not yet released features that can be opted in to",
    "get"        => "Gets the value of a context-specific variable",
    "getg"       => "Gets the value of a global variable",
    "grep"       => "Grep the output of another command",
    "help"       => "Help menu",
    "history"    => "Show command history",
    "load"       => "Load a framework plugin",
    "quit"       => "Exit the console",
    "repeat"     => "Repeat a list of commands",
    "route"      => "Route traffic through a session",
    "save"       => "Saves the active datastores",
    "sessions"   => "Dump session listings and display information about sessions",
    "set"        => "Sets a context-specific variable to a value",
    "setg"       => "Sets a global variable to a value",
    "sleep"      => "Do nothing for the specified number of seconds",
    "tips"       => "Show a list of useful productivity tips",
    "threads"    => "View and manipulate background threads",
    "unload"     => "Unload a framework plugin",
    "unset"      => "Unsets one or more context-specific variables",
    "unsetg"     => "Unsets one or more global variables",
    "version"    => "Show the framework and console library version numbers",
    "spool"      => "Write console output into a file as well the screen"
  }
end

#deprecated_commandsObject



165
166
167
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 165

def deprecated_commands
  ['tip']
end

#list_pluginsObject



959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 959

def list_plugins
  plugin_directories = {
    'Framework' => Msf::Config.plugin_directory,
    'User'      => Msf::Config.user_plugin_directory
  }

  plugin_directories.each do |type, plugin_directory|
    items = Dir.entries(plugin_directory).keep_if { |n| n.match(/^.+\.rb$/)}
    next if items.empty?
    print_status("Available #{type} plugins:")
    items.sort.each do |item|
      print_line("    * #{item.split('.').first}")
    end
    print_line
  end
end

#load_plugin(args) ⇒ Object



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
1010
1011
1012
1013
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 976

def load_plugin(args)
  path = args[0]

  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.exist?( 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}", error: e)
    print_error("Failed to load plugin from #{path}: #{e}")
  end
end

#nameObject

Returns the name of the command dispatcher.



172
173
174
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 172

def name
  "Core"
end

#payload_show_resultsObject



1985
1986
1987
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1985

def payload_show_results
  Msf::Ui::Console::CommandDispatcher::Modules.class_variable_get(:@@payload_show_results)
end

#retrieve_grep_lines(all_lines, line_num, before = nil, after = nil) ⇒ Array<String> (protected)

Returns an array of lines at the provided line number plus any before and/or after lines requested from all_lines by supplying the before and/or after parameters which are always positive

Parameters:

  • all_lines (Array<String>)

    An array of all lines being considered for matching

  • line_num (Integer)

    The line number in all_lines which has satisifed the match

  • after (Integer) (defaults to: nil)

    The number of lines after the match line to include (should always be positive)

  • before (Integer) (defaults to: nil)

    The number of lines before the match line to include (should always be positive)

Returns:

  • (Array<String>)

    Array of lines including the line at line_num and any before and/or after



2623
2624
2625
2626
2627
2628
2629
2630
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2623

def retrieve_grep_lines(all_lines,line_num, before = nil, after = nil)
  after = after.to_i.abs
  before = before.to_i.abs
  start = line_num - before
  start = 0 if start < 0
  finish = line_num + after
  all_lines.slice(start..finish)
end

#verify_session(session_id, quiet = false) ⇒ session, ... (protected)

verifies that a given session_id is valid and that the session is interactive. The various return values allow the caller to make better decisions on what action can & should be taken depending on the capabilities of the session and the caller’s objective while making it simple to use in the nominal case where the caller needs session_id to match an interactive session

Parameters:

  • session_id (String)

    A session id, which is an integer as a string

  • quiet (Boolean) (defaults to: false)

    True means the method will produce no error messages

Returns:

  • (session)

    if the given session_id is valid and session is interactive

  • (false)

    if the given session_id is valid, but not interactive

  • (nil)

    if the given session_id is not valid at all



2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2598

def verify_session(session_id, quiet = false)
  session = framework.sessions.get(session_id)
  if session
    if session.interactive?
      session
    else
      print_error("Session #{session_id} is non-interactive.") unless quiet
      false
    end
  else
    print_error("Invalid session identifier: #{session_id}") unless quiet
    nil
  end
end