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

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