Skip to content

Commit 4b2295d

Browse files
felickzCopilot
andauthored
[New Query - githubsecuritylab/rust/ssrf-reflection-injection] - detect Rust request forgery through Iron handlers and async closures (#258)
* Rust: add the server-side request forgery query for Iron and async closures Add githubsecuritylab/rust/ssrf-reflection-injection (CWE-918). It uses the sources, sinks and barriers of the standard rust/request-forgery query and adds three things: reads of the url, headers and body of an inbound Iron request as sources, a barrier for format! templates that start with a fixed scheme and host, and a flow step for variables that an async block captures, as in a warp Filter::then closure. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust SSRF: capture the value that is live when the async block is created Start the async capture step from the value that a variable has when the async block is created: the pattern that declares it, or the right-hand side of an assignment that is not overwritten before the block. A fixed URL that is assigned before the block no longer reports, and a value that is derived from the parameter before the block still does. Add regressions for an overwrite before the capture, a derived value before the capture, and a nested std::format! template. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust SSRF: select only the outermost template, follow the capture site of nested closures The fixed-host barrier looked for nested format! calls only. A format_args! call in the arguments of a format! call could make the outer call a barrier and hide a request whose host is attacker controlled. Use the outermost format arguments of the call, which are its own template. The async capture step used the declaring pattern when the async block is created in a closure that is nested in the scope of the variable, so an assignment before that closure was ignored. Take the value that the variable has where the outermost closure or async block is created in its scope. Add regressions for a nested format_args! template and for an overwrite and a derived value before a nested closure. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust SSRF: track the captured value through each closure and async block The capture step took the value that the variable has where the outermost closure or async block is created in its scope. An assignment inside an intervening closure, before it creates the async block, was not seen, so a fixed URL that replaces the parameter there was still reported. Follow the value across every boundary instead: a closure or async block passes on the value that it captured unless it assigns the variable first, and the async block gets the value that is live where it is created. Add regressions for an overwrite inside the closure before the async block is created (a fixed URL), for one after it is created (still tainted), and for a derived value inside the closure (still tainted). 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 2191adc commit 4b2295d

8 files changed

Lines changed: 3131 additions & 0 deletions

File tree

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Server-side request forgery (extended framework coverage)
2+
3+
Directly incorporating user input into the URL of an outgoing HTTP request can make the server send requests to destinations chosen by an attacker, for example internal services or cloud metadata endpoints. The response may then be reflected back to the attacker.
4+
5+
This query extends the standard `rust/request-forgery` query with:
6+
7+
- `iron` request sources: reads of the `url`, `headers` and `body` fields of an inbound `iron::request::Request`. The authority of `req.url` is derived from the attacker-controlled `Host` header.
8+
- Flow of captured variables into `async` blocks, such as a `warp` `Filter::then` closure parameter used inside `async move { ... }`.
9+
- A barrier for `format!` templates that start with a fixed scheme and host (for example `"https://my.app/{}"`), because interpolated values cannot change the destination host.
10+
11+
## Recommendation
12+
13+
Do not let user input select the scheme, host or port of an outgoing request. Use a fixed base URL and only append validated path or query components, or check the destination against an allowlist of permitted hosts.
14+
15+
## Example
16+
17+
In the following example, a URL path parameter is used as the host of an outgoing request:
18+
19+
```rust
20+
let routes = warp::path::param().then(|tainted_param: String| async move {
21+
reqwest::Client::new()
22+
.post(format!("https://{}", tainted_param)) // BAD
23+
.send()
24+
.await
25+
});
26+
```
27+
28+
The following example only uses the parameter in the path of a request to a fixed host:
29+
30+
```rust
31+
let routes = warp::path::param().then(|tainted_param: String| async move {
32+
reqwest::Client::new()
33+
.post(format!("https://my.app/{}", tainted_param)) // GOOD
34+
.send()
35+
.await
36+
});
37+
```
38+
39+
## References
40+
41+
- OWASP: [Server Side Request Forgery](https://owasp.org/www-community/attacks/Server_Side_Request_Forgery).
42+
- Common Weakness Enumeration: [CWE-918](https://cwe.mitre.org/data/definitions/918.html).
Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,205 @@
1+
/**
2+
* @name Server-side request forgery (extended framework coverage)
3+
* @description Making a network request with a URL whose host is derived from
4+
* user-controlled data allows an attacker to make the server send
5+
* requests to arbitrary (including internal) destinations.
6+
* @kind path-problem
7+
* @problem.severity error
8+
* @security-severity 9.1
9+
* @precision medium
10+
* @id githubsecuritylab/rust/ssrf-reflection-injection
11+
* @tags security
12+
* experimental
13+
* external/cwe/cwe-918
14+
*/
15+
16+
private import rust
17+
private import codeql.rust.controlflow.ControlFlowGraph
18+
private import codeql.rust.dataflow.DataFlow
19+
private import codeql.rust.dataflow.Ssa
20+
private import codeql.rust.dataflow.TaintTracking
21+
private import codeql.rust.security.RequestForgeryExtensions
22+
23+
/**
24+
* A read of an attacker-controlled field of an inbound `iron` HTTP request,
25+
* such as `req.url` (whose authority comes from the `Host` header),
26+
* `req.headers` or `req.body`.
27+
*/
28+
class IronRequestFieldSource extends RequestForgery::Source {
29+
IronRequestFieldSource() {
30+
exists(Struct s, string name |
31+
s.getCanonicalPath() = "iron::request::Request" and
32+
name = ["url", "headers", "body"] and
33+
this.asExpr().(FieldExpr).getStructField() = s.getStructField(name)
34+
)
35+
}
36+
}
37+
38+
/**
39+
* Holds if `template` is the string literal of a format template that starts
40+
* with a fixed scheme and host, followed by a path, query or fragment
41+
* separator, for example `"https://my.app/{}"`. Values interpolated into such
42+
* a template cannot change the destination host of the request.
43+
*/
44+
bindingset[template]
45+
private predicate isFixedHostTemplate(string template) {
46+
template.regexpMatch("(?s)r?#*\"[a-zA-Z][a-zA-Z0-9+.\\-]*://[^/{}?#@\\s\"\\\\]+[/?#].*")
47+
}
48+
49+
/**
50+
* A `format!(...)` call whose template starts with a fixed scheme and host,
51+
* which is considered to sanitize request forgery.
52+
*/
53+
class FixedHostFormatBarrier extends RequestForgery::Barrier {
54+
FixedHostFormatBarrier() {
55+
exists(MacroExpr me, FormatArgsExpr fa |
56+
this.asExpr() = me and
57+
me.getMacroCall().getPath().getText() = "format" and
58+
fa.getParentNode+() = me and
59+
// the template of this `format!` call, not the template of a macro call in its arguments
60+
not exists(FormatArgsExpr outer |
61+
outer != fa and
62+
outer.getParentNode+() = me and
63+
fa.getParentNode+() = outer
64+
) and
65+
isFixedHostTemplate(fa.getTemplate().(LiteralExpr).getTextValue())
66+
)
67+
}
68+
}
69+
70+
/**
71+
* Holds if the closure or `async` block `scope` reads the variable `v`, perhaps in a closure or an
72+
* `async` block that is nested in it, and does not declare `v`.
73+
*/
74+
private predicate capturesVariable(Variable v, AstNode scope) {
75+
(scope instanceof ClosureExpr or scope.(BlockExpr).isAsync()) and
76+
exists(VariableReadAccess read | read = v.getAnAccess() and read.getParentNode+() = scope) and
77+
not v.getPat().getParentNode+() = scope
78+
}
79+
80+
/** Holds if the variable `v` is read in an `async` block that does not declare it. */
81+
private predicate isCapturedByAsyncBlock(Variable v) {
82+
exists(BlockExpr b | b.isAsync() and capturesVariable(v, b))
83+
}
84+
85+
/** Holds if the control flow node `n` assigns to the variable `v`. */
86+
private predicate assignsTo(CfgNode n, Variable v) {
87+
exists(VariableWriteAccess write | write.getVariable() = v |
88+
n.getAstNode() = write or n.getAstNode() = write.getAssignmentExpr()
89+
)
90+
}
91+
92+
/**
93+
* Holds if the value that `source` gives to the variable `v` can still be its value at the control
94+
* flow node `n`. The `source` is the pattern that declares `v`, or an assignment to `v`, and no
95+
* other assignment to `v` lies on the path from it to `n`.
96+
*/
97+
private predicate valueLiveAt(Variable v, AstNode source, CfgNode n) {
98+
isCapturedByAsyncBlock(v) and
99+
(
100+
source = v.getPat()
101+
or
102+
source = any(VariableWriteAccess write | write.getVariable() = v).getAssignmentExpr()
103+
) and
104+
n.getAstNode() = source
105+
or
106+
exists(CfgNode pred |
107+
valueLiveAt(v, source, pred) and
108+
n = pred.getASuccessor() and
109+
not assignsTo(n, v)
110+
)
111+
}
112+
113+
/** Holds if `n` is the entry node of a scope: it has no AST node and no predecessor. */
114+
private predicate isEntryNode(CfgNode n) {
115+
not exists(n.getAstNode()) and not exists(n.getAPredecessor())
116+
}
117+
118+
/**
119+
* Holds if the value that `v` has when the closure or `async` block that contains the control flow
120+
* node `n` starts can still be its value at `n`: no assignment to `v` lies on a path from the start
121+
* of that closure or block to `n`.
122+
*/
123+
private predicate entryValueLiveAt(Variable v, CfgNode n) {
124+
isCapturedByAsyncBlock(v) and
125+
exists(CfgNode entry |
126+
isEntryNode(entry) and
127+
n = entry.getASuccessor() and
128+
capturesVariable(v, n.getScope()) and
129+
not assignsTo(n, v)
130+
)
131+
or
132+
exists(CfgNode pred |
133+
entryValueLiveAt(v, pred) and
134+
n = pred.getASuccessor() and
135+
not assignsTo(n, v)
136+
)
137+
}
138+
139+
/**
140+
* Holds if the value that `source` gives to the variable `v` can be its value where the closure or
141+
* `async` block `c` is created. The `source` is the pattern that declares `v`, or an assignment to
142+
* `v`. It either reaches that point in the scope that creates `c`, or the closure or `async` block
143+
* that creates `c` captured it and does not overwrite it before `c` is created.
144+
*/
145+
private predicate valueAtCreation(Variable v, AstNode source, AstNode c) {
146+
(c instanceof ClosureExpr or c.(BlockExpr).isAsync()) and
147+
exists(CfgNode creation | creation.getAstNode() = c |
148+
valueLiveAt(v, source, creation)
149+
or
150+
entryValueLiveAt(v, creation) and
151+
valueAtCreation(v, source, creation.getScope())
152+
)
153+
}
154+
155+
/**
156+
* Holds if a captured value from `node1` reaches a read by `node2` in an
157+
* `async` block, for example a closure parameter used in `async move { ... }`
158+
* (as with `warp` `Filter::then`), without being overwritten first.
159+
*
160+
* The captured value is the one that the variable has when the closure or `async` block that contains
161+
* the read is created: the pattern that declares it, or the right-hand side of an assignment that is
162+
* not overwritten before that point. A closure or `async` block between the read and the declaration
163+
* passes on the value that it captured unless it assigns the variable first.
164+
*/
165+
private predicate asyncBlockCaptureStep(DataFlow::Node node1, DataFlow::Node node2) {
166+
exists(Variable v, VariableReadAccess va, BlockExpr b, Ssa::Definition def, AstNode source |
167+
b.isAsync() and
168+
va = v.getAnAccess() and
169+
node2.asExpr() = va and
170+
def.getARead() = va and
171+
def.getAnUltimateDefinition() instanceof Ssa::CapturedEntryDefinition and
172+
va.getParentNode+() = b and
173+
not v.getPat().getParentNode+() = b and
174+
valueAtCreation(v, source, va.getEnclosingCfgScope()) and
175+
(
176+
node1.asPat() = source
177+
or
178+
node1.asExpr() = source.(AssignmentExpr).getRhs()
179+
)
180+
)
181+
}
182+
183+
/**
184+
* A taint-tracking configuration for detecting request forgery vulnerabilities.
185+
*/
186+
module SsrfReflectionInjectionConfig implements DataFlow::ConfigSig {
187+
predicate isSource(DataFlow::Node source) { source instanceof RequestForgery::Source }
188+
189+
predicate isSink(DataFlow::Node sink) { sink instanceof RequestForgery::Sink }
190+
191+
predicate isBarrier(DataFlow::Node barrier) { barrier instanceof RequestForgery::Barrier }
192+
193+
predicate isAdditionalFlowStep(DataFlow::Node node1, DataFlow::Node node2) {
194+
asyncBlockCaptureStep(node1, node2)
195+
}
196+
}
197+
198+
module SsrfReflectionInjectionFlow = TaintTracking::Global<SsrfReflectionInjectionConfig>;
199+
200+
import SsrfReflectionInjectionFlow::PathGraph
201+
202+
from SsrfReflectionInjectionFlow::PathNode source, SsrfReflectionInjectionFlow::PathNode sink
203+
where SsrfReflectionInjectionFlow::flowPath(source, sink)
204+
select sink.getNode(), source, sink, "The URL of this request depends on a $@.", source.getNode(),
205+
"user-provided value"

0 commit comments

Comments
 (0)