From 8e0a9b012b03236d278b063b4e4eec0481d7acae Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 31 Oct 2026 03:41:42 +0000 Subject: [PATCH 1/4] Initial plan From 1de6d25ae468dfa4edc98c976a556ce8c1dd35c8 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 31 Oct 2026 05:34:06 +0000 Subject: [PATCH 2/4] Add py/cors-csp-security-headers query for permissive CORS and weak CSP Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../CorsCspSecurityHeaders.md | 71 ++++++++ .../CorsCspSecurityHeaders.ql | 156 ++++++++++++++++++ .../CorsCspSecurityHeaders.expected | 14 ++ .../CorsCspSecurityHeaders.qlref | 2 + .../CorsCspSecurityHeaders/app_factory.py | 6 + .../CorsCspSecurityHeaders/django_views.py | 15 ++ .../CorsCspSecurityHeaders/fastapi_app.py | 62 +++++++ .../test/CorsCspSecurityHeaders/flask_app.py | 39 +++++ .../custom/test/CorsCspSecurityHeaders/run.py | 24 +++ 9 files changed, 389 insertions(+) create mode 100644 languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.md create mode 100644 languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql create mode 100644 languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected create mode 100644 languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.qlref create mode 100644 languages/python/custom/test/CorsCspSecurityHeaders/app_factory.py create mode 100644 languages/python/custom/test/CorsCspSecurityHeaders/django_views.py create mode 100644 languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py create mode 100644 languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py create mode 100644 languages/python/custom/test/CorsCspSecurityHeaders/run.py diff --git a/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.md b/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.md new file mode 100644 index 00000000..54584d7b --- /dev/null +++ b/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.md @@ -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`), or an unbounded wildcard directly before the domain (`.*example\.com` also matches `evilexample.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) diff --git a/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql b/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql new file mode 100644 index 00000000..8660e5b3 --- /dev/null +++ b/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql @@ -0,0 +1,156 @@ +/** + * @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 a directive (trimmed, lower-cased) of the Content-Security-Policy value `csp`. */ +bindingset[csp] +string cspDirective(string csp) { result = csp.splitAt(";").trim().toLowerCase() and result != "" } + +/** Gets the name of the CSP directive `directive`. */ +bindingset[directive] +string cspDirectiveName(string directive) { result = directive.regexpCapture("([a-z-]+).*", 1) } + +/** + * Holds if the CSP `directive` allows inline scripts, that is, it contains + * `'unsafe-inline'` and no nonce or hash source (which would make browsers ignore it). + */ +bindingset[directive] +predicate directiveAllowsInlineScript(string directive) { + directive.matches("%'unsafe-inline'%") and + not directive.regexpMatch(".*'(nonce|sha256|sha384|sha512)-.*") +} + +/** Holds if the Content-Security-Policy value `csp` allows inline scripts. */ +bindingset[csp] +predicate cspAllowsInlineScript(string csp) { + exists(string directive | directive = cspDirective(csp) | + cspDirectiveName(directive) = ["script-src", "script-src-elem", "script-src-attr"] and + directiveAllowsInlineScript(directive) + or + // `default-src` only applies to scripts when no `script-src` directive is present. + cspDirectiveName(directive) = "default-src" and + directiveAllowsInlineScript(directive) and + not cspDirectiveName(cspDirective(csp)) = "script-src" + ) +} + +/** + * 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 or an unbounded wildcard directly preceding the domain name. + */ +bindingset[regex] +predicate isPermissiveOriginRegex(string regex) { + // Matches any origin, e.g. `.*` or `^.+$`. + regex.regexpMatch("\\^?\\.[*+]\\$?") + or + // An unescaped `.` used as a domain separator, e.g. `restaurant.com`. + regex.regexpMatch("(.*[^\\\\])?\\.[a-zA-Z0-9].*") + or + // An unbounded wildcard directly followed by a domain name, e.g. `.*example\.com`. + regex.regexpMatch("(.*[^\\\\])?\\.[*+]\\??[a-zA-Z0-9(].*") +} + +/** 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() = ["*", "null"] and + message = + "The Access-Control-Allow-Origin header is set to '" + value.trim() + + "', allowing any website 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 diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected b/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected new file mode 100644 index 00000000..80d4ffd2 --- /dev/null +++ b/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected @@ -0,0 +1,14 @@ +| 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. | +| 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 any website 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. | +| 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. | diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.qlref b/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.qlref new file mode 100644 index 00000000..df1abd4d --- /dev/null +++ b/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.qlref @@ -0,0 +1,2 @@ +query: CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql +postprocess: utils/test/InlineExpectationsTestQuery.ql diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/app_factory.py b/languages/python/custom/test/CorsCspSecurityHeaders/app_factory.py new file mode 100644 index 00000000..80b0b0a8 --- /dev/null +++ b/languages/python/custom/test/CorsCspSecurityHeaders/app_factory.py @@ -0,0 +1,6 @@ +from flask import Flask + + +def create_app(): + app = Flask(__name__) + return app diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/django_views.py b/languages/python/custom/test/CorsCspSecurityHeaders/django_views.py new file mode 100644 index 00000000..6b55099c --- /dev/null +++ b/languages/python/custom/test/CorsCspSecurityHeaders/django_views.py @@ -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 diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py b/languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py new file mode 100644 index 00000000..3dba3a77 --- /dev/null +++ b/languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py @@ -0,0 +1,62 @@ +from fastapi import FastAPI +from fastapi.middleware.cors import CORSMiddleware + +app = FastAPI() + +# Unescaped dots and an unbounded `.*` prefix: matches e.g. https://evilrestaurant.com +app.add_middleware( + CORSMiddleware, + allow_origin_regex=".*.(restaurant.com|deliveryservice.com)", # $ Alert + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Unbounded `.*` directly before the domain: matches https://attackerexample.com +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://.*example\.com", # $ Alert + allow_credentials=True, +) + +# Matches any origin. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=".*", # $ Alert + allow_credentials=True, +) + +# Wildcard origin list with credentials. +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], # $ Alert + allow_credentials=True, +) + +# Safe: escaped dots and sub-domain boundary. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://([a-z0-9-]+\.)?(restaurant\.com|deliveryservice\.com)", + allow_credentials=True, +) + +# Safe: subdomain wildcard followed by an escaped dot. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://.*\.example\.com", + allow_credentials=True, +) + +# Safe: explicit origin list. +app.add_middleware( + CORSMiddleware, + allow_origins=["https://trusted.example.com"], + allow_credentials=True, +) + +# Not flagged: permissive regex without credentials. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=".*", + allow_credentials=False, +) diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py b/languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py new file mode 100644 index 00000000..d91f6f01 --- /dev/null +++ b/languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py @@ -0,0 +1,39 @@ +from flask import Flask, Response, make_response + +app = Flask(__name__) + + +@app.after_request +def add_security_headers(response): + response.headers['Access-Control-Allow-Origin'] = '*' # $ Alert + response.headers['Content-Security-Policy'] = "script-src 'self' 'unsafe-inline'" # $ Alert + return response + + +@app.route("/default-src") +def default_src(): + resp = Response("ok") + resp.headers["content-security-policy"] = "default-src 'self' 'unsafe-inline'; img-src *" # $ Alert + resp.headers.set("access-control-allow-origin", "null") # $ Alert + return resp + + +@app.route("/bulk") +def bulk(): + return make_response("ok", 200, {"Access-Control-Allow-Origin": "*"}) # $ Alert + + +@app.route("/safe") +def safe(): + resp = Response("ok") + # Explicitly trusted origin: not flagged. + resp.headers["Access-Control-Allow-Origin"] = "https://trusted.example.com" + # Nonce-based script-src: 'unsafe-inline' is ignored by CSP2+ browsers, not flagged. + resp.headers["Content-Security-Policy"] = "script-src 'self' 'nonce-r4nd0m' 'unsafe-inline'" + # 'unsafe-inline' restricted to styles only: not flagged. + resp.headers["Content-Security-Policy"] = "default-src 'self'; style-src 'self' 'unsafe-inline'" + # script-src overrides default-src for scripts: not flagged. + resp.headers["Content-Security-Policy"] = "default-src 'unsafe-inline'; script-src 'self'" + # Unrelated header: not flagged. + resp.headers["X-Content-Type-Options"] = "nosniff" + return resp diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/run.py b/languages/python/custom/test/CorsCspSecurityHeaders/run.py new file mode 100644 index 00000000..bca23a50 --- /dev/null +++ b/languages/python/custom/test/CorsCspSecurityHeaders/run.py @@ -0,0 +1,24 @@ +from app_factory import create_app +from flask import Blueprint + +app = create_app() +bp = Blueprint("bp", __name__) + + +@app.after_request +def add_csp_headers(response): + response.headers['Access-Control-Allow-Origin'] = '*' # $ Alert + response.headers['Content-Security-Policy'] = "script-src 'self' 'unsafe-inline'" # $ Alert + return response + + +@bp.after_app_request +def add_blueprint_headers(response): + response.headers.add("Access-Control-Allow-Origin", "*") # $ Alert + return response + + +def not_a_hook(response): + # Not registered as an after-request hook, so `response` is not known to be a Flask response. + response.headers['Access-Control-Allow-Origin'] = '*' + return response From ae643fce4b4931fe6487ff6aae2fc4e664d8e7bf Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Sat, 31 Oct 2026 05:37:51 +0000 Subject: [PATCH 3/4] Handle catch-all origin regexes and stricter CSP parsing in py/cors-csp-security-headers Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../CorsCspSecurityHeaders.md | 2 +- .../CorsCspSecurityHeaders.ql | 102 +++++++++++++----- .../CorsCspSecurityHeaders.expected | 8 +- .../CorsCspSecurityHeaders/fastapi_app.py | 40 +++++++ .../test/CorsCspSecurityHeaders/flask_app.py | 14 +++ 5 files changed, 137 insertions(+), 29 deletions(-) diff --git a/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.md b/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.md index 54584d7b..015247e0 100644 --- a/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.md +++ b/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.md @@ -5,7 +5,7 @@ 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`), or an unbounded wildcard directly before the domain (`.*example\.com` also matches `evilexample.com`) (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: diff --git a/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql b/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql index 8660e5b3..d8623f4e 100644 --- a/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql +++ b/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql @@ -59,53 +59,96 @@ predicate headerWrite(Http::Server::ResponseHeaderWrite write, string name, stri value = constantString(write.getValueArg()) } -/** Gets a directive (trimmed, lower-cased) of the Content-Security-Policy value `csp`. */ -bindingset[csp] -string cspDirective(string csp) { result = csp.splitAt(";").trim().toLowerCase() and result != "" } +/** 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 nonce or hash source (which would make browsers ignore it). + * `'unsafe-inline'` and no well-formed nonce or hash source (which would make + * browsers ignore `'unsafe-inline'`). */ bindingset[directive] predicate directiveAllowsInlineScript(string directive) { - directive.matches("%'unsafe-inline'%") and - not directive.regexpMatch(".*'(nonce|sha256|sha384|sha512)-.*") + directive.regexpMatch("(.*\\s)?'unsafe-inline'(\\s.*)?") and + not directive.regexpMatch("(.*\\s)?'(nonce|sha256|sha384|sha512)-[a-z0-9+/_-]+=*'(\\s.*)?") } -/** Holds if the Content-Security-Policy value `csp` allows inline scripts. */ +/** 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")) +} + +/** + * Holds if the Content-Security-Policy value `csp` allows inline scripts. A + * comma-separated value contains several policies that must all allow it. + */ bindingset[csp] predicate cspAllowsInlineScript(string csp) { - exists(string directive | directive = cspDirective(csp) | - cspDirectiveName(directive) = ["script-src", "script-src-elem", "script-src-attr"] and - directiveAllowsInlineScript(directive) - or - // `default-src` only applies to scripts when no `script-src` directive is present. - cspDirectiveName(directive) = "default-src" and - directiveAllowsInlineScript(directive) and - not cspDirectiveName(cspDirective(csp)) = "script-src" + exists(string policy | policy = csp.splitAt(",") and policy.trim() != "") and + forall(string policy | policy = csp.splitAt(",") and policy.trim() != "" | + policyAllowsInlineScript(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 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 or an unbounded wildcard directly preceding the domain name. + * unescaped dots, an unbounded wildcard directly preceding the domain name, or an + * unbounded wildcard after the domain name. */ bindingset[regex] predicate isPermissiveOriginRegex(string regex) { - // Matches any origin, e.g. `.*` or `^.+$`. - regex.regexpMatch("\\^?\\.[*+]\\$?") - or - // An unescaped `.` used as a domain separator, e.g. `restaurant.com`. - regex.regexpMatch("(.*[^\\\\])?\\.[a-zA-Z0-9].*") + // A top-level alternative matches any origin, e.g. `.*` or `https://a\.com|https://.*`. + isCatchAllOriginRegex(regex.splitAt("|")) or - // An unbounded wildcard directly followed by a domain name, e.g. `.*example\.com`. - regex.regexpMatch("(.*[^\\\\])?\\.[*+]\\??[a-zA-Z0-9(].*") + 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`. */ @@ -123,10 +166,15 @@ from DataFlow::Node node, string message where exists(string value | headerWrite(node, "access-control-allow-origin", value) and - value.trim() = ["*", "null"] and - message = - "The Access-Control-Allow-Origin header is set to '" + value.trim() + - "', allowing any website to read this response." + ( + 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 | diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected b/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected index 80d4ffd2..093db4ab 100644 --- a/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected +++ b/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected @@ -4,11 +4,17 @@ | 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.*'. | | 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 any website to read this response. | +| 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. | | 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. | diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py b/languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py index 3dba3a77..eaa73522 100644 --- a/languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py +++ b/languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py @@ -60,3 +60,43 @@ allow_origin_regex=".*", allow_credentials=False, ) + +# Catch-all host after a scheme. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://.*", # $ Alert + allow_credentials=True, +) + +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"^https?://[^/]+$", # $ Alert + allow_credentials=True, +) + +# Catch-all top-level alternative. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://trusted\.example\.com|.*", # $ Alert + allow_credentials=True, +) + +# Unbounded wildcard after the domain: matches https://trusted.example.com.evil.com +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://trusted\.example\.com.*", # $ Alert + allow_credentials=True, +) + +# Safe: alternation of escaped sub-domains, optional port and a dot inside a character class. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://(foo|bar)\.example\.com(:[0-9]+)?", + allow_credentials=True, +) + +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://[.a-z0-9-]+\.example\.com", + allow_credentials=True, +) diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py b/languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py index d91f6f01..4ad82fd1 100644 --- a/languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py +++ b/languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py @@ -23,6 +23,16 @@ def bulk(): return make_response("ok", 200, {"Access-Control-Allow-Origin": "*"}) # $ Alert +@app.route("/malformed-nonce") +def malformed_nonce(): + resp = Response("ok") + # An empty nonce does not disable 'unsafe-inline'. + resp.headers["Content-Security-Policy"] = "script-src 'unsafe-inline' 'nonce-'" # $ Alert + # Every policy allows inline scripts. + resp.headers["Content-Security-Policy"] = "script-src 'unsafe-inline', default-src 'unsafe-inline'" # $ Alert + return resp + + @app.route("/safe") def safe(): resp = Response("ok") @@ -34,6 +44,10 @@ def safe(): resp.headers["Content-Security-Policy"] = "default-src 'self'; style-src 'self' 'unsafe-inline'" # script-src overrides default-src for scripts: not flagged. resp.headers["Content-Security-Policy"] = "default-src 'unsafe-inline'; script-src 'self'" + # Duplicate directive: browsers only use the first one, not flagged. + resp.headers["Content-Security-Policy"] = "script-src 'self'; script-src 'unsafe-inline'" + # Multiple policies are intersected: inline scripts stay blocked, not flagged. + resp.headers["Content-Security-Policy"] = "script-src 'unsafe-inline', script-src 'none'" # Unrelated header: not flagged. resp.headers["X-Content-Type-Options"] = "nosniff" return resp From bb83bbfe22c0c3347e0d8e1646d67361a84552ac Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Mon, 2 Nov 2026 21:45:46 +0000 Subject: [PATCH 4/4] Fix CSP and origin regex review findings Co-authored-by: felickz <1760475+felickz@users.noreply.github.com> --- .../CorsCspSecurityHeaders.ql | 64 +++++++++++++++++-- .../CorsCspSecurityHeaders.expected | 4 ++ .../CorsCspSecurityHeaders/fastapi_app.py | 35 ++++++++++ .../test/CorsCspSecurityHeaders/flask_app.py | 4 ++ 4 files changed, 101 insertions(+), 6 deletions(-) diff --git a/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql b/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql index d8623f4e..6f6ccfc0 100644 --- a/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql +++ b/languages/python/custom/src/CorsCspSecurityHeaders/CorsCspSecurityHeaders.ql @@ -90,7 +90,8 @@ string cspEffectiveDirective(string policy, string name) { 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.*)?") + 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. */ @@ -104,15 +105,29 @@ predicate policyAllowsInlineScript(string policy) { not exists(cspEffectiveDirective(policy, "script-src")) } +/** 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 that must all allow it. + * 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) + policyAllowsInlineScript(policy) or not policyHasApplicableScriptDirective(policy) ) } @@ -125,6 +140,42 @@ 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 @@ -133,8 +184,9 @@ predicate isCatchAllOriginRegex(string s) { */ bindingset[regex] predicate isPermissiveOriginRegex(string regex) { - // A top-level alternative matches any origin, e.g. `.*` or `https://a\.com|https://.*`. - isCatchAllOriginRegex(regex.splitAt("|")) + // 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.]`. @@ -144,7 +196,7 @@ predicate isPermissiveOriginRegex(string regex) { 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(].*") + r.regexpMatch("(.*[^\\\\])?\\.[*+]\\??(?!\\((?:\\?:)?\\\\\\.)[a-zA-Z0-9(].*") or // An unbounded wildcard after the domain name, e.g. `example\.com.*`. r.regexpMatch(".*[^\\\\:]\\.[*+]\\??\\$?\\)?") diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected b/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected index 093db4ab..6a6c7b98 100644 --- a/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected +++ b/languages/python/custom/test/CorsCspSecurityHeaders/CorsCspSecurityHeaders.expected @@ -8,6 +8,9 @@ | 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. | @@ -15,6 +18,7 @@ | 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. | diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py b/languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py index eaa73522..5ba23ed3 100644 --- a/languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py +++ b/languages/python/custom/test/CorsCspSecurityHeaders/fastapi_app.py @@ -100,3 +100,38 @@ allow_origin_regex=r"https://[.a-z0-9-]+\.example\.com", allow_credentials=True, ) + +# Safe: top-level protocol alternatives still require the trusted domain suffix. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"(https://.*|http://.*)\.example\.com", + allow_credentials=True, +) + +# Safe: the escaped domain boundary is grouped. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://.*(\.example\.com)", + allow_credentials=True, +) + +# Still unsafe: the group starts with an unbounded domain name. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://.*(example\.com)", # $ Alert + allow_credentials=True, +) + +# Still unsafe: the group allows any prefix before the trusted-looking suffix. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://.*(foo|bar)\.example\.com", # $ Alert + allow_credentials=True, +) + +# A catch-all nested alternative remains unsafe. +app.add_middleware( + CORSMiddleware, + allow_origin_regex=r"https://(foo|.*)", # $ Alert + allow_credentials=True, +) diff --git a/languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py b/languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py index 4ad82fd1..f78d4af3 100644 --- a/languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py +++ b/languages/python/custom/test/CorsCspSecurityHeaders/flask_app.py @@ -30,6 +30,8 @@ def malformed_nonce(): resp.headers["Content-Security-Policy"] = "script-src 'unsafe-inline' 'nonce-'" # $ Alert # Every policy allows inline scripts. resp.headers["Content-Security-Policy"] = "script-src 'unsafe-inline', default-src 'unsafe-inline'" # $ Alert + # An image-only policy does not restrict scripts. + resp.headers["Content-Security-Policy"] = "script-src 'unsafe-inline', img-src 'self'" # $ Alert return resp @@ -40,6 +42,8 @@ def safe(): resp.headers["Access-Control-Allow-Origin"] = "https://trusted.example.com" # Nonce-based script-src: 'unsafe-inline' is ignored by CSP2+ browsers, not flagged. resp.headers["Content-Security-Policy"] = "script-src 'self' 'nonce-r4nd0m' 'unsafe-inline'" + # 'strict-dynamic' also disables 'unsafe-inline' for scripts. + resp.headers["Content-Security-Policy"] = "script-src 'strict-dynamic' 'unsafe-inline'" # 'unsafe-inline' restricted to styles only: not flagged. resp.headers["Content-Security-Policy"] = "default-src 'self'; style-src 'self' 'unsafe-inline'" # script-src overrides default-src for scripts: not flagged.