Skip to content

Commit 75a875e

Browse files
ambvgpshead
andauthored
[3.11] gh-108310: Fix CVE-2023-40217: Check for & avoid the ssl pre-close flaw (#108317)
gh-108310: Fix CVE-2023-40217: Check for & avoid the ssl pre-close flaw Instances of `ssl.SSLSocket` were vulnerable to a bypass of the TLS handshake and included protections (like certificate verification) and treating sent unencrypted data as if it were post-handshake TLS encrypted data. The vulnerability is caused when a socket is connected, data is sent by the malicious peer and stored in a buffer, and then the malicious peer closes the socket within a small timing window before the other peers’ TLS handshake can begin. After this sequence of events the closed socket will not immediately attempt a TLS handshake due to not being connected but will also allow the buffered data to be read as if a successful TLS handshake had occurred. Co-authored-by: Gregory P. Smith [Google LLC] <greg@krypto.org>
1 parent 5be32d8 commit 75a875e

File tree

3 files changed

+248
-1
lines changed

3 files changed

+248
-1
lines changed

Lib/ssl.py

+30-1
Original file line numberDiff line numberDiff line change
@@ -1037,7 +1037,7 @@ def _create(cls, sock, server_side=False, do_handshake_on_connect=True,
10371037
)
10381038
self = cls.__new__(cls, **kwargs)
10391039
super(SSLSocket, self).__init__(**kwargs)
1040-
self.settimeout(sock.gettimeout())
1040+
sock_timeout = sock.gettimeout()
10411041
sock.detach()
10421042

10431043
self._context = context
@@ -1056,9 +1056,38 @@ def _create(cls, sock, server_side=False, do_handshake_on_connect=True,
10561056
if e.errno != errno.ENOTCONN:
10571057
raise
10581058
connected = False
1059+
blocking = self.getblocking()
1060+
self.setblocking(False)
1061+
try:
1062+
# We are not connected so this is not supposed to block, but
1063+
# testing revealed otherwise on macOS and Windows so we do
1064+
# the non-blocking dance regardless. Our raise when any data
1065+
# is found means consuming the data is harmless.
1066+
notconn_pre_handshake_data = self.recv(1)
1067+
except OSError as e:
1068+
# EINVAL occurs for recv(1) on non-connected on unix sockets.
1069+
if e.errno not in (errno.ENOTCONN, errno.EINVAL):
1070+
raise
1071+
notconn_pre_handshake_data = b''
1072+
self.setblocking(blocking)
1073+
if notconn_pre_handshake_data:
1074+
# This prevents pending data sent to the socket before it was
1075+
# closed from escaping to the caller who could otherwise
1076+
# presume it came through a successful TLS connection.
1077+
reason = "Closed before TLS handshake with data in recv buffer."
1078+
notconn_pre_handshake_data_error = SSLError(e.errno, reason)
1079+
# Add the SSLError attributes that _ssl.c always adds.
1080+
notconn_pre_handshake_data_error.reason = reason
1081+
notconn_pre_handshake_data_error.library = None
1082+
try:
1083+
self.close()
1084+
except OSError:
1085+
pass
1086+
raise notconn_pre_handshake_data_error
10591087
else:
10601088
connected = True
10611089

1090+
self.settimeout(sock_timeout) # Must come after setblocking() calls.
10621091
self._connected = connected
10631092
if connected:
10641093
# create the SSL object

Lib/test/test_ssl.py

+211
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,14 @@
99
from test.support import socket_helper
1010
from test.support import threading_helper
1111
from test.support import warnings_helper
12+
import re
1213
import socket
1314
import select
15+
import struct
1416
import time
1517
import enum
1618
import gc
19+
import http.client
1720
import os
1821
import errno
1922
import pprint
@@ -4896,6 +4899,214 @@ def sni_cb(sock, servername, ctx):
48964899
s.connect((HOST, server.port))
48974900

48984901

4902+
def set_socket_so_linger_on_with_zero_timeout(sock):
4903+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))
4904+
4905+
4906+
class TestPreHandshakeClose(unittest.TestCase):
4907+
"""Verify behavior of close sockets with received data before to the handshake.
4908+
"""
4909+
4910+
class SingleConnectionTestServerThread(threading.Thread):
4911+
4912+
def __init__(self, *, name, call_after_accept):
4913+
self.call_after_accept = call_after_accept
4914+
self.received_data = b'' # set by .run()
4915+
self.wrap_error = None # set by .run()
4916+
self.listener = None # set by .start()
4917+
self.port = None # set by .start()
4918+
super().__init__(name=name)
4919+
4920+
def __enter__(self):
4921+
self.start()
4922+
return self
4923+
4924+
def __exit__(self, *args):
4925+
try:
4926+
if self.listener:
4927+
self.listener.close()
4928+
except OSError:
4929+
pass
4930+
self.join()
4931+
self.wrap_error = None # avoid dangling references
4932+
4933+
def start(self):
4934+
self.ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
4935+
self.ssl_ctx.verify_mode = ssl.CERT_REQUIRED
4936+
self.ssl_ctx.load_verify_locations(cafile=ONLYCERT)
4937+
self.ssl_ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY)
4938+
self.listener = socket.socket()
4939+
self.port = socket_helper.bind_port(self.listener)
4940+
self.listener.settimeout(2.0)
4941+
self.listener.listen(1)
4942+
super().start()
4943+
4944+
def run(self):
4945+
conn, address = self.listener.accept()
4946+
self.listener.close()
4947+
with conn:
4948+
if self.call_after_accept(conn):
4949+
return
4950+
try:
4951+
tls_socket = self.ssl_ctx.wrap_socket(conn, server_side=True)
4952+
except OSError as err: # ssl.SSLError inherits from OSError
4953+
self.wrap_error = err
4954+
else:
4955+
try:
4956+
self.received_data = tls_socket.recv(400)
4957+
except OSError:
4958+
pass # closed, protocol error, etc.
4959+
4960+
def non_linux_skip_if_other_okay_error(self, err):
4961+
if sys.platform == "linux":
4962+
return # Expect the full test setup to always work on Linux.
4963+
if (isinstance(err, ConnectionResetError) or
4964+
(isinstance(err, OSError) and err.errno == errno.EINVAL) or
4965+
re.search('wrong.version.number', getattr(err, "reason", ""), re.I)):
4966+
# On Windows the TCP RST leads to a ConnectionResetError
4967+
# (ECONNRESET) which Linux doesn't appear to surface to userspace.
4968+
# If wrap_socket() winds up on the "if connected:" path and doing
4969+
# the actual wrapping... we get an SSLError from OpenSSL. Typically
4970+
# WRONG_VERSION_NUMBER. While appropriate, neither is the scenario
4971+
# we're specifically trying to test. The way this test is written
4972+
# is known to work on Linux. We'll skip it anywhere else that it
4973+
# does not present as doing so.
4974+
self.skipTest(f"Could not recreate conditions on {sys.platform}:"
4975+
f" {err=}")
4976+
# If maintaining this conditional winds up being a problem.
4977+
# just turn this into an unconditional skip anything but Linux.
4978+
# The important thing is that our CI has the logic covered.
4979+
4980+
def test_preauth_data_to_tls_server(self):
4981+
server_accept_called = threading.Event()
4982+
ready_for_server_wrap_socket = threading.Event()
4983+
4984+
def call_after_accept(unused):
4985+
server_accept_called.set()
4986+
if not ready_for_server_wrap_socket.wait(2.0):
4987+
raise RuntimeError("wrap_socket event never set, test may fail.")
4988+
return False # Tell the server thread to continue.
4989+
4990+
server = self.SingleConnectionTestServerThread(
4991+
call_after_accept=call_after_accept,
4992+
name="preauth_data_to_tls_server")
4993+
self.enterContext(server) # starts it & unittest.TestCase stops it.
4994+
4995+
with socket.socket() as client:
4996+
client.connect(server.listener.getsockname())
4997+
# This forces an immediate connection close via RST on .close().
4998+
set_socket_so_linger_on_with_zero_timeout(client)
4999+
client.setblocking(False)
5000+
5001+
server_accept_called.wait()
5002+
client.send(b"DELETE /data HTTP/1.0\r\n\r\n")
5003+
client.close() # RST
5004+
5005+
ready_for_server_wrap_socket.set()
5006+
server.join()
5007+
wrap_error = server.wrap_error
5008+
self.assertEqual(b"", server.received_data)
5009+
self.assertIsInstance(wrap_error, OSError) # All platforms.
5010+
self.non_linux_skip_if_other_okay_error(wrap_error)
5011+
self.assertIsInstance(wrap_error, ssl.SSLError)
5012+
self.assertIn("before TLS handshake with data", wrap_error.args[1])
5013+
self.assertIn("before TLS handshake with data", wrap_error.reason)
5014+
self.assertNotEqual(0, wrap_error.args[0])
5015+
self.assertIsNone(wrap_error.library, msg="attr must exist")
5016+
5017+
def test_preauth_data_to_tls_client(self):
5018+
client_can_continue_with_wrap_socket = threading.Event()
5019+
5020+
def call_after_accept(conn_to_client):
5021+
# This forces an immediate connection close via RST on .close().
5022+
set_socket_so_linger_on_with_zero_timeout(conn_to_client)
5023+
conn_to_client.send(
5024+
b"HTTP/1.0 307 Temporary Redirect\r\n"
5025+
b"Location: https://example.com/someone-elses-server\r\n"
5026+
b"\r\n")
5027+
conn_to_client.close() # RST
5028+
client_can_continue_with_wrap_socket.set()
5029+
return True # Tell the server to stop.
5030+
5031+
server = self.SingleConnectionTestServerThread(
5032+
call_after_accept=call_after_accept,
5033+
name="preauth_data_to_tls_client")
5034+
self.enterContext(server) # starts it & unittest.TestCase stops it.
5035+
# Redundant; call_after_accept sets SO_LINGER on the accepted conn.
5036+
set_socket_so_linger_on_with_zero_timeout(server.listener)
5037+
5038+
with socket.socket() as client:
5039+
client.connect(server.listener.getsockname())
5040+
if not client_can_continue_with_wrap_socket.wait(2.0):
5041+
self.fail("test server took too long.")
5042+
ssl_ctx = ssl.create_default_context()
5043+
try:
5044+
tls_client = ssl_ctx.wrap_socket(
5045+
client, server_hostname="localhost")
5046+
except OSError as err: # SSLError inherits from OSError
5047+
wrap_error = err
5048+
received_data = b""
5049+
else:
5050+
wrap_error = None
5051+
received_data = tls_client.recv(400)
5052+
tls_client.close()
5053+
5054+
server.join()
5055+
self.assertEqual(b"", received_data)
5056+
self.assertIsInstance(wrap_error, OSError) # All platforms.
5057+
self.non_linux_skip_if_other_okay_error(wrap_error)
5058+
self.assertIsInstance(wrap_error, ssl.SSLError)
5059+
self.assertIn("before TLS handshake with data", wrap_error.args[1])
5060+
self.assertIn("before TLS handshake with data", wrap_error.reason)
5061+
self.assertNotEqual(0, wrap_error.args[0])
5062+
self.assertIsNone(wrap_error.library, msg="attr must exist")
5063+
5064+
def test_https_client_non_tls_response_ignored(self):
5065+
5066+
server_responding = threading.Event()
5067+
5068+
class SynchronizedHTTPSConnection(http.client.HTTPSConnection):
5069+
def connect(self):
5070+
http.client.HTTPConnection.connect(self)
5071+
# Wait for our fault injection server to have done its thing.
5072+
if not server_responding.wait(1.0) and support.verbose:
5073+
sys.stdout.write("server_responding event never set.")
5074+
self.sock = self._context.wrap_socket(
5075+
self.sock, server_hostname=self.host)
5076+
5077+
def call_after_accept(conn_to_client):
5078+
# This forces an immediate connection close via RST on .close().
5079+
set_socket_so_linger_on_with_zero_timeout(conn_to_client)
5080+
conn_to_client.send(
5081+
b"HTTP/1.0 402 Payment Required\r\n"
5082+
b"\r\n")
5083+
conn_to_client.close() # RST
5084+
server_responding.set()
5085+
return True # Tell the server to stop.
5086+
5087+
server = self.SingleConnectionTestServerThread(
5088+
call_after_accept=call_after_accept,
5089+
name="non_tls_http_RST_responder")
5090+
self.enterContext(server) # starts it & unittest.TestCase stops it.
5091+
# Redundant; call_after_accept sets SO_LINGER on the accepted conn.
5092+
set_socket_so_linger_on_with_zero_timeout(server.listener)
5093+
5094+
connection = SynchronizedHTTPSConnection(
5095+
f"localhost",
5096+
port=server.port,
5097+
context=ssl.create_default_context(),
5098+
timeout=2.0,
5099+
)
5100+
# There are lots of reasons this raises as desired, long before this
5101+
# test was added. Sending the request requires a successful TLS wrapped
5102+
# socket; that fails if the connection is broken. It may seem pointless
5103+
# to test this. It serves as an illustration of something that we never
5104+
# want to happen... properly not happening.
5105+
with self.assertRaises(OSError) as err_ctx:
5106+
connection.request("HEAD", "/test", headers={"Host": "localhost"})
5107+
response = connection.getresponse()
5108+
5109+
48995110
class TestEnumerations(unittest.TestCase):
49005111

49015112
def test_tlsversion(self):
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Fixed an issue where instances of :class:`ssl.SSLSocket` were vulnerable to
2+
a bypass of the TLS handshake and included protections (like certificate
3+
verification) and treating sent unencrypted data as if it were
4+
post-handshake TLS encrypted data. Security issue reported as
5+
`CVE-2023-40217
6+
<https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-40217>`_ by
7+
Aapo Oksman. Patch by Gregory P. Smith.

0 commit comments

Comments
 (0)