| 1 |
"""Tests for asyncio/sslproto.py.""" |
| 2 |
|
| 3 |
import logging |
| 4 |
import socket |
| 5 |
import unittest |
| 6 |
import weakref |
| 7 |
from test import support |
| 8 |
from test.support import socket_helper |
| 9 |
from unittest import mock |
| 10 |
try: |
| 11 |
import ssl |
| 12 |
except ImportError: |
| 13 |
ssl = None |
| 14 |
|
| 15 |
import asyncio |
| 16 |
from asyncio import log |
| 17 |
from asyncio import protocols |
| 18 |
from asyncio import sslproto |
| 19 |
from test.test_asyncio import utils as test_utils |
| 20 |
from test.test_asyncio import functional as func_tests |
| 21 |
|
| 22 |
|
| 23 |
def tearDownModule(): |
| 24 |
asyncio.events._set_event_loop_policy(None) |
| 25 |
|
| 26 |
|
| 27 |
@unittest.skipIf(ssl is None, 'No ssl module') |
| 28 |
class SslProtoHandshakeTests(test_utils.TestCase): |
| 29 |
|
| 30 |
def setUp(self): |
| 31 |
super().setUp() |
| 32 |
self.loop = asyncio.new_event_loop() |
| 33 |
self.set_event_loop(self.loop) |
| 34 |
|
| 35 |
def ssl_protocol(self, *, waiter=None, proto=None): |
| 36 |
sslcontext = test_utils.dummy_ssl_context() |
| 37 |
if proto is None: # app protocol |
| 38 |
proto = asyncio.Protocol() |
| 39 |
ssl_proto = sslproto.SSLProtocol(self.loop, proto, sslcontext, waiter, |
| 40 |
ssl_handshake_timeout=0.1) |
| 41 |
self.assertIs(ssl_proto._app_transport.get_protocol(), proto) |
| 42 |
self.addCleanup(ssl_proto._app_transport.close) |
| 43 |
return ssl_proto |
| 44 |
|
| 45 |
def connection_made(self, ssl_proto, *, do_handshake=None): |
| 46 |
transport = mock.Mock() |
| 47 |
sslobj = mock.Mock() |
| 48 |
# emulate reading decompressed data |
| 49 |
sslobj.read.side_effect = ssl.SSLWantReadError |
| 50 |
sslobj.write.side_effect = ssl.SSLWantReadError |
| 51 |
if do_handshake is not None: |
| 52 |
sslobj.do_handshake = do_handshake |
| 53 |
ssl_proto._sslobj = sslobj |
| 54 |
ssl_proto.connection_made(transport) |
| 55 |
return transport |
| 56 |
|
| 57 |
def test_handshake_timeout_zero(self): |
| 58 |
sslcontext = test_utils.dummy_ssl_context() |
| 59 |
app_proto = mock.Mock() |
| 60 |
waiter = mock.Mock() |
| 61 |
with self.assertRaisesRegex(ValueError, 'a positive number'): |
| 62 |
sslproto.SSLProtocol(self.loop, app_proto, sslcontext, waiter, |
| 63 |
ssl_handshake_timeout=0) |
| 64 |
|
| 65 |
def test_handshake_timeout_negative(self): |
| 66 |
sslcontext = test_utils.dummy_ssl_context() |
| 67 |
app_proto = mock.Mock() |
| 68 |
waiter = mock.Mock() |
| 69 |
with self.assertRaisesRegex(ValueError, 'a positive number'): |
| 70 |
sslproto.SSLProtocol(self.loop, app_proto, sslcontext, waiter, |
| 71 |
ssl_handshake_timeout=-10) |
| 72 |
|
| 73 |
def test_eof_received_waiter(self): |
| 74 |
waiter = self.loop.create_future() |
| 75 |
ssl_proto = self.ssl_protocol(waiter=waiter) |
| 76 |
self.connection_made( |
| 77 |
ssl_proto, |
| 78 |
do_handshake=mock.Mock(side_effect=ssl.SSLWantReadError) |
| 79 |
) |
| 80 |
ssl_proto.eof_received() |
| 81 |
test_utils.run_briefly(self.loop) |
| 82 |
self.assertIsInstance(waiter.exception(), ConnectionResetError) |
| 83 |
|
| 84 |
def test_fatal_error_no_name_error(self): |
| 85 |
# From issue #363. |
| 86 |
# _fatal_error() generates a NameError if sslproto.py |
| 87 |
# does not import base_events. |
| 88 |
waiter = self.loop.create_future() |
| 89 |
ssl_proto = self.ssl_protocol(waiter=waiter) |
| 90 |
# Temporarily turn off error logging so as not to spoil test output. |
| 91 |
log_level = log.logger.getEffectiveLevel() |
| 92 |
log.logger.setLevel(logging.FATAL) |
| 93 |
try: |
| 94 |
ssl_proto._fatal_error(None) |
| 95 |
finally: |
| 96 |
# Restore error logging. |
| 97 |
log.logger.setLevel(log_level) |
| 98 |
|
| 99 |
def test_connection_lost(self): |
| 100 |
# From issue #472. |
| 101 |
# yield from waiter hang if lost_connection was called. |
| 102 |
waiter = self.loop.create_future() |
| 103 |
ssl_proto = self.ssl_protocol(waiter=waiter) |
| 104 |
self.connection_made( |
| 105 |
ssl_proto, |
| 106 |
do_handshake=mock.Mock(side_effect=ssl.SSLWantReadError) |
| 107 |
) |
| 108 |
ssl_proto.connection_lost(ConnectionAbortedError) |
| 109 |
test_utils.run_briefly(self.loop) |
| 110 |
self.assertIsInstance(waiter.exception(), ConnectionAbortedError) |
| 111 |
|
| 112 |
def test_connection_lost_when_busy(self): |
| 113 |
# gh-118950: SSLProtocol.connection_lost not being called when OSError |
| 114 |
# is thrown on asyncio.write. |
| 115 |
sock = mock.Mock() |
| 116 |
sock.fileno = mock.Mock(return_value=12345) |
| 117 |
sock.send = mock.Mock(side_effect=BrokenPipeError) |
| 118 |
|
| 119 |
# construct StreamWriter chain that contains loop dependant logic this emulates |
| 120 |
# what _make_ssl_transport() does in BaseSelectorEventLoop |
| 121 |
reader = asyncio.StreamReader(limit=2 ** 16, loop=self.loop) |
| 122 |
protocol = asyncio.StreamReaderProtocol(reader, loop=self.loop) |
| 123 |
ssl_proto = self.ssl_protocol(proto=protocol) |
| 124 |
|
| 125 |
# emulate reading decompressed data |
| 126 |
sslobj = mock.Mock() |
| 127 |
sslobj.read.side_effect = ssl.SSLWantReadError |
| 128 |
sslobj.write.side_effect = ssl.SSLWantReadError |
| 129 |
ssl_proto._sslobj = sslobj |
| 130 |
|
| 131 |
# emulate outgoing data |
| 132 |
data = b'An interesting message' |
| 133 |
|
| 134 |
outgoing = mock.Mock() |
| 135 |
outgoing.read = mock.Mock(return_value=data) |
| 136 |
outgoing.pending = len(data) |
| 137 |
ssl_proto._outgoing = outgoing |
| 138 |
|
| 139 |
# use correct socket transport to initialize the SSLProtocol |
| 140 |
self.loop._make_socket_transport(sock, ssl_proto) |
| 141 |
|
| 142 |
transport = ssl_proto._app_transport |
| 143 |
writer = asyncio.StreamWriter(transport, protocol, reader, self.loop) |
| 144 |
|
| 145 |
async def main(): |
| 146 |
# writes data to transport |
| 147 |
async def write(): |
| 148 |
writer.write(data) |
| 149 |
await writer.drain() |
| 150 |
|
| 151 |
# try to write for the first time |
| 152 |
await write() |
| 153 |
# try to write for the second time, this raises as the connection_lost |
| 154 |
# callback should be done with error |
| 155 |
with self.assertRaises(ConnectionResetError): |
| 156 |
await write() |
| 157 |
|
| 158 |
self.loop.run_until_complete(main()) |
| 159 |
|
| 160 |
def test_close_during_handshake(self): |
| 161 |
# bpo-29743 Closing transport during handshake process leaks socket |
| 162 |
waiter = self.loop.create_future() |
| 163 |
ssl_proto = self.ssl_protocol(waiter=waiter) |
| 164 |
|
| 165 |
transport = self.connection_made( |
| 166 |
ssl_proto, |
| 167 |
do_handshake=mock.Mock(side_effect=ssl.SSLWantReadError) |
| 168 |
) |
| 169 |
test_utils.run_briefly(self.loop) |
| 170 |
|
| 171 |
ssl_proto._app_transport.close() |
| 172 |
self.assertTrue(transport._force_close.called) |
| 173 |
|
| 174 |
def test_close_during_ssl_over_ssl(self): |
| 175 |
# gh-113214: passing exceptions from the inner wrapped SSL protocol to the |
| 176 |
# shim transport provided by the outer SSL protocol should not raise |
| 177 |
# attribute errors |
| 178 |
outer = self.ssl_protocol(proto=self.ssl_protocol()) |
| 179 |
self.connection_made(outer) |
| 180 |
# Closing the outer app transport should not raise an exception |
| 181 |
messages = [] |
| 182 |
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx)) |
| 183 |
outer._app_transport.close() |
| 184 |
self.assertEqual(messages, []) |
| 185 |
|
| 186 |
def test_get_extra_info_on_closed_connection(self): |
| 187 |
waiter = self.loop.create_future() |
| 188 |
ssl_proto = self.ssl_protocol(waiter=waiter) |
| 189 |
self.assertIsNone(ssl_proto._get_extra_info('socket')) |
| 190 |
default = object() |
| 191 |
self.assertIs(ssl_proto._get_extra_info('socket', default), default) |
| 192 |
self.connection_made(ssl_proto) |
| 193 |
self.assertIsNotNone(ssl_proto._get_extra_info('socket')) |
| 194 |
ssl_proto.connection_lost(None) |
| 195 |
self.assertIsNone(ssl_proto._get_extra_info('socket')) |
| 196 |
|
| 197 |
def test_set_new_app_protocol(self): |
| 198 |
waiter = self.loop.create_future() |
| 199 |
ssl_proto = self.ssl_protocol(waiter=waiter) |
| 200 |
new_app_proto = asyncio.Protocol() |
| 201 |
ssl_proto._app_transport.set_protocol(new_app_proto) |
| 202 |
self.assertIs(ssl_proto._app_transport.get_protocol(), new_app_proto) |
| 203 |
self.assertIs(ssl_proto._app_protocol, new_app_proto) |
| 204 |
|
| 205 |
def test_data_received_after_closing(self): |
| 206 |
ssl_proto = self.ssl_protocol() |
| 207 |
self.connection_made(ssl_proto) |
| 208 |
transp = ssl_proto._app_transport |
| 209 |
|
| 210 |
transp.close() |
| 211 |
|
| 212 |
# should not raise |
| 213 |
self.assertIsNone(ssl_proto.buffer_updated(5)) |
| 214 |
|
| 215 |
def test_write_after_closing(self): |
| 216 |
ssl_proto = self.ssl_protocol() |
| 217 |
self.connection_made(ssl_proto) |
| 218 |
transp = ssl_proto._app_transport |
| 219 |
transp.close() |
| 220 |
|
| 221 |
# should not raise |
| 222 |
self.assertIsNone(transp.write(b'data')) |
| 223 |
|
| 224 |
|
| 225 |
############################################################################## |
| 226 |
# Start TLS Tests |
| 227 |
############################################################################## |
| 228 |
|
| 229 |
|
| 230 |
class BaseStartTLS(func_tests.FunctionalTestCaseMixin): |
| 231 |
|
| 232 |
PAYLOAD_SIZE = 1024 * 100 |
| 233 |
TIMEOUT = support.LONG_TIMEOUT |
| 234 |
|
| 235 |
def new_loop(self): |
| 236 |
raise NotImplementedError |
| 237 |
|
| 238 |
def test_buf_feed_data(self): |
| 239 |
|
| 240 |
class Proto(asyncio.BufferedProtocol): |
| 241 |
|
| 242 |
def __init__(self, bufsize, usemv): |
| 243 |
self.buf = bytearray(bufsize) |
| 244 |
self.mv = memoryview(self.buf) |
| 245 |
self.data = b'' |
| 246 |
self.usemv = usemv |
| 247 |
|
| 248 |
def get_buffer(self, sizehint): |
| 249 |
if self.usemv: |
| 250 |
return self.mv |
| 251 |
else: |
| 252 |
return self.buf |
| 253 |
|
| 254 |
def buffer_updated(self, nsize): |
| 255 |
if self.usemv: |
| 256 |
self.data += self.mv[:nsize] |
| 257 |
else: |
| 258 |
self.data += self.buf[:nsize] |
| 259 |
|
| 260 |
for usemv in [False, True]: |
| 261 |
proto = Proto(1, usemv) |
| 262 |
protocols._feed_data_to_buffered_proto(proto, b'12345') |
| 263 |
self.assertEqual(proto.data, b'12345') |
| 264 |
|
| 265 |
proto = Proto(2, usemv) |
| 266 |
protocols._feed_data_to_buffered_proto(proto, b'12345') |
| 267 |
self.assertEqual(proto.data, b'12345') |
| 268 |
|
| 269 |
proto = Proto(2, usemv) |
| 270 |
protocols._feed_data_to_buffered_proto(proto, b'1234') |
| 271 |
self.assertEqual(proto.data, b'1234') |
| 272 |
|
| 273 |
proto = Proto(4, usemv) |
| 274 |
protocols._feed_data_to_buffered_proto(proto, b'1234') |
| 275 |
self.assertEqual(proto.data, b'1234') |
| 276 |
|
| 277 |
proto = Proto(100, usemv) |
| 278 |
protocols._feed_data_to_buffered_proto(proto, b'12345') |
| 279 |
self.assertEqual(proto.data, b'12345') |
| 280 |
|
| 281 |
proto = Proto(0, usemv) |
| 282 |
with self.assertRaisesRegex(RuntimeError, 'empty buffer'): |
| 283 |
protocols._feed_data_to_buffered_proto(proto, b'12345') |
| 284 |
|
| 285 |
def test_start_tls_client_reg_proto_1(self): |
| 286 |
HELLO_MSG = b'1' * self.PAYLOAD_SIZE |
| 287 |
|
| 288 |
server_context = test_utils.simple_server_sslcontext() |
| 289 |
client_context = test_utils.simple_client_sslcontext() |
| 290 |
|
| 291 |
def serve(sock): |
| 292 |
sock.settimeout(self.TIMEOUT) |
| 293 |
|
| 294 |
data = sock.recv_all(len(HELLO_MSG)) |
| 295 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 296 |
|
| 297 |
sock.start_tls(server_context, server_side=True) |
| 298 |
|
| 299 |
sock.sendall(b'O') |
| 300 |
data = sock.recv_all(len(HELLO_MSG)) |
| 301 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 302 |
|
| 303 |
sock.shutdown(socket.SHUT_RDWR) |
| 304 |
sock.close() |
| 305 |
|
| 306 |
class ClientProto(asyncio.Protocol): |
| 307 |
def __init__(self, on_data, on_eof): |
| 308 |
self.on_data = on_data |
| 309 |
self.on_eof = on_eof |
| 310 |
self.con_made_cnt = 0 |
| 311 |
|
| 312 |
def connection_made(proto, tr): |
| 313 |
proto.con_made_cnt += 1 |
| 314 |
# Ensure connection_made gets called only once. |
| 315 |
self.assertEqual(proto.con_made_cnt, 1) |
| 316 |
|
| 317 |
def data_received(self, data): |
| 318 |
self.on_data.set_result(data) |
| 319 |
|
| 320 |
def eof_received(self): |
| 321 |
self.on_eof.set_result(True) |
| 322 |
|
| 323 |
async def client(addr): |
| 324 |
await asyncio.sleep(0.5) |
| 325 |
|
| 326 |
on_data = self.loop.create_future() |
| 327 |
on_eof = self.loop.create_future() |
| 328 |
|
| 329 |
tr, proto = await self.loop.create_connection( |
| 330 |
lambda: ClientProto(on_data, on_eof), *addr) |
| 331 |
|
| 332 |
tr.write(HELLO_MSG) |
| 333 |
new_tr = await self.loop.start_tls(tr, proto, client_context) |
| 334 |
|
| 335 |
self.assertEqual(await on_data, b'O') |
| 336 |
new_tr.write(HELLO_MSG) |
| 337 |
await on_eof |
| 338 |
|
| 339 |
new_tr.close() |
| 340 |
|
| 341 |
with self.tcp_server(serve, timeout=self.TIMEOUT) as srv: |
| 342 |
self.loop.run_until_complete( |
| 343 |
asyncio.wait_for(client(srv.addr), |
| 344 |
timeout=support.SHORT_TIMEOUT)) |
| 345 |
|
| 346 |
# No garbage is left if SSL is closed uncleanly |
| 347 |
client_context = weakref.ref(client_context) |
| 348 |
support.gc_collect() |
| 349 |
self.assertIsNone(client_context()) |
| 350 |
|
| 351 |
def test_create_connection_memory_leak(self): |
| 352 |
HELLO_MSG = b'1' * self.PAYLOAD_SIZE |
| 353 |
|
| 354 |
server_context = test_utils.simple_server_sslcontext() |
| 355 |
client_context = test_utils.simple_client_sslcontext() |
| 356 |
|
| 357 |
def serve(sock): |
| 358 |
sock.settimeout(self.TIMEOUT) |
| 359 |
|
| 360 |
sock.start_tls(server_context, server_side=True) |
| 361 |
|
| 362 |
sock.sendall(b'O') |
| 363 |
data = sock.recv_all(len(HELLO_MSG)) |
| 364 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 365 |
|
| 366 |
sock.shutdown(socket.SHUT_RDWR) |
| 367 |
sock.close() |
| 368 |
|
| 369 |
class ClientProto(asyncio.Protocol): |
| 370 |
def __init__(self, on_data, on_eof): |
| 371 |
self.on_data = on_data |
| 372 |
self.on_eof = on_eof |
| 373 |
self.con_made_cnt = 0 |
| 374 |
|
| 375 |
def connection_made(proto, tr): |
| 376 |
# XXX: We assume user stores the transport in protocol |
| 377 |
proto.tr = tr |
| 378 |
proto.con_made_cnt += 1 |
| 379 |
# Ensure connection_made gets called only once. |
| 380 |
self.assertEqual(proto.con_made_cnt, 1) |
| 381 |
|
| 382 |
def data_received(self, data): |
| 383 |
self.on_data.set_result(data) |
| 384 |
|
| 385 |
def eof_received(self): |
| 386 |
self.on_eof.set_result(True) |
| 387 |
|
| 388 |
async def client(addr): |
| 389 |
await asyncio.sleep(0.5) |
| 390 |
|
| 391 |
on_data = self.loop.create_future() |
| 392 |
on_eof = self.loop.create_future() |
| 393 |
|
| 394 |
tr, proto = await self.loop.create_connection( |
| 395 |
lambda: ClientProto(on_data, on_eof), *addr, |
| 396 |
ssl=client_context) |
| 397 |
|
| 398 |
self.assertEqual(await on_data, b'O') |
| 399 |
tr.write(HELLO_MSG) |
| 400 |
await on_eof |
| 401 |
|
| 402 |
tr.close() |
| 403 |
|
| 404 |
with self.tcp_server(serve, timeout=self.TIMEOUT) as srv: |
| 405 |
self.loop.run_until_complete( |
| 406 |
asyncio.wait_for(client(srv.addr), |
| 407 |
timeout=support.SHORT_TIMEOUT)) |
| 408 |
|
| 409 |
# No garbage is left for SSL client from loop.create_connection, even |
| 410 |
# if user stores the SSLTransport in corresponding protocol instance |
| 411 |
client_context = weakref.ref(client_context) |
| 412 |
support.gc_collect() |
| 413 |
self.assertIsNone(client_context()) |
| 414 |
|
| 415 |
@socket_helper.skip_if_tcp_blackhole |
| 416 |
def test_start_tls_client_buf_proto_1(self): |
| 417 |
HELLO_MSG = b'1' * self.PAYLOAD_SIZE |
| 418 |
|
| 419 |
server_context = test_utils.simple_server_sslcontext() |
| 420 |
client_context = test_utils.simple_client_sslcontext() |
| 421 |
client_con_made_calls = 0 |
| 422 |
|
| 423 |
def serve(sock): |
| 424 |
sock.settimeout(self.TIMEOUT) |
| 425 |
|
| 426 |
data = sock.recv_all(len(HELLO_MSG)) |
| 427 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 428 |
|
| 429 |
sock.start_tls(server_context, server_side=True) |
| 430 |
|
| 431 |
sock.sendall(b'O') |
| 432 |
data = sock.recv_all(len(HELLO_MSG)) |
| 433 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 434 |
|
| 435 |
sock.sendall(b'2') |
| 436 |
data = sock.recv_all(len(HELLO_MSG)) |
| 437 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 438 |
|
| 439 |
sock.shutdown(socket.SHUT_RDWR) |
| 440 |
sock.close() |
| 441 |
|
| 442 |
class ClientProtoFirst(asyncio.BufferedProtocol): |
| 443 |
def __init__(self, on_data): |
| 444 |
self.on_data = on_data |
| 445 |
self.buf = bytearray(1) |
| 446 |
|
| 447 |
def connection_made(self, tr): |
| 448 |
nonlocal client_con_made_calls |
| 449 |
client_con_made_calls += 1 |
| 450 |
|
| 451 |
def get_buffer(self, sizehint): |
| 452 |
return self.buf |
| 453 |
|
| 454 |
def buffer_updated(slf, nsize): |
| 455 |
self.assertEqual(nsize, 1) |
| 456 |
slf.on_data.set_result(bytes(slf.buf[:nsize])) |
| 457 |
|
| 458 |
class ClientProtoSecond(asyncio.Protocol): |
| 459 |
def __init__(self, on_data, on_eof): |
| 460 |
self.on_data = on_data |
| 461 |
self.on_eof = on_eof |
| 462 |
self.con_made_cnt = 0 |
| 463 |
|
| 464 |
def connection_made(self, tr): |
| 465 |
nonlocal client_con_made_calls |
| 466 |
client_con_made_calls += 1 |
| 467 |
|
| 468 |
def data_received(self, data): |
| 469 |
self.on_data.set_result(data) |
| 470 |
|
| 471 |
def eof_received(self): |
| 472 |
self.on_eof.set_result(True) |
| 473 |
|
| 474 |
async def client(addr): |
| 475 |
await asyncio.sleep(0.5) |
| 476 |
|
| 477 |
on_data1 = self.loop.create_future() |
| 478 |
on_data2 = self.loop.create_future() |
| 479 |
on_eof = self.loop.create_future() |
| 480 |
|
| 481 |
tr, proto = await self.loop.create_connection( |
| 482 |
lambda: ClientProtoFirst(on_data1), *addr) |
| 483 |
|
| 484 |
tr.write(HELLO_MSG) |
| 485 |
new_tr = await self.loop.start_tls(tr, proto, client_context) |
| 486 |
|
| 487 |
self.assertEqual(await on_data1, b'O') |
| 488 |
new_tr.write(HELLO_MSG) |
| 489 |
|
| 490 |
new_tr.set_protocol(ClientProtoSecond(on_data2, on_eof)) |
| 491 |
self.assertEqual(await on_data2, b'2') |
| 492 |
new_tr.write(HELLO_MSG) |
| 493 |
await on_eof |
| 494 |
|
| 495 |
new_tr.close() |
| 496 |
|
| 497 |
# connection_made() should be called only once -- when |
| 498 |
# we establish connection for the first time. Start TLS |
| 499 |
# doesn't call connection_made() on application protocols. |
| 500 |
self.assertEqual(client_con_made_calls, 1) |
| 501 |
|
| 502 |
with self.tcp_server(serve, timeout=self.TIMEOUT) as srv: |
| 503 |
self.loop.run_until_complete( |
| 504 |
asyncio.wait_for(client(srv.addr), |
| 505 |
timeout=self.TIMEOUT)) |
| 506 |
|
| 507 |
def test_start_tls_slow_client_cancel(self): |
| 508 |
HELLO_MSG = b'1' * self.PAYLOAD_SIZE |
| 509 |
|
| 510 |
client_context = test_utils.simple_client_sslcontext() |
| 511 |
server_waits_on_handshake = self.loop.create_future() |
| 512 |
|
| 513 |
def serve(sock): |
| 514 |
sock.settimeout(self.TIMEOUT) |
| 515 |
|
| 516 |
data = sock.recv_all(len(HELLO_MSG)) |
| 517 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 518 |
|
| 519 |
try: |
| 520 |
self.loop.call_soon_threadsafe( |
| 521 |
server_waits_on_handshake.set_result, None) |
| 522 |
data = sock.recv_all(1024 * 1024) |
| 523 |
except ConnectionAbortedError: |
| 524 |
pass |
| 525 |
finally: |
| 526 |
sock.close() |
| 527 |
|
| 528 |
class ClientProto(asyncio.Protocol): |
| 529 |
def __init__(self, on_data, on_eof): |
| 530 |
self.on_data = on_data |
| 531 |
self.on_eof = on_eof |
| 532 |
self.con_made_cnt = 0 |
| 533 |
|
| 534 |
def connection_made(proto, tr): |
| 535 |
proto.con_made_cnt += 1 |
| 536 |
# Ensure connection_made gets called only once. |
| 537 |
self.assertEqual(proto.con_made_cnt, 1) |
| 538 |
|
| 539 |
def data_received(self, data): |
| 540 |
self.on_data.set_result(data) |
| 541 |
|
| 542 |
def eof_received(self): |
| 543 |
self.on_eof.set_result(True) |
| 544 |
|
| 545 |
async def client(addr): |
| 546 |
await asyncio.sleep(0.5) |
| 547 |
|
| 548 |
on_data = self.loop.create_future() |
| 549 |
on_eof = self.loop.create_future() |
| 550 |
|
| 551 |
tr, proto = await self.loop.create_connection( |
| 552 |
lambda: ClientProto(on_data, on_eof), *addr) |
| 553 |
|
| 554 |
tr.write(HELLO_MSG) |
| 555 |
|
| 556 |
await server_waits_on_handshake |
| 557 |
|
| 558 |
with self.assertRaises(asyncio.TimeoutError): |
| 559 |
await asyncio.wait_for( |
| 560 |
self.loop.start_tls(tr, proto, client_context), |
| 561 |
0.5) |
| 562 |
|
| 563 |
with self.tcp_server(serve, timeout=self.TIMEOUT) as srv: |
| 564 |
self.loop.run_until_complete( |
| 565 |
asyncio.wait_for(client(srv.addr), |
| 566 |
timeout=support.SHORT_TIMEOUT)) |
| 567 |
|
| 568 |
@socket_helper.skip_if_tcp_blackhole |
| 569 |
def test_start_tls_server_1(self): |
| 570 |
HELLO_MSG = b'1' * self.PAYLOAD_SIZE |
| 571 |
ANSWER = b'answer' |
| 572 |
|
| 573 |
server_context = test_utils.simple_server_sslcontext() |
| 574 |
client_context = test_utils.simple_client_sslcontext() |
| 575 |
answer = None |
| 576 |
|
| 577 |
def client(sock, addr): |
| 578 |
nonlocal answer |
| 579 |
sock.settimeout(self.TIMEOUT) |
| 580 |
|
| 581 |
sock.connect(addr) |
| 582 |
data = sock.recv_all(len(HELLO_MSG)) |
| 583 |
self.assertEqual(len(data), len(HELLO_MSG)) |
| 584 |
|
| 585 |
sock.start_tls(client_context) |
| 586 |
sock.sendall(HELLO_MSG) |
| 587 |
answer = sock.recv_all(len(ANSWER)) |
| 588 |
sock.close() |
| 589 |
|
| 590 |
class ServerProto(asyncio.Protocol): |
| 591 |
def __init__(self, on_con, on_con_lost, on_got_hello): |
| 592 |
self.on_con = on_con |
| 593 |
self.on_con_lost = on_con_lost |
| 594 |
self.on_got_hello = on_got_hello |
| 595 |
self.data = b'' |
| 596 |
self.transport = None |
| 597 |
|
| 598 |
def connection_made(self, tr): |
| 599 |
self.transport = tr |
| 600 |
self.on_con.set_result(tr) |
| 601 |
|
| 602 |
def replace_transport(self, tr): |
| 603 |
self.transport = tr |
| 604 |
|
| 605 |
def data_received(self, data): |
| 606 |
self.data += data |
| 607 |
if len(self.data) >= len(HELLO_MSG): |
| 608 |
self.on_got_hello.set_result(None) |
| 609 |
|
| 610 |
def connection_lost(self, exc): |
| 611 |
self.transport = None |
| 612 |
if exc is None: |
| 613 |
self.on_con_lost.set_result(None) |
| 614 |
else: |
| 615 |
self.on_con_lost.set_exception(exc) |
| 616 |
|
| 617 |
async def main(proto, on_con, on_con_lost, on_got_hello): |
| 618 |
tr = await on_con |
| 619 |
tr.write(HELLO_MSG) |
| 620 |
|
| 621 |
self.assertEqual(proto.data, b'') |
| 622 |
|
| 623 |
new_tr = await self.loop.start_tls( |
| 624 |
tr, proto, server_context, |
| 625 |
server_side=True, |
| 626 |
ssl_handshake_timeout=self.TIMEOUT) |
| 627 |
proto.replace_transport(new_tr) |
| 628 |
|
| 629 |
await on_got_hello |
| 630 |
new_tr.write(ANSWER) |
| 631 |
|
| 632 |
await on_con_lost |
| 633 |
self.assertEqual(proto.data, HELLO_MSG) |
| 634 |
new_tr.close() |
| 635 |
|
| 636 |
async def run_main(): |
| 637 |
on_con = self.loop.create_future() |
| 638 |
on_con_lost = self.loop.create_future() |
| 639 |
on_got_hello = self.loop.create_future() |
| 640 |
proto = ServerProto(on_con, on_con_lost, on_got_hello) |
| 641 |
|
| 642 |
server = await self.loop.create_server( |
| 643 |
lambda: proto, '127.0.0.1', 0) |
| 644 |
addr = server.sockets[0].getsockname() |
| 645 |
|
| 646 |
with self.tcp_client(lambda sock: client(sock, addr), |
| 647 |
timeout=self.TIMEOUT): |
| 648 |
await asyncio.wait_for( |
| 649 |
main(proto, on_con, on_con_lost, on_got_hello), |
| 650 |
timeout=self.TIMEOUT) |
| 651 |
|
| 652 |
server.close() |
| 653 |
await server.wait_closed() |
| 654 |
self.assertEqual(answer, ANSWER) |
| 655 |
|
| 656 |
self.loop.run_until_complete(run_main()) |
| 657 |
|
| 658 |
def test_start_tls_wrong_args(self): |
| 659 |
async def main(): |
| 660 |
with self.assertRaisesRegex(TypeError, 'SSLContext, got'): |
| 661 |
await self.loop.start_tls(None, None, None) |
| 662 |
|
| 663 |
sslctx = test_utils.simple_server_sslcontext() |
| 664 |
with self.assertRaisesRegex(TypeError, 'is not supported'): |
| 665 |
await self.loop.start_tls(None, None, sslctx) |
| 666 |
|
| 667 |
self.loop.run_until_complete(main()) |
| 668 |
|
| 669 |
def test_handshake_timeout(self): |
| 670 |
# bpo-29970: Check that a connection is aborted if handshake is not |
| 671 |
# completed in timeout period, instead of remaining open indefinitely |
| 672 |
client_sslctx = test_utils.simple_client_sslcontext() |
| 673 |
|
| 674 |
messages = [] |
| 675 |
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx)) |
| 676 |
|
| 677 |
server_side_aborted = False |
| 678 |
|
| 679 |
def server(sock): |
| 680 |
nonlocal server_side_aborted |
| 681 |
try: |
| 682 |
sock.recv_all(1024 * 1024) |
| 683 |
except ConnectionAbortedError: |
| 684 |
server_side_aborted = True |
| 685 |
finally: |
| 686 |
sock.close() |
| 687 |
|
| 688 |
async def client(addr): |
| 689 |
await asyncio.wait_for( |
| 690 |
self.loop.create_connection( |
| 691 |
asyncio.Protocol, |
| 692 |
*addr, |
| 693 |
ssl=client_sslctx, |
| 694 |
server_hostname='', |
| 695 |
ssl_handshake_timeout=support.SHORT_TIMEOUT), |
| 696 |
0.5) |
| 697 |
|
| 698 |
with self.tcp_server(server, |
| 699 |
max_clients=1, |
| 700 |
backlog=1) as srv: |
| 701 |
|
| 702 |
with self.assertRaises(asyncio.TimeoutError): |
| 703 |
self.loop.run_until_complete(client(srv.addr)) |
| 704 |
|
| 705 |
self.assertTrue(server_side_aborted) |
| 706 |
|
| 707 |
# Python issue #23197: cancelling a handshake must not raise an |
| 708 |
# exception or log an error, even if the handshake failed |
| 709 |
self.assertEqual(messages, []) |
| 710 |
|
| 711 |
# The 10s handshake timeout should be cancelled to free related |
| 712 |
# objects without really waiting for 10s |
| 713 |
client_sslctx = weakref.ref(client_sslctx) |
| 714 |
support.gc_collect() |
| 715 |
self.assertIsNone(client_sslctx()) |
| 716 |
|
| 717 |
def test_create_connection_ssl_slow_handshake(self): |
| 718 |
client_sslctx = test_utils.simple_client_sslcontext() |
| 719 |
|
| 720 |
messages = [] |
| 721 |
self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx)) |
| 722 |
|
| 723 |
def server(sock): |
| 724 |
try: |
| 725 |
sock.recv_all(1024 * 1024) |
| 726 |
except ConnectionAbortedError: |
| 727 |
pass |
| 728 |
finally: |
| 729 |
sock.close() |
| 730 |
|
| 731 |
async def client(addr): |
| 732 |
reader, writer = await asyncio.open_connection( |
| 733 |
*addr, |
| 734 |
ssl=client_sslctx, |
| 735 |
server_hostname='', |
| 736 |
ssl_handshake_timeout=1.0) |
| 737 |
|
| 738 |
with self.tcp_server(server, |
| 739 |
max_clients=1, |
| 740 |
backlog=1) as srv: |
| 741 |
|
| 742 |
with self.assertRaisesRegex( |
| 743 |
ConnectionAbortedError, |
| 744 |
r'SSL handshake.*is taking longer'): |
| 745 |
|
| 746 |
self.loop.run_until_complete(client(srv.addr)) |
| 747 |
|
| 748 |
self.assertEqual(messages, []) |
| 749 |
|
| 750 |
def test_create_connection_ssl_failed_certificate(self): |
| 751 |
self.loop.set_exception_handler(lambda loop, ctx: None) |
| 752 |
|
| 753 |
sslctx = test_utils.simple_server_sslcontext() |
| 754 |
client_sslctx = test_utils.simple_client_sslcontext( |
| 755 |
disable_verify=False) |
| 756 |
|
| 757 |
def server(sock): |
| 758 |
try: |
| 759 |
sock.start_tls( |
| 760 |
sslctx, |
| 761 |
server_side=True) |
| 762 |
except ssl.SSLError: |
| 763 |
pass |
| 764 |
except OSError: |
| 765 |
pass |
| 766 |
finally: |
| 767 |
sock.close() |
| 768 |
|
| 769 |
async def client(addr): |
| 770 |
reader, writer = await asyncio.open_connection( |
| 771 |
*addr, |
| 772 |
ssl=client_sslctx, |
| 773 |
server_hostname='', |
| 774 |
ssl_handshake_timeout=support.LOOPBACK_TIMEOUT) |
| 775 |
|
| 776 |
with self.tcp_server(server, |
| 777 |
max_clients=1, |
| 778 |
backlog=1) as srv: |
| 779 |
|
| 780 |
with self.assertRaises(ssl.SSLCertVerificationError): |
| 781 |
self.loop.run_until_complete(client(srv.addr)) |
| 782 |
|
| 783 |
def test_start_tls_client_corrupted_ssl(self): |
| 784 |
self.loop.set_exception_handler(lambda loop, ctx: None) |
| 785 |
|
| 786 |
sslctx = test_utils.simple_server_sslcontext() |
| 787 |
client_sslctx = test_utils.simple_client_sslcontext() |
| 788 |
|
| 789 |
def server(sock): |
| 790 |
orig_sock = sock.dup() |
| 791 |
try: |
| 792 |
sock.start_tls( |
| 793 |
sslctx, |
| 794 |
server_side=True) |
| 795 |
sock.sendall(b'A\n') |
| 796 |
sock.recv_all(1) |
| 797 |
orig_sock.send(b'please corrupt the SSL connection') |
| 798 |
except ssl.SSLError: |
| 799 |
pass |
| 800 |
finally: |
| 801 |
orig_sock.close() |
| 802 |
sock.close() |
| 803 |
|
| 804 |
async def client(addr): |
| 805 |
reader, writer = await asyncio.open_connection( |
| 806 |
*addr, |
| 807 |
ssl=client_sslctx, |
| 808 |
server_hostname='') |
| 809 |
|
| 810 |
self.assertEqual(await reader.readline(), b'A\n') |
| 811 |
writer.write(b'B') |
| 812 |
with self.assertRaises(ssl.SSLError): |
| 813 |
await reader.readline() |
| 814 |
|
| 815 |
writer.close() |
| 816 |
return 'OK' |
| 817 |
|
| 818 |
with self.tcp_server(server, |
| 819 |
max_clients=1, |
| 820 |
backlog=1) as srv: |
| 821 |
|
| 822 |
res = self.loop.run_until_complete(client(srv.addr)) |
| 823 |
|
| 824 |
self.assertEqual(res, 'OK') |
| 825 |
|
| 826 |
|
| 827 |
@unittest.skipIf(ssl is None, 'No ssl module') |
| 828 |
class SelectorStartTLSTests(BaseStartTLS, unittest.TestCase): |
| 829 |
|
| 830 |
def new_loop(self): |
| 831 |
return asyncio.SelectorEventLoop() |
| 832 |
|
| 833 |
|
| 834 |
@unittest.skipIf(ssl is None, 'No ssl module') |
| 835 |
@unittest.skipUnless(hasattr(asyncio, 'ProactorEventLoop'), 'Windows only') |
| 836 |
class ProactorStartTLSTests(BaseStartTLS, unittest.TestCase): |
| 837 |
|
| 838 |
def new_loop(self): |
| 839 |
return asyncio.ProactorEventLoop() |
| 840 |
|
| 841 |
|
| 842 |
if __name__ == '__main__': |
| 843 |
unittest.main() |