You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pulsar.apache.org by lh...@apache.org on 2026/10/05 19:08:49 UTC

(pulsar) 02/03: [fix][broker] Close Conscrypt SSL engines when Jetty closes a TLS connection (#26812)

This is an automated email from the ASF dual-hosted git repository.

lhotari pushed a commit to branch branch-4.2
in repository https://gitbox.apache.org/repos/asf/pulsar.git

commit ee6b42a20c848f29fc6fe1406382b17ae7341b8f
Author: Lari Hotari <lh...@users.noreply.github.com>
AuthorDate: Fri Oct 2 22:29:25 2026 +0300

    [fix][broker] Close Conscrypt SSL engines when Jetty closes a TLS connection (#26812)
    
    (cherry picked from commit bf4215ba12876e0c1d8b86e024edc41ad6c5f76c)
---
 .../jetty/tls/PulsarSslConnectionFactory.java      |  84 +++++++++++++++
 .../org/apache/pulsar/broker/web/WebService.java   |   5 +-
 .../jetty/tls/PulsarSslConnectionFactoryTest.java  | 120 +++++++++++++++++++++
 .../pulsar/functions/worker/rest/WorkerServer.java |   5 +-
 .../org/apache/pulsar/proxy/server/WebServer.java  |   5 +-
 .../pulsar/websocket/service/ProxyServer.java      |   5 +-
 6 files changed, 216 insertions(+), 8 deletions(-)

diff --git a/pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/PulsarSslConnectionFactory.java b/pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/PulsarSslConnectionFactory.java
new file mode 100644
index 000000000000..5c9d5930d387
--- /dev/null
+++ b/pulsar-broker-common/src/main/java/org/apache/pulsar/jetty/tls/PulsarSslConnectionFactory.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.jetty.tls;
+
+import com.google.common.annotations.VisibleForTesting;
+import javax.net.ssl.SSLEngine;
+import lombok.extern.slf4j.Slf4j;
+import org.eclipse.jetty.io.Connection;
+import org.eclipse.jetty.io.EndPoint;
+import org.eclipse.jetty.io.ssl.SslConnection;
+import org.eclipse.jetty.server.Connector;
+import org.eclipse.jetty.server.SslConnectionFactory;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+
+/**
+ * A Jetty {@link SslConnectionFactory} that closes a Conscrypt {@link SSLEngine} when its connection closes.
+ *
+ * <p>Jetty's {@link SslConnection} closes the engine's inbound side only when the peer sends a TLS
+ * {@code close_notify}. A client that drops the TCP connection without one leaves the engine open, and Conscrypt
+ * then releases the native {@code SSL} object only when the engine is finalized. For an engine that was not
+ * closed, {@code ConscryptEngine.finalize()} reads the native session, while {@code NativeSsl.finalize()} frees the
+ * same native object. The two finalizers use different locks, so when they run on two threads at once (as they do
+ * with {@code System.runFinalization()}), the read can reach freed memory and crash the JVM with SIGSEGV.
+ *
+ * <p>Closing both sides when the connection closes moves the engine to its closed state on the thread that closed
+ * the connection, while the native {@code SSL} object is still alive. The finalizer then skips the session read.
+ * Only Conscrypt engines are closed this way: other providers, such as SunJSSE, treat a {@code closeInbound()}
+ * without the peer's {@code close_notify} as a fatal error and invalidate the session.
+ */
+@Slf4j
+public class PulsarSslConnectionFactory extends SslConnectionFactory {
+    private static final Connection.Listener CLOSE_CONSCRYPT_ENGINE_ON_CLOSE = new Connection.Listener() {
+        @Override
+        public void onClosed(Connection connection) {
+            if (connection instanceof SslConnection sslConnection) {
+                closeConscryptEngine(sslConnection.getSSLEngine());
+            }
+        }
+    };
+
+    public PulsarSslConnectionFactory(SslContextFactory.Server factory, String nextProtocol) {
+        super(factory, nextProtocol);
+    }
+
+    @Override
+    protected SslConnection newSslConnection(Connector connector, EndPoint endPoint, SSLEngine engine) {
+        SslConnection sslConnection = super.newSslConnection(connector, endPoint, engine);
+        if (isConscryptEngine(engine)) {
+            sslConnection.addEventListener(CLOSE_CONSCRYPT_ENGINE_ON_CLOSE);
+        }
+        return sslConnection;
+    }
+
+    @VisibleForTesting
+    static boolean isConscryptEngine(SSLEngine engine) {
+        return engine.getClass().getName().startsWith("org.conscrypt.");
+    }
+
+    @VisibleForTesting
+    static void closeConscryptEngine(SSLEngine engine) {
+        try {
+            engine.closeOutbound();
+            engine.closeInbound();
+        } catch (Exception e) {
+            log.debug("Failed to close the SSL engine of a closed connection", e);
+        }
+    }
+}
diff --git a/pulsar-broker/src/main/java/org/apache/pulsar/broker/web/WebService.java b/pulsar-broker/src/main/java/org/apache/pulsar/broker/web/WebService.java
index 3c830e01ab38..b1cef32f568a 100644
--- a/pulsar-broker/src/main/java/org/apache/pulsar/broker/web/WebService.java
+++ b/pulsar-broker/src/main/java/org/apache/pulsar/broker/web/WebService.java
@@ -47,6 +47,7 @@ import org.apache.pulsar.common.util.PulsarSslConfiguration;
 import org.apache.pulsar.common.util.PulsarSslFactory;
 import org.apache.pulsar.jetty.metrics.JettyStatisticsCollector;
 import org.apache.pulsar.jetty.tls.JettySslContextFactory;
+import org.apache.pulsar.jetty.tls.PulsarSslConnectionFactory;
 import org.eclipse.jetty.ee8.nested.ContextHandler;
 import org.eclipse.jetty.ee8.nested.ResourceHandler;
 import org.eclipse.jetty.ee8.servlet.FilterHolder;
@@ -66,7 +67,6 @@ import org.eclipse.jetty.server.RequestLog;
 import org.eclipse.jetty.server.SecureRequestCustomizer;
 import org.eclipse.jetty.server.Server;
 import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.SslConnectionFactory;
 import org.eclipse.jetty.server.handler.ContextHandlerCollection;
 import org.eclipse.jetty.server.handler.DefaultHandler;
 import org.eclipse.jetty.server.handler.QoSHandler;
@@ -178,7 +178,8 @@ public class WebService implements AutoCloseable {
                 if (config.isWebServiceHaProxyProtocolEnabled()) {
                     connectionFactories.add(new ProxyConnectionFactory());
                 }
-                connectionFactories.add(new SslConnectionFactory(sslCtxFactory, httpConnectionFactory.getProtocol()));
+                connectionFactories.add(
+                        new PulsarSslConnectionFactory(sslCtxFactory, httpConnectionFactory.getProtocol()));
                 connectionFactories.add(httpConnectionFactory);
                 // org.eclipse.jetty.server.AbstractConnectionFactory.getFactories contains similar logic
                 // this is needed for TLS authentication
diff --git a/pulsar-broker/src/test/java/org/apache/pulsar/jetty/tls/PulsarSslConnectionFactoryTest.java b/pulsar-broker/src/test/java/org/apache/pulsar/jetty/tls/PulsarSslConnectionFactoryTest.java
new file mode 100644
index 000000000000..57545af974bc
--- /dev/null
+++ b/pulsar-broker/src/test/java/org/apache/pulsar/jetty/tls/PulsarSslConnectionFactoryTest.java
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.pulsar.jetty.tls;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import com.google.common.io.Resources;
+import java.io.File;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.security.KeyStore;
+import java.time.Duration;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.SSLSocket;
+import org.apache.pulsar.common.util.SecurityUtility;
+import org.awaitility.Awaitility;
+import org.eclipse.jetty.io.Connection;
+import org.eclipse.jetty.io.ssl.SslConnection;
+import org.eclipse.jetty.server.HttpConnectionFactory;
+import org.eclipse.jetty.server.Server;
+import org.eclipse.jetty.server.ServerConnector;
+import org.eclipse.jetty.util.ssl.SslContextFactory;
+import org.testng.SkipException;
+import org.testng.annotations.Test;
+
+@Test(groups = "broker")
+public class PulsarSslConnectionFactoryTest {
+    private static final String CA = resource("certificate-authority/certs/ca.cert.pem");
+    private static final String BROKER_CERT = resource("certificate-authority/server-keys/broker.cert.pem");
+    private static final String BROKER_KEY = resource("certificate-authority/server-keys/broker.key-pk8.pem");
+
+    /**
+     * A client that resets the connection without a TLS close_notify must not leave the server's Conscrypt engine
+     * open. Otherwise its native SSL object is released only by the engine's finalizer, which can race with the
+     * NativeSsl finalizer and crash the JVM.
+     */
+    @Test
+    public void closesConscryptEngineWhenClientResetsConnection() throws Exception {
+        if (SecurityUtility.CONSCRYPT_PROVIDER == null) {
+            throw new SkipException("Conscrypt is not available on this platform");
+        }
+        KeyStore keyStore = KeyStore.getInstance("PKCS12");
+        keyStore.load(null, null);
+        keyStore.setKeyEntry("broker", SecurityUtility.loadPrivateKeyFromPemFile(BROKER_KEY), new char[0],
+                SecurityUtility.loadCertificatesFromPemFile(BROKER_CERT));
+        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+        keyManagerFactory.init(keyStore, new char[0]);
+        SSLContext serverContext = SSLContext.getInstance("TLS", SecurityUtility.CONSCRYPT_PROVIDER);
+        serverContext.init(keyManagerFactory.getKeyManagers(), null, null);
+        SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
+        sslContextFactory.setSslContext(serverContext);
+
+        Server server = new Server();
+        HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory();
+        ServerConnector connector = new ServerConnector(server,
+                new PulsarSslConnectionFactory(sslContextFactory, httpConnectionFactory.getProtocol()),
+                httpConnectionFactory);
+        connector.setHost(InetAddress.getLoopbackAddress().getHostAddress());
+        connector.setPort(0);
+        CompletableFuture<SslConnection> closedConnection = new CompletableFuture<>();
+        connector.addEventListener(new Connection.Listener() {
+            @Override
+            public void onClosed(Connection connection) {
+                if (connection instanceof SslConnection sslConnection) {
+                    closedConnection.complete(sslConnection);
+                }
+            }
+        });
+        server.addConnector(connector);
+        server.start();
+        try {
+            SSLContext clientContext = SecurityUtility.createSslContext(false,
+                    SecurityUtility.loadCertificatesFromPemFile(CA), null, null);
+            try (Socket socket = new Socket(InetAddress.getLoopbackAddress(), connector.getLocalPort())) {
+                SSLSocket sslSocket = (SSLSocket) clientContext.getSocketFactory()
+                        .createSocket(socket, "localhost", connector.getLocalPort(), false);
+                sslSocket.startHandshake();
+                // Reset the TCP connection without sending a close_notify.
+                socket.setSoLinger(true, 0);
+            }
+
+            SslConnection sslConnection = closedConnection.get(30, TimeUnit.SECONDS);
+            SSLEngine engine = sslConnection.getSSLEngine();
+            assertThat(PulsarSslConnectionFactory.isConscryptEngine(engine)).isTrue();
+            Awaitility.await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
+                    assertThat(engine.isInboundDone()).as("inbound side of the server engine is closed").isTrue());
+        } finally {
+            server.stop();
+        }
+    }
+
+    @Test
+    public void doesNotCloseEnginesOfOtherProviders() throws Exception {
+        SSLEngine engine = SSLContext.getDefault().createSSLEngine();
+        assertThat(PulsarSslConnectionFactory.isConscryptEngine(engine)).isFalse();
+    }
+
+    private static String resource(String name) {
+        return new File(Resources.getResource(name).getPath()).getAbsolutePath();
+    }
+}
diff --git a/pulsar-functions/worker/src/main/java/org/apache/pulsar/functions/worker/rest/WorkerServer.java b/pulsar-functions/worker/src/main/java/org/apache/pulsar/functions/worker/rest/WorkerServer.java
index e65760caf891..ced73b16ade9 100644
--- a/pulsar-functions/worker/src/main/java/org/apache/pulsar/functions/worker/rest/WorkerServer.java
+++ b/pulsar-functions/worker/src/main/java/org/apache/pulsar/functions/worker/rest/WorkerServer.java
@@ -44,6 +44,7 @@ import org.apache.pulsar.functions.worker.rest.api.v2.WorkerApiV2Resource;
 import org.apache.pulsar.functions.worker.rest.api.v2.WorkerStatsApiV2Resource;
 import org.apache.pulsar.jetty.metrics.JettyStatisticsCollector;
 import org.apache.pulsar.jetty.tls.JettySslContextFactory;
+import org.apache.pulsar.jetty.tls.PulsarSslConnectionFactory;
 import org.eclipse.jetty.ee8.servlet.FilterHolder;
 import org.eclipse.jetty.ee8.servlet.ServletContextHandler;
 import org.eclipse.jetty.ee8.servlet.ServletHolder;
@@ -58,7 +59,6 @@ import org.eclipse.jetty.server.ProxyConnectionFactory;
 import org.eclipse.jetty.server.SecureRequestCustomizer;
 import org.eclipse.jetty.server.Server;
 import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.SslConnectionFactory;
 import org.eclipse.jetty.server.handler.ContextHandlerCollection;
 import org.eclipse.jetty.server.handler.DefaultHandler;
 import org.eclipse.jetty.server.handler.QoSHandler;
@@ -188,7 +188,8 @@ public class WorkerServer {
                 if (workerConfig.isWebServiceHaProxyProtocolEnabled()) {
                     connectionFactories.add(new ProxyConnectionFactory());
                 }
-                connectionFactories.add(new SslConnectionFactory(sslCtxFactory, httpConnectionFactory.getProtocol()));
+                connectionFactories.add(
+                        new PulsarSslConnectionFactory(sslCtxFactory, httpConnectionFactory.getProtocol()));
                 connectionFactories.add(httpConnectionFactory);
                 // org.eclipse.jetty.server.AbstractConnectionFactory.getFactories contains similar logic
                 // this is needed for TLS authentication
diff --git a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/WebServer.java b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/WebServer.java
index 3fc78e9f5259..b2629f962aae 100644
--- a/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/WebServer.java
+++ b/pulsar-proxy/src/main/java/org/apache/pulsar/proxy/server/WebServer.java
@@ -56,6 +56,7 @@ import org.apache.pulsar.common.util.PulsarSslConfiguration;
 import org.apache.pulsar.common.util.PulsarSslFactory;
 import org.apache.pulsar.jetty.metrics.JettyStatisticsCollector;
 import org.apache.pulsar.jetty.tls.JettySslContextFactory;
+import org.apache.pulsar.jetty.tls.PulsarSslConnectionFactory;
 import org.apache.pulsar.proxy.stats.PulsarProxyOpenTelemetry;
 import org.eclipse.jetty.ee8.servlet.FilterHolder;
 import org.eclipse.jetty.ee8.servlet.ServletContextHandler;
@@ -72,7 +73,6 @@ import org.eclipse.jetty.server.ProxyConnectionFactory;
 import org.eclipse.jetty.server.SecureRequestCustomizer;
 import org.eclipse.jetty.server.Server;
 import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.SslConnectionFactory;
 import org.eclipse.jetty.server.handler.ContextHandlerCollection;
 import org.eclipse.jetty.server.handler.DefaultHandler;
 import org.eclipse.jetty.server.handler.QoSHandler;
@@ -163,7 +163,8 @@ public class WebServer {
                 if (config.isWebServiceHaProxyProtocolEnabled()) {
                     connectionFactories.add(new ProxyConnectionFactory());
                 }
-                connectionFactories.add(new SslConnectionFactory(sslCtxFactory, httpConnectionFactory.getProtocol()));
+                connectionFactories.add(
+                        new PulsarSslConnectionFactory(sslCtxFactory, httpConnectionFactory.getProtocol()));
                 connectionFactories.add(httpConnectionFactory);
                 // org.eclipse.jetty.server.AbstractConnectionFactory.getFactories contains similar logic
                 // this is needed for TLS authentication
diff --git a/pulsar-websocket/src/main/java/org/apache/pulsar/websocket/service/ProxyServer.java b/pulsar-websocket/src/main/java/org/apache/pulsar/websocket/service/ProxyServer.java
index 88ff5e8374a0..570d3818dc90 100644
--- a/pulsar-websocket/src/main/java/org/apache/pulsar/websocket/service/ProxyServer.java
+++ b/pulsar-websocket/src/main/java/org/apache/pulsar/websocket/service/ProxyServer.java
@@ -39,6 +39,7 @@ import org.apache.pulsar.common.util.DefaultPulsarSslFactory;
 import org.apache.pulsar.common.util.PulsarSslConfiguration;
 import org.apache.pulsar.common.util.PulsarSslFactory;
 import org.apache.pulsar.jetty.tls.JettySslContextFactory;
+import org.apache.pulsar.jetty.tls.PulsarSslConnectionFactory;
 import org.eclipse.jetty.ee8.servlet.ServletContextHandler;
 import org.eclipse.jetty.ee8.servlet.ServletHolder;
 import org.eclipse.jetty.ee8.websocket.server.config.JettyWebSocketServletContainerInitializer;
@@ -53,7 +54,6 @@ import org.eclipse.jetty.server.ProxyConnectionFactory;
 import org.eclipse.jetty.server.SecureRequestCustomizer;
 import org.eclipse.jetty.server.Server;
 import org.eclipse.jetty.server.ServerConnector;
-import org.eclipse.jetty.server.SslConnectionFactory;
 import org.eclipse.jetty.server.handler.ContextHandlerCollection;
 import org.eclipse.jetty.server.handler.QoSHandler;
 import org.eclipse.jetty.util.ssl.SslContextFactory;
@@ -127,7 +127,8 @@ public class ProxyServer {
                 if (config.isWebServiceHaProxyProtocolEnabled()) {
                     connectionFactories.add(new ProxyConnectionFactory());
                 }
-                connectionFactories.add(new SslConnectionFactory(sslCtxFactory, httpConnectionFactory.getProtocol()));
+                connectionFactories.add(
+                        new PulsarSslConnectionFactory(sslCtxFactory, httpConnectionFactory.getProtocol()));
                 connectionFactories.add(httpConnectionFactory);
                 // org.eclipse.jetty.server.AbstractConnectionFactory.getFactories contains similar logic
                 // this is needed for TLS authentication