Skip to content

Commit 0ea3662

Browse files
gh-113280: Always close socket if SSLSocket creation failed (GH-114659)
Co-authored-by: Thomas Grainger <[email protected]>
1 parent ecabff9 commit 0ea3662

File tree

3 files changed

+78
-64
lines changed

3 files changed

+78
-64
lines changed

Lib/ssl.py

Lines changed: 53 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -994,71 +994,67 @@ def _create(cls, sock, server_side=False, do_handshake_on_connect=True,
994994
if context.check_hostname and not server_hostname:
995995
raise ValueError("check_hostname requires server_hostname")
996996

997+
sock_timeout = sock.gettimeout()
997998
kwargs = dict(
998999
family=sock.family, type=sock.type, proto=sock.proto,
9991000
fileno=sock.fileno()
10001001
)
10011002
self = cls.__new__(cls, **kwargs)
10021003
super(SSLSocket, self).__init__(**kwargs)
1003-
sock_timeout = sock.gettimeout()
10041004
sock.detach()
1005-
1006-
self._context = context
1007-
self._session = session
1008-
self._closed = False
1009-
self._sslobj = None
1010-
self.server_side = server_side
1011-
self.server_hostname = context._encode_hostname(server_hostname)
1012-
self.do_handshake_on_connect = do_handshake_on_connect
1013-
self.suppress_ragged_eofs = suppress_ragged_eofs
1014-
1015-
# See if we are connected
1005+
# Now SSLSocket is responsible for closing the file descriptor.
10161006
try:
1017-
self.getpeername()
1018-
except OSError as e:
1019-
if e.errno != errno.ENOTCONN:
1020-
raise
1021-
connected = False
1022-
blocking = self.getblocking()
1023-
self.setblocking(False)
1007+
self._context = context
1008+
self._session = session
1009+
self._closed = False
1010+
self._sslobj = None
1011+
self.server_side = server_side
1012+
self.server_hostname = context._encode_hostname(server_hostname)
1013+
self.do_handshake_on_connect = do_handshake_on_connect
1014+
self.suppress_ragged_eofs = suppress_ragged_eofs
1015+
1016+
# See if we are connected
10241017
try:
1025-
# We are not connected so this is not supposed to block, but
1026-
# testing revealed otherwise on macOS and Windows so we do
1027-
# the non-blocking dance regardless. Our raise when any data
1028-
# is found means consuming the data is harmless.
1029-
notconn_pre_handshake_data = self.recv(1)
1018+
self.getpeername()
10301019
except OSError as e:
1031-
# EINVAL occurs for recv(1) on non-connected on unix sockets.
1032-
if e.errno not in (errno.ENOTCONN, errno.EINVAL):
1020+
if e.errno != errno.ENOTCONN:
10331021
raise
1034-
notconn_pre_handshake_data = b''
1035-
self.setblocking(blocking)
1036-
if notconn_pre_handshake_data:
1037-
# This prevents pending data sent to the socket before it was
1038-
# closed from escaping to the caller who could otherwise
1039-
# presume it came through a successful TLS connection.
1040-
reason = "Closed before TLS handshake with data in recv buffer."
1041-
notconn_pre_handshake_data_error = SSLError(e.errno, reason)
1042-
# Add the SSLError attributes that _ssl.c always adds.
1043-
notconn_pre_handshake_data_error.reason = reason
1044-
notconn_pre_handshake_data_error.library = None
1045-
try:
1046-
self.close()
1047-
except OSError:
1048-
pass
1022+
connected = False
1023+
blocking = self.getblocking()
1024+
self.setblocking(False)
10491025
try:
1050-
raise notconn_pre_handshake_data_error
1051-
finally:
1052-
# Explicitly break the reference cycle.
1053-
notconn_pre_handshake_data_error = None
1054-
else:
1055-
connected = True
1026+
# We are not connected so this is not supposed to block, but
1027+
# testing revealed otherwise on macOS and Windows so we do
1028+
# the non-blocking dance regardless. Our raise when any data
1029+
# is found means consuming the data is harmless.
1030+
notconn_pre_handshake_data = self.recv(1)
1031+
except OSError as e:
1032+
# EINVAL occurs for recv(1) on non-connected on unix sockets.
1033+
if e.errno not in (errno.ENOTCONN, errno.EINVAL):
1034+
raise
1035+
notconn_pre_handshake_data = b''
1036+
self.setblocking(blocking)
1037+
if notconn_pre_handshake_data:
1038+
# This prevents pending data sent to the socket before it was
1039+
# closed from escaping to the caller who could otherwise
1040+
# presume it came through a successful TLS connection.
1041+
reason = "Closed before TLS handshake with data in recv buffer."
1042+
notconn_pre_handshake_data_error = SSLError(e.errno, reason)
1043+
# Add the SSLError attributes that _ssl.c always adds.
1044+
notconn_pre_handshake_data_error.reason = reason
1045+
notconn_pre_handshake_data_error.library = None
1046+
try:
1047+
raise notconn_pre_handshake_data_error
1048+
finally:
1049+
# Explicitly break the reference cycle.
1050+
notconn_pre_handshake_data_error = None
1051+
else:
1052+
connected = True
10561053

1057-
self.settimeout(sock_timeout) # Must come after setblocking() calls.
1058-
self._connected = connected
1059-
if connected:
1060-
# create the SSL object
1061-
try:
1054+
self.settimeout(sock_timeout) # Must come after setblocking() calls.
1055+
self._connected = connected
1056+
if connected:
1057+
# create the SSL object
10621058
self._sslobj = self._context._wrap_socket(
10631059
self, server_side, self.server_hostname,
10641060
owner=self, session=self._session,
@@ -1069,9 +1065,12 @@ def _create(cls, sock, server_side=False, do_handshake_on_connect=True,
10691065
# non-blocking
10701066
raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
10711067
self.do_handshake()
1072-
except (OSError, ValueError):
1068+
except:
1069+
try:
10731070
self.close()
1074-
raise
1071+
except OSError:
1072+
pass
1073+
raise
10751074
return self
10761075

10771076
@property

Lib/test/test_ssl.py

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2206,14 +2206,15 @@ def _test_get_server_certificate(test, host, port, cert=None):
22062206
sys.stdout.write("\nVerified certificate for %s:%s is\n%s\n" % (host, port ,pem))
22072207

22082208
def _test_get_server_certificate_fail(test, host, port):
2209-
try:
2210-
pem = ssl.get_server_certificate((host, port), ca_certs=CERTFILE)
2211-
except ssl.SSLError as x:
2212-
#should fail
2213-
if support.verbose:
2214-
sys.stdout.write("%s\n" % x)
2215-
else:
2216-
test.fail("Got server certificate %s for %s:%s!" % (pem, host, port))
2209+
with warnings_helper.check_no_resource_warning(test):
2210+
try:
2211+
pem = ssl.get_server_certificate((host, port), ca_certs=CERTFILE)
2212+
except ssl.SSLError as x:
2213+
#should fail
2214+
if support.verbose:
2215+
sys.stdout.write("%s\n" % x)
2216+
else:
2217+
test.fail("Got server certificate %s for %s:%s!" % (pem, host, port))
22172218

22182219

22192220
from test.ssl_servers import make_https_server
@@ -3026,6 +3027,16 @@ def test_check_hostname_idn(self):
30263027
server_hostname="python.example.org") as s:
30273028
with self.assertRaises(ssl.CertificateError):
30283029
s.connect((HOST, server.port))
3030+
with ThreadedEchoServer(context=server_context, chatty=True) as server:
3031+
with warnings_helper.check_no_resource_warning(self):
3032+
with self.assertRaises(UnicodeError):
3033+
context.wrap_socket(socket.socket(),
3034+
server_hostname='.pythontest.net')
3035+
with ThreadedEchoServer(context=server_context, chatty=True) as server:
3036+
with warnings_helper.check_no_resource_warning(self):
3037+
with self.assertRaises(UnicodeDecodeError):
3038+
context.wrap_socket(socket.socket(),
3039+
server_hostname=b'k\xf6nig.idn.pythontest.net')
30293040

30303041
def test_wrong_cert_tls12(self):
30313042
"""Connecting when the server rejects the client's certificate
@@ -4983,7 +4994,8 @@ def call_after_accept(conn_to_client):
49834994
self.assertIsNone(wrap_error.library, msg="attr must exist")
49844995
finally:
49854996
# gh-108342: Explicitly break the reference cycle
4986-
wrap_error = None
4997+
with warnings_helper.check_no_resource_warning(self):
4998+
wrap_error = None
49874999
server = None
49885000

49895001
def test_https_client_non_tls_response_ignored(self):
@@ -5032,7 +5044,8 @@ def call_after_accept(conn_to_client):
50325044
# socket; that fails if the connection is broken. It may seem pointless
50335045
# to test this. It serves as an illustration of something that we never
50345046
# want to happen... properly not happening.
5035-
with self.assertRaises(OSError):
5047+
with warnings_helper.check_no_resource_warning(self), \
5048+
self.assertRaises(OSError):
50365049
connection.request("HEAD", "/test", headers={"Host": "localhost"})
50375050
response = connection.getresponse()
50385051

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a leak of open socket in rare cases when error occurred in
2+
:class:`ssl.SSLSocket` creation.

0 commit comments

Comments
 (0)