Skip to content

Commit

Permalink
Place Reline behind a feature flag
Browse files Browse the repository at this point in the history
  • Loading branch information
sjanusz-r7 committed Nov 19, 2024
1 parent e199dd7 commit 226a634
Show file tree
Hide file tree
Showing 24 changed files with 239 additions and 157 deletions.
2 changes: 1 addition & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ GEM
nokogiri
redcarpet (3.6.0)
regexp_parser (2.9.2)
reline (0.5.10)
reline (0.5.11)
io-console (~> 0.5)
require_all (3.0.0)
rex-arch (0.1.16)
Expand Down
8 changes: 8 additions & 0 deletions lib/msf/core/feature_manager.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class FeatureManager
LDAP_SESSION_TYPE = 'ldap_session_type'
SHOW_SUCCESSFUL_LOGINS = 'show_successful_logins'
DISPLAY_MODULE_ACTION = 'display_module_action'
USE_RELINE = 'use_reline'

DEFAULTS = [
{
Expand Down Expand Up @@ -132,6 +133,13 @@ class FeatureManager
requires_restart: false,
default_value: true,
developer_notes: 'Added as a feature so users can turn it off if they wish to reduce clutter in their terminal'
}.freeze,
{
name: USE_RELINE,
description: 'When enabled, the new Reline library will be used instead of the legacy Readline library for input/output.',
requires_restart: true,
default_value: false,
developer_notes: 'To be enabled by default after sufficient testing and Reline fixes the issues raised here: https://github.com/ruby/reline/issues/created_by/sjanusz-r7'
}.freeze
].freeze

Expand Down
15 changes: 9 additions & 6 deletions lib/msf/ui/console/command_dispatcher/core.rb
Original file line number Diff line number Diff line change
Expand Up @@ -760,7 +760,8 @@ def cmd_features_tabs(_str, words)
end

def cmd_history(*args)
length = Readline::HISTORY.length
history = Msf::Ui::Console::MsfReadline.instance.history
length = history.length

if length < @history_limit
limit = length
Expand All @@ -780,10 +781,12 @@ def cmd_history(*args)
limit = val.to_i
end
when '-c'
if Readline::HISTORY.respond_to?(:clear)
Readline::HISTORY.clear
elsif defined?(RbReadline)
RbReadline.clear_history
if history.respond_to?(:clear)
history.clear
elsif history.respond_to?(:clear_history)
history.clear_history
elsif history.respond_to?(:pop) && history.respond_to?(:length)
history.length.times { |_i| history.pop }
else
print_error('Could not clear history, skipping file')
return false
Expand All @@ -808,7 +811,7 @@ def cmd_history(*args)

(start..length-1).each do |pos|
cmd_num = (pos + 1).to_s
print_line "#{cmd_num.ljust(pad_len)} #{Readline::HISTORY[pos]}"
print_line "#{cmd_num.ljust(pad_len)} #{history[pos]}"
end
end

Expand Down
7 changes: 7 additions & 0 deletions lib/msf/ui/console/command_dispatcher/developer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ def cmd_irb(*args)

framework.history_manager.with_context(name: :irb) do
begin
reline_autocomplete = Reline.autocompletion if defined?(Reline)
if active_module
print_status("You are in #{active_module.fullname}\n")
Rex::Ui::Text::IrbShell.new(active_module).run
Expand All @@ -140,6 +141,8 @@ def cmd_irb(*args)
end
rescue
print_error("Error during IRB: #{$!}\n\n#{$@.join("\n")}")
ensure
Reline.autocompletion = reline_autocomplete if defined?(Reline)
end
end

Expand Down Expand Up @@ -515,6 +518,10 @@ def cmd_time_help
private

def modified_files
# Temporary work-around until Open3 gets fixed on Windows 11:
# https://github.com/ruby/open3/issues/9
return [] if Rex::Compat.is_cygwin || Rex::Compat.is_windows

# Using an array avoids shelling out, so we avoid escaping/quoting
changed_files = %w[git diff --name-only]
begin
Expand Down
19 changes: 8 additions & 11 deletions lib/msf/ui/console/driver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ class Driver < Msf::Ui::Driver
# @option opts [Boolean] 'SkipDatabaseInit' (false) Whether to skip
# connecting to the database and running migrations
def initialize(prompt = DefaultPrompt, prompt_char = DefaultPromptChar, opts = {})
setup_readline if opts['Readline']
setup_readline

histfile = opts['HistFile'] || Msf::Config.history_file

Expand Down Expand Up @@ -313,23 +313,20 @@ def save_config
# Saves the recent history to the specified file
#
def save_recent_history(path)
num = Readline::HISTORY.length - hist_last_saved - 1
history = Msf::Ui::Console::MsfReadline.instance.history
num = history.length - hist_last_saved - 1
tmprc = history.entries[hist_last_saved..].join("\n")

