Blame SOURCES/00404-cve-2023-40217.patch

a9c2e6
From 2c7d187c6ef01e803a2dbd3a3e434be05e4f5dd3 Mon Sep 17 00:00:00 2001
a9c2e6
From: =?UTF-8?q?=C5=81ukasz=20Langa?= <lukasz@langa.pl>
a9c2e6
Date: Tue, 22 Aug 2023 19:57:01 +0200
a9c2e6
Subject: [PATCH 1/5] gh-108310: Fix CVE-2023-40217: Check for & avoid the ssl
a9c2e6
 pre-close flaw (#108321)
a9c2e6
MIME-Version: 1.0
a9c2e6
Content-Type: text/plain; charset=UTF-8
a9c2e6
Content-Transfer-Encoding: 8bit
a9c2e6
a9c2e6
gh-108310: Fix CVE-2023-40217: Check for & avoid the ssl pre-close flaw
a9c2e6
a9c2e6
Instances of `ssl.SSLSocket` were vulnerable to a bypass of the TLS handshake
a9c2e6
and included protections (like certificate verification) and treating sent
a9c2e6
unencrypted data as if it were post-handshake TLS encrypted data.
a9c2e6
a9c2e6
The vulnerability is caused when a socket is connected, data is sent by the
a9c2e6
malicious peer and stored in a buffer, and then the malicious peer closes the
a9c2e6
socket within a small timing window before the other peers’ TLS handshake can
a9c2e6
begin. After this sequence of events the closed socket will not immediately
a9c2e6
attempt a TLS handshake due to not being connected but will also allow the
a9c2e6
buffered data to be read as if a successful TLS handshake had occurred.
a9c2e6
a9c2e6
Co-authored-by: Gregory P. Smith [Google LLC] <greg@krypto.org>
a9c2e6
---
a9c2e6
 Lib/ssl.py                                    |  31 ++-
a9c2e6
 Lib/test/test_ssl.py                          | 214 ++++++++++++++++++
a9c2e6
 ...-08-22-17-39-12.gh-issue-108310.fVM3sg.rst |   7 +
a9c2e6
 3 files changed, 251 insertions(+), 1 deletion(-)
a9c2e6
 create mode 100644 Misc/NEWS.d/next/Security/2023-08-22-17-39-12.gh-issue-108310.fVM3sg.rst
a9c2e6
a9c2e6
diff --git a/Lib/ssl.py b/Lib/ssl.py
a9c2e6
index c5c5529..288f237 100644
a9c2e6
--- a/Lib/ssl.py
a9c2e6
+++ b/Lib/ssl.py
a9c2e6
@@ -741,7 +741,7 @@ class SSLSocket(socket):
a9c2e6
                             type=sock.type,
a9c2e6
                             proto=sock.proto,
a9c2e6
                             fileno=sock.fileno())
a9c2e6
-            self.settimeout(sock.gettimeout())
a9c2e6
+            sock_timeout = sock.gettimeout()
a9c2e6
             sock.detach()
a9c2e6
         elif fileno is not None:
a9c2e6
             socket.__init__(self, fileno=fileno)
a9c2e6
@@ -755,9 +755,38 @@ class SSLSocket(socket):
a9c2e6
             if e.errno != errno.ENOTCONN:
a9c2e6
                 raise
a9c2e6
             connected = False
a9c2e6
+            blocking = self.getblocking()
a9c2e6
+            self.setblocking(False)
a9c2e6
+            try:
a9c2e6
+                # We are not connected so this is not supposed to block, but
a9c2e6
+                # testing revealed otherwise on macOS and Windows so we do
a9c2e6
+                # the non-blocking dance regardless. Our raise when any data
a9c2e6
+                # is found means consuming the data is harmless.
a9c2e6
+                notconn_pre_handshake_data = self.recv(1)
a9c2e6
+            except OSError as e:
a9c2e6
+                # EINVAL occurs for recv(1) on non-connected on unix sockets.
a9c2e6
+                if e.errno not in (errno.ENOTCONN, errno.EINVAL):
a9c2e6
+                    raise
a9c2e6
+                notconn_pre_handshake_data = b''
a9c2e6
+            self.setblocking(blocking)
a9c2e6
+            if notconn_pre_handshake_data:
a9c2e6
+                # This prevents pending data sent to the socket before it was
a9c2e6
+                # closed from escaping to the caller who could otherwise
a9c2e6
+                # presume it came through a successful TLS connection.
a9c2e6
+                reason = "Closed before TLS handshake with data in recv buffer."
a9c2e6
+                notconn_pre_handshake_data_error = SSLError(e.errno, reason)
a9c2e6
+                # Add the SSLError attributes that _ssl.c always adds.
a9c2e6
+                notconn_pre_handshake_data_error.reason = reason
a9c2e6
+                notconn_pre_handshake_data_error.library = None
a9c2e6
+                try:
a9c2e6
+                    self.close()
a9c2e6
+                except OSError:
a9c2e6
+                    pass
a9c2e6
+                raise notconn_pre_handshake_data_error
a9c2e6
         else:
a9c2e6
             connected = True
a9c2e6
 
a9c2e6
+        self.settimeout(sock_timeout)  # Must come after setblocking() calls.
a9c2e6
         self._closed = False
a9c2e6
         self._sslobj = None
a9c2e6
         self._connected = connected
