Blame SOURCES/00324-disallow-control-chars-in-http-urls.patch

b9ffd2
From 7e200e0763f5b71c199aaf98bd5588f291585619 Mon Sep 17 00:00:00 2001
b9ffd2
From: =?UTF-8?q?Miro=20Hron=C4=8Dok?= <miro@hroncok.cz>
b9ffd2
Date: Tue, 7 May 2019 17:28:47 +0200
b9ffd2
Subject: [PATCH] bpo-30458: Disallow control chars in http URLs. (GH-12755)
b9ffd2
 (GH-13154)
b9ffd2
MIME-Version: 1.0
b9ffd2
Content-Type: text/plain; charset=UTF-8
b9ffd2
Content-Transfer-Encoding: 8bit
b9ffd2
b9ffd2
Disallow control chars in http URLs in urllib.urlopen.  This addresses a potential security problem for applications that do not sanity check their URLs where http request headers could be injected.
b9ffd2
b9ffd2
Disable https related urllib tests on a build without ssl (GH-13032)
b9ffd2
These tests require an SSL enabled build. Skip these tests when python is built without SSL to fix test failures.
b9ffd2
b9ffd2
Use http.client.InvalidURL instead of ValueError as the new error case's exception. (GH-13044)
b9ffd2
b9ffd2
Backport Co-Authored-By: Miro HronĨok <miro@hroncok.cz>
b9ffd2
---
b9ffd2
 Lib/http/client.py                            | 15 ++++++
b9ffd2
 Lib/test/test_urllib.py                       | 53 +++++++++++++++++++
b9ffd2
 Lib/test/test_xmlrpc.py                       |  7 ++-
b9ffd2
 .../2019-04-10-08-53-30.bpo-30458.51E-DA.rst  |  1 +
b9ffd2
 4 files changed, 75 insertions(+), 1 deletion(-)
b9ffd2
 create mode 100644 Misc/NEWS.d/next/Security/2019-04-10-08-53-30.bpo-30458.51E-DA.rst
b9ffd2
b9ffd2
diff --git a/Lib/http/client.py b/Lib/http/client.py
b9ffd2
index 1de151c38e..2afd452fe3 100644
b9ffd2
--- a/Lib/http/client.py
b9ffd2
+++ b/Lib/http/client.py
b9ffd2
@@ -140,6 +140,16 @@ _MAXHEADERS = 100
b9ffd2
 _is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch
b9ffd2
 _is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
b9ffd2
 
b9ffd2
+# These characters are not allowed within HTTP URL paths.
b9ffd2
+#  See https://tools.ietf.org/html/rfc3986#section-3.3 and the
b9ffd2
+#  https://tools.ietf.org/html/rfc3986#appendix-A pchar definition.
b9ffd2
+# Prevents CVE-2019-9740.  Includes control characters such as \r\n.
b9ffd2
+# We don't restrict chars above \x7f as putrequest() limits us to ASCII.
b9ffd2
+_contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]')
b9ffd2
+# Arguably only these _should_ allowed:
b9ffd2
+#  _is_allowed_url_pchars_re = re.compile(r"^[/!$&'()*+,;=:@%a-zA-Z0-9._~-]+$")
b9ffd2
+# We are more lenient for assumed real world compatibility purposes.
b9ffd2
+
b9ffd2
 # We always set the Content-Length header for these methods because some
b9ffd2
 # servers will otherwise respond with a 411
b9ffd2
 _METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
b9ffd2
@@ -1101,6 +1111,11 @@ class HTTPConnection:
b9ffd2
         self._method = method
b9ffd2
         if not url:
b9ffd2
             url = '/'
b9ffd2
+        # Prevent CVE-2019-9740.
b9ffd2
+        match = _contains_disallowed_url_pchar_re.search(url)
b9ffd2
+        if match:
b9ffd2
+            raise InvalidURL(f"URL can't contain control characters. {url!r} "
b9ffd2
+                             f"(found at least {match.group()!r})")
b9ffd2
         request = '%s %s %s' % (method, url, self._http_vsn_str)
b9ffd2
 
b9ffd2
         # Non-ASCII characters should have been eliminated earlier
b9ffd2
diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py
b9ffd2
index 2ac73b58d8..7214492eca 100644
b9ffd2
--- a/Lib/test/test_urllib.py
b9ffd2
+++ b/Lib/test/test_urllib.py
b9ffd2
@@ -329,6 +329,59 @@ class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin, FakeFTPMixin):
b9ffd2
         finally:
b9ffd2
             self.unfakehttp()
b9ffd2
 
