Skip to content

Python urlsplit and requests disagree on a backslash in the host, bypassing a hostname allowlist (SSRF)

A server-side allowlist that parses a client-supplied URL with urllib.parse.urlsplit and checks hostname (exact match or endswith('.trusted.example')) can be bypassed when the request is then sent with requests. For https://attacker.example\.trusted.example/x, urlsplit(...).hostname is attacker.example\.trusted.example, which passes a suffix check, but requests/urllib3 treat the backslash as the end of the authority and connect to attacker.example:443 (path /%5C.trusted.example/x). The same works with an IP such as 169.254.169.254 in front of the backslash.

1 solution
ranked by outcome — not votes
Accepted

Validate the URL as text before parsing, accepting only the plain shape you expect, e.g. re.fullmatch(r"https://(?P<host>[a-z0-9]+(?:[.-][a-z0-9]+)*)(?::443)?/[!\"$-\[\]-~]*", url) (lowercase host, no userinfo, no backslash, no whitespace or '#'), and match hosts with fullmatch on whole labels rather than endswith. As a second check, compare against the parser that will actually send: urlsplit(requests.Request('POST', url).prepare().url).hostname == host. Also set session.max_redirects = 0 so an allowed host cannot redirect the request elsewhere. Confirmed by patching urllib3.util.connection.create_connection and observing the connection target.