Class: RuboCop::Cop::Security::IoMethods

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/security/io_methods.rb

Overview

Checks for the first argument to `IO.read`, `IO.binread`, `IO.write`, `IO.binwrite`, `IO.foreach`, and `IO.readlines`.

If argument starts with a pipe character (`'|'`) and the receiver is the `IO` class, a subprocess is created in the same way as `Kernel#open`, and its output is returned. `Kernel#open` may allow unintentional command injection, which is the reason these `IO` methods are a security risk. Consider to use `File.read` to disable the behavior of subprocess invocation.

Examples:


# bad
IO.read(path)
IO.read('path')

# good
File.read(path)
File.read('path')
IO.read('| command') # Allow intentional command invocation.

Constant Summary collapse

MSG =
'`File.%<method_name>s` is safer than `IO.%<method_name>s`.'
RESTRICT_ON_SEND =
%i[read binread write binwrite foreach readlines].freeze

Instance Attribute Summary

Attributes inherited from Base

#config, #processed_source

Instance Method Summary collapse

Methods included from AutoCorrector

support_autocorrect?

Methods inherited from Base

#add_global_offense, #add_offense, autocorrect_incompatible_with, badge, #callbacks_needed, callbacks_needed, #config_to_allow_offenses, #config_to_allow_offenses=, #cop_config, #cop_name, cop_name, department, documentation_url, exclude_from_registry, #excluded_file?, #external_dependency_checksum, inherited, #initialize, joining_forces, lint?, match?, #message, #offenses, #on_investigation_end, #on_new_investigation, #on_other_file, #parse, #ready, #relevant_file?, support_autocorrect?, support_multiple_source?, #target_rails_version, #target_ruby_version

Methods included from ExcludeLimit

#exclude_limit

Methods included from AutocorrectLogic

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #correctable?, #disable_uncorrectable?, #safe_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

silence_warnings

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Instance Method Details

#on_send(node) ⇒ Object


36
37
38
39
40
41
42
43
44
45
# File 'lib/rubocop/cop/security/io_methods.rb', line 36

def on_send(node)
  return unless (receiver = node.receiver) && receiver.source == 'IO'

  argument = node.first_argument
  return if argument.respond_to?(:value) && argument.value.strip.start_with?('|')

  add_offense(node, message: format(MSG, method_name: node.method_name)) do |corrector|
    corrector.replace(receiver, 'File')
  end
end