Repository navigation
Prevent stale OpenSSL errors from breaking asynchronous TLS connections - #116692
thevar1able merged 20 commits into
Conversation
|
Workflow [PR], commit [61ad6d8] Summary: ✅
AI ReviewSummaryThis PR hardens asynchronous TLS handling around OpenSSL's thread-local error queue, retry classification, fatal-shutdown rules, and Silk/connection-pool probing. I re-checked the current head against the full diff and every prior review thread; the previously reported issues are fixed in the current code, and I did not find any remaining blockers or major correctness risks. Tests
Final Verdict✅ Approve from a code-review standpoint. LLVM Coverage ReportMeasured on commit 61ad6d8.
Changed lines: Changed C/C++ lines covered: 61/71 (85.92%) · Uncovered code |
…-3916-openssl-error-queue
Address `catch_all` and `arm_tidy` diagnostics in the new TLS regression tests while keeping cleanup failures visible. ClickHouse#116692
Build profile diff (arm_release)Commit See the job log for details. |
Record fatal probe failures in `SecureSocketImpl` so later `shutdown` skips the forbidden `SSL_shutdown` path. Related: ClickHouse#116692
Clear errno before each `performSSLOperation` invocation so a stale retriable value cannot affect OpenSSL error classification. Initialize `SSLSocketStateResult` for static analysis and add a custom `BIO` regression test for the empty error-queue path. Related: ClickHouse#116692
…916-openssl-error-queue
|
None of the current CI failures appears to be introduced by this PR:
|
|
Heh, I just spent the last day or so debugging this exact issue, so thanks for finding (and fixing) this! FWIW, running And end up with a stack trace like this Digging through the clickhouse traces brought us to the same conclusion you reached and summarized nicely for the changelog
|
…916-openssl-error-queue # Conflicts: # base/poco/NetSSL_OpenSSL/src/SecureSocketImpl.cpp
…916-openssl-error-queue
Cherry pick #116692 to 26.3: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
…asynchronous TLS connections
Backport #116692 to 26.8: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
Backport #116692 to 26.3: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
SSL_want_write() reads rwstate, which the next SSL_read overwrites. When a read times out after a timed-out SSL_write, ssl3_read_bytes resets rwstate at start: and the retry path of ossl_tls_handle_rlayer_return sets it to SSL_READING (contrib/openssl/ssl/record/rec_layer_s3.c:683, :497), while wpend_tot stays positive. The guard in shutdown() then saw no pending write, the first SSL_shutdown queued close_notify behind the pending record without doing any I/O, SSL_get_error reported SSL_ERROR_WANT_READ off the stale state, and mustRetry polled SELECT_READ for a fresh max(send, receive) before throwing Poco::TimeoutException. Any other read in between does the same, e.g. the SSL_peek probe in src/IO/SocketPeerClosed.cpp. Record the state where it is created instead. sendBytes sets _pendingWrite when SSL_write returns SSL_ERROR_WANT_WRITE, which leaves its record pending, and clears it when SSL_write completes; acceptSSL and connectSSL reset it together with the new SSL object. shutdown() does not retry while it is set: only a retried SSL_write flushes that record, so the retry could never make progress. The new SSLSocketTimeout.ShutdownAfterSendAndReceiveTimeoutsDoesNotWaitForPeer adds a timed-out receiveBytes between the send timeout and shutdown(), and asserts that SSL_want_write() is false at that point. With the previous guard it fails with elapsed 10009 ms and Poco::TimeoutException; now it takes 0.7 s. Removing the assignment in sendBytes makes both shutdown tests fail the same way. All 39 TLS, socket and Silk fiber unit tests pass, including SilkFiberSecureSocketTest.BlockingShutdownRetriesWantWrite, which pins the backpressure retry from ClickHouse#116692; the shutdown tests passed 40x repeated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closing a TLS socket whose last write timed out blocked for another
max(send_timeout, receive_timeout) inside SecureSocketImpl::shutdown() and then
threw Poco::TimeoutException. Measured on an INSERT INTO FUNCTION
url('https://...') against a peer that accepts, handshakes and never reads, with
http_send_timeout=1 and http_receive_timeout=9: 27.3 s before this change,
18.3 s after, i.e. exactly one max(send, receive) removed from socket teardown,
and the delta scales with that setting (7.4 s -> 5.6 s at receive_timeout=2).
Every direct shutdown() caller reachable from src/ already catches
Poco::TimeoutException, so the consequence is latency rather than a new escaping
exception.
An abandoned SSL_write leaves the OpenSSL record layer with wpend_tot > 0 and
rwstate == SSL_WRITING (contrib/openssl/ssl/record/rec_layer_s3.c:497), and
neither sendBytes timeout exit sets _fatalError, so shutdown() enters its retry
loop with a fresh getMaxTimeoutOrLimit() budget. There, ssl3_send_alert refuses
to dispatch close_notify while RECORD_LAYER_write_pending() is true
(contrib/openssl/ssl/s3_msg.c:68) and returns without performing any I/O, so
SSL_get_error reports SSL_ERROR_WANT_WRITE off the stale rwstate and Poco polls
SELECT_WRITE against a peer whose TCP window is zero until the budget is gone.
Retrying in that state can never succeed. A second SSL_shutdown reaches
ssl3_dispatch_alert, whose pending-write arm only retries when alert_dispatch is
SSL_ALERT_DISPATCH_RETRY; it is SSL_ALERT_DISPATCH_PENDING here, so it takes the
"API misuse?? Give up" branch (s3_msg.c:107-116). Only re-calling SSL_write with
the identical buffer could flush the pending record, and Poco has already
discarded it. A third call would fall into ssl_read_bytes and wait for the peer's
close_notify, the wait the comment above this block says Poco deliberately
avoids.
SSL_want_write() is the public spelling of rwstate == SSL_WRITING, and rwstate is
only set to SSL_WRITING on the same ossl_tls_handle_rlayer_return retry path that
assigns wpend_tot, so the predicate implies a pending record write and cannot
disable a retry that could have worked. The backpressure retry is preserved:
SilkFiberSecureSocketTest.BlockingShutdownRetriesWantWrite still asserts two
SSL_shutdown writes and a close_notify observed by the peer. Everything after the
loop is unchanged, so handleError still returns ERR_SSL_WANT_WRITE without
setting _fatalError and the transport is still shut down. That is the observable
behaviour of 26.3, 26.7, 26.8 and 26.9, none of which carry the retry loop.
The loop condition dates from 001fb05 (ClickHouse#116692, merged 2026-09-24), so no
released version is affected and no changelog entry is required. That PR's
backports ClickHouse#122201 (26.3) and ClickHouse#122197 (26.8) are still open and would import the
regression.
A successful read before the close resets rwstate while wpend_tot stays positive,
so the stall persists in that narrower shape. The exact predicate,
RECORD_LAYER_write_pending(), is declared in the private header
ssl/record/record.h and is not reachable from base/poco.
The new test goes in the existing src/Common/tests/gtest_ssl_send_timeout.cpp,
whose SSLSocketTimeout suite already builds the precondition: a never-reading TLS
peer and a sendBytes that throws. It requires that timeout first, then times
shutdown() with the receive timeout raised to 10 s, and also asserts that
SSL_SENT_SHUTDOWN is set so that skipping the orderly shutdown altogether cannot
pass. Without the guard it fails with elapsed 10009 ms and Poco::TimeoutException;
with it the whole test takes 0.5 s. All 38 TLS and socket unit tests pass, 50x
repeated.
|
@thevar1able I am confused. You merged into 26.3, but closed to 26.7? What about the other backports? Should they be done? |
|
@PedroTadim |
Cherry pick #116692 to 26.9: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
…asynchronous TLS connections
Backport #116692 to 26.9: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
…sl-error-queue Prevent stale OpenSSL errors from breaking asynchronous TLS connections
Cherry pick #116692 to 26.7: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
…asynchronous TLS connections
Backport #116692 to 26.7: Prevent stale OpenSSL errors from breaking asynchronous TLS connections
The strict server rejects a client that sends no certificate. Under TLS 1.3 the client finishes its handshake before the server checks the client certificate, so it writes its native Hello right away. The server tears the failed session down with shutdown(SHUT_RDWR) (FIN) followed by close() with the client's Finished record still unread (RST), so the client receives alert, FIN, RST. If its Hello write comes after both, the RST hits a socket in CLOSE_WAIT, the kernel reports EPIPE, and the client fails with "I/O error: Broken pipe, while writing to socket" without reading the alert. Before the orderly shutdown for sessions that died with a fatal error (ClickHouse#116692) the teardown was RST only, which gives ECONNRESET, the case ClickHouse#93539 already accepts. Which TCP event reaches the client first is not what the test checks: it checks that the connection is refused. pytest.raises still fails the test if the connection is accepted, and the message list still excludes a client-side verification failure. Seen twice on the 26.3 release branch (amd_tsan) after the ClickHouse#116692 backport. Forcing a 300 ms delay on every client socket write with strace reproduces the CI message 5/5 on 26.3.43.4 and on master, and gives "Connection reset by peer" on 26.3.33.24 (before the backport). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Motivation
OpenSSL keeps its error queue in thread-local storage rather than in an individual
SSLobject. TheSSL_get_errorcontract therefore requires the queue to be empty before TLS I/O, and the correspondingSSL_get_errorcall to run immediately afterwards on the same OS thread without intervening OpenSSL calls.SecureSocketImpldid not clear the error queue before its TLS operations and evaluatedSSL_get_errormore than once for the same result. An error left while handling or shutting down one connection could consequently be interpreted as the result of an operation on another connection later using the same OS thread. This could surface as a misleading TLS exception and terminate a distributed query even though the reported peer connection was operating normally.The Silk TLS
BIOmade this more likely because it could suspend a fiber from insideSSL_readorSSL_write. A suspended fiber may resume on another OS thread before OpenSSL finishes the operation and its result is classified.Implementation
A common TLS operation wrapper now:
errnoimmediately after the operation;SSL_get_errorexactly once and before any other OpenSSL function;The saved values are passed to
mustRetryandhandleError, so neither function queries mutable thread-local state again. Retry is restricted to explicitly retriable conditions rather than being inferred from an unrelated leftoverEINTR.Connections that encounter a fatal
SSL_ERROR_SSLorSSL_ERROR_SYSCALLare marked unusable. Their underlying transport is closed without callingSSL_shutdown, as required by theSSL_shutdowncontract. A zero return fromSSL_shutdownis handled as an incomplete orderly shutdown rather than passed toSSL_get_error.The previous write-error workaround performed an auxiliary
SSL_readafter a connection reset. It has been removed because it could silently consume application data that was already buffered by OpenSSL.Silk integration
The Silk
BIOnow performs only non-blockingrecvandsendoperations. OnEAGAIN, it sets the appropriateBIOretry flag and returns control to OpenSSL.SecureSocketImplthen saves theSSL_get_errorresult before performing a timed fiber-aware wait throughpollImpl.This keeps the complete OpenSSL operation and its error classification on one OS thread while preserving asynchronous waiting and socket timeouts.
For immediately available data, the direct syscall avoids creating an I/O future. When a socket returns
EAGAIN, the new path performs an additional non-blocking syscall and OpenSSL retry around the asynchronous poll. It does not add data copies, busy waiting, or blocking of an OS thread.Regression coverage
The added tests verify that:
shutdown while in initerror does not change the result of another TLS connection;SSL_shutdown;SSL_writedoes not consume pending application data;SSL_readandSSL_peekcalls return retry conditions without suspending inside OpenSSL;Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed asynchronous TLS connections occasionally failing with an unrelated OpenSSL error left by another connection on the same OS thread. This could terminate distributed queries with a misleading network exception.
Workflow [PR]
Sync PR [sync-upstream/pr/116692]
Version info
26.10.1.616-master(included in26.10and later)26.9.8.8,26.8.11.48,26.7.23.7,26.3.33.154