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@ad3e69f

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
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
+92-17Lines changed: 92 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,30 @@
2121
import java.security.cert.X509Certificate;
2222
import java.util.Collection;
2323
import java.util.List;
24+
import javax.naming.ldap.LdapName;
25+
import javax.naming.ldap.Rdn;
26+
import javax.net.ssl.ExtendedSSLSession;
27+
import javax.net.ssl.SNIHostName;
28+
import javax.net.ssl.SNIServerName;
2429
import javax.net.ssl.SSLEngine;
30+
import javax.net.ssl.SSLSession;
31+
import javax.net.ssl.SSLSocket;
2532
import javax.net.ssl.X509ExtendedTrustManager;
2633
import javax.net.ssl.X509TrustManager;
34+
import javax.security.auth.x500.X500Principal;
2735

2836
/**
2937
* Wraps an existing {@link X509ExtendedTrustManager} and enhances the {@link CertificateException} that is thrown
3038
* because of hostname validation.
3139
*/
3240
final class EnhancingX509ExtendedTrustManager extends X509ExtendedTrustManager {
41+
42+
// Constants for subject alt names of type DNS and IP. See X509Certificate#getSubjectAlternativeNames() javadocs.
43+
static final int ALTNAME_DNS = 2;
44+
static final int ALTNAME_URI = 6;
45+
static final int ALTNAME_IP = 7;
46+
private static final String SEPARATOR = ", ";
47+
3348
private final X509ExtendedTrustManager wrapped;
3449

3550
EnhancingX509ExtendedTrustManager(X509TrustManager wrapped) {
@@ -48,7 +63,8 @@ public void checkServerTrusted(X509Certificate[] chain, String authType, Socket
4863
try {
4964
wrapped.checkServerTrusted(chain, authType, socket);
5065
} catch (CertificateException e) {
51-
throwEnhancedCertificateException(chain, e);
66+
throwEnhancedCertificateException(e, chain,
67+
socket instanceof SSLSocket ? ((SSLSocket) socket).getHandshakeSession() : null);
5268
}
5369
}
5470

@@ -64,7 +80,7 @@ public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngi
6480
try {
6581
wrapped.checkServerTrusted(chain, authType, engine);
6682
} catch (CertificateException e) {
67-
throwEnhancedCertificateException(chain, e);
83+
throwEnhancedCertificateException(e, chain, engine != null ? engine.getHandshakeSession() : null);
6884
}
6985
}
7086

@@ -80,7 +96,7 @@ public void checkServerTrusted(X509Certificate[] chain, String authType)
8096
try {
8197
wrapped.checkServerTrusted(chain, authType);
8298
} catch (CertificateException e) {
83-
throwEnhancedCertificateException(chain, e);
99+
throwEnhancedCertificateException(e, chain, null);
84100
}
85101
}
86102

@@ -89,32 +105,91 @@ public X509Certificate[] getAcceptedIssuers() {
89105
return wrapped.getAcceptedIssuers();
90106
}
91107

