CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

CoCalc provides the best real-time collaborative environment for Jupyter Notebooks, LaTeX documents, and SageMath, scalable from individual users to large groups and classes!

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/msf/ui/console/command_dispatcher/modules.rb
Views: 1904
1
# -*- coding: binary -*-
2
3
4
module Msf
5
module Ui
6
module Console
7
module CommandDispatcher
8
9
#
10
# {CommandDispatcher} for commands related to background jobs in Metasploit Framework.
11
#
12
class Modules
13
14
include Msf::Ui::Console::CommandDispatcher
15
include Msf::Ui::Console::CommandDispatcher::Common
16
17
include Rex::Text::Color
18
19
@@search_opts = Rex::Parser::Arguments.new(
20
['-h', '--help'] => [false, 'Help banner'],
21
['-I', '--ignore'] => [false, 'Ignore the command if the only match has the same name as the search'],
22
['-o', '--output'] => [true, 'Send output to a file in csv format', '<filename>'],
23
['-S', '--filter'] => [true, 'Regex pattern used to filter search results', '<filter>'],
24
['-u', '--use'] => [false, 'Use module if there is one result'],
25
['-s', '--sort-ascending'] => [true, 'Sort search results by the specified column in ascending order', '<column>'],
26
['-r', '--sort-descending'] => [true, 'Reverse the order of search results to descending order', '<column>']
27
)
28
29
@@favorite_opts = Rex::Parser::Arguments.new(
30
'-h' => [false, 'Help banner'],
31
'-c' => [false, 'Clear the contents of the favorite modules file'],
32
'-d' => [false, 'Delete module(s) or the current active module from the favorite modules file'],
33
'-l' => [false, 'Print the list of favorite modules (alias for `show favorites`)']
34
)
35
36
@@favorites_opts = Rex::Parser::Arguments.new(
37
'-h' => [false, 'Help banner']
38
)
39
40
def commands
41
{
42
"back" => "Move back from the current context",
43
"advanced" => "Displays advanced options for one or more modules",
44
"info" => "Displays information about one or more modules",
45
"options" => "Displays global options or for one or more modules",
46
"loadpath" => "Searches for and loads modules from a path",
47
"popm" => "Pops the latest module off the stack and makes it active",
48
"pushm" => "Pushes the active or list of modules onto the module stack",
49
"listm" => "List the module stack",
50
"clearm" => "Clear the module stack",
51
"previous" => "Sets the previously loaded module as the current module",
52
"reload_all" => "Reloads all modules from all defined module paths",
53
"search" => "Searches module names and descriptions",
54
"show" => "Displays modules of a given type, or all modules",
55
"use" => "Interact with a module by name or search term/index",
56
"favorite" => "Add module(s) to the list of favorite modules",
57
"favorites" => "Print the list of favorite modules (alias for `show favorites`)"
58
}
59
end
60
61
#
62
# Initializes the datastore cache
63
#
64
def initialize(driver)
65
super
66
67
@dscache = {}
68
@previous_module = nil
69
@module_name_stack = []
70
# Array of individual modules that have been searched for
71
@module_search_results = []
72
# Module search results, with additional metadata on what to do if the module is interacted with
73
@module_search_results_with_usage_metadata = []
74
@@payload_show_results = []
75
@dangerzone_map = nil
76
end
77
78
#
79
# Returns the name of the command dispatcher.
80
#
81
def name
82
"Module"
83
end
84
85
def cmd_advanced_help
86
print_line 'Usage: advanced [mod1 mod2 ...]'
87
print_line
88
print_line 'Queries the supplied module or modules for advanced options. If no module is given,'
89
print_line 'show advanced options for the currently active module.'
90
print_line
91
end
92
93
def cmd_advanced(*args)
94
if args.empty?
95
if (active_module)
96
show_advanced_options(active_module)
97
return true
98
else
99
print_error('No module active')
100
return false
101
end
102
end
103
104
args.each { |name|
105
mod = framework.modules.create(name)
106
107
if (mod == nil)
108
print_error("Invalid module: #{name}")
109
else
110
show_advanced_options(mod)
111
end
112
}
113
end
114
115
def cmd_info_help
116
print_line "Usage: info <module name> [mod2 mod3 ...]"
117
print_line
118
print_line "Options:"
119
print_line "* The flag '-j' will print the data in json format"
120
print_line "* The flag '-d' will show the markdown version with a browser. More info, but could be slow."
121
print_line "Queries the supplied module or modules for information. If no module is given,"
122
print_line "show info for the currently active module."
123
print_line
124
end
125
126
def print_module_info(mod, dump_json: false, show_doc: false)
127
if dump_json
128
print(Serializer::Json.dump_module(mod) + "\n")
129
elsif show_doc
130
f = Tempfile.new(["#{mod.shortname}_doc", '.html'])
131
begin
132
print_status("Generating documentation for #{mod.shortname}, then opening #{f.path} in a browser...")
133
Msf::Util::DocumentGenerator.spawn_module_document(mod, f)
134
ensure
135
f.close if f
136
end
137
else
138
print(Serializer::ReadableText.dump_module(mod))
139
print("\nView the full module info with the #{Msf::Ui::Tip.highlight('info -d')} command.\n\n")
140
end
141
end
142
143
# Handles the index selection formatting
144
def print_module_search_results_usage
145
last_mod_with_usage_metadata = @module_search_results_with_usage_metadata.last
146
index_usage = "use #{@module_search_results_with_usage_metadata.length - 1}"
147
index_info = "info #{@module_search_results_with_usage_metadata.length - 1}"
148
name_usage = "use #{last_mod_with_usage_metadata[:mod].fullname}"
149
150
additional_usage_message = ""
151
additional_usage_example = (last_mod_with_usage_metadata[:datastore] || {}).first
152
if framework.features.enabled?(Msf::FeatureManager::HIERARCHICAL_SEARCH_TABLE) && additional_usage_example
153
key, value = additional_usage_example
154
additional_usage_message = "\nAfter interacting with a module you can manually set a #{key} with %grnset #{key} '#{value}'%clr"
155
end
156
print("Interact with a module by name or index. For example %grn#{index_info}%clr, %grn#{index_usage}%clr or %grn#{name_usage}%clr#{additional_usage_message}\n\n")
157
end
158
159
#
160
# Displays information about one or more module.
161
#
162
def cmd_info(*args)
163
dump_json = false
164
show_doc = false
165
166
if args.include?('-j')
167
args.delete('-j')
168
dump_json = true
169
end
170
171
if args.include?('-d')
172
args.delete('-d')
173
show_doc = true
174
end
175
176
if (args.length == 0)
177
if active_module
178
print_module_info(active_module, dump_json: dump_json, show_doc: show_doc)
179
return true
180
else
181
cmd_info_help
182
return false
183
end
184
elsif args.include? '-h'
185
cmd_info_help
186
return false
187
end
188
189
args.each do |arg|
190
mod_name = arg
191
192
additional_datastore_values = nil
193
194
# Use a module by search index
195
index_from_list(@module_search_results_with_usage_metadata, mod_name) do |result|
196
mod = result&.[](:mod)
197
next unless mod && mod.respond_to?(:fullname)
198
199
# Module cache object
200
mod_name = mod.fullname
201
additional_datastore_values = result[:datastore]
202
end
203
204
# Ensure we have a reference name and not a path
205
name = trim_path(mod_name, 'modules')
206
207
# Creates an instance of the module
208
mod = framework.modules.create(name)
209
210
# If any additional datastore values were provided, set these values
211
mod.datastore.update(additional_datastore_values) unless additional_datastore_values.nil?
212
213
if mod.nil?
214
print_error("Invalid module: #{name}")
215
else
216
print_module_info(mod, dump_json: dump_json, show_doc: show_doc)
217
end
218
end
219
end
220
221
def cmd_options_help
222
print_line 'Usage: options [mod1 mod2 ...]'
223
print_line
224
print_line 'Queries the supplied module or modules for options. If no module is given,'
225
print_line 'show options for the currently active module.'
226
print_line
227
end
228
229
def cmd_options(*args)
230
if args.empty?
231
if (active_module)
232
show_options(active_module)
233
return true
234
else
235
show_global_options
236
return true
237
end
238
end
239
240
args.each do |name|
241
mod = framework.modules.create(name)
242
243
if (mod == nil)
244
print_error("Invalid module: #{name}")
245
else
246
show_options(mod)
247
end
248
end
249
end
250
251
#
252
# Tab completion for the advanced command (same as use)
253
#
254
# @param str (see #cmd_use_tabs)
255
# @param words (see #cmd_use_tabs)
256
257
def cmd_advanced_tabs(str, words)
258
cmd_use_tabs(str, words)
259
end
260
261
#
262
# Tab completion for the advanced command (same as use)
263
#
264
# @param str (see #cmd_use_tabs)
265
# @param words (see #cmd_use_tabs)
266
267
def cmd_info_tabs(str, words)
268
cmd_use_tabs(str, words)
269
end
270
271
#
272
# Tab completion for the advanced command (same as use)
273
#
274
# @param str (see #cmd_use_tabs)
275
# @param words (see #cmd_use_tabs)
276
277
def cmd_options_tabs(str, words)
278
cmd_use_tabs(str, words)
279
end
280
281
def cmd_loadpath_help
282
print_line "Usage: loadpath </path/to/modules>"
283
print_line
284
print_line "Loads modules from the given directory which should contain subdirectories for"
285
print_line "module types, e.g. /path/to/modules/exploits"
286
print_line
287
end
288
289
#
290
# Adds one or more search paths.
291
#
292
def cmd_loadpath(*args)
293
if (args.length == 0 or args.include? "-h")
294
cmd_loadpath_help
295
return true
296
end
297
298
totals = {}
299
overall = 0
300
curr_path = nil
301
302
begin
303
# Walk the list of supplied search paths attempting to add each one
304
# along the way
305
args.each { |path|
306
curr_path = path
307
308
# Load modules, but do not consult the cache
309
if (counts = framework.modules.add_module_path(path))
310
counts.each_pair { |type, count|
311
totals[type] = (totals[type]) ? (totals[type] + count) : count
312
313
overall += count
314
}
315
end
316
}
317
rescue NameError, RuntimeError
318
log_error("Failed to add search path #{curr_path}: #{$!}")
319
return true
320
end
321
322
added = "Loaded #{overall} modules:\n"
323
324
totals.sort_by { |type, _count| type }.each { |type, count|
325
added << " #{count} #{type} modules\n"
326
}
327
328
print(added)
329
end
330
331
#
332
# Tab completion for the loadpath command
333
#
334
# @param str [String] the string currently being typed before tab was hit
335
# @param words [Array<String>] the previously completed words on the command line. words is always
336
# at least 1 when tab completion has reached this stage since the command itself has been completed
337
338
def cmd_loadpath_tabs(str, words)
339
return [] if words.length > 1
340
341
# This custom completion might better than Readline's... We'll leave it for now.
342
#tab_complete_filenames(str,words)
343
344
paths = []
345
if (File.directory?(str))
346
paths = Dir.entries(str)
347
paths = paths.map { |f|
348
if File.directory? File.join(str,f)
349
File.join(str,f)
350
end
351
}
352
paths.delete_if { |f| f.nil? or File.basename(f) == '.' or File.basename(f) == '..' }
353
else
354
d = Dir.glob(str + "*").map { |f| f if File.directory?(f) }
355
d.delete_if { |f| f.nil? or f == '.' or f == '..' }
356
# If there's only one possibility, descend to the next level
357
if (1 == d.length)
358
paths = Dir.entries(d[0])
359
paths = paths.map { |f|
360
if File.directory? File.join(d[0],f)
361
File.join(d[0],f)
362
end
363
}
364
paths.delete_if { |f| f.nil? or File.basename(f) == '.' or File.basename(f) == '..' }
365
else
366
paths = d
367
end
368
end
369
paths.sort!
370
return paths
371
end
372
373
def cmd_search_help
374
print_line "Usage: search [<options>] [<keywords>:<value>]"
375
print_line
376
print_line "Prepending a value with '-' will exclude any matching results."
377
print_line "If no options or keywords are provided, cached results are displayed."
378
print_line
379
print @@search_opts.usage
380
print_line
381
print_line "Keywords:"
382
{
383
'adapter' => 'Modules with a matching adater reference name',
384
'aka' => 'Modules with a matching AKA (also-known-as) name',
385
'author' => 'Modules written by this author',
386
'arch' => 'Modules affecting this architecture',
387
'bid' => 'Modules with a matching Bugtraq ID',
388
'cve' => 'Modules with a matching CVE ID',
389
'edb' => 'Modules with a matching Exploit-DB ID',
390
'check' => 'Modules that support the \'check\' method',
391
'date' => 'Modules with a matching disclosure date',
392
'description' => 'Modules with a matching description',
393
'fullname' => 'Modules with a matching full name',
394
'mod_time' => 'Modules with a matching modification date',
395
'name' => 'Modules with a matching descriptive name',
396
'path' => 'Modules with a matching path',
397
'platform' => 'Modules affecting this platform',
398
'port' => 'Modules with a matching port',
399
'rank' => 'Modules with a matching rank (Can be descriptive (ex: \'good\') or numeric with comparison operators (ex: \'gte400\'))',
400
'ref' => 'Modules with a matching ref',
401
'reference' => 'Modules with a matching reference',
402
'session_type' => 'Modules with a matching session type (SMB, MySQL, Meterpreter, etc)',
403
'stage' => 'Modules with a matching stage reference name',
404
'stager' => 'Modules with a matching stager reference name',
405
'target' => 'Modules affecting this target',
406
'type' => 'Modules of a specific type (exploit, payload, auxiliary, encoder, evasion, post, or nop)',
407
'action' => 'Modules with a matching action name or description',
408
}.each_pair do |keyword, description|
409
print_line " #{keyword.ljust 17}: #{description}"
410
end
411
print_line
412
print_line "Supported search columns:"
413
{
414
'rank' => 'Sort modules by their exploitability rank',
415
'date' => 'Sort modules by their disclosure date. Alias for disclosure_date',
416
'disclosure_date' => 'Sort modules by their disclosure date',
417
'name' => 'Sort modules by their name',
418
'type' => 'Sort modules by their type',
419
'check' => 'Sort modules by whether or not they have a check method',
420
'action' => 'Sort modules by whether or not they have actions',
421
}.each_pair do |keyword, description|
422
print_line " #{keyword.ljust 17}: #{description}"
423
end
424
print_line
425
print_line "Examples:"
426
print_line " search cve:2009 type:exploit"
427
print_line " search cve:2009 type:exploit platform:-linux"
428
print_line " search cve:2009 -s name"
429
print_line " search type:exploit -s type -r"
430
print_line
431
end
432
433
#
434
# Searches modules for specific keywords
435
#
436
def cmd_search(*args)
437
match = ''
438
row_filter = nil
439
output_file = nil
440
cached = false
441
use = false
442
count = -1
443
search_terms = []
444
sort_attribute = 'name'
445
valid_sort_attributes = ['action', 'rank','disclosure_date','name','date','type','check']
446
reverse_sort = false
447
ignore_use_exact_match = false
448
449
@@search_opts.parse(args) do |opt, idx, val|
450
case opt
451
when '-S'
452
row_filter = val
453
when '-h'
454
cmd_search_help
455
return false
456
when '-o'
457
output_file = val
458
when '-u'
459
use = true
460
when '-I'
461
ignore_use_exact_match = true
462
when '-s'
463
sort_attribute = val
464
when '-r'
465
reverse_sort = true
466
else
467
match += val + ' '
468
end
469
end
470
471
if args.empty?
472
if @module_search_results_with_usage_metadata.empty?
473
cmd_search_help
474
return false
475
end
476
477
cached = true
478
end
479
480
if sort_attribute && !valid_sort_attributes.include?(sort_attribute)
481
print_error("Supported options for the -s flag are: #{valid_sort_attributes}")
482
return false
483
end
484
485
begin
486
if cached
487
print_status('Displaying cached results')
488
else
489
search_params = Msf::Modules::Metadata::Search.parse_search_string(match)
490
@module_search_results = Msf::Modules::Metadata::Cache.instance.find(search_params)
491
492
@module_search_results.sort_by! do |module_metadata|
493
if sort_attribute == 'action'
494
module_metadata.actions&.any? ? 0 : 1
495
elsif sort_attribute == 'check'
496
module_metadata.check ? 0 : 1
497
elsif sort_attribute == 'disclosure_date' || sort_attribute == 'date'
498
# Not all modules have disclosure_date, i.e. multi/handler
499
module_metadata.disclosure_date || Time.utc(0)
500
else
501
module_metadata.send(sort_attribute)
502
end
503
end
504
505
if reverse_sort
506
@module_search_results.reverse!
507
end
508
end
509
510
if @module_search_results.empty?
511
print_error('No results from search')
512
return false
513
end
514
515
if ignore_use_exact_match && @module_search_results.length == 1 &&
516
@module_search_results.first.fullname == match.strip
517
return false
518
end
519
520
if !search_params.nil? && !search_params['text'].nil?
521
search_params['text'][0].each do |t|
522
search_terms << t
523
end
524
end
525
526
# Generate the table used to display matches
527
tbl = generate_module_table('Matching Modules', search_terms, row_filter)
528
529
@module_search_results_with_usage_metadata = []
530
@module_search_results.each do |m|
531
@module_search_results_with_usage_metadata << { mod: m }
532
count += 1
533
tbl << [
534
count,
535
"#{m.fullname}",
536
m.disclosure_date.nil? ? '' : m.disclosure_date.strftime("%Y-%m-%d"),
537
m.rank,
538
m.check ? 'Yes' : 'No',
539
m.name,
540
]
541
542
if framework.features.enabled?(Msf::FeatureManager::HIERARCHICAL_SEARCH_TABLE)
543
total_children_rows = (m.actions&.length || 0) + (m.targets&.length || 0) + (m.notes&.[]('AKA')&.length || 0)
544
show_child_items = total_children_rows > 1
545
next unless show_child_items
546
547
indent = " \\_ "
548
# Note: We still use visual indicators for blank values as it's easier to read
549
# We can't always use a generic formatter/styler, as it would be applied to the 'parent' rows too
550
blank_value = '.'
551
if (m.actions&.length || 0) > 1
552
m.actions.each do |action|
553
@module_search_results_with_usage_metadata << { mod: m, datastore: { 'ACTION' => action['name'] } }
554
count += 1
555
tbl << [
556
count,
557
"#{indent}action: #{action['name']}",
558
blank_value,
559
blank_value,
560
blank_value,
561
action['description'],
562
]
563
end
564
end
565
566
if (m.targets&.length || 0) > 1
567
m.targets.each do |target|
568
@module_search_results_with_usage_metadata << { mod: m, datastore: { 'TARGET' => target } }
569
count += 1
570
tbl << [
571
count,
572
"#{indent}target: #{target}",
573
blank_value,
574
blank_value,
575
blank_value,
576
blank_value
577
]
578
end
579
end
580
581
if (m.notes&.[]('AKA')&.length || 0) > 1
582
m.notes['AKA'].each do |aka|
583
@module_search_results_with_usage_metadata << { mod: m }
584
count += 1
585
tbl << [
586
count,
587
"#{indent}AKA: #{aka}",
588
blank_value,
589
blank_value,
590
blank_value,
591
blank_value
592
]
593
end
594
end
595
end
596
end
597
rescue ArgumentError
598
print_error("Invalid argument(s)\n")
599
cmd_search_help
600
return false
601
end
602
603
if output_file
604
print_status("Wrote search results to #{output_file}")
605
::File.open(output_file, "wb") { |ofd|
606
ofd.write(tbl.to_csv)
607
}
608
return true
609
end
610
611
print_line(tbl.to_s)
612
print_module_search_results_usage
613
614
if @module_search_results.length == 1 && use
615
used_module = @module_search_results_with_usage_metadata.first[:mod].fullname
616
print_status("Using #{used_module}") if used_module
617
cmd_use(used_module, true)
618
end
619
620
true
621
end
622
623
#
624
# Tab completion for the search command
625
#
626
# @param str [String] the string currently being typed before tab was hit
627
# @param words [Array<String>] the previously completed words on the command line. words is always
628
# at least 1 when tab completion has reached this stage since the command itself has been completed
629
630
def cmd_search_tabs(str, words)
631
if words.length == 1
632
return @@search_opts.option_keys
633
end
634
635
[]
636
end
637
638
def cmd_show_help
639
global_opts = %w{all encoders nops exploits payloads auxiliary post plugins info options favorites}
640
print_status("Valid parameters for the \"show\" command are: #{global_opts.join(", ")}")
641
642
module_opts = %w{ missing advanced evasion targets actions }
643
print_status("Additional module-specific parameters are: #{module_opts.join(", ")}")
644
end
645
646
#
647
# Displays the list of modules based on their type, or all modules if
648
# no type is provided.
649
#
650
def cmd_show(*args)
651
if args.empty?
652
print_error("Argument required\n")
653
cmd_show_help
654
return
655
end
656
657
mod = self.active_module
658
659
args.each { |type|
660
case type
661
when '-h'
662
cmd_show_help
663
when 'all'
664
show_encoders
665
show_nops
666
show_exploits
667
show_payloads
668
show_auxiliary
669
show_post
670
show_plugins
671
when 'encoders'
672
show_encoders
673
when 'nops'
674
show_nops
675
when 'exploits'
676
show_exploits
677
when 'payloads'
678
show_payloads
679
when 'auxiliary'
680
show_auxiliary
681
when 'post'
682
show_post
683
when 'favorites'
684
show_favorites
685
when 'info'
686
cmd_info(*args[1, args.length])
687
when 'options'
688
if (mod)
689
show_options(mod)
690
else
691
show_global_options
692
end
693
when 'missing'
694
if (mod)
695
show_missing(mod)
696
else
697
print_error("No module selected.")
698
end
699
when 'advanced'
700
if (mod)
701
show_advanced_options(mod)
702
else
703
print_error("No module selected.")
704
end
705
when 'evasion'
706
if (mod)
707
show_evasion_options(mod)
708
else
709
show_evasion
710
end
711
when 'sessions'
712
if (active_module and active_module.respond_to?(:compatible_sessions))
713
sessions = active_module.compatible_sessions
714
else
715
sessions = framework.sessions.keys.sort
716
end
717
print_line
718
print(Serializer::ReadableText.dump_sessions(framework, :session_ids => sessions))
719
print_line
720
when "plugins"
721
show_plugins
722
when "targets"
723
if (mod and (mod.exploit? or mod.evasion?))
724
show_targets(mod)
725
else
726
print_error("No exploit module selected.")
727
end
728
when "actions"
729
if mod && mod.kind_of?(Msf::Module::HasActions)
730
show_actions(mod)
731
else
732
print_error("No module with actions selected.")
733
end
734
735
else
736
print_error("Invalid parameter \"#{type}\", use \"show -h\" for more information")
737
end
738
}
739
end
740
741
#
742
# Tab completion for the show command
743
#
744
# @param str [String] the string currently being typed before tab was hit
745
# @param words [Array<String>] the previously completed words on the command line. words is always
746
# at least 1 when tab completion has reached this stage since the command itself has been completed
747
748
def cmd_show_tabs(str, words)
749
return [] if words.length > 1
750
751
res = %w{all encoders nops exploits payloads auxiliary post plugins options favorites}
752
if (active_module)
753
res.concat %w{missing advanced evasion targets actions info}
754
if (active_module.respond_to? :compatible_sessions)
755
res << "sessions"
756
end
757
end
758
return res
759
end
760
761
def cmd_use_help
762
print_line 'Usage: use <name|term|index>'
763
print_line
764
print_line 'Interact with a module by name or search term/index.'
765
print_line 'If a module name is not found, it will be treated as a search term.'
766
print_line 'An index from the previous search results can be selected if desired.'
767
print_line
768
print_line 'Examples:'
769
print_line ' use exploit/windows/smb/ms17_010_eternalblue'
770
print_line
771
print_line ' use eternalblue'
772
print_line ' use <name|index>'
773
print_line
774
print_line ' search eternalblue'
775
print_line ' use <name|index>'
776
print_line
777
print_april_fools_module_use
778
end
779
780
#
781
# Uses a module.
782
#
783
def cmd_use(*args)
784
if args.length == 0 || args.first == '-h'
785
cmd_use_help
786
return false
787
end
788
789
# Divert logic for dangerzone mode
790
args = dangerzone_codename_to_module(args)
791
792
# Try to create an instance of the supplied module name
793
mod_name = args[0]
794
795
additional_datastore_values = nil
796
797
# Use a module by search index
798
index_from_list(@module_search_results_with_usage_metadata, mod_name) do |result|
799
mod = result&.[](:mod)
800
unless mod && mod.respond_to?(:fullname)
801
print_error("Invalid module index: #{mod_name}")
802
return false
803
end
804
805
# Module cache object from @module_search_results_with_usage_metadata
806
mod_name = mod.fullname
807
additional_datastore_values = result[:datastore]
808
end
809
810
# See if the supplied module name has already been resolved
811
mod_resolved = args[1] == true ? true : false
812
813
# Ensure we have a reference name and not a path
814
mod_name = trim_path(mod_name, "modules")
815
816
begin
817
mod = framework.modules.create(mod_name)
818
819
unless mod
820
# Checks to see if we have any load_errors for the current module.
821
# and if so, returns them to the user.
822
load_error = framework.modules.load_error_by_name(mod_name)
823
if load_error
824
print_error("Failed to load module: #{load_error}")
825
return false
826
end
827
unless mod_resolved
828
elog("Module #{mod_name} not found, and no loading errors found. If you're using a custom module" \
829
' refer to our wiki: https://docs.metasploit.com/docs/using-metasploit/intermediate/running-private-modules.html')
830
831
# Avoid trying to use the search result if it exactly matches
832
# the module we were trying to load. The module cannot be
833
# loaded and searching isn't going to change that.
834
mods_found = cmd_search('-I', '-u', *args)
835
end
836
837
unless mods_found
838
print_error("Failed to load module: #{mod_name}")
839
return false
840
end
841
end
842
rescue Rex::AmbiguousArgumentError => info
843
print_error(info.to_s)
844
rescue NameError => info
845
log_error("The supplied module name is ambiguous: #{$!}.")
846
end
847
848
return false if (mod == nil)
849
850
# Enstack the command dispatcher for this module type
851
dispatcher = nil
852
853
case mod.type
854
when Msf::MODULE_ENCODER
855
dispatcher = Msf::Ui::Console::CommandDispatcher::Encoder
856
when Msf::MODULE_EXPLOIT
857
dispatcher = Msf::Ui::Console::CommandDispatcher::Exploit
858
when Msf::MODULE_NOP
859
dispatcher = Msf::Ui::Console::CommandDispatcher::Nop
860
when Msf::MODULE_PAYLOAD
861
dispatcher = Msf::Ui::Console::CommandDispatcher::Payload
862
when Msf::MODULE_AUX
863
dispatcher = Msf::Ui::Console::CommandDispatcher::Auxiliary
864
when Msf::MODULE_POST
865
dispatcher = Msf::Ui::Console::CommandDispatcher::Post
866
when Msf::MODULE_EVASION
867
dispatcher = Msf::Ui::Console::CommandDispatcher::Evasion
868
else
869
print_error("Unsupported module type: #{mod.type}")
870
return false
871
end
872
873
# If there's currently an active module, enqueque it and go back
874
if (active_module)
875
@previous_module = active_module
876
cmd_back()
877
end
878
879
if (dispatcher != nil)
880
driver.enstack_dispatcher(dispatcher)
881
end
882
883
# Update the active module
884
self.active_module = mod
885
886
# If a datastore cache exists for this module, then load it up
887
if @dscache[active_module.fullname]
888
active_module.datastore.update(@dscache[active_module.fullname])
889
end
890
891
# If any additional datastore values were provided, set these values
892
unless additional_datastore_values.nil? || additional_datastore_values.empty?
893
mod.datastore.update(additional_datastore_values)
894
print_status("Additionally setting #{additional_datastore_values.map { |k,v| "#{k} => #{v}" }.join(", ")}")
895
if additional_datastore_values['TARGET'] && (mod.exploit? || mod.evasion?)
896
mod.import_target_defaults
897
end
898
end
899
900
# Choose a default payload when the module is used, not run
901
if mod.datastore['PAYLOAD']
902
print_status("Using configured payload #{mod.datastore['PAYLOAD']}")
903
elsif dispatcher.respond_to?(:choose_payload)
904
chosen_payload = dispatcher.choose_payload(mod)
905
print_status("No payload configured, defaulting to #{chosen_payload}") if chosen_payload
906
end
907
908
mod.init_ui(driver.input, driver.output)
909
end
910
911
#
912
# Command to take to the previously active module
913
#
914
def cmd_previous(*args)
915
if @previous_module
916
self.cmd_use(@previous_module.fullname)
917
else
918
print_error("There isn't a previous module at the moment")
919
end
920
end
921
922
#
923
# Help for the 'previous' command
924
#
925
def cmd_previous_help
926
print_line "Usage: previous"
927
print_line
928
print_line "Set the previously loaded module as the current module"
929
print_line
930
print_line "Previous module: #{@previous_module ? @previous_module.fullname : 'none'}"
931
print_line
932
end
933
934
#
935
# Command to enqueque a module on the module stack
936
#
937
def cmd_pushm(*args)
938
# could check if each argument is a valid module, but for now let them hang themselves
939
if args.count > 0
940
args.each do |arg|
941
@module_name_stack.push(arg)
942
# Note new modules are appended to the array and are only module (full)names
943
end
944
else #then just push the active module
945
if active_module
946
#print_status "Pushing the active module"
947
@module_name_stack.push(active_module.fullname)
948
else
949
print_error("There isn't an active module and you didn't specify a module to push")
950
return self.cmd_pushm_help
951
end
952
end
953
end
954
955
#
956
# Tab completion for the pushm command
957
#
958
# @param str [String] the string currently being typed before tab was hit
959
# @param words [Array<String>] the previously completed words on the command line. words is always
960
# at least 1 when tab completion has reached this stage since the command itself has been completed
961
962
def cmd_pushm_tabs(str, words)
963
tab_complete_module(str, words)
964
end
965
966
#
967
# Help for the 'pushm' command
968
#
969
def cmd_pushm_help
970
print_line "Usage: pushm [module1 [,module2, module3...]]"
971
print_line
972
print_line "push current active module or specified modules onto the module stack"
973
print_line
974
end
975
976
#
977
# Command to dequeque a module from the module stack
978
#
979
def cmd_popm(*args)
980
if (args.count > 1 or not args[0].respond_to?("to_i"))
981
return self.cmd_popm_help
982
elsif args.count == 1
983
# then pop 'n' items off the stack, but don't change the active module
984
if args[0].to_i >= @module_name_stack.count
985
# in case they pass in a number >= the length of @module_name_stack
986
@module_name_stack = []
987
print_status("The module stack is empty")
988
else
989
@module_name_stack.pop(args[0].to_i)
990
end
991
else #then just pop the array and make that the active module
992
pop = @module_name_stack.pop
993
if pop
994
return self.cmd_use(pop)
995
else
996
print_error("There isn't anything to pop, the module stack is empty")
997
end
998
end
999
end
1000
1001
#
1002
# Help for the 'popm' command
1003
#
1004
def cmd_popm_help
1005
print_line "Usage: popm [n]"
1006
print_line
1007
print_line "pop the latest module off of the module stack and make it the active module"
1008
print_line "or pop n modules off the stack, but don't change the active module"
1009
print_line
1010
end
1011
1012
def cmd_listm_help
1013
print_line 'Usage: listm'
1014
print_line
1015
print_line 'List the module stack'
1016
print_line
1017
end
1018
1019
def cmd_listm(*_args)
1020
if @module_name_stack.empty?
1021
print_error('The module stack is empty')
1022
return
1023
end
1024
1025
print_status("Module stack:\n")
1026
1027
@module_name_stack.to_enum.with_index.reverse_each do |name, idx|
1028
print_line("[#{idx}]\t#{name}")
1029
end
1030
end
1031
1032
def cmd_clearm_help
1033
print_line 'Usage: clearm'
1034
print_line
1035
print_line 'Clear the module stack'
1036
print_line
1037
end
1038
1039
def cmd_clearm(*_args)
1040
print_status('Clearing the module stack')
1041
@module_name_stack.clear
1042
end
1043
1044
#
1045
# Tab completion for the use command
1046
#
1047
# @param str [String] the string currently being typed before tab was hit
1048
# @param words [Array<String>] the previously completed words on the command line. words is always
1049
# at least 1 when tab completion has reached this stage since the command itself has been completed
1050
1051
def cmd_use_tabs(str, words)
1052
return [] if words.length > 1
1053
1054
tab_complete_module(str, words)
1055
end
1056
1057
def cmd_reload_all_help
1058
print_line "Usage: reload_all"
1059
print_line
1060
print_line "Reload all modules from all configured module paths. This may take awhile."
1061
print_line "See also: loadpath"
1062
print_line
1063
end
1064
1065
#
1066
# Reload all module paths that we are aware of
1067
#
1068
def cmd_reload_all(*args)
1069
if args.length > 0
1070
cmd_reload_all_help
1071
return
1072
end
1073
1074
print_status("Reloading modules from all module paths...")
1075
framework.modules.reload_modules
1076
1077
log_msg = "Please see #{File.join(Msf::Config.log_directory, 'framework.log')} for details."
1078
1079
# Check for modules that failed to load
1080
if framework.modules.module_load_error_by_path.length > 0
1081
wlog("WARNING! The following modules could not be loaded!")
1082
1083
framework.modules.module_load_error_by_path.each do |path, _error|
1084
wlog("\t#{path}")
1085
end
1086
1087
wlog(log_msg)
1088
end
1089
1090
if framework.modules.module_load_warnings.length > 0
1091
wlog("The following modules were loaded with warnings:")
1092
1093
framework.modules.module_load_warnings.each do |path, _error|
1094
wlog("\t#{path}")
1095
end
1096
1097
wlog(log_msg)
1098
end
1099
1100
self.driver.run_single('reload')
1101
self.driver.run_single("banner")
1102
end
1103
1104
def cmd_back_help
1105
print_line "Usage: back"
1106
print_line
1107
print_line "Return to the global dispatcher context"
1108
print_line
1109
end
1110
1111
#
1112
# Pop the current dispatcher stack context, assuming it isn't pointed at
1113
# the core or database backend stack context.
1114
#
1115
def cmd_back(*args)
1116
if (driver.dispatcher_stack.size > 1 and
1117
driver.current_dispatcher.name != 'Core' and
1118
driver.current_dispatcher.name != 'Database Backend')
1119
# Reset the active module if we have one
1120
if (active_module)
1121
1122
# Do NOT reset the UI anymore
1123
# active_module.reset_ui
1124
1125
# Save the module's datastore so that we can load it later
1126
# if the module is used again
1127
@dscache[active_module.fullname] = active_module.datastore.dup
1128
1129
self.active_module = nil
1130
end
1131
1132
# Destack the current dispatcher
1133
driver.destack_dispatcher
1134
end
1135
end
1136
1137
def cmd_favorite_help
1138
print_line 'Usage: favorite [mod1 mod2 ...]'
1139
print_line
1140
print_line "Add one or multiple modules to the list of favorite modules stored in #{Msf::Config.fav_modules_file}"
1141
print_line 'If no module name is specified, the command will add the active module if there is one'
1142
print @@favorite_opts.usage
1143
end
1144
1145
#
1146
# Helper method for cmd_favorite that writes modules to the fav_modules_file
1147
#
1148
def favorite_add(modules, favs_file)
1149
fav_limit = 50
1150
# obtain useful info about the fav_modules file
1151
exists, writable, readable, contents = favorite_check_fav_modules(favs_file)
1152
1153
# if the fav_modules file exists, check the file permissions
1154
if exists
1155
case
1156
when !writable
1157
print_error("Unable to save module(s) to the favorite modules file because it is not writable")
1158
return
1159
when !readable
1160
print_error("Unable to save module(s) to the favorite modules file because it is not readable")
1161
return
1162
end
1163
end
1164
1165
fav_count = 0
1166
if contents
1167
fav_count = contents.split.size
1168
end
1169
1170
modules = modules.uniq # prevent modules from being added more than once
1171
modules.each do |name|
1172
mod = framework.modules.create(name)
1173
if (mod == nil)
1174
print_error("Invalid module: #{name}")
1175
next
1176
end
1177
1178
if contents && contents.include?(mod.fullname)
1179
print_warning("Module #{mod.fullname} has already been favorited and will not be added to the favorite modules file")
1180
next
1181
end
1182
1183
if fav_count >= fav_limit
1184
print_error("Favorite module limit (#{fav_limit}) exceeded. No more modules will be added.")
1185
return
1186
end
1187
1188
File.open(favs_file, 'a+') { |file| file.puts(mod.fullname) }
1189
print_good("Added #{mod.fullname} to the favorite modules file")
1190
fav_count += 1
1191
end
1192
return
1193
end
1194
1195
#
1196
# Helper method for cmd_favorite that deletes modules from the fav_modules_file
1197
#
1198
def favorite_del(modules, delete_all, favs_file)
1199
# obtain useful info about the fav_modules file
1200
exists, writable, readable, contents = favorite_check_fav_modules(favs_file)
1201
1202
if delete_all
1203
custom_message = 'clear the contents of'
1204
else
1205
custom_message = 'delete module(s) from'
1206
end
1207
1208
case # error handling based on the existence / permissions of the fav_modules file
1209
when !exists
1210
print_warning("Unable to #{custom_message} the favorite modules file because it does not exist")
1211
return
1212
when !writable
1213
print_error("Unable to #{custom_message} the favorite modules file because it is not writable")
1214
return
1215
when !readable
1216
unless delete_all
1217
print_error("Unable to #{custom_message} the favorite modules file because it is not readable")
1218
return
1219
end
1220
when contents.empty?
1221
print_warning("Unable to #{custom_message} the favorite modules file because it is already empty")
1222
return
1223
end
1224
1225
if delete_all
1226
File.write(favs_file, '')
1227
print_good("Favorite modules file cleared")
1228
return
1229
end
1230
1231
modules = modules.uniq # prevent modules from being deleted more than once
1232
contents = contents.split
1233
modules.each do |name|
1234
mod = framework.modules.create(name)
1235
if (mod == nil)
1236
print_error("Invalid module: #{name}")
1237
next
1238
end
1239
1240
unless contents.include?(mod.fullname)
1241
print_warning("Module #{mod.fullname} cannot be deleted because it is not in the favorite modules file")
1242
next
1243
end
1244
1245
contents.delete(mod.fullname)
1246
print_status("Removing #{mod.fullname} from the favorite modules file")
1247
end
1248
1249
# clear the contents of the fav_modules file if removing the module(s) makes it empty
1250
if contents.length == 0
1251
File.write(favs_file, '')
1252
return
1253
end
1254
1255
File.open(favs_file, 'w') { |file| file.puts(contents.join("\n")) }
1256
end
1257
1258
#
1259
# Helper method for cmd_favorite that checks if the fav_modules file exists and is readable / writable
1260
#
1261
def favorite_check_fav_modules(favs_file)
1262
exists = false
1263
writable = false
1264
readable = false
1265
contents = ''
1266
1267
if File.exist?(favs_file)
1268
exists = true
1269
end
1270
1271
if File.writable?(favs_file)
1272
writable = true
1273
end
1274
1275
if File.readable?(favs_file)
1276
readable = true
1277
contents = File.read(favs_file)
1278
end
1279
1280
return exists, writable, readable, contents
1281
end
1282
1283
#
1284
# Add modules to or delete modules from the fav_modules file
1285
#
1286
def cmd_favorite(*args)
1287
valid_custom_args = ['-c', '-d', '-l']
1288
favs_file = Msf::Config.fav_modules_file
1289
1290
# always display the help banner if -h is provided or if multiple options are provided
1291
if args.include?('-h') || args.select{ |arg| arg if valid_custom_args.include?(arg) }.length > 1
1292
cmd_favorite_help
1293
return
1294
end
1295
1296
# if no arguments were provided, check if there is an active module to add
1297
if args.empty?
1298
unless active_module
1299
print_error('No module has been provided to favorite.')
1300
cmd_favorite_help
1301
return
1302
end
1303
1304
args = [active_module.fullname]
1305
favorite_add(args, favs_file)
1306
return
1307
end
1308
1309
case args[0]
1310
when '-c'
1311
args.delete('-c')
1312
unless args.empty?
1313
print_error('Option `-c` does not support arguments.')
1314
cmd_favorite_help
1315
return
1316
end
1317
1318
favorite_del(args, true, favs_file)
1319
when '-d'
1320
args.delete('-d')
1321
if args.empty?
1322
unless active_module
1323
print_error('No module has been provided to delete.')
1324
cmd_favorite_help
1325
return
1326
end
1327
1328
args = [active_module.fullname]
1329
end
1330
1331
favorite_del(args, false, favs_file)
1332
when '-l'
1333
args.delete('-l')
1334
unless args.empty?
1335
print_error('Option `-l` does not support arguments.')
1336
cmd_favorite_help
1337
return
1338
end
1339
cmd_show('favorites')
1340
else # no valid options, but there are arguments
1341
if args[0].start_with?('-')
1342
print_error('Invalid option provided')
1343
cmd_favorite_help
1344
return
1345
end
1346
1347
favorite_add(args, favs_file)
1348
end
1349
end
1350
1351
def cmd_favorites_help
1352
print_line 'Usage: favorites'
1353
print_line
1354
print_line 'Print the list of favorite modules (alias for `show favorites`)'
1355
print_line 'You can use the %grnfavorite%clr command to add the current module to your favorites list'
1356
print @@favorites_opts.usage
1357
end
1358
1359
#
1360
# Print the list of favorite modules from the fav_modules file (alias for `show favorites`)
1361
#
1362
def cmd_favorites(*args)
1363
if args.empty?
1364
cmd_show('favorites')
1365
return
1366
end
1367
1368
# always display the help banner if the command is called with arguments
1369
unless args.include?('-h')
1370
print_error('Invalid option(s) provided')
1371
end
1372
1373
cmd_favorites_help
1374
end
1375
1376
#
1377
# Tab complete module names
1378
#
1379
def tab_complete_module(str, words)
1380
res = []
1381
module_metadata = Msf::Modules::Metadata::Cache.instance.get_metadata
1382
module_metadata.each do |m|
1383
res << "#{m.type}/#{m.ref_name}"
1384
end
1385
framework.modules.module_types.each do |mtyp|
1386
mset = framework.modules.module_names(mtyp)
1387
mset.each do |mref|
1388
res << mtyp + '/' + mref
1389
end
1390
end
1391
1392
return dangerzone_modules_to_codenames(res.sort) if dangerzone_active?
1393
return res.uniq.sort
1394
end
1395
1396
def print_april_fools_module_use
1397
return unless ENV['APRILFOOLSMODULEUSE'] || Time.now.strftime("%m%d") == "0401"
1398
1399
banner = Msf::Ui::Banner.readfile('help-using-a-module.txt')
1400
print_line("%grn#{banner}%clr")
1401
end
1402
1403
#
1404
# Convert squirrel names back to regular module names
1405
#
1406
def dangerzone_codename_to_module(args)
1407
return args unless dangerzone_active? && args.length > 0 && args[0].length > 0
1408
return args unless args[0] =~ /^[A-Z]/
1409
args[0] = dangerzone_codename_to_module_name(args[0])
1410
args
1411
end
1412
1413
#
1414
# Determine if dangerzone mode is active via date or environment variable
1415
#
1416
def dangerzone_active?
1417
active = Time.now.strftime("%m%d") == "0401" || Rex::Compat.getenv('DANGERZONE').to_i > 0
1418
if active && @dangerzone_map.nil?
1419
dangerzone_build_map
1420
end
1421
active
1422
end
1423
1424
#
1425
# Convert module names to squirrel names
1426
#
1427
def dangerzone_modules_to_codenames(names)
1428
(names + @dangerzone_map.keys.grep(/^[A-Z]+/)).sort
1429
end
1430
1431
def dangerzone_codename_to_module_name(cname)
1432
@dangerzone_map[cname] || cname
1433
end
1434
1435
def dangerzone_module_name_to_codename(mname)
1436
@dangerzone_map[mname] || mname
1437
end
1438
1439
def dangerzone_build_map
1440
return unless @dangerzone_map.nil?
1441
1442
@dangerzone_map = {}
1443
1444
res = []
1445
%W{exploit auxiliary}.each do |mtyp|
1446
mset = framework.modules.module_names(mtyp)
1447
mset.each do |mref|
1448
res << mtyp + '/' + mref
1449
end
1450
end
1451
1452
words_a = ::File.readlines(::File.join(
1453
::Msf::Config.data_directory, "wordlists", "dangerzone_a.txt"
1454
)).map{|line| line.strip.upcase}
1455
1456
words_b = ::File.readlines(::File.join(
1457
::Msf::Config.data_directory, "wordlists", "dangerzone_b.txt"
1458
)).map{|line| line.strip.upcase}
1459
1460
aidx = -1
1461
bidx = -1
1462
1463
res.sort.each do |mname|
1464
word_a = words_a[ (aidx += 1) % words_a.length ]
1465
word_b = words_b[ (bidx += 1) % words_b.length ]
1466
cname = word_a + word_b
1467
1468
while @dangerzone_map[cname]
1469
aidx += 1
1470
word_a = words_a[ (aidx += 1) % words_a.length ]
1471
cname = word_a + word_b
1472
end
1473
1474
@dangerzone_map[mname] = cname
1475
@dangerzone_map[cname] = mname
1476
end
1477
end
1478
1479
#
1480
# Module list enumeration
1481
#
1482
1483
def show_encoders # :nodoc:
1484
# If an active module has been selected and it's an exploit, get the
1485
# list of compatible encoders and display them
1486
if (active_module and active_module.exploit? == true)
1487
show_module_metadata('Compatible Encoders', active_module.compatible_encoders)
1488
else
1489
show_module_metadata('Encoders', 'encoder')
1490
end
1491
end
1492
1493
def show_nops # :nodoc:
1494
show_module_metadata('NOP Generators', 'nop')
1495
end
1496
1497
def show_exploits # :nodoc:
1498
show_module_metadata('Exploits', 'exploit')
1499
end
1500
1501
def show_payloads # :nodoc:
1502
# If an active module has been selected and it's an exploit, get the
1503
# list of compatible payloads and display them
1504
if active_module && (active_module.exploit? || active_module.evasion?)
1505
@@payload_show_results = active_module.compatible_payloads
1506
1507
show_module_metadata('Compatible Payloads', @@payload_show_results)
1508
else
1509
# show_module_set(‘Payloads’, framework.payloads, regex, minrank, opts)
1510
show_module_metadata('Payloads', 'payload')
1511
end
1512
end
1513
1514
def show_auxiliary # :nodoc:
1515
show_module_metadata('Auxiliary','auxiliary')
1516
end
1517
1518
def show_post # :nodoc:
1519
show_module_metadata('Post','post')
1520
end
1521
1522
def show_evasion # :nodoc:
1523
show_module_metadata('Evasion','evasion')
1524
end
1525
1526
def show_favorites # :nodoc:
1527
favs_file = Msf::Config.fav_modules_file
1528
1529
unless File.exist?(favs_file)
1530
print_error("The favorite modules file does not exist")
1531
return
1532
end
1533
1534
if File.zero?(favs_file)
1535
print_warning("The favorite modules file is empty")
1536
return
1537
end
1538
1539
unless File.readable?(favs_file)
1540
print_error("Unable to read from #{favs_file}")
1541
return
1542
end
1543
1544
# create module set using the saved modules
1545
fav_modules = {}
1546
1547
# get the full module names from the favorites file and use then to search the MetaData Cache for matching modules
1548
saved_favs = File.readlines(favs_file).map(&:strip)
1549
saved_favs.each do |mod|
1550
# populate hash with module fullname and module object
1551
fav_modules[mod] = framework.modules[mod]
1552
end
1553
1554
fav_modules.each do |fullname, mod_obj|
1555
if mod_obj.nil?
1556
print_warning("#{favs_file} contains a module that can not be found - #{fullname}.")
1557
end
1558
end
1559
1560
# find cache module instance and add it to @module_search_results
1561
@module_search_results = Msf::Modules::Metadata::Cache.instance.find('fullname' => [saved_favs, []])
1562
1563
# This scenario is for when a module fullname is a substring of other module fullnames
1564
# Example, searching for the payload/windows/meterpreter/reverse_tcp module can result in matches for:
1565
# - windows/meterpreter/reverse_tcp_allports
1566
# - windows/meterpreter/reverse_tcp_dns
1567
# So if @module_search_results is greater than the amount of fav_modules, we need to filter the results to be more accurate
1568
if fav_modules.length < @module_search_results.length
1569
filtered_results = []
1570
fav_modules.each do |fullname, _mod_obj|
1571
filtered_results << @module_search_results.select do |search_result|
1572
search_result.fullname == fullname
1573
end
1574
end
1575
@module_search_results = filtered_results.flatten.sort_by(&:fullname)
1576
end
1577
@module_search_results_with_usage_metadata = @module_search_results.map { |mod| { mod: mod, datastore: {} } }
1578
1579
show_module_metadata('Favorites', fav_modules)
1580
print_module_search_results_usage
1581
end
1582
1583
def show_missing(mod) # :nodoc:
1584
mod_opt = Serializer::ReadableText.dump_options(mod, ' ', true)
1585
print("\nModule options (#{mod.fullname}):\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
1586
1587
# If it's an exploit and a payload is defined, create it and
1588
# display the payload's options
1589
if (mod.exploit? and mod.datastore['PAYLOAD'])
1590
p = framework.payloads.create(mod.datastore['PAYLOAD'])
1591
1592
if (!p)
1593
print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
1594
return
1595
end
1596
1597
p.share_datastore(mod.datastore)
1598
1599
if (p)
1600
p_opt = Serializer::ReadableText.dump_options(p, ' ', true)
1601
print("\nPayload options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
1602
end
1603
end
1604
end
1605
1606
def show_global_options
1607
columns = [ 'Option', 'Current Setting', 'Description' ]
1608
tbl = Table.new(
1609
Table::Style::Default,
1610
'Header' => 'Global Options:',
1611
'Prefix' => "\n",
1612
'Postfix' => "\n",
1613
'Columns' => columns
1614
)
1615
[
1616
[ 'ConsoleLogging', framework.datastore['ConsoleLogging'] || "false", 'Log all console input and output' ],
1617
[ 'LogLevel', framework.datastore['LogLevel'] || "0", 'Verbosity of logs (default 0, max 3)' ],
1618
[ 'MinimumRank', framework.datastore['MinimumRank'] || "0", 'The minimum rank of exploits that will run without explicit confirmation' ],
1619
[ 'SessionLogging', framework.datastore['SessionLogging'] || "false", 'Log all input and output for sessions' ],
1620
[ 'SessionTlvLogging', framework.datastore['SessionTlvLogging'] || "false", 'Log all incoming and outgoing TLV packets' ],
1621
[ 'TimestampOutput', framework.datastore['TimestampOutput'] || "false", 'Prefix all console output with a timestamp' ],
1622
[ 'Prompt', framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt.to_s.gsub(/%.../,"") , "The prompt string" ],
1623
[ 'PromptChar', framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar.to_s.gsub(/%.../,""), "The prompt character" ],
1624
[ 'PromptTimeFormat', framework.datastore['PromptTimeFormat'] || Time::DATE_FORMATS[:db].to_s, 'Format for timestamp escapes in prompts' ],
1625
[ 'MeterpreterPrompt', framework.datastore['MeterpreterPrompt'] || '%undmeterpreter%clr', 'The meterpreter prompt string' ],
1626
].each { |r| tbl << r }
1627
1628
print(tbl.to_s)
1629
end
1630
1631
def show_targets(mod) # :nodoc:
1632
case mod
1633
when Msf::Exploit
1634
mod_targs = Serializer::ReadableText.dump_exploit_targets(mod, '', "\nExploit targets:")
1635
print("#{mod_targs}\n") if (mod_targs and mod_targs.length > 0)
1636
when Msf::Evasion
1637
mod_targs = Serializer::ReadableText.dump_evasion_targets(mod, '', "\nEvasion targets:")
1638
print("#{mod_targs}\n") if (mod_targs and mod_targs.length > 0)
1639
end
1640
end
1641
1642
def show_actions(mod) # :nodoc:
1643
mod_actions = Serializer::ReadableText.dump_module_actions(mod, ' ')
1644
print("\n#{mod.type.capitalize} actions:\n\n#{mod_actions}\n") if (mod_actions and mod_actions.length > 0)
1645
end
1646
1647
def show_advanced_options(mod) # :nodoc:
1648
mod_opt = Serializer::ReadableText.dump_advanced_options(mod, ' ')
1649
print("\nModule advanced options (#{mod.fullname}):\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
1650
1651
# If it's an exploit and a payload is defined, create it and
1652
# display the payload's options
1653
if (mod.exploit? and mod.datastore['PAYLOAD'])
1654
p = framework.payloads.create(mod.datastore['PAYLOAD'])
1655
1656
if (!p)
1657
print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
1658
return
1659
end
1660
1661
p.share_datastore(mod.datastore)
1662
1663
if (p)
1664
p_opt = Serializer::ReadableText.dump_advanced_options(p, ' ')
1665
print("\nPayload advanced options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
1666
end
1667
end
1668
print("\nView the full module info with the #{Msf::Ui::Tip.highlight('info')}, or #{Msf::Ui::Tip.highlight('info -d')} command.\n\n")
1669
end
1670
1671
def show_evasion_options(mod) # :nodoc:
1672
mod_opt = Serializer::ReadableText.dump_evasion_options(mod, ' ')
1673
print("\nModule evasion options:\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
1674
1675
# If it's an exploit and a payload is defined, create it and
1676
# display the payload's options
1677
if (mod.evasion? and mod.datastore['PAYLOAD'])
1678
p = framework.payloads.create(mod.datastore['PAYLOAD'])
1679
1680
if (!p)
1681
print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
1682
return
1683
end
1684
1685
p.share_datastore(mod.datastore)
1686
1687
if (p)
1688
p_opt = Serializer::ReadableText.dump_evasion_options(p, ' ')
1689
print("\nPayload evasion options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
1690
end
1691
end
1692
end
1693
1694
def show_plugins # :nodoc:
1695
tbl = Table.new(
1696
Table::Style::Default,
1697
'Header' => 'Loaded Plugins',
1698
'Prefix' => "\n",
1699
'Postfix' => "\n",
1700
'Columns' => [ 'Name', 'Description' ]
1701
)
1702
1703
framework.plugins.each { |plugin|
1704
tbl << [ plugin.name, plugin.desc ]
1705
}
1706
1707
# create an instance of core to call the list_plugins
1708
core = Msf::Ui::Console::CommandDispatcher::Core.new(driver)
1709
core.list_plugins
1710
print(tbl.to_s)
1711
end
1712
1713
# @param [table_name] used to name table
1714
# @param [module_filter] this will either be a modules fullname, or it will be an Array(show payloads/encoders)
1715
# or a Hash(show favorites) containing fullname
1716
# @param [compatible_mod] handles logic for if there is an active module when the
1717
# `show` command is run
1718
#
1719
# Handles the filtering of modules that will be generated into a table
1720
def show_module_metadata(table_name, module_filter)
1721
count = -1
1722
tbl = generate_module_table(table_name)
1723
1724
if module_filter.is_a?(Array) || module_filter.is_a?(Hash)
1725
module_filter.sort.each do |_mod_fullname, mod_obj|
1726
mod = nil
1727
1728
begin
1729
mod = mod_obj.new
1730
rescue ::Exception
1731
end
1732
next unless mod
1733
1734
count += 1
1735
tbl << add_record(mod, count, true)
1736
end
1737
else
1738
results = Msf::Modules::Metadata::Cache.instance.find(
1739
'type' => [[module_filter], []]
1740
)
1741
# Loop over each module and gather data
1742
results.each do |mod, _value|
1743
count += 1
1744
tbl << add_record(mod, count, false)
1745
end
1746
end
1747
print(tbl.to_s)
1748
end
1749
1750
# @param [mod] current module being passed in
1751
# @param [count] passes the count for each record
1752
# @param [compatible_mod] handles logic for if there is an active module when the
1753
# `show` command is run
1754
#
1755
# Adds a record for a table, also handle logic for whether the module is currently
1756
# handling compatible payloads/encoders
1757
def add_record(mod, count, compatible_mod)
1758
if compatible_mod
1759
check = mod.has_check? ? 'Yes' : 'No'
1760
else
1761
check = mod.check ? 'Yes' : 'No'
1762
end
1763
[
1764
count,
1765
mod.fullname,
1766
mod.disclosure_date.nil? ? '' : mod.disclosure_date.strftime('%Y-%m-%d'),
1767
mod.rank,
1768
check,
1769
mod.name
1770
]
1771
end
1772
1773
def generate_module_table(type, search_terms = [], row_filter = nil) # :nodoc:
1774
table_hierarchy_formatters = framework.features.enabled?(Msf::FeatureManager::HIERARCHICAL_SEARCH_TABLE) ? [Msf::Ui::Console::TablePrint::BlankFormatter.new] : []
1775
1776
Table.new(
1777
Table::Style::Default,
1778
'Header' => type,
1779
'Prefix' => "\n",
1780
'Postfix' => "\n",
1781
'SearchTerm' => row_filter,
1782
'SortIndex' => -1,
1783
# For now, don't perform any word wrapping on the search table as it breaks the workflow of
1784
# copying module names in conjunction with the `use <paste-buffer>` command
1785
'WordWrap' => false,
1786
'Columns' => [
1787
'#',
1788
'Name',
1789
'Disclosure Date',
1790
'Rank',
1791
'Check',
1792
'Description'
1793
],
1794
'ColProps' => {
1795
'Rank' => {
1796
'Formatters' => [
1797
*table_hierarchy_formatters,
1798
Msf::Ui::Console::TablePrint::RankFormatter.new
1799
],
1800
'Stylers' => [
1801
Msf::Ui::Console::TablePrint::RankStyler.new
1802
]
1803
},
1804
'Name' => {
1805
'Strip' => false,
1806
'Stylers' => [Msf::Ui::Console::TablePrint::HighlightSubstringStyler.new(search_terms)]
1807
},
1808
'Check' => {
1809
'Formatters' => [
1810
*table_hierarchy_formatters,
1811
]
1812
},
1813
'Disclosure Date' => {
1814
'Formatters' => [
1815
*table_hierarchy_formatters,
1816
]
1817
},
1818
'Description' => {
1819
'Stylers' => [
1820
Msf::Ui::Console::TablePrint::HighlightSubstringStyler.new(search_terms)
1821
]
1822
}
1823
}
1824
)
1825
end
1826
end
1827
end
1828
end
1829
end
1830
end
1831
1832