CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/lib/msf/ui/console/command_dispatcher/modules.rb
Views: 11784
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
if framework.features.enabled?(Msf::FeatureManager::DISPLAY_MODULE_ACTION) && mod.respond_to?(:actions) && mod.actions.size > 1
909
print_status "Using action %grn#{mod.action.name}%clr - view all #{mod.actions.size} actions with the %grnshow actions%clr command"
910
end
911
912
mod.init_ui(driver.input, driver.output)
913
end
914
915
#
916
# Command to take to the previously active module
917
#
918
def cmd_previous(*args)
919
if @previous_module
920
self.cmd_use(@previous_module.fullname)
921
else
922
print_error("There isn't a previous module at the moment")
923
end
924
end
925
926
#
927
# Help for the 'previous' command
928
#
929
def cmd_previous_help
930
print_line "Usage: previous"
931
print_line
932
print_line "Set the previously loaded module as the current module"
933
print_line
934
print_line "Previous module: #{@previous_module ? @previous_module.fullname : 'none'}"
935
print_line
936
end
937
938
#
939
# Command to enqueque a module on the module stack
940
#
941
def cmd_pushm(*args)
942
# could check if each argument is a valid module, but for now let them hang themselves
943
if args.count > 0
944
args.each do |arg|
945
@module_name_stack.push(arg)
946
# Note new modules are appended to the array and are only module (full)names
947
end
948
else #then just push the active module
949
if active_module
950
#print_status "Pushing the active module"
951
@module_name_stack.push(active_module.fullname)
952
else
953
print_error("There isn't an active module and you didn't specify a module to push")
954
return self.cmd_pushm_help
955
end
956
end
957
end
958
959
#
960
# Tab completion for the pushm command
961
#
962
# @param str [String] the string currently being typed before tab was hit
963
# @param words [Array<String>] the previously completed words on the command line. words is always
964
# at least 1 when tab completion has reached this stage since the command itself has been completed
965
966
def cmd_pushm_tabs(str, words)
967
tab_complete_module(str, words)
968
end
969
970
#
971
# Help for the 'pushm' command
972
#
973
def cmd_pushm_help
974
print_line "Usage: pushm [module1 [,module2, module3...]]"
975
print_line
976
print_line "push current active module or specified modules onto the module stack"
977
print_line
978
end
979
980
#
981
# Command to dequeque a module from the module stack
982
#
983
def cmd_popm(*args)
984
if (args.count > 1 or not args[0].respond_to?("to_i"))
985
return self.cmd_popm_help
986
elsif args.count == 1
987
# then pop 'n' items off the stack, but don't change the active module
988
if args[0].to_i >= @module_name_stack.count
989
# in case they pass in a number >= the length of @module_name_stack
990
@module_name_stack = []
991
print_status("The module stack is empty")
992
else
993
@module_name_stack.pop(args[0].to_i)
994
end
995
else #then just pop the array and make that the active module
996
pop = @module_name_stack.pop
997
if pop
998
return self.cmd_use(pop)
999
else
1000
print_error("There isn't anything to pop, the module stack is empty")
1001
end
1002
end
1003
end
1004
1005
#
1006
# Help for the 'popm' command
1007
#
1008
def cmd_popm_help
1009
print_line "Usage: popm [n]"
1010
print_line
1011
print_line "pop the latest module off of the module stack and make it the active module"
1012
print_line "or pop n modules off the stack, but don't change the active module"
1013
print_line
1014
end
1015
1016
def cmd_listm_help
1017
print_line 'Usage: listm'
1018
print_line
1019
print_line 'List the module stack'
1020
print_line
1021
end
1022
1023
def cmd_listm(*_args)
1024
if @module_name_stack.empty?
1025
print_error('The module stack is empty')
1026
return
1027
end
1028
1029
print_status("Module stack:\n")
1030
1031
@module_name_stack.to_enum.with_index.reverse_each do |name, idx|
1032
print_line("[#{idx}]\t#{name}")
1033
end
1034
end
1035
1036
def cmd_clearm_help
1037
print_line 'Usage: clearm'
1038
print_line
1039
print_line 'Clear the module stack'
1040
print_line
1041
end
1042
1043
def cmd_clearm(*_args)
1044
print_status('Clearing the module stack')
1045
@module_name_stack.clear
1046
end
1047
1048
#
1049
# Tab completion for the use command
1050
#
1051
# @param str [String] the string currently being typed before tab was hit
1052
# @param words [Array<String>] the previously completed words on the command line. words is always
1053
# at least 1 when tab completion has reached this stage since the command itself has been completed
1054
1055
def cmd_use_tabs(str, words)
1056
return [] if words.length > 1
1057
1058
tab_complete_module(str, words)
1059
end
1060
1061
def cmd_reload_all_help
1062
print_line "Usage: reload_all"
1063
print_line
1064
print_line "Reload all modules from all configured module paths. This may take awhile."
1065
print_line "See also: loadpath"
1066
print_line
1067
end
1068
1069
#
1070
# Reload all module paths that we are aware of
1071
#
1072
def cmd_reload_all(*args)
1073
if args.length > 0
1074
cmd_reload_all_help
1075
return
1076
end
1077
1078
print_status("Reloading modules from all module paths...")
1079
framework.modules.reload_modules
1080
1081
log_msg = "Please see #{File.join(Msf::Config.log_directory, 'framework.log')} for details."
1082
1083
# Check for modules that failed to load
1084
if framework.modules.module_load_error_by_path.length > 0
1085
wlog("WARNING! The following modules could not be loaded!")
1086
1087
framework.modules.module_load_error_by_path.each do |path, _error|
1088
wlog("\t#{path}")
1089
end
1090
1091
wlog(log_msg)
1092
end
1093
1094
if framework.modules.module_load_warnings.length > 0
1095
wlog("The following modules were loaded with warnings:")
1096
1097
framework.modules.module_load_warnings.each do |path, _error|
1098
wlog("\t#{path}")
1099
end
1100
1101
wlog(log_msg)
1102
end
1103
1104
self.driver.run_single('reload')
1105
self.driver.run_single("banner")
1106
end
1107
1108
def cmd_back_help
1109
print_line "Usage: back"
1110
print_line
1111
print_line "Return to the global dispatcher context"
1112
print_line
1113
end
1114
1115
#
1116
# Pop the current dispatcher stack context, assuming it isn't pointed at
1117
# the core or database backend stack context.
1118
#
1119
def cmd_back(*args)
1120
if (driver.dispatcher_stack.size > 1 and
1121
driver.current_dispatcher.name != 'Core' and
1122
driver.current_dispatcher.name != 'Database Backend')
1123
# Reset the active module if we have one
1124
if (active_module)
1125
1126
# Do NOT reset the UI anymore
1127
# active_module.reset_ui
1128
1129
# Save the module's datastore so that we can load it later
1130
# if the module is used again
1131
@dscache[active_module.fullname] = active_module.datastore.dup
1132
1133
self.active_module = nil
1134
end
1135
1136
# Destack the current dispatcher
1137
driver.destack_dispatcher
1138
end
1139
end
1140
1141
def cmd_favorite_help
1142
print_line 'Usage: favorite [mod1 mod2 ...]'
1143
print_line
1144
print_line "Add one or multiple modules to the list of favorite modules stored in #{Msf::Config.fav_modules_file}"
1145
print_line 'If no module name is specified, the command will add the active module if there is one'
1146
print @@favorite_opts.usage
1147
end
1148
1149
#
1150
# Helper method for cmd_favorite that writes modules to the fav_modules_file
1151
#
1152
def favorite_add(modules, favs_file)
1153
fav_limit = 50
1154
# obtain useful info about the fav_modules file
1155
exists, writable, readable, contents = favorite_check_fav_modules(favs_file)
1156
1157
# if the fav_modules file exists, check the file permissions
1158
if exists
1159
case
1160
when !writable
1161
print_error("Unable to save module(s) to the favorite modules file because it is not writable")
1162
return
1163
when !readable
1164
print_error("Unable to save module(s) to the favorite modules file because it is not readable")
1165
return
1166
end
1167
end
1168
1169
fav_count = 0
1170
if contents
1171
fav_count = contents.split.size
1172
end
1173
1174
modules = modules.uniq # prevent modules from being added more than once
1175
modules.each do |name|
1176
mod = framework.modules.create(name)
1177
if (mod == nil)
1178
print_error("Invalid module: #{name}")
1179
next
1180
end
1181
1182
if contents && contents.include?(mod.fullname)
1183
print_warning("Module #{mod.fullname} has already been favorited and will not be added to the favorite modules file")
1184
next
1185
end
1186
1187
if fav_count >= fav_limit
1188
print_error("Favorite module limit (#{fav_limit}) exceeded. No more modules will be added.")
1189
return
1190
end
1191
1192
File.open(favs_file, 'a+') { |file| file.puts(mod.fullname) }
1193
print_good("Added #{mod.fullname} to the favorite modules file")
1194
fav_count += 1
1195
end
1196
return
1197
end
1198
1199
#
1200
# Helper method for cmd_favorite that deletes modules from the fav_modules_file
1201
#
1202
def favorite_del(modules, delete_all, favs_file)
1203
# obtain useful info about the fav_modules file
1204
exists, writable, readable, contents = favorite_check_fav_modules(favs_file)
1205
1206
if delete_all
1207
custom_message = 'clear the contents of'
1208
else
1209
custom_message = 'delete module(s) from'
1210
end
1211
1212
case # error handling based on the existence / permissions of the fav_modules file
1213
when !exists
1214
print_warning("Unable to #{custom_message} the favorite modules file because it does not exist")
1215
return
1216
when !writable
1217
print_error("Unable to #{custom_message} the favorite modules file because it is not writable")
1218
return
1219
when !readable
1220
unless delete_all
1221
print_error("Unable to #{custom_message} the favorite modules file because it is not readable")
1222
return
1223
end
1224
when contents.empty?
1225
print_warning("Unable to #{custom_message} the favorite modules file because it is already empty")
1226
return
1227
end
1228
1229
if delete_all
1230
File.write(favs_file, '')
1231
print_good("Favorite modules file cleared")
1232
return
1233
end
1234
1235
modules = modules.uniq # prevent modules from being deleted more than once
1236
contents = contents.split
1237
modules.each do |name|
1238
mod = framework.modules.create(name)
1239
if (mod == nil)
1240
print_error("Invalid module: #{name}")
1241
next
1242
end
1243
1244
unless contents.include?(mod.fullname)
1245
print_warning("Module #{mod.fullname} cannot be deleted because it is not in the favorite modules file")
1246
next
1247
end
1248
1249
contents.delete(mod.fullname)
1250
print_status("Removing #{mod.fullname} from the favorite modules file")
1251
end
1252
1253
# clear the contents of the fav_modules file if removing the module(s) makes it empty
1254
if contents.length == 0
1255
File.write(favs_file, '')
1256
return
1257
end
1258
1259
File.open(favs_file, 'w') { |file| file.puts(contents.join("\n")) }
1260
end
1261
1262
#
1263
# Helper method for cmd_favorite that checks if the fav_modules file exists and is readable / writable
1264
#
1265
def favorite_check_fav_modules(favs_file)
1266
exists = false
1267
writable = false
1268
readable = false
1269
contents = ''
1270
1271
if File.exist?(favs_file)
1272
exists = true
1273
end
1274
1275
if File.writable?(favs_file)
1276
writable = true
1277
end
1278
1279
if File.readable?(favs_file)
1280
readable = true
1281
contents = File.read(favs_file)
1282
end
1283
1284
return exists, writable, readable, contents
1285
end
1286
1287
#
1288
# Add modules to or delete modules from the fav_modules file
1289
#
1290
def cmd_favorite(*args)
1291
valid_custom_args = ['-c', '-d', '-l']
1292
favs_file = Msf::Config.fav_modules_file
1293
1294
# always display the help banner if -h is provided or if multiple options are provided
1295
if args.include?('-h') || args.select{ |arg| arg if valid_custom_args.include?(arg) }.length > 1
1296
cmd_favorite_help
1297
return
1298
end
1299
1300
# if no arguments were provided, check if there is an active module to add
1301
if args.empty?
1302
unless active_module
1303
print_error('No module has been provided to favorite.')
1304
cmd_favorite_help
1305
return
1306
end
1307
1308
args = [active_module.fullname]
1309
favorite_add(args, favs_file)
1310
return
1311
end
1312
1313
case args[0]
1314
when '-c'
1315
args.delete('-c')
1316
unless args.empty?
1317
print_error('Option `-c` does not support arguments.')
1318
cmd_favorite_help
1319
return
1320
end
1321
1322
favorite_del(args, true, favs_file)
1323
when '-d'
1324
args.delete('-d')
1325
if args.empty?
1326
unless active_module
1327
print_error('No module has been provided to delete.')
1328
cmd_favorite_help
1329
return
1330
end
1331
1332
args = [active_module.fullname]
1333
end
1334
1335
favorite_del(args, false, favs_file)
1336
when '-l'
1337
args.delete('-l')
1338
unless args.empty?
1339
print_error('Option `-l` does not support arguments.')
1340
cmd_favorite_help
1341
return
1342
end
1343
cmd_show('favorites')
1344
else # no valid options, but there are arguments
1345
if args[0].start_with?('-')
1346
print_error('Invalid option provided')
1347
cmd_favorite_help
1348
return
1349
end
1350
1351
favorite_add(args, favs_file)
1352
end
1353
end
1354
1355
def cmd_favorites_help
1356
print_line 'Usage: favorites'
1357
print_line
1358
print_line 'Print the list of favorite modules (alias for `show favorites`)'
1359
print_line 'You can use the %grnfavorite%clr command to add the current module to your favorites list'
1360
print @@favorites_opts.usage
1361
end
1362
1363
#
1364
# Print the list of favorite modules from the fav_modules file (alias for `show favorites`)
1365
#
1366
def cmd_favorites(*args)
1367
if args.empty?
1368
cmd_show('favorites')
1369
return
1370
end
1371
1372
# always display the help banner if the command is called with arguments
1373
unless args.include?('-h')
1374
print_error('Invalid option(s) provided')
1375
end
1376
1377
cmd_favorites_help
1378
end
1379
1380
#
1381
# Tab complete module names
1382
#
1383
def tab_complete_module(str, words)
1384
res = []
1385
module_metadata = Msf::Modules::Metadata::Cache.instance.get_metadata
1386
module_metadata.each do |m|
1387
res << "#{m.type}/#{m.ref_name}"
1388
end
1389
framework.modules.module_types.each do |mtyp|
1390
mset = framework.modules.module_names(mtyp)
1391
mset.each do |mref|
1392
res << mtyp + '/' + mref
1393
end
1394
end
1395
1396
return dangerzone_modules_to_codenames(res.sort) if dangerzone_active?
1397
return res.uniq.sort
1398
end
1399
1400
def print_april_fools_module_use
1401
return unless ENV['APRILFOOLSMODULEUSE'] || Time.now.strftime("%m%d") == "0401"
1402
1403
banner = Msf::Ui::Banner.readfile('help-using-a-module.txt')
1404
print_line("%grn#{banner}%clr")
1405
end
1406
1407
#
1408
# Convert squirrel names back to regular module names
1409
#
1410
def dangerzone_codename_to_module(args)
1411
return args unless dangerzone_active? && args.length > 0 && args[0].length > 0
1412
return args unless args[0] =~ /^[A-Z]/
1413
args[0] = dangerzone_codename_to_module_name(args[0])
1414
args
1415
end
1416
1417
#
1418
# Determine if dangerzone mode is active via date or environment variable
1419
#
1420
def dangerzone_active?
1421
active = Time.now.strftime("%m%d") == "0401" || Rex::Compat.getenv('DANGERZONE').to_i > 0
1422
if active && @dangerzone_map.nil?
1423
dangerzone_build_map
1424
end
1425
active
1426
end
1427
1428
#
1429
# Convert module names to squirrel names
1430
#
1431
def dangerzone_modules_to_codenames(names)
1432
(names + @dangerzone_map.keys.grep(/^[A-Z]+/)).sort
1433
end
1434
1435
def dangerzone_codename_to_module_name(cname)
1436
@dangerzone_map[cname] || cname
1437
end
1438
1439
def dangerzone_module_name_to_codename(mname)
1440
@dangerzone_map[mname] || mname
1441
end
1442
1443
def dangerzone_build_map
1444
return unless @dangerzone_map.nil?
1445
1446
@dangerzone_map = {}
1447
1448
res = []
1449
%W{exploit auxiliary}.each do |mtyp|
1450
mset = framework.modules.module_names(mtyp)
1451
mset.each do |mref|
1452
res << mtyp + '/' + mref
1453
end
1454
end
1455
1456
words_a = ::File.readlines(::File.join(
1457
::Msf::Config.data_directory, "wordlists", "dangerzone_a.txt"
1458
)).map{|line| line.strip.upcase}
1459
1460
words_b = ::File.readlines(::File.join(
1461
::Msf::Config.data_directory, "wordlists", "dangerzone_b.txt"
1462
)).map{|line| line.strip.upcase}
1463
1464
aidx = -1
1465
bidx = -1
1466
1467
res.sort.each do |mname|
1468
word_a = words_a[ (aidx += 1) % words_a.length ]
1469
word_b = words_b[ (bidx += 1) % words_b.length ]
1470
cname = word_a + word_b
1471
1472
while @dangerzone_map[cname]
1473
aidx += 1
1474
word_a = words_a[ (aidx += 1) % words_a.length ]
1475
cname = word_a + word_b
1476
end
1477
1478
@dangerzone_map[mname] = cname
1479
@dangerzone_map[cname] = mname
1480
end
1481
end
1482
1483
#
1484
# Module list enumeration
1485
#
1486
1487
def show_encoders # :nodoc:
1488
# If an active module has been selected and it's an exploit, get the
1489
# list of compatible encoders and display them
1490
if (active_module and active_module.exploit? == true)
1491
show_module_metadata('Compatible Encoders', active_module.compatible_encoders)
1492
else
1493
show_module_metadata('Encoders', 'encoder')
1494
end
1495
end
1496
1497
def show_nops # :nodoc:
1498
show_module_metadata('NOP Generators', 'nop')
1499
end
1500
1501
def show_exploits # :nodoc:
1502
show_module_metadata('Exploits', 'exploit')
1503
end
1504
1505
def show_payloads # :nodoc:
1506
# If an active module has been selected and it's an exploit, get the
1507
# list of compatible payloads and display them
1508
if active_module && (active_module.exploit? || active_module.evasion?)
1509
@@payload_show_results = active_module.compatible_payloads
1510
1511
show_module_metadata('Compatible Payloads', @@payload_show_results)
1512
else
1513
# show_module_set(‘Payloads’, framework.payloads, regex, minrank, opts)
1514
show_module_metadata('Payloads', 'payload')
1515
end
1516
end
1517
1518
def show_auxiliary # :nodoc:
1519
show_module_metadata('Auxiliary','auxiliary')
1520
end
1521
1522
def show_post # :nodoc:
1523
show_module_metadata('Post','post')
1524
end
1525
1526
def show_evasion # :nodoc:
1527
show_module_metadata('Evasion','evasion')
1528
end
1529
1530
def show_favorites # :nodoc:
1531
favs_file = Msf::Config.fav_modules_file
1532
1533
unless File.exist?(favs_file)
1534
print_error("The favorite modules file does not exist")
1535
return
1536
end
1537
1538
if File.zero?(favs_file)
1539
print_warning("The favorite modules file is empty")
1540
return
1541
end
1542
1543
unless File.readable?(favs_file)
1544
print_error("Unable to read from #{favs_file}")
1545
return
1546
end
1547
1548
# create module set using the saved modules
1549
fav_modules = {}
1550
1551
# get the full module names from the favorites file and use then to search the MetaData Cache for matching modules
1552
saved_favs = File.readlines(favs_file).map(&:strip)
1553
saved_favs.each do |mod|
1554
# populate hash with module fullname and module object
1555
fav_modules[mod] = framework.modules[mod]
1556
end
1557
1558
fav_modules.each do |fullname, mod_obj|
1559
if mod_obj.nil?
1560
print_warning("#{favs_file} contains a module that can not be found - #{fullname}.")
1561
end
1562
end
1563
1564
# find cache module instance and add it to @module_search_results
1565
@module_search_results = Msf::Modules::Metadata::Cache.instance.find('fullname' => [saved_favs, []])
1566
1567
# This scenario is for when a module fullname is a substring of other module fullnames
1568
# Example, searching for the payload/windows/meterpreter/reverse_tcp module can result in matches for:
1569
# - windows/meterpreter/reverse_tcp_allports
1570
# - windows/meterpreter/reverse_tcp_dns
1571
# So if @module_search_results is greater than the amount of fav_modules, we need to filter the results to be more accurate
1572
if fav_modules.length < @module_search_results.length
1573
filtered_results = []
1574
fav_modules.each do |fullname, _mod_obj|
1575
filtered_results << @module_search_results.select do |search_result|
1576
search_result.fullname == fullname
1577
end
1578
end
1579
@module_search_results = filtered_results.flatten.sort_by(&:fullname)
1580
end
1581
@module_search_results_with_usage_metadata = @module_search_results.map { |mod| { mod: mod, datastore: {} } }
1582
1583
show_module_metadata('Favorites', fav_modules)
1584
print_module_search_results_usage
1585
end
1586
1587
def show_missing(mod) # :nodoc:
1588
mod_opt = Serializer::ReadableText.dump_options(mod, ' ', true)
1589
print("\nModule options (#{mod.fullname}):\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
1590
1591
# If it's an exploit and a payload is defined, create it and
1592
# display the payload's options
1593
if (mod.exploit? and mod.datastore['PAYLOAD'])
1594
p = framework.payloads.create(mod.datastore['PAYLOAD'])
1595
1596
if (!p)
1597
print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
1598
return
1599
end
1600
1601
p.share_datastore(mod.datastore)
1602
1603
if (p)
1604
p_opt = Serializer::ReadableText.dump_options(p, ' ', true)
1605
print("\nPayload options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
1606
end
1607
end
1608
end
1609
1610
def show_global_options
1611
columns = [ 'Option', 'Current Setting', 'Description' ]
1612
tbl = Table.new(
1613
Table::Style::Default,
1614
'Header' => 'Global Options:',
1615
'Prefix' => "\n",
1616
'Postfix' => "\n",
1617
'Columns' => columns
1618
)
1619
[
1620
[ 'ConsoleLogging', framework.datastore['ConsoleLogging'] || "false", 'Log all console input and output' ],
1621
[ 'LogLevel', framework.datastore['LogLevel'] || "0", 'Verbosity of logs (default 0, max 3)' ],
1622
[ 'MinimumRank', framework.datastore['MinimumRank'] || "0", 'The minimum rank of exploits that will run without explicit confirmation' ],
1623
[ 'SessionLogging', framework.datastore['SessionLogging'] || "false", 'Log all input and output for sessions' ],
1624
[ 'SessionTlvLogging', framework.datastore['SessionTlvLogging'] || "false", 'Log all incoming and outgoing TLV packets' ],
1625
[ 'TimestampOutput', framework.datastore['TimestampOutput'] || "false", 'Prefix all console output with a timestamp' ],
1626
[ 'Prompt', framework.datastore['Prompt'] || Msf::Ui::Console::Driver::DefaultPrompt.to_s.gsub(/%.../,"") , "The prompt string" ],
1627
[ 'PromptChar', framework.datastore['PromptChar'] || Msf::Ui::Console::Driver::DefaultPromptChar.to_s.gsub(/%.../,""), "The prompt character" ],
1628
[ 'PromptTimeFormat', framework.datastore['PromptTimeFormat'] || Time::DATE_FORMATS[:db].to_s, 'Format for timestamp escapes in prompts' ],
1629
[ 'MeterpreterPrompt', framework.datastore['MeterpreterPrompt'] || '%undmeterpreter%clr', 'The meterpreter prompt string' ],
1630
].each { |r| tbl << r }
1631
1632
print(tbl.to_s)
1633
end
1634
1635
def show_targets(mod) # :nodoc:
1636
case mod
1637
when Msf::Exploit
1638
mod_targs = Serializer::ReadableText.dump_exploit_targets(mod, '', "\nExploit targets:")
1639
print("#{mod_targs}\n") if (mod_targs and mod_targs.length > 0)
1640
when Msf::Evasion
1641
mod_targs = Serializer::ReadableText.dump_evasion_targets(mod, '', "\nEvasion targets:")
1642
print("#{mod_targs}\n") if (mod_targs and mod_targs.length > 0)
1643
end
1644
end
1645
1646
def show_actions(mod) # :nodoc:
1647
mod_actions = Serializer::ReadableText.dump_module_actions(mod, ' ')
1648
print("\n#{mod.type.capitalize} actions:\n\n#{mod_actions}\n") if (mod_actions and mod_actions.length > 0)
1649
end
1650
1651
def show_advanced_options(mod) # :nodoc:
1652
mod_opt = Serializer::ReadableText.dump_advanced_options(mod, ' ')
1653
print("\nModule advanced options (#{mod.fullname}):\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
1654
1655
# If it's an exploit and a payload is defined, create it and
1656
# display the payload's options
1657
if (mod.exploit? and mod.datastore['PAYLOAD'])
1658
p = framework.payloads.create(mod.datastore['PAYLOAD'])
1659
1660
if (!p)
1661
print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
1662
return
1663
end
1664
1665
p.share_datastore(mod.datastore)
1666
1667
if (p)
1668
p_opt = Serializer::ReadableText.dump_advanced_options(p, ' ')
1669
print("\nPayload advanced options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
1670
end
1671
end
1672
print("\nView the full module info with the #{Msf::Ui::Tip.highlight('info')}, or #{Msf::Ui::Tip.highlight('info -d')} command.\n\n")
1673
end
1674
1675
def show_evasion_options(mod) # :nodoc:
1676
mod_opt = Serializer::ReadableText.dump_evasion_options(mod, ' ')
1677
print("\nModule evasion options:\n\n#{mod_opt}\n") if (mod_opt and mod_opt.length > 0)
1678
1679
# If it's an exploit and a payload is defined, create it and
1680
# display the payload's options
1681
if (mod.evasion? and mod.datastore['PAYLOAD'])
1682
p = framework.payloads.create(mod.datastore['PAYLOAD'])
1683
1684
if (!p)
1685
print_error("Invalid payload defined: #{mod.datastore['PAYLOAD']}\n")
1686
return
1687
end
1688
1689
p.share_datastore(mod.datastore)
1690
1691
if (p)
1692
p_opt = Serializer::ReadableText.dump_evasion_options(p, ' ')
1693
print("\nPayload evasion options (#{mod.datastore['PAYLOAD']}):\n\n#{p_opt}\n") if (p_opt and p_opt.length > 0)
1694
end
1695
end
1696
end
1697
1698
def show_plugins # :nodoc:
1699
tbl = Table.new(
1700
Table::Style::Default,
1701
'Header' => 'Loaded Plugins',
1702
'Prefix' => "\n",
1703
'Postfix' => "\n",
1704
'Columns' => [ 'Name', 'Description' ]
1705
)
1706
1707
framework.plugins.each { |plugin|
1708
tbl << [ plugin.name, plugin.desc ]
1709
}
1710
1711
# create an instance of core to call the list_plugins
1712
core = Msf::Ui::Console::CommandDispatcher::Core.new(driver)
1713
core.list_plugins
1714
print(tbl.to_s)
1715
end
1716
1717
# @param [table_name] used to name table
1718
# @param [module_filter] this will either be a modules fullname, or it will be an Array(show payloads/encoders)
1719
# or a Hash(show favorites) containing fullname
1720
# @param [compatible_mod] handles logic for if there is an active module when the
1721
# `show` command is run
1722
#
1723
# Handles the filtering of modules that will be generated into a table
1724
def show_module_metadata(table_name, module_filter)
1725
count = -1
1726
tbl = generate_module_table(table_name)
1727
1728
if module_filter.is_a?(Array) || module_filter.is_a?(Hash)
1729
module_filter.sort.each do |_mod_fullname, mod_obj|
1730
mod = nil
1731
1732
begin
1733
mod = mod_obj.new
1734
rescue ::Exception
1735
end
1736
next unless mod
1737
1738
count += 1
1739
tbl << add_record(mod, count, true)
1740
end
1741
else
1742
results = Msf::Modules::Metadata::Cache.instance.find(
1743
'type' => [[module_filter], []]
1744
)
1745
# Loop over each module and gather data
1746
results.each do |mod, _value|
1747
count += 1
1748
tbl << add_record(mod, count, false)
1749
end
1750
end
1751
print(tbl.to_s)
1752
end
1753
1754
# @param [mod] current module being passed in
1755
# @param [count] passes the count for each record
1756
# @param [compatible_mod] handles logic for if there is an active module when the
1757
# `show` command is run
1758
#
1759
# Adds a record for a table, also handle logic for whether the module is currently
1760
# handling compatible payloads/encoders
1761
def add_record(mod, count, compatible_mod)
1762
if compatible_mod
1763
check = mod.has_check? ? 'Yes' : 'No'
1764
else
1765
check = mod.check ? 'Yes' : 'No'
1766
end
1767
[
1768
count,
1769
mod.fullname,
1770
mod.disclosure_date.nil? ? '' : mod.disclosure_date.strftime('%Y-%m-%d'),
1771
mod.rank,
1772
check,
1773
mod.name
1774
]
1775
end
1776
1777
def generate_module_table(type, search_terms = [], row_filter = nil) # :nodoc:
1778
table_hierarchy_formatters = framework.features.enabled?(Msf::FeatureManager::HIERARCHICAL_SEARCH_TABLE) ? [Msf::Ui::Console::TablePrint::BlankFormatter.new] : []
1779
1780
Table.new(
1781
Table::Style::Default,
1782
'Header' => type,
1783
'Prefix' => "\n",
1784
'Postfix' => "\n",
1785
'SearchTerm' => row_filter,
1786
'SortIndex' => -1,
1787
# For now, don't perform any word wrapping on the search table as it breaks the workflow of
1788
# copying module names in conjunction with the `use <paste-buffer>` command
1789
'WordWrap' => false,
1790
'Columns' => [
1791
'#',
1792
'Name',
1793
'Disclosure Date',
1794
'Rank',
1795
'Check',
1796
'Description'
1797
],
1798
'ColProps' => {
1799
'Rank' => {
1800
'Formatters' => [
1801
*table_hierarchy_formatters,
1802
Msf::Ui::Console::TablePrint::RankFormatter.new
1803
],
1804
'Stylers' => [
1805
Msf::Ui::Console::TablePrint::RankStyler.new
1806
]
1807
},
1808
'Name' => {
1809
'Strip' => false,
1810
'Stylers' => [Msf::Ui::Console::TablePrint::HighlightSubstringStyler.new(search_terms)]
1811
},
1812
'Check' => {
1813
'Formatters' => [
1814
*table_hierarchy_formatters,
1815
]
1816
},
1817
'Disclosure Date' => {
1818
'Formatters' => [
1819
*table_hierarchy_formatters,
1820
]
1821
},
1822
'Description' => {
1823
'Stylers' => [
1824
Msf::Ui::Console::TablePrint::HighlightSubstringStyler.new(search_terms)
1825
]
1826
}
1827
}
1828
)
1829
end
1830
end
1831
end
1832
end
1833
end
1834
end
1835
1836