Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 116 additions & 0 deletions rust/src/common/IronFallback.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/**
* Provides a fallback that recognizes the `iron` crate by the names it uses, for databases in which
* the calls into it cannot be resolved.
*
* A database that is built without compiling the code, as a code scanning default setup does
* (`buildMode: none`), can leave every call that goes through a glob import of `iron::prelude` without
* a target, such as `Iron::new`, `Response::with` and the methods of the request. The data extension
* rows for Iron match canonical paths, and so do the sinks that are written as calls to a canonical
* path, so none of them applies to such code. The classes and predicates here match the same API by
* name, in files that use `iron`, and for calls that have no target.
*/

import rust
private import codeql.rust.dataflow.DataFlow

/** Gets the identifier of the first segment of `path`, such as `iron` for `iron::prelude`. */
private string getRootSegment(Path path) {
not exists(path.getQualifier()) and result = path.getSegment().getIdentifier().getText()
or
result = getRootSegment(path.getQualifier())
}

/** Holds if `file` uses the `iron` crate, with a `use` item or an `extern crate` item. */
predicate isIronFile(File file) {
exists(Use use |
use.getLocation().getFile() = file and
getRootSegment(use.getUseTree().getPath()) = "iron"
)
or
exists(ExternCrate crate |
crate.getLocation().getFile() = file and
crate.getIdentifier().getText() = "iron"
)
}

/** Holds if `typeRepr` is a type that is called `Request`, or a reference to one. */
private predicate isRequestType(TypeRepr typeRepr) {
typeRepr.(PathTypeRepr).getPath().getSegment().getIdentifier().getText() = "Request"
or
isRequestType(typeRepr.(RefTypeRepr).getTypeRepr())
}

/**
* A parameter of type `Request`, `&Request` or `&mut Request` of a function or closure in a file that
* uses `iron`: the shape of an Iron handler or middleware, whether or not the type can be resolved.
*/
class IronRequestParameter extends DataFlow::Node {
IronRequestParameter() {
exists(Param param |
param = this.asParameter() and
isIronFile(param.getLocation().getFile()) and
isRequestType(param.getTypeRepr())
)
}
}

/** The fields of an Iron request that hold data that the client controls. */
private predicate isRequestField(string name) { name = ["url", "headers", "body", "extensions"] }

/** Holds if the method called `name` only tells a property of its receiver, not its content. */
private predicate isNonRevealingMethod(string name) {
name =
[
"len", "is_empty", "capacity", "count", "contains", "starts_with", "ends_with", "is_some",
"is_none", "is_ok", "is_err"
]
}

/**
* Holds if the method called `name` says that it escapes or encodes for HTML, such as `escape_html` or
* `html_escape`. A name that only says `escape_default` or `encode`, or that undoes the encoding
* (`unescape_html`), does not make a value safe for HTML.
*/
bindingset[name]
private predicate isHtmlEncodingMethod(string name) {
name.toLowerCase().regexpMatch("(escape|encode)_?html\\w*|html_?(escape|encode)\\w*")
}

/**
* Holds if the flow goes from `pred` to `succ` in a file that uses `iron`, where the data flow library
* cannot know it because the type of `pred` is not known: `succ` is the read of a field of the
* request that does not resolve to a field, or the result of a method that has no target, called on
* `pred`. A method that says that it encodes for HTML (`escape_html`) is taken to do so, so it does not
* pass the value on.
*/
predicate ironUnresolvedStep(DataFlow::Node pred, DataFlow::Node succ) {
exists(FieldExpr field |
isIronFile(field.getLocation().getFile()) and
isRequestField(field.getIdentifier().getText()) and
not exists(field.getStructField()) and
pred.asExpr() = field.getContainer() and
succ.asExpr() = field
)
or
exists(MethodCallExpr call |
isIronFile(call.getLocation().getFile()) and
not exists(call.getStaticTarget()) and
not isNonRevealingMethod(call.getIdentifier().getText()) and
not isHtmlEncodingMethod(call.getIdentifier().getText()) and
pred.asExpr() = call.getReceiver() and
succ.asExpr() = call
)
}

/**
* Holds if `call` is a call of `Response::with` in a file that uses `iron`, and the call has no target.
* The call may name the type with a longer path, such as `iron::Response::with`.
*/
predicate isUnresolvedIronResponseWith(Call call) {
isIronFile(call.getLocation().getFile()) and
not exists(call.getStaticTarget()) and
exists(Path path | path = call.(CallExpr).getFunction().(PathExpr).getPath() |
path.getSegment().getIdentifier().getText() = "with" and
path.getQualifier().getSegment().getIdentifier().getText() = "Response"
)
}
24 changes: 24 additions & 0 deletions rust/src/security/CWE-079/IronResponseXss.qhelp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,17 @@ whose modifiers include a content type parsed from a string literal that does no
XML, such as <code>"text/plain".parse::&lt;Mime&gt;().unwrap()</code>, and none that does, is not
reported.
</p>
<p>
A database that is built without compiling the code can leave the calls into Iron without a target,
when the names come from a glob import such as <code>use iron::prelude::*</code>. In a file that
uses <code>iron</code>, the query also recognizes these calls by name. A function or closure with a
parameter of type <code>Request</code>, <code>&amp;Request</code> or <code>&amp;mut Request</code> is
a source, the <code>url</code>, <code>headers</code>, <code>body</code> and <code>extensions</code>
fields of the request and the methods that are called on it are followed, and a call of
<code>Response::with</code> that has no target is a sink. For such a call, a body that is passed on its
own, as in <code>Response::with(body)</code>, is a sink as well, because a body that is set on its own
has no content type.
</p>
</overview>

