michael@0: /*
michael@0: * ====================================================================
michael@0: * Licensed to the Apache Software Foundation (ASF) under one
michael@0: * or more contributor license agreements. See the NOTICE file
michael@0: * distributed with this work for additional information
michael@0: * regarding copyright ownership. The ASF licenses this file
michael@0: * to you under the Apache License, Version 2.0 (the
michael@0: * "License"); you may not use this file except in compliance
michael@0: * with the License. You may obtain a copy of the License at
michael@0: *
michael@0: * http://www.apache.org/licenses/LICENSE-2.0
michael@0: *
michael@0: * Unless required by applicable law or agreed to in writing,
michael@0: * software distributed under the License is distributed on an
michael@0: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
michael@0: * KIND, either express or implied. See the License for the
michael@0: * specific language governing permissions and limitations
michael@0: * under the License.
michael@0: * ====================================================================
michael@0: *
michael@0: * This software consists of voluntary contributions made by many
michael@0: * individuals on behalf of the Apache Software Foundation. For more
michael@0: * information on the Apache Software Foundation, please see
michael@0: * .
michael@0: *
michael@0: */
michael@0:
michael@0: package ch.boye.httpclientandroidlib.conn.ssl;
michael@0:
michael@0: import ch.boye.httpclientandroidlib.annotation.Immutable;
michael@0:
michael@0: import ch.boye.httpclientandroidlib.conn.util.InetAddressUtils;
michael@0:
michael@0: import java.io.IOException;
michael@0: import java.io.InputStream;
michael@0: import java.security.cert.Certificate;
michael@0: import java.security.cert.CertificateParsingException;
michael@0: import java.security.cert.X509Certificate;
michael@0: import java.util.Arrays;
michael@0: import java.util.Collection;
michael@0: import java.util.Iterator;
michael@0: import java.util.LinkedList;
michael@0: import java.util.List;
michael@0: import java.util.Locale;
michael@0: import java.util.StringTokenizer;
michael@0: import java.util.logging.Logger;
michael@0: import java.util.logging.Level;
michael@0:
michael@0: import javax.net.ssl.SSLException;
michael@0: import javax.net.ssl.SSLSession;
michael@0: import javax.net.ssl.SSLSocket;
michael@0:
michael@0: /**
michael@0: * Abstract base class for all standard {@link X509HostnameVerifier}
michael@0: * implementations.
michael@0: *
michael@0: * @since 4.0
michael@0: */
michael@0: @Immutable
michael@0: public abstract class AbstractVerifier implements X509HostnameVerifier {
michael@0:
michael@0: /**
michael@0: * This contains a list of 2nd-level domains that aren't allowed to
michael@0: * have wildcards when combined with country-codes.
michael@0: * For example: [*.co.uk].
michael@0: *
michael@0: * The [*.co.uk] problem is an interesting one. Should we just hope
michael@0: * that CA's would never foolishly allow such a certificate to happen?
michael@0: * Looks like we're the only implementation guarding against this.
michael@0: * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check.
michael@0: */
michael@0: private final static String[] BAD_COUNTRY_2LDS =
michael@0: { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info",
michael@0: "lg", "ne", "net", "or", "org" };
michael@0:
michael@0: static {
michael@0: // Just in case developer forgot to manually sort the array. :-)
michael@0: Arrays.sort(BAD_COUNTRY_2LDS);
michael@0: }
michael@0:
michael@0: public AbstractVerifier() {
michael@0: super();
michael@0: }
michael@0:
michael@0: public final void verify(String host, SSLSocket ssl)
michael@0: throws IOException {
michael@0: if(host == null) {
michael@0: throw new NullPointerException("host to verify is null");
michael@0: }
michael@0:
michael@0: SSLSession session = ssl.getSession();
michael@0: if(session == null) {
michael@0: // In our experience this only happens under IBM 1.4.x when
michael@0: // spurious (unrelated) certificates show up in the server'
michael@0: // chain. Hopefully this will unearth the real problem:
michael@0: InputStream in = ssl.getInputStream();
michael@0: in.available();
michael@0: /*
michael@0: If you're looking at the 2 lines of code above because
michael@0: you're running into a problem, you probably have two
michael@0: options:
michael@0:
michael@0: #1. Clean up the certificate chain that your server
michael@0: is presenting (e.g. edit "/etc/apache2/server.crt"
michael@0: or wherever it is your server's certificate chain
michael@0: is defined).
michael@0:
michael@0: OR
michael@0:
michael@0: #2. Upgrade to an IBM 1.5.x or greater JVM, or switch
michael@0: to a non-IBM JVM.
michael@0: */
michael@0:
michael@0: // If ssl.getInputStream().available() didn't cause an
michael@0: // exception, maybe at least now the session is available?
michael@0: session = ssl.getSession();
michael@0: if(session == null) {
michael@0: // If it's still null, probably a startHandshake() will
michael@0: // unearth the real problem.
michael@0: ssl.startHandshake();
michael@0:
michael@0: // Okay, if we still haven't managed to cause an exception,
michael@0: // might as well go for the NPE. Or maybe we're okay now?
michael@0: session = ssl.getSession();
michael@0: }
michael@0: }
michael@0:
michael@0: Certificate[] certs = session.getPeerCertificates();
michael@0: X509Certificate x509 = (X509Certificate) certs[0];
michael@0: verify(host, x509);
michael@0: }
michael@0:
michael@0: public final boolean verify(String host, SSLSession session) {
michael@0: try {
michael@0: Certificate[] certs = session.getPeerCertificates();
michael@0: X509Certificate x509 = (X509Certificate) certs[0];
michael@0: verify(host, x509);
michael@0: return true;
michael@0: }
michael@0: catch(SSLException e) {
michael@0: return false;
michael@0: }
michael@0: }
michael@0:
michael@0: public final void verify(String host, X509Certificate cert)
michael@0: throws SSLException {
michael@0: String[] cns = getCNs(cert);
michael@0: String[] subjectAlts = getSubjectAlts(cert, host);
michael@0: verify(host, cns, subjectAlts);
michael@0: }
michael@0:
michael@0: public final void verify(final String host, final String[] cns,
michael@0: final String[] subjectAlts,
michael@0: final boolean strictWithSubDomains)
michael@0: throws SSLException {
michael@0:
michael@0: // Build the list of names we're going to check. Our DEFAULT and
michael@0: // STRICT implementations of the HostnameVerifier only use the
michael@0: // first CN provided. All other CNs are ignored.
michael@0: // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
michael@0: LinkedList names = new LinkedList();
michael@0: if(cns != null && cns.length > 0 && cns[0] != null) {
michael@0: names.add(cns[0]);
michael@0: }
michael@0: if(subjectAlts != null) {
michael@0: for (String subjectAlt : subjectAlts) {
michael@0: if (subjectAlt != null) {
michael@0: names.add(subjectAlt);
michael@0: }
michael@0: }
michael@0: }
michael@0:
michael@0: if(names.isEmpty()) {
michael@0: String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt";
michael@0: throw new SSLException(msg);
michael@0: }
michael@0:
michael@0: // StringBuilder for building the error message.
michael@0: StringBuilder buf = new StringBuilder();
michael@0:
michael@0: // We're can be case-insensitive when comparing the host we used to
michael@0: // establish the socket to the hostname in the certificate.
michael@0: String hostName = host.trim().toLowerCase(Locale.ENGLISH);
michael@0: boolean match = false;
michael@0: for(Iterator it = names.iterator(); it.hasNext();) {
michael@0: // Don't trim the CN, though!
michael@0: String cn = it.next();
michael@0: cn = cn.toLowerCase(Locale.ENGLISH);
michael@0: // Store CN in StringBuilder in case we need to report an error.
michael@0: buf.append(" <");
michael@0: buf.append(cn);
michael@0: buf.append('>');
michael@0: if(it.hasNext()) {
michael@0: buf.append(" OR");
michael@0: }
michael@0:
michael@0: // The CN better have at least two dots if it wants wildcard
michael@0: // action. It also can't be [*.co.uk] or [*.co.jp] or
michael@0: // [*.org.uk], etc...
michael@0: String parts[] = cn.split("\\.");
michael@0: boolean doWildcard = parts.length >= 3 &&
michael@0: parts[0].endsWith("*") &&
michael@0: acceptableCountryWildcard(cn) &&
michael@0: !isIPAddress(host);
michael@0:
michael@0: if(doWildcard) {
michael@0: if (parts[0].length() > 1) { // e.g. server*
michael@0: String prefix = parts[0].substring(0, parts.length-2); // e.g. server
michael@0: String suffix = cn.substring(parts[0].length()); // skip wildcard part from cn
michael@0: String hostSuffix = hostName.substring(prefix.length()); // skip wildcard part from host
michael@0: match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix);
michael@0: } else {
michael@0: match = hostName.endsWith(cn.substring(1));
michael@0: }
michael@0: if(match && strictWithSubDomains) {
michael@0: // If we're in strict mode, then [*.foo.com] is not
michael@0: // allowed to match [a.b.foo.com]
michael@0: match = countDots(hostName) == countDots(cn);
michael@0: }
michael@0: } else {
michael@0: match = hostName.equals(cn);
michael@0: }
michael@0: if(match) {
michael@0: break;
michael@0: }
michael@0: }
michael@0: if(!match) {
michael@0: throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf);
michael@0: }
michael@0: }
michael@0:
michael@0: public static boolean acceptableCountryWildcard(String cn) {
michael@0: String parts[] = cn.split("\\.");
michael@0: if (parts.length != 3 || parts[2].length() != 2) {
michael@0: return true; // it's not an attempt to wildcard a 2TLD within a country code
michael@0: }
michael@0: return Arrays.binarySearch(BAD_COUNTRY_2LDS, parts[1]) < 0;
michael@0: }
michael@0:
michael@0: public static String[] getCNs(X509Certificate cert) {
michael@0: LinkedList cnList = new LinkedList();
michael@0: /*
michael@0: Sebastian Hauer's original StrictSSLProtocolSocketFactory used
michael@0: getName() and had the following comment:
michael@0:
michael@0: Parses a X.500 distinguished name for the value of the
michael@0: "Common Name" field. This is done a bit sloppy right
michael@0: now and should probably be done a bit more according to
michael@0: RFC 2253
.
michael@0:
michael@0: I've noticed that toString() seems to do a better job than
michael@0: getName() on these X500Principal objects, so I'm hoping that
michael@0: addresses Sebastian's concern.
michael@0:
michael@0: For example, getName() gives me this:
michael@0: 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
michael@0:
michael@0: whereas toString() gives me this:
michael@0: EMAILADDRESS=juliusdavies@cucbc.com
michael@0:
michael@0: Looks like toString() even works with non-ascii domain names!
michael@0: I tested it with "花子.co.jp" and it worked fine.
michael@0: */
michael@0: String subjectPrincipal = cert.getSubjectX500Principal().toString();
michael@0: StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
michael@0: while(st.hasMoreTokens()) {
michael@0: String tok = st.nextToken();
michael@0: int x = tok.indexOf("CN=");
michael@0: if(x >= 0) {
michael@0: cnList.add(tok.substring(x + 3));
michael@0: }
michael@0: }
michael@0: if(!cnList.isEmpty()) {
michael@0: String[] cns = new String[cnList.size()];
michael@0: cnList.toArray(cns);
michael@0: return cns;
michael@0: } else {
michael@0: return null;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Extracts the array of SubjectAlt DNS or IP names from an X509Certificate.
michael@0: * Returns null if there aren't any.
michael@0: *
michael@0: * @param cert X509Certificate
michael@0: * @param hostname
michael@0: * @return Array of SubjectALT DNS or IP names stored in the certificate.
michael@0: */
michael@0: private static String[] getSubjectAlts(
michael@0: final X509Certificate cert, final String hostname) {
michael@0: int subjectType;
michael@0: if (isIPAddress(hostname)) {
michael@0: subjectType = 7;
michael@0: } else {
michael@0: subjectType = 2;
michael@0: }
michael@0:
michael@0: LinkedList subjectAltList = new LinkedList();
michael@0: Collection> c = null;
michael@0: try {
michael@0: c = cert.getSubjectAlternativeNames();
michael@0: }
michael@0: catch(CertificateParsingException cpe) {
michael@0: Logger.getLogger(AbstractVerifier.class.getName())
michael@0: .log(Level.FINE, "Error parsing certificate.", cpe);
michael@0: }
michael@0: if(c != null) {
michael@0: for (List> aC : c) {
michael@0: List> list = aC;
michael@0: int type = ((Integer) list.get(0)).intValue();
michael@0: if (type == subjectType) {
michael@0: String s = (String) list.get(1);
michael@0: subjectAltList.add(s);
michael@0: }
michael@0: }
michael@0: }
michael@0: if(!subjectAltList.isEmpty()) {
michael@0: String[] subjectAlts = new String[subjectAltList.size()];
michael@0: subjectAltList.toArray(subjectAlts);
michael@0: return subjectAlts;
michael@0: } else {
michael@0: return null;
michael@0: }
michael@0: }
michael@0:
michael@0: /**
michael@0: * Extracts the array of SubjectAlt DNS names from an X509Certificate.
michael@0: * Returns null if there aren't any.
michael@0: *
michael@0: * Note: Java doesn't appear able to extract international characters
michael@0: * from the SubjectAlts. It can only extract international characters
michael@0: * from the CN field.
michael@0: *
michael@0: * (Or maybe the version of OpenSSL I'm using to test isn't storing the
michael@0: * international characters correctly in the SubjectAlts?).
michael@0: *
michael@0: * @param cert X509Certificate
michael@0: * @return Array of SubjectALT DNS names stored in the certificate.
michael@0: */
michael@0: public static String[] getDNSSubjectAlts(X509Certificate cert) {
michael@0: return getSubjectAlts(cert, null);
michael@0: }
michael@0:
michael@0: /**
michael@0: * Counts the number of dots "." in a string.
michael@0: * @param s string to count dots from
michael@0: * @return number of dots
michael@0: */
michael@0: public static int countDots(final String s) {
michael@0: int count = 0;
michael@0: for(int i = 0; i < s.length(); i++) {
michael@0: if(s.charAt(i) == '.') {
michael@0: count++;
michael@0: }
michael@0: }
michael@0: return count;
michael@0: }
michael@0:
michael@0: private static boolean isIPAddress(final String hostname) {
michael@0: return hostname != null &&
michael@0: (InetAddressUtils.isIPv4Address(hostname) ||
michael@0: InetAddressUtils.isIPv6Address(hostname));
michael@0: }
michael@0:
michael@0: }