CVE-2023-45803: Exposure of Sensitive Information to an Unauthorized Actor (CWE-200)
value: urllib3 is a user-friendly HTTP client library for Python. urllib3 previously wouldn't remove the HTTP request body when an HTTP redirect response using status 301, 302, or 303 after the request had its method changed from one that could accept a request body (like `POST`) to `GET` as is required by HTTP RFCs. Although this behavior is not specified in the section for redirects, it can be inferred by piecing together information from different sections and we have observed the behavior in other major HTTP client implementations like curl and web browsers. Because the vulnerability requires a previously trusted service to become compromised in order to have an impact on confidentiality we believe the exploitability of this vulnerability is low. Additionally, many users aren't putting sensitive data in HTTP request bodies, if this is the case then this vulnerability isn't exploitable. Both of the following conditions must be true to be affected by this vulnerability: 1. Using urllib3 and submitting sensitive information in the HTTP request body (such as form data or JSON) and 2. The origin service is compromised and starts redirecting using 301, 302, or 303 to a malicious peer or the redirected-to service becomes compromised. This issue has been addressed in versions 1.26.18 and 2.0.7 and users are advised to update to resolve this issue. Users unable to update should disable redirects for services that aren't expecting to respond with redirects with `redirects=False` and disable automatic redirects with `redirects=False` and handle 301, 302, and 303 redirects manually by stripping the HTTP request body.

