Skip to content

Commit 449cec5

Browse files
hugovksethmlarsonpicnixzYhg1s
committed
[3.10] gh-156793: Validate SSLContext.wrap_bio() parameters like wrap_socket() (GH-158503) (GH-158513)
* [3.12] gh-156793: Validate SSLContext.wrap_bio() parameters like wrap_socket() (GH-158503) (cherry picked from commit 1697ea3) * Raise a DeprecationWarning instead of ValueError (cherry picked from commit 869069d) Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> Co-authored-by: Seth Larson <seth@python.org> Co-authored-by: Bénédikt Tran <10796600+picnixz@users.noreply.github.com> Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com> Co-authored-by: T. Wouters <thomas@python.org>
1 parent 197663d commit 449cec5

7 files changed

Lines changed: 188 additions & 1 deletion

File tree

‎Doc/library/asyncio-eventloop.rst‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,11 @@ Opening network connections
505505

506506
For more information: https://tools.ietf.org/html/rfc6555
507507

508+
.. versionchanged:: next
509+
Raises a ``DeprecationWarning`` if ``ssl.check_hostname`` is ``True``
510+
and ``server_hostname`` is not supplied. In Python 3.13 and
511+
later a ``ValueError`` is raised instead.
512+
508513
.. seealso::
509514

510515
The :func:`open_connection` function is a high-level alternative

‎Doc/library/ssl.rst‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1890,7 +1890,11 @@ to speed up repeated connections from the same clients.
18901890
outgoing BIO.
18911891

18921892
The *server_side*, *server_hostname* and *session* parameters have the
1893-
same meaning as in :meth:`SSLContext.wrap_socket`.
1893+
same meaning as in :meth:`SSLContext.wrap_socket`, and are validated in
1894+
the same way: in particular a :exc:`DeprecationWarning` is raised when
1895+
:attr:`~SSLContext.check_hostname` is enabled but no *server_hostname* is
1896+
given, since there would be no name to match the peer's certificate
1897+
against. In Python 3.13 and later a ``ValueError`` is raised instead.
18941898

18951899
.. versionchanged:: 3.6
18961900
*session* argument was added.
@@ -1899,6 +1903,13 @@ to speed up repeated connections from the same clients.
18991903
The method returns on instance of :attr:`SSLContext.sslobject_class`
19001904
instead of hard-coded :class:`SSLObject`.
19011905

1906+
.. versionchanged:: next
1907+
The *server_side*, *server_hostname* and *session* parameters are now
1908+
validated as :meth:`SSLContext.wrap_socket` validates them. Previously
1909+
a context with :attr:`~SSLContext.check_hostname` enabled and no
1910+
*server_hostname* was accepted, and verified the certificate chain but
1911+
never the peer's identity.
1912+
19021913
.. attribute:: SSLContext.sslobject_class
19031914

19041915
The return type of :meth:`SSLContext.wrap_bio`, defaults to

