Skip to content

Commit d149ca5

Browse files
felickzCopilot
andauthored
[New Audit Query - githubsecuritylab/audit/rust/permissive-cors] - detect Rust permissive CORS policies (#261)
* Rust: add the permissive CORS audit query Add githubsecuritylab/audit/rust/permissive-cors (CWE-942). It reports a CORS policy or an Access-Control-Allow-Origin header that allows any origin, for warp, actix-cors, tower-http, rocket_cors, Iron and raw headers. It is an audit query: a wildcard origin is often intended for public data, so the message asks for a review, and the query is not selected by the default Rust suite. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust CORS audit: restrict wildcard and header matching Follow call arguments only for constructors of header values, so a wildcard that is only the message of expect no longer makes an exact origin look like a wildcard. Accept a header name and value pair only for calls that set a header, so a read-only helper that receives them is not reported. Add a regression for each. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust CORS audit: follow only value-preserving methods, correct the help text Follow the receiver of a method call only for methods that keep the value (parse, unwrap, expect, to_string, to_owned, into, try_into, clone, as_str, as_ref, as_bytes, to_vec, ok, map_err), so a wildcard that is changed with replace before it is used is not reported. Add regressions for an origin and a raw header value. Correct the query help: a browser does not honor a wildcard origin for requests that carry credentials. A wildcard exposes data that is protected only by the location of the client, and session-protected data is exposed by a reflected origin together with Access-Control-Allow-Credentials: true. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust CORS audit: follow local aliases of the header name The header name of a raw Access-Control-Allow-Origin header was recognized only when it was written in the call. A name that is held in a local variable, as in `let name = ACCESS_CONTROL_ALLOW_ORIGIN;`, was missed. Follow the variable to the value that reaches it, as is already done for the header value, so that a later assignment replaces an earlier one. Add regressions for a name from a constant and from a constructor, and for a name that is replaced before it is used. 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 92d109c commit d149ca5

7 files changed

Lines changed: 707 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
<!DOCTYPE qhelp PUBLIC
2+
"-//Semmle//qhelp//EN"
3+
"qhelp.dtd">
4+
<qhelp>
5+
6+
<overview>
7+
<p>
8+
Cross-Origin Resource Sharing (CORS) lets a server relax the browser's same-origin policy by
9+
naming the origins that are allowed to read its responses in the
10+
<code>Access-Control-Allow-Origin</code> response header. A policy that allows any origin, for
11+
example by sending <code>Access-Control-Allow-Origin: *</code> or by using a framework's "allow any
12+
origin" or "permissive" CORS configuration, lets every website read the responses that the browser
13+
requests without credentials.
14+
</p>
15+
<p>
16+
This is harmless for truly public data. It exposes data that is protected only by where the client
17+
is, such as a service on localhost or on a private network that the attacker cannot reach directly
18+
but the victim's browser can. A browser does not honor a wildcard for requests that carry
19+
credentials (cookies or HTTP authentication), so a wildcard alone does not expose data that a login
20+
session protects. That data is exposed when a policy reflects the request origin (for example
21+
<code>AllowOrigin::mirror_request()</code> or <code>CorsLayer::very_permissive()</code>) and also
22+
sets <code>Access-Control-Allow-Credentials: true</code>.
23+
</p>
24+
<p>
25+
This query recognizes, among others: <code>allow_any_origin()</code> (warp, actix-cors),
26+
<code>Cors::permissive()</code> (actix-cors), <code>CorsLayer::permissive()</code>,
27+
<code>CorsLayer::very_permissive()</code> and <code>allow_origin</code> with <code>Any</code>,
28+
<code>"*"</code>, <code>AllowOrigin::any()</code> or <code>AllowOrigin::mirror_request()</code>
29+
(tower-http), <code>AllowedOrigins::all()</code> (rocket_cors),
30+
<code>AccessControlAllowOrigin::Any</code> (iron / hyper 0.10), and setting the
31+
<code>Access-Control-Allow-Origin</code> header to <code>"*"</code> directly.
32+
</p>
33+
</overview>
34+
35+
<recommendation>
36+
<p>
37+
Allow only an explicit list of trusted origins. If the endpoint really serves only public data
38+
that every website may read, the alert can be dismissed.
39+
</p>
40+
</recommendation>
41+
42+
<example>
43+
<p>
44+
In the following example, an axum application uses a tower-http <code>CorsLayer</code> that
45+
allows the wildcard origin, so any website can read the JSON responses:
46+
</p>
47+
<sample src="PermissiveCorsBad.rs" />
48+
<p>
49+
The fix is to allow only the trusted front-end origin:
50+
</p>
51+
<sample src="PermissiveCorsGood.rs" />
52+
</example>
53+
54+
<references>
55+
<li>MDN: <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">Cross-Origin Resource Sharing (CORS)</a>.</li>
56+
<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>
57+
<li>Common Weakness Enumeration: <a href="https://cwe.mitre.org/data/definitions/942.html">CWE-942</a>.</li>
58+
</references>
59+
</qhelp>
Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
/**
2+
* @name Permissive CORS configuration
3+
* @description Allowing any origin to read cross-origin responses lets an
4+
* arbitrary website read data served to a victim's browser.
5+
* @kind problem
6+
* @problem.severity warning
7+
* @security-severity 2.5
8+
* @sub-severity low
9+
* @precision very-low
10+
* @id githubsecuritylab/audit/rust/permissive-cors
11+
* @tags security
12+
* experimental
13+
* audit
14+
* external/cwe/cwe-942
15+
*/
16+
17+
import rust
18+
import codeql.rust.dataflow.DataFlow
19+
20+
/** Holds if `e` is a string literal whose value is `value`. */
21+
bindingset[value]
22+
private predicate isStringLiteral(Expr e, string value) {
23+
e.(StringLiteralExpr).getTextValue() = "\"" + value + "\""
24+
}
25+
26+
/**
27+
* Holds if `c` builds a header value from its argument, such as `HeaderValue::from_static("*")`.
28+
*/
29+
private predicate isHeaderValueConstructor(CallExpr c) {
30+
isPathCall(c, "HeaderValue",
31+
["from_static", "from_str", "from_bytes", "from_maybe_shared", "try_from"])
32+
or
33+
isPathCall(c, "String", "from")
34+
or
35+
isPathCall(c, "AllowOrigin", "exact")
36+
}
37+
38+
/**
39+
* Holds if the method `name` returns its receiver, or a conversion of it, without changing the value:
40+
* parsing, unwrapping and conversions. A method that changes the value, such as `replace`, is not
41+
* listed.
42+
*/
43+
private predicate isValuePreservingMethod(string name) {
44+
name =
45+
[
46+
"parse", "unwrap", "expect", "to_string", "to_owned", "into", "try_into", "clone", "as_str",
47+
"as_ref", "as_bytes", "to_vec", "ok", "map_err"
48+
]
49+
}
50+
51+
/**
52+
* Gets an expression whose value the read `e` of a local variable can have: the initializer or the
53+
* right-hand side of an assignment that reaches `e`. A later assignment replaces the earlier one, so
54+
* only the one that is live at `e` is followed.
55+
*/
56+
private Expr getAReachingValue(Expr e) {
57+
exists(Variable v, DataFlow::ExprNode source, DataFlow::ExprNode target |
58+
e = v.getAnAccess() and
59+
target.asExpr() = e and
60+
source.asExpr() = result and
61+
source.asExpr() != e and
62+
DataFlow::localFlow(source, target)
63+
)
64+
}
65+
66+
/**
67+
* Gets an expression that the value of `e` is taken from: the receiver of a value-preserving method
68+
* call, the argument of a constructor of a header value, a referenced or `?`-operand expression, or a
69+
* reaching assignment to a local variable read by `e`.
70+
*
71+
* This handles wrappers such as `"*".parse::<HeaderValue>().unwrap()`,
72+
* `HeaderValue::from_static("*")` and `let origin = "*"; ... origin`. Other arguments are not
73+
* followed: in `origin.parse::<HeaderValue>().expect("*")` the `"*"` is only a message. Other methods
74+
* are not followed either: `"*".replace("*", "https://trusted.example.com")` is not a wildcard.
75+
*/
76+
private Expr getAnInnerExpr(Expr e) {
77+
result = e.(MethodCallExpr).getReceiver() and
78+
isValuePreservingMethod(e.(MethodCallExpr).getIdentifier().getText())
79+
or
80+
isHeaderValueConstructor(e) and result = e.(CallExpr).getArgList().getAnArg()
81+
or
82+
result = e.(RefExpr).getExpr()
83+
or
84+
result = e.(TryExpr).getExpr()
85+
or
86+
result = getAReachingValue(e)
87+
}
88+
89+
/** Holds if `p` is a path whose final segment is `name` (for example `Any` or `cors::Any`). */
90+
bindingset[name]
91+
private predicate pathEndsWith(Path p, string name) { p.getText() = name }
92+
93+
/**
94+
* Holds if `p` is a path whose final segment is `name` and whose qualifier
95+
* ends in `qualifier` (for example `CorsLayer::permissive`).
96+
*/
97+
bindingset[qualifier, name]
98+
private predicate qualifiedPathEndsWith(Path p, string qualifier, string name) {
99+
p.getText() = name and
100+
p.getQualifier().getText() = qualifier
101+
}
102+
103+
/** Holds if `c` is a call to a function at a path ending in `qualifier::name`. */
104+
bindingset[qualifier, name]
105+
private predicate isPathCall(CallExpr c, string qualifier, string name) {
106+
qualifiedPathEndsWith(c.getFunction().(PathExpr).getPath(), qualifier, name)
107+
}
108+
109+
/** Holds if `e` is (or is derived from) a value denoting the wildcard CORS origin. */
110+
private predicate isWildcardOriginValue(Expr e) {
111+
isStringLiteral(e, "*")
112+
or
113+
// `tower_http::cors::Any`, `salvo::cors::Any`
114+
pathEndsWith(e.(PathExpr).getPath(), "Any")
115+
or
116+
// `tower_http::cors::AllowOrigin::any()`, `AllowOrigin::mirror_request()`
117+
isPathCall(e, "AllowOrigin", ["any", "mirror_request"])
118+
or
119+
isWildcardOriginValue(getAnInnerExpr(e))
120+
}
121+
122+
/**
123+
* Holds if `e` names the `Access-Control-Allow-Origin` header, either directly,
124+
* via a header-name constructor such as `HeaderName::from_static(...)`, or through a
125+
* local variable that holds such a name (`let name = ACCESS_CONTROL_ALLOW_ORIGIN;`).
126+
*/
127+
private predicate isAllowOriginHeaderName(Expr e) {
128+
e.(StringLiteralExpr).getTextValue().toLowerCase() = "\"access-control-allow-origin\""
129+
or
130+
pathEndsWith(e.(PathExpr).getPath(), "ACCESS_CONTROL_ALLOW_ORIGIN")
131+
or
132+
isAllowOriginHeaderName(e.(RefExpr).getExpr())
133+
or
134+
isAllowOriginHeaderName(getAReachingValue(e))
135+
or
136+
exists(CallExpr c | c = e |
137+
isPathCall(c, "HeaderName", ["from_static", "from_lowercase", "from_bytes", "from_str"]) and
138+
isAllowOriginHeaderName(c.getArgList().getArg(0))
139+
)
140+
or
141+
exists(MethodCallExpr c |
142+
c = e and
143+
c.getIdentifier().getText() in ["unwrap", "expect"] and
144+
isAllowOriginHeaderName(c.getReceiver())
145+
)
146+
or
147+
isAllowOriginHeaderName(e.(TryExpr).getExpr())
148+
}
149+
150+
/**
151+
* Holds if `call` sets a header on a response, a header map or a header layer: `insert`, `append`
152+
* and `header` style methods, and functions such as `Header::new` and `warp::reply::with::header`.
153+
* A call that only receives a header name and a value, such as a comparison helper, does not.
154+
*/
155+
private predicate isHeaderWriter(Expr call) {
156+
call.(MethodCallExpr).getIdentifier().getText() =
157+
["insert", "append", "header", "insert_header", "append_header", "add_header", "set_header"]
158+
or
159+
call.(CallExpr).getFunction().(PathExpr).getPath().getText() =
160+
["header", "with_header", "overriding", "if_not_present", "appending"]
161+
or
162+
isPathCall(call, "Header", "new")
163+
}
164+
165+
/**
166+
* Holds if `name` and `value` are an adjacent header name/value pair, either
167+
* consecutive arguments of a call that sets a header (for example
168+
* `headers.insert(name, value)` or `with_header(reply, name, value)`) or a
169+
* 2-tuple `(name, value)`.
170+
*/
171+
private predicate isHeaderPair(Expr pair, Expr name, Expr value) {
172+
isHeaderWriter(pair) and
173+
exists(ArgList args, int i |
174+
args = pair.(MethodCallExpr).getArgList() or args = pair.(CallExpr).getArgList()
175+
|
176+
name = args.getArg(i) and
177+
value = args.getArg(i + 1)
178+
)
179+
or
180+
pair.(TupleExpr).getNumberOfFields() = 2 and
181+
name = pair.(TupleExpr).getField(0) and
182+
value = pair.(TupleExpr).getField(1)
183+
}
184+
185+
/**
186+
* Holds if `e` configures a CORS policy (or sets a CORS response header) that
187+
* allows any origin, described by `description`.
188+
*/
189+
predicate isPermissiveCors(Expr e, string description) {
190+
// warp: `warp::cors().allow_any_origin()`; actix-cors: `Cors::default().allow_any_origin()`
191+
e.(MethodCallExpr).getIdentifier().getText() = "allow_any_origin" and
192+
e.(MethodCallExpr).getArgList().getNumberOfArgs() = 0 and
193+
description = "This CORS policy allows any origin"
194+
or
195+
// tower-http / salvo: `.allow_origin(Any)`, `.allow_origin("*".parse().unwrap())`
196+
e.(MethodCallExpr).getIdentifier().getText() = "allow_origin" and
197+
isWildcardOriginValue(e.(MethodCallExpr).getArgList().getArg(0)) and
198+
description = "This CORS policy allows any origin"
199+
or
200+
// actix-cors: `Cors::permissive()`; tower-http: `CorsLayer::permissive()` / `very_permissive()`
201+
(
202+
isPathCall(e, "Cors", "permissive")
203+
or
204+
isPathCall(e, "CorsLayer", ["permissive", "very_permissive"])
205+
or
206+
// rocket_cors: `AllowedOrigins::all()`
207+
isPathCall(e, "AllowedOrigins", "all")
208+
) and
209+
description = "This CORS policy allows any origin"
210+
or
211+
// iron / hyper 0.10: `AccessControlAllowOrigin::Any`
212+
qualifiedPathEndsWith(e.(PathExpr).getPath(), "AccessControlAllowOrigin", "Any") and
213+
description = "This Access-Control-Allow-Origin header allows any origin"
214+
or
215+
// raw header: `headers.insert(ACCESS_CONTROL_ALLOW_ORIGIN, "*")`, `("Access-Control-Allow-Origin", "*")`
216+
exists(Expr name, Expr value |
217+
isHeaderPair(e, name, value) and
218+
isAllowOriginHeaderName(name) and
219+
isWildcardOriginValue(value)
220+
) and
221+
description = "This Access-Control-Allow-Origin header allows any origin"
222+
}
223+
224+
from Expr e, string description
225+
where isPermissiveCors(e, description)
226+
select e,
227+
description +
228+
". Review whether the responses of this service contain sensitive or credentialed data."
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
use axum::{http::HeaderValue, routing::get, Router};
2+
use tower_http::cors::CorsLayer;
3+
4+
fn app() -> Router {
5+
Router::new().route("/json", get(|| async { "{}" })).layer(
6+
// BAD: any website can read responses from this service
7+
CorsLayer::new().allow_origin("*".parse::<HeaderValue>().unwrap()),
8+
)
9+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
use axum::{http::HeaderValue, routing::get, Router};
2+
use tower_http::cors::CorsLayer;
3+
4+
fn app() -> Router {
5+
Router::new().route("/json", get(|| async { "{}" })).layer(
6+
// GOOD: only the trusted front-end origin can read responses
7+
CorsLayer::new().allow_origin("https://app.example.com".parse::<HeaderValue>().unwrap()),
8+
)
9+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
| 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. |
2+
| 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. |
3+
| 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. |
4+
| 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. |
5+
| 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. |
6+
| 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. |
7+
| 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. |
8+
| 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. |
9+
| 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. |
10+
| 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. |
11+
| 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. |
12+
| 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. |
13+
| 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. |
14+
| 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. |
15+
| 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. |
16+
| 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. |
17+
| 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. |
18+
| 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. |
19+
| main.rs:294:9:294:59 | headers.insert(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
20+
| main.rs:302:9:302:59 | headers.insert(...) | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
21+
| main.rs:326:28:326:63 | TupleExpr | This Access-Control-Allow-Origin header allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
22+
| main.rs:339:23:339:56 | ... .allow_any_origin() | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
23+
| main.rs:340:34:340:51 | ...::permissive(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
24+
| main.rs:364:30:364:50 | ...::all(...) | This CORS policy allows any origin. Review whether the responses of this service contain sensitive or credentialed data. |
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
query: audit/CWE-942/PermissiveCors.ql

0 commit comments

Comments
 (0)