tmprc = ""
num.times { |x|
tmprc << Readline::HISTORY[hist_last_saved + x] + "\n"
}

if tmprc.length > 0
if tmprc.empty?
print_error("No commands to save!")
else
print_status("Saving last #{num} commands to #{path} ...")
save_resource(tmprc, path)
else
print_error("No commands to save!")
end

# Always update this, even if we didn't save anything. We do this
# so that we don't end up saving the "makerc" command itself.
self.hist_last_saved = Readline::HISTORY.length
self.hist_last_saved = history.length
end

#
Expand Down
6 changes: 3 additions & 3 deletions lib/msf/ui/console/module_option_tab_completion.rb
Original file line number Diff line number Diff line change
Expand Up @@ -53,18 +53,18 @@ def tab_complete_option(mod, str, words)
option_name = str.chop
option_value = ''

::Readline.completion_append_character = ' '
Msf::Ui::Console::MsfReadline.instance.completion_append_character = ' '
return tab_complete_option_values(mod, option_value, words, opt: option_name).map { |value| "#{str}#{value}" }
elsif str.include?('=')
str_split = str.split('=')
option_name = str_split[0].strip
option_value = str_split[1].strip

::Readline.completion_append_character = ' '
Msf::Ui::Console::MsfReadline.instance.completion_append_character = ' '
return tab_complete_option_values(mod, option_value, words, opt: option_name).map { |value| "#{option_name}=#{value}" }
end

::Readline.completion_append_character = ''
Msf::Ui::Console::MsfReadline.instance.completion_append_character = ''
tab_complete_option_names(mod, str, words).map { |name| "#{name}=" }
end

Expand Down
106 changes: 106 additions & 0 deletions lib/msf/ui/console/msf_readline.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
#
# This class is responsible for handling Readline/Reline-agnostic user input.
#
class Msf::Ui::Console::MsfReadline
require 'singleton'
# Required to check the Reline flag.
require 'msf/core/feature_manager'
require 'readline'
require 'reline'

include Singleton

attr_accessor :history

def initialize
@backend = using_reline? ? ::Reline : ::Readline
@history = @backend::HISTORY
end

def method_missing(sym, *args, &block)
if @backend.respond_to?(sym)
@backend.send(sym, *args, &block)
else
msg = "Method '#{sym}' not found in #{@backend.class}"
elog(msg)
raise NoMethodError, msg
end
end

# Read a line from the user, and return it.
# @param prompt [String] The prompt to show to the user.
# @param add_history [Boolean] True if the user's input should be saved to the history.
# @param opts [Hash] Options
# @return String The line that the user has entered.
def readline(prompt, add_history = false, opts: {})
input(prompt, add_history, opts: opts)
end

def using_reline?
Msf::FeatureManager.instance.enabled?(Msf::FeatureManager::USE_RELINE)
end

private

attr_accessor :backend

def input(*args, opts: {})
using_reline? ? input_reline(*args, opts: opts) : input_rbreadline(*args, opts: opts)
end

def input_rbreadline(prompt, add_history = false, opts: {})
# rb-readlines's Readline.readline hardcodes the input and output to
# $stdin and $stdout, which means setting `Readline.input` or
# `Readline.output` has no effect when running `Readline.readline` with
# rb-readline, so need to reimplement
# []`Readline.readline`](https://github.com/luislavena/rb-readline/blob/ce4908dae45dbcae90a6e42e3710b8c3a1f2cd64/lib/readline.rb#L36-L58)
# for rb-readline to support setting input and output. Output needs to
# be set so that colorization works for the prompt on Windows.

input_on_entry = RbReadline.rl_instream
output_on_entry = RbReadline.rl_outstream

begin
RbReadline.rl_instream = opts[:fd]
RbReadline.rl_outstream = opts[:output]
line = RbReadline.readline(prompt.to_s)
rescue ::StandardError => e
RbReadline.rl_instream = input_on_entry
RbReadline.rl_outstream = output_on_entry
RbReadline.rl_cleanup_after_signal
RbReadline.rl_deprep_terminal

raise e
end

if add_history && line && !line.start_with?(' ')
# Don't add duplicate lines to history
if ::Readline::HISTORY.empty? || line.strip != ::Readline::HISTORY[-1]
RbReadline.add_history(line.strip)
end
end

line.dup
end

def input_reline(prompt, add_history = false, opts: {})
input_on_entry = Reline::IOGate.instance_variable_get(:@input)
output_on_entry = Reline::IOGate.instance_variable_get(:@output)

begin
Reline.input = opts[:fd]
Reline.output = opts[:output]
line = Reline.readline(prompt.to_s, add_history)
ensure
Reline.input = input_on_entry
Reline.output = output_on_entry
end