a9c2e6
diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py
a9c2e6
index 7889e95..76e07d2 100644
a9c2e6
--- a/Lib/test/test_ssl.py
a9c2e6
+++ b/Lib/test/test_ssl.py
a9c2e6
@@ -3,11 +3,14 @@
a9c2e6
 import sys
a9c2e6
 import unittest
a9c2e6
 from test import support
a9c2e6
+import re
a9c2e6
 import socket
a9c2e6
 import select
a9c2e6
+import struct
a9c2e6
 import time
a9c2e6
 import datetime
a9c2e6
 import gc
a9c2e6
+import http.client
a9c2e6
 import os
a9c2e6
 import errno
a9c2e6
 import pprint
a9c2e6
@@ -3909,6 +3912,217 @@ class TestPostHandshakeAuth(unittest.TestCase):
a9c2e6
                 s.write(b'PHA')
a9c2e6
                 self.assertIn(b'WRONG_SSL_VERSION', s.recv(1024))
a9c2e6
 
a9c2e6
+def set_socket_so_linger_on_with_zero_timeout(sock):
a9c2e6
+    sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))
a9c2e6
+
a9c2e6
+
a9c2e6
+class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
+    """Verify behavior of close sockets with received data before to the handshake.
a9c2e6
+    """
a9c2e6
+
a9c2e6
+    class SingleConnectionTestServerThread(threading.Thread):
a9c2e6
+
a9c2e6
+        def __init__(self, *, name, call_after_accept):
a9c2e6
+            self.call_after_accept = call_after_accept
a9c2e6
+            self.received_data = b''  # set by .run()
a9c2e6
+            self.wrap_error = None  # set by .run()
a9c2e6
+            self.listener = None  # set by .start()
a9c2e6
+            self.port = None  # set by .start()
a9c2e6
+            super().__init__(name=name)
a9c2e6
+
a9c2e6
+        def __enter__(self):
a9c2e6
+            self.start()
a9c2e6
+            return self
a9c2e6
+
a9c2e6
+        def __exit__(self, *args):
a9c2e6
+            try:
a9c2e6
+                if self.listener:
a9c2e6
+                    self.listener.close()
a9c2e6
+            except OSError:
a9c2e6
+                pass
a9c2e6
+            self.join()
a9c2e6
+            self.wrap_error = None  # avoid dangling references
a9c2e6
+
a9c2e6
+        def start(self):
a9c2e6
+            self.ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
a9c2e6
+            self.ssl_ctx.verify_mode = ssl.CERT_REQUIRED
a9c2e6
+            self.ssl_ctx.load_verify_locations(cafile=ONLYCERT)
a9c2e6
+            self.ssl_ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY)
a9c2e6
+            self.listener = socket.socket()
a9c2e6
+            self.port = support.bind_port(self.listener)
a9c2e6
+            self.listener.settimeout(2.0)
a9c2e6
+            self.listener.listen(1)
a9c2e6
+            super().start()
a9c2e6
+
a9c2e6
+        def run(self):
a9c2e6
+            conn, address = self.listener.accept()
a9c2e6
+            self.listener.close()
a9c2e6
+            with conn:
a9c2e6
+                if self.call_after_accept(conn):
a9c2e6
+                    return
a9c2e6
+                try:
a9c2e6
+                    tls_socket = self.ssl_ctx.wrap_socket(conn, server_side=True)
a9c2e6
+                except OSError as err:  # ssl.SSLError inherits from OSError
a9c2e6
+                    self.wrap_error = err
a9c2e6
+                else:
a9c2e6
+                    try:
a9c2e6
+                        self.received_data = tls_socket.recv(400)
a9c2e6
+                    except OSError:
a9c2e6
+                        pass  # closed, protocol error, etc.
a9c2e6
+
a9c2e6
+    def non_linux_skip_if_other_okay_error(self, err):
a9c2e6
+        if sys.platform == "linux":
a9c2e6
+            return  # Expect the full test setup to always work on Linux.
a9c2e6
+        if (isinstance(err, ConnectionResetError) or
a9c2e6
+            (isinstance(err, OSError) and err.errno == errno.EINVAL) or
a9c2e6
+            re.search('wrong.version.number', getattr(err, "reason", ""), re.I)):
a9c2e6
+            # On Windows the TCP RST leads to a ConnectionResetError
a9c2e6
+            # (ECONNRESET) which Linux doesn't appear to surface to userspace.
a9c2e6
+            # If wrap_socket() winds up on the "if connected:" path and doing
a9c2e6
+            # the actual wrapping... we get an SSLError from OpenSSL. Typically
a9c2e6
+            # WRONG_VERSION_NUMBER. While appropriate, neither is the scenario
a9c2e6
+            # we're specifically trying to test. The way this test is written
a9c2e6
+            # is known to work on Linux. We'll skip it anywhere else that it
a9c2e6
+            # does not present as doing so.
a9c2e6
+            self.skipTest("Could not recreate conditions on {}: \
a9c2e6
+                          err={}".format(sys.platform,err))
a9c2e6
+        # If maintaining this conditional winds up being a problem.
a9c2e6
+        # just turn this into an unconditional skip anything but Linux.
a9c2e6
+        # The important thing is that our CI has the logic covered.
a9c2e6
+
a9c2e6
+    def test_preauth_data_to_tls_server(self):
a9c2e6
+        server_accept_called = threading.Event()
a9c2e6
+        ready_for_server_wrap_socket = threading.Event()
a9c2e6
+
a9c2e6
+        def call_after_accept(unused):
a9c2e6
+            server_accept_called.set()
a9c2e6
+            if not ready_for_server_wrap_socket.wait(2.0):
a9c2e6
+                raise RuntimeError("wrap_socket event never set, test may fail.")
a9c2e6
+            return False  # Tell the server thread to continue.
a9c2e6
+
a9c2e6
+        server = self.SingleConnectionTestServerThread(
a9c2e6
+                call_after_accept=call_after_accept,
a9c2e6
+                name="preauth_data_to_tls_server")
a9c2e6
+        server.__enter__()  # starts it
a9c2e6
+        self.addCleanup(server.__exit__)  # ... & unittest.TestCase stops it.
a9c2e6
+
a9c2e6
+        with socket.socket() as client:
a9c2e6
+            client.connect(server.listener.getsockname())
a9c2e6
+            # This forces an immediate connection close via RST on .close().
a9c2e6
+            set_socket_so_linger_on_with_zero_timeout(client)
a9c2e6
+            client.setblocking(False)
a9c2e6
+
a9c2e6
+            server_accept_called.wait()
a9c2e6
+            client.send(b"DELETE /data HTTP/1.0\r\n\r\n")
a9c2e6
+            client.close()  # RST
a9c2e6
+
a9c2e6
+        ready_for_server_wrap_socket.set()
a9c2e6
+        server.join()
a9c2e6
+        wrap_error = server.wrap_error
a9c2e6
+        self.assertEqual(b"", server.received_data)
a9c2e6
+        self.assertIsInstance(wrap_error, OSError)  # All platforms.
a9c2e6
+        self.non_linux_skip_if_other_okay_error(wrap_error)
a9c2e6
+        self.assertIsInstance(wrap_error, ssl.SSLError)
a9c2e6
+        self.assertIn("before TLS handshake with data", wrap_error.args[1])
a9c2e6
+        self.assertIn("before TLS handshake with data", wrap_error.reason)
a9c2e6
+        self.assertNotEqual(0, wrap_error.args[0])
a9c2e6
+        self.assertIsNone(wrap_error.library, msg="attr must exist")
a9c2e6
+
a9c2e6
+    def test_preauth_data_to_tls_client(self):
a9c2e6
+        client_can_continue_with_wrap_socket = threading.Event()
a9c2e6
+
a9c2e6
+        def call_after_accept(conn_to_client):
a9c2e6
+            # This forces an immediate connection close via RST on .close().
a9c2e6
+            set_socket_so_linger_on_with_zero_timeout(conn_to_client)
a9c2e6
+            conn_to_client.send(
a9c2e6
+                    b"HTTP/1.0 307 Temporary Redirect\r\n"
a9c2e6
+                    b"Location: https://example.com/someone-elses-server\r\n"
a9c2e6
+                    b"\r\n")
a9c2e6
+            conn_to_client.close()  # RST
a9c2e6
+            client_can_continue_with_wrap_socket.set()
a9c2e6
+            return True  # Tell the server to stop.
a9c2e6
+
a9c2e6
+        server = self.SingleConnectionTestServerThread(
a9c2e6
+                call_after_accept=call_after_accept,
a9c2e6
+                name="preauth_data_to_tls_client")
a9c2e6
+        server.__enter__()  # starts it
a9c2e6
+        self.addCleanup(server.__exit__)  # ... & unittest.TestCase stops it.
a9c2e6
+
a9c2e6
+        # Redundant; call_after_accept sets SO_LINGER on the accepted conn.
a9c2e6
+        set_socket_so_linger_on_with_zero_timeout(server.listener)
a9c2e6
+
a9c2e6
+        with socket.socket() as client:
a9c2e6
+            client.connect(server.listener.getsockname())
a9c2e6
+            if not client_can_continue_with_wrap_socket.wait(2.0):
a9c2e6
+                self.fail("test server took too long.")
a9c2e6
+            ssl_ctx = ssl.create_default_context()
a9c2e6
+            try:
a9c2e6
+                tls_client = ssl_ctx.wrap_socket(
a9c2e6
+                        client, server_hostname="localhost")
a9c2e6
+            except OSError as err:  # SSLError inherits from OSError
a9c2e6
+                wrap_error = err
a9c2e6
+                received_data = b""
a9c2e6
+            else:
a9c2e6
+                wrap_error = None
a9c2e6
+                received_data = tls_client.recv(400)
a9c2e6
+                tls_client.close()
a9c2e6
+
a9c2e6
+        server.join()
a9c2e6
+        self.assertEqual(b"", received_data)
a9c2e6
+        self.assertIsInstance(wrap_error, OSError)  # All platforms.
a9c2e6
+        self.non_linux_skip_if_other_okay_error(wrap_error)
a9c2e6
+        self.assertIsInstance(wrap_error, ssl.SSLError)
a9c2e6
+        self.assertIn("before TLS handshake with data", wrap_error.args[1])
a9c2e6
+        self.assertIn("before TLS handshake with data", wrap_error.reason)
a9c2e6
+        self.assertNotEqual(0, wrap_error.args[0])
a9c2e6
+        self.assertIsNone(wrap_error.library, msg="attr must exist")
a9c2e6
+
a9c2e6
+    def test_https_client_non_tls_response_ignored(self):
a9c2e6
+
a9c2e6
+        server_responding = threading.Event()
a9c2e6
+
a9c2e6
+        class SynchronizedHTTPSConnection(http.client.HTTPSConnection):
a9c2e6
+            def connect(self):
a9c2e6
+                http.client.HTTPConnection.connect(self)
a9c2e6
+                # Wait for our fault injection server to have done its thing.
a9c2e6
+                if not server_responding.wait(1.0) and support.verbose:
a9c2e6
+                    sys.stdout.write("server_responding event never set.")
a9c2e6
+                self.sock = self._context.wrap_socket(
a9c2e6
+                        self.sock, server_hostname=self.host)
a9c2e6
+
a9c2e6
+        def call_after_accept(conn_to_client):
a9c2e6
+            # This forces an immediate connection close via RST on .close().
a9c2e6
+            set_socket_so_linger_on_with_zero_timeout(conn_to_client)
a9c2e6
+            conn_to_client.send(
a9c2e6
+                    b"HTTP/1.0 402 Payment Required\r\n"
a9c2e6
+                    b"\r\n")
a9c2e6
+            conn_to_client.close()  # RST
a9c2e6
+            server_responding.set()
a9c2e6
+            return True  # Tell the server to stop.
a9c2e6
+
a9c2e6
+        server = self.SingleConnectionTestServerThread(
a9c2e6
+                call_after_accept=call_after_accept,
a9c2e6
+                name="non_tls_http_RST_responder")
a9c2e6
+        server.__enter__()  # starts it
a9c2e6
+        self.addCleanup(server.__exit__)  # ... & unittest.TestCase stops it.
a9c2e6
+        # Redundant; call_after_accept sets SO_LINGER on the accepted conn.
a9c2e6
+        set_socket_so_linger_on_with_zero_timeout(server.listener)
a9c2e6
+
a9c2e6
+        connection = SynchronizedHTTPSConnection(
a9c2e6
+                f"localhost",
a9c2e6
+                port=server.port,
a9c2e6
+                context=ssl.create_default_context(),
a9c2e6
+                timeout=2.0,
a9c2e6
+        )
a9c2e6
+        # There are lots of reasons this raises as desired, long before this
a9c2e6
+        # test was added. Sending the request requires a successful TLS wrapped
a9c2e6
+        # socket; that fails if the connection is broken. It may seem pointless
a9c2e6
+        # to test this. It serves as an illustration of something that we never
a9c2e6
+        # want to happen... properly not happening.
a9c2e6
+        with self.assertRaises(OSError) as err_ctx:
a9c2e6
+            connection.request("HEAD", "/test", headers={"Host": "localhost"})
a9c2e6
+            response = connection.getresponse()
a9c2e6
+
a9c2e6
 
a9c2e6
 def test_main(verbose=False):
a9c2e6
     if support.verbose:
a9c2e6
diff --git a/Misc/NEWS.d/next/Security/2023-08-22-17-39-12.gh-issue-108310.fVM3sg.rst b/Misc/NEWS.d/next/Security/2023-08-22-17-39-12.gh-issue-108310.fVM3sg.rst
a9c2e6
new file mode 100644
a9c2e6
index 0000000..403c77a
a9c2e6
--- /dev/null
a9c2e6
+++ b/Misc/NEWS.d/next/Security/2023-08-22-17-39-12.gh-issue-108310.fVM3sg.rst
a9c2e6
@@ -0,0 +1,7 @@
a9c2e6
+Fixed an issue where instances of :class:`ssl.SSLSocket` were vulnerable to
a9c2e6
+a bypass of the TLS handshake and included protections (like certificate
a9c2e6
+verification) and treating sent unencrypted data as if it were
a9c2e6
+post-handshake TLS encrypted data.  Security issue reported as
a9c2e6
+`CVE-2023-40217
a9c2e6
+<https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-40217>`_ by
a9c2e6
+Aapo Oksman. Patch by Gregory P. Smith.
a9c2e6
-- 
a9c2e6
2.41.0
a9c2e6
a9c2e6
a9c2e6
From 32313804cb3abb0e6c2d9e1394282b4736dfd7b6 Mon Sep 17 00:00:00 2001
a9c2e6
From: "Miss Islington (bot)"
a9c2e6
 <31488909+miss-islington@users.noreply.github.com>
a9c2e6
Date: Wed, 23 Aug 2023 03:10:56 -0700
a9c2e6
Subject: [PATCH 2/5] gh-108342: Break ref cycle in SSLSocket._create() exc
a9c2e6
 (GH-108344) (#108352)
a9c2e6
a9c2e6
Explicitly break a reference cycle when SSLSocket._create() raises an
a9c2e6
exception. Clear the variable storing the exception, since the
a9c2e6
exception traceback contains the variables and so creates a reference
a9c2e6
cycle.
a9c2e6
a9c2e6
This test leak was introduced by the test added for the fix of GH-108310.
a9c2e6
(cherry picked from commit 64f99350351bc46e016b2286f36ba7cd669b79e3)
a9c2e6
a9c2e6
Co-authored-by: Victor Stinner <vstinner@python.org>
a9c2e6
---
a9c2e6
 Lib/ssl.py | 6 +++++-
a9c2e6
 1 file changed, 5 insertions(+), 1 deletion(-)
a9c2e6
a9c2e6
diff --git a/Lib/ssl.py b/Lib/ssl.py
a9c2e6
index 288f237..67869c9 100644
a9c2e6
--- a/Lib/ssl.py
a9c2e6
+++ b/Lib/ssl.py
a9c2e6
@@ -782,7 +782,11 @@ class SSLSocket(socket):
a9c2e6
                     self.close()
a9c2e6
                 except OSError:
a9c2e6
                     pass
a9c2e6
-                raise notconn_pre_handshake_data_error
a9c2e6
+                try:
a9c2e6
+                    raise notconn_pre_handshake_data_error
a9c2e6
+                finally:
a9c2e6
+                    # Explicitly break the reference cycle.
a9c2e6
+                    notconn_pre_handshake_data_error = None
a9c2e6
         else:
a9c2e6
             connected = True
a9c2e6
 
a9c2e6
-- 
a9c2e6
2.41.0
a9c2e6
a9c2e6
a9c2e6
From 3fb0a77e625614abad0ba1052c1bc60659c33845 Mon Sep 17 00:00:00 2001
a9c2e6
From: =?UTF-8?q?=C5=81ukasz=20Langa?= <lukasz@langa.pl>
a9c2e6
Date: Thu, 24 Aug 2023 12:09:30 +0200
a9c2e6
Subject: [PATCH 3/5] gh-108342: Make ssl TestPreHandshakeClose more reliable
a9c2e6
 (GH-108370) (#108408)
a9c2e6
a9c2e6
* In preauth tests of test_ssl, explicitly break reference cycles
a9c2e6
  invoving SingleConnectionTestServerThread to make sure that the
a9c2e6
  thread is deleted. Otherwise, the test marks the environment as
a9c2e6
  altered because the threading module sees a "dangling thread"
a9c2e6
  (SingleConnectionTestServerThread). This test leak was introduced
a9c2e6
  by the test added for the fix of issue gh-108310.
a9c2e6
* Use support.SHORT_TIMEOUT instead of hardcoded 1.0 or 2.0 seconds
a9c2e6
  timeout.
a9c2e6
* SingleConnectionTestServerThread.run() catchs TimeoutError
a9c2e6
* Fix a race condition (missing synchronization) in
a9c2e6
  test_preauth_data_to_tls_client(): the server now waits until the
a9c2e6
  client connect() completed in call_after_accept().
a9c2e6
* test_https_client_non_tls_response_ignored() calls server.join()
a9c2e6
  explicitly.
a9c2e6
* Replace "localhost" with server.listener.getsockname()[0].
a9c2e6
(cherry picked from commit 592bacb6fc0833336c0453e818e9b95016e9fd47)
a9c2e6
---
a9c2e6
 Lib/test/test_ssl.py | 102 ++++++++++++++++++++++++++++++-------------
a9c2e6
 1 file changed, 71 insertions(+), 31 deletions(-)
a9c2e6
a9c2e6
diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py
a9c2e6
index 76e07d2..2bb5230 100644
a9c2e6
--- a/Lib/test/test_ssl.py
a9c2e6
+++ b/Lib/test/test_ssl.py
a9c2e6
@@ -3922,12 +3922,16 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
 
a9c2e6
     class SingleConnectionTestServerThread(threading.Thread):
a9c2e6
 
a9c2e6
-        def __init__(self, *, name, call_after_accept):
a9c2e6
+        def __init__(self, *, name, call_after_accept, timeout=None):
a9c2e6
             self.call_after_accept = call_after_accept
a9c2e6
             self.received_data = b''  # set by .run()
a9c2e6
             self.wrap_error = None  # set by .run()
a9c2e6
             self.listener = None  # set by .start()
a9c2e6
             self.port = None  # set by .start()
a9c2e6
+            if timeout is None:
a9c2e6
+                self.timeout = support.SHORT_TIMEOUT
a9c2e6
+            else:
a9c2e6
+                self.timeout = timeout
a9c2e6
             super().__init__(name=name)
a9c2e6
 
a9c2e6
         def __enter__(self):
a9c2e6
@@ -3950,13 +3954,19 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
             self.ssl_ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY)
a9c2e6
             self.listener = socket.socket()
a9c2e6
             self.port = support.bind_port(self.listener)
a9c2e6
-            self.listener.settimeout(2.0)
a9c2e6
+            self.listener.settimeout(self.timeout)
a9c2e6
             self.listener.listen(1)
a9c2e6
             super().start()
a9c2e6
 
a9c2e6
         def run(self):
a9c2e6
-            conn, address = self.listener.accept()
a9c2e6
-            self.listener.close()
a9c2e6
+            try:
a9c2e6
+                conn, address = self.listener.accept()
a9c2e6
+            except TimeoutError:
a9c2e6
+                # on timeout, just close the listener
a9c2e6
+                return
a9c2e6
+            finally:
a9c2e6
+                self.listener.close()
a9c2e6
+
a9c2e6
             with conn:
a9c2e6
                 if self.call_after_accept(conn):
a9c2e6
                     return
a9c2e6
@@ -3984,8 +3994,13 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
             # we're specifically trying to test. The way this test is written
a9c2e6
             # is known to work on Linux. We'll skip it anywhere else that it
a9c2e6
             # does not present as doing so.
a9c2e6
-            self.skipTest("Could not recreate conditions on {}: \
a9c2e6
-                          err={}".format(sys.platform,err))
a9c2e6
+            try:
a9c2e6
+                self.skipTest("Could not recreate conditions on {}: \
a9c2e6
+                              err={}".format(sys.platform,err))
a9c2e6
+            finally:
a9c2e6
+                # gh-108342: Explicitly break the reference cycle
a9c2e6
+                err = None
a9c2e6
+
a9c2e6
         # If maintaining this conditional winds up being a problem.
a9c2e6
         # just turn this into an unconditional skip anything but Linux.
a9c2e6
         # The important thing is that our CI has the logic covered.
a9c2e6
@@ -3996,7 +4011,7 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
 
a9c2e6
         def call_after_accept(unused):
a9c2e6
             server_accept_called.set()
a9c2e6
-            if not ready_for_server_wrap_socket.wait(2.0):
a9c2e6
+            if not ready_for_server_wrap_socket.wait(support.SHORT_TIMEOUT):
a9c2e6
                 raise RuntimeError("wrap_socket event never set, test may fail.")
a9c2e6
             return False  # Tell the server thread to continue.
a9c2e6
 
a9c2e6
@@ -4018,20 +4033,31 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
 
a9c2e6
         ready_for_server_wrap_socket.set()
a9c2e6
         server.join()
a9c2e6
+
a9c2e6
         wrap_error = server.wrap_error
a9c2e6
-        self.assertEqual(b"", server.received_data)
a9c2e6
-        self.assertIsInstance(wrap_error, OSError)  # All platforms.
a9c2e6
-        self.non_linux_skip_if_other_okay_error(wrap_error)
a9c2e6
-        self.assertIsInstance(wrap_error, ssl.SSLError)
a9c2e6
-        self.assertIn("before TLS handshake with data", wrap_error.args[1])
a9c2e6
-        self.assertIn("before TLS handshake with data", wrap_error.reason)
a9c2e6
-        self.assertNotEqual(0, wrap_error.args[0])
a9c2e6
-        self.assertIsNone(wrap_error.library, msg="attr must exist")
a9c2e6
+        server.wrap_error = None
a9c2e6
+        try:
a9c2e6
+            self.assertEqual(b"", server.received_data)
a9c2e6
+            self.assertIsInstance(wrap_error, OSError)  # All platforms.
a9c2e6
+            self.non_linux_skip_if_other_okay_error(wrap_error)
a9c2e6
+            self.assertIsInstance(wrap_error, ssl.SSLError)
a9c2e6
+            self.assertIn("before TLS handshake with data", wrap_error.args[1])
a9c2e6
+            self.assertIn("before TLS handshake with data", wrap_error.reason)
a9c2e6
+            self.assertNotEqual(0, wrap_error.args[0])
a9c2e6
+            self.assertIsNone(wrap_error.library, msg="attr must exist")
a9c2e6
+        finally:
a9c2e6
+            # gh-108342: Explicitly break the reference cycle
a9c2e6
+            wrap_error = None
a9c2e6
+            server = None
a9c2e6
 
a9c2e6
     def test_preauth_data_to_tls_client(self):
a9c2e6
+        server_can_continue_with_wrap_socket = threading.Event()
a9c2e6
         client_can_continue_with_wrap_socket = threading.Event()
a9c2e6
 
a9c2e6
         def call_after_accept(conn_to_client):
a9c2e6
+            if not server_can_continue_with_wrap_socket.wait(support.SHORT_TIMEOUT):
a9c2e6
+                print("ERROR: test client took too long")
a9c2e6
+
a9c2e6
             # This forces an immediate connection close via RST on .close().
a9c2e6
             set_socket_so_linger_on_with_zero_timeout(conn_to_client)
a9c2e6
             conn_to_client.send(
a9c2e6
@@ -4053,8 +4079,10 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
 
a9c2e6
         with socket.socket() as client:
a9c2e6
             client.connect(server.listener.getsockname())
a9c2e6
-            if not client_can_continue_with_wrap_socket.wait(2.0):
a9c2e6
-                self.fail("test server took too long.")
a9c2e6
+            server_can_continue_with_wrap_socket.set()
a9c2e6
+
a9c2e6
+            if not client_can_continue_with_wrap_socket.wait(support.SHORT_TIMEOUT):
a9c2e6
+                self.fail("test server took too long")
a9c2e6
             ssl_ctx = ssl.create_default_context()
a9c2e6
             try:
a9c2e6
                 tls_client = ssl_ctx.wrap_socket(
a9c2e6
@@ -4068,24 +4096,31 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
                 tls_client.close()
a9c2e6
 
a9c2e6
         server.join()
a9c2e6
-        self.assertEqual(b"", received_data)
a9c2e6
-        self.assertIsInstance(wrap_error, OSError)  # All platforms.
a9c2e6
-        self.non_linux_skip_if_other_okay_error(wrap_error)
a9c2e6
-        self.assertIsInstance(wrap_error, ssl.SSLError)
a9c2e6
-        self.assertIn("before TLS handshake with data", wrap_error.args[1])
a9c2e6
-        self.assertIn("before TLS handshake with data", wrap_error.reason)
a9c2e6
-        self.assertNotEqual(0, wrap_error.args[0])
a9c2e6
-        self.assertIsNone(wrap_error.library, msg="attr must exist")
a9c2e6
+        try:
a9c2e6
+            self.assertEqual(b"", received_data)
a9c2e6
+            self.assertIsInstance(wrap_error, OSError)  # All platforms.
a9c2e6
+            self.non_linux_skip_if_other_okay_error(wrap_error)
a9c2e6
+            self.assertIsInstance(wrap_error, ssl.SSLError)
a9c2e6
+            self.assertIn("before TLS handshake with data", wrap_error.args[1])
a9c2e6
+            self.assertIn("before TLS handshake with data", wrap_error.reason)
a9c2e6
+            self.assertNotEqual(0, wrap_error.args[0])
a9c2e6
+            self.assertIsNone(wrap_error.library, msg="attr must exist")
a9c2e6
+        finally:
a9c2e6
+            # gh-108342: Explicitly break the reference cycle
a9c2e6
+            wrap_error = None
a9c2e6
+            server = None
a9c2e6
 
a9c2e6
     def test_https_client_non_tls_response_ignored(self):
a9c2e6
-
a9c2e6
         server_responding = threading.Event()
a9c2e6
 
a9c2e6
         class SynchronizedHTTPSConnection(http.client.HTTPSConnection):
a9c2e6
             def connect(self):
a9c2e6
+                # Call clear text HTTP connect(), not the encrypted HTTPS (TLS)
a9c2e6
+                # connect(): wrap_socket() is called manually below.
a9c2e6
                 http.client.HTTPConnection.connect(self)
a9c2e6
+
a9c2e6
                 # Wait for our fault injection server to have done its thing.
a9c2e6
-                if not server_responding.wait(1.0) and support.verbose:
a9c2e6
+                if not server_responding.wait(support.SHORT_TIMEOUT) and support.verbose:
a9c2e6
                     sys.stdout.write("server_responding event never set.")
a9c2e6
                 self.sock = self._context.wrap_socket(
a9c2e6
                         self.sock, server_hostname=self.host)
a9c2e6
@@ -4100,29 +4135,34 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
             server_responding.set()
a9c2e6
             return True  # Tell the server to stop.
a9c2e6
 
a9c2e6
+        timeout = 2.0
a9c2e6
         server = self.SingleConnectionTestServerThread(
a9c2e6
                 call_after_accept=call_after_accept,
a9c2e6
-                name="non_tls_http_RST_responder")
a9c2e6
+                name="non_tls_http_RST_responder",
a9c2e6
+                timeout=timeout)
a9c2e6
         server.__enter__()  # starts it
a9c2e6
         self.addCleanup(server.__exit__)  # ... & unittest.TestCase stops it.
a9c2e6
         # Redundant; call_after_accept sets SO_LINGER on the accepted conn.
a9c2e6
         set_socket_so_linger_on_with_zero_timeout(server.listener)
a9c2e6
 
a9c2e6
         connection = SynchronizedHTTPSConnection(
a9c2e6
-                f"localhost",
a9c2e6
+                server.listener.getsockname()[0],
a9c2e6
                 port=server.port,
a9c2e6
                 context=ssl.create_default_context(),
a9c2e6
-                timeout=2.0,
a9c2e6
+                timeout=timeout,
a9c2e6
         )
a9c2e6
+
a9c2e6
         # There are lots of reasons this raises as desired, long before this
a9c2e6
         # test was added. Sending the request requires a successful TLS wrapped
a9c2e6
         # socket; that fails if the connection is broken. It may seem pointless
a9c2e6
         # to test this. It serves as an illustration of something that we never
a9c2e6
         # want to happen... properly not happening.
a9c2e6
-        with self.assertRaises(OSError) as err_ctx:
a9c2e6
+        with self.assertRaises(OSError):
a9c2e6
             connection.request("HEAD", "/test", headers={"Host": "localhost"})
a9c2e6
             response = connection.getresponse()
a9c2e6
 
a9c2e6
+        server.join()
a9c2e6
+
a9c2e6
 
a9c2e6
 def test_main(verbose=False):
a9c2e6
     if support.verbose:
a9c2e6
-- 
a9c2e6
2.41.0
a9c2e6
a9c2e6
a9c2e6
From ec51d207851ce1566f8e64710c9410928a9e7417 Mon Sep 17 00:00:00 2001
a9c2e6
From: Charalampos Stratakis <cstratak@redhat.com>
a9c2e6
Date: Mon, 25 Sep 2023 21:55:29 +0200
a9c2e6
Subject: [PATCH 4/5] Downstream: Additional fixup for 3.6:
a9c2e6
a9c2e6
Use alternative for self.getblocking(), which was added in Python 3.7
a9c2e6
see: https://docs.python.org/3/library/socket.html#socket.socket.getblocking
a9c2e6
a9c2e6
Set self._sslobj early to avoid AttributeError
a9c2e6
---
a9c2e6
 Lib/ssl.py | 3 ++-
a9c2e6
 1 file changed, 2 insertions(+), 1 deletion(-)
a9c2e6
a9c2e6
diff --git a/Lib/ssl.py b/Lib/ssl.py
a9c2e6
index 67869c9..daedc82 100644
a9c2e6
--- a/Lib/ssl.py
a9c2e6
+++ b/Lib/ssl.py
a9c2e6
@@ -690,6 +690,7 @@ class SSLSocket(socket):
a9c2e6
                  suppress_ragged_eofs=True, npn_protocols=None, ciphers=None,
a9c2e6
                  server_hostname=None,
a9c2e6
                  _context=None, _session=None):
a9c2e6
+        self._sslobj = None
a9c2e6
 
a9c2e6
         if _context:
a9c2e6
             self._context = _context
a9c2e6
@@ -755,7 +756,7 @@ class SSLSocket(socket):
a9c2e6
             if e.errno != errno.ENOTCONN:
a9c2e6
                 raise
a9c2e6
             connected = False
a9c2e6
-            blocking = self.getblocking()
a9c2e6
+            blocking = (self.gettimeout() != 0)
a9c2e6
             self.setblocking(False)
a9c2e6
             try:
a9c2e6
                 # We are not connected so this is not supposed to block, but
a9c2e6
-- 
a9c2e6
2.41.0
a9c2e6
a9c2e6
a9c2e6
From df78050f8db4337483504b97a54dc74ff6861c40 Mon Sep 17 00:00:00 2001
a9c2e6
From: Lumir Balhar <lbalhar@redhat.com>
a9c2e6
Date: Wed, 11 Oct 2023 15:35:02 +0200
a9c2e6
Subject: [PATCH 5/5] gh-108310: Fix TestPreHandshakeClose tests in test_ssl
a9c2e6
a9c2e6
The new class is part of the fix for CVE-2023-40217:
a9c2e6
https://github.com/python/cpython/commit/b4bcc06a9cfe13d96d5270809d963f8ba278f89b
a9c2e6
but it's not in the lists of tests so they're not
a9c2e6
executed. The new tests also need `SHORT_TIMEOUT`
a9c2e6
constant not available in test.support in 3.8.
a9c2e6
---
a9c2e6
 Lib/test/test_ssl.py | 14 ++++++++------
a9c2e6
 1 file changed, 8 insertions(+), 6 deletions(-)
a9c2e6
a9c2e6
diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py
a9c2e6
index 2bb5230..84ac3b5 100644
a9c2e6
--- a/Lib/test/test_ssl.py
a9c2e6
+++ b/Lib/test/test_ssl.py
a9c2e6
@@ -108,6 +108,8 @@ OP_SINGLE_ECDH_USE = getattr(ssl, "OP_SINGLE_ECDH_USE", 0)
a9c2e6
 OP_CIPHER_SERVER_PREFERENCE = getattr(ssl, "OP_CIPHER_SERVER_PREFERENCE", 0)
a9c2e6
 OP_ENABLE_MIDDLEBOX_COMPAT = getattr(ssl, "OP_ENABLE_MIDDLEBOX_COMPAT", 0)
a9c2e6
 
a9c2e6
+# *_TIMEOUT constants are available in test.support in 3.9+
a9c2e6
+SHORT_TIMEOUT = 30.0
a9c2e6
 
a9c2e6
 def handle_error(prefix):
a9c2e6
     exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
a9c2e6
@@ -3929,7 +3931,7 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
             self.listener = None  # set by .start()
a9c2e6
             self.port = None  # set by .start()
a9c2e6
             if timeout is None:
a9c2e6
-                self.timeout = support.SHORT_TIMEOUT
a9c2e6
+                self.timeout = SHORT_TIMEOUT
a9c2e6
             else:
a9c2e6
                 self.timeout = timeout
a9c2e6
             super().__init__(name=name)
a9c2e6
@@ -4011,7 +4013,7 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
 
a9c2e6
         def call_after_accept(unused):
a9c2e6
             server_accept_called.set()
a9c2e6
-            if not ready_for_server_wrap_socket.wait(support.SHORT_TIMEOUT):
a9c2e6
+            if not ready_for_server_wrap_socket.wait(SHORT_TIMEOUT):
a9c2e6
                 raise RuntimeError("wrap_socket event never set, test may fail.")
a9c2e6
             return False  # Tell the server thread to continue.
a9c2e6
 
a9c2e6
@@ -4055,7 +4057,7 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
         client_can_continue_with_wrap_socket = threading.Event()
a9c2e6
 
a9c2e6
         def call_after_accept(conn_to_client):
a9c2e6
-            if not server_can_continue_with_wrap_socket.wait(support.SHORT_TIMEOUT):
a9c2e6
+            if not server_can_continue_with_wrap_socket.wait(SHORT_TIMEOUT):
a9c2e6
                 print("ERROR: test client took too long")
a9c2e6
 
a9c2e6
             # This forces an immediate connection close via RST on .close().
a9c2e6
@@ -4081,7 +4083,7 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
             client.connect(server.listener.getsockname())
a9c2e6
             server_can_continue_with_wrap_socket.set()
a9c2e6
 
a9c2e6
-            if not client_can_continue_with_wrap_socket.wait(support.SHORT_TIMEOUT):
a9c2e6
+            if not client_can_continue_with_wrap_socket.wait(SHORT_TIMEOUT):
a9c2e6
                 self.fail("test server took too long")
a9c2e6
             ssl_ctx = ssl.create_default_context()
a9c2e6
             try:
a9c2e6
@@ -4120,7 +4122,7 @@ class TestPreHandshakeClose(unittest.TestCase):
a9c2e6
                 http.client.HTTPConnection.connect(self)
a9c2e6
 
a9c2e6
                 # Wait for our fault injection server to have done its thing.
a9c2e6
-                if not server_responding.wait(support.SHORT_TIMEOUT) and support.verbose:
a9c2e6
+                if not server_responding.wait(SHORT_TIMEOUT) and support.verbose:
a9c2e6
                     sys.stdout.write("server_responding event never set.")
a9c2e6
                 self.sock = self._context.wrap_socket(
a9c2e6
                         self.sock, server_hostname=self.host)
a9c2e6
@@ -4206,7 +4208,7 @@ def test_main(verbose=False):
a9c2e6
 
a9c2e6
     tests = [
a9c2e6
         ContextTests, BasicSocketTests, SSLErrorTests, MemoryBIOTests,
a9c2e6
-        SimpleBackgroundTests,
a9c2e6
+        SimpleBackgroundTests, TestPreHandshakeClose
a9c2e6
     ]
a9c2e6
 
a9c2e6
     if support.is_resource_enabled('network'):
a9c2e6
-- 
a9c2e6
2.41.0
a9c2e6