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
55 changes: 55 additions & 0 deletions rust/src/audit/CWE-942/PermissiveCors.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>
Cross-Origin Resource Sharing (CORS) lets a server relax the browser's same-origin policy by
naming the origins that are allowed to read its responses in the
<code>Access-Control-Allow-Origin</code> response header. A policy that allows any origin, for
example by sending <code>Access-Control-Allow-Origin: *</code>, reflecting the request origin, or
using a framework's "allow any origin" or "permissive" CORS configuration, lets every website
read the responses of this service from a victim's browser.
</p>
<p>
This is harmless for truly public, unauthenticated data, but it exposes any sensitive data the
service returns (now or in the future), including data served to clients on a local or private
network that the attacker cannot reach directly.
</p>
<p>
This query recognizes, among others: <code>allow_any_origin()</code> (warp, actix-cors),
<code>Cors::permissive()</code> (actix-cors), <code>CorsLayer::permissive()</code>,
<code>CorsLayer::very_permissive()</code> and <code>allow_origin</code> with <code>Any</code>,
<code>"*"</code>, <code>AllowOrigin::any()</code> or <code>AllowOrigin::mirror_request()</code>
(tower-http), <code>AllowedOrigins::all()</code> (rocket_cors),
<code>AccessControlAllowOrigin::Any</code> (iron / hyper 0.10), and setting the
<code>Access-Control-Allow-Origin</code> header to <code>"*"</code> directly.
</p>
</overview>

<recommendation>
<p>
Allow only an explicit list of trusted origins. If the endpoint really serves only public data
that every website may read, the alert can be dismissed.
</p>
</recommendation>

<example>
<p>
In the following example, an axum application uses a tower-http <code>CorsLayer</code> that
allows the wildcard origin, so any website can read the JSON responses:
</p>
<sample src="PermissiveCorsBad.rs" />
<p>
The fix is to allow only the trusted front-end origin:
</p>
<sample src="PermissiveCorsGood.rs" />
</example>

<references>
<li>MDN: <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">Cross-Origin Resource Sharing (CORS)</a>.</li>
<li>OWASP: <a href="https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/11-Client-side_Testing/07-Testing_Cross_Origin_Resource_Sharing">Testing Cross Origin Resource Sharing</a>.</li>
<li>Common Weakness Enumeration: <a href="https://cwe.mitre.org/data/definitions/942.html">CWE-942</a>.</li>
</references>
</qhelp>
201 changes: 201 additions & 0 deletions rust/src/audit/CWE-942/PermissiveCors.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
/**
* @name Permissive CORS configuration
* @description Allowing any origin to read cross-origin responses lets an
* arbitrary website read data served to a victim's browser.
* @kind problem
* @problem.severity warning
* @security-severity 2.5
* @sub-severity low
* @precision very-low
* @id githubsecuritylab/audit/rust/permissive-cors
* @tags security
* experimental
* audit
* external/cwe/cwe-942
*/

import rust
import codeql.rust.dataflow.DataFlow

/** Holds if `e` is a string literal whose value is `value`. */
bindingset[value]
private predicate isStringLiteral(Expr e, string value) {
e.(StringLiteralExpr).getTextValue() = "\"" + value + "\""
}

/**
* Holds if `c` builds a header value from its argument, such as `HeaderValue::from_static("*")`.
*/
private predicate isHeaderValueConstructor(CallExpr c) {
isPathCall(c, "HeaderValue",
["from_static", "from_str", "from_bytes", "from_maybe_shared", "try_from"])
or
isPathCall(c, "String", "from")
or
isPathCall(c, "AllowOrigin", "exact")
}

/**
* Gets an expression that the value of `e` is taken from: the receiver of a method call, the
* argument of a constructor of a header value, a referenced or `?`-operand expression, or a reaching
* assignment to a local variable read by `e`.
*
* This handles wrappers such as `"*".parse::<HeaderValue>().unwrap()`,
* `HeaderValue::from_static("*")` and `let origin = "*"; ... origin`. Other arguments are not
* followed: in `origin.parse::<HeaderValue>().expect("*")` the `"*"` is only a message.
*/
private Expr getAnInnerExpr(Expr e) {
result = e.(MethodCallExpr).getReceiver()
or
isHeaderValueConstructor(e) and result = e.(CallExpr).getArgList().getAnArg()
or
result = e.(RefExpr).getExpr()
or
result = e.(TryExpr).getExpr()
or
exists(Variable v, DataFlow::ExprNode source, DataFlow::ExprNode target |
e = v.getAnAccess() and
target.asExpr() = e and
source.asExpr() = result and
source.asExpr() != e and
DataFlow::localFlow(source, target)
)
}

