You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

146 lines
7.5 KiB

  1. From 233e3211cfdcca7310e25529e9115fbaddf47cca Mon Sep 17 00:00:00 2001
  2. From: "Gregory P. Smith" <greg@krypto.org>
  3. Date: Tue, 30 Apr 2019 19:12:21 -0700
  4. Subject: [PATCH] bpo-30458: Disallow control chars in http URLs. (GH-12755)
  5. MIME-Version: 1.0
  6. Content-Type: text/plain; charset=UTF-8
  7. Content-Transfer-Encoding: 8bit
  8. 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.
  9. Disable https related urllib tests on a build without ssl (GH-13032)
  10. These tests require an SSL enabled build. Skip these tests when python is built without SSL to fix test failures.
  11. Use http.client.InvalidURL instead of ValueError as the new error case's exception. (GH-13044)
  12. Co-Authored-By: Miro Hrončok <miro@hroncok.cz>
  13. ---
  14. Lib/http/client.py | 15 ++++++
  15. Lib/test/test_urllib.py | 53 +++++++++++++++++++
  16. Lib/test/test_xmlrpc.py | 7 ++-
  17. .../2019-04-10-08-53-30.bpo-30458.51E-DA.rst | 1 +
  18. 4 files changed, 75 insertions(+), 1 deletion(-)
  19. create mode 100644 Misc/NEWS.d/next/Security/2019-04-10-08-53-30.bpo-30458.51E-DA.rst
  20. diff --git a/Lib/http/client.py b/Lib/http/client.py
  21. index 1de151c38e92..2afd452fe30f 100644
  22. --- a/Lib/http/client.py
  23. +++ b/Lib/http/client.py
  24. @@ -140,6 +140,16 @@
  25. _is_legal_header_name = re.compile(rb'[^:\s][^:\r\n]*').fullmatch
  26. _is_illegal_header_value = re.compile(rb'\n(?![ \t])|\r(?![ \t\n])').search
  27. +# These characters are not allowed within HTTP URL paths.
  28. +# See https://tools.ietf.org/html/rfc3986#section-3.3 and the
  29. +# https://tools.ietf.org/html/rfc3986#appendix-A pchar definition.
  30. +# Prevents CVE-2019-9740. Includes control characters such as \r\n.
  31. +# We don't restrict chars above \x7f as putrequest() limits us to ASCII.
  32. +_contains_disallowed_url_pchar_re = re.compile('[\x00-\x20\x7f]')
  33. +# Arguably only these _should_ allowed:
  34. +# _is_allowed_url_pchars_re = re.compile(r"^[/!$&'()*+,;=:@%a-zA-Z0-9._~-]+$")
  35. +# We are more lenient for assumed real world compatibility purposes.
  36. +
  37. # We always set the Content-Length header for these methods because some
  38. # servers will otherwise respond with a 411
  39. _METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
  40. @@ -1101,6 +1111,11 @@ def putrequest(self, method, url, skip_host=False,
  41. self._method = method
  42. if not url:
  43. url = '/'
  44. + # Prevent CVE-2019-9740.
  45. + match = _contains_disallowed_url_pchar_re.search(url)
  46. + if match:
  47. + raise InvalidURL(f"URL can't contain control characters. {url!r} "
  48. + f"(found at least {match.group()!r})")
  49. request = '%s %s %s' % (method, url, self._http_vsn_str)
  50. # Non-ASCII characters should have been eliminated earlier
  51. diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py
  52. index 2ac73b58d832..7214492eca9d 100644
  53. --- a/Lib/test/test_urllib.py
  54. +++ b/Lib/test/test_urllib.py
  55. @@ -329,6 +329,59 @@ def test_willclose(self):
  56. finally:
  57. self.unfakehttp()
  58. + @unittest.skipUnless(ssl, "ssl module required")
  59. + def test_url_with_control_char_rejected(self):
  60. + for char_no in list(range(0, 0x21)) + [0x7f]:
  61. + char = chr(char_no)
  62. + schemeless_url = f"//localhost:7777/test{char}/"
  63. + self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
  64. + try:
  65. + # We explicitly test urllib.request.urlopen() instead of the top
  66. + # level 'def urlopen()' function defined in this... (quite ugly)
  67. + # test suite. They use different url opening codepaths. Plain
  68. + # urlopen uses FancyURLOpener which goes via a codepath that
  69. + # calls urllib.parse.quote() on the URL which makes all of the
  70. + # above attempts at injection within the url _path_ safe.
  71. + escaped_char_repr = repr(char).replace('\\', r'\\')
  72. + InvalidURL = http.client.InvalidURL
  73. + with self.assertRaisesRegex(
  74. + InvalidURL, f"contain control.*{escaped_char_repr}"):
  75. + urllib.request.urlopen(f"http:{schemeless_url}")
  76. + with self.assertRaisesRegex(
  77. + InvalidURL, f"contain control.*{escaped_char_repr}"):
  78. + urllib.request.urlopen(f"https:{schemeless_url}")
  79. + # This code path quotes the URL so there is no injection.
  80. + resp = urlopen(f"http:{schemeless_url}")
  81. + self.assertNotIn(char, resp.geturl())
  82. + finally:
  83. + self.unfakehttp()
  84. +
  85. + @unittest.skipUnless(ssl, "ssl module required")
  86. + def test_url_with_newline_header_injection_rejected(self):
  87. + self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
  88. + host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\r\nTEST: 123"
  89. + schemeless_url = "//" + host + ":8080/test/?test=a"
  90. + try:
  91. + # We explicitly test urllib.request.urlopen() instead of the top
  92. + # level 'def urlopen()' function defined in this... (quite ugly)
  93. + # test suite. They use different url opening codepaths. Plain
  94. + # urlopen uses FancyURLOpener which goes via a codepath that
  95. + # calls urllib.parse.quote() on the URL which makes all of the
  96. + # above attempts at injection within the url _path_ safe.
  97. + InvalidURL = http.client.InvalidURL
  98. + with self.assertRaisesRegex(
  99. + InvalidURL, r"contain control.*\\r.*(found at least . .)"):
  100. + urllib.request.urlopen(f"http:{schemeless_url}")
  101. + with self.assertRaisesRegex(InvalidURL, r"contain control.*\\n"):
  102. + urllib.request.urlopen(f"https:{schemeless_url}")
  103. + # This code path quotes the URL so there is no injection.
  104. + resp = urlopen(f"http:{schemeless_url}")
  105. + self.assertNotIn(' ', resp.geturl())
  106. + self.assertNotIn('\r', resp.geturl())
  107. + self.assertNotIn('\n', resp.geturl())
  108. + finally:
  109. + self.unfakehttp()
  110. +
  111. def test_read_0_9(self):
  112. # "0.9" response accepted (but not "simple responses" without
  113. # a status line)
  114. diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py
  115. index 32263f7f0b3b..0e002ec4ef9f 100644
  116. --- a/Lib/test/test_xmlrpc.py
  117. +++ b/Lib/test/test_xmlrpc.py
  118. @@ -945,7 +945,12 @@ def test_unicode_host(self):
  119. def test_partial_post(self):
  120. # Check that a partial POST doesn't make the server loop: issue #14001.
  121. conn = http.client.HTTPConnection(ADDR, PORT)
  122. - conn.request('POST', '/RPC2 HTTP/1.0\r\nContent-Length: 100\r\n\r\nbye')
  123. + conn.send('POST /RPC2 HTTP/1.0\r\n'
  124. + 'Content-Length: 100\r\n\r\n'
  125. + 'bye HTTP/1.1\r\n'
  126. + f'Host: {ADDR}:{PORT}\r\n'
  127. + 'Accept-Encoding: identity\r\n'
  128. + 'Content-Length: 0\r\n\r\n'.encode('ascii'))
  129. conn.close()
  130. def test_context_manager(self):
  131. 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
  132. new file mode 100644
  133. index 000000000000..ed8027fb4d64
  134. --- /dev/null
  135. +++ b/Misc/NEWS.d/next/Security/2019-04-10-08-53-30.bpo-30458.51E-DA.rst
  136. @@ -0,0 +1 @@
  137. +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.