Skip to content
Draft
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"]
55 changes: 55 additions & 0 deletions rust/src/security/CWE-079/IronResponseXss.qhelp
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<!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>. A tuple that also contains 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>, 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.
</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>
106 changes: 106 additions & 0 deletions rust/src/security/CWE-079/IronResponseXss.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/**
* @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)
)
}

/**
* An element of a modifier tuple passed to `iron::Response::with`, such as `body` in
* `Response::with((status::Ok, body))`.
*
* Tuples that contain a content type modifier parsed from a string literal that does not name
* HTML or XML set an explicit, safe `Content-Type` and are not considered sinks.
*/
class IronResponseModifierTupleElement extends DataFlow::Node {
IronResponseModifierTupleElement() {
exists(Call call, TupleExpr modifiers, Expr argument |
call.getStaticTarget().getCanonicalPath() = "<iron::response::Response>::with" and
argument = call.getPositionalArgument(0) and
exists(DataFlow::ExprNode tupleNode, DataFlow::ExprNode argumentNode |
tupleNode.asExpr() = modifiers and
argumentNode.asExpr() = argument and
DataFlow::localFlow(tupleNode, argumentNode)
) and
this.asExpr() = modifiers.getAField() and
not exists(ParsedStringLiteral literal |
not isMarkupContentType(literal) and
isParsedFrom(modifiers.getAField(), literal)
)
)
}
}

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
}
Loading