CVE-2023-45803 (published 2023-10-17T20:15Z)

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.\n

CVSS v3 base score: 4.2, MEDIUM (CVSS:3.1/AV:A/AC:H/PR:H/UI:N/S:U/C:H/I:N/A:N)

Weakness information:
cwe_id: CWE-200
cwe_name: Exposure of Sensitive Information to an Unauthorized Actor
description: The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
extended_description: 
	   There are many different kinds of mistakes that introduce information exposures. The severity of the error can range widely, depending on the context in which the product operates, the type of sensitive information that is revealed, and the benefits it may provide to an attacker.  Some kinds of sensitive information include:
       
         private, personal information, such as personal messages, financial data, health records, geographic location, or contact details
         system status and environment, such as the operating system and installed packages
		 business secrets and intellectual property
		 network status and configuration
		 the product's own code or internal state
         metadata, e.g. logging of connections or message headers
		 indirect information, such as a discrepancy between two internal operations that can be observed by an outsider
       
	    Information might be sensitive to different parties, each of which may have their own expectations for whether the information should be protected.  These parties include:
               
                  the product's own users
                  people or organizations whose information is created or used by the product, even if they are not direct product users
		  the product's administrators, including the admins of the system(s) and/or networks on which the product operates
                  the developer
               
	    Information exposures can occur in different ways:
               
                  the code explicitly inserts sensitive information into resources or messages that are intentionally made accessible to unauthorized actors, but should not contain the information - i.e., the information should have been "scrubbed" or "sanitized"
                  a different weakness or mistake indirectly inserts the sensitive information into resources, such as a web script error revealing the full system path of the program.
                  the code manages resources that intentionally contain sensitive information, but the resources are unintentionally made accessible to unauthorized actors. In this case, the information exposure is resultant - i.e., a different weakness enabled the access to the information in the first place.
               
	    It is common practice to describe any loss of confidentiality as an "information exposure," but this can lead to overuse of CWE-200 in CWE mapping. From the CWE perspective, loss of confidentiality is a technical impact that can arise from dozens of different weaknesses, such as insecure file permissions or out-of-bounds read.  CWE-200 and its lower-level descendants are intended to cover the mistakes that occur in behaviors that explicitly manage, store, transfer, or cleanse sensitive information.
         
         

Fix information:
repo_url: https://github.com/urllib3/urllib3
commit_details: repo_url: https://github.com/urllib3/urllib3
author: Illia Volochii
author_date: 2023-10-17 21:07:33+03:00
msg: Bring 2.0.7 & 1.26.18 to main (#3161)

* Merge pull request from GHSA-g4mx-q9vg-27p4

* Release 2.0.7
repository: repo_url: https://github.com/urllib3/urllib3
repo_name: urllib3/urllib3
description: urllib3 is a user-friendly HTTP client library for Python
repo_language: Python
owner: urllib3
file_changes: filename: .readthedocs.yml
change_type: ModificationType.MODIFY
diff: @@ -3,7 +3,7 @@ version: 2
 build:
   os: ubuntu-22.04
   tools:
-    python: "3"
+    python: "3.11"
 
 python:
   install:

programming_language: CoffeeScript
filename: CHANGES.rst
change_type: ModificationType.MODIFY
diff: @@ -1,3 +1,8 @@
+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)
 ==================
 
@@ -167,6 +172,11 @@ Fixed
 * 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)
 ====================
 

programming_language: Markdown
filename: handlers.py
change_type: ModificationType.MODIFY
diff: @@ -281,6 +281,12 @@ class TestingApp(RequestHandler):
     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())}))
 

programming_language: Python
filename: _collections.py
change_type: ModificationType.MODIFY
diff: @@ -10,6 +10,8 @@ if typing.TYPE_CHECKING:
     # 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]:
             ...
@@ -391,6 +393,24 @@ class HTTPHeaderDict(typing.MutableMapping[str, str]):
             # 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

programming_language: Python
filename: _version.py
change_type: ModificationType.MODIFY
diff: @@ -1,4 +1,4 @@
 # This file is protected via CODEOWNERS
 from __future__ import annotations
 
-__version__ = "2.0.6"
+__version__ = "2.0.7"

programming_language: Python
filename: connectionpool.py
change_type: ModificationType.MODIFY
diff: @@ -11,6 +11,7 @@ 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,
@@ -892,7 +893,11 @@ class HTTPConnectionPool(ConnectionPool, RequestMethods):
         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)

programming_language: Python
filename: poolmanager.py
change_type: ModificationType.MODIFY
diff: @@ -7,7 +7,7 @@ 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
@@ -448,9 +448,12 @@ class PoolManager(RequestMethods):
         # 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):

programming_language: Python
filename: test_connectionpool.py
change_type: ModificationType.MODIFY
diff: @@ -480,6 +480,17 @@ class TestConnectionPool(HTTPDummyServerTestCase):
             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:

programming_language: Python
filename: test_poolmanager.py
change_type: ModificationType.MODIFY
diff: @@ -244,6 +244,20 @@ class TestPoolManager(HTTPDummyServerTestCase):
             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"

programming_language: Python