/
HostnameVerifierImpl.java
320 lines (277 loc) · 13 KB
/
HostnameVerifierImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package org.mariadb.jdbc.internal.protocol.tls;
import org.mariadb.jdbc.internal.logging.Logger;
import org.mariadb.jdbc.internal.logging.LoggerFactory;
import org.mariadb.jdbc.internal.util.Utils;
import javax.naming.InvalidNameException;
import javax.naming.ldap.LdapName;
import javax.naming.ldap.Rdn;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.security.auth.x500.X500Principal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.cert.Certificate;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.util.*;
public class HostnameVerifierImpl implements HostnameVerifier {
private static Logger logger = LoggerFactory.getLogger(HostnameVerifierImpl.class);
/**
* DNS verification :
* Matching is performed using the matching rules specified by
* [RFC2459]. If more than one identity of a given type is present in
* the certificate (e.g., more than one dNSName name, a match in any one
* of the set is considered acceptable.) Names may contain the wildcard
* character * which is considered to match any single domain name
* component or component fragment. E.g., *.a.com matches foo.a.com but
* not bar.foo.a.com. f*.com matches foo.com but not bar.com.
*
* @param hostname hostname
* @param tlsDnsPattern DNS pattern (may contain wildcard)
* @return true if matching
*/
private static boolean matchDns(String hostname, String tlsDnsPattern) throws SSLException {
boolean hostIsIp = Utils.isIPv4(hostname) || Utils.isIPv6(hostname);
StringTokenizer hostnameSt = new StringTokenizer(hostname.toLowerCase(), ".");
StringTokenizer templateSt = new StringTokenizer(tlsDnsPattern.toLowerCase(), ".");
if (hostnameSt.countTokens() != templateSt.countTokens()) return false;
try {
while (hostnameSt.hasMoreTokens()) {
if (!matchWildCards(hostIsIp, hostnameSt.nextToken(), templateSt.nextToken())) return false;
}
} catch (SSLException exception) {
throw new SSLException(normalizedHostMsg(hostname) + " doesn't correspond to certificate CN \"" + tlsDnsPattern
+ "\" : wildcards not possible for IPs");
}
return true;
}
private static boolean matchWildCards(boolean hostIsIp, String hostnameToken, String tlsDnsToken) throws SSLException {
int wildcardIndex = tlsDnsToken.indexOf("*");
if (wildcardIndex != -1) {
if (hostIsIp) throw new SSLException("WildCards not possible when using IP's");
boolean first = true;
String beforeWildcard;
String afterWildcard = tlsDnsToken;
while (wildcardIndex != -1) {
beforeWildcard = afterWildcard.substring(0, wildcardIndex);
afterWildcard = afterWildcard.substring(wildcardIndex + 1);
int beforeStartIdx = hostnameToken.indexOf(beforeWildcard);
if ((beforeStartIdx == -1) || (first && beforeStartIdx != 0)) return false;
first = false;
hostnameToken = hostnameToken.substring(beforeStartIdx + beforeWildcard.length());
wildcardIndex = afterWildcard.indexOf("*");
}
return hostnameToken.endsWith(afterWildcard);
}
//no wildcard -> token must be equal.
return hostnameToken.equals(tlsDnsToken);
}
static String extractCommonName(String principal) throws SSLException {
if (principal == null) return null;
try {
LdapName ldapName = new LdapName(principal);
for (Rdn rdn : ldapName.getRdns()) {
if (rdn.getType().equalsIgnoreCase("CN")) {
Object obj = rdn.getValue();
if (obj != null) return obj.toString();
}
}
return null;
} catch (InvalidNameException e) {
throw new SSLException("DN value \"" + principal + "\" is invalid");
}
}
private static String normaliseAddress(String hostname) {
try {
if (hostname == null) return hostname;
InetAddress inetAddress = InetAddress.getByName(hostname);
return inetAddress.getHostAddress();
} catch (UnknownHostException unexpected) {
return hostname;
}
}
private SubjectAltNames getSubjectAltNames(X509Certificate cert) throws CertificateParsingException {
Collection<List<?>> entries = cert.getSubjectAlternativeNames();
SubjectAltNames subjectAltNames = new SubjectAltNames();
if (entries != null) {
for (List<?> entry : entries) {
if (entry.size() >= 2) {
int type = (Integer) entry.get(0);
if (type == 2) { //DNS
String altNameDns = (String) entry.get(1);
if (altNameDns != null) {
String normalizedSubjectAlt = altNameDns.toLowerCase(Locale.ROOT);
subjectAltNames.add(new GeneralName(normalizedSubjectAlt, Extension.DNS));
}
}
if (type == 7) { //IP
String altNameIp = (String) entry.get(1);
if (altNameIp != null) {
subjectAltNames.add(new GeneralName(altNameIp, Extension.IP));
}
}
}
}
}
return subjectAltNames;
}
@Override
public boolean verify(String host, SSLSession session) {
try {
Certificate[] certs = session.getPeerCertificates();
X509Certificate cert = (X509Certificate) certs[0];
verify(host, cert);
return true;
} catch (SSLException ex) {
if (logger.isDebugEnabled()) logger.debug(ex.getMessage(), ex);
return false;
}
}
/**
* Verification that throw an exception with a detailed error message in case of error.
*
* @param host hostname
* @param cert certificate
* @throws SSLException exception
*/
public void verify(String host, X509Certificate cert) throws SSLException {
String normalizedHost = host.toLowerCase(Locale.ROOT);
try {
//***********************************************************
// RFC 6125 : check Subject Alternative Name (SAN)
//***********************************************************
String altNameError = "";
SubjectAltNames subjectAltNames = getSubjectAltNames(cert);
if (!subjectAltNames.isEmpty()) {
//***********************************************************
// Host is IPv4 : Check corresponding entries in subject alternative names
//***********************************************************
if (Utils.isIPv4(host)) {
for (GeneralName entry : subjectAltNames.getGeneralNames()) {
if (logger.isTraceEnabled()) {
logger.trace("IPv4 verification of hostname : type=" + entry.extension
+ " value=" + entry.value
+ " to " + host);
}
if (entry.extension == Extension.IP) { //IP
if (host.equals(entry.value)) return;
}
}
} else if (Utils.isIPv6(host)) {
//***********************************************************
// Host is IPv6 : Check corresponding entries in subject alternative names
//***********************************************************
String normalisedHost = normaliseAddress(host);
for (GeneralName entry : subjectAltNames.getGeneralNames()) {
if (logger.isTraceEnabled()) {
logger.trace("IPv6 verification of hostname : type=" + entry.extension
+ " value=" + entry.value
+ " to " + host);
}
if (entry.extension == Extension.IP) { //IP
if (!Utils.isIPv4(entry.value)) {
String normalizedSubjectAlt = normaliseAddress(entry.value);
if (normalisedHost.equals(normalizedSubjectAlt)) {
return;
}
}
}
}
} else {
//***********************************************************
// Host is not IP = DNS : Check corresponding entries in alternative subject names
//***********************************************************
for (GeneralName entry : subjectAltNames.getGeneralNames()) {
if (logger.isTraceEnabled()) {
logger.trace("DNS verification of hostname : type=" + entry.extension
+ " value=" + entry.value
+ " to " + host);
}
if (entry.extension == Extension.DNS) { //IP
String normalizedSubjectAlt = entry.value.toLowerCase(Locale.ROOT);
if (matchDns(normalizedHost, normalizedSubjectAlt)) {
return;
}
}
}
}
}
//***********************************************************
// RFC 2818 : legacy fallback using CN (recommendation is using alt-names)
//***********************************************************
X500Principal subjectPrincipal = cert.getSubjectX500Principal();
String cn = extractCommonName(subjectPrincipal.getName(X500Principal.RFC2253));
if (cn == null) {
if (subjectAltNames.isEmpty()) {
throw new SSLException("CN not found in certificate principal \"" + subjectPrincipal
+ "\" and certificate doesn't contain SAN");
} else {
throw new SSLException("CN not found in certificate principal \"" + subjectPrincipal
+ "\" and " + normalizedHostMsg(normalizedHost) + " doesn't correspond to " + subjectAltNames.toString());
}
}
String normalizedCn = cn.toLowerCase(Locale.ROOT);
if (!matchDns(normalizedHost, normalizedCn)) {
String errorMsg = normalizedHostMsg(normalizedHost) + " doesn't correspond to certificate CN \"" + normalizedCn + "\"";
if (!subjectAltNames.isEmpty()) errorMsg += " and " + subjectAltNames.toString();
throw new SSLException(errorMsg);
}
return;
} catch (CertificateParsingException cpe) {
throw new SSLException("certificate parsing error : " + cpe.getMessage());
}
}
private static String normalizedHostMsg(String normalizedHost) {
StringBuilder msg = new StringBuilder();
if (Utils.isIPv4(normalizedHost)) {
msg.append("IPv4 host \"");
} else if (Utils.isIPv6(normalizedHost)) {
msg.append("IPv6 host \"");
} else {
msg.append("DNS host \"");
}
msg.append(normalizedHost).append("\"");
return msg.toString();
}
private enum Extension {
DNS, IP
}
private class GeneralName {
String value;
Extension extension;
public GeneralName(String value, Extension extension) {
this.value = value;
this.extension = extension;
}
@Override
public String toString() {
return "{" + extension + ":\"" + value + "\"}";
}
}
private class SubjectAltNames {
List<GeneralName> generalNames = new ArrayList<>();
@Override
public String toString() {
if (isEmpty()) return "SAN[-empty-]";
StringBuilder sb = new StringBuilder("SAN[");
boolean first = true;
for (GeneralName generalName : generalNames) {
if (!first) sb.append(",");
first = false;
sb.append(generalName.toString());
}
sb.append("]");
return sb.toString();
}
public List<GeneralName> getGeneralNames() {
return generalNames;
}
public void add(GeneralName generalName) {
generalNames.add(generalName);
}
public boolean isEmpty() {
return generalNames.isEmpty();
}
}
}