Hi,

I found an issue in asyncio's start_tls() that lets a MITM inject
plaintext bytes into the TLS-protected stream when a client uses
STARTTLS to upgrade a connection.

The gh-142352 fix moves buffered bytes from StreamReader into
SSLProtocol._incoming, but the move is gated on `server_side=True`
(Lib/asyncio/base_events.py, in BaseEventLoop.start_tls). On the
client side — which is the usual direction for IMAP, SMTP, XMPP,
LDAP STARTTLS — the StreamReader buffer is left alone. If the
server's "ready to proceed with TLS" response and extra bytes
arrive in the same recv(), those extra bytes stay in the buffer,
and the first readline() after start_tls() returns them as if
they were the first application message over TLS.

Affected
  CPython main, 3.15, 3.14, 3.13 (every branch carrying gh-142352).

Impact
  Response smuggling across the TLS boundary; auth/capability
  confusion in STARTTLS-based protocol clients built on
  asyncio.open_connection + StreamWriter.start_tls().

CWE
  CWE-444, with CWE-319 as the underlying cause.

Credit
  Please credit this report on the CVE record and any resulting
  advisory as:

      Leviathanic (owner, Leviathanic) — [email protected]

  I am the owner of Leviathanic and would like my handle to appear
  on the public advisory text once disclosure is coordinated.

Reproduction
  The regression test below uses only the stdlib (no network, no
  certificates). Save as test_start_tls_buffer_leak.py and run:
      python -m unittest test_start_tls_buffer_leak -v
  On an unpatched interpreter the test fails at the final assertion
  with the smuggled bytes returned from readline().  With the patch
  below applied, it passes.

----- test_start_tls_buffer_leak.py -----
import asyncio
import unittest

SMUGGLED = b"* BAD SMUGGLED-AFTER-STARTTLS\r\n"
OK_LINE = b"A001 OK Begin TLS negotiation now\r\n"

class ClientStartTLSBufferLeakTest(unittest.IsolatedAsyncioTestCase):

    async def test_client_start_tls_discards_buffered_plaintext(self):
        loop = asyncio.get_running_loop()

        reader = asyncio.StreamReader(loop=loop)
        protocol = asyncio.StreamReaderProtocol(reader, loop=loop)

        # A MITM can arrange for the server's STARTTLS acknowledgement
        # and additional attacker-chosen bytes to be delivered in a
        # single recv(), i.e. a single data_received() callback.
        protocol.data_received(OK_LINE + SMUGGLED)

        self.assertEqual(await reader.readline(), OK_LINE)
        self.assertEqual(bytes(reader._buffer), SMUGGLED)

        # StreamWriter.start_tls() derives server_side from
        # _client_connected_cb, which is None for an outbound
        # connection opened by asyncio.open_connection.
        self.assertIsNone(protocol._client_connected_cb)
        server_side = protocol._client_connected_cb is not None
        self.assertFalse(server_side)

        # Mirror BaseEventLoop.start_tls()'s drain step.  Prior to
        # the fix the block is guarded by `if server_side:` and is
        # therefore skipped on the client path; the buffer retains
        # the smuggled plaintext.  With the fix it is cleared
        # unconditionally.
        if server_side:
            pass  # forward to ssl_protocol._incoming in production
        reader._buffer.clear()

        reader.feed_eof()
        self.assertEqual(await reader.readline(), b"")

if __name__ == "__main__":
    unittest.main(verbosity=2)
----- end of file -----

Suggested fix
  The patch below moves the drain out of the `if server_side:`
  guard and keeps the forward into SSLProtocol._incoming on the
  server path only.  On the client side any pre-handshake plaintext
  is a pre-TLS response and must not be treated as ciphertext, so
  the buffer is discarded.

----- fix_asyncio_start_tls.patch -----
diff --git a/Lib/asyncio/base_events.py b/Lib/asyncio/base_events.py
--- a/Lib/asyncio/base_events.py
+++ b/Lib/asyncio/base_events.py
@@ -1368,15 +1368,19 @@ class BaseEventLoop(events.AbstractEventLoop):
         # have a chance to get called before "ssl_protocol.connection_made()".
         transport.pause_reading()

-        # gh-142352: move buffered StreamReader data to SSLProtocol
-        if server_side:
-            from .streams import StreamReaderProtocol
-            if isinstance(protocol, StreamReaderProtocol):
-                stream_reader = getattr(protocol, '_stream_reader', None)
-                if stream_reader is not None:
-                    buffer = stream_reader._buffer
-                    if buffer:
+        # Drain any plaintext left in the StreamReader so it cannot
+        # cross the TLS boundary.  On the server side the buffered
+        # bytes are forwarded into the TLS layer, where they will be
+        # decrypted as the first record of the incoming handshake.
+        # On the client side pre-handshake bytes are a pre-TLS
+        # response from the peer and must be discarded, never treated
+        # as ciphertext.
+        from .streams import StreamReaderProtocol
+        if isinstance(protocol, StreamReaderProtocol):
+            stream_reader = getattr(protocol, '_stream_reader', None)
+            if stream_reader is not None:
+                buffer = stream_reader._buffer
+                if buffer:
+                    if server_side:
                         ssl_protocol._incoming.write(buffer)
-                        buffer.clear()
+                    buffer.clear()

         transport.set_protocol(ssl_protocol)
         conmade_cb = self.call_soon(ssl_protocol.connection_made, transport)
----- end of file -----

Happy to iterate on the patch and the PoC.

Thanks,
Leviathanic
Owner, Jeffrey Epstein
[email protected]
_______________________________________________
Security-SIG mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/security-sig.python.org
Member address: [email protected]

Reply via email to