92-
private static void throwEnhancedCertificateException(X509Certificate[] chain, CertificateException e)
93-
throws CertificateException {
108+
private static void throwEnhancedCertificateException(CertificateException e, X509Certificate[] chain,
109+
SSLSession session) throws CertificateException {
94110
// Matching the message is the best we can do sadly.
95111
String message = e.getMessage();
96-
if (message != null && e.getMessage().startsWith("No subject alternative DNS name matching")) {
97-
StringBuilder names = new StringBuilder(64);
112+
if (message != null &&
113+
(message.startsWith("No subject alternative") || message.startsWith("No name matching"))) {
114+
StringBuilder sb = new StringBuilder(128);
115+
sb.append(message);
116+
// Some exception messages from sun.security.util.HostnameChecker may end with a dot that we don't need
117+
if (message.charAt(message.length() - 1) == '.') {
118+
sb.setLength(sb.length() - 1);
119+
}
120+
if (session != null) {
121+
sb.append(" for SNIHostName=").append(getSNIHostName(session))
122+
.append(" and peerHost=").append(session.getPeerHost());
123+
}
124+
sb.append(" in the chain of ").append(chain.length).append(" certificate(s):");
98125
for (int i = 0; i < chain.length; i++) {
99126
X509Certificate cert = chain[i];
100127
Collection<List<?>> collection = cert.getSubjectAlternativeNames();
128+
sb.append(' ').append(i + 1).append(". subjectAlternativeNames=[");
101129
if (collection != null) {
130+
boolean hasNames = false;
102131
for (List<?> altNames : collection) {
103-
// 2 is dNSName. See X509Certificate javadocs.
104-
if (altNames.size() >= 2 && ((Integer) altNames.get(0)).intValue() == 2) {
105-
names.append((String) altNames.get(1)).append(",");
132+
if (altNames.size() < 2) {
133+
// We expect at least a pair of 'nameType:value' in that list.
134+
continue;
106135
}
136+
final int nameType = ((Integer) altNames.get(0)).intValue();
137+
if (nameType == ALTNAME_DNS) {
138+
sb.append("DNS");
139+
} else if (nameType == ALTNAME_IP) {
140+
sb.append("IP");
141+
} else if (nameType == ALTNAME_URI) {
142+
// URI names are common in some environments with gRPC services that use SPIFFEs.
143+
// Though the hostname matcher won't be looking at them, having them there can help
144+
// debugging cases where hostname verification was enabled when it shouldn't be.
145+
sb.append("URI");
146+
} else {
147+
continue;
148+
}
149+
sb.append(':').append((String) altNames.get(1)).append(SEPARATOR);
150+
hasNames = true;
151+
}
152+
if (hasNames) {
153+
// Strip of the last separator
154+
sb.setLength(sb.length() - SEPARATOR.length());
107155
}
108156
}
157+
sb.append("], CN=").append(getCommonName(cert)).append('.');
109158
}
110-
if (names.length() != 0) {
111-
// Strip of ,
112-
names.setLength(names.length() - 1);
113-
throw new CertificateException(message +
114-
" Subject alternative DNS names in the certificate chain of " + chain.length +
115-
" certificate(s): " + names, e);
116-
}
159+
throw new CertificateException(sb.toString(), e);
117160
}
118161
throw e;
119162
}
163+
164+
private static String getSNIHostName(SSLSession session) {
165+
if (!(session instanceof ExtendedSSLSession)) {
166+
return null;
167+
}
168+
List<SNIServerName> names = ((ExtendedSSLSession) session).getRequestedServerNames();
169+
for (SNIServerName sni : names) {
170+
if (sni instanceof SNIHostName) {
171+
SNIHostName hostName = (SNIHostName) sni;
172+
return hostName.getAsciiName();
173+
}
174+
}
175+
return null;
176+
}
177+
178+
private static String getCommonName(X509Certificate cert) {
179+
try {
180+
// 1. Get the X500Principal (better than getSubjectDN which is implementation dependent and deprecated)
181+
X500Principal principal = cert.getSubjectX500Principal();
182+
// 2. Parse the DN using LdapName
183+
LdapName ldapName = new LdapName(principal.getName());
184+
// 3. Iterate over the Relative Distinguished Names (RDNs) to find CN
185+
for (Rdn rdn : ldapName.getRdns()) {
186+
if (rdn.getType().equalsIgnoreCase("CN")) {
187+
return rdn.getValue().toString();
188+
}
189+
}
190+
} catch (Exception ignore) {
191+
// ignore
192+
}
193+
return "null";
194+
}
120195
}
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
+74-21Lines changed: 74 additions & 21 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 org.junit.jupiter.api.TestInfo;
2021
import org.junit.jupiter.api.function.Executable;
2122
import org.junit.jupiter.params.ParameterizedTest;
23+
import org.junit.jupiter.params.provider.Arguments;
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;
@@ -35,20 +35,46 @@
3535
import java.util.Date;
3636
import java.util.List;
3737
import java.util.Set;
38+
import javax.net.ssl.ExtendedSSLSession;
39+
import javax.net.ssl.SNIHostName;
40+
import javax.net.ssl.SSLEngine;
41+
import javax.net.ssl.SSLSession;
42+
import javax.net.ssl.SSLSocket;
43+
import javax.net.ssl.X509ExtendedTrustManager;
44+
import javax.security.auth.x500.X500Principal;
3845

46+
import static io.netty.handler.ssl.EnhancingX509ExtendedTrustManager.ALTNAME_DNS;
47+
import static io.netty.handler.ssl.EnhancingX509ExtendedTrustManager.ALTNAME_IP;
48+
import static io.netty.handler.ssl.EnhancingX509ExtendedTrustManager.ALTNAME_URI;
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.Named.named;
55+
import static org.junit.jupiter.params.provider.Arguments.arguments;
4456

4557
public class EnhancedX509ExtendedTrustManagerTest {
4658

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

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

5480
@Override
@@ -192,7 +218,7 @@ public void checkClientTrusted(X509Certificate[] chain, String authType, Socket
192218
@Override
193219
public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket)
194220
throws CertificateException {
195-
throw new CertificateException("No subject alternative DNS name matching netty.io.");
221+
throw newCertificateExceptionWithMatchingMessage();
196222
}
197223

198224
@Override
@@ -203,7 +229,7 @@ public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngi
203229
@Override
204230
public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
205231
throws CertificateException {
206-
throw new CertificateException("No subject alternative DNS name matching netty.io.");
232+
throw newCertificateExceptionWithMatchingMessage();
207233
}
208234

209235
@Override
@@ -214,32 +240,49 @@ public void checkClientTrusted(X509Certificate[] chain, String authType) {
214240
@Override
215241
public void checkServerTrusted(X509Certificate[] chain, String authType)
216242
throws CertificateException {
217-
throw new CertificateException("No subject alternative DNS name matching netty.io.");
243+
throw newCertificateExceptionWithMatchingMessage();
218244
}
219245

220246
@Override
221247
public X509Certificate[] getAcceptedIssuers() {
222248
return new X509Certificate[0];
223249
}
250+
251+
private CertificateException newCertificateExceptionWithMatchingMessage() {
252+
return new CertificateException("No subject alternative DNS name matching " + HOSTNAME + " found.");
253+
}
224254
});
225255

226-
static List<Executable> throwingMatchingExecutables() {
227-
return Arrays.asList(new Executable() {
256+
static List<Arguments> throwingMatchingExecutables() {
257+
return Arrays.asList(arguments(named("checkServerTrusted", new Executable() {
228258
@Override
229259
public void execute() throws Throwable {
230260
MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null);
231261
}
232-
}, new Executable() {
262+
})), arguments(named("checkServerTrusted with SSLEngine", new Executable() {
233263
@Override
234264
public void execute() throws Throwable {
235-
MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null, (SSLEngine) null);
265+
SSLSession session = mockSSLSession();
266+
SSLEngine engine = Mockito.mock(SSLEngine.class);
267+
Mockito.when(engine.getHandshakeSession()).thenReturn(session);
268+
MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null, engine);
236269
}
237-
}, new Executable() {
270+
})), arguments(named("checkServerTrusted with SSLSocket", new Executable() {
238271
@Override
239272
public void execute() throws Throwable {
240-
MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null, (SSLSocket) null);
273+
SSLSession session = mockSSLSession();
274+
SSLSocket socket = Mockito.mock(SSLSocket.class);
275+
Mockito.when(socket.getHandshakeSession()).thenReturn(session);
276+
MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null, socket);
241277
}
242-
});
278+
})));
279+
}
280+
281+
private static SSLSession mockSSLSession() {
282+
ExtendedSSLSession session = Mockito.mock(ExtendedSSLSession.class);
283+
Mockito.when(session.getRequestedServerNames()).thenReturn(Arrays.asList(new SNIHostName(HOSTNAME)));
284+
Mockito.when(session.getPeerHost()).thenReturn(HOSTNAME);
285+
return session;
243286
}
244287

