Skip to content

Commit 92d109c

Browse files
felickzCopilot
andauthored
[New Query and models - githubsecuritylab/rust/iron-response-xss] - detect Rust Iron response XSS and add Iron models (#260)
* Rust: add Iron models and the response modifier tuple XSS query Add source, sink and summary rows for the Iron web framework, and githubsecuritylab/rust/iron-response-xss (CWE-79), which reports user input in a modifier tuple that is passed to Response::with when no modifier sets a content type other than HTML or XML. A body passed to Response::with on its own is covered by the html-injection sink row. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust Iron XSS: only the parsed content type itself suppresses the alert A string literal that was parsed and then merely formatted into the body suppressed the whole response, because the suppression used taint tracking from the literal to any tuple element. Require the tuple element to be the parsed value itself (the parse call, also through unwrap, expect, ? and local variables) and add a regression for a body built from a parsed literal. State in the query help that the parsed type is not checked. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust Iron XSS: reject mixed content types, test the standard query with the rows A content type that several parsed literals can reach, for example one on each branch of an if, was treated as safe when any of them was not markup. It is now safe only when a parsed literal reaches it and none of them names HTML or XML. Add a regression for a plain text and HTML mix. Add the standard rust/xss query as a test of the data extension rows, as the test packs of the other languages do: the Rust test pack depends on codeql/rust-queries 0.1.47 (the version that the pinned CLI bundles) and the lock file lists it and codeql/suite-helpers. The new test has one alert, the body that is passed on its own to Response::with. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust Iron XSS: look through nested modifier tuples, judge every content type Only the immediate elements of the modifier tuple were sinks, so a body in a nested tuple was missed. A content type that is parsed from a safe literal removed the sinks of the whole tuple, even when another modifier of the same response is parsed from an HTML literal and is applied after it. Use the leaf elements of the tuple and of the tuples that are nested in it as the sinks, and judge the content type of the whole response: it is safe only when a modifier is parsed from a literal that is not markup and no modifier is parsed from one that is. Add regressions for a body in a nested tuple (written in place, or built first), a text/html modifier after a text/plain one, and a text/plain modifier in a nested tuple. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust Iron XSS: document that a tuple field assigned later is not tracked The sinks of the query are the expressions that a modifier tuple is built from, so a body that is assigned to a tuple field after the tuple is built (modifiers.1 = body) is not a sink. Tracking the field contents at the call would need a different sink model that also changes where alerts are reported, for a pattern that Iron code rarely uses, so say so in the query help and pin it with a fixture. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752
1 parent 62a1992 commit 92d109c

16 files changed

Lines changed: 1164 additions & 0 deletions

‎rust/ext/manual/iron.model.yml‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
extensions:
2+
- addsTo:
3+
pack: codeql/rust-all
4+
extensible: sourceModel
5+
data:
6+
# The `&mut Request` passed to a handler registered with `Chain::new` or `Iron::new`.
7+
- ["<iron::iron::Iron>::new", "Argument[0].Parameter[0]", "remote", "manual"]
8+
- ["<iron::middleware::Chain>::new", "Argument[0].Parameter[0]", "remote", "manual"]
9+
- addsTo:
10+
pack: codeql/rust-all
11+
extensible: sinkModel
12+
data:
13+
# `Response::with(body)` sets the response body without a `Content-Type`, so browsers
14+
# sniff the content type and render markup as HTML. Bodies passed inside a modifier tuple,
15+
# such as `Response::with((status::Ok, body))`, cannot be expressed as a MaD sink and are
16+
# handled by the `githubsecuritylab/rust/iron-response-xss` query.
17+
- ["<iron::response::Response>::with", "Argument[0]", "html-injection", "manual"]
18+
- addsTo:
19+
pack: codeql/rust-all
20+
extensible: summaryModel
21+
data:
22+
- ["<iron::request::url::Url>::path", "Argument[self].Reference", "ReturnValue", "taint", "manual"]
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<!DOCTYPE qhelp PUBLIC
2+
"-//Semmle//qhelp//EN"
3+
"qhelp.dtd">
4+
<qhelp>
5+
6+
<overview>
7+
<p>
8+
The Iron web framework builds a response from a tuple of modifiers, for example
9+
<code>Response::with((status::Ok, body))</code>. A body that is added this way is sent without a
10+
<code>Content-Type</code> header unless one of the modifiers sets it, and browsers then guess the
11+
content type from the body. If the body contains user-controlled data, an attacker can make the
12+
browser render it as HTML and run a script in the context of the application.
13+
</p>
14+
<p>
15+
This query finds user-controlled data that is part of a modifier tuple passed to
16+
<code>Response::with</code>, including the elements of tuples that are nested in it. A response
17+
whose modifiers include a content type parsed from a string literal that does not name HTML or
18+
XML, such as <code>"text/plain".parse::&lt;Mime&gt;().unwrap()</code>, and none that does, is not
19+
reported.
20+
</p>
21+
</overview>
22+
23+
<recommendation>
24+
<p>
25+
Set an explicit content type that is not HTML when the body is not markup, or encode the
26+
user-controlled data for HTML before it is added to the body.
27+
</p>
28+
</recommendation>
29+
30+
<example>
31+
<p>
32+
In the following example, the path of the request is written into the body of the response without
33+
a content type, so a path that contains markup is rendered as HTML:
34+
</p>
35+
<sample src="IronResponseXssBad.rs" />
36+
<p>
37+
In the following corrected example, the response declares that its body is plain text:
38+
</p>
39+
<sample src="IronResponseXssGood.rs" />
40+
</example>
41+
42+
<section title="Known limitations">
43+
<p>
44+
A content type that is set by another kind of modifier, such as <code>Header(ContentType::json())</code>,
45+
is not recognized, so the body of such a response is still reported. A content type is recognized
46+
only when it is parsed directly from a string literal and flows to the tuple through local
47+
variables, <code>unwrap</code>, <code>expect</code> or <code>?</code>. The type that the literal is
48+
parsed into is not checked. If several parsed literals can reach the content types of a response, for
49+
example one on each branch of an <code>if</code>, or one in each of two modifiers, the response is
50+
recognized only when none of them names HTML or XML. Iron applies the modifiers in order, so a
51+
<code>text/html</code> modifier after a <code>text/plain</code> one replaces it, and the query does
52+
not try to tell which of two content types wins.
53+
</p>
54+
<p>
55+
The sinks are the expressions that a modifier tuple is built from, so a tuple that is changed after it
56+
is built, for example by assigning a body to one of its fields (<code>modifiers.1 = body;</code>), is
57+
not tracked.
58+
</p>
59+
</section>
60+
61+
<references>
62+
<li>OWASP: <a href="https://owasp.org/www-community/attacks/xss/">Cross Site Scripting (XSS)</a>.</li>
63+
<li>Common Weakness Enumeration: <a href="https://cwe.mitre.org/data/definitions/79.html">CWE-79</a>.</li>
64+
</references>
65+
</qhelp>
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
1+
/**
2+
* @name Cross-site scripting through an Iron response modifier tuple
3+
* @description Writing user input into the body of an Iron response built from a
4+
* modifier tuple (for example `Response::with((status::Ok, body))`)
5+
* allows for a cross-site scripting vulnerability, because Iron does
6+
* not set a `Content-Type` and browsers sniff the body as HTML.
7+
* @kind path-problem
8+
* @problem.severity error
9+
* @security-severity 6.1
10+
* @precision medium
11+
* @id githubsecuritylab/rust/iron-response-xss
12+
* @tags security
13+
* experimental
14+
* external/cwe/cwe-079
15+
* external/cwe/cwe-116
16+
*/
17+
18+
import rust
19+
import codeql.rust.dataflow.DataFlow
20+
import codeql.rust.dataflow.TaintTracking
21+
import codeql.rust.security.XssExtensions
22+
23+
/**
24+
* A string literal that is parsed, such as the `"text/plain"` of
25+
* `"text/plain".parse::<Mime>().unwrap()`.
26+
*/
27+
private class ParsedStringLiteral extends StringLiteralExpr {
28+
ParsedStringLiteral() {
29+
exists(MethodCallExpr parse |
30+
parse.getIdentifier().getText() = "parse" and
31+
parse.getReceiver() = this
32+
)
33+
}
34+
}
35+
36+
/** Holds if `literal` names a content type that browsers render as markup. */
37+
private predicate isMarkupContentType(StringLiteralExpr literal) {
38+
literal.getTextValue().toLowerCase().matches(["%html%", "%xml%"])
39+
}
40+
41+
/**
42+
* Holds if `e` is the value that parsing `literal` produces: the `parse` call itself, that call
43+
* unwrapped with `unwrap`, `expect` or `?`, or a local variable that holds such a value. A value
44+
* that is merely derived from it, for example by formatting it into a string, is not.
45+
*/
46+
private predicate isParsedFrom(Expr e, ParsedStringLiteral literal) {
47+
e.(MethodCallExpr).getIdentifier().getText() = "parse" and
48+
e.(MethodCallExpr).getReceiver() = literal
49+
or
50+
e.(MethodCallExpr).getIdentifier().getText() = ["unwrap", "expect"] and
51+
isParsedFrom(e.(MethodCallExpr).getReceiver(), literal)
52+
or
53+
isParsedFrom(e.(TryExpr).getExpr(), literal)
54+
or
55+
exists(DataFlow::ExprNode source, DataFlow::ExprNode target |
56+
target.asExpr() = e and
57+
source.asExpr() != e and
58+
DataFlow::localFlow(source, target) and
59+
isParsedFrom(source.asExpr(), literal)
60+
)
61+
}
62+
63+
/**
64+
* Holds if `tuple` is a tuple expression whose value the expression `e` holds: `e` is the tuple, or a
65+
* local variable or expression that the tuple flows to.
66+
*/
67+
private predicate holdsTuple(Expr e, TupleExpr tuple) {
68+
exists(DataFlow::ExprNode tupleNode, DataFlow::ExprNode eNode |
69+
tupleNode.asExpr() = tuple and
70+
eNode.asExpr() = e and
71+
DataFlow::localFlow(tupleNode, eNode)
72+
)
73+
}
74+
75+
/**
76+
* Gets a modifier of the response that is built from `e`, the argument of `Response::with`: an element
77+
* of the tuple that `e` holds, or of a tuple that is nested in it. Iron applies the modifiers of a
78+
* nested tuple to the same response.
79+
*/
80+
private Expr getAModifier(Expr e) {
81+
exists(TupleExpr tuple, Expr element | holdsTuple(e, tuple) and element = tuple.getAField() |
82+
result = element and not holdsTuple(element, _)
83+
or
84+
result = getAModifier(element)
85+
)
86+
}
87+
88+
/**
89+
* Holds if the response that is built from `argument` has an explicit content type that is not markup:
90+
* a modifier is parsed from a string literal that does not name HTML or XML, and no modifier of the
91+
* response is parsed from a literal that does. Iron applies the modifiers in order, so a `text/html`
92+
* modifier after a `text/plain` one replaces it, and a response whose content type can be markup is
93+
* not safe. This also covers a content type that is parsed from different literals on different
94+
* branches of an `if`.
95+
*/
96+
private predicate hasSafeContentType(Expr argument) {
97+
exists(ParsedStringLiteral safe |
98+
isParsedFrom(getAModifier(argument), safe) and
99+
not isMarkupContentType(safe)
100+
) and
101+
not exists(ParsedStringLiteral markup |
102+
isParsedFrom(getAModifier(argument), markup) and
103+
isMarkupContentType(markup)
104+
)
105+
}
106+
107+
/**
108+
* An element of a modifier tuple passed to `iron::Response::with`, such as `body` in
109+
* `Response::with((status::Ok, body))`, or of a tuple that is nested in it.
110+
*
111+
* A response whose modifiers include a content type that is parsed from a string literal that does not
112+
* name HTML or XML, and none that does, has an explicit, safe `Content-Type` and is not considered a
113+
* sink.
114+
*/
115+
class IronResponseModifierTupleElement extends DataFlow::Node {
116+
IronResponseModifierTupleElement() {
117+
exists(Call call, Expr argument |
118+
call.getStaticTarget().getCanonicalPath() = "<iron::response::Response>::with" and
119+
argument = call.getPositionalArgument(0) and
120+
this.asExpr() = getAModifier(argument) and
121+
not hasSafeContentType(argument)
122+
)
123+
}
124+
}
125+
126+
module IronResponseXssConfig implements DataFlow::ConfigSig {
127+
predicate isSource(DataFlow::Node node) { node instanceof Xss::Source }
128+
129+
predicate isSink(DataFlow::Node node) { node instanceof IronResponseModifierTupleElement }
130+
131+
predicate isBarrier(DataFlow::Node barrier) { barrier instanceof Xss::Barrier }
132+
133+
predicate observeDiffInformedIncrementalMode() { any() }
134+
}
135+
136+
module IronResponseXssFlow = TaintTracking::Global<IronResponseXssConfig>;
137+
138+
import IronResponseXssFlow::PathGraph
139+
140+
from IronResponseXssFlow::PathNode sourceNode, IronResponseXssFlow::PathNode sinkNode
141+
where IronResponseXssFlow::flowPath(sourceNode, sinkNode)
142+
select sinkNode.getNode(), sourceNode, sinkNode, "Cross-site scripting vulnerability due to a $@.",
143+
sourceNode.getNode(), "user-provided value"
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
use iron::status;
2+
use iron::{IronResult, Request, Response};
3+
4+
fn handler(req: &mut Request) -> IronResult<Response> {
5+
let name = req.url.path();
6+
let body = format!("<h1>Hello, {:?}!</h1>", name);
7+
Ok(Response::with((status::Ok, body))) // BAD: no content type, the body may be sniffed as HTML
8+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
use iron::mime::Mime;
2+
use iron::status;
3+
use iron::{IronResult, Request, Response};
4+
5+
fn handler(req: &mut Request) -> IronResult<Response> {
6+
let name = req.url.path();
7+
let body = format!("Hello, {:?}!", name);
8+
let plain: Mime = "text/plain".parse().unwrap();
9+
Ok(Response::with((status::Ok, plain, body))) // GOOD: the body is declared as plain text
10+
}

‎rust/test/codeql-pack.lock.yml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,12 @@ dependencies:
1515
version: 1.0.62
1616
codeql/rust-all:
1717
version: 0.2.26
18+
codeql/rust-queries:
19+
version: 0.1.47
1820
codeql/ssa:
1921
version: 2.0.38
22+
codeql/suite-helpers:
23+
version: 1.0.62
2024
codeql/threat-models:
2125
version: 1.1.2
2226
codeql/tutorial:

‎rust/test/qlpack.yml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ name: githubsecuritylab/codeql-rust-tests
22
groups: [rust, test]
33
dependencies:
44
codeql/rust-all: '0.2.26'
5+
codeql/rust-queries: '0.1.47'
56
githubsecuritylab/codeql-rust-queries: '*'
67
githubsecuritylab/codeql-rust-extensions: '*'
78

0 commit comments

Comments
 (0)