Repository navigation
Python: Fix URL redirection validation sanitizers #22872
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
f8fa903
e224317
f0e5329
8bac259
e4faecf
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| --- | ||
| category: minorAnalysis | ||
| --- | ||
| * URL redirection sanitizers based on `urllib.parse.urlparse` and `urllib.parse.urlsplit` now require checks of the scheme, leading slashes, and browser-ignored characters when the network location may be empty. Host allowlists must resolve locally to known values, and collection allowlists are trusted only when immutable or used directly as literals. Hostname attributes are trusted only when all possible receivers originate from `urlparse` or `urlsplit` calls on constant URLs. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -11,6 +11,7 @@ | |
| private import semmle.python.Concepts | ||
| private import semmle.python.ApiGraphs | ||
| private import semmle.python.security.dataflow.UrlRedirectCustomizations | ||
| private import codeql.util.Boolean | ||
|
|
||
| /** | ||
| * Provides models for the `urllib` module, part of | ||
|
|
@@ -81,47 +82,298 @@ | |
| */ | ||
| module Parse { | ||
| /** | ||
| * A call to `urllib.parse.urlparse`. | ||
| * A call to `urllib.parse.urlparse` or `urllib.parse.urlsplit`. | ||
| */ | ||
| private DataFlow::CallCfgNode getUrlParseCall() { | ||
| result = API::moduleImport("urllib").getMember("parse").getMember("urlparse").getACall() | ||
| result = | ||
| API::moduleImport("urllib") | ||
| .getMember("parse") | ||
| .getMember(["urlparse", "urlsplit"]) | ||
| .getACall() and | ||
| forex(DataFlow::LocalSourceNode source | source = result.getFunction().getALocalSource() | | ||
| // API reachability does not exclude other values passed to a parameter or returned by a call. | ||
| not source instanceof DataFlow::ParameterNode and | ||
| not source instanceof DataFlow::CallCfgNode and | ||
| source = | ||
| API::moduleImport("urllib") | ||
| .getMember("parse") | ||
| .getMember(["urlparse", "urlsplit"]) | ||
| .getAValueReachableFromSource() | ||
| ) | ||
| } | ||
|
|
||
| /** A URL parser call whose URL argument resolves entirely to string literals. */ | ||
| private DataFlow::CallCfgNode getConstantUrlParseCall() { | ||
| result = getUrlParseCall() and | ||
| forex(DataFlow::LocalSourceNode source | | ||
| source = [result.getArg(0), result.getArgByName(["url", "urlstring"])].getALocalSource() | ||
| | | ||
| source.asExpr() instanceof StringLiteral | ||
| ) | ||
| } | ||
|
|
||
| /** Holds if `e` is a parsed URL hostname, which is either non-empty or `None`. */ | ||
| private predicate isParsedUrlHostname(Expr e) { | ||
| exists(DataFlow::AttrRead read | | ||
| read = DataFlow::exprNode(e) and | ||
| read.getAttributeName() = "hostname" and | ||
| forex(DataFlow::LocalSourceNode source | source = read.getObject().getALocalSource() | | ||
| source = getConstantUrlParseCall() | ||
| ) | ||
| ) | ||
| } | ||
|
|
||
| /** Holds if `e` itself is known not to be `""`. */ | ||
| private predicate sourceExcludesEmptyString(Expr e) { | ||
| e.(StringLiteral).getText() != "" | ||
| or | ||
| isParsedUrlHostname(e) | ||
| } | ||
|
|
||
| /** Holds if every local source of `e` excludes `""`. */ | ||
| private predicate excludesEmptyString(Expr e) { | ||
| forex(DataFlow::LocalSourceNode source | source = DataFlow::exprNode(e).getALocalSource() | | ||
| sourceExcludesEmptyString(source.asExpr()) | ||
| ) | ||
| } | ||
|
|
||
| /** Holds if every local source of `e` is a collection literal, rather than a string. */ | ||
| private predicate membershipChecksCollection(Expr e) { | ||
| forex(DataFlow::LocalSourceNode source | source = DataFlow::exprNode(e).getALocalSource() | | ||
|
owen-mc marked this conversation as resolved.
Resolved
|
||
| source.asCfgNode() instanceof IterableNode | ||
| or | ||
| source.asCfgNode() instanceof DictNode | ||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * A read of the `netloc` attribute of a parsed URL as returned by `urllib.parse.urlparse`, | ||
| * which is being checked in a way that is relevant for URL redirection vulnerabilities. | ||
| * Holds if every local source of `e` is an immutable collection literal, or a mutable | ||
| * collection literal used directly in the membership test, with known host elements or keys. | ||
| * Empty strings are accepted only when `allowEmpty` is true. | ||
| */ | ||
| private predicate netlocCheck(DataFlow::GuardNode g, ControlFlowNode node, boolean branch) { | ||
| exists(DataFlow::CallCfgNode urlParseCall, DataFlow::AttrRead netlocRead | | ||
| private predicate membershipChecksKnownHosts(Expr e, Boolean allowEmpty) { | ||
| forex(DataFlow::LocalSourceNode source | source = DataFlow::exprNode(e).getALocalSource() | | ||
| exists(Expr collection | collection = source.asExpr() | | ||
| (collection instanceof List or collection instanceof Tuple or collection instanceof Set) and | ||
|
owen-mc marked this conversation as resolved.
Resolved
|
||
| (collection instanceof Tuple or collection = e) and | ||
| forall(Expr elt | | ||
| elt = | ||
| [ | ||
| collection.(List).getAnElt(), collection.(Tuple).getAnElt(), | ||
| collection.(Set).getAnElt() | ||
| ] | ||
| | | ||
| excludesEmptyString(elt) | ||
| or | ||
| allowEmpty = true and isEmptyString(elt) | ||
|
owen-mc marked this conversation as resolved.
Resolved
|
||
| ) | ||
| or | ||
| collection instanceof Dict and | ||
| collection = e and | ||
| not collection.(Dict).getAnItem() instanceof DictUnpacking and | ||
| forall(Expr key | key = collection.(Dict).getAKey() | | ||
| excludesEmptyString(key) | ||
| or | ||
| allowEmpty = true and isEmptyString(key) | ||
|
owen-mc marked this conversation as resolved.
Resolved
|
||
| ) | ||
| ) | ||
| ) | ||
| } | ||
|
|
||
| /** Holds if every local source of `e` is `""`. */ | ||
| private predicate isEmptyString(Expr e) { | ||
| forex(DataFlow::LocalSourceNode source | source = DataFlow::exprNode(e).getALocalSource() | | ||
| source.asExpr().(StringLiteral).getText() = "" | ||
| ) | ||
| } | ||
|
|
||
| /** Holds if comparing against `e` using `op` cannot accept `""`. */ | ||
| private predicate comparisonExcludesEmptyString(Cmpop op, Expr e) { | ||
| op.getSymbol() in ["in", "not in"] and membershipChecksKnownHosts(e, false) | ||
| or | ||
| op.getSymbol() in ["==", "is", "!=", "is not"] and excludesEmptyString(e) | ||
| } | ||
|
|
||
| /** Holds if `read` reads `attribute` from the result of `urlParseCall`. */ | ||
| private predicate parsedUrlAttributeRead( | ||
| DataFlow::CallCfgNode urlParseCall, DataFlow::AttrRead read, string attribute | ||
| ) { | ||
| read.getAttributeName() = attribute and | ||
| forex(DataFlow::LocalSourceNode source | source = read.getObject().getALocalSource() | | ||
| source = urlParseCall | ||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * Holds if `g` is a falsiness check `not parsed.<attribute>` on a parsed URL `node`. | ||
| */ | ||
| private predicate parsedUrlAttributeFalsiness( | ||
| DataFlow::GuardNode g, ControlFlowNode node, boolean branch, string attribute | ||
| ) { | ||
| exists(DataFlow::CallCfgNode urlParseCall, DataFlow::AttrRead attributeRead | | ||
| urlParseCall = getUrlParseCall() and | ||
| netlocRead = urlParseCall.getAnAttributeRead("netloc") and | ||
| node = urlParseCall.getArg(0).asCfgNode() | ||
| | | ||
| // either a simple check of the netloc attribute | ||
| g = netlocRead.asCfgNode() and | ||
| parsedUrlAttributeRead(urlParseCall, attributeRead, attribute) and | ||
| g = attributeRead.asCfgNode() and | ||
| node = [urlParseCall.getArg(0), urlParseCall.getArgByName(["url", "urlstring"])].asCfgNode() and | ||
| branch = false | ||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * Holds if `g` compares `attribute` (`"netloc"` or `"scheme"`) of a parsed URL `node` | ||
| * against `other` using `op`, and the equality or collection membership holds on `branch`. | ||
| */ | ||
| private predicate parsedUrlAttributeComparison( | ||
| DataFlow::GuardNode g, ControlFlowNode node, boolean branch, string attribute, Cmpop op, | ||
| Expr other | ||
| ) { | ||
| exists( | ||
| DataFlow::CallCfgNode urlParseCall, DataFlow::AttrRead attributeRead, CompareNode cmp, | ||
| ControlFlowNode otherNode | ||
| | | ||
| urlParseCall = getUrlParseCall() and | ||
| parsedUrlAttributeRead(urlParseCall, attributeRead, attribute) and | ||
| node = [urlParseCall.getArg(0), urlParseCall.getArgByName(["url", "urlstring"])].asCfgNode() and | ||
| cmp = g and | ||
| op = unique(Cmpop opp | opp = cmp.getNode().getAnOp()) and | ||
| other = otherNode.getNode() | ||
| | | ||
| op.getSymbol() in ["==", "is"] and | ||
| branch = true and | ||
| ( | ||
| cmp.operands(attributeRead.asCfgNode(), op, otherNode) or | ||
| cmp.operands(otherNode, op, attributeRead.asCfgNode()) | ||
| ) | ||
| or | ||
| op.getSymbol() in ["!=", "is not"] and | ||
| branch = false and | ||
| ( | ||
| cmp.operands(attributeRead.asCfgNode(), op, otherNode) or | ||
| cmp.operands(otherNode, op, attributeRead.asCfgNode()) | ||
| ) | ||
| or | ||
| op.getSymbol() = "in" and | ||
| membershipChecksCollection(other) and | ||
| branch = true and | ||
| cmp.operands(attributeRead.asCfgNode(), op, otherNode) | ||
| or | ||
| // or a comparison (we don't care against what) | ||
| exists(Compare cmp, string op | | ||
| cmp = g.getNode() and | ||
| op = unique(Cmpop opp | opp = cmp.getAnOp()).getSymbol() and | ||
| cmp.getASubExpression() = netlocRead.asExpr() | ||
| | | ||
| op in ["==", "is", "in"] and branch = true | ||
| op.getSymbol() = "not in" and | ||
| membershipChecksCollection(other) and | ||
| branch = false and | ||
| cmp.operands(attributeRead.asCfgNode(), op, otherNode) | ||
| ) | ||
| } | ||
|
|
||
| /** A `netloc` check that does not allow `""` (e.g. `parsed.netloc == request.host`). */ | ||
| private predicate nonEmptyNetlocCheck( | ||
| DataFlow::GuardNode g, ControlFlowNode node, boolean branch | ||
| ) { | ||
| exists(Cmpop op, Expr other | | ||
| parsedUrlAttributeComparison(g, node, branch, "netloc", op, other) and | ||
| comparisonExcludesEmptyString(op, other) | ||
| ) | ||
| } | ||
|
|
||
| /** A `netloc` check allowing `""` and otherwise only known hosts. */ | ||
| private predicate possiblyEmptyNetlocCheck( | ||
| DataFlow::GuardNode g, ControlFlowNode node, boolean branch | ||
| ) { | ||
| parsedUrlAttributeFalsiness(g, node, branch, "netloc") | ||
| or | ||
| exists(Cmpop op, Expr other | | ||
| parsedUrlAttributeComparison(g, node, branch, "netloc", op, other) and | ||
| ( | ||
| op.getSymbol() in ["==", "is", "!=", "is not"] and isEmptyString(other) | ||
| or | ||
| op in ["!=", "is not", "not in"] and branch = false | ||
| op.getSymbol() in ["in", "not in"] and membershipChecksKnownHosts(other, true) | ||
| ) | ||
| ) | ||
| } | ||
|
|
||
| /** A `scheme` check that ensures `scheme` is `""`. */ | ||
| private predicate emptySchemeCheck(DataFlow::GuardNode g, ControlFlowNode node, boolean branch) { | ||
| parsedUrlAttributeFalsiness(g, node, branch, "scheme") | ||
| or | ||
| exists(Cmpop op, Expr other | | ||
| parsedUrlAttributeComparison(g, node, branch, "scheme", op, other) and | ||
| op.getSymbol() in ["==", "is", "!=", "is not"] and | ||
| isEmptyString(other) | ||
| ) | ||
| } | ||
|
|
||
| /** Holds if every possible callee is `methodName` bound to `object`. */ | ||
| private predicate callsOnlyMethod( | ||
| DataFlow::MethodCallNode call, DataFlow::Node object, string methodName | ||
| ) { | ||
| forex(DataFlow::LocalSourceNode source | source = call.getFunction().getALocalSource() | | ||
| source.(DataFlow::AttrRead).getAttributeName() = methodName and | ||
| source.(DataFlow::AttrRead).getObject() = object | ||
| ) | ||
| } | ||
|
|
||
| private predicate leadingSlashesCheck( | ||
| DataFlow::GuardNode g, ControlFlowNode node, boolean branch | ||
| ) { | ||
| exists(DataFlow::MethodCallNode call, DataFlow::Node url, Expr prefix | | ||
| callsOnlyMethod(call, url, "startswith") and | ||
| ( | ||
| prefix = call.getArg(0).asExpr() or | ||
| prefix = call.getArg(0).asExpr().(Tuple).getAnElt() | ||
| ) and | ||
| prefix.(StringLiteral).getText() in ["/", "//", "///"] and | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
would reject |
||
| not exists(call.getArg(1)) and | ||
| not exists(call.getStarArg()) and | ||
| g = call.asCfgNode() and | ||
| node = url.asCfgNode() and | ||
| branch = false | ||
| ) | ||
| } | ||
|
|
||
| /** Holds if every local source of `node` is a no-argument `strip` or `lstrip` call. */ | ||
| private predicate isStripped(DataFlow::Node node) { | ||
| forex(DataFlow::LocalSourceNode source | source = node.getALocalSource() | | ||
| callsOnlyMethod(source, _, ["strip", "lstrip"]) and | ||
| not exists(source.asExpr().(Call).getAPositionalArg()) and | ||
| not exists(source.asExpr().(Call).getANamedArg()) | ||
| ) | ||
| } | ||
|
|
||
| /** An `isprintable` check on a stripped URL. */ | ||
| private predicate normalizedPrintableCheck( | ||
| DataFlow::GuardNode g, ControlFlowNode node, boolean branch | ||
| ) { | ||
| exists(DataFlow::MethodCallNode call, DataFlow::Node url | | ||
| callsOnlyMethod(call, url, "isprintable") and | ||
| not exists(call.asExpr().(Call).getAPositionalArg()) and | ||
| not exists(call.asExpr().(Call).getANamedArg()) and | ||
| isStripped(url) and | ||
| g = call.asCfgNode() and | ||
| node = url.asCfgNode() and | ||
| branch = true | ||
| ) | ||
| } | ||
|
|
||
| /** | ||
| * A check of `urllib.parse.urlparse().netloc`, considered as a sanitizer-guard for URL redirection. | ||
| * A check of `urllib.parse.urlparse` or `urllib.parse.urlsplit` considered as a | ||
| * sanitizer-guard for URL redirection. | ||
| * | ||
| * Either `netloc` is restricted to a non-empty host, or `netloc` may be empty | ||
| * and `scheme`, leading slashes (`///`), and browser-ignored characters are also checked. | ||
| */ | ||
| private class NetlocCheck extends UrlRedirect::Sanitizer { | ||
| NetlocCheck() { this = DataFlow::BarrierGuard<netlocCheck/3>::getABarrierNode() } | ||
| NetlocCheck() { | ||
| this = DataFlow::BarrierGuard<nonEmptyNetlocCheck/3>::getABarrierNode() | ||
| or | ||
| this = DataFlow::BarrierGuard<possiblyEmptyNetlocCheck/3>::getABarrierNode() and | ||
| this = DataFlow::BarrierGuard<emptySchemeCheck/3>::getABarrierNode() and | ||
| // Browsers interpret three or more leading slashes as an authority, unlike `urlparse`. | ||
| this = DataFlow::BarrierGuard<leadingSlashesCheck/3>::getABarrierNode() and | ||
| // Browsers ignore leading whitespace and control characters within URLs. | ||
| this = DataFlow::BarrierGuard<normalizedPrintableCheck/3>::getABarrierNode() | ||
| } | ||
|
|
||
| override predicate sanitizes(UrlRedirect::FlowState state) { | ||
| // `urlparse` does not handle backslashes | ||
| // Neither parser handles backslashes as browsers do. | ||
| state instanceof UrlRedirect::NoBackslashes | ||
| } | ||
| } | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.