Title: ssl: PySSL_SetError leaves the ERR_LIB_SYS entry on the OpenSSL error queue, so every later SSL I/O on that thread fails with the same OSError · Issue #158313 · python/cpython · GitHub
Open Graph Title: ssl: PySSL_SetError leaves the ERR_LIB_SYS entry on the OpenSSL error queue, so every later SSL I/O on that thread fails with the same OSError · Issue #158313 · python/cpython
X Title: ssl: PySSL_SetError leaves the ERR_LIB_SYS entry on the OpenSSL error queue, so every later SSL I/O on that thread fails with the same OSError · Issue #158313 · python/cpython
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 s...
Open Graph 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 ...
X 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 ...
Opengraph URL: https://github.com/python/cpython/issues/158313
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"ssl: PySSL_SetError leaves the ERR_LIB_SYS entry on the OpenSSL error queue, so every later SSL I/O on that thread fails with the same OSError","articleBody":"# Bug report\n\n### Bug description\n\nSince 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`:\n\n```c\nif (ERR_GET_LIB(e) == ERR_LIB_SYS) {\n // A system error is being reported; reason is set to errno\n errno = ERR_GET_REASON(e);\n return PyErr_SetFromErrno(PyExc_OSError);\n}\n```\n\nThe 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.\n\nOpenSSL'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 (would-block, EOF, …), **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.\n\nNothing in the ssl module recovers from this. What sometimes does is a coincidence: OpenSSL's `state_machine()` calls `ERR_clear_error()` on entry, so a post-handshake message (e.g. a TLS 1.3 NewSessionTicket) processed inside a later read cleans up by accident. That is why this is hard to see in small tests and easy to hit in a long-running client that handshakes connections on one thread and reads them on another.\n\n### Reproducer\n\nLoopback only; needs the `openssl` CLI for a throwaway certificate.\n\n```python\n\"\"\"Two TLS connections on loopback. The peer resets the first; sending on it raises ConnectionResetError,\nwhich is correct. The second connection is healthy and idle, so recv() on it should wait for the timeout.\nInstead it raises ConnectionResetError at once, and keeps doing so on every call.\n\nSession tickets are switched off on purpose: TLS 1.3 sends them after the handshake and the client processes\nthem inside its next read, which runs OpenSSL's state machine, whose entry point calls ERR_clear_error() and\nwould hide the bug by coincidence.\"\"\"\nimport os, socket, ssl, struct, subprocess, sys, tempfile, threading, time\n\nprint(sys.version.split()[0], ssl.OPENSSL_VERSION, sys.platform)\nd = tempfile.mkdtemp()\ncrt, key = os.path.join(d, \"cert.pem\"), os.path.join(d, \"key.pem\")\nsubprocess.run([\"openssl\", \"req\", \"-x509\", \"-newkey\", \"ec\", \"-pkeyopt\", \"ec_paramgen_curve:prime256v1\", \"-nodes\",\n \"-keyout\", key, \"-out\", crt, \"-days\", \"1\", \"-subj\", \"/CN=localhost\"], check=True, capture_output=True)\nserver_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\nserver_ctx.load_cert_chain(crt, key)\nserver_ctx.num_tickets = 0\nclient_ctx = ssl.create_default_context()\nclient_ctx.check_hostname, client_ctx.verify_mode = False, ssl.CERT_NONE\n\nlistener = socket.socket()\nlistener.bind((\"127.0.0.1\", 0))\nlistener.listen(5)\nheld = []\n\ndef serve():\n while True:\n conn, _ = listener.accept()\n tls = server_ctx.wrap_socket(conn, server_side=True)\n tls.settimeout(10)\n if tls.recv(16) == b\"reset\":\n raw = socket.socket(fileno=tls.detach())\n raw.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack(\"ii\", 1, 0))\n raw.close() # RST, no close_notify\n else:\n held.append(tls) # stays open and silent\n\nthreading.Thread(target=serve, daemon=True).start()\n\ndef connect(first_message):\n c = client_ctx.wrap_socket(socket.create_connection(listener.getsockname()), server_hostname=\"localhost\")\n c.settimeout(1)\n c.send(first_message)\n return c\n\ndef show(label, op):\n t = time.time()\n try:\n r = op()\n print(f\"{label}: returned {r!r} after {time.time() - t:.2f}s\")\n except Exception as e:\n print(f\"{label}: {type(e).__name__}({getattr(e, 'errno', None)}) after {time.time() - t:.2f}s\")\n\nhealthy = connect(b\"idle\")\nshow(\"healthy.recv() before \", lambda: healthy.recv(100)) # TimeoutError after 1s: correct\nbroken = connect(b\"reset\")\ntime.sleep(0.2)\nshow(\"broken.send() after peer RST\", lambda: broken.send(b\"x\")) # ConnectionResetError: correct\nfor i in range(3):\n show(f\"healthy.recv() after, try {i + 1}\", lambda: healthy.recv(100)) # expected: TimeoutError after 1s\n```\n\nPython 3.12.13, OpenSSL 3.5.5, Linux aarch64 (the `python:3.12-slim` image):\n\n```\nhealthy.recv() before : TimeoutError(None) after 1.00s\nbroken.send() after peer RST: ConnectionResetError(104) after 0.00s\nhealthy.recv() after, try 1: ConnectionResetError(104) after 0.00s\nhealthy.recv() after, try 2: ConnectionResetError(104) after 0.00s\nhealthy.recv() after, try 3: ConnectionResetError(104) after 0.00s\n```\n\nThe `ConnectionResetError` from `broken.send()` is correct. The three from `healthy.recv()` are not: that connection is open and idle, and `recv()` should have waited 1 s and raised `TimeoutError`, as it did before.\n\nSame script on Python 3.12.8, OpenSSL 3.5.7, macOS (predates the backport):\n\n```\nhealthy.recv() before : TimeoutError(None) after 1.00s\nbroken.send() after peer RST: SSLError(5) after 0.00s\nhealthy.recv() after, try 1: TimeoutError(None) after 1.00s\nhealthy.recv() after, try 2: TimeoutError(None) after 1.00s\nhealthy.recv() after, try 3: TimeoutError(None) after 1.00s\n```\n\n(The `SSLError` for the reset connection is the older, less precise report that GH-127361 improved on; the healthy connection is unaffected because that code path ends in `fill_and_set_sslerror()` + `ERR_clear_error()`.)\n\n### How it was found\n\nslack_sdk's builtin Socket Mode client reads every WebSocket connection it will ever have on one long-lived thread and handshakes new ones on another. One TLS connection reset by a network gateway put the receive thread's queue in this state. From then on every new connection was established fine, delivered one record, and failed with `BrokenPipeError` on the first would-block read — reconnect, repeat every 10 seconds, for three days, with the process otherwise healthy. `strace` showed no failing syscall at all in those cycles (the read returned `EAGAIN`), and reading the thread's queue through ctypes showed two entries: `SSL_R_UNEXPECTED_EOF_WHILE_READING` from the reset and `ERR_LIB_SYS`/`EPIPE` from OpenSSL's attempt to send the alert (`tls_retry_write_records`), so `SSL_get_error()` answered `SSL_ERROR_SSL` and the early return in *that* case was the one taken. Calling `ERR_clear_error()` from the receive thread recovered the client immediately.\n\n### Suggested fix\n\nCall `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.)\n\n### CPython versions tested on\n\n3.12.13 (affected); 3.12.8 (not affected). The same two early returns are on `main` today.\n\n### Operating systems tested on\n\nLinux (aarch64, Debian-based `python:3.12-slim`); macOS for the unaffected comparison.\n\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-158333\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/liaoruoxing","@type":"Person","name":"liaoruoxing"},"datePublished":"2026-09-28T06:11:58Z","url":"https://github.com/python/cpython/issues/158313"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:82952b63-fa82-1112-95c6-6fdc25c7429a |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E0CE:17FB7:3C39ED9:4C3EA4C:6B023ABE |
| html-safe-nonce | 3ed2379092958f5a57ed3ec777dc8e0d251e017a7afbccc074687f91e9c5d43b |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFMENFOjE3RkI3OjNDMzlFRDk6NEMzRUE0Qzo2QjAyM0FCRSIsInZpc2l0b3JfaWQiOiIzODMwODY5MjMzNjIxOTQwOTI2IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | ca87a0ddc6e90beedd750cde43ab9bfb05739dcdbdf6e86a324f3094b1e550a9 |
| hovercard-subject-tag | issue:5610179156 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/158313/issue_layout |
| twitter:image | https://opengraph.githubassets.com/2f9ff1eeaf85ae73f13d76e6c81ee31b4d77a68fd1c374c673f053af72a23c1c/python/cpython/issues/158313 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/2f9ff1eeaf85ae73f13d76e6c81ee31b4d77a68fd1c374c673f053af72a23c1c/python/cpython/issues/158313 |
| og:image:alt | 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 ... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | liaoruoxing |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width