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

Inherits:
Object
  • Object
show all
Includes:
Msf::Ui::Console::CommandDispatcher, Common
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"  => [ true,  "Run a command on the session given with -i, or all"             ],
"-C"  => [ true,  "Run a Meterpreter Command on the session given with -i, or all" ],
"-h"  => [ false, "Help banner"                                                    ],
"-i"  => [ true,  "Interact with the supplied session ID"                          ],
"-l"  => [ false, "List all active sessions"                                       ],
"-v"  => [ false, "List all active sessions in verbose mode"                       ],
"-d" =>  [ false, "List all inactive sessions"                                     ],
"-q"  => [ false, "Quiet mode"                                                     ],
"-k"  => [ true,  "Terminate sessions by session ID and/or range"                  ],
"-K"  => [ false, "Terminate all sessions"                                         ],
"-s"  => [ true,  "Run a script or module on the session given with -i, or all"    ],
"-u"  => [ true,  "Upgrade a shell to a meterpreter session on many platforms"     ],
"-t"  => [ true,  "Set a response timeout (default: 15)"                           ],
"-S"  => [ true,  "Row search filter."                                             ],
"-x" =>  [ false, "Show extended information in the session table"                 ],
"-n" =>  [ true,  "Name or rename a session by ID"                                 ])
@@threads_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ],
"-k" => [ true,  "Terminate the specified thread ID."             ],
"-K" => [ false, "Terminate all non-critical threads."            ],
"-i" => [ true,  "Lists detailed information about a thread."     ],
"-l" => [ false, "List all background threads."                   ],
"-v" => [ false, "Print more detailed info.  Use with -i and -l"  ])
@@tip_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ])
@@debug_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ],
"-d" => [ false, "Display the Datastore Information."             ],
"-c" => [ false, "Display command history."                       ],
"-e" => [ false, "Display the most recent Error and Stack Trace." ],
"-l" => [ false, "Display the most recent logs."                  ],
"-v" => [ false, "Display versions and install info."             ])
@@connect_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ],
"-p" => [ true,  "List of proxies to use."                        ],
"-C" => [ false, "Try to use CRLF for EOL sequence."              ],
"-c" => [ true,  "Specify which Comm to use."                     ],
"-i" => [ true,  "Send the contents of a file."                   ],
"-P" => [ true,  "Specify source port."                           ],
"-S" => [ true,  "Specify source address."                        ],
"-s" => [ false, "Connect with SSL."                              ],
"-u" => [ false, "Switch to a UDP socket."                        ],
"-w" => [ true,  "Specify connect timeout."                       ],
"-z" => [ false, "Just try to connect, then return."              ])
@@search_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ],
"-S" => [ true, "Row search filter."                              ])
@@history_opts =
Rex::Parser::Arguments.new(
"-h" => [ false, "Help banner."                                   ],
"-a" => [ false, "Show all commands in history."                  ],
"-n" => [ true,  "Show the last n commands."                      ],
"-c" => [ false, "Clear command history and history file."        ])

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 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, #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, #print, #print_error, #print_good, #print_line, #print_status, #print_warning, #tab_complete_directory, #tab_complete_filenames, #tab_complete_generic, #tab_complete_source_address, #update_prompt

Constructor Details

#initialize(driver) ⇒ Core

Initializes the datastore cache


144
145
146
147
148
149
150
151
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 144

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.


235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 235

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

  avdwarn = nil

  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 << "Metasploit tip: #{Tip.sample}\n"

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

  # Display the banner
  print_line(banner)

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

end

#cmd_banner_helpObject


225
226
227
228
229
230
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 225

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


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

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


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

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


221
222
223
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 221

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

#cmd_color(*args) ⇒ Object


172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 172

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


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

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


193
194
195
196
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 193

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

#cmd_connect(*args) ⇒ Object

Talk to a host


363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 363

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

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

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

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

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

  args = args[aidx .. -1]

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

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

  comm = nil

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

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

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

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

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

  _, 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


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

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

Display information useful for debugging errors.


317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 317

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

  if args.include?("-h")
    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)
      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


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

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_exit(*args) ⇒ Object Also known as: cmd_quit

Instructs the driver to stop executing.


545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 545

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.


595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 595

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}")
    # Reload the current module, as feature flags may impact the available module options etc
    driver.run_single("reload") if driver.active_module
  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


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 567

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


662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 662

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.


2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2002

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


1992
1993
1994
1995
1996
1997
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1992

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


2035
2036
2037
2038
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2035

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.


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

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

  cmd_get(*args)
end

#cmd_getg_helpObject


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

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


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

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


2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
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
2256
2257
2258
2259
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2190

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


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

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


2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2300

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


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
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 683

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


736
737
738
739
740
741
742
743
744
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 736

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 @@history_opts.usage
end

