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
22 changes: 22 additions & 0 deletions rust/ext/manual/iron.model.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
extensions:
- addsTo:
pack: codeql/rust-all
extensible: sourceModel
data:
# The `&mut Request` passed to a handler registered with `Chain::new` or `Iron::new`.
- ["<iron::iron::Iron>::new", "Argument[0].Parameter[0]", "remote", "manual"]
- ["<iron::middleware::Chain>::new", "Argument[0].Parameter[0]", "remote", "manual"]
- addsTo:
pack: codeql/rust-all
extensible: sinkModel
data:
# `Response::with(body)` sets the response body without a `Content-Type`, so browsers
# sniff the content type and render markup as HTML. Bodies passed inside a modifier tuple,
# such as `Response::with((status::Ok, body))`, cannot be expressed as a MaD sink and are
# handled by the `githubsecuritylab/rust/iron-response-xss` query.
- ["<iron::response::Response>::with", "Argument[0]", "html-injection", "manual"]
- addsTo:
pack: codeql/rust-all
extensible: summaryModel
data:
- ["<iron::request::url::Url>::path", "Argument[self].Reference", "ReturnValue", "taint", "manual"]
65 changes: 65 additions & 0 deletions rust/src/security/CWE-079/IronResponseXss.qhelp
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>

<overview>
<p>
The Iron web framework builds a response from a tuple of modifiers, for example
<code>Response::with((status::Ok, body))</code>. A body that is added this way is sent without a
<code>Content-Type</code> header unless one of the modifiers sets it, and browsers then guess the
content type from the body. If the body contains user-controlled data, an attacker can make the
browser render it as HTML and run a script in the context of the application.
</p>
<p>
This query finds user-controlled data that is part of a modifier tuple passed to
<code>Response::with</code>, including the elements of tuples that are nested in it. A response
whose modifiers include a content type parsed from a string literal that does not name HTML or
XML, such as <code>"text/plain".parse::&lt;Mime&gt;().unwrap()</code>, and none that does, is not
reported.
</p>
</overview>

<recommendation>
<p>
Set an explicit content type that is not HTML when the body is not markup, or encode the
user-controlled data for HTML before it is added to the body.
</p>
</recommendation>

<example>
<p>
In the following example, the path of the request is written into the body of the response without
a content type, so a path that contains markup is rendered as HTML:
</p>
<sample src="IronResponseXssBad.rs" />
<p>
In the following corrected example, the response declares that its body is plain text:
</p>
<sample src="IronResponseXssGood.rs" />
</example>

<section title="Known limitations">
<p>
A content type that is set by another kind of modifier, such as <code>Header(ContentType::json())</code>,
is not recognized, so the body of such a response is still reported. A content type is recognized
only when it is parsed directly from a string literal and flows to the tuple through local
variables, <code>unwrap</code>, <code>expect</code> or <code>?</code>. The type that the literal is
parsed into is not checked. If several parsed literals can reach the content types of a response, for
example one on each branch of an <code>if</code>, or one in each of two modifiers, the response is
recognized only when none of them names HTML or XML. Iron applies the modifiers in order, so a
<code>text/html</code> modifier after a <code>text/plain</code> one replaces it, and the query does
not try to tell which of two content types wins.
</p>
<p>
The sinks are the expressions that a modifier tuple is built from, so a tuple that is changed after it
is built, for example by assigning a body to one of its fields (<code>modifiers.1 = body;</code>), is
not tracked.
</p>
</section>

<references>
<li>OWASP: <a href="https://owasp.org/www-community/attacks/xss/">Cross Site Scripting (XSS)</a>.</li>
<li>Common Weakness Enumeration: <a href="https://cwe.mitre.org/data/definitions/79.html">CWE-79</a>.</li>
</references>
</qhelp>
143 changes: 143 additions & 0 deletions rust/src/security/CWE-079/IronResponseXss.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/**
* @name Cross-site scripting through an Iron response modifier tuple
* @description Writing user input into the body of an Iron response built from a
* modifier tuple (for example `Response::with((status::Ok, body))`)
* allows for a cross-site scripting vulnerability, because Iron does
* not set a `Content-Type` and browsers sniff the body as HTML.
* @kind path-problem
* @problem.severity error
* @security-severity 6.1
* @precision medium
* @id githubsecuritylab/rust/iron-response-xss
* @tags security
* experimental
* external/cwe/cwe-079
* external/cwe/cwe-116
*/

import rust
import codeql.rust.dataflow.DataFlow
import codeql.rust.dataflow.TaintTracking
import codeql.rust.security.XssExtensions

/**
* A string literal that is parsed, such as the `"text/plain"` of
* `"text/plain".parse::<Mime>().unwrap()`.
*/
private class ParsedStringLiteral extends StringLiteralExpr {
ParsedStringLiteral() {
exists(MethodCallExpr parse |
parse.getIdentifier().getText() = "parse" and
parse.getReceiver() = this
)
}
}

/** Holds if `literal` names a content type that browsers render as markup. */
private predicate isMarkupContentType(StringLiteralExpr literal) {
literal.getTextValue().toLowerCase().matches(["%html%", "%xml%"])
}