<recommendation>
Expand Down Expand Up @@ -56,6 +67,19 @@ The sinks are the expressions that a modifier tuple is built from, so a tuple th
is built, for example by assigning a body to one of its fields (<code>modifiers.1 = body;</code>), is
not tracked.
</p>
<p>
When the calls have no target, the query goes by names and only looks at files that use
<code>iron</code>. It follows the result of every method that is called on the request and has no
target, except for a few that only tell a property of the value, such as <code>len</code> and
<code>is_empty</code>, and for names that say that they escape or encode for HTML, such as
<code>escape_html</code>, which are taken to do so. A method that encodes the value under another name
(or only partly, as <code>escape_default</code> does) is not recognized as a barrier. A parameter is
recognized by the name of its type, so it can be a type of another crate that has the same name. A
function that takes a request is a source whether or not a call of <code>Iron::new</code> or
<code>Chain::new</code> registers it. For a handler that nothing registers in the file, a body that is
passed on its own to a call of <code>Response::with</code> that resolves is reported by this query, as
the standard query has no source for it.
</p>
</section>

<references>
Expand Down
76 changes: 72 additions & 4 deletions rust/src/security/CWE-079/IronResponseXss.ql
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import rust
import codeql.rust.dataflow.DataFlow
import codeql.rust.dataflow.TaintTracking
import codeql.rust.security.XssExtensions
import common.IronFallback

/**
* A string literal that is parsed, such as the `"text/plain"` of
Expand Down Expand Up @@ -108,28 +109,79 @@ private predicate hasSafeContentType(Expr argument) {
* An element of a modifier tuple passed to `iron::Response::with`, such as `body` in
* `Response::with((status::Ok, body))`, or of a tuple that is nested in it.
*
* A call of `Response::with` that cannot be resolved is matched by its name in a file that uses `iron`
* (see `common.IronFallback`).
*
* A response whose modifiers include a content type that is parsed from a string literal that does not
* name HTML or XML, and none that does, has an explicit, safe `Content-Type` and is not considered a
* sink.
*/
class IronResponseModifierTupleElement extends DataFlow::Node {
IronResponseModifierTupleElement() {
exists(Call call, Expr argument |
call.getStaticTarget().getCanonicalPath() = "<iron::response::Response>::with" and
(
call.getStaticTarget().getCanonicalPath() = "<iron::response::Response>::with"
or
isUnresolvedIronResponseWith(call)
) and
argument = call.getPositionalArgument(0) and
this.asExpr() = getAModifier(argument) and
not hasSafeContentType(argument)
)
}
}

/**
* The argument of a call of `Response::with` that has no target, when it is a body on its own and not a
* tuple of modifiers. A call that can be resolved is covered by the data extension row for the same
* function, which the standard cross-site scripting query uses, and a body that is set on its own has no
* content type.
*/
class IronUnresolvedResponseBody extends DataFlow::Node {
IronUnresolvedResponseBody() {
exists(Call call, Expr argument |
isUnresolvedIronResponseWith(call) and
Comment thread
felickz marked this conversation as resolved.
Resolved
argument = call.getPositionalArgument(0) and
not holdsTuple(argument, _) and
this.asExpr() = argument
)
}
}

/**
* The argument of a call of `Response::with` that resolves, when it is a body on its own and not a tuple
* of modifiers. The data extension row for the function makes it a sink of the standard cross-site
* scripting query, but only the handlers that the rows make a source reach it there. This query reports
* the other handlers, whose request parameter is a source of this query only (see the `where` clause).
*/
class IronResolvedResponseBody extends DataFlow::Node {
IronResolvedResponseBody() {
exists(Call call, Expr argument |
call.getStaticTarget().getCanonicalPath() = "<iron::response::Response>::with" and
argument = call.getPositionalArgument(0) and
not holdsTuple(argument, _) and
this.asExpr() = argument
)
}
}

module IronResponseXssConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node node) { node instanceof Xss::Source }
predicate isSource(DataFlow::Node node) {
node instanceof Xss::Source or node instanceof IronRequestParameter
}

predicate isSink(DataFlow::Node node) { node instanceof IronResponseModifierTupleElement }
predicate isSink(DataFlow::Node node) {
node instanceof IronResponseModifierTupleElement or
node instanceof IronUnresolvedResponseBody or
node instanceof IronResolvedResponseBody
}

predicate isBarrier(DataFlow::Node barrier) { barrier instanceof Xss::Barrier }