‎Lib/ssl.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -862,6 +862,19 @@ def __init__(self, *args, **kwargs):
862862
@classmethod
863863
def _create(cls, incoming, outgoing, server_side=False,
864864
server_hostname=None, session=None, context=None):
865+
if server_side:
866+
if server_hostname:
867+
raise ValueError("server_hostname can only be specified "
868+
"in client mode")
869+
if session is not None:
870+
raise ValueError("session can only be specified in "
871+
"client mode")
872+
if context.check_hostname and server_hostname is None:
873+
# Note: server_hostname='' is handled within _wrap_bio().
874+
warnings.warn("check_hostname requires server_hostname",
875+
category=DeprecationWarning,
876+
stacklevel=3)
877+
865878
self = cls.__new__(cls)
866879
sslobj = context._wrap_bio(
867880
incoming, outgoing, server_side=server_side,

‎Lib/test/test_asyncio/test_sslproto.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,56 @@ def test_handshake_timeout_negative(self):
7171
sslproto.SSLProtocol(self.loop, app_proto, sslcontext, waiter,
7272
ssl_handshake_timeout=-10)
7373

74+
def test_check_hostname_accepts_server_hostname(self):
75+
# Supplying a server_hostname succeeds with check_hostname enabled.
76+
sslcontext = test_utils.simple_client_sslcontext(disable_verify=False)
77+
sslcontext.check_hostname = True
78+
app_proto = mock.Mock()
79+
waiter = mock.Mock()
80+
81+
# No ValueError is raised from SSLProtocol with 'server_hostname'.
82+
ssl_proto = sslproto.SSLProtocol(self.loop, app_proto, sslcontext, waiter,
83+
server_hostname='example.org')
84+
self.addCleanup(ssl_proto._app_transport.close)
85+
86+
def test_check_hostname_requires_server_hostname(self):
87+
# A caller-supplied context asking for hostname checking used to be
88+
# taken through wrap_bio() with no name to check against, verifying
89+
# the certificate chain but never the peer's identity.
90+
# loop.start_tls() defaults server_hostname to None, and
91+
# loop.create_connection() turns server_hostname='' into None here,
92+
# so both reached that state.
93+
sslcontext = test_utils.simple_client_sslcontext(disable_verify=False)
94+
sslcontext.check_hostname = True
95+
app_proto = mock.Mock()
96+
waiter = mock.Mock()
97+
server_hostname = None
98+
99+
# Supplying no server_hostname warns with check_hostname enabled.
100+
with self.assertWarnsRegex(
101+
DeprecationWarning,
102+
'check_hostname requires server_hostname'):
103+
sslproto.SSLProtocol(self.loop, app_proto, sslcontext,
104+
waiter)
105+
106+
with self.assertWarnsRegex(
107+
DeprecationWarning,
108+
'check_hostname requires server_hostname'):
109+
sslproto.SSLProtocol(self.loop, app_proto, sslcontext,
110+
waiter,
111+
server_hostname=server_hostname)
112+
113+
# Disabling check_hostname allows for an empty or unset server_hostname.
114+
sslcontext.check_hostname = False
115+
116+
ssl_proto = sslproto.SSLProtocol(self.loop, app_proto, sslcontext, waiter)
117+
self.addCleanup(ssl_proto._app_transport.close)
118+
119+
ssl_proto = sslproto.SSLProtocol(self.loop, app_proto, sslcontext,
120+
waiter,
121+
server_hostname=server_hostname)
122+
self.addCleanup(ssl_proto._app_transport.close)
123+
74124
def test_eof_received_waiter(self):
75125
waiter = self.loop.create_future()
76126
ssl_proto = self.ssl_protocol(waiter=waiter)

‎Lib/test/test_ssl.py‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from test.support import socket_helper
1010
from test.support import threading_helper
1111
from test.support import warnings_helper
12+
import contextlib
1213
import re
1314
import socket
1415
import select
@@ -328,6 +329,34 @@ def testing_context(server_cert=SIGNED_CERTFILE, *, server_chain=True):
328329
return client_context, server_context, hostname
329330

330331

332+
def connected_bio_pair(client_context, server_context, hostname, max_retry=5):
333+
"""Handshake a client and a server SSLObject against each other.
334+
335+
Everything happens in memory, so this needs no socket and no thread.
336+
Returns the two objects followed by their four BIOs, in the order
337+
client, server, c_in, c_out, s_in, s_out.
338+
"""
339+
c_in, c_out = ssl.MemoryBIO(), ssl.MemoryBIO()
340+
s_in, s_out = ssl.MemoryBIO(), ssl.MemoryBIO()
341+
client = client_context.wrap_bio(c_in, c_out, server_hostname=hostname)
342+
server = server_context.wrap_bio(s_in, s_out, server_side=True)
343+
344+
# Loop on the handshake for a bit to get it settled
345+
for _ in range(max_retry):
346+
with contextlib.suppress(ssl.SSLWantReadError):
347+
client.do_handshake()
348+
if c_out.pending:
349+
s_in.write(c_out.read())
350+
with contextlib.suppress(ssl.SSLWantReadError):
351+
server.do_handshake()
352+
if s_out.pending:
353+
c_in.write(s_out.read())
354+
# Now the handshakes should be complete (don't raise WantReadError)
355+
client.do_handshake()
356+
server.do_handshake()
357+
return client, server, c_in, c_out, s_in, s_out
358+
359+
331360
class BasicSocketTests(unittest.TestCase):
332361

333362
def test_constants(self):
@@ -1888,6 +1917,10 @@ def test_subclass(self):
18881917

18891918
def test_bad_server_hostname(self):
18901919
ctx = ssl.create_default_context()
1920+
# Omitting the name entirely is bad too: this context checks it.
1921+
with self.assertWarns(DeprecationWarning):
1922+
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
1923+
server_hostname=None)
18911924
with self.assertRaises(ValueError):
18921925
ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
18931926
server_hostname="")
@@ -1968,6 +2001,66 @@ def test_private_init(self):
19682001
with self.assertRaisesRegex(TypeError, "public constructor"):
19692002
ssl.SSLObject(bio, bio)
19702003

