Class: RuboCop::Cop::Security::Open

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/security/open.rb

Overview

Checks for the use of ‘Kernel#open` and `URI.open` with dynamic data.

‘Kernel#open` and `URI.open` enable not only file access but also process invocation by prefixing a pipe symbol (e.g., `open(“| ls”)`). So, it may lead to a serious security risk by using variable input to the argument of `Kernel#open` and `URI.open`. It would be better to use `File.open`, `IO.popen` or `URI.parse#open` explicitly.

NOTE: ‘open` and `URI.open` with literal strings are not flagged by this cop.

Examples:

# bad
open(something)
open("| #{something}")
open("| foo")
URI.open(something)

# good
File.open(something)
IO.popen(something)
URI.parse(something).open

# good (literal strings)
open("foo.text")
URI.open("http://example.com")

Constant Summary collapse

MSG =
'The use of `%<receiver>sopen` is a serious security risk.'
RESTRICT_ON_SEND =
%i[open].freeze

Instance Attribute Summary

Attributes inherited from Base

#config, #processed_source

Instance Method Summary collapse

Methods inherited from Base

#active_support_extensions_enabled?, #add_global_offense, #add_offense, #always_autocorrect?, autocorrect_incompatible_with, badge, #begin_investigation, #callbacks_needed, callbacks_needed, #config_to_allow_offenses, #config_to_allow_offenses=, #contextual_autocorrect?, #cop_config, cop_name, #cop_name, department, documentation_url, exclude_from_registry, #excluded_file?, #external_dependency_checksum, inherited, #initialize, #inspect, joining_forces, lint?, match?, #message, #offenses, #on_investigation_end, #on_new_investigation, #on_other_file, #parse, #parser_engine, #ready, #relevant_file?, requires_gem, #string_literals_frozen_by_default?, 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?, #autocorrect_with_disable_uncorrectable?, #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



46
47
48
49
50
51
52
53
# File 'lib/rubocop/cop/security/open.rb', line 46

def on_send(node)
  open?(node) do |receiver, code|
    return if safe?(code)

    message = format(MSG, receiver: receiver ? "#{receiver.source}." : 'Kernel#')
    add_offense(node.loc.selector, message: message)
  end
end

#open?(node) ⇒ Object



42
43
44
# File 'lib/rubocop/cop/security/open.rb', line 42

def_node_matcher :open?, <<~PATTERN
  (send ${nil? (const {nil? cbase} :URI)} :open $_ ...)
PATTERN