GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Improve exception message generated by `EnhancingX509ExtendedTrustMan… · netty/netty@0bb5674

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • handler/src
    • main/java/io/netty/handler/ssl
      • EnhancingX509ExtendedTrustManager.java
    • test/java/io/netty/handler/ssl
      • EnhancedX509ExtendedTrustManagerTest.java
      • SniClientJava8TestUtil.java
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎handler/src/main/java/io/netty/handler/ssl/EnhancingX509ExtendedTrustManager.java‎

Copy file name to clipboardExpand all lines: handler/src/main/java/io/netty/handler/ssl/EnhancingX509ExtendedTrustManager.java
+95-21Lines changed: 95 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -18,22 +18,36 @@
1818

1919
import io.netty.util.internal.SuppressJava6Requirement;
2020

21-
import javax.net.ssl.SSLEngine;
22-
import javax.net.ssl.X509ExtendedTrustManager;
23-
import javax.net.ssl.X509TrustManager;
2421
import java.net.Socket;
2522
import java.security.cert.CertificateException;
2623
import java.security.cert.X509Certificate;
2724
import java.util.Collection;
2825
import java.util.List;
29-
26+
import javax.naming.ldap.LdapName;
27+
import javax.naming.ldap.Rdn;
28+
import javax.net.ssl.ExtendedSSLSession;
29+
import javax.net.ssl.SNIHostName;
30+
import javax.net.ssl.SNIServerName;
31+
import javax.net.ssl.SSLEngine;
32+
import javax.net.ssl.SSLSession;
33+
import javax.net.ssl.SSLSocket;
34+
import javax.net.ssl.X509ExtendedTrustManager;
35+
import javax.net.ssl.X509TrustManager;
36+
import javax.security.auth.x500.X500Principal;
3037

3138
/**
3239
* Wraps an existing {@link X509ExtendedTrustManager} and enhances the {@link CertificateException} that is thrown
3340
* because of hostname validation.
3441
*/
3542
@SuppressJava6Requirement(reason = "Usage guarded by java version check")
3643
final class EnhancingX509ExtendedTrustManager extends X509ExtendedTrustManager {
44+
45+
// Constants for subject alt names of type DNS and IP. See X509Certificate#getSubjectAlternativeNames() javadocs.
46+
static final int ALTNAME_DNS = 2;
47+
static final int ALTNAME_URI = 6;
48+
static final int ALTNAME_IP = 7;
49+
private static final String SEPARATOR = ", ";
50+
3751
private final X509ExtendedTrustManager wrapped;
3852

3953
EnhancingX509ExtendedTrustManager(X509TrustManager wrapped) {
@@ -52,7 +66,8 @@ public void checkServerTrusted(X509Certificate[] chain, String authType, Socket
5266
try {
5367
wrapped.checkServerTrusted(chain, authType, socket);
5468
} catch (CertificateException e) {
55-
throwEnhancedCertificateException(chain, e);
69+
throwEnhancedCertificateException(e, chain,
70+
socket instanceof SSLSocket ? ((SSLSocket) socket).getHandshakeSession() : null);
5671
}
5772
}
5873

@@ -68,7 +83,7 @@ public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngi
6883
try {
6984
wrapped.checkServerTrusted(chain, authType, engine);
7085
} catch (CertificateException e) {
71-
throwEnhancedCertificateException(chain, e);
86+
throwEnhancedCertificateException(e, chain, engine != null ? engine.getHandshakeSession() : null);
7287
}
7388
}
7489

@@ -84,7 +99,7 @@ public void checkServerTrusted(X509Certificate[] chain, String authType)
8499
try {
85100
wrapped.checkServerTrusted(chain, authType);
86101
} catch (CertificateException e) {
87-
throwEnhancedCertificateException(chain, e);
102+
throwEnhancedCertificateException(e, chain, null);
88103
}
89104
}
90105

@@ -93,32 +108,91 @@ public X509Certificate[] getAcceptedIssuers() {
93108
return wrapped.getAcceptedIssuers();
94109
}
95110

96-
private static void throwEnhancedCertificateException(X509Certificate[] chain, CertificateException e)
97-
throws CertificateException {
111+
private static void throwEnhancedCertificateException(CertificateException e, X509Certificate[] chain,
112+
SSLSession session) throws CertificateException {
98113
// Matching the message is the best we can do sadly.
99114
String message = e.getMessage();
100-
if (message != null && e.getMessage().startsWith("No subject alternative DNS name matching")) {
101-
StringBuilder names = new StringBuilder(64);
115+
if (message != null &&
116+
(message.startsWith("No subject alternative") || message.startsWith("No name matching"))) {
117+
StringBuilder sb = new StringBuilder(128);
118+
sb.append(message);
119+
// Some exception messages from sun.security.util.HostnameChecker may end with a dot that we don't need
120+
if (message.charAt(message.length() - 1) == '.') {
121+
sb.setLength(sb.length() - 1);
122+
}
123+
if (session != null) {
124+
sb.append(" for SNIHostName=").append(getSNIHostName(session))
125+
.append(" and peerHost=").append(session.getPeerHost());
126+
}
127+
sb.append(" in the chain of ").append(chain.length).append(" certificate(s):");
102128
for (int i = 0; i < chain.length; i++) {
103129
X509Certificate cert = chain[i];
104130
Collection<List<?>> collection = cert.getSubjectAlternativeNames();
131+
sb.append(' ').append(i + 1).append(". subjectAlternativeNames=[");
105132
if (collection != null) {
133+
boolean hasNames = false;
106134
for (List<?> altNames : collection) {
107-
// 2 is dNSName. See X509Certificate javadocs.
108-
if (altNames.size() >= 2 && ((Integer) altNames.get(0)).intValue() == 2) {
109-
names.append((String) altNames.get(1)).append(",");
135+
if (altNames.size() < 2) {
136+
// We expect at least a pair of 'nameType:value' in that list.
137+
continue;
138+
}
139+
final int nameType = ((Integer) altNames.get(0)).intValue();
140+
if (nameType == ALTNAME_DNS) {
141+
sb.append("DNS");
142+
} else if (nameType == ALTNAME_IP) {
143+
sb.append("IP");
144+
} else if (nameType == ALTNAME_URI) {
145+
// URI names are common in some environments with gRPC services that use SPIFFEs.
146+
// Though the hostname matcher won't be looking at them, having them there can help
147+
// debugging cases where hostname verification was enabled when it shouldn't be.
148+
sb.append("URI");
149+
} else {
150+
continue;
110151
}
152+
sb.append(':').append((String) altNames.get(1)).append(SEPARATOR);
153+
hasNames = true;
154+
}
155+
if (hasNames) {
156+
// Strip of the last separator
157+
sb.setLength(sb.length() - SEPARATOR.length());
111158
}
112159
}
160+
sb.append("], CN=").append(getCommonName(cert)).append('.');
113161
}
114-
if (names.length() != 0) {
115-
// Strip of ,
116-
names.setLength(names.length() - 1);
117-
throw new CertificateException(message +
118-
" Subject alternative DNS names in the certificate chain of " + chain.length +
119-
" certificate(s): " + names, e);
120-
}
162+
throw new CertificateException(sb.toString(), e);
121163
}
122164
throw e;
123165
}
166+
167+
private static String getSNIHostName(SSLSession session) {
168+
if (!(session instanceof ExtendedSSLSession)) {
169+
return null;
170+
}
171+
List<SNIServerName> names = ((ExtendedSSLSession) session).getRequestedServerNames();
172+
for (SNIServerName sni : names) {
173+
if (sni instanceof SNIHostName) {
174+
SNIHostName hostName = (SNIHostName) sni;
175+
return hostName.getAsciiName();
176+
}
177+
}
178+
return null;
179+
}
180+
181+
private static String getCommonName(X509Certificate cert) {
182+
try {
183+
// 1. Get the X500Principal (better than getSubjectDN which is implementation dependent and deprecated)
184+
X500Principal principal = cert.getSubjectX500Principal();
185+
// 2. Parse the DN using LdapName
186+
LdapName ldapName = new LdapName(principal.getName());
187+
// 3. Iterate over the Relative Distinguished Names (RDNs) to find CN
188+
for (Rdn rdn : ldapName.getRdns()) {
189+
if (rdn.getType().equalsIgnoreCase("CN")) {
190+
return rdn.getValue().toString();
191+
}
192+
}
193+
} catch (Exception ignore) {
194+
// ignore
195+
}
196+
return "null";
197+
}
124198
}
Collapse file

‎handler/src/test/java/io/netty/handler/ssl/EnhancedX509ExtendedTrustManagerTest.java‎

Copy file name to clipboardExpand all lines: handler/src/test/java/io/netty/handler/ssl/EnhancedX509ExtendedTrustManagerTest.java
+61-11Lines changed: 61 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,13 @@
1717
package io.netty.handler.ssl;
1818

1919
import io.netty.util.internal.EmptyArrays;
20+
import io.netty.util.internal.PlatformDependent;
21+
import org.junit.jupiter.api.TestInfo;
2022
import org.junit.jupiter.api.function.Executable;
2123
import org.junit.jupiter.params.ParameterizedTest;
2224
import org.junit.jupiter.params.provider.MethodSource;
25+
import org.mockito.Mockito;
2326

24-
import javax.net.ssl.SSLEngine;
25-
import javax.net.ssl.SSLSocket;
26-
import javax.net.ssl.X509ExtendedTrustManager;
2727
import java.math.BigInteger;
2828
import java.net.Socket;
2929
import java.security.Principal;
@@ -32,23 +32,48 @@
3232
import java.security.cert.X509Certificate;
3333
import java.util.Arrays;
3434
import java.util.Collection;
35+
import java.util.Collections;
3536
import java.util.Date;
3637
import java.util.List;
3738
import java.util.Set;
39+
import javax.net.ssl.SSLEngine;
40+
import javax.net.ssl.SSLSession;
41+
import javax.net.ssl.SSLSocket;
42+
import javax.net.ssl.X509ExtendedTrustManager;
43+
import javax.security.auth.x500.X500Principal;
3844

45+
import static io.netty.handler.ssl.EnhancingX509ExtendedTrustManager.ALTNAME_DNS;
46+
import static io.netty.handler.ssl.EnhancingX509ExtendedTrustManager.ALTNAME_IP;
47+
import static io.netty.handler.ssl.EnhancingX509ExtendedTrustManager.ALTNAME_URI;
48+
import static io.netty.handler.ssl.SniClientJava8TestUtil.mockSSLSessionWithSNIHostNameAndPeerHost;
3949
import static org.assertj.core.api.Assertions.assertThat;
4050
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
4151
import static org.junit.jupiter.api.Assertions.assertNull;
4252
import static org.junit.jupiter.api.Assertions.assertThrows;
4353
import static org.junit.jupiter.api.Assertions.fail;
54+
import static org.junit.jupiter.api.Assumptions.assumeTrue;
4455

4556
public class EnhancedX509ExtendedTrustManagerTest {
4657

58+
private static final String HOSTNAME = "netty.io";
59+
private static final String SAN_ENTRY_DNS = "some.netty.io";
60+
private static final String SAN_ENTRY_IP = "127.0.0.1";
61+
private static final String SAN_ENTRY_URI = "URI:https://uri.netty.io/profile";
62+
private static final String SAN_ENTRY_RFC822 = "[email protected]";
63+
private static final String COMMON_NAME = "leaf.netty.io";
64+
4765
private static final X509Certificate TEST_CERT = new X509Certificate() {
4866

4967
@Override
5068
public Collection<List<?>> getSubjectAlternativeNames() {
51-
return Arrays.asList(Arrays.asList(1, new Object()), Arrays.asList(2, "some.netty.io"));
69+
return Arrays.asList(Arrays.asList(1, new Object()),
70+
Arrays.asList(ALTNAME_DNS, SAN_ENTRY_DNS), Arrays.asList(ALTNAME_IP, SAN_ENTRY_IP),
71+
Arrays.asList(ALTNAME_URI, SAN_ENTRY_URI), Arrays.asList(1 /* rfc822Name */, SAN_ENTRY_RFC822));
72+
}
73+
74+
@Override
75+
public X500Principal getSubjectX500Principal() {
76+
return new X500Principal("CN=" + COMMON_NAME + ", O=Netty");
5277
}
5378

5479
@Override
@@ -192,7 +217,7 @@ public void checkClientTrusted(X509Certificate[] chain, String authType, Socket
192217
@Override
193218
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket)
194219
throws CertificateException {
195-
throw new CertificateException("No subject alternative DNS name matching netty.io.");
220+
throw newCertificateExceptionWithMatchingMessage();
196221
}
197222

198223
@Override
@@ -203,7 +228,7 @@ public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngi
203228
@Override
204229
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
205230
throws CertificateException {
206-
throw new CertificateException("No subject alternative DNS name matching netty.io.");
231+
throw newCertificateExceptionWithMatchingMessage();
207232
}
208233

209234
@Override
@@ -214,16 +239,23 @@ public void checkClientTrusted(X509Certificate[] chain, String authType) {
214239
@Override
215240
public void checkServerTrusted(X509Certificate[] chain, String authType)
216241
throws CertificateException {
217-
throw new CertificateException("No subject alternative DNS name matching netty.io.");
242+
throw newCertificateExceptionWithMatchingMessage();
218243
}
219244

220245
@Override
221246
public X509Certificate[] getAcceptedIssuers() {
222247
return new X509Certificate[0];
223248
}
249+
250+
private CertificateException newCertificateExceptionWithMatchingMessage() {
251+
return new CertificateException("No subject alternative DNS name matching " + HOSTNAME + " found.");
252+
}
224253
});
225254

226255
static List<Executable> throwingMatchingExecutables() {
256+
if (PlatformDependent.javaVersion() < 8) {
257+
return Collections.emptyList();
258+
}
227259
return Arrays.asList(new Executable() {
228260
@Override
229261
public void execute() throws Throwable {
@@ -232,12 +264,18 @@ public void execute() throws Throwable {
232264
}, new Executable() {
233265
@Override
234266
public void execute() throws Throwable {
235-
MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null, (SSLEngine) null);
267+
SSLSession session = mockSSLSessionWithSNIHostNameAndPeerHost(HOSTNAME);
268+
SSLEngine engine = Mockito.mock(SSLEngine.class);
269+
Mockito.when(engine.getHandshakeSession()).thenReturn(session);
270+
MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null, engine);
236271
}
237272
}, new Executable() {
238273
@Override
239274
public void execute() throws Throwable {
240-
MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null, (SSLSocket) null);
275+
SSLSession session = mockSSLSessionWithSNIHostNameAndPeerHost(HOSTNAME);
276+
SSLSocket socket = Mockito.mock(SSLSocket.class);
277+
Mockito.when(socket.getHandshakeSession()).thenReturn(session);
278+
MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null, socket);
241279
}
242280
});
243281
}
@@ -307,16 +345,28 @@ public void execute() throws Throwable {
307345

308346
@ParameterizedTest
309347
@MethodSource("throwingMatchingExecutables")
310-
void testEnhanceException(Executable executable) {
348+
void testEnhanceException(Executable executable, TestInfo testInfo) {
349+
assumeTrue(PlatformDependent.javaVersion() >= 8);
311350
CertificateException exception = assertThrows(CertificateException.class, executable);
312351
// We should wrap the original cause with our own.
313352
assertInstanceOf(CertificateException.class, exception.getCause());
314-
assertThat(exception.getMessage()).contains("some.netty.io");
353+
String message = exception.getMessage();
354+
if (testInfo.getDisplayName().contains("with")) {
355+
// The following data can be extracted only when we run the test with SSLEngine or SSLSocket:
356+
assertThat(message).contains("SNIHostName=" + HOSTNAME);
357+
assertThat(message).contains("peerHost=" + HOSTNAME);
358+
}
359+
assertThat(message).contains("DNS:" + SAN_ENTRY_DNS);
360+
assertThat(message).contains("IP:" + SAN_ENTRY_IP);
361+
assertThat(message).contains("URI:" + SAN_ENTRY_URI);
362+
assertThat(message).contains("CN=" + COMMON_NAME);
363+
assertThat(message).doesNotContain(SAN_ENTRY_RFC822);
315364
}
316365

317366
@ParameterizedTest
318367
@MethodSource("throwingNonMatchingExecutables")
319368
void testNotEnhanceException(Executable executable) {
369+
assumeTrue(PlatformDependent.javaVersion() >= 8);
320370
CertificateException exception = assertThrows(CertificateException.class, executable);
321371
// We should not wrap the original cause with our own.
322372
assertNull(exception.getCause());
Collapse file

‎handler/src/test/java/io/netty/handler/ssl/SniClientJava8TestUtil.java‎

Copy file name to clipboardExpand all lines: handler/src/test/java/io/netty/handler/ssl/SniClientJava8TestUtil.java
+10Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
import io.netty.util.concurrent.Promise;
3636
import io.netty.util.internal.EmptyArrays;
3737
import io.netty.util.internal.ThrowableUtil;
38+
import org.mockito.Mockito;
3839

3940
import javax.net.ssl.ExtendedSSLSession;
4041
import javax.net.ssl.KeyManager;
@@ -64,6 +65,7 @@
6465
import java.security.cert.CertificateException;
6566
import java.security.cert.X509Certificate;
6667
import java.util.ArrayList;
68+
import java.util.Arrays;
6769
import java.util.Collections;
6870
import java.util.List;
6971

@@ -345,4 +347,12 @@ public String chooseEngineServerAlias(String s, Principal[] principals,
345347
}, factory.getProvider(), factory.getAlgorithm());
346348
}
347349
}
350+
351+
static SSLSession mockSSLSessionWithSNIHostNameAndPeerHost(String hostname) {
352+
ExtendedSSLSession session = Mockito.mock(ExtendedSSLSession.class);
353+
SNIServerName sniName = new SNIHostName(hostname);
354+
Mockito.when(session.getRequestedServerNames()).thenReturn(Arrays.asList(sniName));
355+
Mockito.when(session.getPeerHost()).thenReturn(hostname);
356+
return session;
357+
}
348358
}

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.