File CVE-2020-26116-httplib-header-injection.patch of Package python-base.17357

Index: Python-2.7.17/Lib/httplib.py
===================================================================
--- Python-2.7.17.orig/Lib/httplib.py
+++ Python-2.7.17/Lib/httplib.py
@@ -261,6 +261,10 @@ _contains_disallowed_url_pchar_re = re.c
 # servers will otherwise respond with a 411
 _METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
 
+# These characters are not allowed within HTTP method names
+# to prevent http header injection.
+_contains_disallowed_method_pchar_re = re.compile('[\x00-\x1f]')
+
 
 class HTTPMessage(mimetools.Message):
 
@@ -935,6 +939,8 @@ class HTTPConnection:
         else:
             raise CannotSendRequest()
 
+        self._validate_method(method)
+
         # Save the method for use later in the response phase
         self._method = method
 
@@ -1042,6 +1048,15 @@ class HTTPConnection:
             ).format(matched=match.group(), host=host)
             raise InvalidURL(msg)
 
+    def _validate_method(self, method):
+        """Validate a method name for putrequest."""
+        # prevent http header injection
+        match = _contains_disallowed_method_pchar_re.search(method)
+        if match:
+            raise ValueError(
+                "method can't contain control characters. %r (found at "
+                "least %r)" % (method, match.group()))
+
     def putheader(self, header, *values):
         """Send a request header line to the server.
 
Index: Python-2.7.17/Lib/test/test_httplib.py
===================================================================
--- Python-2.7.17.orig/Lib/test/test_httplib.py
+++ Python-2.7.17/Lib/test/test_httplib.py
@@ -1007,11 +1007,31 @@ class TunnelTests(TestCase):
         self.assertTrue('Host: destination.com' in conn.sock.data)
 
 
+class HttpMethodTests(TestCase):
+    def test_invalid_method_names(self):
+        methods = (
+            'GET\r',
+            'POST\n',
+            'PUT\n\r',
+            'POST\nValue',
+            'POST\nHOST:abc',
+            'GET\nrHost:abc\n',
+            'POST\rRemainder:\r',
+            'GET\rHOST:\n',
+            '\nPUT'
+        )
+
+        for method in methods:
+            conn = httplib.HTTPConnection('example.com')
+            conn.sock = FakeSocket(None)
+            self.assertRaises(ValueError, conn.request, method=method, url="/")
+
+
 @test_support.reap_threads
 def test_main(verbose=None):
     test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
-                              HTTPTest, HTTPSTest, SourceAddressTest,
-                              TunnelTests)
+                              HTTPTest, HTTPSTest, HttpMethodTests,
+                              SourceAddressTest, TunnelTests)
 
 if __name__ == '__main__':
     test_main()
openSUSE Build Service is sponsored by