/** Holds if `p` is a path whose final segment is `name` (for example `Any` or `cors::Any`). */
bindingset[name]
private predicate pathEndsWith(Path p, string name) { p.getText() = name }

/**
* Holds if `p` is a path whose final segment is `name` and whose qualifier
* ends in `qualifier` (for example `CorsLayer::permissive`).
*/
bindingset[qualifier, name]
private predicate qualifiedPathEndsWith(Path p, string qualifier, string name) {
p.getText() = name and
p.getQualifier().getText() = qualifier
}

/** Holds if `c` is a call to a function at a path ending in `qualifier::name`. */
bindingset[qualifier, name]
private predicate isPathCall(CallExpr c, string qualifier, string name) {
qualifiedPathEndsWith(c.getFunction().(PathExpr).getPath(), qualifier, name)
}

/** Holds if `e` is (or is derived from) a value denoting the wildcard CORS origin. */
private predicate isWildcardOriginValue(Expr e) {
isStringLiteral(e, "*")
or
// `tower_http::cors::Any`, `salvo::cors::Any`
pathEndsWith(e.(PathExpr).getPath(), "Any")
or
// `tower_http::cors::AllowOrigin::any()`, `AllowOrigin::mirror_request()`
isPathCall(e, "AllowOrigin", ["any", "mirror_request"])
or
isWildcardOriginValue(getAnInnerExpr(e))
}

/**
* Holds if `e` names the `Access-Control-Allow-Origin` header, either directly
* or via a header-name constructor such as `HeaderName::from_static(...)`.
*/
private predicate isAllowOriginHeaderName(Expr e) {
e.(StringLiteralExpr).getTextValue().toLowerCase() = "\"access-control-allow-origin\""
or
pathEndsWith(e.(PathExpr).getPath(), "ACCESS_CONTROL_ALLOW_ORIGIN")
or
isAllowOriginHeaderName(e.(RefExpr).getExpr())
or
exists(CallExpr c | c = e |
isPathCall(c, "HeaderName", ["from_static", "from_lowercase", "from_bytes", "from_str"]) and
isAllowOriginHeaderName(c.getArgList().getArg(0))
)
or
exists(MethodCallExpr c |
c = e and
c.getIdentifier().getText() in ["unwrap", "expect"] and
isAllowOriginHeaderName(c.getReceiver())
)
or
isAllowOriginHeaderName(e.(TryExpr).getExpr())
}

/**
* Holds if `call` sets a header on a response, a header map or a header layer: `insert`, `append`
* and `header` style methods, and functions such as `Header::new` and `warp::reply::with::header`.
* A call that only receives a header name and a value, such as a comparison helper, does not.
*/
private predicate isHeaderWriter(Expr call) {
call.(MethodCallExpr).getIdentifier().getText() =
["insert", "append", "header", "insert_header", "append_header", "add_header", "set_header"]
or
call.(CallExpr).getFunction().(PathExpr).getPath().getText() =
["header", "with_header", "overriding", "if_not_present", "appending"]
or
isPathCall(call, "Header", "new")
}

/**
* Holds if `name` and `value` are an adjacent header name/value pair, either
* consecutive arguments of a call that sets a header (for example
* `headers.insert(name, value)` or `with_header(reply, name, value)`) or a
* 2-tuple `(name, value)`.
*/
private predicate isHeaderPair(Expr pair, Expr name, Expr value) {
isHeaderWriter(pair) and
exists(ArgList args, int i |
args = pair.(MethodCallExpr).getArgList() or args = pair.(CallExpr).getArgList()
|
name = args.getArg(i) and
value = args.getArg(i + 1)
Comment thread
felickz marked this conversation as resolved.
Resolved
)
or
pair.(TupleExpr).getNumberOfFields() = 2 and
name = pair.(TupleExpr).getField(0) and
value = pair.(TupleExpr).getField(1)
}

