| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import os |
| 4 |
import socket as stdlib_socket |
| 5 |
import ssl |
| 6 |
import sys |
| 7 |
import threading |
| 8 |
from contextlib import asynccontextmanager, contextmanager, suppress |
| 9 |
from functools import partial |
| 10 |
from ssl import SSLContext |
| 11 |
from typing import TYPE_CHECKING, Any, NoReturn, TypeAlias |
| 12 |
|
| 13 |
import pytest |
| 14 |
|
| 15 |
from trio import StapledStream |
| 16 |
from trio._tests.pytest_plugin import skip_if_optional_else_raise |
| 17 |
from trio.abc import ReceiveStream, SendStream |
| 18 |
from trio.testing import MemoryReceiveStream, MemorySendStream |
| 19 |
|
| 20 |
try: |
| 21 |
import trustme |
| 22 |
from OpenSSL import SSL |
| 23 |
except ImportError as error: |
| 24 |
skip_if_optional_else_raise(error) |
| 25 |
|
| 26 |
import trio |
| 27 |
|
| 28 |
from .. import _core, socket as tsocket |
| 29 |
from .._abc import Stream |
| 30 |
from .._core import BrokenResourceError, ClosedResourceError |
| 31 |
from .._core._tests.tutil import slow |
| 32 |
from .._highlevel_generic import aclose_forcefully |
| 33 |
from .._highlevel_open_tcp_stream import open_tcp_stream |
| 34 |
from .._highlevel_socket import SocketListener, SocketStream |
| 35 |
from .._ssl import NeedHandshakeError, SSLListener, SSLStream, _is_eof |
| 36 |
from .._util import ConflictDetector |
| 37 |
from ..testing import ( |
| 38 |
Sequencer, |
| 39 |
assert_checkpoints, |
| 40 |
check_two_way_stream, |
| 41 |
lockstep_stream_pair, |
| 42 |
memory_stream_pair, |
| 43 |
) |
| 44 |
|
| 45 |
if TYPE_CHECKING: |
| 46 |
from collections.abc import AsyncIterator, Awaitable, Callable, Iterator |
| 47 |
|
| 48 |
from trio._core import MockClock |
| 49 |
from trio._ssl import T_Stream |
| 50 |
|
| 51 |
from .._core._run import CancelScope |
| 52 |
|
| 53 |
# We have two different kinds of echo server fixtures we use for testing. The |
| 54 |
# first is a real server written using the stdlib ssl module and blocking |
| 55 |
# sockets. It runs in a thread and we talk to it over a real socketpair(), to |
| 56 |
# validate interoperability in a semi-realistic setting. |
| 57 |
# |
| 58 |
# The second is a very weird virtual echo server that lives inside a custom |
| 59 |
# Stream class. It lives entirely inside the Python object space; there are no |
| 60 |
# operating system calls in it at all. No threads, no I/O, nothing. It's |
| 61 |
# 'send_all' call takes encrypted data from a client and feeds it directly into |
| 62 |
# the server-side TLS state engine to decrypt, then takes that data, feeds it |
| 63 |
# back through to get the encrypted response, and returns it from 'receive_some'. This |
| 64 |
# gives us full control and reproducibility. This server is written using |
| 65 |
# PyOpenSSL, so that we can trigger renegotiations on demand. It also allows |
| 66 |
# us to insert random (virtual) delays, to really exercise all the weird paths |
| 67 |
# in SSLStream's state engine. |
| 68 |
# |
| 69 |
# Both present a certificate for "trio-test-1.example.org". |
| 70 |
|
| 71 |
TRIO_TEST_CA = trustme.CA() |
| 72 |
TRIO_TEST_1_CERT = TRIO_TEST_CA.issue_server_cert("trio-test-1.example.org") |
| 73 |
|
| 74 |
SERVER_CTX = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) |
| 75 |
if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"): |
| 76 |
SERVER_CTX.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF |
| 77 |
|
| 78 |
TRIO_TEST_1_CERT.configure_cert(SERVER_CTX) |
| 79 |
|
| 80 |
|
| 81 |
# TLS 1.3 has a lot of changes from previous versions. So we want to run tests |
| 82 |
# with both TLS 1.3, and TLS 1.2. |
| 83 |
# "tls13" means that we're willing to negotiate TLS 1.3. Usually that's |
| 84 |
# what will happen, but the renegotiation tests explicitly force a |
| 85 |
# downgrade on the server side. "tls12" means we refuse to negotiate TLS |
| 86 |
# 1.3, so we'll almost certainly use TLS 1.2. |
| 87 |
@pytest.fixture(scope="module", params=["tls13", "tls12"]) |
| 88 |
def client_ctx(request: pytest.FixtureRequest) -> ssl.SSLContext: |
| 89 |
ctx = ssl.create_default_context() |
| 90 |
|
| 91 |
if hasattr(ssl, "OP_IGNORE_UNEXPECTED_EOF"): |
| 92 |
ctx.options &= ~ssl.OP_IGNORE_UNEXPECTED_EOF |
| 93 |
|
| 94 |
TRIO_TEST_CA.configure_trust(ctx) |
| 95 |
if request.param in ["default", "tls13"]: |
| 96 |
return ctx |
| 97 |
elif request.param == "tls12": |
| 98 |
ctx.maximum_version = ssl.TLSVersion.TLSv1_2 |
| 99 |
return ctx |
| 100 |
else: # pragma: no cover |
| 101 |
raise AssertionError() |
| 102 |
|
| 103 |
|
| 104 |
# The blocking socket server. |
| 105 |
def ssl_echo_serve_sync( |
| 106 |
sock: stdlib_socket.socket, |
| 107 |
*, |
| 108 |
expect_fail: bool = False, |
| 109 |
) -> None: |
| 110 |
try: |
| 111 |
wrapped = SERVER_CTX.wrap_socket( |
| 112 |
sock, |
| 113 |
server_side=True, |
| 114 |
suppress_ragged_eofs=False, |
| 115 |
) |
| 116 |
with wrapped: |
| 117 |
wrapped.do_handshake() |
| 118 |
while True: |
| 119 |
data = wrapped.recv(4096) |
| 120 |
if not data: |
| 121 |
# other side has initiated a graceful shutdown; we try to |
| 122 |
# respond in kind but it's legal for them to have already |
| 123 |
# gone away. |
| 124 |
with suppress(BrokenPipeError, ssl.SSLZeroReturnError): |
| 125 |
wrapped.unwrap() |
| 126 |
return |
| 127 |
wrapped.sendall(data) |
| 128 |
# This is an obscure workaround for an openssl bug. In server mode, in |
| 129 |
# some versions, openssl sends some extra data at the end of do_handshake |
| 130 |
# that it shouldn't send. Normally this is harmless, but, if the other |
| 131 |
# side shuts down the connection before it reads that data, it might cause |
| 132 |
# the OS to report a ECONNREST or even ECONNABORTED (which is just wrong, |
| 133 |
# since ECONNABORTED is supposed to mean that connect() failed, but what |
| 134 |
# can you do). In this case the other side did nothing wrong, but there's |
| 135 |
# no way to recover, so we let it pass, and just cross our fingers its not |
| 136 |
# hiding any (other) real bugs. For more details see: |
| 137 |
# |
| 138 |
# https://github.com/python-trio/trio/issues/1293 |
| 139 |
# |
| 140 |
# Also, this happens frequently but non-deterministically, so we have to |
| 141 |
# 'no cover' it to avoid coverage flapping. |
| 142 |
except (ConnectionResetError, ConnectionAbortedError): # pragma: no cover |
| 143 |
return |
| 144 |
except Exception as exc: |
| 145 |
if expect_fail: |
| 146 |
print("ssl_echo_serve_sync got error as expected:", exc) |
| 147 |
else: # pragma: no cover |
| 148 |
print("ssl_echo_serve_sync got unexpected error:", exc) |
| 149 |
raise |
| 150 |
else: |
| 151 |
if expect_fail: # pragma: no cover |
| 152 |
raise RuntimeError("failed to fail?") |
| 153 |
finally: |
| 154 |
sock.close() |
| 155 |
|
| 156 |
|
| 157 |
# Fixture that gives a raw socket connected to a trio-test-1 echo server |
| 158 |
# (running in a thread). Useful for testing making connections with different |
| 159 |
# SSLContexts. |
| 160 |
@asynccontextmanager |
| 161 |
async def ssl_echo_server_raw(expect_fail: bool = False) -> AsyncIterator[SocketStream]: |
| 162 |
a, b = stdlib_socket.socketpair() |
| 163 |
async with trio.open_nursery() as nursery: |
| 164 |
# Exiting the 'with a, b' context manager closes the sockets, which |
| 165 |
# causes the thread to exit (possibly with an error), which allows the |
| 166 |
# nursery context manager to exit too. |
| 167 |
with a, b: |
| 168 |
nursery.start_soon( |
| 169 |
trio.to_thread.run_sync, |
| 170 |
partial(ssl_echo_serve_sync, b, expect_fail=expect_fail), |
| 171 |
) |
| 172 |
|
| 173 |
yield SocketStream(tsocket.from_stdlib_socket(a)) |
| 174 |
|
| 175 |
|
| 176 |
# Fixture that gives a properly set up SSLStream connected to a trio-test-1 |
| 177 |
# echo server (running in a thread) |
| 178 |
@asynccontextmanager |
| 179 |
async def ssl_echo_server( |
| 180 |
client_ctx: SSLContext, |
| 181 |
expect_fail: bool = False, |
| 182 |
) -> AsyncIterator[SSLStream[Stream]]: |
| 183 |
async with ssl_echo_server_raw(expect_fail=expect_fail) as sock: |
| 184 |
yield SSLStream(sock, client_ctx, server_hostname="trio-test-1.example.org") |
| 185 |
|
| 186 |
|
| 187 |
# The weird in-memory server ... thing. |
| 188 |
# Doesn't inherit from Stream because I left out the methods that we don't |
| 189 |
# actually need. |
| 190 |
# jakkdl: it seems to implement all the abstract methods (now), so I made it inherit |
| 191 |
# from Stream for the sake of typechecking. |
| 192 |
class PyOpenSSLEchoStream(Stream): |
| 193 |
def __init__( |
| 194 |
self, |
| 195 |
sleeper: Callable[[str], Awaitable[None]] | None = None, |
| 196 |
) -> None: |
| 197 |
ctx = SSL.Context(SSL.SSLv23_METHOD) |
| 198 |
# TLS 1.3 removes renegotiation support. Which is great for them, but |
| 199 |
# we still have to support versions before that, and that means we |
| 200 |
# need to test renegotiation support, which means we need to force this |
| 201 |
# to use a lower version where this test server can trigger |
| 202 |
# renegotiations. |
| 203 |
from cryptography.hazmat.bindings.openssl.binding import Binding |
| 204 |
|
| 205 |
b = Binding() |
| 206 |
ctx.set_options(b.lib.SSL_OP_NO_TLSv1_3) |
| 207 |
|
| 208 |
# Unfortunately there's currently no way to say "use 1.3 or worse", we |
| 209 |
# can only disable specific versions. And if the two sides start |
| 210 |
# negotiating 1.4 at some point in the future, it *might* mean that |
| 211 |
# our tests silently stop working properly. So the next line is a |
| 212 |
# tripwire to remind us we need to revisit this stuff in 5 years or |
| 213 |
# whatever when the next TLS version is released: |
| 214 |
assert not hasattr(SSL, "OP_NO_TLSv1_4") |
| 215 |
TRIO_TEST_1_CERT.configure_cert(ctx) |
| 216 |
self._conn = SSL.Connection(ctx, None) |
| 217 |
self._conn.set_accept_state() |
| 218 |
self._lot = _core.ParkingLot() |
| 219 |
self._pending_cleartext = bytearray() |
| 220 |
|
| 221 |
self._send_all_conflict_detector = ConflictDetector( |
| 222 |
"simultaneous calls to PyOpenSSLEchoStream.send_all", |
| 223 |
) |
| 224 |
self._receive_some_conflict_detector = ConflictDetector( |
| 225 |
"simultaneous calls to PyOpenSSLEchoStream.receive_some", |
| 226 |
) |
| 227 |
|
| 228 |
self.sleeper: Callable[[str], Awaitable[None]] |
| 229 |
if sleeper is None: |
| 230 |
|
| 231 |
async def no_op_sleeper(_: object) -> None: |
| 232 |
return |
| 233 |
|
| 234 |
self.sleeper = no_op_sleeper |
| 235 |
else: |
| 236 |
self.sleeper = sleeper |
| 237 |
|
| 238 |
async def aclose(self) -> None: |
| 239 |
self._conn.bio_shutdown() |
| 240 |
|
| 241 |
def renegotiate_pending(self) -> bool: |
| 242 |
return self._conn.renegotiate_pending() |
| 243 |
|
| 244 |
def renegotiate(self) -> None: |
| 245 |
# Returns false if a renegotiation is already in progress, meaning |
| 246 |
# nothing happens. |
| 247 |
assert self._conn.renegotiate() |
| 248 |
|
| 249 |
async def wait_send_all_might_not_block(self) -> None: |
| 250 |
with self._send_all_conflict_detector: |
| 251 |
await _core.checkpoint() |
| 252 |
await _core.checkpoint() |
| 253 |
await self.sleeper("wait_send_all_might_not_block") |
| 254 |
|
| 255 |
async def send_all(self, data: bytes | bytearray | memoryview[int]) -> None: |
| 256 |
print(" --> transport_stream.send_all") |
| 257 |
data_ = bytes(data) |
| 258 |
with self._send_all_conflict_detector: |
| 259 |
await _core.checkpoint() |
| 260 |
await _core.checkpoint() |
| 261 |
await self.sleeper("send_all") |
| 262 |
self._conn.bio_write(data_) |
| 263 |
while True: |
| 264 |
await self.sleeper("send_all") |
| 265 |
try: |
| 266 |
data_ = self._conn.recv(1) |
| 267 |
except SSL.ZeroReturnError: |
| 268 |
self._conn.shutdown() |
| 269 |
print("renegotiations:", self._conn.total_renegotiations()) |
| 270 |
break |
| 271 |
except SSL.WantReadError: |
| 272 |
break |
| 273 |
else: |
| 274 |
self._pending_cleartext += data_ |
| 275 |
self._lot.unpark_all() |
| 276 |
await self.sleeper("send_all") |
| 277 |
print(" <-- transport_stream.send_all finished") |
| 278 |
|
| 279 |
async def receive_some(self, nbytes: int | None = None) -> bytes: |
| 280 |
print(" --> transport_stream.receive_some") |
| 281 |
if nbytes is None: |
| 282 |
nbytes = 65536 # arbitrary |
| 283 |
with self._receive_some_conflict_detector: |
| 284 |
try: |
| 285 |
await _core.checkpoint() |
| 286 |
await _core.checkpoint() |
| 287 |
while True: |
| 288 |
await self.sleeper("receive_some") |
| 289 |
try: |
| 290 |
return self._conn.bio_read(nbytes) |
| 291 |
except SSL.WantReadError: |
| 292 |
# No data in our ciphertext buffer; try to generate |
| 293 |
# some. |
| 294 |
if self._pending_cleartext: |
| 295 |
# We have some cleartext; maybe we can encrypt it |
| 296 |
# and then return it. |
| 297 |
print(" trying", self._pending_cleartext) |
| 298 |
try: |
| 299 |
# PyOpenSSL bug: doesn't accept bytearray |
| 300 |
# https://github.com/pyca/pyopenssl/issues/621 |
| 301 |
next_byte = self._pending_cleartext[0:1] |
| 302 |
self._conn.send(bytes(next_byte)) |
| 303 |
# Apparently this next bit never gets hit in the |
| 304 |
# test suite, but it's not an interesting omission |
| 305 |
# so let's pragma it. |
| 306 |
except SSL.WantReadError: # pragma: no cover |
| 307 |
# We didn't manage to send the cleartext (and |
| 308 |
# in particular we better leave it there to |
| 309 |
# try again, due to openssl's retry |
| 310 |
# semantics), but it's possible we pushed a |
| 311 |
# renegotiation forward and *now* we have data |
| 312 |
# to send. |
| 313 |
try: |
| 314 |
return self._conn.bio_read(nbytes) |
| 315 |
except SSL.WantReadError: |
| 316 |
# Nope. We're just going to have to wait |
| 317 |
# for someone to call send_all() to give |
| 318 |
# use more data. |
| 319 |
print("parking (a)") |
| 320 |
await self._lot.park() |
| 321 |
else: |
| 322 |
# We successfully sent that byte, so we don't |
| 323 |
# have to again. |
| 324 |
del self._pending_cleartext[0:1] |
| 325 |
else: |
| 326 |
# no pending cleartext; nothing to do but wait for |
| 327 |
# someone to call send_all |
| 328 |
print("parking (b)") |
| 329 |
await self._lot.park() |
| 330 |
finally: |
| 331 |
await self.sleeper("receive_some") |
| 332 |
print(" <-- transport_stream.receive_some finished") |
| 333 |
|
| 334 |
|
| 335 |
async def test_PyOpenSSLEchoStream_gives_resource_busy_errors() -> None: |
| 336 |
# Make sure that PyOpenSSLEchoStream complains if two tasks call send_all |
| 337 |
# at the same time, or ditto for receive_some. The tricky cases where SSLStream |
| 338 |
# might accidentally do this are during renegotiation, which we test using |
| 339 |
# PyOpenSSLEchoStream, so this makes sure that if we do have a bug then |
| 340 |
# PyOpenSSLEchoStream will notice and complain. |
| 341 |
|
| 342 |
async def do_test( |
| 343 |
func1: str, |
| 344 |
args1: tuple[object, ...], |
| 345 |
func2: str, |
| 346 |
args2: tuple[object, ...], |
| 347 |
) -> None: |
| 348 |
s = PyOpenSSLEchoStream() |
| 349 |
with pytest.RaisesGroup( |
| 350 |
pytest.RaisesExc(_core.BusyResourceError, match="simultaneous") |
| 351 |
): |
| 352 |
async with _core.open_nursery() as nursery: |
| 353 |
nursery.start_soon(getattr(s, func1), *args1) |
| 354 |
nursery.start_soon(getattr(s, func2), *args2) |
| 355 |
|
| 356 |
await do_test("send_all", (b"x",), "send_all", (b"x",)) |
| 357 |
await do_test("send_all", (b"x",), "wait_send_all_might_not_block", ()) |
| 358 |
await do_test( |
| 359 |
"wait_send_all_might_not_block", |
| 360 |
(), |
| 361 |
"wait_send_all_might_not_block", |
| 362 |
(), |
| 363 |
) |
| 364 |
await do_test("receive_some", (1,), "receive_some", (1,)) |
| 365 |
|
| 366 |
|
| 367 |
@contextmanager |
| 368 |
def virtual_ssl_echo_server( |
| 369 |
client_ctx: SSLContext, |
| 370 |
sleeper: Callable[[str], Awaitable[None]] | None = None, |
| 371 |
) -> Iterator[SSLStream[PyOpenSSLEchoStream]]: |
| 372 |
fakesock = PyOpenSSLEchoStream(sleeper=sleeper) |
| 373 |
yield SSLStream(fakesock, client_ctx, server_hostname="trio-test-1.example.org") |
| 374 |
|
| 375 |
|
| 376 |
def ssl_wrap_pair( # type: ignore[explicit-any] |
| 377 |
client_ctx: SSLContext, |
| 378 |
client_transport: T_Stream, |
| 379 |
server_transport: T_Stream, |
| 380 |
*, |
| 381 |
client_kwargs: dict[str, Any] | None = None, |
| 382 |
server_kwargs: dict[str, Any] | None = None, |
| 383 |
) -> tuple[SSLStream[T_Stream], SSLStream[T_Stream]]: |
| 384 |
if server_kwargs is None: |
| 385 |
server_kwargs = {} |
| 386 |
if client_kwargs is None: |
| 387 |
client_kwargs = {} |
| 388 |
client_ssl = SSLStream( |
| 389 |
client_transport, |
| 390 |
client_ctx, |
| 391 |
server_hostname="trio-test-1.example.org", |
| 392 |
**client_kwargs, |
| 393 |
) |
| 394 |
server_ssl = SSLStream( |
| 395 |
server_transport, |
| 396 |
SERVER_CTX, |
| 397 |
server_side=True, |
| 398 |
**server_kwargs, |
| 399 |
) |
| 400 |
return client_ssl, server_ssl |
| 401 |
|
| 402 |
|
| 403 |
MemoryStapledStream: TypeAlias = StapledStream[MemorySendStream, MemoryReceiveStream] |
| 404 |
|
| 405 |
|
| 406 |
def ssl_memory_stream_pair( |
| 407 |
client_ctx: SSLContext, |
| 408 |
client_kwargs: dict[str, str | bytes | bool | None] | None = None, |
| 409 |
server_kwargs: dict[str, str | bytes | bool | None] | None = None, |
| 410 |
) -> tuple[ |
| 411 |
SSLStream[MemoryStapledStream], |
| 412 |
SSLStream[MemoryStapledStream], |
| 413 |
]: |
| 414 |
client_transport, server_transport = memory_stream_pair() |
| 415 |
return ssl_wrap_pair( |
| 416 |
client_ctx, |
| 417 |
client_transport, |
| 418 |
server_transport, |
| 419 |
client_kwargs=client_kwargs, |
| 420 |
server_kwargs=server_kwargs, |
| 421 |
) |
| 422 |
|
| 423 |
|
| 424 |
MyStapledStream: TypeAlias = StapledStream[SendStream, ReceiveStream] |
| 425 |
|
| 426 |
|
| 427 |
def ssl_lockstep_stream_pair( |
| 428 |
client_ctx: SSLContext, |
| 429 |
client_kwargs: dict[str, str | bytes | bool | None] | None = None, |
| 430 |
server_kwargs: dict[str, str | bytes | bool | None] | None = None, |
| 431 |
) -> tuple[ |
| 432 |
SSLStream[MyStapledStream], |
| 433 |
SSLStream[MyStapledStream], |
| 434 |
]: |
| 435 |
client_transport, server_transport = lockstep_stream_pair() |
| 436 |
return ssl_wrap_pair( |
| 437 |
client_ctx, |
| 438 |
client_transport, |
| 439 |
server_transport, |
| 440 |
client_kwargs=client_kwargs, |
| 441 |
server_kwargs=server_kwargs, |
| 442 |
) |
| 443 |
|
| 444 |
|
| 445 |
# Simple smoke test for handshake/send/receive/shutdown talking to a |
| 446 |
# synchronous server, plus make sure that we do the bare minimum of |
| 447 |
# certificate checking (even though this is really Python's responsibility) |
| 448 |
async def test_ssl_client_basics(client_ctx: SSLContext) -> None: |
| 449 |
# Everything OK |
| 450 |
async with ssl_echo_server(client_ctx) as s: |
| 451 |
assert not s.server_side |
| 452 |
await s.send_all(b"x") |
| 453 |
assert await s.receive_some(1) == b"x" |
| 454 |
await s.aclose() |
| 455 |
|
| 456 |
# Didn't configure the CA file, should fail |
| 457 |
async with ssl_echo_server_raw(expect_fail=True) as sock: |
| 458 |
bad_client_ctx = ssl.create_default_context() |
| 459 |
s = SSLStream(sock, bad_client_ctx, server_hostname="trio-test-1.example.org") |
| 460 |
assert not s.server_side |
| 461 |
with pytest.raises(BrokenResourceError) as excinfo: |
| 462 |
await s.send_all(b"x") |
| 463 |
assert isinstance(excinfo.value.__cause__, ssl.SSLError) |
| 464 |
|
| 465 |
# Trusted CA, but wrong host name |
| 466 |
async with ssl_echo_server_raw(expect_fail=True) as sock: |
| 467 |
s = SSLStream(sock, client_ctx, server_hostname="trio-test-2.example.org") |
| 468 |
assert not s.server_side |
| 469 |
with pytest.raises(BrokenResourceError) as excinfo: |
| 470 |
await s.send_all(b"x") |
| 471 |
assert isinstance(excinfo.value.__cause__, ssl.CertificateError) |
| 472 |
|
| 473 |
|
| 474 |
async def test_ssl_server_basics(client_ctx: SSLContext) -> None: |
| 475 |
a, b = stdlib_socket.socketpair() |
| 476 |
with a, b: |
| 477 |
server_sock = tsocket.from_stdlib_socket(b) |
| 478 |
server_transport = SSLStream( |
| 479 |
SocketStream(server_sock), |
| 480 |
SERVER_CTX, |
| 481 |
server_side=True, |
| 482 |
) |
| 483 |
assert server_transport.server_side |
| 484 |
|
| 485 |
def client() -> None: |
| 486 |
with client_ctx.wrap_socket( |
| 487 |
a, |
| 488 |
server_hostname="trio-test-1.example.org", |
| 489 |
) as client_sock: |
| 490 |
client_sock.sendall(b"x") |
| 491 |
assert client_sock.recv(1) == b"y" |
| 492 |
client_sock.sendall(b"z") |
| 493 |
client_sock.unwrap() |
| 494 |
|
| 495 |
t = threading.Thread(target=client) |
| 496 |
t.start() |
| 497 |
|
| 498 |
assert await server_transport.receive_some(1) == b"x" |
| 499 |
await server_transport.send_all(b"y") |
| 500 |
assert await server_transport.receive_some(1) == b"z" |
| 501 |
assert await server_transport.receive_some(1) == b"" |
| 502 |
await server_transport.aclose() |
| 503 |
|
| 504 |
t.join() |
| 505 |
|
| 506 |
|
| 507 |
async def test_attributes(client_ctx: SSLContext) -> None: |
| 508 |
async with ssl_echo_server_raw(expect_fail=True) as sock: |
| 509 |
good_ctx = client_ctx |
| 510 |
bad_ctx = ssl.create_default_context() |
| 511 |
s = SSLStream(sock, good_ctx, server_hostname="trio-test-1.example.org") |
| 512 |
|
| 513 |
assert s.transport_stream is sock |
| 514 |
|
| 515 |
# Forwarded attribute getting |
| 516 |
assert s.context is good_ctx |
| 517 |
assert s.server_side == False # noqa |
| 518 |
assert s.server_hostname == "trio-test-1.example.org" |
| 519 |
with pytest.raises(AttributeError): |
| 520 |
s.asfdasdfsa # noqa: B018 # "useless expression" |
| 521 |
|
| 522 |
# __dir__ |
| 523 |
assert "transport_stream" in dir(s) |
| 524 |
assert "context" in dir(s) |
| 525 |
|
| 526 |
# Setting the attribute goes through to the underlying object |
| 527 |
|
| 528 |
# most attributes on SSLObject are read-only |
| 529 |
with pytest.raises(AttributeError): |
| 530 |
s.server_side = True |
| 531 |
with pytest.raises(AttributeError): |
| 532 |
s.server_hostname = "asdf" |
| 533 |
|
| 534 |
# but .context is *not*. Check that we forward attribute setting by |
| 535 |
# making sure that after we set the bad context our handshake indeed |
| 536 |
# fails: |
| 537 |
s.context = bad_ctx |
| 538 |
assert s.context is bad_ctx |
| 539 |
with pytest.raises(BrokenResourceError) as excinfo: |
| 540 |
await s.do_handshake() |
| 541 |
assert isinstance(excinfo.value.__cause__, ssl.SSLError) |
| 542 |
|
| 543 |
|
| 544 |
# Note: this test fails horribly if we force TLS 1.2 and trigger a |
| 545 |
# renegotiation at the beginning (e.g. by switching to the pyopenssl |
| 546 |
# server). Usually the client crashes in SSLObject.write with "UNEXPECTED |
| 547 |
# RECORD"; sometimes we get something more exotic like a SyscallError. This is |
| 548 |
# odd because openssl isn't doing any syscalls, but so it goes. After lots of |
| 549 |
# websearching I'm pretty sure this is due to a bug in OpenSSL, where it just |
| 550 |
# can't reliably handle full-duplex communication combined with |
| 551 |
# renegotiation. Nice, eh? |
| 552 |
# |
| 553 |
# https://rt.openssl.org/Ticket/Display.html?id=3712 |
| 554 |
# https://rt.openssl.org/Ticket/Display.html?id=2481 |
| 555 |
# http://openssl.6102.n7.nabble.com/TLS-renegotiation-failure-on-receiving-application-data-during-handshake-td48127.html |
| 556 |
# https://stackoverflow.com/questions/18728355/ssl-renegotiation-with-full-duplex-socket-communication |
| 557 |
# |
| 558 |
# In some variants of this test (maybe only against the java server?) I've |
| 559 |
# also seen cases where our send_all blocks waiting to write, and then our receive_some |
| 560 |
# also blocks waiting to write, and they never wake up again. It looks like |
| 561 |
# some kind of deadlock. I suspect there may be an issue where we've filled up |
| 562 |
# the send buffers, and the remote side is trying to handle the renegotiation |
| 563 |
# from inside a write() call, so it has a problem: there's all this application |
| 564 |
# data clogging up the pipe, but it can't process and return it to the |
| 565 |
# application because it's in write(), and it doesn't want to buffer infinite |
| 566 |
# amounts of data, and... actually I guess those are the only two choices. |
| 567 |
# |
| 568 |
# NSS even documents that you shouldn't try to do a renegotiation except when |
| 569 |
# the connection is idle: |
| 570 |
# |
| 571 |
# https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/SSL_functions/sslfnc.html#1061582 |
| 572 |
# |
| 573 |
# I begin to see why HTTP/2 forbids renegotiation and TLS 1.3 removes it... |
| 574 |
|
| 575 |
|
| 576 |
async def test_full_duplex_basics(client_ctx: SSLContext) -> None: |
| 577 |
CHUNKS = 30 |
| 578 |
CHUNK_SIZE = 32768 |
| 579 |
EXPECTED = CHUNKS * CHUNK_SIZE |
| 580 |
|
| 581 |
sent = bytearray() |
| 582 |
received = bytearray() |
| 583 |
|
| 584 |
async def sender(s: Stream) -> None: |
| 585 |
nonlocal sent |
| 586 |
for i in range(CHUNKS): |
| 587 |
print(i) |
| 588 |
chunk = bytes([i] * CHUNK_SIZE) |
| 589 |
sent += chunk |
| 590 |
await s.send_all(chunk) |
| 591 |
|
| 592 |
async def receiver(s: Stream) -> None: |
| 593 |
nonlocal received |
| 594 |
while len(received) < EXPECTED: |
| 595 |
chunk = await s.receive_some(CHUNK_SIZE // 2) |
| 596 |
received += chunk |
| 597 |
|
| 598 |
async with ssl_echo_server(client_ctx) as s: |
| 599 |
async with _core.open_nursery() as nursery: |
| 600 |
nursery.start_soon(sender, s) |
| 601 |
nursery.start_soon(receiver, s) |
| 602 |
# And let's have some doing handshakes too, everyone |
| 603 |
# simultaneously |
| 604 |
nursery.start_soon(s.do_handshake) |
| 605 |
nursery.start_soon(s.do_handshake) |
| 606 |
|
| 607 |
await s.aclose() |
| 608 |
|
| 609 |
assert len(sent) == len(received) == EXPECTED |
| 610 |
assert sent == received |
| 611 |
|
| 612 |
|
| 613 |
async def test_renegotiation_simple(client_ctx: SSLContext) -> None: |
| 614 |
with virtual_ssl_echo_server(client_ctx) as s: |
| 615 |
await s.do_handshake() |
| 616 |
s.transport_stream.renegotiate() |
| 617 |
await s.send_all(b"a") |
| 618 |
assert await s.receive_some(1) == b"a" |
| 619 |
|
| 620 |
# Have to send some more data back and forth to make sure the |
| 621 |
# renegotiation is finished before shutting down the |
| 622 |
# connection... otherwise openssl raises an error. I think this is a |
| 623 |
# bug in openssl but what can ya do. |
| 624 |
await s.send_all(b"b") |
| 625 |
assert await s.receive_some(1) == b"b" |
| 626 |
|
| 627 |
await s.aclose() |
| 628 |
|
| 629 |
|
| 630 |
@slow |
| 631 |
async def test_renegotiation_randomized( |
| 632 |
mock_clock: MockClock, |
| 633 |
client_ctx: SSLContext, |
| 634 |
) -> None: |
| 635 |
# The only blocking things in this function are our random sleeps, so 0 is |
| 636 |
# a good threshold. |
| 637 |
mock_clock.autojump_threshold = 0 |
| 638 |
|
| 639 |
import random |
| 640 |
|
| 641 |
r = random.Random(0) |
| 642 |
|
| 643 |
async def sleeper(_: object) -> None: |
| 644 |
await trio.sleep(r.uniform(0, 10)) |
| 645 |
|
| 646 |
async def clear() -> None: |
| 647 |
while s.transport_stream.renegotiate_pending(): |
| 648 |
with assert_checkpoints(): |
| 649 |
await send(b"-") |
| 650 |
with assert_checkpoints(): |
| 651 |
await expect(b"-") |
| 652 |
print("-- clear --") |
| 653 |
|
| 654 |
async def send(byte: bytes) -> None: |
| 655 |
await s.transport_stream.sleeper("outer send") |
| 656 |
print("calling SSLStream.send_all", byte) |
| 657 |
with assert_checkpoints(): |
| 658 |
await s.send_all(byte) |
| 659 |
|
| 660 |
async def expect(expected: bytes) -> None: |
| 661 |
await s.transport_stream.sleeper("expect") |
| 662 |
print("calling SSLStream.receive_some, expecting", expected) |
| 663 |
assert len(expected) == 1 |
| 664 |
with assert_checkpoints(): |
| 665 |
assert await s.receive_some(1) == expected |
| 666 |
|
| 667 |
with virtual_ssl_echo_server(client_ctx, sleeper=sleeper) as s: |
| 668 |
await s.do_handshake() |
| 669 |
|
| 670 |
await send(b"a") |
| 671 |
s.transport_stream.renegotiate() |
| 672 |
await expect(b"a") |
| 673 |
|
| 674 |
await clear() |
| 675 |
|
| 676 |
for i in range(100): |
| 677 |
b1 = bytes([i % 0xFF]) |
| 678 |
b2 = bytes([(2 * i) % 0xFF]) |
| 679 |
s.transport_stream.renegotiate() |
| 680 |
async with _core.open_nursery() as nursery: |
| 681 |
nursery.start_soon(send, b1) |
| 682 |
nursery.start_soon(expect, b1) |
| 683 |
async with _core.open_nursery() as nursery: |
| 684 |
nursery.start_soon(expect, b2) |
| 685 |
nursery.start_soon(send, b2) |
| 686 |
await clear() |
| 687 |
|
| 688 |
for i in range(100): |
| 689 |
b1 = bytes([i % 0xFF]) |
| 690 |
b2 = bytes([(2 * i) % 0xFF]) |
| 691 |
await send(b1) |
| 692 |
s.transport_stream.renegotiate() |
| 693 |
await expect(b1) |
| 694 |
async with _core.open_nursery() as nursery: |
| 695 |
nursery.start_soon(expect, b2) |
| 696 |
nursery.start_soon(send, b2) |
| 697 |
await clear() |
| 698 |
|
| 699 |
# Checking that wait_send_all_might_not_block and receive_some don't |
| 700 |
# conflict: |
| 701 |
|
| 702 |
# 1) Set up a situation where expect (receive_some) is blocked sending, |
| 703 |
# and wait_send_all_might_not_block comes in. |
| 704 |
|
| 705 |
# Our receive_some() call will get stuck when it hits send_all |
| 706 |
async def sleeper_with_slow_send_all(method: str) -> None: |
| 707 |
if method == "send_all": |
| 708 |
# ignore ASYNC116, not sleep_forever, trying to test a large but finite sleep |
| 709 |
await trio.sleep(100000) # noqa: ASYNC116 |
| 710 |
|
| 711 |
# And our wait_send_all_might_not_block call will give it time to get |
| 712 |
# stuck, and then start |
| 713 |
async def sleep_then_wait_writable() -> None: |
| 714 |
await trio.sleep(1000) |
| 715 |
await s.wait_send_all_might_not_block() |
| 716 |
|
| 717 |
with virtual_ssl_echo_server(client_ctx, sleeper=sleeper_with_slow_send_all) as s: |
| 718 |
await send(b"x") |
| 719 |
s.transport_stream.renegotiate() |
| 720 |
async with _core.open_nursery() as nursery: |
| 721 |
nursery.start_soon(expect, b"x") |
| 722 |
nursery.start_soon(sleep_then_wait_writable) |
| 723 |
|
| 724 |
await clear() |
| 725 |
|
| 726 |
await s.aclose() |
| 727 |
|
| 728 |
# 2) Same, but now wait_send_all_might_not_block is stuck when |
| 729 |
# receive_some tries to send. |
| 730 |
|
| 731 |
async def sleeper_with_slow_wait_writable_and_expect(method: str) -> None: |
| 732 |
if method == "wait_send_all_might_not_block": |
| 733 |
# ignore ASYNC116, not sleep_forever, trying to test a large but finite sleep |
| 734 |
await trio.sleep(100000) # noqa: ASYNC116 |
| 735 |
elif method == "expect": |
| 736 |
await trio.sleep(1000) |
| 737 |
|
| 738 |
with virtual_ssl_echo_server( |
| 739 |
client_ctx, |
| 740 |
sleeper=sleeper_with_slow_wait_writable_and_expect, |
| 741 |
) as s: |
| 742 |
await send(b"x") |
| 743 |
s.transport_stream.renegotiate() |
| 744 |
async with _core.open_nursery() as nursery: |
| 745 |
nursery.start_soon(expect, b"x") |
| 746 |
nursery.start_soon(s.wait_send_all_might_not_block) |
| 747 |
|
| 748 |
await clear() |
| 749 |
|
| 750 |
await s.aclose() |
| 751 |
|
| 752 |
|
| 753 |
async def test_resource_busy_errors(client_ctx: SSLContext) -> None: |
| 754 |
S: TypeAlias = trio.SSLStream[ |
| 755 |
trio.StapledStream[trio.abc.SendStream, trio.abc.ReceiveStream] |
| 756 |
] |
| 757 |
|
| 758 |
async def do_send_all(s: S) -> None: |
| 759 |
with assert_checkpoints(): |
| 760 |
await s.send_all(b"x") |
| 761 |
|
| 762 |
async def do_receive_some(s: S) -> None: |
| 763 |
with assert_checkpoints(): |
| 764 |
await s.receive_some(1) |
| 765 |
|
| 766 |
async def do_wait_send_all_might_not_block(s: S) -> None: |
| 767 |
with assert_checkpoints(): |
| 768 |
await s.wait_send_all_might_not_block() |
| 769 |
|
| 770 |
async def do_test( |
| 771 |
func1: Callable[[S], Awaitable[None]], |
| 772 |
func2: Callable[[S], Awaitable[None]], |
| 773 |
) -> None: |
| 774 |
s, _ = ssl_lockstep_stream_pair(client_ctx) |
| 775 |
with pytest.RaisesGroup( |
| 776 |
pytest.RaisesExc(_core.BusyResourceError, match="another task") |
| 777 |
): |
| 778 |
async with _core.open_nursery() as nursery: |
| 779 |
nursery.start_soon(func1, s) |
| 780 |
nursery.start_soon(func2, s) |
| 781 |
|
| 782 |
await do_test(do_send_all, do_send_all) |
| 783 |
await do_test(do_receive_some, do_receive_some) |
| 784 |
await do_test(do_send_all, do_wait_send_all_might_not_block) |
| 785 |
await do_test(do_wait_send_all_might_not_block, do_wait_send_all_might_not_block) |
| 786 |
|
| 787 |
|
| 788 |
async def test_wait_writable_calls_underlying_wait_writable() -> None: |
| 789 |
record = [] |
| 790 |
|
| 791 |
class NotAStream(Stream): |
| 792 |
async def wait_send_all_might_not_block(self) -> None: |
| 793 |
record.append("ok") |
| 794 |
|
| 795 |
# define methods that are abstract in Stream |
| 796 |
async def aclose(self) -> None: |
| 797 |
raise AssertionError("Should not get called") # pragma: no cover |
| 798 |
|
| 799 |
async def receive_some(self, max_bytes: int | None = None) -> bytes | bytearray: |
| 800 |
raise AssertionError("Should not get called") # pragma: no cover |
| 801 |
|
| 802 |
async def send_all(self, data: bytes | bytearray | memoryview) -> None: |
| 803 |
raise AssertionError("Should not get called") # pragma: no cover |
| 804 |
|
| 805 |
ctx = ssl.create_default_context() |
| 806 |
s = SSLStream(NotAStream(), ctx, server_hostname="x") |
| 807 |
await s.wait_send_all_might_not_block() |
| 808 |
assert record == ["ok"] |
| 809 |
|
| 810 |
|
| 811 |
@pytest.mark.skipif( |
| 812 |
os.name == "nt" and sys.version_info >= (3, 10), |
| 813 |
reason="frequently fails on Windows + Python 3.10", |
| 814 |
) |
| 815 |
async def test_checkpoints(client_ctx: SSLContext) -> None: |
| 816 |
async with ssl_echo_server(client_ctx) as s: |
| 817 |
with assert_checkpoints(): |
| 818 |
await s.do_handshake() |
| 819 |
with assert_checkpoints(): |
| 820 |
await s.do_handshake() |
| 821 |
with assert_checkpoints(): |
| 822 |
await s.wait_send_all_might_not_block() |
| 823 |
with assert_checkpoints(): |
| 824 |
await s.send_all(b"xxx") |
| 825 |
with assert_checkpoints(): |
| 826 |
await s.receive_some(1) |
| 827 |
# These receive_some's in theory could return immediately, because the |
| 828 |
# "xxx" was sent in a single record and after the first |
| 829 |
# receive_some(1) the rest are sitting inside the SSLObject's internal |
| 830 |
# buffers. |
| 831 |
with assert_checkpoints(): |
| 832 |
await s.receive_some(1) |
| 833 |
with assert_checkpoints(): |
| 834 |
await s.receive_some(1) |
| 835 |
with assert_checkpoints(): |
| 836 |
await s.unwrap() |
| 837 |
|
| 838 |
async with ssl_echo_server(client_ctx) as s: |
| 839 |
await s.do_handshake() |
| 840 |
with assert_checkpoints(): |
| 841 |
await s.aclose() |
| 842 |
|
| 843 |
|
| 844 |
async def test_send_all_empty_string(client_ctx: SSLContext) -> None: |
| 845 |
async with ssl_echo_server(client_ctx) as s: |
| 846 |
await s.do_handshake() |
| 847 |
|
| 848 |
# underlying SSLObject interprets writing b"" as indicating an EOF, |
| 849 |
# for some reason. Make sure we don't inherit this. |
| 850 |
with assert_checkpoints(): |
| 851 |
await s.send_all(b"") |
| 852 |
with assert_checkpoints(): |
| 853 |
await s.send_all(b"") |
| 854 |
await s.send_all(b"x") |
| 855 |
assert await s.receive_some(1) == b"x" |
| 856 |
|
| 857 |
await s.aclose() |
| 858 |
|
| 859 |
|
| 860 |
@pytest.mark.parametrize("https_compatible", [False, True]) |
| 861 |
async def test_SSLStream_generic( |
| 862 |
client_ctx: SSLContext, |
| 863 |
https_compatible: bool, |
| 864 |
) -> None: |
| 865 |
async def stream_maker() -> tuple[ |
| 866 |
SSLStream[MemoryStapledStream], |
| 867 |
SSLStream[MemoryStapledStream], |
| 868 |
]: |
| 869 |
return ssl_memory_stream_pair( |
| 870 |
client_ctx, |
| 871 |
client_kwargs={"https_compatible": https_compatible}, |
| 872 |
server_kwargs={"https_compatible": https_compatible}, |
| 873 |
) |
| 874 |
|
| 875 |
async def clogged_stream_maker() -> tuple[ |
| 876 |
SSLStream[MyStapledStream], |
| 877 |
SSLStream[MyStapledStream], |
| 878 |
]: |
| 879 |
client, server = ssl_lockstep_stream_pair(client_ctx) |
| 880 |
# If we don't do handshakes up front, then we run into a problem in |
| 881 |
# the following situation: |
| 882 |
# - server does wait_send_all_might_not_block |
| 883 |
# - client does receive_some to unclog it |
| 884 |
# Then the client's receive_some will actually send some data to start |
| 885 |
# the handshake, and itself get stuck. |
| 886 |
async with _core.open_nursery() as nursery: |
| 887 |
nursery.start_soon(client.do_handshake) |
| 888 |
nursery.start_soon(server.do_handshake) |
| 889 |
return client, server |
| 890 |
|
| 891 |
await check_two_way_stream(stream_maker, clogged_stream_maker) |
| 892 |
|
| 893 |
|
| 894 |
async def test_unwrap(client_ctx: SSLContext) -> None: |
| 895 |
client_ssl, server_ssl = ssl_memory_stream_pair(client_ctx) |
| 896 |
client_transport = client_ssl.transport_stream |
| 897 |
server_transport = server_ssl.transport_stream |
| 898 |
|
| 899 |
seq = Sequencer() |
| 900 |
|
| 901 |
async def client() -> None: |
| 902 |
await client_ssl.do_handshake() |
| 903 |
await client_ssl.send_all(b"x") |
| 904 |
assert await client_ssl.receive_some(1) == b"y" |
| 905 |
await client_ssl.send_all(b"z") |
| 906 |
|
| 907 |
# After sending that, disable outgoing data from our end, to make |
| 908 |
# sure the server doesn't see our EOF until after we've sent some |
| 909 |
# trailing data |
| 910 |
async with seq(0): |
| 911 |
send_all_hook = client_transport.send_stream.send_all_hook |
| 912 |
client_transport.send_stream.send_all_hook = None |
| 913 |
|
| 914 |
assert await client_ssl.receive_some(1) == b"" |
| 915 |
assert client_ssl.transport_stream is client_transport |
| 916 |
# We just received EOF. Unwrap the connection and send some more. |
| 917 |
raw, trailing = await client_ssl.unwrap() |
| 918 |
assert raw is client_transport |
| 919 |
assert trailing == b"" |
| 920 |
assert client_ssl.transport_stream is None |
| 921 |
await raw.send_all(b"trailing") |
| 922 |
|
| 923 |
# Reconnect the streams. Now the server will receive both our shutdown |
| 924 |
# acknowledgement + the trailing data in a single lump. |
| 925 |
client_transport.send_stream.send_all_hook = send_all_hook |
| 926 |
await client_transport.send_stream.send_all_hook() |
| 927 |
|
| 928 |
async def server() -> None: |
| 929 |
await server_ssl.do_handshake() |
| 930 |
assert await server_ssl.receive_some(1) == b"x" |
| 931 |
await server_ssl.send_all(b"y") |
| 932 |
assert await server_ssl.receive_some(1) == b"z" |
| 933 |
# Now client is blocked waiting for us to send something, but |
| 934 |
# instead we close the TLS connection (with sequencer to make sure |
| 935 |
# that the client won't see and automatically respond before we've had |
| 936 |
# a chance to disable the client->server transport) |
| 937 |
async with seq(1): |
| 938 |
raw, trailing = await server_ssl.unwrap() |
| 939 |
assert raw is server_transport |
| 940 |
assert trailing == b"trailing" |
| 941 |
assert server_ssl.transport_stream is None |
| 942 |
|
| 943 |
async with _core.open_nursery() as nursery: |
| 944 |
nursery.start_soon(client) |
| 945 |
nursery.start_soon(server) |
| 946 |
|
| 947 |
|
| 948 |
async def test_closing_nice_case(client_ctx: SSLContext) -> None: |
| 949 |
# the nice case: graceful closes all around |
| 950 |
|
| 951 |
client_ssl, server_ssl = ssl_memory_stream_pair(client_ctx) |
| 952 |
client_transport = client_ssl.transport_stream |
| 953 |
|
| 954 |
# Both the handshake and the close require back-and-forth discussion, so |
| 955 |
# we need to run them concurrently |
| 956 |
async def client_closer() -> None: |
| 957 |
with assert_checkpoints(): |
| 958 |
await client_ssl.aclose() |
| 959 |
|
| 960 |
async def server_closer() -> None: |
| 961 |
assert await server_ssl.receive_some(10) == b"" |
| 962 |
assert await server_ssl.receive_some(10) == b"" |
| 963 |
with assert_checkpoints(): |
| 964 |
await server_ssl.aclose() |
| 965 |
|
| 966 |
async with _core.open_nursery() as nursery: |
| 967 |
nursery.start_soon(client_closer) |
| 968 |
nursery.start_soon(server_closer) |
| 969 |
|
| 970 |
# closing the SSLStream also closes its transport |
| 971 |
with pytest.raises(ClosedResourceError): |
| 972 |
await client_transport.send_all(b"123") |
| 973 |
|
| 974 |
# once closed, it's OK to close again |
| 975 |
with assert_checkpoints(): |
| 976 |
await client_ssl.aclose() |
| 977 |
with assert_checkpoints(): |
| 978 |
await client_ssl.aclose() |
| 979 |
|
| 980 |
# Trying to send more data does not work |
| 981 |
with pytest.raises(ClosedResourceError): |
| 982 |
await server_ssl.send_all(b"123") |
| 983 |
|
| 984 |
# And once the connection is has been closed *locally*, then instead of |
| 985 |
# getting empty bytestrings we get a proper error |
| 986 |
with pytest.raises(ClosedResourceError): |
| 987 |
assert await client_ssl.receive_some(10) == b"" |
| 988 |
|
| 989 |
with pytest.raises(ClosedResourceError): |
| 990 |
await client_ssl.unwrap() |
| 991 |
|
| 992 |
with pytest.raises(ClosedResourceError): |
| 993 |
await client_ssl.do_handshake() |
| 994 |
|
| 995 |
# Check that a graceful close *before* handshaking gives a clean EOF on |
| 996 |
# the other side |
| 997 |
client_ssl, server_ssl = ssl_memory_stream_pair(client_ctx) |
| 998 |
|
| 999 |
async def expect_eof_server() -> None: |
| 1000 |
with assert_checkpoints(): |
| 1001 |
assert await server_ssl.receive_some(10) == b"" |
| 1002 |
with assert_checkpoints(): |
| 1003 |
await server_ssl.aclose() |
| 1004 |
|
| 1005 |
async with _core.open_nursery() as nursery: |
| 1006 |
nursery.start_soon(client_ssl.aclose) |
| 1007 |
nursery.start_soon(expect_eof_server) |
| 1008 |
|
| 1009 |
|
| 1010 |
async def test_send_all_fails_in_the_middle(client_ctx: SSLContext) -> None: |
| 1011 |
client, server = ssl_memory_stream_pair(client_ctx) |
| 1012 |
|
| 1013 |
async with _core.open_nursery() as nursery: |
| 1014 |
nursery.start_soon(client.do_handshake) |
| 1015 |
nursery.start_soon(server.do_handshake) |
| 1016 |
|
| 1017 |
async def bad_hook() -> NoReturn: |
| 1018 |
raise KeyError |
| 1019 |
|
| 1020 |
client.transport_stream.send_stream.send_all_hook = bad_hook |
| 1021 |
|
| 1022 |
with pytest.raises(KeyError): |
| 1023 |
await client.send_all(b"x") |
| 1024 |
|
| 1025 |
with pytest.raises(BrokenResourceError): |
| 1026 |
await client.wait_send_all_might_not_block() |
| 1027 |
|
| 1028 |
closed = 0 |
| 1029 |
|
| 1030 |
def close_hook() -> None: |
| 1031 |
nonlocal closed |
| 1032 |
closed += 1 |
| 1033 |
|
| 1034 |
client.transport_stream.send_stream.close_hook = close_hook |
| 1035 |
client.transport_stream.receive_stream.close_hook = close_hook |
| 1036 |
await client.aclose() |
| 1037 |
|
| 1038 |
assert closed == 2 |
| 1039 |
|
| 1040 |
|
| 1041 |
async def test_ssl_over_ssl(client_ctx: SSLContext) -> None: |
| 1042 |
client_0, server_0 = memory_stream_pair() |
| 1043 |
|
| 1044 |
client_1 = SSLStream( |
| 1045 |
client_0, |
| 1046 |
client_ctx, |
| 1047 |
server_hostname="trio-test-1.example.org", |
| 1048 |
) |
| 1049 |
server_1 = SSLStream(server_0, SERVER_CTX, server_side=True) |
| 1050 |
|
| 1051 |
client_2 = SSLStream( |
| 1052 |
client_1, |
| 1053 |
client_ctx, |
| 1054 |
server_hostname="trio-test-1.example.org", |
| 1055 |
) |
| 1056 |
server_2 = SSLStream(server_1, SERVER_CTX, server_side=True) |
| 1057 |
|
| 1058 |
async def client() -> None: |
| 1059 |
await client_2.send_all(b"hi") |
| 1060 |
assert await client_2.receive_some(10) == b"bye" |
| 1061 |
|
| 1062 |
async def server() -> None: |
| 1063 |
assert await server_2.receive_some(10) == b"hi" |
| 1064 |
await server_2.send_all(b"bye") |
| 1065 |
|
| 1066 |
async with _core.open_nursery() as nursery: |
| 1067 |
nursery.start_soon(client) |
| 1068 |
nursery.start_soon(server) |
| 1069 |
|
| 1070 |
|
| 1071 |
async def test_ssl_bad_shutdown(client_ctx: SSLContext) -> None: |
| 1072 |
client, server = ssl_memory_stream_pair(client_ctx) |
| 1073 |
|
| 1074 |
async with _core.open_nursery() as nursery: |
| 1075 |
nursery.start_soon(client.do_handshake) |
| 1076 |
nursery.start_soon(server.do_handshake) |
| 1077 |
|
| 1078 |
await trio.aclose_forcefully(client) |
| 1079 |
# now the server sees a broken stream |
| 1080 |
with pytest.raises(BrokenResourceError): |
| 1081 |
await server.receive_some(10) |
| 1082 |
with pytest.raises(BrokenResourceError): |
| 1083 |
await server.send_all(b"x" * 10) |
| 1084 |
|
| 1085 |
await server.aclose() |
| 1086 |
|
| 1087 |
|
| 1088 |
async def test_ssl_bad_shutdown_but_its_ok(client_ctx: SSLContext) -> None: |
| 1089 |
client, server = ssl_memory_stream_pair( |
| 1090 |
client_ctx, |
| 1091 |
server_kwargs={"https_compatible": True}, |
| 1092 |
client_kwargs={"https_compatible": True}, |
| 1093 |
) |
| 1094 |
|
| 1095 |
async with _core.open_nursery() as nursery: |
| 1096 |
nursery.start_soon(client.do_handshake) |
| 1097 |
nursery.start_soon(server.do_handshake) |
| 1098 |
|
| 1099 |
await trio.aclose_forcefully(client) |
| 1100 |
# the server sees that as a clean shutdown |
| 1101 |
assert await server.receive_some(10) == b"" |
| 1102 |
with pytest.raises(BrokenResourceError): |
| 1103 |
await server.send_all(b"x" * 10) |
| 1104 |
|
| 1105 |
await server.aclose() |
| 1106 |
|
| 1107 |
|
| 1108 |
async def test_ssl_handshake_failure_during_aclose() -> None: |
| 1109 |
# Weird scenario: aclose() triggers an automatic handshake, and this |
| 1110 |
# fails. This also exercises a bit of code in aclose() that was otherwise |
| 1111 |
# uncovered, for re-raising exceptions after calling aclose_forcefully on |
| 1112 |
# the underlying transport. |
| 1113 |
async with ssl_echo_server_raw(expect_fail=True) as sock: |
| 1114 |
# Don't configure trust correctly |
| 1115 |
client_ctx = ssl.create_default_context() |
| 1116 |
s = SSLStream(sock, client_ctx, server_hostname="trio-test-1.example.org") |
| 1117 |
# It's a little unclear here whether aclose should swallow the error |
| 1118 |
# or let it escape. We *do* swallow the error if it arrives when we're |
| 1119 |
# sending close_notify, because both sides closing the connection |
| 1120 |
# simultaneously is allowed. But I guess when https_compatible=False |
| 1121 |
# then it's bad if we can get through a whole connection with a peer |
| 1122 |
# that has no valid certificate, and never raise an error. |
| 1123 |
with pytest.raises(BrokenResourceError): |
| 1124 |
await s.aclose() |
| 1125 |
|
| 1126 |
|
| 1127 |
async def test_ssl_only_closes_stream_once(client_ctx: SSLContext) -> None: |
| 1128 |
# We used to have a bug where if transport_stream.aclose() raised an |
| 1129 |
# error, we would call it again. This checks that that's fixed. |
| 1130 |
client, server = ssl_memory_stream_pair(client_ctx) |
| 1131 |
|
| 1132 |
async with _core.open_nursery() as nursery: |
| 1133 |
nursery.start_soon(client.do_handshake) |
| 1134 |
nursery.start_soon(server.do_handshake) |
| 1135 |
|
| 1136 |
client_orig_close_hook = client.transport_stream.send_stream.close_hook |
| 1137 |
transport_close_count = 0 |
| 1138 |
|
| 1139 |
def close_hook() -> NoReturn: |
| 1140 |
nonlocal transport_close_count |
| 1141 |
assert client_orig_close_hook is not None |
| 1142 |
client_orig_close_hook() |
| 1143 |
transport_close_count += 1 |
| 1144 |
raise KeyError |
| 1145 |
|
| 1146 |
client.transport_stream.send_stream.close_hook = close_hook |
| 1147 |
|
| 1148 |
with pytest.raises(KeyError): |
| 1149 |
await client.aclose() |
| 1150 |
assert transport_close_count == 1 |
| 1151 |
|
| 1152 |
|
| 1153 |
async def test_ssl_https_compatibility_disagreement(client_ctx: SSLContext) -> None: |
| 1154 |
client, server = ssl_memory_stream_pair( |
| 1155 |
client_ctx, |
| 1156 |
server_kwargs={"https_compatible": False}, |
| 1157 |
client_kwargs={"https_compatible": True}, |
| 1158 |
) |
| 1159 |
|
| 1160 |
async with _core.open_nursery() as nursery: |
| 1161 |
nursery.start_soon(client.do_handshake) |
| 1162 |
nursery.start_soon(server.do_handshake) |
| 1163 |
|
| 1164 |
# client is in HTTPS-mode, server is not |
| 1165 |
# so client doing graceful_shutdown causes an error on server |
| 1166 |
async def receive_and_expect_error() -> None: |
| 1167 |
with pytest.raises(BrokenResourceError) as excinfo: |
| 1168 |
await server.receive_some(10) |
| 1169 |
|
| 1170 |
assert _is_eof(excinfo.value.__cause__) |
| 1171 |
|
| 1172 |
async with _core.open_nursery() as nursery: |
| 1173 |
nursery.start_soon(client.aclose) |
| 1174 |
nursery.start_soon(receive_and_expect_error) |
| 1175 |
|
| 1176 |
|
| 1177 |
async def test_https_mode_eof_before_handshake(client_ctx: SSLContext) -> None: |
| 1178 |
client, server = ssl_memory_stream_pair( |
| 1179 |
client_ctx, |
| 1180 |
server_kwargs={"https_compatible": True}, |
| 1181 |
client_kwargs={"https_compatible": True}, |
| 1182 |
) |
| 1183 |
|
| 1184 |
async def server_expect_clean_eof() -> None: |
| 1185 |
assert await server.receive_some(10) == b"" |
| 1186 |
|
| 1187 |
async with _core.open_nursery() as nursery: |
| 1188 |
nursery.start_soon(client.aclose) |
| 1189 |
nursery.start_soon(server_expect_clean_eof) |
| 1190 |
|
| 1191 |
|
| 1192 |
async def test_send_error_during_handshake(client_ctx: SSLContext) -> None: |
| 1193 |
client, _server = ssl_memory_stream_pair(client_ctx) |
| 1194 |
|
| 1195 |
async def bad_hook() -> NoReturn: |
| 1196 |
raise KeyError |
| 1197 |
|
| 1198 |
client.transport_stream.send_stream.send_all_hook = bad_hook |
| 1199 |
|
| 1200 |
with pytest.raises(KeyError): |
| 1201 |
with assert_checkpoints(): |
| 1202 |
await client.do_handshake() |
| 1203 |
|
| 1204 |
with pytest.raises(BrokenResourceError): |
| 1205 |
with assert_checkpoints(): |
| 1206 |
await client.do_handshake() |
| 1207 |
|
| 1208 |
|
| 1209 |
async def test_receive_error_during_handshake(client_ctx: SSLContext) -> None: |
| 1210 |
client, server = ssl_memory_stream_pair(client_ctx) |
| 1211 |
|
| 1212 |
async def bad_hook() -> NoReturn: |
| 1213 |
raise KeyError |
| 1214 |
|
| 1215 |
client.transport_stream.receive_stream.receive_some_hook = bad_hook |
| 1216 |
|
| 1217 |
async def client_side(cancel_scope: CancelScope) -> None: |
| 1218 |
with pytest.raises(KeyError): |
| 1219 |
with assert_checkpoints(): |
| 1220 |
await client.do_handshake() |
| 1221 |
cancel_scope.cancel() |
| 1222 |
|
| 1223 |
async with _core.open_nursery() as nursery: |
| 1224 |
nursery.start_soon(client_side, nursery.cancel_scope) |
| 1225 |
nursery.start_soon(server.do_handshake) |
| 1226 |
|
| 1227 |
with pytest.raises(BrokenResourceError): |
| 1228 |
with assert_checkpoints(): |
| 1229 |
await client.do_handshake() |
| 1230 |
|
| 1231 |
|
| 1232 |
def test_selected_alpn_protocol_before_handshake(client_ctx: SSLContext) -> None: |
| 1233 |
client, server = ssl_memory_stream_pair(client_ctx) |
| 1234 |
|
| 1235 |
with pytest.raises(NeedHandshakeError): |
| 1236 |
client.selected_alpn_protocol() |
| 1237 |
|
| 1238 |
with pytest.raises(NeedHandshakeError): |
| 1239 |
server.selected_alpn_protocol() |
| 1240 |
|
| 1241 |
|
| 1242 |
async def test_selected_alpn_protocol_when_not_set(client_ctx: SSLContext) -> None: |
| 1243 |
# ALPN protocol still returns None when it's not set, |
| 1244 |
# instead of raising an exception |
| 1245 |
client, server = ssl_memory_stream_pair(client_ctx) |
| 1246 |
|
| 1247 |
async with _core.open_nursery() as nursery: |
| 1248 |
nursery.start_soon(client.do_handshake) |
| 1249 |
nursery.start_soon(server.do_handshake) |
| 1250 |
|
| 1251 |
assert client.selected_alpn_protocol() is None |
| 1252 |
assert server.selected_alpn_protocol() is None |
| 1253 |
|
| 1254 |
assert client.selected_alpn_protocol() == server.selected_alpn_protocol() |
| 1255 |
|
| 1256 |
|
| 1257 |
def test_selected_npn_protocol_before_handshake(client_ctx: SSLContext) -> None: |
| 1258 |
client, server = ssl_memory_stream_pair(client_ctx) |
| 1259 |
|
| 1260 |
with pytest.raises(NeedHandshakeError): |
| 1261 |
client.selected_npn_protocol() |
| 1262 |
|
| 1263 |
with pytest.raises(NeedHandshakeError): |
| 1264 |
server.selected_npn_protocol() |
| 1265 |
|
| 1266 |
|
| 1267 |
@pytest.mark.filterwarnings( |
| 1268 |
r"ignore: ssl module. NPN is deprecated, use ALPN instead:UserWarning", |
| 1269 |
r"ignore:ssl NPN is deprecated, use ALPN instead:DeprecationWarning", |
| 1270 |
) |
| 1271 |
async def test_selected_npn_protocol_when_not_set(client_ctx: SSLContext) -> None: |
| 1272 |
# NPN protocol still returns None when it's not set, |
| 1273 |
# instead of raising an exception |
| 1274 |
client, server = ssl_memory_stream_pair(client_ctx) |
| 1275 |
|
| 1276 |
async with _core.open_nursery() as nursery: |
| 1277 |
nursery.start_soon(client.do_handshake) |
| 1278 |
nursery.start_soon(server.do_handshake) |
| 1279 |
|
| 1280 |
assert client.selected_npn_protocol() is None |
| 1281 |
assert server.selected_npn_protocol() is None |
| 1282 |
|
| 1283 |
assert client.selected_npn_protocol() == server.selected_npn_protocol() |
| 1284 |
|
| 1285 |
|
| 1286 |
def test_get_channel_binding_before_handshake(client_ctx: SSLContext) -> None: |
| 1287 |
client, server = ssl_memory_stream_pair(client_ctx) |
| 1288 |
|
| 1289 |
with pytest.raises(NeedHandshakeError): |
| 1290 |
client.get_channel_binding() |
| 1291 |
|
| 1292 |
with pytest.raises(NeedHandshakeError): |
| 1293 |
server.get_channel_binding() |
| 1294 |
|
| 1295 |
|
| 1296 |
async def test_get_channel_binding_after_handshake(client_ctx: SSLContext) -> None: |
| 1297 |
client, server = ssl_memory_stream_pair(client_ctx) |
| 1298 |
|
| 1299 |
async with _core.open_nursery() as nursery: |
| 1300 |
nursery.start_soon(client.do_handshake) |
| 1301 |
nursery.start_soon(server.do_handshake) |
| 1302 |
|
| 1303 |
assert client.get_channel_binding() is not None |
| 1304 |
assert server.get_channel_binding() is not None |
| 1305 |
|
| 1306 |
assert client.get_channel_binding() == server.get_channel_binding() |
| 1307 |
|
| 1308 |
|
| 1309 |
async def test_getpeercert(client_ctx: SSLContext) -> None: |
| 1310 |
# Make sure we're not affected by https://bugs.python.org/issue29334 |
| 1311 |
client, server = ssl_memory_stream_pair(client_ctx) |
| 1312 |
|
| 1313 |
async with _core.open_nursery() as nursery: |
| 1314 |
nursery.start_soon(client.do_handshake) |
| 1315 |
nursery.start_soon(server.do_handshake) |
| 1316 |
|
| 1317 |
assert server.getpeercert() is None |
| 1318 |
print(client.getpeercert()) |
| 1319 |
assert ("DNS", "trio-test-1.example.org") in client.getpeercert()["subjectAltName"] |
| 1320 |
|
| 1321 |
|
| 1322 |
async def test_SSLListener(client_ctx: SSLContext) -> None: |
| 1323 |
async def setup( |
| 1324 |
https_compatible: bool = False, |
| 1325 |
) -> tuple[tsocket.SocketType, SSLListener[SocketStream], SSLStream[SocketStream]]: |
| 1326 |
listen_sock = tsocket.socket() |
| 1327 |
await listen_sock.bind(("127.0.0.1", 0)) |
| 1328 |
listen_sock.listen(1) |
| 1329 |
socket_listener = SocketListener(listen_sock) |
| 1330 |
ssl_listener = SSLListener( |
| 1331 |
socket_listener, |
| 1332 |
SERVER_CTX, |
| 1333 |
https_compatible=https_compatible, |
| 1334 |
) |
| 1335 |
|
| 1336 |
transport_client = await open_tcp_stream(*listen_sock.getsockname()) |
| 1337 |
ssl_client = SSLStream( |
| 1338 |
transport_client, |
| 1339 |
client_ctx, |
| 1340 |
server_hostname="trio-test-1.example.org", |
| 1341 |
) |
| 1342 |
return listen_sock, ssl_listener, ssl_client |
| 1343 |
|
| 1344 |
listen_sock, ssl_listener, ssl_client = await setup() |
| 1345 |
|
| 1346 |
async with ssl_client: |
| 1347 |
ssl_server = await ssl_listener.accept() |
| 1348 |
|
| 1349 |
async with ssl_server: |
| 1350 |
assert not ssl_server._https_compatible |
| 1351 |
|
| 1352 |
# Make sure the connection works |
| 1353 |
async with _core.open_nursery() as nursery: |
| 1354 |
nursery.start_soon(ssl_client.do_handshake) |
| 1355 |
nursery.start_soon(ssl_server.do_handshake) |
| 1356 |
|
| 1357 |
# Test SSLListener.aclose |
| 1358 |
await ssl_listener.aclose() |
| 1359 |
assert listen_sock.fileno() == -1 |
| 1360 |
|
| 1361 |
################ |
| 1362 |
|
| 1363 |
# Test https_compatible |
| 1364 |
_, ssl_listener, ssl_client = await setup(https_compatible=True) |
| 1365 |
|
| 1366 |
ssl_server = await ssl_listener.accept() |
| 1367 |
|
| 1368 |
assert ssl_server._https_compatible |
| 1369 |
|
| 1370 |
await aclose_forcefully(ssl_listener) |
| 1371 |
await aclose_forcefully(ssl_client) |
| 1372 |
await aclose_forcefully(ssl_server) |