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
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Server-side request forgery (extended framework coverage)

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.

This query extends the standard `rust/request-forgery` query with:

- `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.
- Flow of captured variables into `async` blocks, such as a `warp` `Filter::then` closure parameter used inside `async move { ... }`.
- 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.

## Recommendation

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.

## Example

In the following example, a URL path parameter is used as the host of an outgoing request:

```rust
let routes = warp::path::param().then(|tainted_param: String| async move {
reqwest::Client::new()
.post(format!("https://{}", tainted_param)) // BAD
.send()
.await
});
```

The following example only uses the parameter in the path of a request to a fixed host:

```rust
let routes = warp::path::param().then(|tainted_param: String| async move {
reqwest::Client::new()
.post(format!("https://my.app/{}", tainted_param)) // GOOD
.send()
.await
});
```

## References

- OWASP: [Server Side Request Forgery](https://owasp.org/www-community/attacks/Server_Side_Request_Forgery).
- Common Weakness Enumeration: [CWE-918](https://cwe.mitre.org/data/definitions/918.html).
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/**
* @name Server-side request forgery (extended framework coverage)
* @description Making a network request with a URL whose host is derived from
* user-controlled data allows an attacker to make the server send
* requests to arbitrary (including internal) destinations.
* @kind path-problem
* @problem.severity error
* @security-severity 9.1
* @precision high
* @id rust/ssrf-reflection-injection
* @tags security
* external/cwe/cwe-918
*/

private import rust
private import codeql.rust.dataflow.DataFlow
private import codeql.rust.dataflow.Ssa
private import codeql.rust.dataflow.TaintTracking
private import codeql.rust.security.RequestForgeryExtensions

/**
* A read of an attacker-controlled field of an inbound `iron` HTTP request,
* such as `req.url` (whose authority comes from the `Host` header),
* `req.headers` or `req.body`.
*/
class IronRequestFieldSource extends RequestForgery::Source {
IronRequestFieldSource() {
exists(Struct s, string name |
s.getCanonicalPath() = "iron::request::Request" and
name = ["url", "headers", "body"] and
this.asExpr().(FieldExpr).getStructField() = s.getStructField(name)
)
}
}

/**
* Holds if `template` is the string literal of a format template that starts
* with a fixed scheme and host, followed by a path, query or fragment
* separator, for example `"https://my.app/{}"`. Values interpolated into such
* a template cannot change the destination host of the request.
*/
bindingset[template]
private predicate isFixedHostTemplate(string template) {
template.regexpMatch("(?s)r?#*\"[a-zA-Z][a-zA-Z0-9+.\\-]*://[^/{}?#@\\s\"\\\\]+[/?#].*")
}

/**
* A `format!(...)` call whose template starts with a fixed scheme and host,
* which is considered to sanitize request forgery.
*/
class FixedHostFormatBarrier extends RequestForgery::Barrier {
FixedHostFormatBarrier() {
exists(MacroExpr me, FormatArgsExpr fa |
this.asExpr() = me and
me.getMacroCall().getPath().getText() = "format" and
fa.getParentNode+() = me and
not exists(MacroExpr nested |
nested != me and
nested.getMacroCall().getPath().getText() = "format" and
fa.getParentNode+() = nested and
nested.getParentNode+() = me
) and
isFixedHostTemplate(fa.getTemplate().(LiteralExpr).getTextValue())
Comment thread
felickz marked this conversation as resolved.
Resolved
)
}
}

/**
* Holds if a captured value from `node1` reaches a read by `node2` in an
* `async` block, for example a closure parameter used in `async move { ... }`
* (as with `warp` `Filter::then`), without being overwritten first.
*/
private predicate asyncBlockCaptureStep(DataFlow::Node node1, DataFlow::Node node2) {
exists(Variable v, VariableAccess va, BlockExpr b, Ssa::Definition def |
b.isAsync() and
node1.asPat() = v.getPat() and
va = v.getAnAccess() and
va instanceof VariableReadAccess and
node2.asExpr() = va and
Comment thread
felickz marked this conversation as resolved.
Resolved
def.getARead() = va and
def.getAnUltimateDefinition() instanceof Ssa::CapturedEntryDefinition and
va.getParentNode+() = b and
not v.getPat().getParentNode+() = b
)
}

/**
* A taint-tracking configuration for detecting request forgery vulnerabilities.
*/
module SsrfReflectionInjectionConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node source) { source instanceof RequestForgery::Source }

predicate isSink(DataFlow::Node sink) { sink instanceof RequestForgery::Sink }

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

predicate isAdditionalFlowStep(DataFlow::Node node1, DataFlow::Node node2) {
asyncBlockCaptureStep(node1, node2)
}
}

module SsrfReflectionInjectionFlow = TaintTracking::Global<SsrfReflectionInjectionConfig>;

import SsrfReflectionInjectionFlow::PathGraph

from SsrfReflectionInjectionFlow::PathNode source, SsrfReflectionInjectionFlow::PathNode sink
where SsrfReflectionInjectionFlow::flowPath(source, sink)
select sink.getNode(), source, sink, "The URL of this request depends on a $@.", source.getNode(),
"user-provided value"
5 changes: 5 additions & 0 deletions languages/rust/custom/src/qlpack.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name: languages-rust-custom-src
version: 0.0.2
library: false
dependencies:
codeql/rust-all: "*"
5 changes: 5 additions & 0 deletions languages/rust/custom/test/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Generated by the Rust extractor when running `codeql test extract` / `codeql test run`
Cargo.toml
Cargo.lock
lib.rs
target/
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#select
| iron_app.rs:11:43:11:53 | request_url | iron_app.rs:9:27:9:33 | req.url | iron_app.rs:11:43:11:53 | request_url | The URL of this request depends on a $@. | iron_app.rs:9:27:9:33 | req.url | user-provided value |
| warp_app.rs:7:19:7:54 | MacroExpr | warp_app.rs:5:43:14:5 | \|...\| ... | warp_app.rs:7:19:7:54 | MacroExpr | The URL of this request depends on a $@. | warp_app.rs:5:43:14:5 | \|...\| ... | user-provided value |
| warp_app.rs:23:19:27:13 | MacroExpr | warp_app.rs:21:43:33:5 | \|...\| ... | warp_app.rs:23:19:27:13 | MacroExpr | The URL of this request depends on a $@. | warp_app.rs:21:43:33:5 | \|...\| ... | user-provided value |
edges
| iron_app.rs:9:13:9:23 | request_url | iron_app.rs:11:43:11:53 | request_url | provenance | Sink:MaD:5271 |
| iron_app.rs:9:27:9:33 | req.url | iron_app.rs:9:27:9:45 | ... .to_string() | provenance | MaD:364 |
| iron_app.rs:9:27:9:45 | ... .to_string() | iron_app.rs:9:13:9:23 | request_url | provenance | |
| warp_app.rs:5:43:14:5 | \|...\| ... | warp_app.rs:5:44:5:64 | ...: String | provenance | Src:MaD:740 |
| warp_app.rs:5:44:5:56 | tainted_param | warp_app.rs:7:41:7:53 | tainted_param | provenance | Config |
| warp_app.rs:5:44:5:64 | ...: String | warp_app.rs:5:44:5:56 | tainted_param | provenance | |
| warp_app.rs:7:27:7:53 | ...::format(...) | warp_app.rs:7:27:7:53 | { ... } | provenance | |
| warp_app.rs:7:27:7:53 | ...::must_use(...) | warp_app.rs:7:19:7:54 | MacroExpr | provenance | Sink:MaD:5244 |
| warp_app.rs:7:27:7:53 | MacroExpr | warp_app.rs:7:27:7:53 | ...::format(...) | provenance | MaD:346 |
| warp_app.rs:7:27:7:53 | { ... } | warp_app.rs:7:27:7:53 | ...::must_use(...) | provenance | MaD:13296 |
| warp_app.rs:7:41:7:53 | tainted_param | warp_app.rs:7:27:7:53 | MacroExpr | provenance | |
| warp_app.rs:21:43:33:5 | \|...\| ... | warp_app.rs:21:44:21:64 | ...: String | provenance | Src:MaD:740 |
| warp_app.rs:21:44:21:56 | tainted_param | warp_app.rs:25:17:25:29 | tainted_param | provenance | Config |
| warp_app.rs:21:44:21:64 | ...: String | warp_app.rs:21:44:21:56 | tainted_param | provenance | |
| warp_app.rs:24:17:26:56 | ...::format(...) | warp_app.rs:24:17:26:56 | { ... } | provenance | |
| warp_app.rs:24:17:26:56 | ...::must_use(...) | warp_app.rs:23:19:27:13 | MacroExpr | provenance | Sink:MaD:5244 |
| warp_app.rs:24:17:26:56 | MacroExpr | warp_app.rs:24:17:26:56 | ...::format(...) | provenance | MaD:346 |
| warp_app.rs:24:17:26:56 | { ... } | warp_app.rs:24:17:26:56 | ...::must_use(...) | provenance | MaD:13296 |
| warp_app.rs:25:17:25:29 | tainted_param | warp_app.rs:24:17:26:56 | MacroExpr | provenance | |
nodes
| iron_app.rs:9:13:9:23 | request_url | semmle.label | request_url |
| iron_app.rs:9:27:9:33 | req.url | semmle.label | req.url |
| iron_app.rs:9:27:9:45 | ... .to_string() | semmle.label | ... .to_string() |
| iron_app.rs:11:43:11:53 | request_url | semmle.label | request_url |
| warp_app.rs:5:43:14:5 | \|...\| ... | semmle.label | \|...\| ... |
| warp_app.rs:5:44:5:56 | tainted_param | semmle.label | tainted_param |
| warp_app.rs:5:44:5:64 | ...: String | semmle.label | ...: String |
| warp_app.rs:7:19:7:54 | MacroExpr | semmle.label | MacroExpr |
| warp_app.rs:7:27:7:53 | ...::format(...) | semmle.label | ...::format(...) |
| warp_app.rs:7:27:7:53 | ...::must_use(...) | semmle.label | ...::must_use(...) |
| warp_app.rs:7:27:7:53 | MacroExpr | semmle.label | MacroExpr |
| warp_app.rs:7:27:7:53 | { ... } | semmle.label | { ... } |
| warp_app.rs:7:41:7:53 | tainted_param | semmle.label | tainted_param |
| warp_app.rs:21:43:33:5 | \|...\| ... | semmle.label | \|...\| ... |
| warp_app.rs:21:44:21:56 | tainted_param | semmle.label | tainted_param |
| warp_app.rs:21:44:21:64 | ...: String | semmle.label | ...: String |
| warp_app.rs:23:19:27:13 | MacroExpr | semmle.label | MacroExpr |
| warp_app.rs:24:17:26:56 | ...::format(...) | semmle.label | ...::format(...) |
| warp_app.rs:24:17:26:56 | ...::must_use(...) | semmle.label | ...::must_use(...) |
| warp_app.rs:24:17:26:56 | MacroExpr | semmle.label | MacroExpr |
| warp_app.rs:24:17:26:56 | { ... } | semmle.label | { ... } |
| warp_app.rs:25:17:25:29 | tainted_param | semmle.label | tainted_param |
subpaths
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
query: SsrfReflectionInjection/SsrfReflectionInjection.ql
postprocess: utils/test/InlineExpectationsTestQuery.ql
38 changes: 38 additions & 0 deletions languages/rust/custom/test/SsrfReflectionInjection/iron_app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use iron::prelude::*;
use iron::status;
use iron::Request;

// BAD: the full inbound request URL (whose authority comes from the attacker-controlled
// `Host` header) is fetched by the server.
pub fn bad_request_url() {
Iron::new(|req: &mut Request| {
let request_url = req.url.to_string(); // $ Source

let data = reqwest::blocking::get(request_url) // $ Alert
.expect("failed")
.text()
.expect("error");

Ok(Response::with((status::Ok, data)))
})
.http("localhost:8080")
.unwrap();
}

// GOOD: the request URL is only used in the path of a request to a fixed host.
pub fn good_fixed_host() {
Iron::new(|req: &mut Request| {
let request_url = req.url.to_owned();

let path = format!("http://my.app/{request_url}");

let data = reqwest::blocking::get(path)
.expect("failed")
.text()
.expect("error");

Ok(Response::with((status::Ok, data)))
})
.http("localhost:8081")
.unwrap();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
qltest_cargo_check: true
qltest_dependencies:
- iron = { version = "0.6.1" }
- reqwest = { version = "0.12", features = ["blocking"] }
- tokio = { version = "1.0", features = ["full"] }
- warp = { version = "0.3" }
85 changes: 85 additions & 0 deletions languages/rust/custom/test/SsrfReflectionInjection/warp_app.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use warp::Filter;

// BAD: a URL path parameter is used as the host of an outbound request.
pub async fn bad_path_param() {
let routes = warp::path::param().then(|tainted_param: String| async move {
let response = reqwest::Client::new()
.post(format!("https://{}", tainted_param)) // $ Alert
.form(&[("one", "1")])
.send()
.await
.expect("send");

format!("{}", response.status())
}); // $ Source (the source is the `then` closure, reported at its last line)

warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}

// BAD: a nested fixed-host template does not make the outer template safe.
pub async fn bad_nested_fixed_host_template() {
let routes = warp::path::param().then(|tainted_param: String| async move {
let response = reqwest::Client::new()
.post(format!(
"https://{}/{}",
tainted_param,
format!("https://my.app/{}", "constant")
)) // $ Alert
.send()
.await
.expect("send");

format!("{}", response.status())
}); // $ Source

warp::serve(routes).run(([127, 0, 0, 1], 3032)).await;
}

// GOOD: the path parameter is only used in the path of a request to a fixed host.
pub async fn good_fixed_host() {
let routes = warp::path::param().then(|tainted_param: String| async move {
let response = reqwest::Client::new()
.post(format!("https://my.app/{}", tainted_param))
.send()
.await
.expect("send");

format!("{}", response.status())
});

warp::serve(routes).run(([127, 0, 0, 1], 3031)).await;
}

// GOOD: overwriting the captured parameter with a fixed URL removes taint.
pub async fn good_overwrite_before_use() {
let routes = warp::path::param().then(|mut tainted_param: String| async move {
tainted_param = "https://my.app/".to_owned();

let response = reqwest::Client::new()
.post(tainted_param)
.send()
.await
.expect("send");

format!("{}", response.status())
});

warp::serve(routes).run(([127, 0, 0, 1], 3033)).await;
}

// GOOD: assigning the result of a fixed-host template removes taint.
pub async fn good_fixed_host_reassignment() {
let routes = warp::path::param().then(|mut tainted_param: String| async move {
tainted_param = format!("https://my.app/{}", tainted_param);

let response = reqwest::Client::new()
.post(tainted_param)
.send()
.await
.expect("send");

format!("{}", response.status())
});

warp::serve(routes).run(([127, 0, 0, 1], 3034)).await;
}
5 changes: 5 additions & 0 deletions languages/rust/custom/test/qlpack.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
name: languages-rust-custom-test
version: 0.0.2
dependencies:
languages-rust-custom-src: ${workspace}
extractor: rust
4 changes: 2 additions & 2 deletions scripts/install-codeql-packs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ Install CodeQL packs for all packs discovered in the CodeQL workspace.
OPTIONS:
--language <lang> Install packs only for the specified language
Valid values: actions, cpp, csharp, go, java, javascript,
python, ruby
python, ruby, rust
-h, --help Show this help message

By default, the script installs packs for all languages in the workspace.
Expand Down Expand Up @@ -44,7 +44,7 @@ while [[ $# -gt 0 ]]; do
done

## Validate language if provided
VALID_LANGUAGES=("actions" "cpp" "csharp" "go" "java" "javascript" "python" "ruby")
VALID_LANGUAGES=("actions" "cpp" "csharp" "go" "java" "javascript" "python" "ruby" "rust")
if [[ -n "${LANGUAGE}" ]]; then
LANGUAGE_VALID=false
for valid_lang in "${VALID_LANGUAGES[@]}"; do
Expand Down
Loading