predicate isAdditionalFlowStep(DataFlow::Node pred, DataFlow::Node succ) {
ironUnresolvedStep(pred, succ)
}

predicate observeDiffInformedIncrementalMode() { any() }
}

Expand All @@ -138,6 +190,22 @@ module IronResponseXssFlow = TaintTracking::Global<IronResponseXssConfig>;
import IronResponseXssFlow::PathGraph

from IronResponseXssFlow::PathNode sourceNode, IronResponseXssFlow::PathNode sinkNode
where IronResponseXssFlow::flowPath(sourceNode, sinkNode)
where
IronResponseXssFlow::flowPath(sourceNode, sinkNode) and
// A handler that the data extension rows already make a source is reported through that source.
not (
sourceNode.getNode() instanceof IronRequestParameter and
not sourceNode.getNode() instanceof Xss::Source and
exists(IronResponseXssFlow::PathNode modelled |
IronResponseXssFlow::flowPath(modelled, sinkNode) and
modelled.getNode() instanceof Xss::Source
)
) and
// A body on its own that goes to a call that resolves is reported by the standard query, from the
// sources that the data extension rows make. This query leaves those flows to it.
not (
sinkNode.getNode() instanceof IronResolvedResponseBody and
sourceNode.getNode() instanceof Xss::Source
Comment on lines +207 to +208
)
select sinkNode.getNode(), sourceNode, sinkNode, "Cross-site scripting vulnerability due to a $@.",
sourceNode.getNode(), "user-provided value"
74 changes: 74 additions & 0 deletions rust/test/security/CWE-079/IronResponseXss/GlobCalls.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
| 10 | ... .path() |
| 13 | ...::with(...) |
| 17 | ... .path() |
| 19 | ...::with(...) |
| 23 | ... .path() |
| 27 | ...::with(...) |
| 31 | ... .path() |
| 34 | ...::with(...) |
| 38 | ... .query() |
| 38 | ... .unwrap_or(...) |
| 41 | ...::with(...) |
| 45 | ... .path() |
| 46 | path.join(...) |
| 49 | ...::with(...) |
| 54 | ...::with(...) |
| 58 | ... .path() |
| 59 | res.len() |
| 61 | ...::with(...) |
| 65 | ... .path() |
| 69 | ...::with(...) |
| 75 | ...::with(...) |
| 79 | ... .escape_default() |
| 79 | ... .join(...) |
| 79 | ... .path() |
| 79 | ... .to_string() |
| 82 | ...::with(...) |
| 86 | ... .escape_html() |
| 86 | ... .join(...) |
| 86 | ... .path() |
| 89 | ...::with(...) |
| 95 | ... .path() |
| 99 | clean(...) |
| 100 | ...::with(...) |
| 104 | ... .http(...) |
| 104 | ... .unwrap() |
| 104 | ...::new(...) |
| 105 | ... .http(...) |
| 105 | ... .unwrap() |
| 105 | ...::new(...) |
| 106 | ... .http(...) |
| 106 | ... .unwrap() |
| 106 | ...::new(...) |
| 107 | ... .http(...) |
| 107 | ... .unwrap() |
| 107 | ...::new(...) |
| 108 | ... .http(...) |
| 108 | ... .unwrap() |
| 108 | ...::new(...) |
| 109 | ... .http(...) |
| 109 | ... .unwrap() |
| 109 | ...::new(...) |
| 110 | ... .http(...) |
| 110 | ... .unwrap() |
| 110 | ...::new(...) |
| 111 | ... .http(...) |
| 111 | ... .unwrap() |
| 111 | ...::new(...) |
| 112 | ... .http(...) |
| 112 | ... .unwrap() |
| 112 | ...::new(...) |
| 113 | ... .http(...) |
| 113 | ... .unwrap() |
| 113 | ...::new(...) |
| 114 | ... .http(...) |
| 114 | ... .unwrap() |
| 114 | ...::new(...) |
| 115 | ... .http(...) |
| 115 | ... .unwrap() |
| 115 | ...::new(...) |
| 116 | ... .http(...) |
| 116 | ... .unwrap() |
| 116 | ...::new(...) |
| 118 | ... .path() |
| 119 | ...::with(...) |
13 changes: 13 additions & 0 deletions rust/test/security/CWE-079/IronResponseXss/GlobCalls.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* Lists the calls of `glob_prelude.rs` that have no target. The queries recognize Iron by its names
* because of them: if the extraction resolves these calls some day, this test changes and the file no
* longer exercises the fallback.
*/

import rust

from Call call
where
call.getLocation().getFile().getBaseName() = "glob_prelude.rs" and
not exists(call.getStaticTarget())
select call.getLocation().getStartLine(), call.toString()
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@
| main.rs:135:15:135:44 | bad_nested_named_tuple_handler | remote source |
| main.rs:136:15:136:49 | missed_field_assigned_later_handler | remote source |
| main.rs:146:23:146:31 | modifiers | html-injection sink |
| main.rs:154:23:154:44 | TupleExpr | html-injection sink |
| main.rs:162:23:162:30 | response | html-injection sink |
Loading