Skip to content

TLSStream.send loses an already-encrypted record when cancelled, corrupting the TLS stream #1385

Closed

Description

@doerus

Things to check first

  • I have searched the existing issues and didn't find my bug already reported there

  • I have checked that my bug is still present in the latest release

AnyIO version

4.15.1 (also 4.14.2)

Python version

3.13.5

What happened?

When a TLSStream.send() is cancelled, the stream can be left corrupted for every later send.

_call_sslobject_method calls SSLObject.write(), which encrypts the data into the write BIO and uses up the next TLS record sequence number. It then flushes the BIO with await self.transport_stream.send(self._write_bio.read()). SocketStream.send checkpoints before it calls transport.write(). If the cancel lands at that checkpoint, the encrypted bytes have already been taken out of the BIO, so they are gone. The peer never receives that record. Every record after it has a sequence number the peer doesn't expect, so the peer fails with DECRYPTION_FAILED_OR_BAD_RECORD_MAC and closes the connection with a fatal alert.

I expected one of two outcomes. Either the cancelled send has no effect on the stream, or the record that was already encrypted is still delivered. In both cases later sends would keep working.

We hit this in production through httpcore's HTTP/2 client. Many requests share one TLS connection, and the task reading a response also writes to it (WINDOW_UPDATE frames, PING acks). When a client disconnects, the server framework cancels that task. If the cancel lands during one of those writes, the upstream answers with SSLV3_ALERT_BAD_RECORD_MAC and every other request on the connection fails with it.

Shielding the flush fixes the reproducer below:

            else:
                # Flush any pending writes first
                if self._write_bio.pending:
                    with CancelScope(shield=True):
                        await self.transport_stream.send(self._write_bio.read())

                return result

How can we reproduce the bug?

import ssl

import anyio
import trustme
from anyio.streams.tls import TLSStream

ca = trustme.CA()
server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ca.issue_cert("localhost").configure_cert(server_context)
client_context = ssl.create_default_context()
ca.configure_trust(client_context)


async def serve(stream):
    tls = await TLSStream.wrap(stream, server_side=True, ssl_context=server_context)
    try:
        while True:
            print("server got:", await tls.receive())
    except ssl.SSLError as exc:
        print("server error:", exc)


async def main():
    async with await anyio.create_tcp_listener(local_host="127.0.0.1") as listener:
        async with anyio.create_task_group() as tg:
            tg.start_soon(listener.serve, serve)
            port = listener.extra(anyio.abc.SocketAttribute.local_port)
            client = await anyio.connect_tcp(
                "127.0.0.1", port, ssl_context=client_context, tls_hostname="localhost"
            )
            await client.send(b"first")

            # A send cancelled before it starts (e.g. the caller hung up).
            with anyio.CancelScope() as scope:
                scope.cancel()
                await client.send(b"cancelled")

            await client.send(b"second")
            await anyio.sleep(0.5)
            tg.cancel_scope.cancel()


anyio.run(main)

Output:

server got: b'first'
server error: [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC] decryption failed or bad record mac (_ssl.c:2648)

With the shielded flush applied:

server got: b'first'
server got: b'cancelled'
server got: b'second'

Activity

  1. added
    bug
    on Oct 5, 2026
  2. agronholm commented on Oct 5, 2026

    @agronholm
    Owner

    Shielding the send() seems risky, as it could potentially hang forever, and won't respect timeouts.

  3. agronholm commented on Oct 5, 2026

    @agronholm
    Owner

    I was thinking of stashing the chunk if sending is cancelled, but what happens if it gets partially sent?

  4. gschaffner commented on Oct 7, 2026

    @gschaffner
    Collaborator

    Shielding the send() seems risky, as it could potentially hang forever, and won't respect timeouts.

    Agreed, we definitely cannot shield that.

    TLSStream's cancellation semantics are consistent with the cancellation semantics of trio.abc.SendStream.send_all and trio.SSLStream.send_all:

    Most low-level operations in Trio provide a guarantee: if they raise trio.Cancelled, this means that they had no effect, so the system remains in a known state. This is not true for send_all(). If this operation raises trio.Cancelled (or any other exception for that matter), then it may have sent some, all, or none of the requested data, and there is no way to know which. [src]

    Warning

    If this method is cancelled, then it may leave the SSLStream in an unusable state. If this happens then any attempt to use the object will raise trio.BrokenResourceError. [src]

  5. gschaffner commented on Oct 7, 2026

    @gschaffner
    Collaborator

    Actually, AnyIO probably isn't making subsequent calls raise BrokenResourceError in this case. I think that that is the right fix here.

  6. gschaffner commented on Oct 7, 2026

    @gschaffner
    Collaborator

    I was thinking of stashing the chunk if sending is cancelled, but what happens if it gets partially sent?

    You can never know if it got partially sent. So you must assume that ByteSendStream.send raising Cancelled left the stream in an unknown state, which (for almost all wire protocols) means that the stream is effectively lost/broken and you can't use it anymore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions