hostnameverifier.java

来自「开源的axis2框架的源码。用于开发WEBSERVER」· Java 代码 · 共 576 行 · 第 1/2 页

JAVA
576
字号
                         is presenting (e.g. edit "/etc/apache2/server.crt"
                         or wherever it is your server's certificate chain
                         is defined).

                                               OR

                    #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
                          to a non-IBM JVM.
                */

                // If ssl.getInputStream().available() didn't cause an
                // exception, maybe at least now the session is available?
                session = ssl.getSession();
                if (session == null) {
                    // If it's still null, probably a startHandshake() will
                    // unearth the real problem.
                    ssl.startHandshake();

                    // Okay, if we still haven't managed to cause an exception,
                    // might as well go for the NPE.  Or maybe we're okay now?
                    session = ssl.getSession();
                }
            }
            Certificate[] certs;
            try {
                certs = session.getPeerCertificates();
            } catch (SSLPeerUnverifiedException spue) {
                InputStream in = ssl.getInputStream();
                in.available();
                // Didn't trigger anything interesting?  Okay, just throw
                // original.
                throw spue;
            }
            X509Certificate x509 = (X509Certificate) certs[0];
            check(host, x509);
        }

        public void check(String[] host, X509Certificate cert)
            throws SSLException {

            String[] cns = Certificates.getCNs(cert);
            String[] subjectAlts = Certificates.getDNSSubjectAlts(cert);
            check(host, cns, subjectAlts);

        }

        public void check(final String[] hosts, final String[] cns,
            final String[] subjectAlts, final boolean ie6,
            final boolean strictWithSubDomains)
            throws SSLException {
            // Build up lists of allowed hosts For logging/debugging purposes.
            StringBuffer buf = new StringBuffer(32);
            buf.append('<');
            for (int i = 0; i < hosts.length; i++) {
                String h = hosts[i];
                h = h != null ? h.trim().toLowerCase() : "";
                hosts[i] = h;
                if (i > 0) {
                    buf.append('/');
                }
                buf.append(h);
            }
            buf.append('>');
            String hostnames = buf.toString();
            // Build the list of names we're going to check.  Our DEFAULT and
            // STRICT implementations of the HostnameVerifier only use the
            // first CN provided.  All other CNs are ignored.
            // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
            TreeSet names = new TreeSet();
            if (cns != null && cns.length > 0 && cns[0] != null) {
                names.add(cns[0]);
                if (ie6) {
                    for (int i = 1; i < cns.length; i++) {
                        names.add(cns[i]);
                    }
                }
            }
            if (subjectAlts != null) {
                for (int i = 0; i < subjectAlts.length; i++) {
                    if (subjectAlts[i] != null) {
                        names.add(subjectAlts[i]);
                    }
                }
            }
            if (names.isEmpty()) {
                String msg = "Certificate for " + hosts[0] + " doesn't contain CN or DNS subjectAlt";
                throw new SSLException(msg);
            }

            // StringBuffer for building the error message.
            buf = new StringBuffer();

            boolean match = false;
            out:
            for (Iterator it = names.iterator(); it.hasNext();) {
                // Don't trim the CN, though!
                String cn = (String) it.next();
                cn = cn.toLowerCase();
                // Store CN in StringBuffer 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...
                boolean doWildcard = cn.startsWith("*.") &&
                    cn.lastIndexOf('.') >= 0 &&
                    !isIP4Address(cn) &&
                    acceptableCountryWildcard(cn);

                for (int i = 0; i < hosts.length; i++) {
                    final String hostName = hosts[i].trim().toLowerCase();
                    if (doWildcard) {
                        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(cn);
                    }
                    if (match) {
                        break out;
                    }
                }
            }
            if (!match) {
                throw new SSLException("hostname in certificate didn't match: " + hostnames + " !=" + buf);
            }
        }

        public static boolean isIP4Address(final String cn) {
            boolean isIP4 = true;
            String tld = cn;
            int x = cn.lastIndexOf('.');
            // We only bother analyzing the characters after the final dot
            // in the name.
            if (x >= 0 && x + 1 < cn.length()) {
                tld = cn.substring(x + 1);
            }
            for (int i = 0; i < tld.length(); i++) {
                if (!Character.isDigit(tld.charAt(0))) {
                    isIP4 = false;
                    break;
                }
            }
            return isIP4;
        }

        public static boolean acceptableCountryWildcard(final String cn) {
            int cnLen = cn.length();
            if (cnLen >= 7 && cnLen <= 9) {
                // Look for the '.' in the 3rd-last position:
                if (cn.charAt(cnLen - 3) == '.') {
                    // Trim off the [*.] and the [.XX].
                    String s = cn.substring(2, cnLen - 3);
                    // And test against the sorted array of bad 2lds:
                    int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s);
                    return x < 0;
                }
            }
            return true;
        }

        public static boolean isLocalhost(String host) {
            host = host != null ? host.trim().toLowerCase() : "";
            if (host.startsWith("::1")) {
                int x = host.lastIndexOf('%');
                if (x >= 0) {
                    host = host.substring(0, x);
                }
            }
            int x = Arrays.binarySearch(LOCALHOSTS, host);
            return x >= 0;
        }

        /**
         * Counts the number of dots "." in a string.
         *
         * @param s string to count dots from
         * @return number of dots
         */
        public static int countDots(final String s) {
            int count = 0;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '.') {
                    count++;
                }
            }
            return count;
        }
    }

    class Certificates {
        public static String[] getCNs(X509Certificate cert) {
            LinkedList cnList = new LinkedList();
            /*
           Sebastian Hauer's original StrictSSLProtocolSocketFactory used
           getName() and had the following comment:

              Parses a X.500 distinguished name for the value of the
              "Common Name" field.  This is done a bit sloppy right
              now and should probably be done a bit more according to
              <code>RFC 2253</code>.

            I've noticed that toString() seems to do a better job than
            getName() on these X500Principal objects, so I'm hoping that
            addresses Sebastian's concern.

            For example, getName() gives me this:
            1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d

            whereas toString() gives me this:
            EMAILADDRESS=juliusdavies@cucbc.com

            Looks like toString() even works with non-ascii domain names!
            I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
           */
            String subjectPrincipal = cert.getSubjectX500Principal().toString();
            StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
            while (st.hasMoreTokens()) {
                String tok = st.nextToken();
                int x = tok.indexOf("CN=");
                if (x >= 0) {
                    cnList.add(tok.substring(x + 3));
                }
            }
            if (!cnList.isEmpty()) {
                String[] cns = new String[cnList.size()];
                cnList.toArray(cns);
                return cns;
            } else {
                return null;
            }
        }

        /**
         * Extracts the array of SubjectAlt DNS names from an X509Certificate.
         * Returns null if there aren't any.
         * <p/>
         * Note:  Java doesn't appear able to extract international characters
         * from the SubjectAlts.  It can only extract international characters
         * from the CN field.
         * <p/>
         * (Or maybe the version of OpenSSL I'm using to test isn't storing the
         * international characters correctly in the SubjectAlts?).
         *
         * @param cert X509Certificate
         * @return Array of SubjectALT DNS names stored in the certificate.
         */
        public static String[] getDNSSubjectAlts(X509Certificate cert) {
            LinkedList subjectAltList = new LinkedList();
            Collection c = null;
            try {
                c = cert.getSubjectAlternativeNames();
            }
            catch (CertificateParsingException cpe) {
                // Should probably log.debug() this?
                cpe.printStackTrace();
            }
            if (c != null) {
                Iterator it = c.iterator();
                while (it.hasNext()) {
                    List list = (List) it.next();
                    int type = ((Integer) list.get(0)).intValue();
                    // If type is 2, then we've got a dNSName
                    if (type == 2) {
                        String s = (String) list.get(1);
                        subjectAltList.add(s);
                    }
                }
            }
            if (!subjectAltList.isEmpty()) {
                String[] subjectAlts = new String[subjectAltList.size()];
                subjectAltList.toArray(subjectAlts);
                return subjectAlts;
            } else {
                return null;
            }
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?