#cmd_history_tabs(str, words) ⇒ Object


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

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


965
966
967
968
969
970
971
972
973
974
975
976
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 965

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


895
896
897
898
899
900
901
902
903
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 895

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


985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 985

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


2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2318

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


2311
2312
2313
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2311

def cmd_repeat_help
  cmd_repeat '-h'
end

#cmd_repeat_tabs(str, words) ⇒ Object

Almost the exact same as grep


2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2375

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.


1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1045

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)
        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'  => { 'MaxWidth' => 17 },
            'Netmask' => { 'MaxWidth' => 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'  => { 'MaxWidth' => 17 },
            'Netmask' => { 'MaxWidth' => 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


1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1010

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


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

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

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

  ret
end

#cmd_save(*args) ⇒ Object

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


1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1243

def cmd_save(*args)
  # 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

#cmd_save_helpObject


1230
1231
1232
1233
1234
1235
1236
1237
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1230

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

#cmd_sessions(*args) ⇒ Object

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


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
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1316

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

  # 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|
      case opt
      when "-q"
        quiet = true
      # Run a command on all sessions, or the session given with -i
      when "-c"
        method = 'cmd'
        cmds << val if val
      when "-C"
          method = 'meterp-cmd'
          cmds << val if val
      # Display the list of inactive sessions
      when "-d"
        show_inactive = true
        method = 'list_inactive'
      when "-x"
        show_extended = true
      when "-v"
        verbose = true
      # Do something with the supplied session identifier instead of
      # all sessions.
      when "-i"
        sid = val
      # Display the list of active sessions
      when "-l"
        show_active = true
        method = 'list'
      when "-k"
        method = 'kill'
        sid = val || false
      when "-K"
        method = 'killall'
      # Run a script or module on specified sessions
      when "-s"
        unless script
          method = 'script'
          script = val
        end
      # Upload and exec to the specific command session
      when "-u"
        method = 'upexec'
        sid = val || false
      # Search for specific session
      when "-S", "--search"
        search_term = val
      # Display help banner
      when "-h"
        cmd_sessions_help
        return false
      when "-t"
        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
              process = session.sys.process.execute(c, c_args,
                {
                  'Channelized' => true,
                  'Hidden'      => true
                })
              if process && process.channel
                data = process.channel.read
                print_line(data) if data
              end
            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 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


1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1302

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


1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1692

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

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

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

  when "-s"
    # XXX: Complete scripts

  end

  []
end

#cmd_set(*args) ⇒ Object

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


1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1728

def cmd_set(*args)

  # Figure out if these are global variables
  global = false

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

  # Decide if this is an append operation
  append = false

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

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

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

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

  # Set the supplied name to the supplied value
  name  = args[0]
  value = args[1, args.length-1].join(' ')

  # Set PAYLOAD
  if name.upcase == 'PAYLOAD' && active_module && (active_module.exploit? || active_module.evasion?)
    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

  # 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 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

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

#cmd_set_helpObject


1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1712

def cmd_set_help
  print_line "Usage: set [option] [value]"
  print_line
  print_line "Set the given option to value.  If value is omitted, print the current value."
  print_line "If both are omitted, print options that are currently set."
  print_line
  print_line "If run from a module context, this will set the value in the module's"
  print_line "datastore.  Use -g to operate on the global datastore."
  print_line
  print_line "If setting a PAYLOAD, this command can take an index from `show payloads'."
  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


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

def cmd_set_tabs(str, words)

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

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

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

  if (not mod)
    return res
  end

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

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

  if mod.kind_of?(Msf::Module::HasActions)
    res << "ACTION"
  end

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

  unless str.blank?
    res = res.select { |term| term.upcase.start_with?(str.upcase) }
    res = res.map { |term|
      if str == str.upcase
        str + term[str.length..-1].upcase
      elsif str == str.downcase
        str + term[str.length..-1].downcase
      else
        str + term[str.length..-1]
      end
    }
  end

  return res
end

#cmd_setg(*args) ⇒ Object

Sets the supplied variables in the global datastore.


1931
1932
1933
1934
1935
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1931

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

  cmd_set(*args)
end

#cmd_setg_helpObject


1921
1922
1923
1924
1925
1926
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1921

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

#cmd_setg_tabs(str, words) ⇒ Object

Tab completion for the setg command

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

Parameters:

  • str (String)

    the string currently being typed before tab was hit

  • words (Array<String>)

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


1944
1945
1946
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1944

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


761
762
763
764
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 761

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

#cmd_sleep_helpObject


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

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


1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1280

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


1268
1269
1270
1271
1272
1273
1274
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1268

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


1276
1277
1278
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1276

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

#cmd_threads(*args) ⇒ Object

Displays and manages running background threads


776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 776

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


766
767
768
769
770
771
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 766

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


883
884
885
886
887
888
889
890
891
892
893
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 883

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

  if words.length == 2 and (@@threads_opts.fmt[words[1]] || [false])[0]
    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.


285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 285

def cmd_tips(*args)
  if args.include?("-h")
    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


273
274
275
276
277
278
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 273

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

Unloads a plugin by its name.


1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1960

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


1949
1950
1951
1952
1953
1954
1955
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1949

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


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

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.


2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2079

def cmd_unset(*args)

  # Figure out if these are global variables
  global = false

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

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

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

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

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

    return true
  end

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

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

    datastore.delete(val)
  end
end

#cmd_unset_helpObject Also known as: cmd_unsetg_help


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

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

#cmd_unset_tabs(str, words) ⇒ Object

Tab completion for the unset command

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.


2136
2137
2138
2139
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2136

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

#cmd_unsetg(*args) ⇒ Object

Unsets variables in the global data store.


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

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


2164
2165
2166
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2164

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

#cmd_version(*args) ⇒ Object

Returns the revision of the framework and console library


2173
2174
2175
2176
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2173

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


107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 107

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


153
154
155
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 153

def deprecated_commands
  ['tip']
end

#list_pluginsObject


905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 905

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.each do |item|
      print_line("    * #{item.split('.').first}")
    end
    print_line
  end
end

#load_plugin(args) ⇒ Object


922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 922

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.


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

def name
  "Core"
end

#option_values_actionsObject

Provide valid action options for the current module


2568
2569
2570
2571
2572
2573
2574
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2568

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

#option_values_dispatch(o, str, words) ⇒ Object

Provide possible option values based on type


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
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2451

def option_values_dispatch(o, str, words)

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

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

  when Msf::OptAddressRange
    case str
    when /^file:(.*)/
      files = tab_complete_filenames($1, words)
      res += files.map { |f| "file:" + f } if files
    when /\/$/
      res << str+'32'
      res << str+'24'
      res << str+'16'
    when /\-$/
      res << str+str[0, str.length - 1]
    else
      option_values_target_addrs().each do |addr|
        res << addr
      end
    end

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

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

  when Msf::OptEnum
    o.enums.each do |val|
      res << val
    end

  when Msf::OptPath
    files = tab_complete_filenames(str, words)
    res += files if files

  when Msf::OptBool
    res << 'true'
    res << 'false'

  when Msf::OptString
    if (str =~ /^file:(.*)/)
      files = tab_complete_filenames($1, words)
      res += files.map { |f| "file:" + f } if files
    end
  end

  return res
end

#option_values_encodersObject

Provide valid encoders options for the current exploit or payload


2586
2587
2588
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2586

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

#option_values_nopsObject

Provide valid nops options for the current exploit


2579
2580
2581
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2579

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

#option_values_payloadsObject

Provide valid payload options for the current exploit


2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2528

def option_values_payloads
  if @cache_payloads && active_module == @previous_module && active_module.target == @previous_target
    return @cache_payloads
  end

  @previous_module = active_module
  @previous_target = active_module.target

  @cache_payloads = active_module.compatible_payloads.map do |refname, payload|
    refname
  end

  @cache_payloads
end

#option_values_sessionsObject

Provide valid session options for the current post-exploit module


2546
2547
2548
2549
2550
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2546

def option_values_sessions
  if active_module.respond_to?(:compatible_sessions)
    active_module.compatible_sessions.map { |sid| sid.to_s }
  end
end

#option_values_target_addrsObject

Provide the target addresses


2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2593

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

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

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

  # List all hosts in the database
  else
    framework.db.hosts.each do |host|
      res << host.address
    end
  end

  return res
end

#option_values_target_portsObject

Provide the target ports


2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2626

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

  framework.db.services.each do |service|
    if service.host_id == host.id
      res << service.port.to_s
    end
  end

  return res
end

#option_values_targetsObject

Provide valid target options for the current exploit


2555
2556
2557
2558
2559
2560
2561
2562
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2555

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

#payload_show_resultsObject


1831
1832
1833
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1831

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


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

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

#tab_complete_option(str, words) ⇒ Object

Provide tab completion for option values


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

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

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

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

  # Well-known option names specific to modules with actions
  if mod.kind_of?(Msf::Module::HasActions)
    return option_values_actions() if opt.upcase == 'ACTION'
  end

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

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

  # Is this option used by the active module?
  mod.options.each_key do |key|
    res.concat(option_values_dispatch(mod.options[key], str, words)) if key.downcase == opt.downcase
  end

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

  return res
end

#tab_complete_source_interface(o) ⇒ Object

XXX: We repurpose OptAddressLocal#interfaces, so we can't put this in Rex


2443
2444
2445
2446
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2443

def tab_complete_source_interface(o)
  return [] unless o.is_a?(Msf::OptAddressLocal)
  o.interfaces
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


2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2656

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