Skip to content

Python: Should StringConcatAsSanitizer in py/url-redirection check the left operand, so that "/" + target and "https://" + target are reported? #23154

Backlog

Description

@wildoranges

Description of the issue

I'm wondering whether py/url-redirection is meant to treat the right operand of every + as sanitized, whatever the left operand is. The sanitizer's comment says "Url redirection is a problem only if the user controls the prefix of the URL", but a constant prefix only protects the host if it already ends the host, as in "https://safe.example/" + target. With "/" + target, "https://" + target, "https://safe.example" + target or even "" + target, the user still controls the host of the redirect, and none of these are reported.

Affected sanitizer

StringConcatAsSanitizer matches any BinaryExprNode with Add and sanitizes its right operand in all flow states. The TODO there says it "doesn't cover formatting", which I read as being about the .format/f-string/% cases marked $ SPURIOUS in the query test, not about which prefixes are safe.

For comparison, the JavaScript URL redirection queries only treat a concatenation as a barrier when the prefix contains ?, # or a / that ends the host, or is not fully known (hasHostnameSanitizingSubstring), and the Python SSRF modelling already excludes "http://" and "https://" as left operands "since that will still allow full URL control" (StringConstructionAsFullUrlControlSanitizer).

Steps to reproduce

from flask import Flask, request, redirect

app = Flask(__name__)


@app.route("/direct")
def direct():
    target = request.args.get("target", "")
    return redirect(target)  # reported


@app.route("/path")
def path():
    target = request.args.get("target", "")
    return redirect("https://safe.example/" + target)  # not reported, and safe


@app.route("/slash")
def slash():
    target = request.args.get("target", "")
    return redirect("/" + target)  # not reported


@app.route("/scheme")
def scheme():
    target = request.args.get("target", "")
    return redirect("https://" + target)  # not reported


@app.route("/host")
def host():
    target = request.args.get("target", "")
    return redirect("https://safe.example" + target)  # not reported


@app.route("/empty")
def empty():
    target = request.args.get("target", "")
    return redirect("" + target)  # not reported

py/url-redirection (and python-security-extended.qls) reports only line 9. I requested each route with Flask's test client and resolved the Location header against https://site.example/app/page with the WHATWG URL parser (Node.js 24), as a browser would:

Route target Location Host the browser goes to
/path @evil.example https://safe.example/@evil.example safe.example
/slash /evil.example/ //evil.example/ evil.example
/scheme evil.example/ https://evil.example/ evil.example
/host @evil.example/ https://safe.example@evil.example/ evil.example
/host .evil.example/ https://safe.example.evil.example/ safe.example.evil.example
/empty https://evil.example/ https://evil.example/ evil.example

For comparison, js/server-side-unvalidated-url-redirection reports the Express equivalents of /slash, /scheme, /host and /empty (for example res.redirect("/" + req.query.target)) and does not report /path.

The same two shapes, a value at the start of a path and a value directly after the host, were the subject of Tornado's recent advisory for RedirectHandler URL templates, GHSA-pw9p-v7r6-gx4p, which notes that templates are safe only if "every substitution comes after a fixed host and a /".

Question

Is it intended that any left operand makes the right operand of + safe? Would it be reasonable to require that the left operand ends the host, as sketched below?

Possible change

One possible change, along the lines of hasHostnameSanitizingSubstring in JavaScript, is to keep StringConcatAsSanitizer for left operands whose value is not known, but not to apply it when a local source of the left operand is a string literal that does not end the host. This is only a sketch against current main:

+  /**
+   * Holds if the string literal `prefix` prevents anything appended after it from affecting
+   * the host of a URL (same check as `hasHostnameSanitizingSubstring` in JavaScript).
+   */
+  private predicate isHostnameSanitizingPrefix(StringLiteral prefix) {
+    prefix.getText().regexpMatch(".*([?#]|[^?#:/\\\\][/\\\\]).*|[/\\\\][^/\\\\].*")
+  }
+
   class StringConcatAsSanitizer extends Sanitizer {
     StringConcatAsSanitizer() {
       ...
       exists(BinaryExprNode string_concat | string_concat.getOp() instanceof Add |
-        string_concat.getRight() = this.asCfgNode()
+        string_concat.getRight() = this.asCfgNode() and
+        not exists(DataFlow::Node left, StringLiteral prefix |
+          left.asCfgNode() = string_concat.getLeft() and
+          prefix = left.getALocalSource().asExpr()
+        |
+          not isHostnameSanitizingPrefix(prefix)
+        )
       )
     }

With this change, py/url-redirection also reports /slash, /scheme, /host and /empty above (lines 21, 27, 33 and 39) and still does not report /path, and the existing tests in python/ql/test/query-tests/Security/CWE-601-UrlRedirect/ pass with an unchanged .expected. The condition is checked for every control-flow node of the left operand, because the target of an augmented assignment also has a store node whose local source is the + itself; this way url = "/" followed by url += target is reported too, while the existing /ok test ("https://safe.com/" with +=) is still not. Prefixes that are not known, such as a variable or parameter, stay sanitizing as they are now, as in the JavaScript check. The main effect on alert volume would be new alerts for "/" + value, which is a common pattern; these are open redirects whenever the value can start with /. Open PR #22872 does not change this example (with it applied, only line 9 is reported), and this change does not overlap its library changes; both add cases to test.py.

Environment

  • CodeQL CLI 2.27.4 (codeql/python-queries 1.9.0, codeql/javascript-queries 2.5.0 for the comparison)
  • CodeQL main 57bace85f49150248166ec49587bcbb1fa53c440 (commit for the links above)
  • Python 3.12.3, Flask 3.1.3, Werkzeug 3.1.9; Node.js v24.18.0

Activity

  1. jketema commented on Nov 18, 2026

    @jketema
    Contributor

    Hi @wildoranges,

    Thanks for your report. I've relayed this to responsible team.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions