Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .licenserc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,8 @@ header:
- 'Jenkinsfile'
- '**/vendor/**'
- '**/src/test/resources/certs/**'
- 'dubbo-remoting/dubbo-remoting-netty4/src/test/resources/tls-hostname/*.pem'
- 'dubbo-remoting/dubbo-remoting-netty4/src/test/resources/tls-hostname/*.key'
- '**/src/test/resources/definition/**'
- 'dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocal.java'
- 'dubbo-common/src/main/java/org/apache/dubbo/common/threadlocal/InternalThreadLocalMap.java'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ protected void initChannel(SocketChannel ch) throws Exception {
int heartbeatInterval = UrlUtils.getHeartbeat(getUrl());

if (sslContext != null) {
ch.pipeline().addLast("negotiation", new SslClientTlsHandler(sslContext));
ch.pipeline().addLast("negotiation", new SslClientTlsHandler(sslContext, getConnectAddress()));
}

NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ protected void initChannel(SocketChannel ch) {
NettySslContextOperator nettySslContextOperator = new NettySslContextOperator();

if (sslContext != null) {
pipeline.addLast("negotiation", new SslClientTlsHandler(sslContext));
pipeline.addLast("negotiation", new SslClientTlsHandler(sslContext, getConnectAddress()));
}

// pipeline.addLast("logging", new LoggingHandler(LogLevel.INFO)); //for debug
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSession;

import java.net.InetSocketAddress;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.ssl.SslContext;
Expand All @@ -38,18 +40,26 @@ public class SslClientTlsHandler extends ChannelInboundHandlerAdapter {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(SslClientTlsHandler.class);
private static final AttributeKey<SSLSession> SSL_SESSION_KEY = AttributeKey.valueOf(Constants.SSL_SESSION_KEY);
private final SslContext sslContext;
private final InetSocketAddress peerAddress;

public SslClientTlsHandler(URL url) {
this(SslContexts.buildClientSslContext(url));
this(SslContexts.buildClientSslContext(url), url.toInetSocketAddress());
}

public SslClientTlsHandler(SslContext sslContext) {
this(sslContext, null);
}

public SslClientTlsHandler(SslContext sslContext, InetSocketAddress peerAddress) {
this.sslContext = sslContext;
this.peerAddress = peerAddress;
}

@Override
public void handlerAdded(ChannelHandlerContext ctx) {
SSLEngine sslEngine = sslContext.newEngine(ctx.alloc());
SSLEngine sslEngine = peerAddress == null
? sslContext.newEngine(ctx.alloc())
: sslContext.newEngine(ctx.alloc(), peerAddress.getHostString(), peerAddress.getPort());
ctx.pipeline().addAfter(ctx.name(), null, new SslHandler(sslEngine, false));
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,256 @@
/*
* 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.dubbo.remoting.transport.netty4;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.SslConfig;
import org.apache.dubbo.remoting.transport.AbstractClient;
import org.apache.dubbo.remoting.transport.ChannelHandlerAdapter;
import org.apache.dubbo.remoting.transport.netty4.ssl.SslClientTlsHandler;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;

import javax.net.ssl.SSLException;

import java.io.InputStream;
import java.net.InetSocketAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.cert.CertificateException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.ClientAuth;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.SslHandshakeCompletionEvent;
import io.netty.handler.ssl.SslProvider;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;

/**
* Verifies hostname validation through both TCP client TLS pipelines.
*
* @date 2026-11-12
*/
class ClientTlsHostnameVerificationTest {

@TempDir
Path directory;

@ParameterizedTest
@ValueSource(booleans = {false, true})
void acceptsMatchingSubjectAlternativeName(boolean connectionClient) throws Exception {
assertHandshake(connectionClient, "server.pem", true);
}

@ParameterizedTest
@ValueSource(booleans = {false, true})
void rejectsMismatchedSubjectAlternativeName(boolean connectionClient) throws Exception {
assertHandshake(connectionClient, "wrong-host.pem", false);
}

@Test
void usesUrlAddressForLegacyConstructor() throws Exception {
FrameworkModel frameworkModel = new FrameworkModel();
EmbeddedChannel channel = null;
try {
ApplicationModel applicationModel = configureClient(frameworkModel, copyResource("ca.pem"));
URL url = URL.valueOf("empty://localhost:20880").setScopeModel(applicationModel.getDefaultModule());
channel = new EmbeddedChannel(new SslClientTlsHandler(url));
SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
assertNotNull(sslHandler);
assertEquals("localhost", sslHandler.engine().getPeerHost());
assertEquals(20880, sslHandler.engine().getPeerPort());
} finally {
try {
if (channel != null) {
channel.finishAndReleaseAll();
}
} finally {
frameworkModel.destroy();
}
}
}

@Test
void preservesContextOnlyConstructor() throws Exception {
SslContext context =
SslContextBuilder.forClient().sslProvider(SslProvider.JDK).build();
EmbeddedChannel channel = new EmbeddedChannel(new SslClientTlsHandler(context));
try {
SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
assertNotNull(sslHandler);
assertNull(sslHandler.engine().getPeerHost());
assertEquals(-1, sslHandler.engine().getPeerPort());
} finally {
channel.finishAndReleaseAll();
}
}

private void assertHandshake(boolean connectionClient, String serverCertificate, boolean expectedSuccess)
throws Exception {
Path trust = copyResource("ca.pem");
SslContext serverContext = SslContextBuilder.forServer(
copyResource(serverCertificate).toFile(),
copyResource("server.key").toFile())
.trustManager(trust.toFile())
.clientAuth(ClientAuth.REQUIRE)
.sslProvider(SslProvider.JDK)
.build();
BlockingQueue<SslHandshakeCompletionEvent> handshakes = new LinkedBlockingQueue<>();
BlockingQueue<Channel> acceptedChannels = new LinkedBlockingQueue<>();
EventLoopGroup group = new NioEventLoopGroup(1);
ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
FrameworkModel frameworkModel = new FrameworkModel();
AbstractClient client = null;
try {
Channel server = new ServerBootstrap()
.group(group)
.channel(NioServerSocketChannel.class)
// Delay server TLS until the client's SslHandler has been captured.
.childOption(ChannelOption.AUTO_READ, false)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel channel) {
channels.add(channel);
channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object event)
throws Exception {
if (event instanceof SslHandshakeCompletionEvent) {
handshakes.add((SslHandshakeCompletionEvent) event);
}
super.userEventTriggered(ctx, event);
}
});
acceptedChannels.add(channel);
}
})
.bind("127.0.0.1", 0)
.sync()
.channel();
channels.add(server);
ApplicationModel applicationModel = configureClient(frameworkModel, trust);
// Use mapped loopback so AbstractClient does not replace it with the machine address.
URL url = URL.valueOf("empty://[::ffff:127.0.0.1]:" + ((InetSocketAddress) server.localAddress()).getPort())
.addParameter("codec", "telnet")
.setScopeModel(applicationModel.getDefaultModule());
client = connectionClient
? new NettyConnectionClient(url, new ChannelHandlerAdapter())
: new NettyClient(url, new ChannelHandlerAdapter());
Channel nettyChannel = connectionClient
? ((NettyConnectionClient) client).<Channel>getChannel(Boolean.TRUE)
: ((NettyClient) client).getNettyChannel();
assertNotNull(nettyChannel);
SslHandler clientTls = nettyChannel.pipeline().get(SslHandler.class);
assertNotNull(clientTls);
assertEquals(
client.getConnectAddress().getHostString(),
clientTls.engine().getPeerHost());
assertEquals(
client.getConnectAddress().getPort(), clientTls.engine().getPeerPort());
Channel accepted = acceptedChannels.poll(5, TimeUnit.SECONDS);
assertNotNull(accepted, "The server did not accept the TCP connection");
accepted.eventLoop()
.submit(() -> {
accepted.pipeline().addFirst(serverContext.newHandler(accepted.alloc()));
accepted.config().setAutoRead(true);
})
.sync();
assertTrue(
clientTls.handshakeFuture().await(10, TimeUnit.SECONDS),
"The client TLS handshake did not complete");
assertEquals(
expectedSuccess,
clientTls.handshakeFuture().isSuccess(),
() -> "Client TLS handshake: " + clientTls.handshakeFuture().cause());
if (!expectedSuccess) {
assertSubjectAlternativeNameMismatch(clientTls.handshakeFuture().cause());
}
SslHandshakeCompletionEvent handshake = handshakes.poll(10, TimeUnit.SECONDS);
assertNotNull(handshake, "The server TLS handshake did not complete");
assertEquals(expectedSuccess, handshake.isSuccess(), () -> "Server TLS handshake: " + handshake.cause());
} finally {
if (client != null) {
client.close();
}
channels.close().awaitUninterruptibly();
frameworkModel.destroy();
group.shutdownGracefully(0, 5, TimeUnit.SECONDS).sync();
}
}

private void assertSubjectAlternativeNameMismatch(Throwable cause) {
assertInstanceOf(SSLException.class, cause);
for (Throwable current = cause; current != null; current = current.getCause()) {
if (current instanceof CertificateException
&& current.getMessage() != null
&& current.getMessage().contains("subject alternative")
&& current.getMessage().contains("127.0.0.1")) {
return;
}
}
fail("Expected a certificate SAN mismatch for 127.0.0.1", cause);
}

private ApplicationModel configureClient(FrameworkModel frameworkModel, Path trust) throws Exception {
ApplicationModel applicationModel = frameworkModel.newApplication();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig("tls-hostname-test"));
SslConfig sslConfig = new SslConfig();
sslConfig.setClientKeyCertChainPath(copyResource("client.pem").toString());
sslConfig.setClientPrivateKeyPath(copyResource("client.key").toString());
sslConfig.setClientTrustCertCollectionPath(trust.toString());
applicationModel.getApplicationConfigManager().setSsl(sslConfig);
return applicationModel;
}

private Path copyResource(String name) throws Exception {
Path destination = directory.resolve(name);
try (InputStream stream =
ClientTlsHostnameVerificationTest.class.getResourceAsStream("/tls-hostname/" + name)) {
Files.copy(stream, destination);
}
return destination;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDBzCCAe+gAwIBAgIUE8rx3Vh8pCFm0a4RO/jdmtMzTJswDQYJKoZIhvcNAQEL
BQAwEjEQMA4GA1UEAwwHcXVpYy1jYTAgFw0yNDA4MjEwNjM3NTlaGA8yMDc0MDgw
OTA2Mzc1OVowEjEQMA4GA1UEAwwHcXVpYy1jYTCCASIwDQYJKoZIhvcNAQEBBQAD
ggEPADCCAQoCggEBANQY2D0FKsC4hzsPYWMP7Wb0SMxQDbsY0TGBR++Y4CwwrVet
lFNpFMk9TiNcUmj3Hpy6T5zsZx6CC3Phl8JFdfD/jm4OPQxd4o7yQpcqCU1+sHuB
8P0diUa5PHwfEnRfkq4wdmUZ/wv/Cn/S1WjCW62nwIQ8QKAeuxEs/wibeAZl+576
fOi5q6XfcLncSfAranzOp9ETBkVM9IDl+RXX/Bc/QkiLGlRj4pCsnquAk0/r+m/E
fEkODANhp06CRY/S3khYaxi7nfNNIrwf/iU3mb2ZXJml/V6DQfoD0eQ3jeeGEGn/
mExY0kATrTSoIo9Th+V1VVRxuSn0mKtI17Lrqj0CAwEAAaNTMFEwHQYDVR0OBBYE
FAQr8dTHZueMEw3eIEyMBYrTFjptMB8GA1UdIwQYMBaAFAQr8dTHZueMEw3eIEyM
BYrTFjptMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBALNTH7Hx
l2nUxn68AHagnzYBGgGzJDmGGZU5tNuzPSTUnCDe+6x527KQsRMJ8gLBbAYzef07
98JK3SDKyl1AHus6oYBavtrE3D2vQXbCZSHR5BkdNsuwAxnqB+1qxfFCR3GUPry5
+KocqHHG1kBApHeSYM43mAbZ2bfo9BAHAu/xq4JDc8Hdm6bwFkdMsvkOZJAVtEYi
m+ARw6XvWOsp9atRnhzfCBBhpayl6NtsnNth1wY/FuSmm2ZUlDVMsa3hjSnY0/E/
aV9Mi1WvgGklc5efveGufoIYHy/twYwUtkYaz6Z1Z+TFoC2tTRjlXjESTN/ti+Un
XRMjTKn90G9c5bQ=
-----END CERTIFICATE-----
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC1jcPcCCtgysUO
YvtQkFU7OPAPUqP69M9pHvB61mGomrCfpeuzc2Xcdn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602j3HaCVrRR2GRGMi3zowhcFDSB50ClQUoQ2Oe1JJLqF/WxUXtpI/
n3poMnvynHrVzEHCOSbt24hKKs+C7zolJ2DSpxsMXOV5oBASsbsic+0lAoGBAIBe
zKK1hOHSPdvGyA+yHLtvgfMOAL9EKIuS54lBPOFewt7NY/+5TYuTWJ3C2idZEaOL
uaLPPbM37nfXFBEN/5xIAbf3Bw4Cxv8/d7RFaP/sjLK9316z91ZwfJwLFPY5RJk2
Uyf3l1j6jKJbIqPH7hCVMcYu4i73yhLun5sNUuyxAoGBAJTh0qK3MJPFFM0P5zqJ
gZsrQZi6DAawFiHnNdab99npti07zUvNtgcbdszLfcpHvYSMI1Xpg+hZqC1BifIj
hAQdZIc3APnGeCghjemDg2NWa2yHcqkKNVkVB7647bgsKP1ewg0GFFLN17XiUfiv
6/NvZACAHJCj0YqQUpJ8dsEK
-----END PRIVATE KEY-----
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-----BEGIN CERTIFICATE-----
MIIC+jCCAeKgAwIBAgIUFrQFPMAmmmGTMmlyK4+r3aaCRw0wDQYJKoZIhvcNAQEL
BQAwEjEQMA4GA1UEAwwHcXVpYy1jYTAgFw0yNDA4MjEwNjM4MjZaGA8yMDc0MDgw
OTA2MzgyNlowFjEUMBIGA1UEAwwLcXVpYy1jbGllbnQwggEiMA0GCSqGSIb3DQEB
AQUAA4IBDwAwggEKAoIBAQC1jcPcCCtgysUOYvtQkFU7OPAPUqP69M9pHvB61mGo
mrCfpeuzc2XcdnyDa/FBITH6Czd8p88eteXa+LpgOcrU+W93ziOLHXwS1mtETOSx
fzK+HQuwcUfhEGs/0HUc1wEfWeWldGaGri0COAtKI/vzqFaaspK+L4I++UvPO9ai
ypQ3WEwVlLgHnXckQl4fx8fi2HZ0wGKR7OoLKbVITlKopN0QqRnuA1L8vohrOf8P
51KioAWBDUsWJ54cnrla09NPEkEKu4DHz6aOGJTRYttsXQwNIPUeq6z+4GzVFDih
9sEI3rQFTQgXSLiUB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