-
-
Notifications
You must be signed in to change notification settings - Fork 392
Expand file tree
/
Copy pathtest_ssl.py
More file actions
1495 lines (1216 loc) · 54.9 KB
/
test_ssl.py
File metadata and controls
1495 lines (1216 loc) · 54.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import datetime
import os
import socket as stdlib_socket
import ssl
import sys
import threading
from contextlib import asynccontextmanager, contextmanager, suppress
from functools import partial
from ssl import SSLContext
from typing import TYPE_CHECKING, Any, NoReturn, TypeAlias
import pytest
from trio import StapledStream
from trio._tests.pytest_plugin import skip_if_optional_else_raise
from trio.abc import ReceiveStream, SendStream
from trio.testing import MemoryReceiveStream, MemorySendStream
try:
import trustme
from OpenSSL import SSL
except ImportError as error:
skip_if_optional_else_raise(error)
import trio
from .. import _core, socket as tsocket
from .._abc import Stream
from .._core import BrokenResourceError, ClosedResourceError
from .._core._tests.tutil import slow
from .._highlevel_generic import aclose_forcefully
from .._highlevel_open_tcp_stream import open_tcp_stream
from .._highlevel_socket import SocketListener, SocketStream
from .._ssl import NeedHandshakeError, SSLListener, SSLStream, _is_eof
from .._util import ConflictDetector
from ..testing import (
Sequencer,
assert_checkpoints,
check_two_way_stream,
lockstep_stream_pair,
memory_stream_pair,
)
if TYPE_CHECKING:
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
from trio._core import MockClock
from trio._ssl import T_Stream
from .._core._run import CancelScope
# We have two different kinds of echo server fixtures we use for testing. The
# first is a real server written using the stdlib ssl module and blocking
# sockets. It runs in a thread and we talk to it over a real socketpair(), to
# validate interoperability in a semi-realistic setting.
#
# The second is a very weird virtual echo server that lives inside a custom
# Stream class. It lives entirely inside the Python object space; there are no
# operating system calls in it at all. No threads, no I/O, nothing. It's
# 'send_all' call takes encrypted data from a client and feeds it directly into
# the server-side TLS state engine to decrypt, then takes that data, feeds it
# back through to get the encrypted response, and returns it from 'receive_some'. This
# gives us full control and reproducibility. This server is written using
# PyOpenSSL, so that we can trigger renegotiations on demand. It also allows
# us to insert random (virtual) delays, to really exercise all the weird paths
# in SSLStream's state engine.
#
# Both present a certificate for "trio-test-1.example.org".
TRIO_TEST_CA = trustme.CA()
TRIO_TEST_1_CERT = TRIO_TEST_CA.issue_server_cert("trio-test-1.example.org")
SERVER_CTX = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"):
SERVER_CTX.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF
TRIO_TEST_1_CERT.configure_cert(SERVER_CTX)
SERVER_CTX_REQ = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"):
SERVER_CTX_REQ.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF
TRIO_TEST_1_CERT.configure_cert(SERVER_CTX_REQ)
SERVER_CTX_REQ.verify_mode = ssl.CERT_REQUIRED
TRIO_TEST_CA.configure_trust(SERVER_CTX_REQ)
# TLS 1.3 has a lot of changes from previous versions. So we want to run tests
# with both TLS 1.3, and TLS 1.2.
# "tls13" means that we're willing to negotiate TLS 1.3. Usually that's
# what will happen, but the renegotiation tests explicitly force a
# downgrade on the server side. "tls12" means we refuse to negotiate TLS
# 1.3, so we'll almost certainly use TLS 1.2.
@pytest.fixture(scope="module", params=["tls13", "tls12"])
def client_ctx(request: pytest.FixtureRequest) -> ssl.SSLContext:
ctx = ssl.create_default_context()
if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"):
ctx.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF
TRIO_TEST_CA.configure_trust(ctx)
if request.param in ["default", "tls13"]:
return ctx
elif request.param == "tls12":
ctx.maximum_version = ssl.TLSVersion.TLSv1_2
return ctx
else: # pragma: no cover
raise AssertionError()
# The blocking socket server.
def ssl_echo_serve_sync(
sock: stdlib_socket.socket,
*,
# expect_fail = "raise" expects to fail but raises nevertheless, i.e. it is
# like False but does not print; used where the raised exception is checked
# in the main thread.
expect_fail: bool | str = False,
) -> None:
try:
wrapped = SERVER_CTX.wrap_socket(
sock,
server_side=True,
suppress_ragged_eofs=False,
)
with wrapped:
wrapped.do_handshake()
while True:
data = wrapped.recv(4096)
if not data:
# other side has initiated a graceful shutdown; we try to
# respond in kind but it's legal for them to have already
# gone away.
with suppress(BrokenPipeError, ssl.SSLZeroReturnError):
wrapped.unwrap()
return
wrapped.sendall(data)
# This is an obscure workaround for an openssl bug. In server mode, in
# some versions, openssl sends some extra data at the end of do_handshake
# that it shouldn't send. Normally this is harmless, but, if the other
# side shuts down the connection before it reads that data, it might cause
# the OS to report a ECONNREST or even ECONNABORTED (which is just wrong,
# since ECONNABORTED is supposed to mean that connect() failed, but what
# can you do). In this case the other side did nothing wrong, but there's
# no way to recover, so we let it pass, and just cross our fingers its not
# hiding any (other) real bugs. For more details see:
#
# https://github.com/python-trio/trio/issues/1293
#
# Also, this happens frequently but non-deterministically, so we have to
# 'no cover' it to avoid coverage flapping.
except (ConnectionResetError, ConnectionAbortedError): # pragma: no cover
return
except Exception as exc:
if expect_fail == "raise":
raise
elif expect_fail:
print("ssl_echo_serve_sync got error as expected:", exc)
else: # pragma: no cover
print("ssl_echo_serve_sync got unexpected error:", exc)
raise
else:
if expect_fail: # pragma: no cover
raise RuntimeError("failed to fail?")
finally:
sock.close()
# Fixture that gives a raw socket connected to a trio-test-1 echo server
# (running in a thread). Useful for testing making connections with different
# SSLContexts.
@asynccontextmanager
async def ssl_echo_server_raw(
expect_fail: bool | str = False,
) -> AsyncIterator[SocketStream]:
a, b = stdlib_socket.socketpair()
async with trio.open_nursery() as nursery:
# Exiting the 'with a, b' context manager closes the sockets, which
# causes the thread to exit (possibly with an error), which allows the
# nursery context manager to exit too.
with a, b:
nursery.start_soon(
trio.to_thread.run_sync,
partial(ssl_echo_serve_sync, b, expect_fail=expect_fail),
)
yield SocketStream(tsocket.from_stdlib_socket(a))
# Fixture that gives a properly set up SSLStream connected to a trio-test-1
# echo server (running in a thread)
@asynccontextmanager
async def ssl_echo_server(
client_ctx: SSLContext,
expect_fail: bool | str = False,
) -> AsyncIterator[SSLStream[Stream]]:
async with ssl_echo_server_raw(expect_fail=expect_fail) as sock:
yield SSLStream(sock, client_ctx, server_hostname="trio-test-1.example.org")
# The weird in-memory server ... thing.
# Doesn't inherit from Stream because I left out the methods that we don't
# actually need.
# jakkdl: it seems to implement all the abstract methods (now), so I made it inherit
# from Stream for the sake of typechecking.
class PyOpenSSLEchoStream(Stream):
def __init__(
self,
sleeper: Callable[[str], Awaitable[None]] | None = None,
) -> None:
ctx = SSL.Context(SSL.SSLv23_METHOD)
# TLS 1.3 removes renegotiation support. Which is great for them, but
# we still have to support versions before that, and that means we
# need to test renegotiation support, which means we need to force this
# to use a lower version where this test server can trigger
# renegotiations.
from cryptography.hazmat.bindings.openssl.binding import Binding
b = Binding()
ctx.set_options(b.lib.SSL_OP_NO_TLSv1_3)
# Unfortunately there's currently no way to say "use 1.3 or worse", we
# can only disable specific versions. And if the two sides start
# negotiating 1.4 at some point in the future, it *might* mean that
# our tests silently stop working properly. So the next line is a
# tripwire to remind us we need to revisit this stuff in 5 years or
# whatever when the next TLS version is released:
assert not hasattr(SSL, "OP_NO_TLSv1_4")
TRIO_TEST_1_CERT.configure_cert(ctx)
self._conn = SSL.Connection(ctx, None)
self._conn.set_accept_state()
self._lot = _core.ParkingLot()
self._pending_cleartext = bytearray()
self._send_all_conflict_detector = ConflictDetector(
"simultaneous calls to PyOpenSSLEchoStream.send_all",
)
self._receive_some_conflict_detector = ConflictDetector(
"simultaneous calls to PyOpenSSLEchoStream.receive_some",
)
self.sleeper: Callable[[str], Awaitable[None]]
if sleeper is None:
async def no_op_sleeper(_: object) -> None:
return
self.sleeper = no_op_sleeper
else:
self.sleeper = sleeper
async def aclose(self) -> None:
self._conn.bio_shutdown()
def renegotiate_pending(self) -> bool:
return self._conn.renegotiate_pending()
def renegotiate(self) -> None:
# Returns false if a renegotiation is already in progress, meaning
# nothing happens.
assert self._conn.renegotiate()
async def wait_send_all_might_not_block(self) -> None:
with self._send_all_conflict_detector:
await _core.checkpoint()
await _core.checkpoint()
await self.sleeper("wait_send_all_might_not_block")
async def send_all(self, data: bytes) -> None:
print(" --> transport_stream.send_all")
with self._send_all_conflict_detector:
await _core.checkpoint()
await _core.checkpoint()
await self.sleeper("send_all")
self._conn.bio_write(data)
while True:
await self.sleeper("send_all")
try:
data = self._conn.recv(1)
except SSL.ZeroReturnError:
self._conn.shutdown()
print("renegotiations:", self._conn.total_renegotiations())
break
except SSL.WantReadError:
break
else:
self._pending_cleartext += data
self._lot.unpark_all()
await self.sleeper("send_all")
print(" <-- transport_stream.send_all finished")
async def receive_some(self, nbytes: int | None = None) -> bytes:
print(" --> transport_stream.receive_some")
if nbytes is None:
nbytes = 65536 # arbitrary
with self._receive_some_conflict_detector:
try:
await _core.checkpoint()
await _core.checkpoint()
while True:
await self.sleeper("receive_some")
try:
return self._conn.bio_read(nbytes)
except SSL.WantReadError:
# No data in our ciphertext buffer; try to generate
# some.
if self._pending_cleartext:
# We have some cleartext; maybe we can encrypt it
# and then return it.
print(" trying", self._pending_cleartext)
try:
# PyOpenSSL bug: doesn't accept bytearray
# https://github.com/pyca/pyopenssl/issues/621
next_byte = self._pending_cleartext[0:1]
self._conn.send(bytes(next_byte))
# Apparently this next bit never gets hit in the
# test suite, but it's not an interesting omission
# so let's pragma it.
except SSL.WantReadError: # pragma: no cover
# We didn't manage to send the cleartext (and
# in particular we better leave it there to
# try again, due to openssl's retry
# semantics), but it's possible we pushed a
# renegotiation forward and *now* we have data
# to send.
try:
return self._conn.bio_read(nbytes)
except SSL.WantReadError:
# Nope. We're just going to have to wait
# for someone to call send_all() to give
# use more data.
print("parking (a)")
await self._lot.park()
else:
# We successfully sent that byte, so we don't
# have to again.
del self._pending_cleartext[0:1]
else:
# no pending cleartext; nothing to do but wait for
# someone to call send_all
print("parking (b)")
await self._lot.park()
finally:
await self.sleeper("receive_some")
print(" <-- transport_stream.receive_some finished")
async def test_PyOpenSSLEchoStream_gives_resource_busy_errors() -> None:
# Make sure that PyOpenSSLEchoStream complains if two tasks call send_all
# at the same time, or ditto for receive_some. The tricky cases where SSLStream
# might accidentally do this are during renegotiation, which we test using
# PyOpenSSLEchoStream, so this makes sure that if we do have a bug then
# PyOpenSSLEchoStream will notice and complain.
async def do_test(
func1: str,
args1: tuple[object, ...],
func2: str,
args2: tuple[object, ...],
) -> None:
s = PyOpenSSLEchoStream()
with pytest.RaisesGroup(
pytest.RaisesExc(_core.BusyResourceError, match="simultaneous")
):
async with _core.open_nursery() as nursery:
nursery.start_soon(getattr(s, func1), *args1)
nursery.start_soon(getattr(s, func2), *args2)
await do_test("send_all", (b"x",), "send_all", (b"x",))
await do_test("send_all", (b"x",), "wait_send_all_might_not_block", ())
await do_test(
"wait_send_all_might_not_block",
(),
"wait_send_all_might_not_block",
(),
)
await do_test("receive_some", (1,), "receive_some", (1,))
@contextmanager
def virtual_ssl_echo_server(
client_ctx: SSLContext,
sleeper: Callable[[str], Awaitable[None]] | None = None,
) -> Iterator[SSLStream[PyOpenSSLEchoStream]]:
fakesock = PyOpenSSLEchoStream(sleeper=sleeper)
yield SSLStream(fakesock, client_ctx, server_hostname="trio-test-1.example.org")
def ssl_wrap_pair( # type: ignore[explicit-any]
client_ctx: SSLContext,
client_transport: T_Stream,
server_transport: T_Stream,
*,
client_kwargs: dict[str, Any] | None = None,
server_kwargs: dict[str, Any] | None = None,
) -> tuple[SSLStream[T_Stream], SSLStream[T_Stream]]:
if server_kwargs is None:
server_kwargs = {}
if client_kwargs is None:
client_kwargs = {}
client_ssl = SSLStream(
client_transport,
client_ctx,
server_hostname="trio-test-1.example.org",
**client_kwargs,
)
server_ssl = SSLStream(
server_transport,
SERVER_CTX,
server_side=True,
**server_kwargs,
)
return client_ssl, server_ssl
MemoryStapledStream: TypeAlias = StapledStream[MemorySendStream, MemoryReceiveStream]
def ssl_memory_stream_pair(
client_ctx: SSLContext,
client_kwargs: dict[str, str | bytes | bool | None] | None = None,
server_kwargs: dict[str, str | bytes | bool | None] | None = None,
) -> tuple[
SSLStream[MemoryStapledStream],
SSLStream[MemoryStapledStream],
]:
client_transport, server_transport = memory_stream_pair()
return ssl_wrap_pair(
client_ctx,
client_transport,
server_transport,
client_kwargs=client_kwargs,
server_kwargs=server_kwargs,
)
MyStapledStream: TypeAlias = StapledStream[SendStream, ReceiveStream]
def ssl_lockstep_stream_pair(
client_ctx: SSLContext,
client_kwargs: dict[str, str | bytes | bool | None] | None = None,
server_kwargs: dict[str, str | bytes | bool | None] | None = None,
) -> tuple[
SSLStream[MyStapledStream],
SSLStream[MyStapledStream],
]:
client_transport, server_transport = lockstep_stream_pair()
return ssl_wrap_pair(
client_ctx,
client_transport,
server_transport,
client_kwargs=client_kwargs,
server_kwargs=server_kwargs,
)
# Simple smoke test for handshake/send/receive/shutdown talking to a
# synchronous server, plus make sure that we do the bare minimum of
# certificate checking (even though this is really Python's responsibility)
async def test_ssl_client_basics(client_ctx: SSLContext) -> None:
# Everything OK
async with ssl_echo_server(client_ctx) as s:
assert not s.server_side
await s.send_all(b"x")
assert await s.receive_some(1) == b"x"
await s.aclose()
# Didn't configure the CA file, should fail
# Check that the server receives TLSV1_ALERT_UNKNOWN_CA
# rather than choking with UNEXPECTED_EOF_WHILE_READING.
with pytest.RaisesGroup(
pytest.RaisesExc(ssl.SSLError, match="TLSV1_ALERT_UNKNOWN_CA")
):
async with ssl_echo_server_raw(expect_fail="raise") as sock:
bad_client_ctx = ssl.create_default_context()
s = SSLStream(
sock, bad_client_ctx, server_hostname="trio-test-1.example.org"
)
assert not s.server_side
with pytest.raises(BrokenResourceError) as excinfo1:
await s.send_all(b"x")
assert isinstance(excinfo1.value.__cause__, ssl.SSLError)
# Trusted CA, but wrong host name
# Check that the server receives SSLV3_ALERT_BAD_CERTIFICATE
# rather than choking with UNEXPECTED_EOF_WHILE_READING.
with pytest.RaisesGroup(
pytest.RaisesExc(ssl.SSLError, match="SSLV3_ALERT_BAD_CERTIFICATE")
):
async with ssl_echo_server_raw(expect_fail="raise") as sock:
s = SSLStream(sock, client_ctx, server_hostname="trio-test-2.example.org")
assert not s.server_side
with pytest.raises(BrokenResourceError) as excinfo2:
await s.send_all(b"x")
assert isinstance(excinfo2.value.__cause__, ssl.CertificateError)
async def test_ssl_server_basics(client_ctx: SSLContext) -> None:
a, b = stdlib_socket.socketpair()
with a, b:
server_sock = tsocket.from_stdlib_socket(b)
server_transport = SSLStream(
SocketStream(server_sock),
SERVER_CTX,
server_side=True,
)
assert server_transport.server_side
def client() -> None:
with client_ctx.wrap_socket(
a,
server_hostname="trio-test-1.example.org",
) as client_sock:
client_sock.sendall(b"x")
assert client_sock.recv(1) == b"y"
client_sock.sendall(b"z")
client_sock.unwrap()
t = threading.Thread(target=client)
t.start()
assert await server_transport.receive_some(1) == b"x"
await server_transport.send_all(b"y")
assert await server_transport.receive_some(1) == b"z"
assert await server_transport.receive_some(1) == b""
await server_transport.aclose()
t.join()
async def test_client_certificate(client_ctx: SSLContext) -> None:
# A valid client certificate
client_cert = TRIO_TEST_CA.issue_cert("[email protected]")
client_cert.configure_cert(client_ctx)
a, b = stdlib_socket.socketpair()
with a, b:
server_sock = tsocket.from_stdlib_socket(b)
server_transport = SSLStream(
SocketStream(server_sock),
SERVER_CTX_REQ,
server_side=True,
)
assert server_transport.server_side
def client() -> None:
with client_ctx.wrap_socket(
a,
server_hostname="trio-test-1.example.org",
) as client_sock:
client_sock.sendall(b"x")
assert client_sock.recv(1) == b"y"
client_sock.sendall(b"z")
client_sock.unwrap()
t = threading.Thread(target=client)
t.start()
assert await server_transport.receive_some(1) == b"x"
await server_transport.send_all(b"y")
assert await server_transport.receive_some(1) == b"z"
assert await server_transport.receive_some(1) == b""
await server_transport.aclose()
t.join()
# An expired client certificate: this should fail
client_cert = TRIO_TEST_CA.issue_cert(
"[email protected]", not_after=datetime.datetime.now(datetime.timezone.utc)
)
client_cert.configure_cert(client_ctx)
a, b = stdlib_socket.socketpair()
with a, b:
server_sock = tsocket.from_stdlib_socket(b)
server_transport = SSLStream(
SocketStream(server_sock),
SERVER_CTX_REQ,
server_side=True,
)
assert server_transport.server_side
# Prior to the changes to _ssl.py made in this commit, this test hangs
# without the timeout introduced below. With the new _ssl.py,
# pytest.raises in the client successfully catches the error; the
# thread therefore finishes, setting client_done. With the old
# _ssl.py, the thread hangs and will be abandoned after the timeout,
# leaving client_done unset and thereby triggering the assertion error.
# (The general timeout imposed on tests is not only too long for this,
# but it also doesn't work, because the thread is not abandoned.)
#
# Potential problem: determinism. It is highly unlikely but I guess it
# could happen that the client thread doesn't get from .recv to
# client_done.set in the allotted time, resulting in a false negative.
client_done = trio.Event()
def client() -> None:
# For TLS 1.3, pytest.raises is ok around .sendall below, but it
# needs to be here for TLS 1.2. (Is this because TLS 1.2 verifies
# client-side certificates during the initial handshake?)
with pytest.raises(ssl.SSLError, match="SSLV3_ALERT_CERTIFICATE_EXPIRED"):
with client_ctx.wrap_socket(
a,
server_hostname="trio-test-1.example.org",
) as client_sock:
client_sock.sendall(b"x")
client_sock.recv(1)
trio.from_thread.run_sync(client_done.set)
async with trio.open_nursery() as nursery:
nursery.start_soon(
partial(trio.to_thread.run_sync, client, abandon_on_cancel=True)
)
with pytest.raises(BrokenResourceError) as excinfo:
assert await server_transport.receive_some(1) == b"x"
assert isinstance(excinfo.value.__cause__, ssl.SSLError)
assert excinfo.value.__cause__.reason == "CERTIFICATE_VERIFY_FAILED"
# This timeout shouldn't affect the execution time of the test on
# healthy code.
with trio.move_on_after(0.1):
await client_done.wait()
nursery.cancel_scope.cancel()
assert client_done.is_set(), "The client thread is hanging"
async def test_attributes(client_ctx: SSLContext) -> None:
async with ssl_echo_server_raw(expect_fail=True) as sock:
good_ctx = client_ctx
bad_ctx = ssl.create_default_context()
s = SSLStream(sock, good_ctx, server_hostname="trio-test-1.example.org")
assert s.transport_stream is sock
# Forwarded attribute getting
assert s.context is good_ctx
assert s.server_side == False # noqa
assert s.server_hostname == "trio-test-1.example.org"
with pytest.raises(AttributeError):
s.asfdasdfsa # noqa: B018 # "useless expression"
# __dir__
assert "transport_stream" in dir(s)
assert "context" in dir(s)
# Setting the attribute goes through to the underlying object
# most attributes on SSLObject are read-only
with pytest.raises(AttributeError):
s.server_side = True
with pytest.raises(AttributeError):
s.server_hostname = "asdf"
# but .context is *not*. Check that we forward attribute setting by
# making sure that after we set the bad context our handshake indeed
# fails:
s.context = bad_ctx
assert s.context is bad_ctx
with pytest.raises(BrokenResourceError) as excinfo:
await s.do_handshake()
assert isinstance(excinfo.value.__cause__, ssl.SSLError)
# Note: this test fails horribly if we force TLS 1.2 and trigger a
# renegotiation at the beginning (e.g. by switching to the pyopenssl
# server). Usually the client crashes in SSLObject.write with "UNEXPECTED
# RECORD"; sometimes we get something more exotic like a SyscallError. This is
# odd because openssl isn't doing any syscalls, but so it goes. After lots of
# websearching I'm pretty sure this is due to a bug in OpenSSL, where it just
# can't reliably handle full-duplex communication combined with
# renegotiation. Nice, eh?
#
# https://rt.openssl.org/Ticket/Display.html?id=3712
# https://rt.openssl.org/Ticket/Display.html?id=2481
# http://openssl.6102.n7.nabble.com/TLS-renegotiation-failure-on-receiving-application-data-during-handshake-td48127.html
# https://stackoverflow.com/questions/18728355/ssl-renegotiation-with-full-duplex-socket-communication
#
# In some variants of this test (maybe only against the java server?) I've
# also seen cases where our send_all blocks waiting to write, and then our receive_some
# also blocks waiting to write, and they never wake up again. It looks like
# some kind of deadlock. I suspect there may be an issue where we've filled up
# the send buffers, and the remote side is trying to handle the renegotiation
# from inside a write() call, so it has a problem: there's all this application
# data clogging up the pipe, but it can't process and return it to the
# application because it's in write(), and it doesn't want to buffer infinite
# amounts of data, and... actually I guess those are the only two choices.
#
# NSS even documents that you shouldn't try to do a renegotiation except when
# the connection is idle:
#
# https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/SSL_functions/sslfnc.html#1061582
#
# I begin to see why HTTP/2 forbids renegotiation and TLS 1.3 removes it...
async def test_full_duplex_basics(client_ctx: SSLContext) -> None:
CHUNKS = 30
CHUNK_SIZE = 32768
EXPECTED = CHUNKS * CHUNK_SIZE
sent = bytearray()
received = bytearray()
async def sender(s: Stream) -> None:
nonlocal sent
for i in range(CHUNKS):
print(i)
chunk = bytes([i] * CHUNK_SIZE)
sent += chunk
await s.send_all(chunk)
async def receiver(s: Stream) -> None:
nonlocal received
while len(received) < EXPECTED:
chunk = await s.receive_some(CHUNK_SIZE // 2)
received += chunk
async with ssl_echo_server(client_ctx) as s:
async with _core.open_nursery() as nursery:
nursery.start_soon(sender, s)
nursery.start_soon(receiver, s)
# And let's have some doing handshakes too, everyone
# simultaneously
nursery.start_soon(s.do_handshake)
nursery.start_soon(s.do_handshake)
await s.aclose()
assert len(sent) == len(received) == EXPECTED
assert sent == received
async def test_renegotiation_simple(client_ctx: SSLContext) -> None:
with virtual_ssl_echo_server(client_ctx) as s:
await s.do_handshake()
s.transport_stream.renegotiate()
await s.send_all(b"a")
assert await s.receive_some(1) == b"a"
# Have to send some more data back and forth to make sure the
# renegotiation is finished before shutting down the
# connection... otherwise openssl raises an error. I think this is a
# bug in openssl but what can ya do.
await s.send_all(b"b")
assert await s.receive_some(1) == b"b"
await s.aclose()
@slow
async def test_renegotiation_randomized(
mock_clock: MockClock,
client_ctx: SSLContext,
) -> None:
# The only blocking things in this function are our random sleeps, so 0 is
# a good threshold.
mock_clock.autojump_threshold = 0
import random
r = random.Random(0)
async def sleeper(_: object) -> None:
await trio.sleep(r.uniform(0, 10))
async def clear() -> None:
while s.transport_stream.renegotiate_pending():
with assert_checkpoints():
await send(b"-")
with assert_checkpoints():
await expect(b"-")
print("-- clear --")
async def send(byte: bytes) -> None:
await s.transport_stream.sleeper("outer send")
print("calling SSLStream.send_all", byte)
with assert_checkpoints():
await s.send_all(byte)
async def expect(expected: bytes) -> None:
await s.transport_stream.sleeper("expect")
print("calling SSLStream.receive_some, expecting", expected)
assert len(expected) == 1
with assert_checkpoints():
assert await s.receive_some(1) == expected
with virtual_ssl_echo_server(client_ctx, sleeper=sleeper) as s:
await s.do_handshake()
await send(b"a")
s.transport_stream.renegotiate()
await expect(b"a")
await clear()
for i in range(100):
b1 = bytes([i % 0xFF])
b2 = bytes([(2 * i) % 0xFF])
s.transport_stream.renegotiate()
async with _core.open_nursery() as nursery:
nursery.start_soon(send, b1)
nursery.start_soon(expect, b1)
async with _core.open_nursery() as nursery:
nursery.start_soon(expect, b2)
nursery.start_soon(send, b2)
await clear()
for i in range(100):
b1 = bytes([i % 0xFF])
b2 = bytes([(2 * i) % 0xFF])
await send(b1)
s.transport_stream.renegotiate()
await expect(b1)
async with _core.open_nursery() as nursery:
nursery.start_soon(expect, b2)
nursery.start_soon(send, b2)
await clear()
# Checking that wait_send_all_might_not_block and receive_some don't
# conflict:
# 1) Set up a situation where expect (receive_some) is blocked sending,
# and wait_send_all_might_not_block comes in.
# Our receive_some() call will get stuck when it hits send_all
async def sleeper_with_slow_send_all(method: str) -> None:
if method == "send_all":
# ignore ASYNC116, not sleep_forever, trying to test a large but finite sleep
await trio.sleep(100000) # noqa: ASYNC116
# And our wait_send_all_might_not_block call will give it time to get
# stuck, and then start
async def sleep_then_wait_writable() -> None:
await trio.sleep(1000)
await s.wait_send_all_might_not_block()
with virtual_ssl_echo_server(client_ctx, sleeper=sleeper_with_slow_send_all) as s:
await send(b"x")
s.transport_stream.renegotiate()
async with _core.open_nursery() as nursery:
nursery.start_soon(expect, b"x")
nursery.start_soon(sleep_then_wait_writable)
await clear()
await s.aclose()
# 2) Same, but now wait_send_all_might_not_block is stuck when
# receive_some tries to send.
async def sleeper_with_slow_wait_writable_and_expect(method: str) -> None:
if method == "wait_send_all_might_not_block":
# ignore ASYNC116, not sleep_forever, trying to test a large but finite sleep
await trio.sleep(100000) # noqa: ASYNC116
elif method == "expect":
await trio.sleep(1000)
with virtual_ssl_echo_server(
client_ctx,
sleeper=sleeper_with_slow_wait_writable_and_expect,
) as s:
await send(b"x")
s.transport_stream.renegotiate()
async with _core.open_nursery() as nursery:
nursery.start_soon(expect, b"x")
nursery.start_soon(s.wait_send_all_might_not_block)
await clear()
await s.aclose()
async def test_resource_busy_errors(client_ctx: SSLContext) -> None:
S: TypeAlias = trio.SSLStream[
trio.StapledStream[trio.abc.SendStream, trio.abc.ReceiveStream]
]
async def do_send_all(s: S) -> None:
with assert_checkpoints():
await s.send_all(b"x")
async def do_receive_some(s: S) -> None:
with assert_checkpoints():
await s.receive_some(1)
async def do_wait_send_all_might_not_block(s: S) -> None:
with assert_checkpoints():
await s.wait_send_all_might_not_block()
async def do_test(
func1: Callable[[S], Awaitable[None]],
func2: Callable[[S], Awaitable[None]],
) -> None:
s, _ = ssl_lockstep_stream_pair(client_ctx)
with pytest.RaisesGroup(
pytest.RaisesExc(_core.BusyResourceError, match="another task")
):
async with _core.open_nursery() as nursery:
nursery.start_soon(func1, s)
nursery.start_soon(func2, s)
await do_test(do_send_all, do_send_all)
await do_test(do_receive_some, do_receive_some)
await do_test(do_send_all, do_wait_send_all_might_not_block)
await do_test(do_wait_send_all_might_not_block, do_wait_send_all_might_not_block)
async def test_wait_writable_calls_underlying_wait_writable() -> None:
record = []
class NotAStream(Stream):
async def wait_send_all_might_not_block(self) -> None:
record.append("ok")
# define methods that are abstract in Stream
async def aclose(self) -> None:
raise AssertionError("Should not get called") # pragma: no cover
async def receive_some(self, max_bytes: int | None = None) -> bytes | bytearray:
raise AssertionError("Should not get called") # pragma: no cover
async def send_all(self, data: bytes | bytearray | memoryview) -> None:
raise AssertionError("Should not get called") # pragma: no cover
ctx = ssl.create_default_context()
s = SSLStream(NotAStream(), ctx, server_hostname="x")
await s.wait_send_all_might_not_block()
assert record == ["ok"]
@pytest.mark.skipif(
os.name == "nt" and sys.version_info >= (3, 10),
reason="frequently fails on Windows + Python 3.10",
)
async def test_checkpoints(client_ctx: SSLContext) -> None:
async with ssl_echo_server(client_ctx) as s:
with assert_checkpoints():
await s.do_handshake()
with assert_checkpoints():
await s.do_handshake()
with assert_checkpoints():
await s.wait_send_all_might_not_block()
with assert_checkpoints():
await s.send_all(b"xxx")
with assert_checkpoints():
await s.receive_some(1)
# These receive_some's in theory could return immediately, because the
# "xxx" was sent in a single record and after the first
# receive_some(1) the rest are sitting inside the SSLObject's internal
# buffers.
with assert_checkpoints():
await s.receive_some(1)
with assert_checkpoints():
await s.receive_some(1)
with assert_checkpoints():
await s.unwrap()
async with ssl_echo_server(client_ctx) as s:
await s.do_handshake()
with assert_checkpoints():
await s.aclose()
async def test_send_all_empty_string(client_ctx: SSLContext) -> None:
async with ssl_echo_server(client_ctx) as s:
await s.do_handshake()
# underlying SSLObject interprets writing b"" as indicating an EOF,
# for some reason. Make sure we don't inherit this.
with assert_checkpoints():
await s.send_all(b"")
with assert_checkpoints():
await s.send_all(b"")
await s.send_all(b"x")
assert await s.receive_some(1) == b"x"
await s.aclose()
@pytest.mark.parametrize("https_compatible", [False, True])
async def test_SSLStream_generic(
client_ctx: SSLContext,
https_compatible: bool,
) -> None:
async def stream_maker() -> tuple[
SSLStream[MemoryStapledStream],
SSLStream[MemoryStapledStream],
]:
return ssl_memory_stream_pair(
client_ctx,
client_kwargs={"https_compatible": https_compatible},
server_kwargs={"https_compatible": https_compatible},
)
async def clogged_stream_maker() -> tuple[
SSLStream[MyStapledStream],
SSLStream[MyStapledStream],