/**
* Holds if `e` configures a CORS policy (or sets a CORS response header) that
* allows any origin, described by `description`.
*/
predicate isPermissiveCors(Expr e, string description) {
// warp: `warp::cors().allow_any_origin()`; actix-cors: `Cors::default().allow_any_origin()`
e.(MethodCallExpr).getIdentifier().getText() = "allow_any_origin" and
e.(MethodCallExpr).getArgList().getNumberOfArgs() = 0 and
description = "This CORS policy allows any origin"
or
// tower-http / salvo: `.allow_origin(Any)`, `.allow_origin("*".parse().unwrap())`
e.(MethodCallExpr).getIdentifier().getText() = "allow_origin" and
isWildcardOriginValue(e.(MethodCallExpr).getArgList().getArg(0)) and
description = "This CORS policy allows any origin"
or
// actix-cors: `Cors::permissive()`; tower-http: `CorsLayer::permissive()` / `very_permissive()`
(
isPathCall(e, "Cors", "permissive")
or
isPathCall(e, "CorsLayer", ["permissive", "very_permissive"])
or
// rocket_cors: `AllowedOrigins::all()`
isPathCall(e, "AllowedOrigins", "all")
) and
description = "This CORS policy allows any origin"
or
// iron / hyper 0.10: `AccessControlAllowOrigin::Any`
qualifiedPathEndsWith(e.(PathExpr).getPath(), "AccessControlAllowOrigin", "Any") and
description = "This Access-Control-Allow-Origin header allows any origin"
or
// raw header: `headers.insert(ACCESS_CONTROL_ALLOW_ORIGIN, "*")`, `("Access-Control-Allow-Origin", "*")`
exists(Expr name, Expr value |
isHeaderPair(e, name, value) and
isAllowOriginHeaderName(name) and
isWildcardOriginValue(value)
) and
description = "This Access-Control-Allow-Origin header allows any origin"
}

from Expr e, string description
where isPermissiveCors(e, description)
select e,
description +
". Review whether the responses of this service contain sensitive or credentialed data."
9 changes: 9 additions & 0 deletions rust/src/audit/CWE-942/PermissiveCorsBad.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use axum::{http::HeaderValue, routing::get, Router};
use tower_http::cors::CorsLayer;

fn app() -> Router {
Router::new().route("/json", get(|| async { "{}" })).layer(
// BAD: any website can read responses from this service
CorsLayer::new().allow_origin("*".parse::<HeaderValue>().unwrap()),
)
}
9 changes: 9 additions & 0 deletions rust/src/audit/CWE-942/PermissiveCorsGood.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use axum::{http::HeaderValue, routing::get, Router};
use tower_http::cors::CorsLayer;

fn app() -> Router {
Router::new().route("/json", get(|| async { "{}" })).layer(
// GOOD: only the trusted front-end origin can read responses
CorsLayer::new().allow_origin("https://app.example.com".parse::<HeaderValue>().unwrap()),
)
}
22 changes: 22 additions & 0 deletions rust/test/audit/CWE-942/PermissiveCors/PermissiveCors.expected
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
| main.rs:11:20:12:31 | ... .allow_any_origin() | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:27:19:27:79 | ...::header(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:62:27:62:55 | ...::Any | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:99:13:100:66 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:108:20:108:79 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:114:20:114:53 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:120:20:120:59 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:126:20:126:68 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:132:20:132:79 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:139:20:139:88 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:147:20:147:88 | ... .allow_origin(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:161:20:161:42 | ...::permissive(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:167:20:167:47 | ...::very_permissive(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:172:9:172:90 | headers.insert(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:177:11:177:52 | TupleExpr | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:216:9:219:9 | headers.insert(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:225:9:228:9 | headers.insert(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:235:9:238:9 | headers.insert(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:280:28:280:63 | TupleExpr | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:293:23:293:56 | ... .allow_any_origin() | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:294:34:294:51 | ...::permissive(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
| main.rs:318:30:318:50 | ...::all(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
query: audit/CWE-942/PermissiveCors.ql
Loading