}
}
if(names.isEmpty()) {
final String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt";
throw new SSLException(msg);
}
// StringBuilder for building the error message.
final StringBuilder buf = new StringBuilder();
// We're can be case-insensitive when comparing the host we used to
// establish the socket to the hostname in the certificate.
final String hostName = normaliseIPv6Address(host.trim().toLowerCase(Locale.ENGLISH));
boolean match = false;
for(final Iterator<String> it = names.iterator(); it.hasNext();) {
// Don't trim the CN, though!
String cn = it.next();
cn = cn.toLowerCase(Locale.ENGLISH);
// Store CN in StringBuilder in case we need to report an error.
buf.append(" <");
buf.append(cn);
buf.append('>');
if(it.hasNext()) {
buf.append(" OR");
}
// The CN better have at least two dots if it wants wildcard
// action. It also can't be [*.co.uk] or [*.co.jp] or
// [*.org.uk], etc...
final String parts[] = cn.split("\\.");
final boolean doWildcard =
parts.length >= 3 && parts[0].endsWith("*") &&
validCountryWildcard(cn) && !isIPAddress(host);
if(doWildcard) {
final String firstpart = parts[0];
if (firstpart.length() > 1) { // e.g. server*
final String prefix = firstpart.substring(0, firstpart.length() - 1); // e.g. server
final String suffix = cn.substring(firstpart.length()); // skip wildcard part from cn
final String hostSuffix = hostName.substring(prefix.length()); // skip wildcard part from host
match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix);
} else {
match = hostName.endsWith(cn.substring(1));
}
if(match && strictWithSubDomains) {
// If we're in strict mode, then [*.foo.com] is not
// allowed to match [a.b.foo.com]
match = countDots(hostName) == countDots(cn);
}
} else {
match = hostName.equals(normaliseIPv6Address(cn));
}
if(match) {
break;
}
}
if(!match) {
throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf);
}
}