/**
* Holds if `e` is the value that parsing `literal` produces: the `parse` call itself, that call
* unwrapped with `unwrap`, `expect` or `?`, or a local variable that holds such a value. A value
* that is merely derived from it, for example by formatting it into a string, is not.
*/
private predicate isParsedFrom(Expr e, ParsedStringLiteral literal) {
e.(MethodCallExpr).getIdentifier().getText() = "parse" and
e.(MethodCallExpr).getReceiver() = literal
or
e.(MethodCallExpr).getIdentifier().getText() = ["unwrap", "expect"] and
isParsedFrom(e.(MethodCallExpr).getReceiver(), literal)
or
isParsedFrom(e.(TryExpr).getExpr(), literal)
or
exists(DataFlow::ExprNode source, DataFlow::ExprNode target |
target.asExpr() = e and
source.asExpr() != e and
DataFlow::localFlow(source, target) and
isParsedFrom(source.asExpr(), literal)
)
}

/**
* Holds if `tuple` is a tuple expression whose value the expression `e` holds: `e` is the tuple, or a
* local variable or expression that the tuple flows to.
*/
private predicate holdsTuple(Expr e, TupleExpr tuple) {
exists(DataFlow::ExprNode tupleNode, DataFlow::ExprNode eNode |
tupleNode.asExpr() = tuple and
eNode.asExpr() = e and
DataFlow::localFlow(tupleNode, eNode)
)
}

/**
* Gets a modifier of the response that is built from `e`, the argument of `Response::with`: an element
* of the tuple that `e` holds, or of a tuple that is nested in it. Iron applies the modifiers of a
* nested tuple to the same response.
*/
private Expr getAModifier(Expr e) {
exists(TupleExpr tuple, Expr element | holdsTuple(e, tuple) and element = tuple.getAField() |
result = element and not holdsTuple(element, _)
Comment thread
felickz marked this conversation as resolved.
Resolved
or
result = getAModifier(element)
)
}

/**
* Holds if the response that is built from `argument` has an explicit content type that is not markup:
* a modifier is parsed from a string literal that does not name HTML or XML, and no modifier of the
* response is parsed from a literal that does. Iron applies the modifiers in order, so a `text/html`
* modifier after a `text/plain` one replaces it, and a response whose content type can be markup is
* not safe. This also covers a content type that is parsed from different literals on different
* branches of an `if`.
*/
private predicate hasSafeContentType(Expr argument) {
exists(ParsedStringLiteral safe |
isParsedFrom(getAModifier(argument), safe) and
not isMarkupContentType(safe)
) and
not exists(ParsedStringLiteral markup |
isParsedFrom(getAModifier(argument), markup) and
isMarkupContentType(markup)
)
}

/**
* 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 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
argument = call.getPositionalArgument(0) and
this.asExpr() = getAModifier(argument) and
not hasSafeContentType(argument)
)
}
}

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

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

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

predicate observeDiffInformedIncrementalMode() { any() }
}

module IronResponseXssFlow = TaintTracking::Global<IronResponseXssConfig>;

import IronResponseXssFlow::PathGraph

from IronResponseXssFlow::PathNode sourceNode, IronResponseXssFlow::PathNode sinkNode
where IronResponseXssFlow::flowPath(sourceNode, sinkNode)
select sinkNode.getNode(), sourceNode, sinkNode, "Cross-site scripting vulnerability due to a $@.",
sourceNode.getNode(), "user-provided value"
8 changes: 8 additions & 0 deletions rust/src/security/CWE-079/IronResponseXssBad.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use iron::status;
use iron::{IronResult, Request, Response};

fn handler(req: &mut Request) -> IronResult<Response> {
let name = req.url.path();
let body = format!("<h1>Hello, {:?}!</h1>", name);
Ok(Response::with((status::Ok, body))) // BAD: no content type, the body may be sniffed as HTML
}
10 changes: 10 additions & 0 deletions rust/src/security/CWE-079/IronResponseXssGood.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
use iron::mime::Mime;
use iron::status;
use iron::{IronResult, Request, Response};

fn handler(req: &mut Request) -> IronResult<Response> {
let name = req.url.path();
let body = format!("Hello, {:?}!", name);
let plain: Mime = "text/plain".parse().unwrap();
Ok(Response::with((status::Ok, plain, body))) // GOOD: the body is declared as plain text
}
4 changes: 4 additions & 0 deletions rust/test/codeql-pack.lock.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@ dependencies:
version: 1.0.62
codeql/rust-all:
version: 0.2.26
codeql/rust-queries:
version: 0.1.47
codeql/ssa:
version: 2.0.38
codeql/suite-helpers:
version: 1.0.62
codeql/threat-models:
version: 1.1.2
codeql/tutorial:
Expand Down
1 change: 1 addition & 0 deletions rust/test/qlpack.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ name: githubsecuritylab/codeql-rust-tests
groups: [rust, test]
dependencies:
codeql/rust-all: '0.2.26'
codeql/rust-queries: '0.1.47'
githubsecuritylab/codeql-rust-queries: '*'
githubsecuritylab/codeql-rust-extensions: '*'

Expand Down
Loading