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/developer.rb
Views: 11784
1
# -*- coding: binary -*-
2
3
class Msf::Ui::Console::CommandDispatcher::Developer
4
5
include Msf::Ui::Console::CommandDispatcher
6
7
@@irb_opts = Rex::Parser::Arguments.new(
8
'-h' => [false, 'Help menu.' ],
9
'-e' => [true, 'Expression to evaluate.']
10
)
11
12
@@time_opts = Rex::Parser::Arguments.new(
13
['-h', '--help'] => [ false, 'Help banner.' ],
14
'--cpu' => [false, 'Profile the CPU usage.'],
15
'--memory' => [false, 'Profile the memory usage.']
16
)
17
18
@@_servicemanager_opts = Rex::Parser::Arguments.new(
19
['-l', '--list'] => [false, 'View the currently running services' ]
20
)
21
22
@@_historymanager_opts = Rex::Parser::Arguments.new(
23
'-h' => [false, 'Help menu.' ],
24
['-l', '--list'] => [true, 'View the current history manager contexts.'],
25
['-d', '--debug'] => [true, 'Debug the current history manager contexts.']
26
)
27
28
def initialize(driver)
29
super
30
@modified_files = modified_file_paths(print_errors: false)
31
end
32
33
def name
34
'Developer'
35
end
36
37
def commands
38
commands = {
39
'irb' => 'Open an interactive Ruby shell in the current context',
40
'pry' => 'Open the Pry debugger on the current module or Framework',
41
'edit' => 'Edit the current module or a file with the preferred editor',
42
'reload_lib' => 'Reload Ruby library files from specified paths',
43
'log' => 'Display framework.log paged to the end if possible',
44
'time' => 'Time how long it takes to run a particular command'
45
}
46
if framework.features.enabled?(Msf::FeatureManager::MANAGER_COMMANDS)
47
commands['_servicemanager'] = 'Interact with the Rex::ServiceManager'
48
commands['_historymanager'] = 'Interact with the Rex::Ui::Text::Shell::HistoryManager'
49
end
50
commands
51
end
52
53
def local_editor
54
framework.datastore['LocalEditor'] ||
55
Rex::Compat.getenv('VISUAL') ||
56
Rex::Compat.getenv('EDITOR') ||
57
Msf::Util::Helper.which('vim') ||
58
Msf::Util::Helper.which('vi')
59
end
60
61
def local_pager
62
framework.datastore['LocalPager'] ||
63
Rex::Compat.getenv('PAGER') ||
64
Rex::Compat.getenv('MANPAGER') ||
65
Msf::Util::Helper.which('less') ||
66
Msf::Util::Helper.which('more')
67
end
68
69
# XXX: This will try to reload *any* .rb and break on modules
70
def reload_file(path, print_errors: true)
71
full_path = File.expand_path(path)
72
73
unless File.exist?(full_path) && full_path.end_with?('.rb')
74
print_error("#{full_path} must exist and be a .rb file") if print_errors
75
return
76
end
77
78
# The file must exist to reach this, so we try our best here
79
if full_path.start_with?(Msf::Config.module_directory, Msf::Config.user_module_directory)
80
print_error('Reloading Metasploit modules is not supported (try "reload")') if print_errors
81
return
82
end
83
84
print_status("Reloading #{full_path}")
85
load full_path
86
end
87
88
# @return [Array<String>] The list of modified file paths since startup
89
def modified_file_paths(print_errors: true)
90
files, is_success = modified_files
91
92
unless is_success
93
print_error("Git is not available") if print_errors
94
files = []
95
end
96
97
@modified_files ||= []
98
@modified_files |= files.map do |file|
99
next if file.end_with?('_spec.rb') || file.end_with?("spec_helper.rb")
100
File.join(Msf::Config.install_root, file)
101
end.compact
102
@modified_files
103
end
104
105
def cmd_irb_help
106
print_line 'Usage: irb'
107
print_line
108
print_line 'Open an interactive Ruby shell in the current context.'
109
print @@irb_opts.usage
110
end
111
112
#
113
# Open an interactive Ruby shell in the current context
114
#
115
def cmd_irb(*args)
116
expressions = []
117
118
# Parse the command options
119
@@irb_opts.parse(args) do |opt, idx, val|
120
case opt
121
when '-e'
122
expressions << val
123
when '-h'
124
cmd_irb_help
125
return false
126
end
127
end
128
129
if expressions.empty?
130
print_status('Starting IRB shell...')
131
132
framework.history_manager.with_context(name: :irb) do
133
begin
134
if active_module
135
print_status("You are in #{active_module.fullname}\n")
136
Rex::Ui::Text::IrbShell.new(active_module).run
137
else
138
print_status("You are in the \"framework\" object\n")
139
Rex::Ui::Text::IrbShell.new(framework).run
140
end
141
rescue
142
print_error("Error during IRB: #{$!}\n\n#{$@.join("\n")}")
143
end
144
end
145
146
# Reset tab completion
147
if (driver.input.supports_readline)
148
driver.input.reset_tab_completion
149
end
150
else
151
# XXX: No vprint_status here either
152
if framework.datastore['VERBOSE'].to_s == 'true'
153
print_status("You are executing expressions in #{binding.receiver}")
154
end
155
156
expressions.each { |expression| eval(expression, binding) }
157
end
158
end
159
160
#
161
# Tab completion for the irb command
162
#
163
def cmd_irb_tabs(_str, words)
164
return [] if words.length > 1
165
166
@@irb_opts.option_keys
167
end
168
169
def cmd_pry_help
170
print_line 'Usage: pry'
171
print_line
172
print_line 'Open the Pry debugger on the current module or Framework.'
173
print_line
174
end
175
176
#
177
# Open the Pry debugger on the current module or Framework
178
#
179
def cmd_pry(*args)
180
if args.include?('-h')
181
cmd_pry_help
182
return
183
end
184
185
begin
186
require 'pry'
187
rescue LoadError
188
print_error('Failed to load Pry, try "gem install pry"')
189
return
190
end
191
192
print_status('Starting Pry shell...')
193
194
Pry.config.history_load = false
195
framework.history_manager.with_context(history_file: Msf::Config.pry_history, name: :pry) do
196
if active_module
197
print_status("You are in the \"#{active_module.fullname}\" module object\n")
198
active_module.pry
199
else
200
print_status("You are in the \"framework\" object\n")
201
framework.pry
202
end
203
end
204
end
205
206
def cmd_edit_help
207
print_line 'Usage: edit [file/to/edit]'
208
print_line
209
print_line "Edit the currently active module or a local file with #{local_editor}."
210
print_line 'To change the preferred editor, you can "setg LocalEditor".'
211
print_line 'If a library file is specified, it will automatically be reloaded after editing.'
212
print_line 'Otherwise, you can reload the active module with "reload" or "rerun".'
213
print_line
214
end
215
216
#
217
# Edit the current module or a file with the preferred editor
218
#
219
def cmd_edit(*args)
220
editing_module = false
221
222
if args.length > 0
223
path = File.expand_path(args[0])
224
elsif active_module
225
editing_module = true
226
path = active_module.file_path
227
end
228
229
unless path
230
print_error('Nothing to edit. Try using a module first or specifying a library file to edit.')
231
return
232
end
233
234
editor = local_editor
235
236
unless editor
237
# ed(1) is the standard editor
238
editor = 'ed'
239
print_warning("LocalEditor or $VISUAL/$EDITOR should be set. Falling back on #{editor}.")
240
end
241
242
# XXX: No vprint_status in this context?
243
# XXX: VERBOSE is a string instead of Bool??
244
print_status("Launching #{editor} #{path}") if framework.datastore['VERBOSE'].to_s == 'true'
245
246
unless system(*editor.split, path)
247
print_error("Could not execute #{editor} #{path}")
248
return
249
end
250
251
return if editing_module
252
253
reload_file(path)
254
end
255
256
#
257
# Tab completion for the edit command
258
#
259
def cmd_edit_tabs(str, words)
260
tab_complete_filenames(str, words)
261
end
262
263
def cmd_reload_lib_help
264
cmd_reload_lib('-h')
265
end
266
267
#
268
# Reload Ruby library files from specified paths
269
#
270
def cmd_reload_lib(*args)
271
files = []
272
options = OptionParser.new do |opts|
273
opts.banner = 'Usage: reload_lib lib/to/reload.rb [...]'
274
opts.separator ''
275
opts.separator 'Reload Ruby library files from specified paths.'
276
opts.separator ''
277
278
opts.on '-h', '--help', 'Help banner.' do
279
return print(opts.help)
280
end
281
282
opts.on '-a', '--all', 'Reload all* changed files in your current Git working tree.
283
*Excludes modules and non-Ruby files.' do
284
files.concat(modified_file_paths)
285
end
286
end
287
288
# The remaining unparsed arguments are files
289
files.concat(options.order(args))
290
files.uniq!
291
292
return print(options.help) if files.empty?
293
294
files.each do |file|
295
reload_file(file)
296
rescue ScriptError, StandardError => e
297
print_error("Error while reloading file #{file.inspect}: #{e}:\n#{e.backtrace.to_a.map { |line| " #{line}" }.join("\n")}")
298
end
299
end
300
301
#
302
# Tab completion for the reload_lib command
303
#
304
def cmd_reload_lib_tabs(str, words)
305
tab_complete_filenames(str, words)
306
end
307
308
def cmd_log_help
309
print_line 'Usage: log'
310
print_line
311
print_line 'Display framework.log paged to the end if possible.'
312
print_line 'To change the preferred pager, you can "setg LocalPager".'
313
print_line 'For full effect, "setg LogLevel 3" before running modules.'
314
print_line
315
print_line "Log location: #{File.join(Msf::Config.log_directory, 'framework.log')}"
316
print_line
317
end
318
319
#
320
# Display framework.log paged to the end if possible
321
#
322
def cmd_log(*args)
323
path = File.join(Msf::Config.log_directory, 'framework.log')
324
325
# XXX: +G isn't portable and may hang on large files
326
pager = local_pager.to_s.include?('less') ? "#{local_pager} +G" : local_pager
327
328
unless pager
329
pager = 'tail -n 50'
330
print_warning("LocalPager or $PAGER/$MANPAGER should be set. Falling back on #{pager}.")
331
end
332
333
# XXX: No vprint_status in this context?
334
# XXX: VERBOSE is a string instead of Bool??
335
print_status("Launching #{pager} #{path}") if framework.datastore['VERBOSE'].to_s == 'true'
336
337
unless system(*pager.split, path)
338
print_error("Could not execute #{pager} #{path}")
339
end
340
end
341
342
#
343
# Interact with framework's service manager
344
#
345
def cmd__servicemanager(*args)
346
if args.include?('-h') || args.include?('--help')
347
cmd__servicemanager_help
348
return false
349
end
350
351
opts = {}
352
@@_servicemanager_opts.parse(args) do |opt, idx, val|
353
case opt
354
when '-l', '--list'
355
opts[:list] = true
356
end
357
end
358
359
if opts.empty?
360
opts[:list] = true
361
end
362
363
if opts[:list]
364
table = Rex::Text::Table.new(
365
'Header' => 'Services',
366
'Indent' => 1,
367
'Columns' => ['Id', 'Name', 'References']
368
)
369
Rex::ServiceManager.instance.each.with_index do |(name, instance), id|
370
# TODO: Update rex-core to support querying the reference count
371
table << [id, name, instance.instance_variable_get(:@_references)]
372
end
373
374
if table.rows.empty?
375
print_status("No framework services are currently running.")
376
else
377
print_line(table.to_s)
378
end
379
end
380
end
381
382
#
383
# Tab completion for the _servicemanager command
384
#
385
def cmd__servicemanager_tabs(_str, words)
386
return [] if words.length > 1
387
388
@@_servicemanager_opts.option_keys
389
end
390
391
def cmd__servicemanager_help
392
print_line 'Usage: _servicemanager'
393
print_line
394
print_line 'Manage running framework services'
395
print @@_servicemanager_opts.usage
396
print_line
397
end
398
399
#
400
# Interact with framework's history manager
401
#
402
def cmd__historymanager(*args)
403
if args.include?('-h') || args.include?('--help')
404
cmd__historymanager_help
405
return false
406
end
407
408
opts = {}
409
@@_historymanager_opts.parse(args) do |opt, idx, val|
410
case opt
411
when '-l', '--list'
412
opts[:list] = true
413
when '-d', '--debug'
414
opts[:debug] = val.nil? ? true : val.downcase.start_with?(/t|y/)
415
end
416
end
417
418
if opts.empty?
419
opts[:list] = true
420
end
421
422
if opts.key?(:debug)
423
framework.history_manager._debug = opts[:debug]
424
print_status("HistoryManager debugging is now #{opts[:debug] ? 'on' : 'off'}")
425
end
426
427
if opts[:list]
428
table = Rex::Text::Table.new(
429
'Header' => 'History contexts',
430
'Indent' => 1,
431
'Columns' => ['Id', 'File', 'Name']
432
)
433
framework.history_manager._contexts.each.with_index do |context, id|
434
table << [id, context[:history_file], context[:name]]
435
end
436
437
if table.rows.empty?
438
print_status("No history contexts present.")
439
else
440
print_line(table.to_s)
441
end
442
end
443
end
444
445
#
446
# Tab completion for the _historymanager command
447
#
448
def cmd__historymanager_tabs(_str, words)
449
return [] if words.length > 1
450
451
@@_historymanager_opts.option_keys
452
end
453
454
def cmd__historymanager_help
455
print_line 'Usage: _historymanager'
456
print_line
457
print_line 'Manage the history manager'
458
print @@_historymanager_opts.usage
459
print_line
460
end
461
462
#
463
# Time how long in seconds a command takes to execute
464
#
465
def cmd_time(*args)
466
if args.empty? || args.first == '-h' || args.first == '--help'
467
cmd_time_help
468
return true
469
end
470
471
profiler = nil
472
while args.first == '--cpu' || args.first == '--memory'
473
profiler = args.shift
474
end
475
476
begin
477
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
478
command = Shellwords.shelljoin(args)
479
480
case profiler
481
when '--cpu'
482
Metasploit::Framework::Profiler.record_cpu do
483
driver.run_single(command)
484
end
485
when '--memory'
486
Metasploit::Framework::Profiler.record_memory do
487
driver.run_single(command)
488
end
489
else
490
driver.run_single(command)
491
end
492
ensure
493
end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
494
elapsed_time = end_time - start_time
495
print_good("Command #{command.inspect} completed in #{elapsed_time} seconds")
496
end
497
end
498
499
def cmd_time_help
500
print_line 'Usage: time [options] [command]'
501
print_line
502
print_line 'Time how long a command takes to execute in seconds. Also supports profiling options.'
503
print_line
504
print_line ' Usage:'
505
print_line ' * time db_import ./db_import.html'
506
print_line ' * time show exploits'
507
print_line ' * time reload_all'
508
print_line ' * time missing_command'
509
print_line ' * time --cpu db_import ./db_import.html'
510
print_line ' * time --memory db_import ./db_import.html'
511
print @@time_opts.usage
512
print_line
513
end
514
515
private
516
517
def modified_files
518
# Using an array avoids shelling out, so we avoid escaping/quoting
519
changed_files = %w[git diff --name-only]
520
begin
521
output, status = Open3.capture2e(*changed_files, chdir: Msf::Config.install_root)
522
is_success = status.success?
523
output = output.split("\n")
524
rescue => e
525
elog(e)
526
output = []
527
is_success = false
528
end
529
return output, is_success
530
end
531
end
532
533