# Don't add duplicate lines to history
if Reline::HISTORY.length > 1 && line == Reline::HISTORY[-2]
Reline::HISTORY.pop
end

line.dup
end
end
5 changes: 3 additions & 2 deletions lib/msf/ui/debug.rb
Original file line number Diff line number Diff line change
Expand Up @@ -220,13 +220,14 @@ def self.framework_config(framework)
end

def self.history(driver)
end_pos = Readline::HISTORY.length - 1
history = Msf::Ui::Console::MsfReadline.instance.history
end_pos = history.length - 1
start_pos = end_pos - COMMAND_HISTORY_TOTAL > driver.hist_last_saved ? end_pos - (COMMAND_HISTORY_TOTAL - 1) : driver.hist_last_saved

commands = ''
while start_pos <= end_pos
# Formats command position in history to 6 characters in length
commands += "#{'%-6.6s' % start_pos.to_s} #{Readline::HISTORY[start_pos]}\n"
commands += "#{'%-6.6s' % start_pos.to_s} #{history[start_pos]}\n"
start_pos += 1
end

Expand Down
14 changes: 14 additions & 0 deletions lib/msf_autoload.rb
Original file line number Diff line number Diff line change
Expand Up @@ -347,3 +347,17 @@ def finalize_loader(loader)

# XXX: Should be removed once the `lib/metasploit` folder is loaded by Zeitwerk
require 'metasploit/framework/hashes'

# TODO: Remove this monkey-patch once the following issue is addressed over on Reline's repository here:
# https://github.com/ruby/reline/issues/756
require 'reline'
class ::Reline::Core
alias old_completion_append_character= completion_append_character=
alias old_completion_append_character completion_append_character

def completion_append_character=(v)
self.old_completion_append_character = v
# Additionally keep the line_editor in sync
line_editor.completion_append_character = self.old_completion_append_character
end
end
9 changes: 9 additions & 0 deletions lib/msfenv.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,3 +82,12 @@ def print_error(msg, exception = nil)

$stderr.puts(msg)
end

# Currently, we need to require readline for backwards-compatibility with Reline.
require 'readline'

# If we are using Reline, require it explicitly.
# IRB also calls off to "require 'reline'", so we don't need to check if we are in the development group here.
if framework.features.enabled?(Msf::FeatureManager::USE_RELINE)
require 'reline'
end
Original file line number Diff line number Diff line change
Expand Up @@ -902,7 +902,7 @@ def tab_complete_cdirectory(str, words)

def tab_complete_path(str, words, dir_only)
if client.platform == 'windows'
::Readline.completion_case_fold = true
Msf::Ui::Console::MsfReadline.instance.completion_case_fold = true
end
if client.commands.include?(COMMAND_ID_STDAPI_FS_LS)
expanded = str
Expand All @@ -915,7 +915,7 @@ def tab_complete_path(str, words, dir_only)
# This is annoying if we're recursively tab-traversing our way through subdirectories -
# we may want to continue traversing, but MSF will add a space, requiring us to back up to continue
# tab-completing our way through successive subdirectories.
::Readline.completion_append_character = nil
Msf::Ui::Console::MsfReadline.instance.completion_append_character = nil
end
results
else
Expand Down
18 changes: 9 additions & 9 deletions lib/rex/ui/text/dispatcher_shell.rb
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def tab_complete_directory(str, words)
# This is annoying if we're recursively tab-traversing our way through subdirectories -
# we may want to continue traversing, but MSF will add a space, requiring us to back up to continue
# tab-completing our way through successive subdirectories.
::Readline.completion_append_character = nil
Msf::Ui::Console::MsfReadline.instance.completion_append_character = nil
end

if dirs.length == 0 && File.directory?(str)
Expand Down Expand Up @@ -408,9 +408,13 @@ def initialize(prompt, prompt_char = '>', histfile = nil, framework = nil, name
# a design problem in the Readline module and depends on the
# Readline.basic_word_break_characters variable being set to \x00
#
def tab_complete(str)
::Readline.completion_append_character = ' '
::Readline.completion_case_fold = false
def tab_complete(str, opts: {})
Msf::Ui::Console::MsfReadline.instance.completion_append_character = ' '
Msf::Ui::Console::MsfReadline.instance.completion_case_fold = false

if opts[:preposing] && Msf::Ui::Console::MsfReadline.instance.using_reline?
str = "#{opts[:preposing]}#{str}"
end

# Check trailing whitespace so we can tell 'x' from 'x '
str_match = str.match(/[^\\]([\\]{2})*\s+$/)
Expand All @@ -424,11 +428,7 @@ def tab_complete(str)

# Pop the last word and pass it to the real method
result = tab_complete_stub(str, split_str)
if result
result.uniq
else
result
end
result&.uniq
end

# Performs tab completion of a command, if supported
Expand Down
Loading

0 comments on commit 226a634

Please sign in to comment.