require 'rex/text/table'12module Msf3class Plugin::Alias < Msf::Plugin4class AliasCommandDispatcher5include Msf::Ui::Console::CommandDispatcher67attr_reader :aliases89def initialize(driver)10super(driver)11@aliases = {}12end1314def name15'Alias'16end1718@@alias_opts = Rex::Parser::Arguments.new(19'-h' => [ false, 'Help banner.' ],20'-c' => [ true, 'Clear an alias (* to clear all).'],21'-f' => [ true, 'Force an alias assignment.' ]22)23#24# Returns the hash of commands supported by this dispatcher.25#26# driver.dispatcher_stack[3].commands27def commands28{29'alias' => 'create or view an alias.'30# "alias_clear" => "clear an alias (or all aliases).",31# "alias_force" => "Force an alias (such as to override)"32}.merge(aliases) # make aliased commands available as commands of their own33end3435#36# the main alias command handler37#38# usage: alias [options] [name [value]]39def cmd_alias(*args)40# we parse args manually instead of using @@alias.opts.parse to handle special cases41case args.length42when 0 # print the list of current aliases43if @aliases.empty?44return print_status('No aliases currently defined')45else46tbl = Rex::Text::Table.new(47'Header' => 'Current Aliases',48'Prefix' => "\n",49'Postfix' => "\n",50'Columns' => [ '', 'Alias Name', 'Alias Value' ]51)52# add 'alias' in front of each row so that the output can be copy pasted into an rc file if desired53@aliases.each_pair do |key, val|54tbl << ['alias', key, val]55end56print_status("Total aliases: #{@aliases.length}")57return print(tbl.to_s)5859end60when 1 # display the alias if one matches this name (or help)61return cmd_alias_help if (args[0] == '-h') || (args[0] == '--help')6263if @aliases.keys.include?(args[0])64print_status("\'#{args[0]}\' is aliased to \'#{@aliases[args[0]]}\'")65else66print_status("\'#{args[0]}\' is not currently aliased")67end68else # let's see if we can assign or clear the alias69force = false70clear = false71# if using -f or -c, they must be the first arg, because -f/-c may also show up in the alias72# value so we can't do something like if args.include("-f") or delete_if etc73# we should never have to force and clear simultaneously.74if args[0] == '-f'75force = true76args.shift77elsif args[0] == '-c'78clear = true79args.shift80end81name = args.shift82# alias name can NEVER be certain reserved words like 'alias', add any other reserved words here83# We prevent the user from naming the alias "alias" cuz they could end up unable to clear the aliases,84# for example you 'alias -f set unset and then 'alias -f alias sessions', now you're screwed. The byproduct85# of this is that it prevents you from aliasing 'alias' to 'alias -f' etc, but that's acceptable86reserved_words = [/^alias$/i]87reserved_words.each do |regex|88if name =~ regex89print_error "You cannot use #{name} as the name for an alias, sorry"90return false91end92end9394if clear95# clear all aliases if "*"96if name == '*'97@aliases.each_key do |a|98deregister_alias(a)99end100print_status 'Cleared all aliases'101elsif @aliases.keys.include?(name) # clear the named alias if it exists102deregister_alias(name)103print_status "Cleared alias #{name}"104else105print_error("#{name} is not a currently active alias")106end107return108end109# smash everything that's left together110value = args.join(' ')111value.strip!112# value can NEVER be certain bad words like 'rm -rf /', add any other reserved words here113# this is basic idiot protection, not meant to be impervious to subversive intentions114reserved_words = [%r{^rm +(-rf|-r +-f|-f +-r) +/.*$}]115reserved_words.each do |regex|116if value =~ regex117print_error "You cannot use #{value} as the value for an alias, sorry"118return false119end120end121122is_valid_alias = valid_alias?(name, value)123# print_good "Alias validity = #{is_valid_alias}"124is_sys_cmd = Rex::FileUtils.find_full_path(name)125is_already_alias = @aliases.keys.include?(name)126if is_valid_alias && !is_sys_cmd && !is_already_alias127register_alias(name, value)128elsif force129if !is_valid_alias130print_status 'The alias failed validation, but force is set so we allow this. This is often the case'131print_status "when for instance 'exploit' is being overridden but msfconsole is not currently in the"132print_status 'exploit context (an exploit is not loaded), or you are overriding a system command'133end134register_alias(name, value)135else136print_error("#{name} already exists as a system command, use -f to force override") if is_sys_cmd137print_error("#{name} is already an alias, use -f to force override") if is_already_alias138if !is_valid_alias && !force139print_error("'#{name}' is not a permitted name or '#{value}' is not valid/permitted")140print_error("It's possible the responding dispatcher isn't loaded yet, try changing to the proper context or using -f to force")141end142end143end144end145146def cmd_alias_help147print_line 'Usage: alias [options] [name [value]]'148print_line149print(@@alias_opts.usage)150end151152#153# Tab completion for the alias command154#155def cmd_alias_tabs(_str, words)156if words.length <= 1157# puts "1 word or less"158return @@alias_opts.option_keys + tab_complete_aliases_and_commands159else160# puts "more than 1 word"161return tab_complete_aliases_and_commands162end163end164165private166167#168# do everything needed to add an alias of +name+ having the value +value+169#170def register_alias(name, value)171# TODO: begin rescue?172# TODO: security concerns since we are using eval173174# define some class instance methods175class_eval do176# define a class instance method that will respond for the alias177define_method "cmd_#{name}" do |*args|178# just replace the alias w/the alias' value and run that179driver.run_single("#{value} #{args.join(' ')}")180end181# define a class instance method that will tab complete the aliased command182# we just proxy to the top-level tab complete function and let them handle it183define_method "cmd_#{name}_tabs" do |str, words|184# we need to repair the tab complete string/words and pass back185# replace alias name with the root alias value186value_words = value.split(/[\s\t\n]+/) # in case value is e.g. 'sessions -l'187# valwords is now [sessions,-l]188words[0] = value_words[0]189# words[0] is now 'sessions' (was 'sue')190value_words.shift # valwords is now ['-l']191# insert any remaining parts of value and rebuild the line192line = words.join(' ') + ' ' + value_words.join(' ') + ' ' + str193194[driver.tab_complete(line.strip), :override_completions]195end196# add a cmd_#{name}_help method197define_method "cmd_#{name}_help" do |*_args|198driver.run_single("help #{value}")199end200end201# add the alias to the list202@aliases[name] = value203end204205#206# do everything required to remove an alias of name +name+207#208def deregister_alias(name)209class_eval do210# remove the class methods we created when the alias was registered211remove_method("cmd_#{name}")212remove_method("cmd_#{name}_tabs")213remove_method("cmd_#{name}_help")214end215# remove the alias from the list of active aliases216@aliases.delete(name)217end218219#220# Validate a proposed alias with the +name+ and having the value +value+221#222def valid_alias?(name, value)223# print_good "Assessing validay for #{name} and #{value}"224# we validate two things, the name and the value225226### name227# we don't check if this alias name exists or if it's a console command already etc as -f can override228# that so those need to be checked externally, we pretty much just check to see if the name is sane229name.strip!230bad_words = [/\*/] # add any additional "bad word" regexes here231bad_words.each do |regex|232# don't mess around, just return false in this case, prevents wasted processing233return false if name =~ regex234end235236### value237# value is considered valid if it's a ref to a valid console cmd, a system executable, or an existing238# alias AND isn't a "bad word"239# Here we check for "bad words" to avoid for the value...value would have to NOT match these regexes240# this is just basic idiot protection241value.strip!242bad_words = [/^msfconsole$/]243bad_words.each do |regex|244# don't mess around, just return false if we match245return false if value =~ regex246end247248# we're only gonna validate the first part of the cmd, e.g. just ls from "ls -lh"249value = value.split(' ').first250return true if @aliases.keys.include?(value)251252[value, value + '.exe'].each do |cmd|253return true if Rex::FileUtils.find_full_path(cmd)254end255256# gather all the current commands the driver's dispatcher's have & check 'em257driver.dispatcher_stack.each do |dispatcher|258next unless dispatcher.respond_to?(:commands)259next if dispatcher.commands.nil?260next if dispatcher.commands.empty?261262if dispatcher.respond_to?("cmd_#{value.split(' ').first}")263# print_status "Dispatcher (#{dispatcher.name}) responds to cmd_#{value.split(" ").first}"264return true265end266end267268false269end270271#272# Provide tab completion list for aliases and commands273#274def tab_complete_aliases_and_commands275items = []276# gather all the current commands the driver's dispatcher's have277driver.dispatcher_stack.each do |dispatcher|278next unless dispatcher.respond_to?(:commands)279next if (dispatcher.commands.nil? || dispatcher.commands.empty?)280281items.concat(dispatcher.commands.keys)282end283# add all the current aliases to the list284items.concat(@aliases.keys)285return items286end287288end289290#291# The constructor is called when an instance of the plugin is created. The292# framework instance that the plugin is being associated with is passed in293# the framework parameter. Plugins should call the parent constructor when294# inheriting from Msf::Plugin to ensure that the framework attribute on295# their instance gets set.296#297def initialize(framework, opts)298super299300## Register the commands above301add_console_dispatcher(AliasCommandDispatcher)302end303304#305# The cleanup routine for plugins gives them a chance to undo any actions306# they may have done to the framework. For instance, if a console307# dispatcher was added, then it should be removed in the cleanup routine.308#309def cleanup310# If we had previously registered a console dispatcher with the console,311# deregister it now.312remove_console_dispatcher('Alias')313314# we don't need to remove class methods we added because they were added to315# AliasCommandDispatcher class316end317318#319# This method returns a short, friendly name for the plugin.320#321def name322'alias'323end324325#326# This method returns a brief description of the plugin. It should be no327# more than 60 characters, but there are no hard limits.328#329def desc330'Adds the ability to alias console commands'331end332333end334end335336337