Path: blob/master/src/java.base/share/classes/sun/security/util/HostnameChecker.java
41159 views
/*1* Copyright (c) 2002, 2020, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package sun.security.util;2627import java.io.IOException;28import java.net.IDN;29import java.net.InetAddress;30import java.net.UnknownHostException;31import java.security.Principal;32import java.security.cert.*;33import java.text.Normalizer;34import java.util.*;35import javax.security.auth.x500.X500Principal;36import javax.net.ssl.SNIHostName;3738import sun.net.util.IPAddressUtil;39import sun.security.x509.X500Name;40import sun.security.ssl.SSLLogger;4142/**43* Class to check hostnames against the names specified in a certificate as44* required for TLS and LDAP.45*46*/47public class HostnameChecker {4849// Constant for a HostnameChecker for TLS50public static final byte TYPE_TLS = 1;51private static final HostnameChecker INSTANCE_TLS =52new HostnameChecker(TYPE_TLS);5354// Constant for a HostnameChecker for LDAP55public static final byte TYPE_LDAP = 2;56private static final HostnameChecker INSTANCE_LDAP =57new HostnameChecker(TYPE_LDAP);5859// constants for subject alt names of type DNS and IP60private static final int ALTNAME_DNS = 2;61private static final int ALTNAME_IP = 7;6263// the algorithm to follow to perform the check. Currently unused.64private final byte checkType;6566private HostnameChecker(byte checkType) {67this.checkType = checkType;68}6970/**71* Get a HostnameChecker instance. checkType should be one of the72* TYPE_* constants defined in this class.73*/74public static HostnameChecker getInstance(byte checkType) {75if (checkType == TYPE_TLS) {76return INSTANCE_TLS;77} else if (checkType == TYPE_LDAP) {78return INSTANCE_LDAP;79}80throw new IllegalArgumentException("Unknown check type: " + checkType);81}8283/**84* Perform the check.85*86* @param expectedName the expected host name or ip address87* @param cert the certificate to check against88* @param chainsToPublicCA true if the certificate chains to a public89* root CA (as pre-installed in the cacerts file)90* @throws CertificateException if the name does not match any of91* the names specified in the certificate92*/93public void match(String expectedName, X509Certificate cert,94boolean chainsToPublicCA) throws CertificateException {95if (expectedName == null) {96throw new CertificateException("Hostname or IP address is " +97"undefined.");98}99if (isIpAddress(expectedName)) {100matchIP(expectedName, cert);101} else {102matchDNS(expectedName, cert, chainsToPublicCA);103}104}105106public void match(String expectedName, X509Certificate cert)107throws CertificateException {108match(expectedName, cert, false);109}110111/**112* Test whether the given hostname looks like a literal IPv4 or IPv6113* address. The hostname does not need to be a fully qualified name.114*115* This is not a strict check that performs full input validation.116* That means if the method returns true, name need not be a correct117* IP address, rather that it does not represent a valid DNS hostname.118* Likewise for IP addresses when it returns false.119*/120private static boolean isIpAddress(String name) {121if (IPAddressUtil.isIPv4LiteralAddress(name) ||122IPAddressUtil.isIPv6LiteralAddress(name)) {123return true;124} else {125return false;126}127}128129/**130* Check if the certificate allows use of the given IP address.131*132* From RFC2818:133* In some cases, the URI is specified as an IP address rather than a134* hostname. In this case, the iPAddress subjectAltName must be present135* in the certificate and must exactly match the IP in the URI.136*/137private static void matchIP(String expectedIP, X509Certificate cert)138throws CertificateException {139Collection<List<?>> subjAltNames = cert.getSubjectAlternativeNames();140if (subjAltNames == null) {141throw new CertificateException142("No subject alternative names present");143}144for (List<?> next : subjAltNames) {145// For IP address, it needs to be exact match146if (((Integer)next.get(0)).intValue() == ALTNAME_IP) {147String ipAddress = (String)next.get(1);148if (expectedIP.equalsIgnoreCase(ipAddress)) {149return;150} else {151// compare InetAddress objects in order to ensure152// equality between a long IPv6 address and its153// abbreviated form.154try {155if (InetAddress.getByName(expectedIP).equals(156InetAddress.getByName(ipAddress))) {157return;158}159} catch (UnknownHostException e) {160} catch (SecurityException e) {}161}162}163}164throw new CertificateException("No subject alternative " +165"names matching " + "IP address " +166expectedIP + " found");167}168169/**170* Check if the certificate allows use of the given DNS name.171*172* From RFC2818:173* If a subjectAltName extension of type dNSName is present, that MUST174* be used as the identity. Otherwise, the (most specific) Common Name175* field in the Subject field of the certificate MUST be used. Although176* the use of the Common Name is existing practice, it is deprecated and177* Certification Authorities are encouraged to use the dNSName instead.178*179* Matching is performed using the matching rules specified by180* [RFC5280]. If more than one identity of a given type is present in181* the certificate (e.g., more than one dNSName name, a match in any one182* of the set is considered acceptable.)183*/184private void matchDNS(String expectedName, X509Certificate cert,185boolean chainsToPublicCA)186throws CertificateException {187// Check that the expected name is a valid domain name.188try {189// Using the checking implemented in SNIHostName190SNIHostName sni = new SNIHostName(expectedName);191} catch (IllegalArgumentException iae) {192throw new CertificateException(193"Illegal given domain name: " + expectedName, iae);194}195196Collection<List<?>> subjAltNames = cert.getSubjectAlternativeNames();197if (subjAltNames != null) {198boolean foundDNS = false;199for (List<?> next : subjAltNames) {200if (((Integer)next.get(0)).intValue() == ALTNAME_DNS) {201foundDNS = true;202String dnsName = (String)next.get(1);203if (isMatched(expectedName, dnsName, chainsToPublicCA)) {204return;205}206}207}208if (foundDNS) {209// if certificate contains any subject alt names of type DNS210// but none match, reject211throw new CertificateException("No subject alternative DNS "212+ "name matching " + expectedName + " found.");213}214}215X500Name subjectName = getSubjectX500Name(cert);216DerValue derValue = subjectName.findMostSpecificAttribute217(X500Name.commonName_oid);218if (derValue != null) {219try {220String cname = derValue.getAsString();221if (!Normalizer.isNormalized(cname, Normalizer.Form.NFKC)) {222throw new CertificateException("Not a formal name "223+ cname);224}225if (isMatched(expectedName, cname, chainsToPublicCA)) {226return;227}228} catch (IOException e) {229// ignore230}231}232String msg = "No name matching " + expectedName + " found";233throw new CertificateException(msg);234}235236237/**238* Return the subject of a certificate as X500Name, by reparsing if239* necessary. X500Name should only be used if access to name components240* is required, in other cases X500Principal is to be preferred.241*242* This method is currently used from within JSSE, do not remove.243*/244@SuppressWarnings("deprecation")245public static X500Name getSubjectX500Name(X509Certificate cert)246throws CertificateParsingException {247try {248Principal subjectDN = cert.getSubjectDN();249if (subjectDN instanceof X500Name) {250return (X500Name)subjectDN;251} else {252X500Principal subjectX500 = cert.getSubjectX500Principal();253return new X500Name(subjectX500.getEncoded());254}255} catch (IOException e) {256throw(CertificateParsingException)257new CertificateParsingException().initCause(e);258}259}260261262/**263* Returns true if name matches against template.<p>264*265* The matching is performed as per RFC 2818 rules for TLS and266* RFC 2830 rules for LDAP.<p>267*268* The <code>name</code> parameter should represent a DNS name. The269* <code>template</code> parameter may contain the wildcard character '*'.270*/271private boolean isMatched(String name, String template,272boolean chainsToPublicCA) {273274// Normalize to Unicode, because PSL is in Unicode.275try {276name = IDN.toUnicode(IDN.toASCII(name));277template = IDN.toUnicode(IDN.toASCII(template));278} catch (RuntimeException re) {279if (SSLLogger.isOn) {280SSLLogger.fine("Failed to normalize to Unicode: " + re);281}282283return false;284}285286if (hasIllegalWildcard(template, chainsToPublicCA)) {287return false;288}289290// check the validity of the domain name template.291try {292// Replacing wildcard character '*' with 'z' so as to check293// the domain name template validity.294//295// Using the checking implemented in SNIHostName296new SNIHostName(template.replace('*', 'z'));297} catch (IllegalArgumentException iae) {298// It would be nice to add debug log if not matching.299return false;300}301302if (checkType == TYPE_TLS) {303return matchAllWildcards(name, template);304} else if (checkType == TYPE_LDAP) {305return matchLeftmostWildcard(name, template);306} else {307return false;308}309}310311/**312* Returns true if the template contains an illegal wildcard character.313*/314private static boolean hasIllegalWildcard(315String template, boolean chainsToPublicCA) {316// not ok if it is a single wildcard character or "*."317if (template.equals("*") || template.equals("*.")) {318if (SSLLogger.isOn) {319SSLLogger.fine(320"Certificate domain name has illegal single " +321"wildcard character: " + template);322}323return true;324}325326int lastWildcardIndex = template.lastIndexOf("*");327328// ok if it has no wildcard character329if (lastWildcardIndex == -1) {330return false;331}332333String afterWildcard = template.substring(lastWildcardIndex);334int firstDotIndex = afterWildcard.indexOf(".");335336// not ok if there is no dot after wildcard (ex: "*com")337if (firstDotIndex == -1) {338if (SSLLogger.isOn) {339SSLLogger.fine(340"Certificate domain name has illegal wildcard, " +341"no dot after wildcard character: " + template);342}343return true;344}345346if (!chainsToPublicCA) {347return false; // skip check for non-public certificates348}349350// If the wildcarded domain is a top-level domain under which names351// can be registered, then a wildcard is not allowed.352String wildcardedDomain = afterWildcard.substring(firstDotIndex + 1);353String templateDomainSuffix =354RegisteredDomain.from("z." + wildcardedDomain)355.filter(d -> d.type() == RegisteredDomain.Type.ICANN)356.map(RegisteredDomain::publicSuffix).orElse(null);357if (templateDomainSuffix == null) {358return false; // skip check if not known public suffix359}360361// Is it a top-level domain?362if (wildcardedDomain.equalsIgnoreCase(templateDomainSuffix)) {363if (SSLLogger.isOn) {364SSLLogger.fine(365"Certificate domain name has illegal " +366"wildcard for top-level public suffix: " + template);367}368return true;369}370371return false;372}373374/**375* Returns true if name matches against template.<p>376*377* According to RFC 2818, section 3.1 -378* Names may contain the wildcard character * which is379* considered to match any single domain name component380* or component fragment.381* E.g., *.a.com matches foo.a.com but not382* bar.foo.a.com. f*.com matches foo.com but not bar.com.383*/384private static boolean matchAllWildcards(String name,385String template) {386name = name.toLowerCase(Locale.ENGLISH);387template = template.toLowerCase(Locale.ENGLISH);388StringTokenizer nameSt = new StringTokenizer(name, ".");389StringTokenizer templateSt = new StringTokenizer(template, ".");390391if (nameSt.countTokens() != templateSt.countTokens()) {392return false;393}394395while (nameSt.hasMoreTokens()) {396if (!matchWildCards(nameSt.nextToken(),397templateSt.nextToken())) {398return false;399}400}401return true;402}403404405/**406* Returns true if name matches against template.<p>407*408* As per RFC 2830, section 3.6 -409* The "*" wildcard character is allowed. If present, it applies only410* to the left-most name component.411* E.g. *.bar.com would match a.bar.com, b.bar.com, etc. but not412* bar.com.413*/414private static boolean matchLeftmostWildcard(String name,415String template) {416name = name.toLowerCase(Locale.ENGLISH);417template = template.toLowerCase(Locale.ENGLISH);418419// Retrieve leftmost component420int templateIdx = template.indexOf(".");421int nameIdx = name.indexOf(".");422423if (templateIdx == -1)424templateIdx = template.length();425if (nameIdx == -1)426nameIdx = name.length();427428if (matchWildCards(name.substring(0, nameIdx),429template.substring(0, templateIdx))) {430431// match rest of the name432return template.substring(templateIdx).equals(433name.substring(nameIdx));434} else {435return false;436}437}438439440/**441* Returns true if the name matches against the template that may442* contain wildcard char * <p>443*/444private static boolean matchWildCards(String name, String template) {445446int wildcardIdx = template.indexOf("*");447if (wildcardIdx == -1)448return name.equals(template);449450boolean isBeginning = true;451String beforeWildcard = "";452String afterWildcard = template;453454while (wildcardIdx != -1) {455456// match in sequence the non-wildcard chars in the template.457beforeWildcard = afterWildcard.substring(0, wildcardIdx);458afterWildcard = afterWildcard.substring(wildcardIdx + 1);459460int beforeStartIdx = name.indexOf(beforeWildcard);461if ((beforeStartIdx == -1) ||462(isBeginning && beforeStartIdx != 0)) {463return false;464}465isBeginning = false;466467// update the match scope468name = name.substring(beforeStartIdx + beforeWildcard.length());469wildcardIdx = afterWildcard.indexOf("*");470}471return name.endsWith(afterWildcard);472}473}474475476