Add query for Code Injection

This query finds cases where user input flows to an argument to `eval`
or `send`, which can execute arbitrary Ruby code.
This commit is contained in:
Harry Maclean
2021-09-14 10:58:25 +01:00
parent 916b844557
commit 95e50cedad
13 changed files with 294 additions and 0 deletions

View File

@@ -0,0 +1,46 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
Directly evaluating user input (for example, an HTTP request parameter) as code without first
sanitizing the input allows an attacker arbitrary code execution. This can occur when user
input is passed to code that interprets it as an expression to be
evaluated, using methods such as <code>Kernel.eval</code> or <code>Kernel.send</code>.
</p>
</overview>
<recommendation>
<p>
Avoid including user input in any expression that may be dynamically evaluated. If user input must
be included, use context-specific escaping before including it.
It is important that the correct escaping is used for the type of evaluation that will occur.
</p>
</recommendation>
<example>
<p>
The following example shows two functions setting a name from a request.
The first function uses <code>eval</code> to execute the <code>set_name</code> method.
This is dangerous as it can allow a malicious user to execute arbitrary code on the server.
For example, the user could supply the value <code>"' + exec('rm -rf') + '"</code>
to destroy the server's file system.
The second function calls the <code>set_name</code> method directly and is thus safe.
</p>
<sample src="examples/code_injection.rb" />
</example>
<references>
<li>
OWASP:
<a href="https://www.owasp.org/index.php/Code_Injection">Code Injection</a>.
</li>
<li>
Wikipedia: <a href="https://en.wikipedia.org/wiki/Code_injection">Code Injection</a>.
</li>
</references>
</qhelp>

View File

@@ -0,0 +1,27 @@
/**
* @name Code injection
* @description Interpreting unsanitized user input as code allows a malicious user to perform arbitrary
* code execution.
* @kind path-problem
* @problem.severity error
* @security-severity 9.3
* @sub-severity high
* @precision high
* @id rb/code-injection
* @tags security
* external/owasp/owasp-a1
* external/cwe/cwe-094
* external/cwe/cwe-095
* external/cwe/cwe-116
*/
import ruby
import codeql.ruby.security.CodeInjectionQuery
import DataFlow::PathGraph
from Configuration config, DataFlow::PathNode source, DataFlow::PathNode sink, Source sourceNode
where
config.hasFlowPath(source, sink) and
sourceNode = source.getNode()
select sink.getNode(), source, sink, "This code execution depends on $@.", sourceNode,
"a user-provided value"

View File

@@ -0,0 +1,17 @@
class UsersController < ActionController::Base
# BAD - Allow user to define code to be run.
def create_bad
first_name = params[:first_name]
eval("set_name(#{first_name})")
end
# GOOD - Call code directly
def create_good
first_name = params[:first_name]
set_name(first_name)
end
def set_name(name)
@name = name
end
end