Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/sun/security/util/HostnameChecker.java
38830 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.InetAddress;29import java.net.UnknownHostException;30import java.util.*;3132import java.security.Principal;33import java.security.cert.*;34import java.text.Normalizer;3536import javax.security.auth.x500.X500Principal;37import javax.net.ssl.SNIHostName;3839import sun.security.ssl.Krb5Helper;40import sun.security.x509.X500Name;4142import sun.net.util.IPAddressUtil;43import sun.security.ssl.SSLLogger;4445/**46* Class to check hostnames against the names specified in a certificate as47* required for TLS and LDAP.48*49*/50public class HostnameChecker {5152// Constant for a HostnameChecker for TLS53public final static byte TYPE_TLS = 1;54private final static HostnameChecker INSTANCE_TLS =55new HostnameChecker(TYPE_TLS);5657// Constant for a HostnameChecker for LDAP58public final static byte TYPE_LDAP = 2;59private final static HostnameChecker INSTANCE_LDAP =60new HostnameChecker(TYPE_LDAP);6162// constants for subject alt names of type DNS and IP63private final static int ALTNAME_DNS = 2;64private final static int ALTNAME_IP = 7;6566// the algorithm to follow to perform the check. Currently unused.67private final byte checkType;6869private HostnameChecker(byte checkType) {70this.checkType = checkType;71}7273/**74* Get a HostnameChecker instance. checkType should be one of the75* TYPE_* constants defined in this class.76*/77public static HostnameChecker getInstance(byte checkType) {78if (checkType == TYPE_TLS) {79return INSTANCE_TLS;80} else if (checkType == TYPE_LDAP) {81return INSTANCE_LDAP;82}83throw new IllegalArgumentException("Unknown check type: " + checkType);84}8586/**87* Perform the check.88*89* @param expectedName the expected host name or ip address90* @param cert the certificate to check against91* @param chainsToPublicCA true if the certificate chains to a public92* root CA (as pre-installed in the cacerts file)93* @throws CertificateException if the name does not match any of94* the names specified in the certificate95*/96public void match(String expectedName, X509Certificate cert,97boolean chainsToPublicCA) throws CertificateException {98if (expectedName == null) {99throw new CertificateException("Hostname or IP address is " +100"undefined.");101}102if (isIpAddress(expectedName)) {103matchIP(expectedName, cert);104} else {105matchDNS(expectedName, cert, chainsToPublicCA);106}107}108109public void match(String expectedName, X509Certificate cert)110throws CertificateException {111match(expectedName, cert, false);112}113114/**115* Perform the check for Kerberos.116*/117public static boolean match(String expectedName, Principal principal) {118String hostName = getServerName(principal);119return (expectedName.equalsIgnoreCase(hostName));120}121122/**123* Return the Server name from Kerberos principal.124*/125public static String getServerName(Principal principal) {126return Krb5Helper.getPrincipalHostName(principal);127}128129/**130* Test whether the given hostname looks like a literal IPv4 or IPv6131* address. The hostname does not need to be a fully qualified name.132*133* This is not a strict check that performs full input validation.134* That means if the method returns true, name need not be a correct135* IP address, rather that it does not represent a valid DNS hostname.136* Likewise for IP addresses when it returns false.137*/138private static boolean isIpAddress(String name) {139if (IPAddressUtil.isIPv4LiteralAddress(name) ||140IPAddressUtil.isIPv6LiteralAddress(name)) {141return true;142} else {143return false;144}145}146147/**148* Check if the certificate allows use of the given IP address.149*150* From RFC2818:151* In some cases, the URI is specified as an IP address rather than a152* hostname. In this case, the iPAddress subjectAltName must be present153* in the certificate and must exactly match the IP in the URI.154*/155private static void matchIP(String expectedIP, X509Certificate cert)156throws CertificateException {157Collection<List<?>> subjAltNames = cert.getSubjectAlternativeNames();158if (subjAltNames == null) {159throw new CertificateException160("No subject alternative names present");161}162for (List<?> next : subjAltNames) {163// For IP address, it needs to be exact match164if (((Integer)next.get(0)).intValue() == ALTNAME_IP) {165String ipAddress = (String)next.get(1);166if (expectedIP.equalsIgnoreCase(ipAddress)) {167return;168} else {169// compare InetAddress objects in order to ensure170// equality between a long IPv6 address and its171// abbreviated form.172try {173if (InetAddress.getByName(expectedIP).equals(174InetAddress.getByName(ipAddress))) {175return;176}177} catch (UnknownHostException e) {178} catch (SecurityException e) {}179}180}181}182throw new CertificateException("No subject alternative " +183"names matching " + "IP address " +184expectedIP + " found");185}186187/**188* Check if the certificate allows use of the given DNS name.189*190* From RFC2818:191* If a subjectAltName extension of type dNSName is present, that MUST192* be used as the identity. Otherwise, the (most specific) Common Name193* field in the Subject field of the certificate MUST be used. Although194* the use of the Common Name is existing practice, it is deprecated and195* Certification Authorities are encouraged to use the dNSName instead.196*197* Matching is performed using the matching rules specified by198* [RFC5280]. If more than one identity of a given type is present in199* the certificate (e.g., more than one dNSName name, a match in any one200* of the set is considered acceptable.)201*/202private void matchDNS(String expectedName, X509Certificate cert,203boolean chainsToPublicCA)204throws CertificateException {205// Check that the expected name is a valid domain name.206try {207// Using the checking implemented in SNIHostName208SNIHostName sni = new SNIHostName(expectedName);209} catch (IllegalArgumentException iae) {210throw new CertificateException(211"Illegal given domain name: " + expectedName, iae);212}213214Collection<List<?>> subjAltNames = cert.getSubjectAlternativeNames();215if (subjAltNames != null) {216boolean foundDNS = false;217for ( List<?> next : subjAltNames) {218if (((Integer)next.get(0)).intValue() == ALTNAME_DNS) {219foundDNS = true;220String dnsName = (String)next.get(1);221if (isMatched(expectedName, dnsName, chainsToPublicCA)) {222return;223}224}225}226if (foundDNS) {227// if certificate contains any subject alt names of type DNS228// but none match, reject229throw new CertificateException("No subject alternative DNS "230+ "name matching " + expectedName + " found.");231}232}233X500Name subjectName = getSubjectX500Name(cert);234DerValue derValue = subjectName.findMostSpecificAttribute235(X500Name.commonName_oid);236if (derValue != null) {237try {238String cname = derValue.getAsString();239if (!Normalizer.isNormalized(cname, Normalizer.Form.NFKC)) {240throw new CertificateException("Not a formal name "241+ cname);242}243if (isMatched(expectedName, cname,244chainsToPublicCA)) {245return;246}247} catch (IOException e) {248// ignore249}250}251String msg = "No name matching " + expectedName + " found";252throw new CertificateException(msg);253}254255256/**257* Return the subject of a certificate as X500Name, by reparsing if258* necessary. X500Name should only be used if access to name components259* is required, in other cases X500Principal is to be preferred.260*261* This method is currently used from within JSSE, do not remove.262*/263public static X500Name getSubjectX500Name(X509Certificate cert)264throws CertificateParsingException {265try {266Principal subjectDN = cert.getSubjectDN();267if (subjectDN instanceof X500Name) {268return (X500Name)subjectDN;269} else {270X500Principal subjectX500 = cert.getSubjectX500Principal();271return new X500Name(subjectX500.getEncoded());272}273} catch (IOException e) {274throw(CertificateParsingException)275new CertificateParsingException().initCause(e);276}277}278279280/**281* Returns true if name matches against template.<p>282*283* The matching is performed as per RFC 2818 rules for TLS and284* RFC 2830 rules for LDAP.<p>285*286* The <code>name</code> parameter should represent a DNS name. The287* <code>template</code> parameter may contain the wildcard character '*'.288*/289private boolean isMatched(String name, String template,290boolean chainsToPublicCA) {291if (hasIllegalWildcard(name, template, chainsToPublicCA)) {292return false;293}294// check the validity of the domain name template.295try {296// Replacing wildcard character '*' with 'z' so as to check297// the domain name template validity.298//299// Using the checking implemented in SNIHostName300SNIHostName sni = new SNIHostName(template.replace('*', 'z'));301} catch (IllegalArgumentException iae) {302// It would be nice to add debug log if not matching.303return false;304}305306if (checkType == TYPE_TLS) {307return matchAllWildcards(name, template);308} else if (checkType == TYPE_LDAP) {309return matchLeftmostWildcard(name, template);310} else {311return false;312}313}314315/**316* Returns true if the template contains an illegal wildcard character.317*/318private static boolean hasIllegalWildcard(String domain, String template,319boolean chainsToPublicCA) {320// not ok if it is a single wildcard character or "*."321if (template.equals("*") || template.equals("*.")) {322if (SSLLogger.isOn) {323SSLLogger.fine(324"Certificate domain name has illegal single " +325"wildcard character: " + template);326}327return true;328}329330int lastWildcardIndex = template.lastIndexOf("*");331332// ok if it has no wildcard character333if (lastWildcardIndex == -1) {334return false;335}336337String afterWildcard = template.substring(lastWildcardIndex);338int firstDotIndex = afterWildcard.indexOf(".");339340// not ok if there is no dot after wildcard (ex: "*com")341if (firstDotIndex == -1) {342if (SSLLogger.isOn) {343SSLLogger.fine(344"Certificate domain name has illegal wildcard, " +345"no dot after wildcard character: " + template);346}347return true;348}349350// If the wildcarded domain is a top-level domain under which names351// can be registered, then a wildcard is not allowed.352353if (!chainsToPublicCA) {354return false; // skip check for non-public certificates355}356Optional<RegisteredDomain> rd = RegisteredDomain.from(domain)357.filter(d -> d.type() == RegisteredDomain.Type.ICANN);358359if (rd.isPresent()) {360String wDomain = afterWildcard.substring(firstDotIndex + 1);361if (rd.get().publicSuffix().equalsIgnoreCase(wDomain)) {362if (SSLLogger.isOn) {363SSLLogger.fine(364"Certificate domain name has illegal " +365"wildcard for public suffix: " + template);366}367return true;368}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// Retreive 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