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

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