Skip to content

Commit 9e811f1

Browse files
kieran-farrellcoffeys
authored andcommitted
8346705: SNI not sent with Java 22+ using java.net.http.HttpClient.Builder#sslParameters
Backport-of: 72f1114909854aaed5d190d1c74a98527600a0c2
1 parent f1b1fd4 commit 9e811f1

File tree

3 files changed

+268
-12
lines changed

3 files changed

+268
-12
lines changed

src/java.net.http/share/classes/jdk/internal/net/http/AbstractAsyncSSLConnection.java

Lines changed: 44 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved.
2+
* Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved.
33
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
44
*
55
* This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,7 @@
2626
package jdk.internal.net.http;
2727

2828
import java.net.InetSocketAddress;
29+
import java.net.http.HttpClient;
2930
import java.util.Arrays;
3031
import java.util.ArrayDeque;
3132
import java.util.List;
@@ -75,7 +76,7 @@ abstract class AbstractAsyncSSLConnection extends HttpConnection
7576
ServerName serverName, int port,
7677
String[] alpn) {
7778
super(addr, client);
78-
this.sniServerNames = formSNIServerNames(serverName);
79+
this.sniServerNames = formSNIServerNames(serverName, client);
7980
SSLContext context = client.theSSLContext();
8081
sslParameters = createSSLParameters(client, this.sniServerNames, alpn);
8182
Log.logParams(sslParameters);
@@ -102,6 +103,20 @@ private static boolean contains(String[] rr, String target) {
102103
return false;
103104
}
104105

106+
/**
107+
* Returns the {@link SSLParameters} to be used by the {@link SSLEngine} for this connection.
108+
* <p>
109+
* The returned {@code SSLParameters} will have its {@link SNIServerName}s set to the given
110+
* {@code sniServerNames}. If {@code alpn} is non-null then the returned {@code SSLParameters}
111+
* will have its {@linkplain SSLParameters#getApplicationProtocols() application layer protocols}
112+
* set to this value. All other parameters in the returned {@code SSLParameters} will be
113+
* copied over from {@link HttpClient#sslParameters()} of the given {@code client}.
114+
*
115+
* @param client the HttpClient
116+
* @param sniServerNames the SNIServerName(s)
117+
* @param alpn the application layer protocols
118+
* @return the SSLParameters to be set on the SSLEngine used by this connection.
119+
*/
105120
private static SSLParameters createSSLParameters(HttpClientImpl client,
106121
List<SNIServerName> sniServerNames,
107122
String[] alpn) {
@@ -132,22 +147,39 @@ private static SSLParameters createSSLParameters(HttpClientImpl client,
132147
return sslParameters;
133148
}
134149

135-
private static List<SNIServerName> formSNIServerNames(final ServerName serverName) {
136-
if (serverName == null) {
137-
return List.of();
138-
}
139-
if (!serverName.isLiteral()) {
140-
String name = serverName.name();
141-
if (name != null && name.length() > 0) {
150+
/**
151+
* Returns a list of {@link SNIServerName}s that are expected to be used to
152+
* configure the {@link SSLEngine} used by this connection.
153+
* <p>
154+
* The given {@code serverName} is given preference, and if it is not null and
155+
* is not an IP address literal, then the returned list will contain only one
156+
* {@code SNIServerName} formed out of the {@code serverName}. If {@code serverName}
157+
* is null or is an IP address literal then the {@code SNIServerName}(s)
158+
* configured through {@link HttpClient#sslParameters()} will be returned. If none have
159+
* been configured, then an empty list is returned.
160+
*
161+
* @param serverName the {@link ServerName}, typically computed based on the request URI
162+
* @param client the {@code HttpClient}
163+
* @return a list of {@code SNIServerName}s to be used by the {@code SSLEngine}
164+
* of this connection.
165+
*/
166+
private static List<SNIServerName> formSNIServerNames(final ServerName serverName,
167+
final HttpClientImpl client) {
168+
if (serverName != null && !serverName.isLiteral()) {
169+
final String name = serverName.name();
170+
if (name != null && !name.isEmpty()) {
142171
return List.of(new SNIHostName(name));
143172
}
144173
}
145-
return List.of();
174+
// fallback on any SNIServerName(s) configured through HttpClient.sslParameters()
175+
final SSLParameters clientSSLParams = client.sslParameters();
176+
final List<SNIServerName> clientConfigured = clientSSLParams.getServerNames();
177+
return clientConfigured != null ? clientConfigured : List.of();
146178
}
147179

148-
private static SSLEngine createEngine(SSLContext context, String serverName, int port,
180+
private static SSLEngine createEngine(SSLContext context, String peerHost, int port,
149181
SSLParameters sslParameters) {
150-
SSLEngine engine = context.createSSLEngine(serverName, port);
182+
SSLEngine engine = context.createSSLEngine(peerHost, port);
151183
engine.setUseClientMode(true);
152184

153185
engine.setSSLParameters(sslParameters);
Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
/*
2+
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
3+
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4+
*
5+
* This code is free software; you can redistribute it and/or modify it
6+
* under the terms of the GNU General Public License version 2 only, as
7+
* published by the Free Software Foundation.
8+
*
9+
* This code is distributed in the hope that it will be useful, but WITHOUT
10+
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11+
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12+
* version 2 for more details (a copy is included in the LICENSE file that
13+
* accompanied this code).
14+
*
15+
* You should have received a copy of the GNU General Public License version
16+
* 2 along with this work; if not, write to the Free Software Foundation,
17+
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18+
*
19+
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20+
* or visit www.oracle.com if you need additional information or have any
21+
* questions.
22+
*/
23+
24+
import java.io.IOException;
25+
import java.io.OutputStream;
26+
import java.net.InetAddress;
27+
import java.net.InetSocketAddress;
28+
import java.net.URI;
29+
import java.net.http.HttpClient;
30+
import java.net.http.HttpRequest;
31+
import java.net.http.HttpResponse;
32+
import java.net.http.HttpResponse.BodyHandlers;
33+
import java.util.List;
34+
35+
import javax.net.ssl.SNIHostName;
36+
import javax.net.ssl.SNIMatcher;
37+
import javax.net.ssl.SSLContext;
38+
import javax.net.ssl.SSLParameters;
39+
40+
import com.sun.net.httpserver.HttpsConfigurator;
41+
import com.sun.net.httpserver.HttpsParameters;
42+
import com.sun.net.httpserver.HttpsServer;
43+
import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestExchange;
44+
import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestHandler;
45+
import jdk.httpclient.test.lib.common.HttpServerAdapters.HttpTestServer;
46+
import jdk.httpclient.test.lib.common.ServerNameMatcher;
47+
import jdk.test.lib.net.SimpleSSLContext;
48+
import jdk.test.lib.net.URIBuilder;
49+
import org.junit.jupiter.api.BeforeAll;
50+
import org.junit.jupiter.params.ParameterizedTest;
51+
import org.junit.jupiter.params.provider.ValueSource;
52+
import static java.nio.charset.StandardCharsets.US_ASCII;
53+
import static org.junit.jupiter.api.Assertions.assertEquals;
54+
import static org.junit.jupiter.api.Assertions.assertFalse;
55+
import static org.junit.jupiter.api.Assertions.assertNotNull;
56+
import static org.junit.jupiter.api.Assertions.assertTrue;
57+
58+
/*
59+
* @test
60+
* @bug 8346705
61+
* @summary verify the behaviour of java.net.http.HttpClient
62+
* when sending a Server Name Indication in the TLS
63+
* connections that it establishes for the requests
64+
* @library /test/lib /test/jdk/java/net/httpclient/lib
65+
* @build jdk.httpclient.test.lib.common.HttpServerAdapters
66+
* jdk.test.lib.net.SimpleSSLContext
67+
* jdk.test.lib.net.URIBuilder
68+
* @run junit HttpClientSNITest
69+
*/
70+
public class HttpClientSNITest {
71+
private static final String RESP_BODY_TEXT = "hello world";
72+
73+
private static SSLContext sslContext;
74+
75+
private static final class Handler implements HttpTestHandler {
76+
77+
@Override
78+
public void handle(final HttpTestExchange exch) throws IOException {
79+
System.out.println("handling request " + exch.getRequestURI());
80+
final byte[] respBody = RESP_BODY_TEXT.getBytes(US_ASCII);
81+
exch.sendResponseHeaders(200, respBody.length);
82+
try (final OutputStream os = exch.getResponseBody()) {
83+
os.write(respBody);
84+
}
85+
}
86+
}
87+
88+
@BeforeAll
89+
static void beforeAll() throws Exception {
90+
sslContext = new SimpleSSLContext().get();
91+
assertNotNull(sslContext, "could not create a SSLContext");
92+
}
93+
94+
/*
95+
* Creates and configures a HTTPS server with a SNIMatcher that
96+
* expects a specific SNI name to be sent by the connection client.
97+
* The test uses a HttpClient to issue a couple of requests with the URI having
98+
* a IP address literal as the host. For one of the request, the HttpClient
99+
* is configured with specific ServerName(s) through HttpClient.sslParameters()
100+
* and for the other request, it isn't.
101+
* The test then verifies that for such requests with a IP address literal as the host,
102+
* the HttpClient sends across the ServerName(s) if any has been configured on the client.
103+
*/
104+
@ParameterizedTest
105+
@ValueSource(booleans = {false, true})
106+
void testRequestToIPLiteralHost(final boolean sniConfiguredOnClient) throws Exception {
107+
final String expectedSNI = "non-dns-resolvable.foo.bar.localhost";
108+
final ServerNameMatcher matcher = new ServerNameMatcher(expectedSNI);
109+
final HttpTestServer server = createServer(matcher);
110+
try {
111+
final HttpClient.Builder builder = HttpClient.newBuilder().sslContext(sslContext);
112+
if (sniConfiguredOnClient) {
113+
final SSLParameters clientConfiguredSSLParams = new SSLParameters();
114+
clientConfiguredSSLParams.setServerNames(List.of(new SNIHostName(expectedSNI)));
115+
builder.sslParameters(clientConfiguredSSLParams);
116+
}
117+
try (final HttpClient client = builder.build()) {
118+
final String ipLiteral = InetAddress.getLoopbackAddress().getHostAddress();
119+
final URI reqURI = URIBuilder.newBuilder()
120+
.host(ipLiteral)
121+
.port(server.getAddress().getPort())
122+
.scheme("https")
123+
.path("/")
124+
.build();
125+
final HttpRequest req = HttpRequest.newBuilder(reqURI).build();
126+
System.out.println("issuing request " + reqURI);
127+
final HttpResponse<String> resp = client.send(req, BodyHandlers.ofString(US_ASCII));
128+
assertEquals(200, resp.statusCode(), "unexpected response status code");
129+
assertEquals(RESP_BODY_TEXT, resp.body(), "unexpected response body");
130+
if (sniConfiguredOnClient) {
131+
assertTrue(matcher.wasInvoked(), "SNIMatcher wasn't invoked on the server");
132+
} else {
133+
assertFalse(matcher.wasInvoked(), "SNIMatcher was unexpectedly invoked" +
134+
" on the server");
135+
}
136+
}
137+
} finally {
138+
System.out.println("stopping server " + server.getAddress());
139+
server.stop();
140+
}
141+
}
142+
143+
/*
144+
* Creates and configures a HTTPS server with a SNIMatcher that
145+
* expects a specific SNI name to be sent by the connection client.
146+
* The test uses a HttpClient to issue a couple of requests with the URI having
147+
* a hostname (i.e. not a IP address literal) as the host. For one of the request,
148+
* the HttpClient is configured with specific ServerName(s) through
149+
* HttpClient.sslParameters() and for the other request, it isn't.
150+
* The test then verifies that for such requests with a hostname
151+
* (i.e. not a IP address literal) in the request URI,
152+
* the HttpClient never sends ServerName(s) that may have been configured on the
153+
* client and instead it sends the hostname (from the request URI) as the ServerName
154+
* for each of the request.
155+
*/
156+
@ParameterizedTest
157+
@ValueSource(booleans = {false, true})
158+
void testRequestResolvedHostName(final boolean sniConfiguredOnClient) throws Exception {
159+
final String resolvedHostName = InetAddress.getLoopbackAddress().getHostName();
160+
final String expectedSNI = resolvedHostName;
161+
final ServerNameMatcher matcher = new ServerNameMatcher(expectedSNI);
162+
final HttpTestServer server = createServer(matcher);
163+
try {
164+
final HttpClient.Builder builder = HttpClient.newBuilder().sslContext(sslContext);
165+
if (sniConfiguredOnClient) {
166+
final SSLParameters clientConfiguredSSLParams = new SSLParameters();
167+
clientConfiguredSSLParams.setServerNames(List.of(new SNIHostName("does-not-matter")));
168+
builder.sslParameters(clientConfiguredSSLParams);
169+
}
170+
try (final HttpClient client = builder.build()) {
171+
final URI reqURI = URIBuilder.newBuilder()
172+
.host(resolvedHostName)
173+
.port(server.getAddress().getPort())
174+
.scheme("https")
175+
.path("/")
176+
.build();
177+
final HttpRequest req = HttpRequest.newBuilder(reqURI).build();
178+
System.out.println("issuing request " + reqURI);
179+
final HttpResponse<String> resp = client.send(req, BodyHandlers.ofString(US_ASCII));
180+
assertEquals(200, resp.statusCode(), "unexpected response status code");
181+
assertEquals(RESP_BODY_TEXT, resp.body(), "unexpected response body");
182+
assertTrue(matcher.wasInvoked(), "SNIMatcher wasn't invoked on the server");
183+
}
184+
} finally {
185+
System.out.println("stopping server " + server.getAddress());
186+
server.stop();
187+
}
188+
}
189+
190+
/*
191+
* Creates a HttpsServer configured to use the given SNIMatcher
192+
*/
193+
private static HttpTestServer createServer(final SNIMatcher matcher) throws Exception {
194+
final InetSocketAddress addr = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
195+
final int backlog = 0;
196+
final HttpsServer httpsServer = HttpsServer.create(addr, backlog);
197+
final HttpsConfigurator configurator = new HttpsConfigurator(sslContext) {
198+
@Override
199+
public void configure(final HttpsParameters params) {
200+
final SSLParameters sslParameters = sslContext.getDefaultSSLParameters();
201+
// add the SNIMatcher
202+
sslParameters.setSNIMatchers(List.of(matcher));
203+
params.setSSLParameters(sslParameters);
204+
System.out.println("configured HttpsServer with SNIMatcher: " + matcher);
205+
}
206+
};
207+
httpsServer.setHttpsConfigurator(configurator);
208+
final HttpTestServer server = HttpTestServer.of(httpsServer);
209+
server.addHandler(new Handler(), "/");
210+
server.start();
211+
System.out.println("server started at " + server.getAddress());
212+
return server;
213+
}
214+
}

test/jdk/java/net/httpclient/lib/jdk/httpclient/test/lib/common/ServerNameMatcher.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ public class ServerNameMatcher extends SNIMatcher {
5858
private final Logger debug;
5959
private final boolean attemptDNSResolution;
6060
private final Set<String> recognizedSNINames;
61+
private volatile boolean invoked;
6162

6263
/**
6364
* Creates a ServerNameMatcher which recognizes the passed {@code recognizedSNIName}
@@ -97,6 +98,7 @@ public ServerNameMatcher(final boolean attemptDNSResolution,
9798
*/
9899
@Override
99100
public boolean matches(final SNIServerName clientRequestedSNI) {
101+
this.invoked = true;
100102
Objects.requireNonNull(clientRequestedSNI);
101103
if (!SNIHostName.class.isInstance(clientRequestedSNI)) {
102104
if (debug.on()) {
@@ -128,6 +130,14 @@ public boolean matches(final SNIServerName clientRequestedSNI) {
128130
return false;
129131
}
130132

133+
/**
134+
* @return true if the {@link #matches(SNIServerName)} method of this SNIMatcher instance
135+
* was invoked at least once, false otherwise.
136+
*/
137+
public boolean wasInvoked() {
138+
return this.invoked;
139+
}
140+
131141
private boolean matchesAfterDNSResolution(final String clientRequestedSNI) {
132142
final InetAddress clientRequestedAddr;
133143
try {

0 commit comments

Comments
 (0)