Debian Codegraph @

lib-python/3/test/test_asyncio/test_sslproto.py

raw symbols SCIP
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.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_close_during_handshake(self):
113 # bpo-29743 Closing transport during handshake process leaks socket
114 waiter = self.loop.create_future()
115 ssl_proto = self.ssl_protocol(waiter=waiter)
116
117 transport = self.connection_made(
118 ssl_proto,
119 do_handshake=mock.Mock(side_effect=ssl.SSLWantReadError)
120 )
121 test_utils.run_briefly(self.loop)
122
123 ssl_proto._app_transport.close()
124 self.assertTrue(transport._force_close.called)
125
126 def test_close_during_ssl_over_ssl(self):
127 # gh-113214: passing exceptions from the inner wrapped SSL protocol to the
128 # shim transport provided by the outer SSL protocol should not raise
129 # attribute errors
130 outer = self.ssl_protocol(proto=self.ssl_protocol())
131 self.connection_made(outer)
132 # Closing the outer app transport should not raise an exception
133 messages = []
134 self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx))
135 outer._app_transport.close()
136 self.assertEqual(messages, [])
137
138 def test_get_extra_info_on_closed_connection(self):
139 waiter = self.loop.create_future()
140 ssl_proto = self.ssl_protocol(waiter=waiter)
141 self.assertIsNone(ssl_proto._get_extra_info('socket'))
142 default = object()
143 self.assertIs(ssl_proto._get_extra_info('socket', default), default)
144 self.connection_made(ssl_proto)
145 self.assertIsNotNone(ssl_proto._get_extra_info('socket'))
146 ssl_proto.connection_lost(None)
147 self.assertIsNone(ssl_proto._get_extra_info('socket'))
148
149 def test_set_new_app_protocol(self):
150 waiter = self.loop.create_future()
151 ssl_proto = self.ssl_protocol(waiter=waiter)
152 new_app_proto = asyncio.Protocol()
153 ssl_proto._app_transport.set_protocol(new_app_proto)
154 self.assertIs(ssl_proto._app_transport.get_protocol(), new_app_proto)
155 self.assertIs(ssl_proto._app_protocol, new_app_proto)
156
157 def test_data_received_after_closing(self):
158 ssl_proto = self.ssl_protocol()
159 self.connection_made(ssl_proto)
160 transp = ssl_proto._app_transport
161
162 transp.close()
163
164 # should not raise
165 self.assertIsNone(ssl_proto.buffer_updated(5))
166
167 def test_write_after_closing(self):
168 ssl_proto = self.ssl_protocol()
169 self.connection_made(ssl_proto)
170 transp = ssl_proto._app_transport
171 transp.close()
172
173 # should not raise
174 self.assertIsNone(transp.write(b'data'))
175
176
177 ##############################################################################
178 # Start TLS Tests
179 ##############################################################################
180
181
182 class BaseStartTLS(func_tests.FunctionalTestCaseMixin):
183
184 PAYLOAD_SIZE = 1024 * 100
185 TIMEOUT = support.LONG_TIMEOUT
186
187 def new_loop(self):
188 raise NotImplementedError
189
190 def test_buf_feed_data(self):
191
192 class Proto(asyncio.BufferedProtocol):
193
194 def __init__(self, bufsize, usemv):
195 self.buf = bytearray(bufsize)
196 self.mv = memoryview(self.buf)
197 self.data = b''
198 self.usemv = usemv
199
200 def get_buffer(self, sizehint):
201 if self.usemv:
202 return self.mv
203 else:
204 return self.buf
205
206 def buffer_updated(self, nsize):
207 if self.usemv:
208 self.data += self.mv[:nsize]
209 else:
210 self.data += self.buf[:nsize]
211
212 for usemv in [False, True]:
213 proto = Proto(1, usemv)
214 protocols._feed_data_to_buffered_proto(proto, b'12345')
215 self.assertEqual(proto.data, b'12345')
216
217 proto = Proto(2, usemv)
218 protocols._feed_data_to_buffered_proto(proto, b'12345')
219 self.assertEqual(proto.data, b'12345')
220
221 proto = Proto(2, usemv)
222 protocols._feed_data_to_buffered_proto(proto, b'1234')
223 self.assertEqual(proto.data, b'1234')
224
225 proto = Proto(4, usemv)
226 protocols._feed_data_to_buffered_proto(proto, b'1234')
227 self.assertEqual(proto.data, b'1234')
228
229 proto = Proto(100, usemv)
230 protocols._feed_data_to_buffered_proto(proto, b'12345')
231 self.assertEqual(proto.data, b'12345')
232
233 proto = Proto(0, usemv)
234 with self.assertRaisesRegex(RuntimeError, 'empty buffer'):
235 protocols._feed_data_to_buffered_proto(proto, b'12345')
236
237 def test_start_tls_client_reg_proto_1(self):
238 HELLO_MSG = b'1' * self.PAYLOAD_SIZE
239
240 server_context = test_utils.simple_server_sslcontext()
241 client_context = test_utils.simple_client_sslcontext()
242
243 def serve(sock):
244 sock.settimeout(self.TIMEOUT)
245
246 data = sock.recv_all(len(HELLO_MSG))
247 self.assertEqual(len(data), len(HELLO_MSG))
248
249 sock.start_tls(server_context, server_side=True)
250
251 sock.sendall(b'O')
252 data = sock.recv_all(len(HELLO_MSG))
253 self.assertEqual(len(data), len(HELLO_MSG))
254
255 sock.shutdown(socket.SHUT_RDWR)
256 sock.close()
257
258 class ClientProto(asyncio.Protocol):
259 def __init__(self, on_data, on_eof):
260 self.on_data = on_data
261 self.on_eof = on_eof
262 self.con_made_cnt = 0
263
264 def connection_made(proto, tr):
265 proto.con_made_cnt += 1
266 # Ensure connection_made gets called only once.
267 self.assertEqual(proto.con_made_cnt, 1)
268
269 def data_received(self, data):
270 self.on_data.set_result(data)
271
272 def eof_received(self):
273 self.on_eof.set_result(True)
274
275 async def client(addr):
276 await asyncio.sleep(0.5)
277
278 on_data = self.loop.create_future()
279 on_eof = self.loop.create_future()
280
281 tr, proto = await self.loop.create_connection(
282 lambda: ClientProto(on_data, on_eof), *addr)
283
284 tr.write(HELLO_MSG)
285 new_tr = await self.loop.start_tls(tr, proto, client_context)
286
287 self.assertEqual(await on_data, b'O')
288 new_tr.write(HELLO_MSG)
289 await on_eof
290
291 new_tr.close()
292
293 with self.tcp_server(serve, timeout=self.TIMEOUT) as srv:
294 self.loop.run_until_complete(
295 asyncio.wait_for(client(srv.addr),
296 timeout=support.SHORT_TIMEOUT))
297
298 # No garbage is left if SSL is closed uncleanly
299 client_context = weakref.ref(client_context)
300 support.gc_collect()
301 self.assertIsNone(client_context())
302
303 def test_create_connection_memory_leak(self):
304 HELLO_MSG = b'1' * self.PAYLOAD_SIZE
305
306 server_context = test_utils.simple_server_sslcontext()
307 client_context = test_utils.simple_client_sslcontext()
308
309 def serve(sock):
310 sock.settimeout(self.TIMEOUT)
311
312 sock.start_tls(server_context, server_side=True)
313
314 sock.sendall(b'O')
315 data = sock.recv_all(len(HELLO_MSG))
316 self.assertEqual(len(data), len(HELLO_MSG))
317
318 sock.shutdown(socket.SHUT_RDWR)
319 sock.close()
320
321 class ClientProto(asyncio.Protocol):
322 def __init__(self, on_data, on_eof):
323 self.on_data = on_data
324 self.on_eof = on_eof
325 self.con_made_cnt = 0
326
327 def connection_made(proto, tr):
328 # XXX: We assume user stores the transport in protocol
329 proto.tr = tr
330 proto.con_made_cnt += 1
331 # Ensure connection_made gets called only once.
332 self.assertEqual(proto.con_made_cnt, 1)
333
334 def data_received(self, data):
335 self.on_data.set_result(data)
336
337 def eof_received(self):
338 self.on_eof.set_result(True)
339
340 async def client(addr):
341 await asyncio.sleep(0.5)
342
343 on_data = self.loop.create_future()
344 on_eof = self.loop.create_future()
345
346 tr, proto = await self.loop.create_connection(
347 lambda: ClientProto(on_data, on_eof), *addr,
348 ssl=client_context)
349
350 self.assertEqual(await on_data, b'O')
351 tr.write(HELLO_MSG)
352 await on_eof
353
354 tr.close()
355
356 with self.tcp_server(serve, timeout=self.TIMEOUT) as srv:
357 self.loop.run_until_complete(
358 asyncio.wait_for(client(srv.addr),
359 timeout=support.SHORT_TIMEOUT))
360
361 # No garbage is left for SSL client from loop.create_connection, even
362 # if user stores the SSLTransport in corresponding protocol instance
363 client_context = weakref.ref(client_context)
364 support.gc_collect()
365 self.assertIsNone(client_context())
366
367 @socket_helper.skip_if_tcp_blackhole
368 def test_start_tls_client_buf_proto_1(self):
369 HELLO_MSG = b'1' * self.PAYLOAD_SIZE
370
371 server_context = test_utils.simple_server_sslcontext()
372 client_context = test_utils.simple_client_sslcontext()
373 client_con_made_calls = 0
374
375 def serve(sock):
376 sock.settimeout(self.TIMEOUT)
377
378 data = sock.recv_all(len(HELLO_MSG))
379 self.assertEqual(len(data), len(HELLO_MSG))
380
381 sock.start_tls(server_context, server_side=True)
382
383 sock.sendall(b'O')
384 data = sock.recv_all(len(HELLO_MSG))
385 self.assertEqual(len(data), len(HELLO_MSG))
386
387 sock.sendall(b'2')
388 data = sock.recv_all(len(HELLO_MSG))
389 self.assertEqual(len(data), len(HELLO_MSG))
390
391 sock.shutdown(socket.SHUT_RDWR)
392 sock.close()
393
394 class ClientProtoFirst(asyncio.BufferedProtocol):
395 def __init__(self, on_data):
396 self.on_data = on_data
397 self.buf = bytearray(1)
398
399 def connection_made(self, tr):
400 nonlocal client_con_made_calls
401 client_con_made_calls += 1
402
403 def get_buffer(self, sizehint):
404 return self.buf
405
406 def buffer_updated(slf, nsize):
407 self.assertEqual(nsize, 1)
408 slf.on_data.set_result(bytes(slf.buf[:nsize]))
409
410 class ClientProtoSecond(asyncio.Protocol):
411 def __init__(self, on_data, on_eof):
412 self.on_data = on_data
413 self.on_eof = on_eof
414 self.con_made_cnt = 0
415
416 def connection_made(self, tr):
417 nonlocal client_con_made_calls
418 client_con_made_calls += 1
419
420 def data_received(self, data):
421 self.on_data.set_result(data)
422
423 def eof_received(self):
424 self.on_eof.set_result(True)
425
426 async def client(addr):
427 await asyncio.sleep(0.5)
428
429 on_data1 = self.loop.create_future()
430 on_data2 = self.loop.create_future()
431 on_eof = self.loop.create_future()
432
433 tr, proto = await self.loop.create_connection(
434 lambda: ClientProtoFirst(on_data1), *addr)
435
436 tr.write(HELLO_MSG)
437 new_tr = await self.loop.start_tls(tr, proto, client_context)
438
439 self.assertEqual(await on_data1, b'O')
440 new_tr.write(HELLO_MSG)
441
442 new_tr.set_protocol(ClientProtoSecond(on_data2, on_eof))
443 self.assertEqual(await on_data2, b'2')
444 new_tr.write(HELLO_MSG)
445 await on_eof
446
447 new_tr.close()
448
449 # connection_made() should be called only once -- when
450 # we establish connection for the first time. Start TLS
451 # doesn't call connection_made() on application protocols.
452 self.assertEqual(client_con_made_calls, 1)
453
454 with self.tcp_server(serve, timeout=self.TIMEOUT) as srv:
455 self.loop.run_until_complete(
456 asyncio.wait_for(client(srv.addr),
457 timeout=self.TIMEOUT))
458
459 def test_start_tls_slow_client_cancel(self):
460 HELLO_MSG = b'1' * self.PAYLOAD_SIZE
461
462 client_context = test_utils.simple_client_sslcontext()
463 server_waits_on_handshake = self.loop.create_future()
464
465 def serve(sock):
466 sock.settimeout(self.TIMEOUT)
467
468 data = sock.recv_all(len(HELLO_MSG))
469 self.assertEqual(len(data), len(HELLO_MSG))
470
471 try:
472 self.loop.call_soon_threadsafe(
473 server_waits_on_handshake.set_result, None)
474 data = sock.recv_all(1024 * 1024)
475 except ConnectionAbortedError:
476 pass
477 finally:
478 sock.close()
479
480 class ClientProto(asyncio.Protocol):
481 def __init__(self, on_data, on_eof):
482 self.on_data = on_data
483 self.on_eof = on_eof
484 self.con_made_cnt = 0
485
486 def connection_made(proto, tr):
487 proto.con_made_cnt += 1
488 # Ensure connection_made gets called only once.
489 self.assertEqual(proto.con_made_cnt, 1)
490
491 def data_received(self, data):
492 self.on_data.set_result(data)
493
494 def eof_received(self):
495 self.on_eof.set_result(True)
496
497 async def client(addr):
498 await asyncio.sleep(0.5)
499
500 on_data = self.loop.create_future()
501 on_eof = self.loop.create_future()
502
503 tr, proto = await self.loop.create_connection(
504 lambda: ClientProto(on_data, on_eof), *addr)
505
506 tr.write(HELLO_MSG)
507
508 await server_waits_on_handshake
509
510 with self.assertRaises(asyncio.TimeoutError):
511 await asyncio.wait_for(
512 self.loop.start_tls(tr, proto, client_context),
513 0.5)
514
515 with self.tcp_server(serve, timeout=self.TIMEOUT) as srv:
516 self.loop.run_until_complete(
517 asyncio.wait_for(client(srv.addr),
518 timeout=support.SHORT_TIMEOUT))
519
520 @socket_helper.skip_if_tcp_blackhole
521 def test_start_tls_server_1(self):
522 HELLO_MSG = b'1' * self.PAYLOAD_SIZE
523 ANSWER = b'answer'
524
525 server_context = test_utils.simple_server_sslcontext()
526 client_context = test_utils.simple_client_sslcontext()
527 answer = None
528
529 def client(sock, addr):
530 nonlocal answer
531 sock.settimeout(self.TIMEOUT)
532
533 sock.connect(addr)
534 data = sock.recv_all(len(HELLO_MSG))
535 self.assertEqual(len(data), len(HELLO_MSG))
536
537 sock.start_tls(client_context)
538 sock.sendall(HELLO_MSG)
539 answer = sock.recv_all(len(ANSWER))
540 sock.close()
541
542 class ServerProto(asyncio.Protocol):
543 def __init__(self, on_con, on_con_lost, on_got_hello):
544 self.on_con = on_con
545 self.on_con_lost = on_con_lost
546 self.on_got_hello = on_got_hello
547 self.data = b''
548 self.transport = None
549
550 def connection_made(self, tr):
551 self.transport = tr
552 self.on_con.set_result(tr)
553
554 def replace_transport(self, tr):
555 self.transport = tr
556
557 def data_received(self, data):
558 self.data += data
559 if len(self.data) >= len(HELLO_MSG):
560 self.on_got_hello.set_result(None)
561
562 def connection_lost(self, exc):
563 self.transport = None
564 if exc is None:
565 self.on_con_lost.set_result(None)
566 else:
567 self.on_con_lost.set_exception(exc)
568
569 async def main(proto, on_con, on_con_lost, on_got_hello):
570 tr = await on_con
571 tr.write(HELLO_MSG)
572
573 self.assertEqual(proto.data, b'')
574
575 new_tr = await self.loop.start_tls(
576 tr, proto, server_context,
577 server_side=True,
578 ssl_handshake_timeout=self.TIMEOUT)
579 proto.replace_transport(new_tr)
580
581 await on_got_hello
582 new_tr.write(ANSWER)
583
584 await on_con_lost
585 self.assertEqual(proto.data, HELLO_MSG)
586 new_tr.close()
587
588 async def run_main():
589 on_con = self.loop.create_future()
590 on_con_lost = self.loop.create_future()
591 on_got_hello = self.loop.create_future()
592 proto = ServerProto(on_con, on_con_lost, on_got_hello)
593
594 server = await self.loop.create_server(
595 lambda: proto, '127.0.0.1', 0)
596 addr = server.sockets[0].getsockname()
597
598 with self.tcp_client(lambda sock: client(sock, addr),
599 timeout=self.TIMEOUT):
600 await asyncio.wait_for(
601 main(proto, on_con, on_con_lost, on_got_hello),
602 timeout=self.TIMEOUT)
603
604 server.close()
605 await server.wait_closed()
606 self.assertEqual(answer, ANSWER)
607
608 self.loop.run_until_complete(run_main())
609
610 def test_start_tls_wrong_args(self):
611 async def main():
612 with self.assertRaisesRegex(TypeError, 'SSLContext, got'):
613 await self.loop.start_tls(None, None, None)
614
615 sslctx = test_utils.simple_server_sslcontext()
616 with self.assertRaisesRegex(TypeError, 'is not supported'):
617 await self.loop.start_tls(None, None, sslctx)
618
619 self.loop.run_until_complete(main())
620
621 def test_handshake_timeout(self):
622 # bpo-29970: Check that a connection is aborted if handshake is not
623 # completed in timeout period, instead of remaining open indefinitely
624 client_sslctx = test_utils.simple_client_sslcontext()
625
626 messages = []
627 self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx))
628
629 server_side_aborted = False
630
631 def server(sock):
632 nonlocal server_side_aborted
633 try:
634 sock.recv_all(1024 * 1024)
635 except ConnectionAbortedError:
636 server_side_aborted = True
637 finally:
638 sock.close()
639
640 async def client(addr):
641 await asyncio.wait_for(
642 self.loop.create_connection(
643 asyncio.Protocol,
644 *addr,
645 ssl=client_sslctx,
646 server_hostname='',
647 ssl_handshake_timeout=support.SHORT_TIMEOUT),
648 0.5)
649
650 with self.tcp_server(server,
651 max_clients=1,
652 backlog=1) as srv:
653
654 with self.assertRaises(asyncio.TimeoutError):
655 self.loop.run_until_complete(client(srv.addr))
656
657 self.assertTrue(server_side_aborted)
658
659 # Python issue #23197: cancelling a handshake must not raise an
660 # exception or log an error, even if the handshake failed
661 self.assertEqual(messages, [])
662
663 # The 10s handshake timeout should be cancelled to free related
664 # objects without really waiting for 10s
665 client_sslctx = weakref.ref(client_sslctx)
666 support.gc_collect()
667 self.assertIsNone(client_sslctx())
668
669 def test_create_connection_ssl_slow_handshake(self):
670 client_sslctx = test_utils.simple_client_sslcontext()
671
672 messages = []
673 self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx))
674
675 def server(sock):
676 try:
677 sock.recv_all(1024 * 1024)
678 except ConnectionAbortedError:
679 pass
680 finally:
681 sock.close()
682
683 async def client(addr):
684 reader, writer = await asyncio.open_connection(
685 *addr,
686 ssl=client_sslctx,
687 server_hostname='',
688 ssl_handshake_timeout=1.0)
689
690 with self.tcp_server(server,
691 max_clients=1,
692 backlog=1) as srv:
693
694 with self.assertRaisesRegex(
695 ConnectionAbortedError,
696 r'SSL handshake.*is taking longer'):
697
698 self.loop.run_until_complete(client(srv.addr))
699
700 self.assertEqual(messages, [])
701
702 def test_create_connection_ssl_failed_certificate(self):
703 self.loop.set_exception_handler(lambda loop, ctx: None)
704
705 sslctx = test_utils.simple_server_sslcontext()
706 client_sslctx = test_utils.simple_client_sslcontext(
707 disable_verify=False)
708
709 def server(sock):
710 try:
711 sock.start_tls(
712 sslctx,
713 server_side=True)
714 except ssl.SSLError:
715 pass
716 except OSError:
717 pass
718 finally:
719 sock.close()
720
721 async def client(addr):
722 reader, writer = await asyncio.open_connection(
723 *addr,
724 ssl=client_sslctx,
725 server_hostname='',
726 ssl_handshake_timeout=support.LOOPBACK_TIMEOUT)
727
728 with self.tcp_server(server,
729 max_clients=1,
730 backlog=1) as srv:
731
732 with self.assertRaises(ssl.SSLCertVerificationError):
733 self.loop.run_until_complete(client(srv.addr))
734
735 def test_start_tls_client_corrupted_ssl(self):
736 self.loop.set_exception_handler(lambda loop, ctx: None)
737
738 sslctx = test_utils.simple_server_sslcontext()
739 client_sslctx = test_utils.simple_client_sslcontext()
740
741 def server(sock):
742 orig_sock = sock.dup()
743 try:
744 sock.start_tls(
745 sslctx,
746 server_side=True)
747 sock.sendall(b'A\n')
748 sock.recv_all(1)
749 orig_sock.send(b'please corrupt the SSL connection')
750 except ssl.SSLError:
751 pass
752 finally:
753 orig_sock.close()
754 sock.close()
755
756 async def client(addr):
757 reader, writer = await asyncio.open_connection(
758 *addr,
759 ssl=client_sslctx,
760 server_hostname='')
761
762 self.assertEqual(await reader.readline(), b'A\n')
763 writer.write(b'B')
764 with self.assertRaises(ssl.SSLError):
765 await reader.readline()
766
767 writer.close()
768 return 'OK'
769
770 with self.tcp_server(server,
771 max_clients=1,
772 backlog=1) as srv:
773
774 res = self.loop.run_until_complete(client(srv.addr))
775
776 self.assertEqual(res, 'OK')
777
778
779 @unittest.skipIf(ssl is None, 'No ssl module')
780 class SelectorStartTLSTests(BaseStartTLS, unittest.TestCase):
781
782 def new_loop(self):
783 return asyncio.SelectorEventLoop()
784
785
786 @unittest.skipIf(ssl is None, 'No ssl module')
787 @unittest.skipUnless(hasattr(asyncio, 'ProactorEventLoop'), 'Windows only')
788 class ProactorStartTLSTests(BaseStartTLS, unittest.TestCase):
789
790 def new_loop(self):
791 return asyncio.ProactorEventLoop()
792
793
794 if __name__ == '__main__':
795 unittest.main()