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,71 @@
# Permissive CORS or weak Content-Security-Policy configuration

## Overview

Browsers enforce the same-origin policy and, when configured, a Content-Security-Policy (CSP). Both can be weakened by response headers or middleware configuration:

- `Access-Control-Allow-Origin: *` (or `null`) lets scripts on any website read the response. This exposes data from unauthenticated endpoints, and from deployments that are only reachable from a victim's browser or an internal network (CWE-942).
- A CORS middleware such as Starlette/FastAPI `CORSMiddleware` with `allow_credentials=True` and an origin pattern that is too broad lets attacker-controlled origins send credentialed cross-origin requests and read the responses. Examples are `allow_origins=["*"]`, `allow_origin_regex=".*"`, a regex with unescaped dots (`restaurant.com` also matches `restaurantXcom`), an unbounded wildcard directly before the domain (`.*example\.com` also matches `evilexample.com`), or an unbounded wildcard after the domain (`example\.com.*` also matches `example.com.evil.com`) (CWE-942).
- A CSP whose `script-src` (or `default-src` when no `script-src` is present) contains `'unsafe-inline'` without a nonce or hash allows injected inline scripts to run, which negates the CSP's protection against cross-site scripting (CWE-693).

This query reports:

- response header writes modeled by CodeQL (Flask, Werkzeug, Django, and others, plus the response passed to Flask `after_request` / `after_app_request` hooks) that set `Access-Control-Allow-Origin` to `*` or `null`, or set `Content-Security-Policy` to a value that allows inline scripts, and
- Starlette/FastAPI `CORSMiddleware` configurations with `allow_credentials=True` and a permissive `allow_origin_regex` or a wildcard in `allow_origins`.

## Recommendation

- Only allow explicitly trusted origins. Avoid `*`, and never combine permissive origins with credentials.
- For `allow_origin_regex`, escape literal dots and use an explicit sub-domain boundary, for example `https://([a-z0-9-]+\.)?example\.com`.
- Remove `'unsafe-inline'` from `script-src`. Use nonce- or hash-based sources instead.

## Example

The following Flask hook allows any origin to read responses and allows inline scripts:

```python
@app.after_request
def add_headers(response):
response.headers['Access-Control-Allow-Origin'] = '*' # BAD
response.headers['Content-Security-Policy'] = "script-src 'self' 'unsafe-inline'" # BAD
return response
```

Restrict the origin and use a nonce instead:

```python
@app.after_request
def add_headers(response):
response.headers['Access-Control-Allow-Origin'] = 'https://trusted.example.com' # GOOD
response.headers['Content-Security-Policy'] = f"script-src 'self' 'nonce-{g.csp_nonce}'" # GOOD
return response
```

The following FastAPI middleware accepts origins such as `https://evilrestaurant.com` with credentials:

```python
app.add_middleware(
CORSMiddleware,
allow_origin_regex=".*.(restaurant.com|deliveryservice.com)", # BAD
allow_credentials=True,
)
```

Escape the dots and anchor the sub-domain boundary:

```python
app.add_middleware(
CORSMiddleware,
allow_origin_regex=r"https://([a-z0-9-]+\.)?(restaurant\.com|deliveryservice\.com)", # GOOD
allow_credentials=True,
)
```

## References

