Skip to content

Commit 0cb0c23

Browse files
ambvgpshead
andauthored
gh-108310: Fix CVE-2023-40217: Check for & avoid the ssl pre-close flaw (#108315)
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] <[email protected]>
1 parent d2879f2 commit 0cb0c23

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
@@ -975,7 +975,7 @@ def _create(cls, sock, server_side=False, do_handshake_on_connect=True,
975975
)
976976
self = cls.__new__(cls, **kwargs)
977977
super(SSLSocket, self).__init__(**kwargs)
978-
self.settimeout(sock.gettimeout())
978+
sock_timeout = sock.gettimeout()
979979
sock.detach()
980980

981981
self._context = context
@@ -994,9 +994,38 @@ def _create(cls, sock, server_side=False, do_handshake_on_connect=True,
994994
if e.errno != errno.ENOTCONN:
995995
raise
996996
connected = False
997+
blocking = self.getblocking()
998+
self.setblocking(False)
999+
try:
1000+
# We are not connected so this is not supposed to block, but
1001+
# testing revealed otherwise on macOS and Windows so we do
1002+
# the non-blocking dance regardless. Our raise when any data
1003+
# is found means consuming the data is harmless.
1004+
notconn_pre_handshake_data = self.recv(1)
1005+
except OSError as e:
1006+
# EINVAL occurs for recv(1) on non-connected on unix sockets.
1007+
if e.errno not in (errno.ENOTCONN, errno.EINVAL):
1008+
raise
1009+
notconn_pre_handshake_data = b''
1010+
self.setblocking(blocking)
1011+
if notconn_pre_handshake_data:
1012+
# This prevents pending data sent to the socket before it was
1013+
# closed from escaping to the caller who could otherwise
1014+
# presume it came through a successful TLS connection.
1015+
reason = "Closed before TLS handshake with data in recv buffer."
1016+
notconn_pre_handshake_data_error = SSLError(e.errno, reason)
1017+
# Add the SSLError attributes that _ssl.c always adds.
1018+
notconn_pre_handshake_data_error.reason = reason
1019+
notconn_pre_handshake_data_error.library = None
1020+
try:
1021+
self.close()
1022+
except OSError:
1023+
pass
1024+
raise notconn_pre_handshake_data_error
9971025
else:
9981026
connected = True
9991027

1028+
self.settimeout(sock_timeout) # Must come after setblocking() calls.
10001029
self._connected = connected
10011030
if connected:
10021031
# create the SSL object

Lib/test/test_ssl.py

+211
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,14 @@
1010
from test.support import threading_helper
1111
from test.support import warnings_helper
1212
from test.support import asyncore
13+
import re
1314
import socket
1415
import select
16+
import struct
1517
import time
1618
import enum
1719
import gc
20+
import http.client
1821
import os
1922
import errno
2023
import pprint
@@ -4659,6 +4662,214 @@ def sni_cb(sock, servername, ctx):
46594662
s.connect((HOST, server.port))
46604663

46614664

4665+
def set_socket_so_linger_on_with_zero_timeout(sock):
4666+
sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 0))
4667+
4668+
4669+
class TestPreHandshakeClose(unittest.TestCase):
4670+
"""Verify behavior of close sockets with received data before to the handshake.
4671+
"""
4672+
4673+
class SingleConnectionTestServerThread(threading.Thread):
4674+
4675+
def __init__(self, *, name, call_after_accept):
4676+
self.call_after_accept = call_after_accept
4677+
self.received_data = b'' # set by .run()
4678+
self.wrap_error = None # set by .run()
4679+
self.listener = None # set by .start()
4680+
self.port = None # set by .start()
4681+
super().__init__(name=name)
4682+
4683+
def __enter__(self):
4684+
self.start()
4685+
return self
4686+
4687+
def __exit__(self, *args):
4688+
try:
4689+
if self.listener:
4690+
self.listener.close()
4691+
except OSError:
4692+
pass
4693+
self.join()
4694+
self.wrap_error = None # avoid dangling references
4695+
4696+
def start(self):
4697+
self.ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
4698+
self.ssl_ctx.verify_mode = ssl.CERT_REQUIRED
4699+
self.ssl_ctx.load_verify_locations(cafile=ONLYCERT)
4700+
self.ssl_ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY)
4701+
self.listener = socket.socket()
4702+
self.port = socket_helper.bind_port(self.listener)
4703+
self.listener.settimeout(2.0)
4704+
self.listener.listen(1)
4705+
super().start()
4706+
4707+
def run(self):
4708+
conn, address = self.listener.accept()
4709+
self.listener.close()
4710+
with conn:
4711+
if self.call_after_accept(conn):
4712+
return
4713+
try:
4714+
tls_socket = self.ssl_ctx.wrap_socket(conn, server_side=True)
4715+
except OSError as err: # ssl.SSLError inherits from OSError
4716+
self.wrap_error = err
4717+
else:
4718+
try:
4719+
self.received_data = tls_socket.recv(400)
4720+
except OSError:
4721+
pass # closed, protocol error, etc.
4722+
4723+
def non_linux_skip_if_other_okay_error(self, err):
4724+
if sys.platform == "linux":
4725+
return # Expect the full test setup to always work on Linux.
4726+
if (isinstance(err, ConnectionResetError) or
4727+
(isinstance(err, OSError) and err.errno == errno.EINVAL) or
4728+
re.search('wrong.version.number', getattr(err, "reason", ""), re.I)):
4729+
# On Windows the TCP RST leads to a ConnectionResetError
4730+
# (ECONNRESET) which Linux doesn't appear to surface to userspace.
4731+
# If wrap_socket() winds up on the "if connected:" path and doing
4732+
# the actual wrapping... we get an SSLError from OpenSSL. Typically
4733+
# WRONG_VERSION_NUMBER. While appropriate, neither is the scenario
4734+
# we're specifically trying to test. The way this test is written
4735+
# is known to work on Linux. We'll skip it anywhere else that it
4736+
# does not present as doing so.
4737+
self.skipTest(f"Could not recreate conditions on {sys.platform}:"
4738+
f" {err=}")
4739+
# If maintaining this conditional winds up being a problem.
4740+
# just turn this into an unconditional skip anything but Linux.
4741+
# The important thing is that our CI has the logic covered.
4742+
4743+
def test_preauth_data_to_tls_server(self):
4744+
server_accept_called = threading.Event()
4745+
ready_for_server_wrap_socket = threading.Event()
4746+
4747+
def call_after_accept(unused):
4748+
server_accept_called.set()
4749+
if not ready_for_server_wrap_socket.wait(2.0):
4750+
raise RuntimeError("wrap_socket event never set, test may fail.")
4751+
return False # Tell the server thread to continue.
4752+
4753+
server = self.SingleConnectionTestServerThread(
4754+
call_after_accept=call_after_accept,
4755+
name="preauth_data_to_tls_server")
4756+
self.enterContext(server) # starts it & unittest.TestCase stops it.
4757+
4758+
with socket.socket() as client:
4759+
client.connect(server.listener.getsockname())
4760+
# This forces an immediate connection close via RST on .close().
4761+
set_socket_so_linger_on_with_zero_timeout(client)
4762+
client.setblocking(False)
4763+
4764+
server_accept_called.wait()
4765+
client.send(b"DELETE /data HTTP/1.0\r\n\r\n")
4766+
client.close() # RST
4767+
4768+
ready_for_server_wrap_socket.set()
4769+
server.join()
4770+
wrap_error = server.wrap_error
4771+
self.assertEqual(b"", server.received_data)
4772+
self.assertIsInstance(wrap_error, OSError) # All platforms.
4773+
self.non_linux_skip_if_other_okay_error(wrap_error)
4774+
self.assertIsInstance(wrap_error, ssl.SSLError)
4775+
self.assertIn("before TLS handshake with data", wrap_error.args[1])
4776+
self.assertIn("before TLS handshake with data", wrap_error.reason)
4777+
self.assertNotEqual(0, wrap_error.args[0])
4778+
self.assertIsNone(wrap_error.library, msg="attr must exist")
4779+
4780+
def test_preauth_data_to_tls_client(self):
4781+
client_can_continue_with_wrap_socket = threading.Event()
4782+
4783+
def call_after_accept(conn_to_client):
4784+
# This forces an immediate connection close via RST on .close().
4785+
set_socket_so_linger_on_with_zero_timeout(conn_to_client)
4786+
conn_to_client.send(
4787+
b"HTTP/1.0 307 Temporary Redirect\r\n"
4788+
b"Location: https://example.com/someone-elses-server\r\n"
4789+
b"\r\n")
4790+
conn_to_client.close() # RST
4791+
client_can_continue_with_wrap_socket.set()
4792+
return True # Tell the server to stop.
4793+
4794+
server = self.SingleConnectionTestServerThread(
4795+
call_after_accept=call_after_accept,
4796+
name="preauth_data_to_tls_client")
4797+
self.enterContext(server) # starts it & unittest.TestCase stops it.
4798+
# Redundant; call_after_accept sets SO_LINGER on the accepted conn.
4799+
set_socket_so_linger_on_with_zero_timeout(server.listener)
4800+
4801+
with socket.socket() as client:
4802+
client.connect(server.listener.getsockname())
4803+
if not client_can_continue_with_wrap_socket.wait(2.0):
4804+
self.fail("test server took too long.")
4805+
ssl_ctx = ssl.create_default_context()
4806+
try:
4807+
tls_client = ssl_ctx.wrap_socket(
4808+
client, server_hostname="localhost")
4809+
except OSError as err: # SSLError inherits from OSError
4810+
wrap_error = err
4811+
received_data = b""
4812+
else:
4813+
wrap_error = None
4814+
received_data = tls_client.recv(400)
4815+
tls_client.close()
4816+
4817+
server.join()
4818+
self.assertEqual(b"", received_data)
4819+
self.assertIsInstance(wrap_error, OSError) # All platforms.
4820+
self.non_linux_skip_if_other_okay_error(wrap_error)
4821+
self.assertIsInstance(wrap_error, ssl.SSLError)
4822+
self.assertIn("before TLS handshake with data", wrap_error.args[1])
4823+
self.assertIn("before TLS handshake with data", wrap_error.reason)
4824+
self.assertNotEqual(0, wrap_error.args[0])
4825+
self.assertIsNone(wrap_error.library, msg="attr must exist")
4826+
4827+
def test_https_client_non_tls_response_ignored(self):
4828+
4829+
server_responding = threading.Event()
4830+
4831+
class SynchronizedHTTPSConnection(http.client.HTTPSConnection):
4832+
def connect(self):
4833+
http.client.HTTPConnection.connect(self)
4834+
# Wait for our fault injection server to have done its thing.
4835+
if not server_responding.wait(1.0) and support.verbose:
4836+
sys.stdout.write("server_responding event never set.")
4837+
self.sock = self._context.wrap_socket(
4838+
self.sock, server_hostname=self.host)
4839+
4840+
def call_after_accept(conn_to_client):
4841+
# This forces an immediate connection close via RST on .close().
4842+
set_socket_so_linger_on_with_zero_timeout(conn_to_client)
4843+
conn_to_client.send(
4844+
b"HTTP/1.0 402 Payment Required\r\n"
4845+
b"\r\n")
4846+
conn_to_client.close() # RST
4847+
server_responding.set()
4848+
return True # Tell the server to stop.
4849+
4850+
server = self.SingleConnectionTestServerThread(
4851+
call_after_accept=call_after_accept,
4852+
name="non_tls_http_RST_responder")
4853+
self.enterContext(server) # starts it & unittest.TestCase stops it.
4854+
# Redundant; call_after_accept sets SO_LINGER on the accepted conn.
4855+
set_socket_so_linger_on_with_zero_timeout(server.listener)
4856+
4857+
connection = SynchronizedHTTPSConnection(
4858+
f"localhost",
4859+
port=server.port,
4860+
context=ssl.create_default_context(),
4861+
timeout=2.0,
4862+
)
4863+
# There are lots of reasons this raises as desired, long before this
4864+
# test was added. Sending the request requires a successful TLS wrapped
4865+
# socket; that fails if the connection is broken. It may seem pointless
4866+
# to test this. It serves as an illustration of something that we never
4867+
# want to happen... properly not happening.
4868+
with self.assertRaises(OSError) as err_ctx:
4869+
connection.request("HEAD", "/test", headers={"Host": "localhost"})
4870+
response = connection.getresponse()
4871+
4872+
46624873
class TestEnumerations(unittest.TestCase):
46634874

46644875
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)