Debian Codegraph @

src/trio/_tests/test_dtls.py

raw
1 from __future__ import annotations
2
3 import random
4 from contextlib import asynccontextmanager
5 from itertools import count
6 from typing import TYPE_CHECKING, NoReturn
7
8 import attrs
9 import pytest
10
11 from trio._tests.pytest_plugin import skip_if_optional_else_raise
12
13 try:
14 import trustme
15 from OpenSSL import SSL
16 except ImportError as error:
17 skip_if_optional_else_raise(error)
18
19
20 import trio
21 import trio.testing
22 from trio import DTLSChannel, DTLSEndpoint
23 from trio.testing._fake_net import FakeNet, UDPPacket
24
25 from .._core._tests.tutil import binds_ipv6, gc_collect_harder, slow
26
27 if TYPE_CHECKING:
28 from collections.abc import AsyncGenerator
29
30 ca = trustme.CA()
31 server_cert = ca.issue_cert("example.com")
32
33
34 @pytest.fixture
35 def server_ctx() -> SSL.Context:
36 ctx = SSL.Context(SSL.DTLS_METHOD)
37 server_cert.configure_cert(ctx)
38 return ctx
39
40
41 def client_ctx_fn() -> SSL.Context:
42 ctx = SSL.Context(SSL.DTLS_METHOD)
43 ca.configure_trust(ctx)
44 return ctx
45
46
47 @pytest.fixture
48 def client_ctx() -> SSL.Context:
49 return client_ctx_fn()
50
51
52 parametrize_ipv6 = pytest.mark.parametrize(
53 "ipv6",
54 [False, pytest.param(True, marks=binds_ipv6)],
55 ids=["ipv4", "ipv6"],
56 )
57
58
59 def endpoint(**kwargs: int | bool) -> DTLSEndpoint:
60 ipv6 = kwargs.pop("ipv6", False)
61 family = trio.socket.AF_INET6 if ipv6 else trio.socket.AF_INET
62 sock = trio.socket.socket(type=trio.socket.SOCK_DGRAM, family=family)
63 return DTLSEndpoint(sock, **kwargs)
64
65
66 @asynccontextmanager
67 async def dtls_echo_server(
68 *,
69 server_ctx: SSL.Context,
70 autocancel: bool = True,
71 mtu: int | None = None,
72 ipv6: bool = False,
73 ) -> AsyncGenerator[tuple[DTLSEndpoint, tuple[str, int]], None]:
74 with endpoint(ipv6=ipv6) as server:
75 localhost = "::1" if ipv6 else "127.0.0.1"
76 await server.socket.bind((localhost, 0))
77 async with trio.open_nursery() as nursery:
78
79 async def echo_handler(dtls_channel: DTLSChannel) -> None:
80 print(
81 "echo handler started: "
82 f"server {dtls_channel.endpoint.socket.getsockname()!r} "
83 f"client {dtls_channel.peer_address!r}",
84 )
85 if mtu is not None:
86 dtls_channel.set_ciphertext_mtu(mtu)
87 try:
88 print("server starting do_handshake")
89 await dtls_channel.do_handshake()
90 print("server finished do_handshake")
91 # no branch for leaving this for loop because we only leave
92 # a channel by cancellation.
93 async for packet in dtls_channel: # pragma: no branch
94 print(f"echoing {packet!r} -> {dtls_channel.peer_address!r}")
95 await dtls_channel.send(packet)
96 except trio.BrokenResourceError: # pragma: no cover
97 print("echo handler channel broken")
98
99 await nursery.start(server.serve, server_ctx, echo_handler)
100
101 yield server, server.socket.getsockname() # noqa: RUF075
102
103 if autocancel:
104 nursery.cancel_scope.cancel()
105
106
107 @parametrize_ipv6
108 async def test_smoke(
109 ipv6: bool, server_ctx: SSL.Context, client_ctx: SSL.Context
110 ) -> None:
111 async with dtls_echo_server(ipv6=ipv6, server_ctx=server_ctx) as (
112 _server_endpoint,
113 address,
114 ):
115 with endpoint(ipv6=ipv6) as client_endpoint:
116 client_channel = client_endpoint.connect(address, client_ctx)
117 with pytest.raises(trio.NeedHandshakeError):
118 client_channel.get_cleartext_mtu()
119
120 await client_channel.do_handshake()
121 await client_channel.send(b"hello")
122 assert await client_channel.receive() == b"hello"
123 await client_channel.send(b"goodbye")
124 assert await client_channel.receive() == b"goodbye"
125
126 with pytest.raises(
127 ValueError,
128 match=r"^openssl doesn't support sending empty DTLS packets$",
129 ):
130 await client_channel.send(b"")
131
132 client_channel.set_ciphertext_mtu(1234)
133 cleartext_mtu_1234 = client_channel.get_cleartext_mtu()
134 client_channel.set_ciphertext_mtu(4321)
135 assert client_channel.get_cleartext_mtu() > cleartext_mtu_1234
136 client_channel.set_ciphertext_mtu(1234)
137 assert client_channel.get_cleartext_mtu() == cleartext_mtu_1234
138
139
140 @slow
141 async def test_handshake_over_terrible_network(
142 autojump_clock: trio.testing.MockClock,
143 server_ctx: SSL.Context,
144 ) -> None:
145 HANDSHAKES = 100
146 r = random.Random(0)
147 fn = FakeNet()
148 fn.enable()
149 # avoid spurious timeouts on slow machines
150 autojump_clock.autojump_threshold = 0.001
151
152 async with dtls_echo_server(server_ctx=server_ctx) as (_, address):
153 async with trio.open_nursery() as nursery:
154
155 async def route_packet(packet: UDPPacket) -> None:
156 while True:
157 op = r.choices(
158 ["deliver", "drop", "dupe", "delay"],
159 weights=[0.7, 0.1, 0.1, 0.1],
160 )[0]
161 print(f"{packet.source} -> {packet.destination}: {op}")
162 if op == "drop":
163 return
164 elif op == "dupe":
165 fn.send_packet(packet)
166 elif op == "delay":
167 await trio.sleep(r.random() * 3)
168 # I wanted to test random packet corruption too, but it turns out
169 # openssl has a bug in the following scenario:
170 #
171 # - client sends ClientHello
172 # - server sends HelloVerifyRequest with cookie -- but cookie is
173 # invalid b/c either the ClientHello or HelloVerifyRequest was
174 # corrupted
175 # - client re-sends ClientHello with invalid cookie
176 # - server replies with new HelloVerifyRequest and correct cookie
177 #
178 # At this point, the client *should* switch to the new, valid
179 # cookie. But OpenSSL doesn't; it stubbornly insists on re-sending
180 # the original, invalid cookie over and over. In theory we could
181 # work around this by detecting cookie changes and starting over
182 # with a whole new SSL object, but (a) it doesn't seem worth it, (b)
183 # when I tried then I ran into another issue where OpenSSL got stuck
184 # in an infinite loop sending alerts over and over, which I didn't
185 # dig into because see (a).
186 #
187 # elif op == "distort":
188 # payload = bytearray(packet.payload)
189 # payload[r.randrange(len(payload))] ^= 1 << r.randrange(8)
190 # packet = attrs.evolve(packet, payload=payload)
191 else:
192 assert op == "deliver"
193 print(
194 f"{packet.source} -> {packet.destination}: delivered"
195 f" {packet.payload.hex()}",
196 )
197 fn.deliver_packet(packet)
198 break
199
200 def route_packet_wrapper(packet: UDPPacket) -> None:
201 try: # noqa: SIM105 # suppressible-exception
202 nursery.start_soon(route_packet, packet)
203 except RuntimeError: # pragma: no cover
204 # We're exiting the nursery, so any remaining packets can just get
205 # dropped
206 pass
207
208 fn.route_packet = route_packet_wrapper # type: ignore[assignment] # TODO: Fix FakeNet typing
209
210 for i in range(HANDSHAKES):
211 print("#" * 80)
212 print("#" * 80)
213 print("#" * 80)
214 with endpoint() as client_endpoint:
215 client = client_endpoint.connect(address, client_ctx_fn())
216 print("client starting do_handshake")
217 await client.do_handshake()
218 print("client finished do_handshake")
219 msg = str(i).encode()
220 # Make multiple attempts to send data, because the network might
221 # drop it
222 while True:
223 with trio.move_on_after(10) as cscope:
224 await client.send(msg)
225 assert await client.receive() == msg
226 if not cscope.cancelled_caught:
227 break
228
229
230 async def test_implicit_handshake(
231 server_ctx: SSL.Context, client_ctx: SSL.Context
232 ) -> None:
233 async with dtls_echo_server(server_ctx=server_ctx) as (_, address):
234 with endpoint() as client_endpoint:
235 client = client_endpoint.connect(address, client_ctx)
236
237 # Implicit handshake
238 await client.send(b"xyz")
239 assert await client.receive() == b"xyz"
240
241
242 async def test_full_duplex(server_ctx: SSL.Context, client_ctx: SSL.Context) -> None:
243 # Tests simultaneous send/receive, and also multiple methods implicitly invoking
244 # do_handshake simultaneously.
245 with endpoint() as server_endpoint, endpoint() as client_endpoint:
246 await server_endpoint.socket.bind(("127.0.0.1", 0))
247 async with trio.open_nursery() as server_nursery:
248
249 async def handler(channel: DTLSChannel) -> None:
250 async with trio.open_nursery() as nursery:
251 nursery.start_soon(channel.send, b"from server")
252 nursery.start_soon(channel.receive)
253
254 await server_nursery.start(server_endpoint.serve, server_ctx, handler)
255
256 client = client_endpoint.connect(
257 server_endpoint.socket.getsockname(),
258 client_ctx,
259 )
260 async with trio.open_nursery() as nursery:
261 nursery.start_soon(client.send, b"from client")
262 nursery.start_soon(client.receive)
263
264 server_nursery.cancel_scope.cancel()
265
266
267 async def test_channel_closing(
268 server_ctx: SSL.Context, client_ctx: SSL.Context
269 ) -> None:
270 async with dtls_echo_server(server_ctx=server_ctx) as (_, address):
271 with endpoint() as client_endpoint:
272 client = client_endpoint.connect(address, client_ctx)
273 await client.do_handshake()
274 client.close()
275
276 with pytest.raises(trio.ClosedResourceError):
277 await client.send(b"abc")
278 with pytest.raises(trio.ClosedResourceError):
279 await client.receive()
280
281 # close is idempotent
282 client.close()
283 # can also aclose
284 await client.aclose()
285
286
287 async def test_serve_exits_cleanly_on_close(server_ctx: SSL.Context) -> None:
288 async with dtls_echo_server(autocancel=False, server_ctx=server_ctx) as (
289 server_endpoint,
290 _address,
291 ):
292 server_endpoint.close()
293 # Testing that the nursery exits even without being cancelled
294 # close is idempotent
295 server_endpoint.close()
296
297
298 async def test_client_multiplex(server_ctx: SSL.Context) -> None:
299 async with (
300 dtls_echo_server(server_ctx=server_ctx) as (_, address1),
301 dtls_echo_server(server_ctx=server_ctx) as (_, address2),
302 ):
303 with endpoint() as client_endpoint:
304 client1 = client_endpoint.connect(address1, client_ctx_fn())
305 client2 = client_endpoint.connect(address2, client_ctx_fn())
306
307 await client1.send(b"abc")
308 await client2.send(b"xyz")
309 assert await client2.receive() == b"xyz"
310 assert await client1.receive() == b"abc"
311
312 client_endpoint.close()
313
314 with pytest.raises(trio.ClosedResourceError):
315 await client1.send(b"xxx")
316 with pytest.raises(trio.ClosedResourceError):
317 await client2.receive()
318 with pytest.raises(trio.ClosedResourceError):
319 client_endpoint.connect(address1, client_ctx_fn())
320
321 async def null_handler(_: object) -> None: # pragma: no cover
322 pass
323
324 async with trio.open_nursery() as nursery:
325 with pytest.raises(trio.ClosedResourceError):
326 await nursery.start(client_endpoint.serve, server_ctx, null_handler)
327
328
329 async def test_dtls_over_dgram_only() -> None:
330 with trio.socket.socket() as s:
331 with pytest.raises(ValueError, match=r"^DTLS requires a SOCK_DGRAM socket$"):
332 DTLSEndpoint(s)
333
334
335 async def test_double_serve(server_ctx: SSL.Context) -> None:
336 async def null_handler(_: object) -> None: # pragma: no cover
337 pass
338
339 with endpoint() as server_endpoint:
340 await server_endpoint.socket.bind(("127.0.0.1", 0))
341 async with trio.open_nursery() as nursery:
342 await nursery.start(server_endpoint.serve, server_ctx, null_handler)
343 with pytest.raises(trio.BusyResourceError):
344 await nursery.start(server_endpoint.serve, server_ctx, null_handler)
345
346 nursery.cancel_scope.cancel()
347
348 async with trio.open_nursery() as nursery:
349 await nursery.start(server_endpoint.serve, server_ctx, null_handler)
350 nursery.cancel_scope.cancel()
351
352
353 async def test_connect_to_non_server(
354 autojump_clock: trio.abc.Clock, client_ctx: SSL.Context
355 ) -> None:
356 fn = FakeNet()
357 fn.enable()
358 with endpoint() as client1, endpoint() as client2:
359 await client1.socket.bind(("127.0.0.1", 0))
360 # This should just time out
361 with trio.move_on_after(100) as cscope:
362 channel = client2.connect(client1.socket.getsockname(), client_ctx)
363 await channel.do_handshake()
364 assert cscope.cancelled_caught
365
366
367 @pytest.mark.parametrize("buffer_size", [10, 20])
368 async def test_incoming_buffer_overflow(
369 autojump_clock: trio.abc.Clock,
370 server_ctx: SSL.Context,
371 client_ctx: SSL.Context,
372 buffer_size: int,
373 ) -> None:
374 fn = FakeNet()
375 fn.enable()
376 async with dtls_echo_server(server_ctx=server_ctx) as (_, address):
377 with endpoint(incoming_packets_buffer=buffer_size) as client_endpoint:
378 assert client_endpoint.incoming_packets_buffer == buffer_size
379 client = client_endpoint.connect(address, client_ctx)
380 for i in range(buffer_size + 15):
381 await client.send(str(i).encode())
382 await trio.sleep(1)
383 stats = client.statistics()
384 assert stats.incoming_packets_dropped_in_trio == 15
385 for i in range(buffer_size):
386 assert await client.receive() == str(i).encode()
387 await client.send(b"buffer clear now")
388 assert await client.receive() == b"buffer clear now"
389
390
391 async def test_server_socket_doesnt_crash_on_garbage(
392 autojump_clock: trio.abc.Clock, server_ctx: SSL.Context
393 ) -> None:
394 fn = FakeNet()
395 fn.enable()
396
397 from trio._dtls import (
398 ContentType,
399 HandshakeFragment,
400 HandshakeType,
401 ProtocolVersion,
402 Record,
403 encode_handshake_fragment,
404 encode_record,
405 )
406
407 client_hello = encode_record(
408 Record(
409 content_type=ContentType.handshake,
410 version=ProtocolVersion.DTLS10,
411 epoch_seqno=0,
412 payload=encode_handshake_fragment(
413 HandshakeFragment(
414 msg_type=HandshakeType.client_hello,
415 msg_len=10,
416 msg_seq=0,
417 frag_offset=0,
418 frag_len=10,
419 frag=bytes(10),
420 ),
421 ),
422 ),
423 )
424
425 client_hello_extended = client_hello + b"\x00"
426 client_hello_short = client_hello[:-1]
427 # cuts off in middle of handshake message header
428 client_hello_really_short = client_hello[:14]
429 client_hello_corrupt_record_len = bytearray(client_hello)
430 client_hello_corrupt_record_len[11] = 0xFF
431
432 client_hello_fragmented = encode_record(
433 Record(
434 content_type=ContentType.handshake,
435 version=ProtocolVersion.DTLS10,
436 epoch_seqno=0,
437 payload=encode_handshake_fragment(
438 HandshakeFragment(
439 msg_type=HandshakeType.client_hello,
440 msg_len=20,
441 msg_seq=0,
442 frag_offset=0,
443 frag_len=10,
444 frag=bytes(10),
445 ),
446 ),
447 ),
448 )
449
450 client_hello_trailing_data_in_record = encode_record(
451 Record(
452 content_type=ContentType.handshake,
453 version=ProtocolVersion.DTLS10,
454 epoch_seqno=0,
455 payload=encode_handshake_fragment(
456 HandshakeFragment(
457 msg_type=HandshakeType.client_hello,
458 msg_len=20,
459 msg_seq=0,
460 frag_offset=0,
461 frag_len=10,
462 frag=bytes(10),
463 ),
464 )
465 + b"\x00",
466 ),
467 )
468
469 handshake_empty = encode_record(
470 Record(
471 content_type=ContentType.handshake,
472 version=ProtocolVersion.DTLS10,
473 epoch_seqno=0,
474 payload=b"",
475 ),
476 )
477
478 client_hello_truncated_in_cookie = encode_record(
479 Record(
480 content_type=ContentType.handshake,
481 version=ProtocolVersion.DTLS10,
482 epoch_seqno=0,
483 payload=bytes(2 + 32 + 1) + b"\xff",
484 ),
485 )
486
487 async with dtls_echo_server(server_ctx=server_ctx) as (_, address):
488 with trio.socket.socket(type=trio.socket.SOCK_DGRAM) as sock:
489 bad_packets: list[bytes | bytearray | memoryview[int]] = [
490 b"",
491 b"xyz",
492 client_hello_extended,
493 client_hello_short,
494 client_hello_really_short,
495 client_hello_corrupt_record_len,
496 client_hello_fragmented,
497 client_hello_trailing_data_in_record,
498 handshake_empty,
499 client_hello_truncated_in_cookie,
500 ]
501
502 for bad_packet in bad_packets:
503 await sock.sendto(bad_packet, address)
504 await trio.sleep(1)
505
506
507 async def test_invalid_cookie_rejected(
508 autojump_clock: trio.abc.Clock, server_ctx: SSL.Context, client_ctx: SSL.Context
509 ) -> None:
510 fn = FakeNet()
511 fn.enable()
512
513 from trio._dtls import BadPacket, decode_client_hello_untrusted
514
515 with trio.CancelScope() as cscope:
516 # the first 11 bytes of ClientHello aren't protected by the cookie, so only test
517 # corrupting bytes after that.
518 offset_to_corrupt = count(11)
519
520 def route_packet(packet: UDPPacket) -> None:
521 try:
522 _, cookie, _ = decode_client_hello_untrusted(packet.payload)
523 except BadPacket:
524 pass
525 else:
526 if len(cookie) != 0:
527 # this is a challenge response packet
528 # let's corrupt the next offset so the handshake should fail
529 payload = bytearray(packet.payload)
530 offset = next(offset_to_corrupt)
531 if offset >= len(payload):
532 # We've tried all offsets. Clamp offset to the end of the
533 # payload, and terminate the test.
534 offset = len(payload) - 1
535 cscope.cancel()
536 payload[offset] ^= 0x01
537 packet = attrs.evolve(packet, payload=bytes(payload))
538
539 fn.deliver_packet(packet)
540
541 fn.route_packet = route_packet # type: ignore[assignment] # TODO: Fix FakeNet typing
542
543 async with dtls_echo_server(server_ctx=server_ctx) as (_, address):
544 while True:
545 with endpoint() as client:
546 channel = client.connect(address, client_ctx)
547 await channel.do_handshake()
548 assert cscope.cancelled_caught
549
550
551 async def test_client_cancels_handshake_and_starts_new_one(
552 autojump_clock: trio.abc.Clock, server_ctx: SSL.Context
553 ) -> None:
554 # if a client disappears during the handshake, and then starts a new handshake from
555 # scratch, then the first handler's channel should fail, and a new handler get
556 # started
557 fn = FakeNet()
558 fn.enable()
559
560 with endpoint() as server, endpoint() as client:
561 await server.socket.bind(("127.0.0.1", 0))
562 async with trio.open_nursery() as nursery:
563 first_time = True
564
565 async def handler(channel: DTLSChannel) -> None:
566 nonlocal first_time
567 if first_time:
568 first_time = False
569 print("handler: first time, cancelling connect")
570 connect_cscope.cancel()
571 await trio.sleep(0.5)
572 print("handler: handshake should fail now")
573 with pytest.raises(trio.BrokenResourceError):
574 await channel.do_handshake()
575 else:
576 print("handler: not first time, sending hello")
577 await channel.send(b"hello")
578
579 await nursery.start(server.serve, server_ctx, handler)
580
581 print("client: starting first connect")
582 with trio.CancelScope() as connect_cscope:
583 channel = client.connect(server.socket.getsockname(), client_ctx_fn())
584 await channel.do_handshake()
585 assert connect_cscope.cancelled_caught
586
587 print("client: starting second connect")
588 channel = client.connect(server.socket.getsockname(), client_ctx_fn())
589 assert await channel.receive() == b"hello"
590
591 # Give handlers a chance to finish
592 await trio.sleep(10)
593 nursery.cancel_scope.cancel()
594
595
596 async def test_swap_client_server(server_ctx: SSL.Context) -> None:
597 with endpoint() as a, endpoint() as b:
598 await a.socket.bind(("127.0.0.1", 0))
599 await b.socket.bind(("127.0.0.1", 0))
600
601 async def echo_handler(channel: DTLSChannel) -> None:
602 async for packet in channel:
603 await channel.send(packet)
604
605 async def crashing_echo_handler(channel: DTLSChannel) -> None:
606 with pytest.raises(trio.BrokenResourceError):
607 await echo_handler(channel)
608
609 async with trio.open_nursery() as nursery:
610 await nursery.start(a.serve, server_ctx, crashing_echo_handler)
611 await nursery.start(b.serve, server_ctx, echo_handler)
612
613 b_to_a = b.connect(a.socket.getsockname(), client_ctx_fn())
614 await b_to_a.send(b"b as client")
615 assert await b_to_a.receive() == b"b as client"
616
617 a_to_b = a.connect(b.socket.getsockname(), client_ctx_fn())
618 await a_to_b.do_handshake()
619 with pytest.raises(trio.BrokenResourceError):
620 await b_to_a.send(b"association broken")
621 await a_to_b.send(b"a as client")
622 assert await a_to_b.receive() == b"a as client"
623
624 nursery.cancel_scope.cancel()
625
626
627 @slow
628 async def test_openssl_retransmit_doesnt_break_stuff(
629 server_ctx: SSL.Context, client_ctx: SSL.Context
630 ) -> None:
631 # can't use autojump_clock here, because the point of the test is to wait for
632 # openssl's built-in retransmit timer to expire, which is hard-coded to use
633 # wall-clock time.
634 fn = FakeNet()
635 fn.enable()
636
637 blackholed = True
638
639 def route_packet(packet: UDPPacket) -> None:
640 if blackholed:
641 print("dropped packet", packet)
642 return
643 print("delivered packet", packet)
644 # packets.append(
645 # scapy.all.IP(
646 # src=packet.source.ip.compressed, dst=packet.destination.ip.compressed
647 # )
648 # / scapy.all.UDP(sport=packet.source.port, dport=packet.destination.port)
649 # / packet.payload
650 # )
651 fn.deliver_packet(packet)
652
653 fn.route_packet = route_packet # type: ignore[assignment] # TODO add type annotations for FakeNet
654
655 async with dtls_echo_server(server_ctx=server_ctx) as (server_endpoint, address):
656 with endpoint() as client_endpoint:
657 async with trio.open_nursery() as nursery:
658
659 async def connecter() -> None:
660 client = client_endpoint.connect(address, client_ctx)
661 await client.do_handshake(initial_retransmit_timeout=1.5)
662 await client.send(b"hi")
663 assert await client.receive() == b"hi"
664
665 nursery.start_soon(connecter)
666
667 # openssl's default timeout is 1 second, so this ensures that it thinks
668 # the timeout has expired
669 await trio.sleep(1.1)
670 # disable blackholing and send a garbage packet to wake up openssl so it
671 # notices the timeout has expired
672 blackholed = False
673 await server_endpoint.socket.sendto(
674 b"xxx",
675 client_endpoint.socket.getsockname(),
676 )
677 # now the client task should finish connecting and exit cleanly
678
679 # scapy.all.wrpcap("/tmp/trace.pcap", packets)
680
681
682 async def test_initial_retransmit_timeout_configuration(
683 autojump_clock: trio.abc.Clock, server_ctx: SSL.Context
684 ) -> None:
685 fn = FakeNet()
686 fn.enable()
687
688 blackholed = True
689
690 def route_packet(packet: UDPPacket) -> None:
691 nonlocal blackholed
692 if blackholed:
693 blackholed = False
694 else:
695 fn.deliver_packet(packet)
696
697 fn.route_packet = route_packet # type: ignore[assignment] # TODO: add type annotations for FakeNet
698
699 async with dtls_echo_server(server_ctx=server_ctx) as (_, address):
700 for t in [1, 2, 4]:
701 with endpoint() as client:
702 before = trio.current_time()
703 blackholed = True
704 channel = client.connect(address, client_ctx_fn())
705 await channel.do_handshake(initial_retransmit_timeout=t)
706 after = trio.current_time()
707 assert after - before == t
708
709
710 async def test_explicit_tiny_mtu_is_respected(
711 server_ctx: SSL.Context, client_ctx: SSL.Context
712 ) -> None:
713 # ClientHello is ~240 bytes, and it can't be fragmented, so our mtu has to
714 # be larger than that. (300 is still smaller than any real network though.)
715 MTU = 300
716
717 fn = FakeNet()
718 fn.enable()
719
720 def route_packet(packet: UDPPacket) -> None:
721 print(f"delivering {packet}")
722 print(f"payload size: {len(packet.payload)}")
723 assert len(packet.payload) <= MTU
724 fn.deliver_packet(packet)
725
726 fn.route_packet = route_packet # type: ignore[assignment] # TODO add type annotations for FakeNet
727
728 async with dtls_echo_server(mtu=MTU, server_ctx=server_ctx) as (_server, address):
729 with endpoint() as client:
730 channel = client.connect(address, client_ctx)
731 channel.set_ciphertext_mtu(MTU)
732 await channel.do_handshake()
733 await channel.send(b"hi")
734 assert await channel.receive() == b"hi"
735
736
737 @parametrize_ipv6
738 async def test_handshake_handles_minimum_network_mtu(
739 ipv6: bool,
740 autojump_clock: trio.abc.Clock,
741 server_ctx: SSL.Context,
742 client_ctx: SSL.Context,
743 ) -> None:
744 # Fake network that has the minimum allowable MTU for whatever protocol we're using.
745 fn = FakeNet()
746 fn.enable()
747
748 mtu = 1280 - 48 if ipv6 else 576 - 28
749
750 def route_packet(packet: UDPPacket) -> None:
751 if len(packet.payload) > mtu:
752 print(f"dropping {packet}")
753 else:
754 print(f"delivering {packet}")
755 fn.deliver_packet(packet)
756
757 fn.route_packet = route_packet # type: ignore[assignment] # TODO: add type annotations for FakeNet
758
759 # See if we can successfully do a handshake -- some of the volleys will get dropped,
760 # and the retransmit logic should detect this and back off the MTU to something
761 # smaller until it succeeds.
762 async with dtls_echo_server(ipv6=ipv6, server_ctx=server_ctx) as (_, address):
763 with endpoint(ipv6=ipv6) as client_endpoint:
764 client = client_endpoint.connect(address, client_ctx)
765 # the handshake mtu backoff shouldn't affect the return value from
766 # get_cleartext_mtu, b/c that's under the user's control via
767 # set_ciphertext_mtu
768 client.set_ciphertext_mtu(9999)
769 await client.send(b"xyz")
770 assert await client.receive() == b"xyz"
771 assert client.get_cleartext_mtu() > 9000 # as vegeta said
772
773
774 @pytest.mark.filterwarnings("always:unclosed DTLS:ResourceWarning")
775 async def test_system_task_cleaned_up_on_gc(client_ctx: SSL.Context) -> None:
776 before_tasks = trio.lowlevel.current_statistics().tasks_living
777
778 # We put this into a sub-function so that everything automatically becomes garbage
779 # when the frame exits. For some reason just doing 'del e' wasn't enough on pypy
780 # with coverage enabled -- I think we were hitting this bug:
781 # https://foss.heptapod.net/pypy/pypy/-/issues/3656
782 async def start_and_forget_endpoint() -> int:
783 e = endpoint()
784
785 # This connection/handshake attempt can't succeed. The only purpose is to force
786 # the endpoint to set up a receive loop.
787 with trio.socket.socket(type=trio.socket.SOCK_DGRAM) as s:
788 await s.bind(("127.0.0.1", 0))
789 c = e.connect(s.getsockname(), client_ctx)
790 async with trio.open_nursery() as nursery:
791 nursery.start_soon(c.do_handshake)
792 await trio.testing.wait_all_tasks_blocked()
793 nursery.cancel_scope.cancel()
794
795 during_tasks = trio.lowlevel.current_statistics().tasks_living
796 return during_tasks
797
798 with pytest.warns(ResourceWarning): # noqa: PT031
799 during_tasks = await start_and_forget_endpoint()
800 await trio.testing.wait_all_tasks_blocked()
801 gc_collect_harder()
802
803 await trio.testing.wait_all_tasks_blocked()
804
805 after_tasks = trio.lowlevel.current_statistics().tasks_living
806 assert before_tasks < during_tasks
807 assert before_tasks == after_tasks
808
809
810 @pytest.mark.filterwarnings("always:unclosed DTLS:ResourceWarning")
811 async def test_gc_before_system_task_starts() -> None:
812 e = endpoint()
813
814 with pytest.warns(ResourceWarning): # noqa: PT031
815 del e
816 gc_collect_harder()
817
818 await trio.testing.wait_all_tasks_blocked()
819
820
821 @pytest.mark.filterwarnings("always:unclosed DTLS:ResourceWarning")
822 async def test_gc_as_packet_received() -> None:
823 fn = FakeNet()
824 fn.enable()
825
826 e = endpoint()
827 await e.socket.bind(("127.0.0.1", 0))
828 e._ensure_receive_loop()
829
830 await trio.testing.wait_all_tasks_blocked()
831
832 with trio.socket.socket(type=trio.socket.SOCK_DGRAM) as s:
833 await s.sendto(b"xxx", e.socket.getsockname())
834 # At this point, the endpoint's receive loop has been marked runnable because it
835 # just received a packet; closing the endpoint socket won't interrupt that. But by
836 # the time it wakes up to process the packet, the endpoint will be gone.
837 with pytest.warns(ResourceWarning): # noqa: PT031
838 del e
839 gc_collect_harder()
840
841
842 @pytest.mark.filterwarnings("always:unclosed DTLS:ResourceWarning")
843 def test_gc_after_trio_exits() -> None:
844 async def main() -> DTLSEndpoint:
845 # We use fakenet just to make sure no real sockets can leak out of the test
846 # case - on pypy somehow the socket was outliving the gc_collect_harder call
847 # below. Since the test is just making sure DTLSEndpoint.__del__ doesn't explode
848 # when called after trio exits, it doesn't need a real socket.
849 fn = FakeNet()
850 fn.enable()
851 return endpoint()
852
853 e = trio.run(main)
854 with pytest.warns(ResourceWarning): # noqa: PT031
855 del e
856 gc_collect_harder()
857
858
859 async def test_already_closed_socket_doesnt_crash() -> None:
860 with endpoint() as e:
861 # We close the socket before checkpointing, so the socket will already be closed
862 # when the system task starts up
863 e.socket.close()
864 # Now give it a chance to start up, and hopefully not crash
865 await trio.testing.wait_all_tasks_blocked()
866
867
868 async def test_socket_closed_while_processing_clienthello(
869 autojump_clock: trio.abc.Clock, server_ctx: SSL.Context, client_ctx: SSL.Context
870 ) -> None:
871 fn = FakeNet()
872 fn.enable()
873
874 # Check what happens if the socket is discovered to be closed when sending a
875 # HelloVerifyRequest, since that has its own sending logic
876 async with dtls_echo_server(server_ctx=server_ctx) as (server, address):
877
878 def route_packet(packet: UDPPacket) -> None:
879 fn.deliver_packet(packet)
880 server.socket.close()
881
882 fn.route_packet = route_packet # type: ignore[assignment] # TODO add type annotations for FakeNet
883
884 with endpoint() as client_endpoint:
885 with trio.move_on_after(10):
886 client = client_endpoint.connect(address, client_ctx)
887 await client.do_handshake()
888
889
890 async def test_association_replaced_while_handshake_running(
891 autojump_clock: trio.abc.Clock, server_ctx: SSL.Context
892 ) -> None:
893 fn = FakeNet()
894 fn.enable()
895
896 def route_packet(packet: UDPPacket) -> None:
897 pass
898
899 fn.route_packet = route_packet # type: ignore[assignment] # TODO: add type annotations for FakeNet
900
901 async with dtls_echo_server(server_ctx=server_ctx) as (_, address):
902 with endpoint() as client_endpoint:
903 # TODO: should this have the same exact client_ctx?
904 c1 = client_endpoint.connect(address, client_ctx_fn())
905 async with trio.open_nursery() as nursery:
906
907 async def doomed_handshake() -> None:
908 with pytest.raises(trio.BrokenResourceError):
909 await c1.do_handshake()
910
911 nursery.start_soon(doomed_handshake)
912
913 await trio.sleep(10)
914
915 client_endpoint.connect(address, client_ctx_fn())
916
917
918 async def test_association_replaced_before_handshake_starts(
919 server_ctx: SSL.Context,
920 ) -> None:
921 fn = FakeNet()
922 fn.enable()
923
924 # This test shouldn't send any packets
925 def route_packet(packet: UDPPacket) -> NoReturn: # pragma: no cover
926 raise AssertionError()
927
928 fn.route_packet = route_packet # type: ignore[assignment] # TODO add type annotations for FakeNet
929
930 async with dtls_echo_server(server_ctx=server_ctx) as (_, address):
931 with endpoint() as client_endpoint:
932 # TODO: should this use the same client_ctx?
933 c1 = client_endpoint.connect(address, client_ctx_fn())
934 client_endpoint.connect(address, client_ctx_fn())
935 with pytest.raises(trio.BrokenResourceError):
936 await c1.do_handshake()
937
938
939 async def test_send_to_closed_local_port(server_ctx: SSL.Context) -> None:
940 # On Windows, sending a UDP packet to a closed local port can cause a weird
941 # ECONNRESET error later, inside the receive task. Make sure we're handling it
942 # properly.
943 async with dtls_echo_server(server_ctx=server_ctx) as (_, address):
944 with endpoint() as client_endpoint:
945 async with trio.open_nursery() as nursery:
946 for i in range(1, 10):
947 channel = client_endpoint.connect(("127.0.0.1", i), client_ctx_fn())
948 nursery.start_soon(channel.do_handshake)
949 channel = client_endpoint.connect(address, client_ctx_fn())
950 await channel.send(b"xxx")
951 assert await channel.receive() == b"xxx"
952 nursery.cancel_scope.cancel()