Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rapid7
GitHub Repository: rapid7/metasploit-framework
Path: blob/master/plugins/alias.rb
19566 views
1
require 'rex/text/table'
2
3
module Msf
4
class Plugin::Alias < Msf::Plugin
5
class AliasCommandDispatcher
6
include Msf::Ui::Console::CommandDispatcher
7
8
attr_reader :aliases
9
10
def initialize(driver)
11
super(driver)
12
@aliases = {}
13
end
14
15
def name
16
'Alias'
17
end
18
19
@@alias_opts = Rex::Parser::Arguments.new(
20
'-h' => [ false, 'Help banner.' ],
21
'-c' => [ true, 'Clear an alias (* to clear all).'],
22
'-f' => [ true, 'Force an alias assignment.' ]
23
)
24
#
25
# Returns the hash of commands supported by this dispatcher.
26
#
27
# driver.dispatcher_stack[3].commands
28
def commands
29
{
30
'alias' => 'create or view an alias.'
31
# "alias_clear" => "clear an alias (or all aliases).",
32
# "alias_force" => "Force an alias (such as to override)"
33
}.merge(aliases) # make aliased commands available as commands of their own
34
end
35
36
#
37
# the main alias command handler
38
#
39
# usage: alias [options] [name [value]]
40
def cmd_alias(*args)
41
# we parse args manually instead of using @@alias.opts.parse to handle special cases
42
case args.length
43
when 0 # print the list of current aliases
44
if @aliases.empty?
45
return print_status('No aliases currently defined')
46
else
47
tbl = Rex::Text::Table.new(
48
'Header' => 'Current Aliases',
49
'Prefix' => "\n",
50
'Postfix' => "\n",
51
'Columns' => [ '', 'Alias Name', 'Alias Value' ]
52
)
53
# add 'alias' in front of each row so that the output can be copy pasted into an rc file if desired
54
@aliases.each_pair do |key, val|
55
tbl << ['alias', key, val]
56
end
57
print_status("Total aliases: #{@aliases.length}")
58
return print(tbl.to_s)
59
60
end
61
when 1 # display the alias if one matches this name (or help)
62
return cmd_alias_help if (args[0] == '-h') || (args[0] == '--help')
63
64
if @aliases.keys.include?(args[0])
65
print_status("\'#{args[0]}\' is aliased to \'#{@aliases[args[0]]}\'")
66
else
67
print_status("\'#{args[0]}\' is not currently aliased")
68
end
69
else # let's see if we can assign or clear the alias
70
force = false
71
clear = false
72
# if using -f or -c, they must be the first arg, because -f/-c may also show up in the alias
73
# value so we can't do something like if args.include("-f") or delete_if etc
74
# we should never have to force and clear simultaneously.
75
if args[0] == '-f'
76
force = true
77
args.shift
78
elsif args[0] == '-c'
79
clear = true
80
args.shift
81
end
82
name = args.shift
83
# alias name can NEVER be certain reserved words like 'alias', add any other reserved words here
84
# We prevent the user from naming the alias "alias" cuz they could end up unable to clear the aliases,
85
# for example you 'alias -f set unset and then 'alias -f alias sessions', now you're screwed. The byproduct
86
# of this is that it prevents you from aliasing 'alias' to 'alias -f' etc, but that's acceptable
87
reserved_words = [/^alias$/i]
88
reserved_words.each do |regex|
89
if name =~ regex
90
print_error "You cannot use #{name} as the name for an alias, sorry"
91
return false
92
end
93
end
94
95
if clear
96
# clear all aliases if "*"
97
if name == '*'
98
@aliases.each_key do |a|
99
deregister_alias(a)
100
end
101
print_status 'Cleared all aliases'
102
elsif @aliases.keys.include?(name) # clear the named alias if it exists
103
deregister_alias(name)
104
print_status "Cleared alias #{name}"
105
else
106
print_error("#{name} is not a currently active alias")
107
end
108
return
109
end
110
# smash everything that's left together
111
value = args.join(' ')
112
value.strip!
113
# value can NEVER be certain bad words like 'rm -rf /', add any other reserved words here
114
# this is basic idiot protection, not meant to be impervious to subversive intentions
115
reserved_words = [%r{^rm +(-rf|-r +-f|-f +-r) +/.*$}]
116
reserved_words.each do |regex|
117
if value =~ regex
118
print_error "You cannot use #{value} as the value for an alias, sorry"
119
return false
120
end
121
end
122
123
is_valid_alias = valid_alias?(name, value)
124
# print_good "Alias validity = #{is_valid_alias}"
125
is_sys_cmd = Rex::FileUtils.find_full_path(name)
126
is_already_alias = @aliases.keys.include?(name)
127
if is_valid_alias && !is_sys_cmd && !is_already_alias
128
register_alias(name, value)
129
elsif force
130
if !is_valid_alias
131
print_status 'The alias failed validation, but force is set so we allow this. This is often the case'
132
print_status "when for instance 'exploit' is being overridden but msfconsole is not currently in the"
133
print_status 'exploit context (an exploit is not loaded), or you are overriding a system command'
134
end
135
register_alias(name, value)
136
else
137
print_error("#{name} already exists as a system command, use -f to force override") if is_sys_cmd
138
print_error("#{name} is already an alias, use -f to force override") if is_already_alias
139
if !is_valid_alias && !force
140
print_error("'#{name}' is not a permitted name or '#{value}' is not valid/permitted")
141
print_error("It's possible the responding dispatcher isn't loaded yet, try changing to the proper context or using -f to force")
142
end
143
end
144
end
145
end
146
147
def cmd_alias_help
148
print_line 'Usage: alias [options] [name [value]]'
149
print_line
150
print(@@alias_opts.usage)
151
end
152
153
#
154
# Tab completion for the alias command
155
#
156
def cmd_alias_tabs(_str, words)
157
if words.length <= 1
158
# puts "1 word or less"
159
return @@alias_opts.option_keys + tab_complete_aliases_and_commands
160
else
161
# puts "more than 1 word"
162
return tab_complete_aliases_and_commands
163
end
164
end
165
166
private
167
168
#
169
# do everything needed to add an alias of +name+ having the value +value+
170
#
171
def register_alias(name, value)
172
# TODO: begin rescue?
173
# TODO: security concerns since we are using eval
174
175
# define some class instance methods
176
class_eval do
177
# define a class instance method that will respond for the alias
178
define_method "cmd_#{name}" do |*args|
179
# just replace the alias w/the alias' value and run that
180
driver.run_single("#{value} #{args.join(' ')}")
181
end
182
# define a class instance method that will tab complete the aliased command
183
# we just proxy to the top-level tab complete function and let them handle it
184
define_method "cmd_#{name}_tabs" do |str, words|
185
# we need to repair the tab complete string/words and pass back
186
# replace alias name with the root alias value
187
value_words = value.split(/[\s\t\n]+/) # in case value is e.g. 'sessions -l'
188
# valwords is now [sessions,-l]
189
words[0] = value_words[0]
190
# words[0] is now 'sessions' (was 'sue')
191
value_words.shift # valwords is now ['-l']
192
# insert any remaining parts of value and rebuild the line
193
line = words.join(' ') + ' ' + value_words.join(' ') + ' ' + str
194
195
[driver.tab_complete(line.strip), :override_completions]
196
end
197
# add a cmd_#{name}_help method
198
define_method "cmd_#{name}_help" do |*_args|
199
driver.run_single("help #{value}")
200
end
201
end
202
# add the alias to the list
203
@aliases[name] = value
204
end
205
206
#
207
# do everything required to remove an alias of name +name+
208
#
209
def deregister_alias(name)
210
class_eval do
211
# remove the class methods we created when the alias was registered
212
remove_method("cmd_#{name}")
213
remove_method("cmd_#{name}_tabs")
214
remove_method("cmd_#{name}_help")
215
end
216
# remove the alias from the list of active aliases
217
@aliases.delete(name)
218
end
219
220
#
221
# Validate a proposed alias with the +name+ and having the value +value+
222
#
223
def valid_alias?(name, value)
224
# print_good "Assessing validay for #{name} and #{value}"
225
# we validate two things, the name and the value
226
227
### name
228
# we don't check if this alias name exists or if it's a console command already etc as -f can override
229
# that so those need to be checked externally, we pretty much just check to see if the name is sane
230
name.strip!
231
bad_words = [/\*/] # add any additional "bad word" regexes here
232
bad_words.each do |regex|
233
# don't mess around, just return false in this case, prevents wasted processing
234
return false if name =~ regex
235
end
236
237
### value
238
# value is considered valid if it's a ref to a valid console cmd, a system executable, or an existing
239
# alias AND isn't a "bad word"
240
# Here we check for "bad words" to avoid for the value...value would have to NOT match these regexes
241
# this is just basic idiot protection
242
value.strip!
243
bad_words = [/^msfconsole$/]
244
bad_words.each do |regex|
245
# don't mess around, just return false if we match
246
return false if value =~ regex
247
end
248
249
# we're only gonna validate the first part of the cmd, e.g. just ls from "ls -lh"
250
value = value.split(' ').first
251
return true if @aliases.keys.include?(value)
252
253
[value, value + '.exe'].each do |cmd|
254
return true if Rex::FileUtils.find_full_path(cmd)
255
end
256
257
# gather all the current commands the driver's dispatcher's have & check 'em
258
driver.dispatcher_stack.each do |dispatcher|
259
next unless dispatcher.respond_to?(:commands)
260
next if dispatcher.commands.nil?
261
next if dispatcher.commands.empty?
262
263
if dispatcher.respond_to?("cmd_#{value.split(' ').first}")
264
# print_status "Dispatcher (#{dispatcher.name}) responds to cmd_#{value.split(" ").first}"
265
return true
266
end
267
end
268
269
false
270
end
271
272
#
273
# Provide tab completion list for aliases and commands
274
#
275
def tab_complete_aliases_and_commands
276
items = []
277
# gather all the current commands the driver's dispatcher's have
278
driver.dispatcher_stack.each do |dispatcher|
279
next unless dispatcher.respond_to?(:commands)
280
next if (dispatcher.commands.nil? || dispatcher.commands.empty?)
281
282
items.concat(dispatcher.commands.keys)
283
end
284
# add all the current aliases to the list
285
items.concat(@aliases.keys)
286
return items
287
end
288
289
end
290
291
#
292
# The constructor is called when an instance of the plugin is created. The
293
# framework instance that the plugin is being associated with is passed in
294
# the framework parameter. Plugins should call the parent constructor when
295
# inheriting from Msf::Plugin to ensure that the framework attribute on
296
# their instance gets set.
297
#
298
def initialize(framework, opts)
299
super
300
301
## Register the commands above
302
add_console_dispatcher(AliasCommandDispatcher)
303
end
304
305
#
306
# The cleanup routine for plugins gives them a chance to undo any actions
307
# they may have done to the framework. For instance, if a console
308
# dispatcher was added, then it should be removed in the cleanup routine.
309
#
310
def cleanup
311
# If we had previously registered a console dispatcher with the console,
312
# deregister it now.
313
remove_console_dispatcher('Alias')
314
315
# we don't need to remove class methods we added because they were added to
316
# AliasCommandDispatcher class
317
end
318
319
#
320
# This method returns a short, friendly name for the plugin.
321
#
322
def name
323
'alias'
324
end
325
326
#
327
# This method returns a brief description of the plugin. It should be no
328
# more than 60 characters, but there are no hard limits.
329
#
330
def desc
331
'Adds the ability to alias console commands'
332
end
333
334
end
335
end
336
337