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

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

Overview

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

Constant Summary collapse

@@sessions_opts =

Session command options

Rex::Parser::Arguments.new(
"-c"  => [ 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 ModuleOptionTabCompletion

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

Methods included from Common

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

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

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

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

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

Constructor Details

#initialize(driver) ⇒ Core

Initializes the datastore cache


134
135
136
137
138
139
140
141
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 134

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.


225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 225

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

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

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

  banner << "\n"
  banner << Msf::Serializer::ReadableText.word_wrap("Metasploit tip: #{Tip.sample}\n", indent = 0, cols = 60)

  # Display the banner
  print_line(banner)

end

#cmd_banner_helpObject


215
216
217
218
219
220
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 215

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


198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 198

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


188
189
190
191
192
193
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 188

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


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

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

#cmd_color(*args) ⇒ Object


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

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


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

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


183
184
185
186
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 183

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

#cmd_connect(*args) ⇒ Object

Talk to a host


338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 338

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


327
328
329
330
331
332
333
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 327

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.


292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 292

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


280
281
282
283
284
285
286
287
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 280

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.


520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 520

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.


570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 570

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


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

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


637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 637

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.


1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1918

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


1908
1909
1910
1911
1912
1913
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1908

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


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

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.


1966
1967
1968
1969
1970
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1966

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

  cmd_get(*args)
end

#cmd_getg_helpObject


1956
1957
1958
1959
1960
1961
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1956

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


1979
1980
1981
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1979

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


2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2094

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


2082
2083
2084
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2082

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


2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2204

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


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

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


711
712
713
714
715
716
717
718
719
720
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 711

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

#cmd_history_tabs(str, words) ⇒ Object


722
723
724
725
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 722

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.


941
942
943
944
945
946
947
948
949
950
951
952
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 941

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


871
872
873
874
875
876
877
878
879
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 871

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


961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 961

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


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

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


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

def cmd_repeat_help
  cmd_repeat '-h'
end

#cmd_repeat_tabs(str, words) ⇒ Object

Almost the exact same as grep


2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2279

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.


1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1021

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


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

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


1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1170

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.


1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1219

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


1206
1207
1208
1209
1210
1211
1212
1213
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1206

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.


1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1292

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
              data = session.sys.process.capture_output(c, c_args,
              {
                'Channelized' => true,
                'Subshell'    => true,
                'Hidden'      => true
              }, response_timeout)
              print_line(data) unless data.blank?
            rescue ::Rex::Post::Meterpreter::RequestError
              print_error("Failed: #{$!.class} #{$!}")
            rescue Rex::TimeoutError
              print_error("Operation timed out")
            end
          elsif session.type == 'shell' || session.type == 'powershell'
            output = session.shell_command(cmd)
            print_line(output) if output
          end
        ensure
          # Restore timeout for each session
          if session.respond_to?(:response_timeout) && last_known_timeout
            session.response_timeout = last_known_timeout
          end
        end
        # If the session isn't a meterpreter or shell type, it
        # could be a VNC session (which can't run commands) or
        # something custom (which we don't know how to run
        # commands on), so don't bother.
      end
    end
    when 'meterp-cmd'
      if cmds.length < 1
        print_error("No command specified!")
        return false
      end

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

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

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

          output = session.run_cmd(cmd, driver.output)
        end
      end
  when 'kill'
    print_status("Killing the following session(s): #{session_list.join(', ')}")
    session_list.each do |sess_id|
      session = framework.sessions.get(sess_id)
      if session
        if session.respond_to?(:response_timeout)
          last_known_timeout = session.response_timeout
          session.response_timeout = response_timeout
        end
        print_status("Killing session #{sess_id}")
        begin
          session.kill
        ensure
          if session.respond_to?(:response_timeout) && last_known_timeout
            session.response_timeout = last_known_timeout
          end
        end
      else
        print_error("Invalid session identifier: #{sess_id}")
      end
    end
  when 'killall'
    print_status("Killing all sessions...")
    framework.sessions.each_sorted 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


1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1278

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


1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1666

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.


1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1702

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 Msf::OptionValidateError => e
    print_error(e.message)
    elog('Exception encountered in cmd_set', error: e)
  end

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

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

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

#cmd_set_helpObject


1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1686

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


1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1815

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_values(active_module, str, words, opt: words[1])
  end
  tab_complete_option_names(active_module, str, words)
end

#cmd_setg(*args) ⇒ Object

Sets the supplied variables in the global datastore.


1847
1848
1849
1850
1851
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1847

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

  cmd_set(*args)
end

#cmd_setg_helpObject


1826
1827
1828
1829
1830
1831
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1826

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


1860
1861
1862
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1860

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


737
738
739
740
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 737

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

#cmd_sleep_helpObject


727
728
729
730
731
732
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 727

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


1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1256

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


1244
1245
1246
1247
1248
1249
1250
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1244

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


1252
1253
1254
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1252

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

#cmd_threads(*args) ⇒ Object

Displays and manages running background threads


752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
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
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 752

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


742
743
744
745
746
747
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 742

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


859
860
861
862
863
864
865
866
867
868
869
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 859

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.


260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 260

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


248
249
250
251
252
253
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 248

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.


1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1876

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


1865
1866
1867
1868
1869
1870
1871
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1865

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


1900
1901
1902
1903
1904
1905
1906
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1900

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.


1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1995

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


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

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.


1840
1841
1842
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1840

def cmd_unset_tabs(str, words)
  tab_complete_datastore_names(active_module, str, words)
end

#cmd_unsetg(*args) ⇒ Object

Unsets variables in the global data store.


2055
2056
2057
2058
2059
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2055

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


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

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

#cmd_version(*args) ⇒ Object

Returns the revision of the framework and console library


2077
2078
2079
2080
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2077

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


97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 97

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


143
144
145
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 143

def deprecated_commands
  ['tip']
end

#list_pluginsObject


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

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


898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 898

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.


150
151
152
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 150

def name
  "Core"
end

#payload_show_resultsObject


1805
1806
1807
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 1805

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


2329
2330
2331
2332
2333
2334
2335
2336
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2329

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

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

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

Parameters:

  • session_id (String)

    A session id, which is an integer as a string

  • quiet (Boolean) (defaults to: false)

    True means the method will produce no error messages

Returns:

  • (session)

    if the given session_id is valid and session is interactive

  • (false)

    if the given session_id is valid, but not interactive

  • (nil)

    if the given session_id is not valid at all


2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
# File 'lib/msf/ui/console/command_dispatcher/core.rb', line 2304

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