2004+
def test_check_hostname_requires_server_hostname(self):
2005+
# wrap_bio() used to accept a context asking for hostname checking
2006+
# without a name to check against, and then verify the certificate
2007+
# chain but never the peer's identity without a warning. Now
2008+
# a warning is emitted in this scenario.
2009+
client_context, _, hostname = testing_context()
2010+
self.assertTrue(client_context.check_hostname)
2011+
2012+
server_hostname = None
2013+
with self.assertWarnsRegex(
2014+
DeprecationWarning,
2015+
"check_hostname requires server_hostname"):
2016+
client_context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
2017+
server_hostname=server_hostname)
2018+
# The sibling constructor refuses the very same call, but with
2019+
# a ValueError instead of DeprecationWarning.
2020+
with socket.socket() as sock:
2021+
with self.assertRaisesRegex(
2022+
ValueError,
2023+
"check_hostname requires server_hostname"):
2024+
client_context.wrap_socket(
2025+
sock, server_hostname=server_hostname)
2026+
2027+
# A name was all that was missing.
2028+
with warnings_helper.check_no_warnings(self):
2029+
client_context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
2030+
server_hostname=hostname)
2031+
2032+
# Asking for no hostname check remains a way to say so explicitly.
2033+
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
2034+
context.check_hostname = False
2035+
self.assertFalse(context.check_hostname)
2036+
with warnings_helper.check_no_warnings(self):
2037+
context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO())
2038+
2039+
def test_server_side_bad_params(self):
2040+
# A server neither sends a hostname nor resumes a client's session,
2041+
# so wrap_bio() rejects both in server mode like wrap_socket()
2042+
client_context, server_context, hostname = testing_context()
2043+
2044+
with self.assertRaisesRegex(
2045+
ValueError,
2046+
"server_hostname can only be specified in client mode"):
2047+
server_context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
2048+
server_side=True,
2049+
server_hostname=hostname)
2050+
2051+
client, server, *_ = connected_bio_pair(
2052+
client_context, server_context, hostname)
2053+
session = client.session
2054+
self.assertIsNotNone(session)
2055+
with self.assertRaisesRegex(
2056+
ValueError, "session can only be specified in client mode"):
2057+
server_context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
2058+
server_side=True, session=session)
2059+
2060+
# Neither argument is what a server passes, so this still works.
2061+
server_context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(),
2062+
server_side=True)
2063+
19712064
def test_unwrap(self):
19722065
client_ctx, server_ctx, hostname = testing_context()
19732066
c_in = ssl.MemoryBIO()
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
:meth:`ssl.SSLContext.wrap_bio` now validates its *server_side*,
2+
*server_hostname* and *session* arguments similar to
3+
:meth:`ssl.SSLContext.wrap_socket`, but for backward compatiblity reasons
4+
emits :exc:`DeprecationWarning` instead of :exc:`ValueError`.
5+
6+
In particular, a context with :attr:`~ssl.SSLContext.check_hostname` enabled
7+
and no *server_hostname* passed to :meth:`!wrap_bio` now emits
8+
:exc:`DeprecationWarning` to indicate the hostname wasn't checked.
9+
(In Python 3.13 and later, this raises :exc:`ValueError`.)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
:mod:`asyncio`: :meth:`loop.start_tls() <asyncio.loop.start_tls>` and
2+
:meth:`loop.create_connection() <asyncio.loop.create_connection>` now
3+
validate the *server_hostname* argument if an :class:`ssl.SSLContext` is
4+
passed with *check_hostname* set to ``True``, emitting
5+
:exc:`DeprecationWarning` if *server_hostname* is missing. (This will raise
6+
:exc:`ValueError` in Python 3.13 and later.)

0 commit comments

Comments
 (0)