-
Notifications
You must be signed in to change notification settings - Fork 13.7k
/
core.rb
2767 lines (2422 loc) · 86.9 KB
/
core.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
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
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
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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
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
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: binary -*-
#
# Rex
#
#
# Project
#
require 'msf/core/opt_condition'
require 'optparse'
module Msf
module Ui
module Console
module CommandDispatcher
###
#
# Command dispatcher for core framework commands, such as module loading,
# session interaction, and other general things.
#
###
class Core
include Msf::Ui::Console::CommandDispatcher
include Msf::Ui::Console::CommandDispatcher::Common
include Msf::Ui::Console::ModuleOptionTabCompletion
# Session command options
@@sessions_opts = Rex::Parser::Arguments.new(
["-c", "--command"] => [ true, "Run a command on the session given with -i, or all", "<command>" ],
["-C", "--meterpreter-command"] => [ true, "Run a Meterpreter Command on the session given with -i, or all", "<command>" ],
["-h", "--help"] => [ false, "Help banner" ],
["-i", "--interact"] => [ true, "Interact with the supplied session ID", "<id>" ],
["-l", "--list"] => [ false, "List all active sessions" ],
["-v", "--list-verbose"] => [ false, "List all active sessions in verbose mode" ],
["-d", "--list-inactive"] => [ false, "List all inactive sessions" ],
["-q", "--quiet"] => [ false, "Quiet mode" ],
["-k", "--kill"] => [ true, "Terminate sessions by session ID and/or range", "<id>" ],
["-K", "--kill-all"] => [ false, "Terminate all sessions" ],
["-s", "--script"] => [ true, "Run a script or module on the session given with -i, or all", "<script>" ],
["-u", "--upgrade"] => [ true, "Upgrade a shell to a meterpreter session on many platforms", "<id>" ],
["-t", "--timeout"] => [ true, "Set a response timeout (default: 15)", "<seconds>" ],
["-S", "--search"] => [ true, "Row search filter.", "<filter>" ],
["-x", "--list-extended"] => [ false, "Show extended information in the session table" ],
["-n", "--name"] => [ true, "Name or rename a session by ID", "<id> <name>" ])
@@threads_opts = Rex::Parser::Arguments.new(
["-h", "--help"] => [ false, "Help banner." ],
["-k", "--kill"] => [ true, "Terminate the specified thread ID.", "<id>" ],
["-K", "--kill-all"] => [ false, "Terminate all non-critical threads." ],
["-i", "--info"] => [ true, "Lists detailed information about a thread.", "<id>" ],
["-l", "--list"] => [ false, "List all background threads." ],
["-v", "--verbose"] => [ false, "Print more detailed info. Use with -i and -l" ])
@@tip_opts = Rex::Parser::Arguments.new(
["-h", "--help"] => [ false, "Help banner." ])
@@debug_opts = Rex::Parser::Arguments.new(
["-h", "--help"] => [ false, "Help banner." ],
["-d", "--datastore"] => [ false, "Display the datastore information." ],
["-c", "--commands"] => [ false, "Display command history." ],
["-e", "--errors"] => [ false, "Display the most recent Error and Stack Trace." ],
["-l", "--logs"] => [ false, "Display the most recent logs." ],
["-v", "--version"] => [ false, "Display versions and install info." ],
["-s", "--database"] => [ false, "Display database statistics." ])
@@connect_opts = Rex::Parser::Arguments.new(
["-h", "--help"] => [ false, "Help banner." ],
["-p", "--proxies"] => [ true, "List of proxies to use.", "<proxies>" ],
["-C", "--crlf"] => [ false, "Try to use CRLF for EOL sequence." ],
["-c", "--comm"] => [ true, "Specify which Comm to use.", "<comm>" ],
["-i", "--send-contents"] => [ true, "Send the contents of a file.", "<file>" ],
["-P", "--source-port"] => [ true, "Specify source port.", "<port>" ],
["-S", "--source-address"] => [ true, "Specify source address.", "<address>" ],
["-s", "--ssl"] => [ false, "Connect with SSL." ],
["-u", "--udp"] => [ false, "Switch to a UDP socket." ],
["-w", "--timeout"] => [ true, "Specify connect timeout.", "<seconds>" ],
["-z", "--try-connection"] => [ false, "Just try to connect, then return." ])
@@history_opts = Rex::Parser::Arguments.new(
["-h", "--help"] => [ false, "Help banner." ],
["-a", "--all-commands"] => [ false, "Show all commands in history." ],
["-n"] => [ true, "Show the last n commands.", "<num>" ],
["-c", "--clear"] => [ false, "Clear command history and history file." ])
@@save_opts = Rex::Parser::Arguments.new(
["-h", "--help"] => [ false, "Help banner." ],
["-r", "--reload-default"] => [ false, "Reload default options for the active module." ],
["-l", "--load"] => [ false, "Load the saved options for the active module." ],
["-d", "--delete-all"] => [ false, "Delete saved options for all modules from the config file." ])
# set command options
@@setg_opts = Rex::Parser::Arguments.new(
["-h", "--help"] => [ false, "Help banner."],
["-c", "--clear"] => [ false, "Clear the values, explicitly setting to nil (default)"]
)
@@set_opts = @@setg_opts.merge(
["-g", "--global"] => [ false, "Operate on global datastore variables"]
)
# unset command options
@@unsetg_opts = Rex::Parser::Arguments.new(
["-h", "--help"] => [ false, "Help banner."],
)
@@unset_opts = @@unsetg_opts.merge(
["-g", "--global"] => [ false, "Operate on global datastore variables"]
)
VALID_SESSION_SEARCH_PARAMS =
%w[
last_checkin
session_id
session_type
]
private_constant :VALID_SESSION_SEARCH_PARAMS
# Returns the list of commands supported by this command dispatcher
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
#
# Initializes the datastore cache
#
def initialize(driver)
super
@cache_payloads = nil
@previous_module = nil
@previous_target = nil
@history_limit = 100
end
def deprecated_commands
['tip']
end
#
# Returns the name of the command dispatcher.
#
def name
"Core"
end
def cmd_color_help
print_line "Usage: color <'true'|'false'|'auto'>"
print_line
print_line "Enable or disable color output."
print_line
end
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
#
# Tab completion for the color command
#
# @param str [String] the string currently being typed before tab was hit
# @param 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
#
def cmd_color_tabs(str, words)
return [] if words.length > 1
%w[auto true false]
end
def cmd_cd_help
print_line "Usage: cd <directory>"
print_line
print_line "Change the current working directory"
print_line
end
#
# Change the current working directory
#
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
def cmd_cd_tabs(str, words)
tab_complete_directory(str, words)
end
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
#
# Display one of the fabulous banners.
#
def cmd_banner(*args)
banner = "%cya" + Banner.to_s + "%clr\n\n"
stats = framework.stats
version = "%yelmetasploit v#{Metasploit::Framework::VERSION}%clr",
exp_aux_pos = "#{stats.num_exploits} exploits - #{stats.num_auxiliary} auxiliary - #{stats.num_post} post",
pay_enc_nop = "#{stats.num_payloads} payloads - #{stats.num_encoders} encoders - #{stats.num_nops} nops",
eva = "#{stats.num_evasion} evasion",
padding = 48
banner << (" =[ %-#{padding+8}s]\n" % version)
banner << ("+ -- --=[ %-#{padding}s]\n" % exp_aux_pos)
banner << ("+ -- --=[ %-#{padding}s]\n" % pay_enc_nop)
banner << ("+ -- --=[ %-#{padding}s]\n" % eva)
banner << "\n"
banner << Rex::Text.wordwrap("Metasploit tip: #{Tip.sample}\n", indent = 0, cols = 60)
banner << Rex::Text.wordwrap('Metasploit Documentation: https://docs.metasploit.com/', indent = 0, cols = 60)
# Display the banner
print_line(banner)
end
#
# Tab completion for the tips command
#
# @param str [String] the string currently being typed before tab was hit
# @param 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
def cmd_tips_tabs(str, words)
if words.length == 1
return @@tip_opts.option_keys.select { |opt| opt.start_with?(str) }
end
[]
end
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
alias cmd_tip_help cmd_tips_help
#
# Display useful productivity tips to the user.
#
def cmd_tips(*args)
if args.include?("-h") || args.include?("--help")
cmd_tip_help
else
tbl = Table.new(
Table::Style::Default,
'Columns' => %w[Id Tip]
)
Tip.all.each_with_index do |tip, index|
tbl << [ index, tip ]
end
print(tbl.to_s)
end
end
alias cmd_tip cmd_tips
#
# Tab completion for the debug command
#
# @param str [String] the string currently being typed before tab was hit
# @param 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
def cmd_debug_tabs(str, words)
if words.length >= 1
return @@debug_opts.option_keys.select do |opt|
opt.start_with?(str) && !words.include?(opt)
end
end
[]
end
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
#
# Display information useful for debugging errors.
#
def cmd_debug(*args)
if args.empty?
print_line Debug.all(framework, driver)
return
end
if args.include?("-h") || args.include?("--help")
cmd_debug_help
else
output = ""
@@debug_opts.parse(args) do |opt|
case opt
when '-d'
output << Debug.datastore(framework, driver)
when '-c'
output << Debug.history(driver)
when '-e'
output << Debug.errors
when '-l'
output << Debug.logs
when '-v'
output << Debug.versions(framework)
when '-s'
output << Debug.database_configuration(framework)
end
end
if output.empty?
print_line("Valid argument was not given.")
cmd_debug_help
else
output = Debug.preamble + output
print_line output
end
end
end
#
# Tab completion for the connect command
#
# @param str [String] the string currently being typed before tab was hit
# @param 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
def cmd_connect_tabs(str, words)
if words.length == 1
return @@connect_opts.option_keys.select do |opt|
opt.start_with?(str) && !words.include?(opt)
end
end
case words[-1]
when '-c', '--comm'
# Rex::Socket::Comm
end
[]
end
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
#
# Talk to a host
#
def cmd_connect(*args)
if args.length < 2 or args.include?("-h") or args.include?("--help")
cmd_connect_help
return false
end
crlf = false
commval = nil
fileval = nil
proxies = nil
srcaddr = nil
srcport = nil
ssl = false
udp = false
cto = nil
justconn = false
aidx = 0
@@connect_opts.parse(args) do |opt, idx, val|
case opt
when "-C"
crlf = true
aidx = idx + 1
when "-c"
commval = val
aidx = idx + 2
when "-i"
fileval = val
aidx = idx + 2
when "-P"
srcport = val
aidx = idx + 2
when "-p"
proxies = val
aidx = idx + 2
when "-S"
srcaddr = val
aidx = idx + 2
when "-s"
ssl = true
aidx = idx + 1
when "-w"
cto = val.to_i
aidx = idx + 2
when "-u"
udp = true
aidx = idx + 1
when "-z"
justconn = true
aidx = idx + 1
end
end
commval = "Local" if commval =~ /local/i
if fileval
begin
raise "Not a file" if File.ftype(fileval) != "file"
infile = ::File.open(fileval)
rescue
print_error("Can't read from '#{fileval}': #{$!}")
return false
end
end
args = args[aidx .. -1]
if args.length < 2
print_error("You must specify a host and port")
return false
end
host = args[0]
port = args[1]
comm = nil
if commval
begin
if Rex::Socket::Comm.const_defined?(commval)
comm = Rex::Socket::Comm.const_get(commval)
end
rescue NameError
end
if not comm
session = framework.sessions.get(commval)
if session.kind_of?(Msf::Session::Comm)
comm = session
end
end
if not comm
print_error("Invalid comm '#{commval}' selected")
return false
end
end
begin
klass = udp ? ::Rex::Socket::Udp : ::Rex::Socket::Tcp
sock = klass.create({
'Comm' => comm,
'Proxies' => proxies,
'SSL' => ssl,
'PeerHost' => host,
'PeerPort' => port,
'LocalHost' => srcaddr,
'LocalPort' => srcport,
'Timeout' => cto,
'Context' => {
'Msf' => framework
}
})
rescue
print_error("Unable to connect: #{$!}")
return false
end
_, lhost, lport = sock.getlocalname()
print_status("Connected to #{host}:#{port} (via: #{lhost}:#{lport})")
if justconn
sock.close
infile.close if infile
return true
end
cin = infile || driver.input
cout = driver.output
begin
# Console -> Network
c2n = framework.threads.spawn("ConnectConsole2Network", false, cin, sock) do |input, output|
while true
begin
res = input.gets
break if not res
if crlf and (res =~ /^\n$/ or res =~ /[^\r]\n$/)
res.gsub!(/\n$/, "\r\n")
end
output.write res
rescue ::EOFError, ::IOError
break
end
end
end
# Network -> Console
n2c = framework.threads.spawn("ConnectNetwork2Console", false, sock, cout, c2n) do |input, output, cthr|
while true
begin
res = input.read(65535)
break if not res
output.print res
rescue ::EOFError, ::IOError
break
end
end
Thread.kill(cthr)
end
c2n.join
rescue ::Interrupt
c2n.kill
n2c.kill
end
c2n.join
n2c.join
sock.close rescue nil
infile.close if infile
true
end
#
# Instructs the driver to stop executing.
#
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
alias cmd_quit cmd_exit
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
#
# This method handles the features command which allows a user to opt into enabling
# features that are not yet released to everyone by default.
#
def cmd_features(*args)
args << 'print' if args.empty?
action, *rest = args
case action
when 'set'
feature_name, value = rest
unless framework.features.exists?(feature_name)
print_warning("Feature name '#{feature_name}' is not available. Either it has been removed, integrated by default, or does not exist in this version of Metasploit.")
print_warning("Currently supported features: #{framework.features.names.join(', ')}") if framework.features.all.any?
print_warning('There are currently no features to toggle.') if framework.features.all.empty?
return
end
unless %w[true false].include?(value)
print_warning('Please specify true or false to configure this feature.')
return
end
framework.features.set(feature_name, value == 'true')
print_line("#{feature_name} => #{value}")
# Some flags may require a full console restart
if framework.features.requires_restart?(feature_name)
print_warning("Run the #{Msf::Ui::Tip.highlight("save")} command and restart the console for this feature to take effect.")
else
# Reload the current module, as feature flags may impact the available module options etc
driver.run_single("reload") if driver.active_module
end
when 'print'
if framework.features.all.empty?
print_line 'There are no features to enable at this time. Either the features have been removed, or integrated by default.'
return
end
features_table = Table.new(
Table::Style::Default,
'Header' => 'Features table',
'Prefix' => "\n",
'Postfix' => "\n",
'Columns' => [
'#',
'Name',
'Enabled',
'Description',
]
)
framework.features.all.each.with_index do |feature, index|
features_table << [
index,
feature[:name],
feature[:enabled].to_s,
feature[:description]
]
end
print_line features_table.to_s
else
cmd_features_help
end
rescue StandardError => e
elog(e)
print_error(e.message)
end
#
# Tab completion for the features command
#
# @param _str [String] The string currently being typed before tab was hit
# @param 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
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
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
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
def cmd_history_tabs(str, words)
return [] if words.length > 1
@@history_opts.option_keys
end
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
#
# Causes process to pause for the specified number of seconds
#
def cmd_sleep(*args)
return if not (args and args.length == 1)
Rex::ThreadSafe.sleep(args[0].to_f)
end
def cmd_threads_help
print_line "Usage: threads [options]"
print_line
print_line "Background thread management."
print_line @@threads_opts.usage()
end
#
# Displays and manages running background threads
#
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
#
# Tab completion for the threads command
#
# @param str [String] the string currently being typed before tab was hit
# @param 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
def cmd_threads_tabs(str, words)
if words.length == 1
return @@threads_opts.option_keys
end
if words.length == 2 && @@threads_opts.include?(words[1]) && @@threads_opts.arg_required?(words[1])
return framework.threads.each_index.map{ |idx| idx.to_s }
end
[]
end
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
def list_plugins
plugin_directories = {
'Framework' => Msf::Config.plugin_directory,
'User' => Msf::Config.user_plugin_directory
}
plugin_directories.each do |type, plugin_directory|
items = Dir.entries(plugin_directory).keep_if { |n| n.match(/^.+\.rb$/)}
next if items.empty?
print_status("Available #{type} plugins:")
items.sort.each do |item|
print_line(" * #{item.split('.').first}")
end
print_line
end
end
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)
}