CWE description: The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
CVSS v3 base score: 4.2
Published: 2023-10-17T20:15Z
Repository: https://github.com/urllib3/urllib3
Language: Python
Files changed: .readthedocs.yml, CHANGES.rst, dummyserver/handlers.py, src/urllib3/_collections.py, src/urllib3/_version.py, src/urllib3/connectionpool.py, src/urllib3/poolmanager.py, test/with_dummyserver/test_connectionpool.py, test/with_dummyserver/test_poolmanager.py
Commit date: 2023-10-17 21:07:33 +0300
Commit message: Bring 2.0.7 & 1.26.18 to main (#3161)

* Merge pull request from GHSA-g4mx-q9vg-27p4

* Release 2.0.7
Diff: diff --git a/.readthedocs.yml b/.readthedocs.yml
index 78bd2064f..7c59df5b3 100644
--- a/.readthedocs.yml
+++ b/.readthedocs.yml
@@ -1,11 +1,11 @@
 version: 2
 
 build:
   os: ubuntu-22.04
   tools:
-    python: "3"
+    python: "3.11"
 
 python:
   install:
     - requirements: docs/requirements.txt
     - method: pip
diff --git a/CHANGES.rst b/CHANGES.rst
index 27038fef4..6c37aeba1 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -1,5 +1,10 @@
+2.0.7 (2023-10-17)
+==================
+
+* Made body stripped from HTTP requests changing the request method to GET after HTTP 303 "See Other" redirect responses.
+
 2.0.6 (2023-10-02)
 ==================
 
 * Added the ``Cookie`` header to the list of headers to strip from requests when redirecting to a different host. As before, different headers can be set via ``Retry.remove_headers_on_redirect``.
 
@@ -165,10 +170,15 @@ Fixed
 * Fixed a bug where ``headers`` would be modified by the ``remove_headers_on_redirect`` feature (`#2272 <https://github.com/urllib3/urllib3/issues/2272>`__).
 * Fixed a reference cycle bug in ``urllib3.util.connection.create_connection()`` (`#2277 <https://github.com/urllib3/urllib3/issues/2277>`__).
 * Fixed a socket leak if ``HTTPConnection.connect()`` fails (`#2571 <https://github.com/urllib3/urllib3/pull/2571>`__).
 * Fixed ``urllib3.contrib.pyopenssl.WrappedSocket`` and ``urllib3.contrib.securetransport.WrappedSocket`` close methods (`#2970 <https://github.com/urllib3/urllib3/issues/2970>`__)
 
+1.26.18 (2023-10-17)
+====================
+
+* Made body stripped from HTTP requests changing the request method to GET after HTTP 303 "See Other" redirect responses.
+
 1.26.17 (2023-10-02)
 ====================
 
 * Added the ``Cookie`` header to the list of headers to strip from requests when redirecting to a different host. As before, different headers can be set via ``Retry.remove_headers_on_redirect``. (`#3139 <https://github.com/urllib3/urllib3/pull/3139>`_)
 
diff --git a/dummyserver/handlers.py b/dummyserver/handlers.py
index 9fde80e04..86201a116 100644
--- a/dummyserver/handlers.py
+++ b/dummyserver/handlers.py
@@ -279,10 +279,16 @@ class TestingApp(RequestHandler):
         return Response(data, headers=headers)
 
     def headers(self, request: httputil.HTTPServerRequest) -> Response:
         return Response(json.dumps(dict(request.headers)))
 
+    def headers_and_params(self, request: httputil.HTTPServerRequest) -> Response:
+        params = request_params(request)
+        return Response(
+            json.dumps({"headers": dict(request.headers), "params": params})
+        )
+
     def multi_headers(self, request: httputil.HTTPServerRequest) -> Response:
         return Response(json.dumps({"headers": list(request.headers.get_all())}))
 
     def successful_retry(self, request: httputil.HTTPServerRequest) -> Response:
         """Handler which will return an error and then success
diff --git a/src/urllib3/_collections.py b/src/urllib3/_collections.py
index f1cb60654..55b032479 100644
--- a/src/urllib3/_collections.py
+++ b/src/urllib3/_collections.py
@@ -8,10 +8,12 @@ from threading import RLock
 if typing.TYPE_CHECKING:
     # We can only import Protocol if TYPE_CHECKING because it's a development
     # dependency, and is not available at runtime.
     from typing import Protocol
 
+    from typing_extensions import Self
+
     class HasGettableStringKeys(Protocol):
         def keys(self) -> typing.Iterator[str]:
             ...
 
         def __getitem__(self, key: str) -> str:
@@ -389,10 +391,28 @@ class HTTPHeaderDict(typing.MutableMapping[str, str]):
         else:
             # _DT may or may not be bound; vals[1:] is instance of List[str], which
             # meets our external interface requirement of `Union[List[str], _DT]`.
             return vals[1:]
 
+    def _prepare_for_method_change(self) -> Self:
+        """
+        Remove content-specific header fields before changing the request
+        method to GET or HEAD according to RFC 9110, Section 15.4.
+        """
+        content_specific_headers = [
+            "Content-Encoding",
+            "Content-Language",
+            "Content-Location",
+            "Content-Type",
+            "Content-Length",
+            "Digest",
+            "Last-Modified",
+        ]
+        for header in content_specific_headers:
+            self.discard(header)
+        return self
+
     # Backwards compatibility for httplib
     getheaders = getlist
     getallmatchingheaders = getlist
     iget = getlist
 
diff --git a/src/urllib3/_version.py b/src/urllib3/_version.py
index 2d0d43089..e2b88f1d6 100644
--- a/src/urllib3/_version.py
+++ b/src/urllib3/_version.py
@@ -1,4 +1,4 @@
 # This file is protected via CODEOWNERS
 from __future__ import annotations
 
-__version__ = "2.0.6"
+__version__ = "2.0.7"
diff --git a/src/urllib3/connectionpool.py b/src/urllib3/connectionpool.py
index 113d264d7..70048b7ae 100644
--- a/src/urllib3/connectionpool.py
+++ b/src/urllib3/connectionpool.py
@@ -9,10 +9,11 @@ import warnings
 import weakref
 from socket import timeout as SocketTimeout
 from types import TracebackType
 
 from ._base_connection import _TYPE_BODY
+from ._collections import HTTPHeaderDict
 from ._request_methods import RequestMethods
 from .connection import (
     BaseSSLError,
     BrokenPipeError,
     DummyConnection,
@@ -890,11 +891,15 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
 
         # Handle redirect?
         redirect_location = redirect and response.get_redirect_location()
         if redirect_location:
             if response.status == 303:
+                # Change the method according to RFC 9110, Section 15.4.4.
                 method = "GET"
+                # And lose the body not to transfer anything sensitive.
+                body = None
+                headers = HTTPHeaderDict(headers)._prepare_for_method_change()
 
             try:
                 retries = retries.increment(method, url, response=response, _pool=self)
             except MaxRetryError:
                 if retries.raise_on_redirect:
diff --git a/src/urllib3/poolmanager.py b/src/urllib3/poolmanager.py
index 7a998ee89..8b8fac9e0 100644
--- a/src/urllib3/poolmanager.py
+++ b/src/urllib3/poolmanager.py
@@ -5,11 +5,11 @@ import logging
 import typing
 import warnings
 from types import TracebackType
 from urllib.parse import urljoin
 
-from ._collections import RecentlyUsedContainer
+from ._collections import HTTPHeaderDict, RecentlyUsedContainer
 from ._request_methods import RequestMethods
 from .connection import ProxyConfig
 from .connectionpool import HTTPConnectionPool, HTTPSConnectionPool, port_by_scheme
 from .exceptions import (
     LocationValueError,
@@ -446,13 +446,16 @@ class PoolManager(RequestMethods):
             return response
 
         # Support relative URLs for redirecting.
         redirect_location = urljoin(url, redirect_location)
 
-        # RFC 7231, Section 6.4.4
         if response.status == 303:
+            # Change the method according to RFC 9110, Section 15.4.4.
             method = "GET"
+            # And lose the body not to transfer anything sensitive.
+            kw["body"] = None
+            kw["headers"] = HTTPHeaderDict(kw["headers"])._prepare_for_method_change()
 
         retries = kw.get("retries")
         if not isinstance(retries, Retry):
             retries = Retry.from_int(retries, redirect=redirect)
 
diff --git a/test/with_dummyserver/test_connectionpool.py b/test/with_dummyserver/test_connectionpool.py
index fdfb2c9ab..ebfaf3878 100644
--- a/test/with_dummyserver/test_connectionpool.py
+++ b/test/with_dummyserver/test_connectionpool.py
@@ -478,10 +478,21 @@ class TestConnectionPool(HTTPDummyServerTestCase):
 
             r = pool.request("GET", "/redirect", fields={"target": "/"})
             assert r.status == 200
             assert r.data == b"Dummy server!"
 
+    def test_303_redirect_makes_request_lose_body(self) -> None:
+        with HTTPConnectionPool(self.host, self.port) as pool:
+            response = pool.request(
+                "POST",
+                "/redirect",
+                fields={"target": "/headers_and_params", "status": "303 See Other"},
+            )
+        data = response.json()
+        assert data["params"] == {}
+        assert "Content-Type" not in HTTPHeaderDict(data["headers"])
+
     def test_bad_connect(self) -> None:
         with HTTPConnectionPool("badhost.invalid", self.port) as pool:
             with pytest.raises(MaxRetryError) as e:
                 pool.request("GET", "/", retries=5)
             assert type(e.value.reason) == NameResolutionError
diff --git a/test/with_dummyserver/test_poolmanager.py b/test/with_dummyserver/test_poolmanager.py
index da802a38b..ab0111e45 100644
--- a/test/with_dummyserver/test_poolmanager.py
+++ b/test/with_dummyserver/test_poolmanager.py
@@ -242,10 +242,24 @@ class TestPoolManager(HTTPDummyServerTestCase):
             assert r._pool is not None
             assert r._pool.num_requests == 2
             assert r._pool.num_connections == 1
             assert len(http.pools) == 1
 
+    def test_303_redirect_makes_request_lose_body(self) -> None:
+        with PoolManager() as http:
+            response = http.request(
+                "POST",
+                f"{self.base_url}/redirect",
+                fields={
+                    "target": f"{self.base_url}/headers_and_params",
+                    "status": "303 See Other",
+                },
+            )
+        data = response.json()
+        assert data["params"] == {}
+        assert "Content-Type" not in HTTPHeaderDict(data["headers"])
+
     def test_unknown_scheme(self) -> None:
         with PoolManager() as http:
             unknown_scheme = "unknown"
             unknown_scheme_url = f"{unknown_scheme}://host"
             with pytest.raises(URLSchemeUnknown) as e:

Vulnerable code:     python: "3"
__version__ = "2.0.6"
from ._collections import RecentlyUsedContainer
        # RFC 7231, Section 6.4.4
Fixed code:     python: "3.11"
2.0.7 (2023-10-17)
==================

* Made body stripped from HTTP requests changing the request method to GET after HTTP 303 "See Other" redirect responses.

1.26.18 (2023-10-17)
====================

* Made body stripped from HTTP requests changing the request method to GET after HTTP 303 "See Other" redirect responses.

    def headers_and_params(self, request: httputil.HTTPServerRequest) -> Response:
        params = request_params(request)
        return Response(
            json.dumps({"headers": dict(request.headers), "params": params})
        )

    from typing_extensions import Self

    def _prepare_for_method_change(self) -> Self:
        """
        Remove content-specific header fields before changing the request
        method to GET or HEAD according to RFC 9110, Section 15.4.
        """
        content_specific_headers = [
            "Content-Encoding",
            "Content-Language",
            "Content-Location",
            "Content-Type",
            "Content-Length",
            "Digest",
            "Last-Modified",
        ]
        for header in content_specific_headers:
            self.discard(header)
        return self

__version__ = "2.0.7"
from ._collections import HTTPHeaderDict
                # Change the method according to RFC 9110, Section 15.4.4.
                # And lose the body not to transfer anything sensitive.
                body = None
                headers = HTTPHeaderDict(headers)._prepare_for_method_change()
from ._collections import HTTPHeaderDict, RecentlyUsedContainer
            # Change the method according to RFC 9110, Section 15.4.4.
            # And lose the body not to transfer anything sensitive.
            kw["body"] = None
            kw["headers"] = HTTPHeaderDict(kw["headers"])._prepare_for_method_change()
    def test_303_redirect_makes_request_lose_body(self) -> None:
        with HTTPConnectionPool(self.host, self.port) as pool:
            response = pool.request(
                "POST",
                "/redirect",
                fields={"target": "/headers_and_params", "status": "303 See Other"},
            )
        data = response.json()
        assert data["params"] == {}
        assert "Content-Type" not in HTTPHeaderDict(data["headers"])

    def test_303_redirect_makes_request_lose_body(self) -> None:
        with PoolManager() as http:
            response = http.request(
                "POST",
                f"{self.base_url}/redirect",
                fields={
                    "target": f"{self.base_url}/headers_and_params",
                    "status": "303 See Other",
                },
            )
        data = response.json()
        assert data["params"] == {}
        assert "Content-Type" not in HTTPHeaderDict(data["headers"])