From ed42e8052f12be3b64aff30305045d0587522278 Mon Sep 17 00:00:00 2001 From: Luke Gruber Date: Fri, 20 Nov 2026 15:19:06 -0500 Subject: [PATCH] ssl: clear @callback_state before re-raising handshake callback exception ossl_start_ssl() re-raises an exception saved by a callback (servername_cb, alpn_select_cb, session_get_cb, tmp_dh_callback, ...) with rb_jump_tag(), but leaves @callback_state set. If the application rescues the failed accept / connect and then calls #sysread / #syswrite on the same SSLSocket, ossl_ssl_read() / ossl_ssl_write() find the stale state and rb_jump_tag(TAG_RAISE) with no pending exception (errinfo is nil). The process then segfaults. Reset the ivar before jumping, as the read/write paths already do. The next I/O call then fails normally with OpenSSL::SSL::SSLError. NOTE: I couldn't find any misuses in the wild. --- ext/openssl/ossl_ssl.c | 1 + test/openssl/test_ssl.rb | 1 + 2 files changed, 2 insertions(+) diff --git a/ext/openssl/ossl_ssl.c b/ext/openssl/ossl_ssl.c index 25f3cc4f2..f3c1f382b 100644 --- a/ext/openssl/ossl_ssl.c +++ b/ext/openssl/ossl_ssl.c @@ -1898,6 +1898,7 @@ ossl_start_ssl(VALUE self, int (*func)(SSL *), const char *funcname) cb_state = rb_attr_get(self, ID_callback_state); if (!NIL_P(cb_state)) { + rb_ivar_set(self, ID_callback_state, Qnil); /* must cleanup OpenSSL error stack before re-raising */ ossl_clear_error(); rb_jump_tag(NUM2INT(cb_state)); diff --git a/test/openssl/test_ssl.rb b/test/openssl/test_ssl.rb index d65949744..ca1e11c34 100644 --- a/test/openssl/test_ssl.rb +++ b/test/openssl/test_ssl.rb @@ -1244,6 +1244,7 @@ def test_servername_cb_exception sctx.servername_cb = lambda { |args| raise RuntimeError, "foo" } ssl = OpenSSL::SSL::SSLSocket.new(sock, sctx) assert_raise_with_message(RuntimeError, "foo") { ssl.accept } + assert_raise(OpenSSL::SSL::SSLError) { ssl.syswrite("a") } end start_server_proc(server_proc) do |port| sock = TCPSocket.new("127.0.0.1", port)