245288
private static final EnhancingX509ExtendedTrustManager NON_MATCHING_MANAGER =
@@ -286,32 +329,42 @@ public X509Certificate[] getAcceptedIssuers() {
286329
}
287330
});
288331

289-
static List<Executable> throwingNonMatchingExecutables() {
290-
return Arrays.asList(new Executable() {
332+
static List<Arguments> throwingNonMatchingExecutables() {
333+
return Arrays.asList(arguments(named("checkServerTrusted", new Executable() {
291334
@Override
292335
public void execute() throws Throwable {
293336
NON_MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null);
294337
}
295-
}, new Executable() {
338+
})), arguments(named("checkServerTrusted with SSLEngine", new Executable() {
296339
@Override
297340
public void execute() throws Throwable {
298341
NON_MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null, (SSLEngine) null);
299342
}
300-
}, new Executable() {
343+
})), arguments(named("checkServerTrusted with SSLSocket", new Executable() {
301344
@Override
302345
public void execute() throws Throwable {
303346
NON_MATCHING_MANAGER.checkServerTrusted(new X509Certificate[] { TEST_CERT }, null, (SSLSocket) null);
304347
}
305-
});
348+
})));
306349
}
307350

308351
@ParameterizedTest
309352
@MethodSource("throwingMatchingExecutables")
310-
void testEnhanceException(Executable executable) {
353+
void testEnhanceException(Executable executable, TestInfo testInfo) {
311354
CertificateException exception = assertThrows(CertificateException.class, executable);
312355
// We should wrap the original cause with our own.
313356
assertInstanceOf(CertificateException.class, exception.getCause());
314-
assertThat(exception.getMessage()).contains("some.netty.io");
357+
String message = exception.getMessage();
358+
if (testInfo.getDisplayName().contains("with")) {
359+
// The following data can be extracted only when we run the test with SSLEngine or SSLSocket:
360+
assertThat(message).contains("SNIHostName=" + HOSTNAME);
361+
assertThat(message).contains("peerHost=" + HOSTNAME);
362+
}
363+
assertThat(message).contains("DNS:" + SAN_ENTRY_DNS);
364+
assertThat(message).contains("IP:" + SAN_ENTRY_IP);
365+
assertThat(message).contains("URI:" + SAN_ENTRY_URI);
366+
assertThat(message).contains("CN=" + COMMON_NAME);
367+
assertThat(message).doesNotContain(SAN_ENTRY_RFC822);
315368
}
316369

317370
@ParameterizedTest

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.