b9ffd2
+    @unittest.skipUnless(ssl, "ssl module required")
b9ffd2
+    def test_url_with_control_char_rejected(self):
b9ffd2
+        for char_no in list(range(0, 0x21)) + [0x7f]:
b9ffd2
+            char = chr(char_no)
b9ffd2
+            schemeless_url = f"//localhost:7777/test{char}/"
b9ffd2
+            self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
b9ffd2
+            try:
b9ffd2
+                # We explicitly test urllib.request.urlopen() instead of the top
b9ffd2
+                # level 'def urlopen()' function defined in this... (quite ugly)
b9ffd2
+                # test suite.  They use different url opening codepaths.  Plain
b9ffd2
+                # urlopen uses FancyURLOpener which goes via a codepath that
b9ffd2
+                # calls urllib.parse.quote() on the URL which makes all of the
b9ffd2
+                # above attempts at injection within the url _path_ safe.
b9ffd2
+                escaped_char_repr = repr(char).replace('\\', r'\\')
b9ffd2
+                InvalidURL = http.client.InvalidURL
b9ffd2
+                with self.assertRaisesRegex(
b9ffd2
+                    InvalidURL, f"contain control.*{escaped_char_repr}"):
b9ffd2
+                    urllib.request.urlopen(f"http:{schemeless_url}")
b9ffd2
+                with self.assertRaisesRegex(
b9ffd2
+                    InvalidURL, f"contain control.*{escaped_char_repr}"):
b9ffd2
+                    urllib.request.urlopen(f"https:{schemeless_url}")
b9ffd2
+                # This code path quotes the URL so there is no injection.
b9ffd2
+                resp = urlopen(f"http:{schemeless_url}")
b9ffd2
+                self.assertNotIn(char, resp.geturl())
b9ffd2
+            finally:
b9ffd2
+                self.unfakehttp()
b9ffd2
+
b9ffd2
+    @unittest.skipUnless(ssl, "ssl module required")
b9ffd2
+    def test_url_with_newline_header_injection_rejected(self):
b9ffd2
+        self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
b9ffd2
+        host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\r\nTEST: 123"
b9ffd2
+        schemeless_url = "//" + host + ":8080/test/?test=a"
b9ffd2
+        try:
b9ffd2
+            # We explicitly test urllib.request.urlopen() instead of the top
b9ffd2
+            # level 'def urlopen()' function defined in this... (quite ugly)
b9ffd2
+            # test suite.  They use different url opening codepaths.  Plain
b9ffd2
+            # urlopen uses FancyURLOpener which goes via a codepath that
b9ffd2
+            # calls urllib.parse.quote() on the URL which makes all of the
b9ffd2
+            # above attempts at injection within the url _path_ safe.
b9ffd2
+            InvalidURL = http.client.InvalidURL
b9ffd2
+            with self.assertRaisesRegex(
b9ffd2
+                InvalidURL, r"contain control.*\\r.*(found at least . .)"):
b9ffd2
+                urllib.request.urlopen(f"http:{schemeless_url}")
b9ffd2
+            with self.assertRaisesRegex(InvalidURL, r"contain control.*\\n"):
b9ffd2
+                urllib.request.urlopen(f"https:{schemeless_url}")
b9ffd2
+            # This code path quotes the URL so there is no injection.
b9ffd2
+            resp = urlopen(f"http:{schemeless_url}")
b9ffd2
+            self.assertNotIn(' ', resp.geturl())
b9ffd2
+            self.assertNotIn('\r', resp.geturl())
b9ffd2
+            self.assertNotIn('\n', resp.geturl())
b9ffd2
+        finally:
b9ffd2
+            self.unfakehttp()
b9ffd2
+
b9ffd2
     def test_read_0_9(self):
b9ffd2
         # "0.9" response accepted (but not "simple responses" without
b9ffd2
         # a status line)
b9ffd2
diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py
b9ffd2
index 32263f7f0b..0e002ec4ef 100644
b9ffd2
--- a/Lib/test/test_xmlrpc.py
b9ffd2
+++ b/Lib/test/test_xmlrpc.py
b9ffd2
@@ -945,7 +945,12 @@ class SimpleServerTestCase(BaseServerTestCase):
b9ffd2
     def test_partial_post(self):
b9ffd2
         # Check that a partial POST doesn't make the server loop: issue #14001.
b9ffd2
         conn = http.client.HTTPConnection(ADDR, PORT)
b9ffd2
-        conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye')
b9ffd2
+        conn.send('POST /RPC2 HTTP/1.0\r\n'
b9ffd2
+                  'Content-Length: 100\r\n\r\n'
b9ffd2
+                  'bye HTTP/1.1\r\n'
b9ffd2
+                  f'Host: {ADDR}:{PORT}\r\n'
b9ffd2
+                  'Accept-Encoding: identity\r\n'
b9ffd2
+                  'Content-Length: 0\r\n\r\n'.encode('ascii'))
b9ffd2
         conn.close()
b9ffd2
 
b9ffd2
     def test_context_manager(self):
b9ffd2
diff --git a/Misc/NEWS.d/next/Security/2019-04-10-08-53-30.bpo-30458.51E-DA.rst b/Misc/NEWS.d/next/Security/2019-04-10-08-53-30.bpo-30458.51E-DA.rst
b9ffd2
new file mode 100644
b9ffd2
index 0000000000..ed8027fb4d
b9ffd2
--- /dev/null
b9ffd2
+++ b/Misc/NEWS.d/next/Security/2019-04-10-08-53-30.bpo-30458.51E-DA.rst
b9ffd2
@@ -0,0 +1 @@
b9ffd2
+Address CVE-2019-9740 by disallowing URL paths with embedded whitespace or control characters through into the underlying http client request.  Such potentially malicious header injection URLs now cause an http.client.InvalidURL exception to be raised.
b9ffd2
-- 
b9ffd2
2.21.0
b9ffd2