Class: Scryer::Rules::CommandInjectionRule

Inherits:
Scryer::Rule show all
Defined in:
lib/scryer/rules/command_injection_rule.rb

Overview

Flags shell-executing calls (system, ` ` backticks, %x{}, Kernel#exec, IO.popen, Open3.*) whose command string contains interpolation — user-controlled input reaching a shell is a command injection risk.

Constant Summary collapse

SHELL_METHODS =
%w[system exec popen spawn].freeze

Instance Attribute Summary

Attributes inherited from Scryer::Rule

#file, #sexp, #source

Instance Method Summary collapse

Methods inherited from Scryer::Rule

inherited, #initialize

Constructor Details

This class inherits a constructor from Scryer::Rule

Instance Method Details

#scanObject



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/scryer/rules/command_injection_rule.rb', line 15

def scan
  findings = []

  Ast.each_node(sexp) do |node|
    # backticks / %x{} literals: [:xstring_literal, [:xstring, [:@tstring_content, ...] or [:string_embexpr, ...]]]
    if Ast.tagged?(node, :xstring_literal) && Ast.string_literal_has_interpolation?(node)
      line = Ast.line_of(node)
      findings << finding(
        line: line,
        message: "Backtick/`%x{}` shell execution contains interpolated input.",
        suggested_fix: "Avoid shelling out with interpolated strings. If you must run a " \
                        "command, use `system(\"cmd\", arg1, arg2)` (array form) so each " \
                        "argument is passed directly to the OS without going through a shell."
      )
    end

    next unless Ast.tagged?(node, :method_add_arg, :command, :command_call)

    inner = Ast.tagged?(node, :method_add_arg) ? node[1] : node
    receiver_and_name = Ast.call_name(inner)
    next unless receiver_and_name

    _receiver, method_name = receiver_and_name
    next unless SHELL_METHODS.include?(method_name)

    args = Ast.call_arguments(node)
    next if args.empty?

    first_arg = args.first
    next unless Ast.string_literal_has_interpolation?(first_arg)

    line = Ast.line_of(first_arg) || Ast.line_of(node)
    findings << finding(
      line: line,
      message: "`#{method_name}` is called with a single interpolated string, which goes " \
                "through a shell — user-controlled input here can inject arbitrary commands.",
      suggested_fix: "Pass arguments as separate strings instead of one interpolated " \
                      "string, e.g. `#{method_name}(\"cmd\", user_input)` rather than " \
                      "`#{method_name}(\"cmd \#{user_input}\")` — the array form bypasses the shell entirely."
    )
  end

  findings
end