Repository navigation
Description
Bug report
Bug description
Since gh-127257 (GH-127361; backported to 3.12 in GH-127905 and to 3.13 in GH-127812), PySSL_SetError maps an ERR_LIB_SYS entry on the OpenSSL error queue to OSError:
if (ERR_GET_LIB(e) == ERR_LIB_SYS) {
// A system error is being reported; reason is set to errno
errno = ERR_GET_REASON(e);
return PyErr_SetFromErrno(PyExc_OSError);
}The same block appears in both the SSL_ERROR_SYSCALL and the SSL_ERROR_SSL case. Both return early, before the ERR_clear_error() that every other exit of PySSL_SetError goes through (and that the neighbouring e == 0 branch of SSL_ERROR_SYSCALL calls explicitly). The entry therefore stays on the thread's error queue.
OpenSSL's SSL_get_error() inspects that queue before anything else — the man page says "The current thread's error queue must be empty before the TLS/SSL I/O operation is attempted, or SSL_get_error() will not work reliably" — so the next SSL_read_ex()/SSL_write_ex() on that thread that does not complete immediately, on any connection, is reported as SSL_ERROR_SYSCALL/SSL_ERROR_SSL; PySSL_SetError takes the same early return, raises the same stale OSError, and again does not clear. The thread stays poisoned for the life of the process.
This is particularly damaging for server-side thread pools. In a ThreadingMixIn/fixed-worker-thread HTTPS server, each worker thread handles connections sequentially for the whole process lifetime. A client that resets a connection while the server is writing its response (the normal sendall() → ECONNRESET → ConnectionResetError path, logged as "Broken pipe") now leaves ERR_LIB_SYS/104 on that worker's queue. Every subsequent connection assigned to that worker is killed a few milliseconds after the TLS handshake completes: the first recv() raises the stale ConnectionResetError at t=0, the handler closes the socket, and the client sees a FIN piggybacked on the tail of the handshake. Browsers render this as ERR_EMPTY_RESPONSE/ERR_SOCKET_NOT_CONNECTED. Because ordinary traffic (page refreshes aborting in-flight requests) keeps generating the trigger, a fixed pool degrades progressively — in our measurements, from a fully clean 20-thread pool to a 100 % poisoned pool within about 60 page refreshes (~1–2 minutes of real user activity) — and never recovers until process restart. netstat shows no backlog (connections die in 1–5 ms) and the server log only shows the legitimate-looking original BrokenPipeErrors, which makes the failure very hard to diagnose from the outside.
Python 3.11 does not have the early return: its SSL_ERROR_SYSCALL branch falls through to fill_and_set_sslerror() followed by an unconditional ERR_clear_error(), so the queue is always clean when PySSL_SetError returns, and unrelated connections are unaffected.
Reproducer
Loopback only; needs the openssl CLI for a throwaway certificate. The server keeps a fixed pool of worker threads, each handling connections sequentially — the same shape as any threaded HTTP server. The client sends a request and then aborts the connection with a pure RST (SO_LINGER on/off=1, linger=0) while the server is still writing the response, then opens a fresh connection and tries to read on it.
"""Racing-RST reproducer: a connection reset while the server is writing
its response poisons the worker thread's OpenSSL error queue via the
ERR_LIB_SYS early return in PySSL_SetError. The next, unrelated connection
handled by that worker is killed right after the TLS handshake: recv()
raises the stale ConnectionResetError at t=0 instead of waiting for data."""
import os, socket, ssl, struct, subprocess, sys, tempfile, threading, time
print(sys.version.split()[0], ssl.OPENSSL_VERSION, sys.platform)
d = tempfile.mkdtemp()
crt, key = os.path.join(d, "cert.pem"), os.path.join(d, "key.pem")
subprocess.run(["openssl", "req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",
"-nodes", "-keyout", key, "-out", crt, "-days", "1", "-subj", "/CN=localhost"],
check=True, capture_output=True)
server_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
server_ctx.load_cert_chain(crt, key)
server_ctx.num_tickets = 0 # a post-handshake ticket would run the state
# machine, whose entry ERR_clear_error()
# would clean the queue by coincidence
client_ctx = ssl.create_default_context()
client_ctx.check_hostname, client_ctx.verify_mode = False, ssl.CERT_NONE
listener = socket.socket()
listener.bind(("127.0.0.1", 0))
listener.listen(64)
tasks = []
lock = threading.Lock()
def worker():
while True:
raw = tasks.pop(0) if tasks else None
if raw is None:
time.sleep(0.001)
continue
tls = None
try:
tls = server_ctx.wrap_socket(raw, server_side=True)
tls.settimeout(5)
tls.recv(65536) # read the request
tls.sendall(b"HTTP/1.1 200 OK\r\n" # write; fails if peer RST'd us
b"Content-Length: 2\r\n\r\nok")
except Exception as e:
print(f"[worker {threading.get_ident()}] {type(e).__name__}: {e!r}")
finally:
for s in (tls, raw):
try:
if s is not None:
s.close()
except Exception:
pass
# fixed pool: 2 workers, exactly like a threaded HTTP server
for _ in range(2):
threading.Thread(target=worker, daemon=True).start()
def acceptor():
while True:
raw, _ = listener.accept()
tasks.append(raw)
threading.Thread(target=acceptor, daemon=True).start()
addr = listener.getsockname()
def racing_rst():
"""Send a full request, then abort with a pure RST while the server
is still processing/writing, so its sendall() hits ECONNRESET."""
c = client_ctx.wrap_socket(socket.create_connection(addr), server_hostname="localhost")
c.sendall(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n")
c.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0))
c.close()
def hangup_probe(label):
"""Fresh, healthy connection: handshake, send a request, then read the
response. On a poisoned worker the read fails immediately with the stale
ConnectionResetError; on a clean worker it returns the response body."""
t0 = time.time()
try:
c = client_ctx.wrap_socket(socket.create_connection(addr), server_hostname="localhost")
c.settimeout(3)
c.sendall(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n")
body = c.recv(100)
print(f"{label}: returned {body!r} after {time.time() - t0:.2f}s")
except Exception as e:
print(f"{label}: {type(e).__name__}({getattr(e, 'errno', None)}) after {time.time() - t0:.2f}s")
time.sleep(0.3)
hangup_probe("probe before ")
for i in range(5):
racing_rst()
time.sleep(0.1)
hangup_probe("probe after 5 RSTs ")
for i in range(5):
racing_rst()
time.sleep(0.1)
hangup_probe("probe after 10 RSTs ")Python 3.12.10, OpenSSL 3.5.4, Linux x86-64 (openEuler; affected):
3.12.10 OpenSSL 3.5.4 15 Mar 2022 linux
probe before : returned b'HTTP/1.1 200 OK...ok' after 0.01s
[worker 140244818118400] ConnectionResetError: [Errno 104] Connection reset by peer
[worker 140244818118400] ConnectionResetError: [Errno 104] Connection reset by peer
...
probe after 5 RSTs : ConnectionResetError(104) after 0.00s
[worker 140244818118400] ConnectionResetError: [Errno 104] Connection reset by peer
...
probe after 10 RSTs : ConnectionResetError(104) after 0.00s
The ConnectionResetErrors printed by the worker for the racing-RST connections are correct — the peer really reset those. The two from hangup_probe are not: those connections are healthy, their requests were accepted, and recv() should have returned the response, as it did in the "before" probe. Instead the stale ERR_LIB_SYS/104 entry left by the previous connection makes SSL_get_error() report SSL_ERROR_SYSCALL, PySSL_SetError takes the ERR_LIB_SYS early return, and the fresh connection is killed. The worker never recovers; every later connection it handles fails the same way.
Same script on Python 3.11.4, OpenSSL 1.1.1n, Linux x86-64 (not affected):
3.11.4 OpenSSL 1.1.1n 15 Mar 2022 linux
probe before : returned b'HTTP/1.1 200 OK...ok' after 0.01s
[worker 139812345678912] ConnectionResetError: [Errno 104] Connection reset by peer
...
probe after 5 RSTs : returned b'HTTP/1.1 200 OK...ok' after 0.01s
probe after 10 RSTs : returned b'HTTP/1.1 200 OK...ok' after 0.01s
The reset connections still raise the correct ConnectionResetError, but the healthy probe connections are unaffected, because 3.11's PySSL_SetError always reaches the unconditional ERR_clear_error().
How it was found
A Django-based HTTPS management tool (custom threaded WSGI server, 20 fixed worker threads, TLS terminated in Python) became unreachable from browsers within minutes of startup: ERR_EMPTY_RESPONSE/ERR_SOCKET_NOT_CONNECTED on every refresh, while netstat showed no established-connection backlog and the access log kept recording a subset of requests (the workers that were still clean). A process restart restored service, and the failure reappeared after another few minutes of use. Server-side packet capture showed the server sending a FIN ~1–5 ms after completing the TLS handshake, before any HTTP request byte arrived, piggybacked on the second NewSessionTicket — the client had done nothing wrong.
strace on a poisoned worker showed the signature: read(fd, ...) = -1 EAGAIN, then, 0.7 ms later and with no intervening syscall, the Python-level exception traceback was written and the socket shut down. The EAGAIN means the kernel was healthy — the exception was manufactured in user space. Dumping the thread's OpenSSL error queue through ctypes showed a residual ERR_LIB_SYS/104 entry; calling ERR_clear_error() from the worker thread instantly restored it. Adding ERR_clear_error() calls at connection-handling boundaries (after each processed request in the worker threads, and after accept/handshake in the acceptor thread) eliminated the failure completely in A/B testing: 250 racing-RST bursts left a patched server fully healthy (20/20 probe connections alive, 0 killed), while the unpatched server had every probe connection killed right after the handshake.
Suggested fix
Call ERR_clear_error() before the two return PyErr_SetFromErrno(PyExc_OSError) in the ERR_LIB_SYS branches, as the e == 0 branch of SSL_ERROR_SYSCALL already does. (The broader request to clear the queue before every I/O call is gh-81891 / bpo-37710; this report is about the specific regression from GH-127361.)
CPython versions tested on
3.12.10 (affected); 3.11.4 (not affected). The same two early returns are present in the 3.12.10 sources at Modules/_ssl.c lines 654-657 (SSL_ERROR_SYSCALL) and 684-687 (SSL_ERROR_SSL), before the ERR_clear_error() at line 697.
Operating systems tested on
Linux x86-64 (openEuler, vendor-hardened kernel) for both the affected 3.12.10 + OpenSSL 3.5.4 deployment and the unaffected 3.11.4 + OpenSSL 1.1.1n comparison.
Activity