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

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