- MDN: [Access-Control-Allow-Origin](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin)
- MDN: [Content-Security-Policy: script-src](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src)
- Starlette: [CORSMiddleware](https://www.starlette.io/middleware/#corsmiddleware)
- OWASP: [CORS origin header scrutiny](https://owasp.org/www-community/attacks/CORS_OriginHeaderScrutiny)
- Common Weakness Enumeration: [CWE-693](https://cwe.mitre.org/data/definitions/693.html)
- Common Weakness Enumeration: [CWE-942](https://cwe.mitre.org/data/definitions/942.html)
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
/**
* @name Permissive CORS or weak Content-Security-Policy configuration
* @description Allowing any origin to read responses, trusting an overly permissive
* CORS origin pattern with credentials, or allowing inline scripts in a
* Content-Security-Policy weakens browser-enforced protections.
* @kind problem
* @problem.severity warning
* @security-severity 5.3
* @precision medium
* @id py/cors-csp-security-headers
* @tags security
* external/cwe/cwe-693
* external/cwe/cwe-942
*/

import python
import semmle.python.Concepts
import semmle.python.dataflow.new.DataFlow
import semmle.python.ApiGraphs
private import semmle.python.frameworks.Flask
private import semmle.python.frameworks.Werkzeug

/**
* A `headers` attribute read on the response parameter of a Flask
* `after_request` / `after_app_request` hook, such as `response.headers` in:
*
* ```python
* @app.after_request
* def add_headers(response):
* response.headers["Access-Control-Allow-Origin"] = "*"
* return response
* ```
*/
private class FlaskAfterRequestResponseHeaders extends Werkzeug::Headers::InstanceSource {
FlaskAfterRequestResponseHeaders() {
exists(Function hook, DataFlow::ParameterNode response |
hook.getADecorator() =
[Flask::FlaskApp::instance(), Flask::Blueprint::instance()]
.getMember(["after_request", "after_app_request"])
.getAValueReachableFromSource()
.asExpr() and
response.getParameter() = hook.getArg(0) and
this.(DataFlow::AttrRead).getObject().getALocalSource() = response and
this.(DataFlow::AttrRead).getAttributeName() = "headers"
)
}
}

/** Gets the constant string value of `node`, if it is a string literal (possibly via local flow). */
string constantString(DataFlow::Node node) {
result = node.asExpr().(StringLiteral).getText()
or
result = node.getALocalSource().asExpr().(StringLiteral).getText()
}

/** Holds if `write` sets the response header `name` (lower-cased) to the constant `value`. */
predicate headerWrite(Http::Server::ResponseHeaderWrite write, string name, string value) {
name = constantString(write.getNameArg()).toLowerCase() and
value = constantString(write.getValueArg())
}

/** Gets the `i`th directive (trimmed, lower-cased) of the single CSP policy `policy`. */
bindingset[policy]
string cspDirective(string policy, int i) {
result = policy.splitAt(";", i).trim().toLowerCase() and result != ""
}

/** Gets the name of the CSP directive `directive`. */
bindingset[directive]
string cspDirectiveName(string directive) { result = directive.regexpCapture("([a-z-]+).*", 1) }

/**
* Gets the effective directive named `name` in the CSP policy `policy`. Browsers
* ignore all but the first occurrence of a directive.
*/
bindingset[policy]
string cspEffectiveDirective(string policy, string name) {
exists(int i |
result = cspDirective(policy, i) and
name = cspDirectiveName(result) and
not exists(int j | j < i and cspDirectiveName(cspDirective(policy, j)) = name)
)
}

/**
* Holds if the CSP `directive` allows inline scripts, that is, it contains
* `'unsafe-inline'` and no well-formed nonce or hash source (which would make
* browsers ignore `'unsafe-inline'`).
*/
bindingset[directive]
predicate directiveAllowsInlineScript(string directive) {
directive.regexpMatch("(.*\\s)?'unsafe-inline'(\\s.*)?") and
not directive.regexpMatch("(.*\\s)?'(nonce|sha256|sha384|sha512)-[a-z0-9+/_-]+=*'(\\s.*)?") and
not directive.regexpMatch("(.*\\s)?'strict-dynamic'(\\s.*)?")
}

/** Holds if the single CSP policy `policy` allows inline scripts. */
bindingset[policy]
predicate policyAllowsInlineScript(string policy) {
directiveAllowsInlineScript(cspEffectiveDirective(policy,
["script-src", "script-src-elem", "script-src-attr"]))
or
// `default-src` only applies to scripts when no `script-src` directive is present.
directiveAllowsInlineScript(cspEffectiveDirective(policy, "default-src")) and
not exists(cspEffectiveDirective(policy, "script-src"))
}
Comment thread
felickz marked this conversation as resolved.
Resolved

/** Holds if `policy` has a directive that applies to scripts. */
bindingset[policy]
predicate policyHasApplicableScriptDirective(string policy) {
exists(string name |
name = ["script-src", "script-src-elem", "script-src-attr", "default-src"] and
exists(string directive | directive = cspEffectiveDirective(policy, name))
)
}

/**
* Holds if the Content-Security-Policy value `csp` allows inline scripts. A
* comma-separated value contains several policies whose script directives
* intersect. Policies without an applicable script directive do not restrict
* inline scripts.
*/
bindingset[csp]
predicate cspAllowsInlineScript(string csp) {
exists(string policy | policy = csp.splitAt(",") and policy.trim() != "") and
exists(string policy |
policy = csp.splitAt(",") and policy.trim() != "" and policyAllowsInlineScript(policy)
) and
forall(string policy | policy = csp.splitAt(",") and policy.trim() != "" |
policyAllowsInlineScript(policy) or not policyHasApplicableScriptDirective(policy)
)
}

/**
* Holds if `s` is a regular expression (fragment) that matches any origin, such as
* `.*`, `^.+$`, `https://.*` or `https?://[^/]+`.
*/
bindingset[s]
predicate isCatchAllOriginRegex(string s) {
s.regexpMatch("\\(?\\^?([a-z()|?]*://)?(\\.|\\[\\^[^\\].]*\\])[*+]\\??\\$?\\)?")
}

/** Holds if character `i` is a top-level alternative separator in `regex`. */
bindingset[regex]
private predicate isTopLevelRegexSeparator(string regex, int i) {
exists(string prefix, string unescapedPrefix, string outsideClasses, string parentheses,
string trailingBackslashes |
i >= 0 and i < regex.length() and
regex.charAt(i) = "|" and
prefix = regex.substring(0, i) and
trailingBackslashes = prefix.regexpCapture(".*(\\\\*)$", 1) and
trailingBackslashes.length() % 2 = 0 and
unescapedPrefix = prefix.regexpReplaceAll("\\\\.", "#") and
outsideClasses =
unescapedPrefix.regexpReplaceAll("\\[(\\\\.|[^\\]\\\\])*\\]", "#") and
not outsideClasses.regexpMatch(".*\\[.*") and
parentheses = outsideClasses.regexpReplaceAll("[^()]", "") and
parentheses.regexpReplaceAll("\\)", "").length() =
parentheses.regexpReplaceAll("\\(", "").length()
)
}

/** Holds if `regex` has a catch-all top-level alternative. */
bindingset[regex]
private predicate hasCatchAllTopLevelAlternative(string regex) {
exists(int start, int end |
start >= 0 and end >= start and end <= regex.length() and
(start = 0 or exists(int previous |
isTopLevelRegexSeparator(regex, previous) and start = previous + 1
)) and
(end = regex.length() or isTopLevelRegexSeparator(regex, end)) and
not exists(int separator |
separator >= start and separator < end and isTopLevelRegexSeparator(regex, separator)
) and
isCatchAllOriginRegex(regex.substring(start, end))
)
}

/**
* Holds if the CORS origin regular expression `regex` accepts origins that are
* likely not intended, such as any origin, or attacker-registrable domains due to
* unescaped dots, an unbounded wildcard directly preceding the domain name, or an
* unbounded wildcard after the domain name.
*/
bindingset[regex]
predicate isPermissiveOriginRegex(string regex) {
// The complete expression and each top-level alternative can match any origin.
isCatchAllOriginRegex(regex) or
hasCatchAllTopLevelAlternative(regex)
or
exists(string r |
// Ignore the contents of character classes, e.g. the `.` in `[a-z.]`.
r = regex.regexpReplaceAll("\\[(\\\\.|[^\\]\\\\])*\\]", "#")
|
// An unescaped `.` used as a domain separator, e.g. `restaurant.com`.
r.regexpMatch("(.*[^\\\\])?\\.[a-zA-Z0-9].*")
or
// An unbounded wildcard directly followed by a domain name, e.g. `.*example\.com`.
r.regexpMatch("(.*[^\\\\])?\\.[*+]\\??(?!\\((?:\\?:)?\\\\\\.)[a-zA-Z0-9(].*")
or
// An unbounded wildcard after the domain name, e.g. `example\.com.*`.
r.regexpMatch(".*[^\\\\:]\\.[*+]\\??\\$?\\)?")
)
}

/** Gets the value of the keyword argument `name` of the CORS middleware `mw`. */
DataFlow::Node corsMiddlewareArg(Http::Server::CorsMiddleware mw, string name) {
result = mw.(DataFlow::CallCfgNode).getArgByName(name)
}

/** Holds if the CORS middleware `mw` allows credentialed requests. */
predicate corsAllowsCredentials(Http::Server::CorsMiddleware mw) {
mw.getMiddlewareName() = "CORSMiddleware" and
mw.getCredentialsAllowed().getALocalSource().asExpr() instanceof True
}

from DataFlow::Node node, string message
where
exists(string value |
headerWrite(node, "access-control-allow-origin", value) and
(
value.trim() = "*" and
message =
"The Access-Control-Allow-Origin header is set to '*', allowing any website to read this response."
or
value.trim() = "null" and
message =
"The Access-Control-Allow-Origin header is set to 'null', allowing sandboxed or opaque origins to read this response."
)
)
or
exists(string value |
headerWrite(node, "content-security-policy", value) and
cspAllowsInlineScript(value) and
message =
"This Content-Security-Policy allows inline scripts via 'unsafe-inline', which negates its protection against script injection."
)
or
exists(Http::Server::CorsMiddleware mw | corsAllowsCredentials(mw) |
exists(string regex |
node = corsMiddlewareArg(mw, "allow_origin_regex") and
regex = constantString(node) and
isPermissiveOriginRegex(regex) and
message =
"This CORS middleware allows credentialed requests from origins matching the overly permissive regular expression '"
+ regex + "'."
)
or
node = corsMiddlewareArg(mw, "allow_origins") and
exists(Expr origins | origins = node.getALocalSource().asExpr() |
(origins instanceof List or origins instanceof Tuple) and
origins.getASubExpression().(StringLiteral).getText() = "*"
) and
message = "This CORS middleware allows credentialed requests from any origin."
)
select node, message
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
| django_views.py:6:5:6:43 | ControlFlowNode for Subscript | The Access-Control-Allow-Origin header is set to '*', allowing any website to read this response. |
| django_views.py:7:5:7:47 | ControlFlowNode for Subscript | This Content-Security-Policy allows inline scripts via 'unsafe-inline', which negates its protection against script injection. |
| fastapi_app.py:9:24:9:64 | ControlFlowNode for StringLiteral | This CORS middleware allows credentialed requests from origins matching the overly permissive regular expression '.*.(restaurant.com\|deliveryservice.com)'. |
| fastapi_app.py:18:24:18:48 | ControlFlowNode for StringLiteral | This CORS middleware allows credentialed requests from origins matching the overly permissive regular expression 'https://.*example\\.com'. |
| fastapi_app.py:25:24:25:27 | ControlFlowNode for StringLiteral | This CORS middleware allows credentialed requests from origins matching the overly permissive regular expression '.*'. |
| fastapi_app.py:32:19:32:23 | ControlFlowNode for List | This CORS middleware allows credentialed requests from any origin. |
| fastapi_app.py:67:24:67:36 | ControlFlowNode for StringLiteral | This CORS middleware allows credentialed requests from origins matching the overly permissive regular expression 'https://.*'. |
| fastapi_app.py:73:24:73:42 | ControlFlowNode for StringLiteral | This CORS middleware allows credentialed requests from origins matching the overly permissive regular expression '^https?://[^/]+$'. |
| fastapi_app.py:80:24:80:58 | ControlFlowNode for StringLiteral | This CORS middleware allows credentialed requests from origins matching the overly permissive regular expression 'https://trusted\\.example\\.com\|.*'. |
| fastapi_app.py:87:24:87:57 | ControlFlowNode for StringLiteral | This CORS middleware allows credentialed requests from origins matching the overly permissive regular expression 'https://trusted\\.example\\.com.*'. |
| fastapi_app.py:121:24:121:50 | ControlFlowNode for StringLiteral | This CORS middleware allows credentialed requests from origins matching the overly permissive regular expression 'https://.*(example\\.com)'. |
| fastapi_app.py:128:24:128:59 | ControlFlowNode for StringLiteral | This CORS middleware allows credentialed requests from origins matching the overly permissive regular expression 'https://.*(foo\|bar)\\.example\\.com'. |
| fastapi_app.py:135:24:135:42 | ControlFlowNode for StringLiteral | This CORS middleware allows credentialed requests from origins matching the overly permissive regular expression 'https://(foo\|.*)'. |
| flask_app.py:8:5:8:51 | ControlFlowNode for Subscript | The Access-Control-Allow-Origin header is set to '*', allowing any website to read this response. |
| flask_app.py:9:5:9:47 | ControlFlowNode for Subscript | This Content-Security-Policy allows inline scripts via 'unsafe-inline', which negates its protection against script injection. |
| flask_app.py:16:5:16:43 | ControlFlowNode for Subscript | This Content-Security-Policy allows inline scripts via 'unsafe-inline', which negates its protection against script injection. |
| flask_app.py:17:5:17:59 | ControlFlowNode for Attribute() | The Access-Control-Allow-Origin header is set to 'null', allowing sandboxed or opaque origins to read this response. |
| flask_app.py:23:12:23:73 | ControlFlowNode for make_response() | The Access-Control-Allow-Origin header is set to '*', allowing any website to read this response. |
| flask_app.py:30:5:30:43 | ControlFlowNode for Subscript | This Content-Security-Policy allows inline scripts via 'unsafe-inline', which negates its protection against script injection. |
| flask_app.py:32:5:32:43 | ControlFlowNode for Subscript | This Content-Security-Policy allows inline scripts via 'unsafe-inline', which negates its protection against script injection. |
| flask_app.py:34:5:34:43 | ControlFlowNode for Subscript | This Content-Security-Policy allows inline scripts via 'unsafe-inline', which negates its protection against script injection. |
| run.py:10:5:10:51 | ControlFlowNode for Subscript | The Access-Control-Allow-Origin header is set to '*', allowing any website to read this response. |
| run.py:11:5:11:47 | ControlFlowNode for Subscript | This Content-Security-Policy allows inline scripts via 'unsafe-inline', which negates its protection against script injection. |
| run.py:17:5:17:60 | ControlFlowNode for Attribute() | The Access-Control-Allow-Origin header is set to '*', allowing any website to read this response. |
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
query: CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql
postprocess: utils/test/InlineExpectationsTestQuery.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from flask import Flask


def create_app():
app = Flask(__name__)
return app
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from django.http import HttpResponse


def permissive_view(request):
response = HttpResponse("ok")
response["Access-Control-Allow-Origin"] = "*" # $ Alert
response.headers["Content-Security-Policy"] = "script-src 'unsafe-inline'" # $ Alert
return response


def safe_view(request):
response = HttpResponse("ok")
response["Access-Control-Allow-Origin"] = "https://trusted.example.com"
response.headers["Content-Security-Policy"] = "script-src 'self'"
return response
Loading
Loading