mobile/android/thirdparty/ch/boye/httpclientandroidlib/conn/ssl/AbstractVerifier.java

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rw-r--r--

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

     1 /*
     2  * ====================================================================
     3  * Licensed to the Apache Software Foundation (ASF) under one
     4  * or more contributor license agreements.  See the NOTICE file
     5  * distributed with this work for additional information
     6  * regarding copyright ownership.  The ASF licenses this file
     7  * to you under the Apache License, Version 2.0 (the
     8  * "License"); you may not use this file except in compliance
     9  * with the License.  You may obtain a copy of the License at
    10  *
    11  *   http://www.apache.org/licenses/LICENSE-2.0
    12  *
    13  * Unless required by applicable law or agreed to in writing,
    14  * software distributed under the License is distributed on an
    15  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    16  * KIND, either express or implied.  See the License for the
    17  * specific language governing permissions and limitations
    18  * under the License.
    19  * ====================================================================
    20  *
    21  * This software consists of voluntary contributions made by many
    22  * individuals on behalf of the Apache Software Foundation.  For more
    23  * information on the Apache Software Foundation, please see
    24  * <http://www.apache.org/>.
    25  *
    26  */
    28 package ch.boye.httpclientandroidlib.conn.ssl;
    30 import ch.boye.httpclientandroidlib.annotation.Immutable;
    32 import ch.boye.httpclientandroidlib.conn.util.InetAddressUtils;
    34 import java.io.IOException;
    35 import java.io.InputStream;
    36 import java.security.cert.Certificate;
    37 import java.security.cert.CertificateParsingException;
    38 import java.security.cert.X509Certificate;
    39 import java.util.Arrays;
    40 import java.util.Collection;
    41 import java.util.Iterator;
    42 import java.util.LinkedList;
    43 import java.util.List;
    44 import java.util.Locale;
    45 import java.util.StringTokenizer;
    46 import java.util.logging.Logger;
    47 import java.util.logging.Level;
    49 import javax.net.ssl.SSLException;
    50 import javax.net.ssl.SSLSession;
    51 import javax.net.ssl.SSLSocket;
    53 /**
    54  * Abstract base class for all standard {@link X509HostnameVerifier}
    55  * implementations.
    56  *
    57  * @since 4.0
    58  */
    59 @Immutable
    60 public abstract class AbstractVerifier implements X509HostnameVerifier {
    62     /**
    63      * This contains a list of 2nd-level domains that aren't allowed to
    64      * have wildcards when combined with country-codes.
    65      * For example: [*.co.uk].
    66      * <p/>
    67      * The [*.co.uk] problem is an interesting one.  Should we just hope
    68      * that CA's would never foolishly allow such a certificate to happen?
    69      * Looks like we're the only implementation guarding against this.
    70      * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check.
    71      */
    72     private final static String[] BAD_COUNTRY_2LDS =
    73           { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info",
    74             "lg", "ne", "net", "or", "org" };
    76     static {
    77         // Just in case developer forgot to manually sort the array.  :-)
    78         Arrays.sort(BAD_COUNTRY_2LDS);
    79     }
    81     public AbstractVerifier() {
    82         super();
    83     }
    85     public final void verify(String host, SSLSocket ssl)
    86           throws IOException {
    87         if(host == null) {
    88             throw new NullPointerException("host to verify is null");
    89         }
    91         SSLSession session = ssl.getSession();
    92         if(session == null) {
    93             // In our experience this only happens under IBM 1.4.x when
    94             // spurious (unrelated) certificates show up in the server'
    95             // chain.  Hopefully this will unearth the real problem:
    96             InputStream in = ssl.getInputStream();
    97             in.available();
    98             /*
    99               If you're looking at the 2 lines of code above because
   100               you're running into a problem, you probably have two
   101               options:
   103                 #1.  Clean up the certificate chain that your server
   104                      is presenting (e.g. edit "/etc/apache2/server.crt"
   105                      or wherever it is your server's certificate chain
   106                      is defined).
   108                                            OR
   110                 #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
   111                       to a non-IBM JVM.
   112             */
   114             // If ssl.getInputStream().available() didn't cause an
   115             // exception, maybe at least now the session is available?
   116             session = ssl.getSession();
   117             if(session == null) {
   118                 // If it's still null, probably a startHandshake() will
   119                 // unearth the real problem.
   120                 ssl.startHandshake();
   122                 // Okay, if we still haven't managed to cause an exception,
   123                 // might as well go for the NPE.  Or maybe we're okay now?
   124                 session = ssl.getSession();
   125             }
   126         }
   128         Certificate[] certs = session.getPeerCertificates();
   129         X509Certificate x509 = (X509Certificate) certs[0];
   130         verify(host, x509);
   131     }
   133     public final boolean verify(String host, SSLSession session) {
   134         try {
   135             Certificate[] certs = session.getPeerCertificates();
   136             X509Certificate x509 = (X509Certificate) certs[0];
   137             verify(host, x509);
   138             return true;
   139         }
   140         catch(SSLException e) {
   141             return false;
   142         }
   143     }
   145     public final void verify(String host, X509Certificate cert)
   146           throws SSLException {
   147         String[] cns = getCNs(cert);
   148         String[] subjectAlts = getSubjectAlts(cert, host);
   149         verify(host, cns, subjectAlts);
   150     }
   152     public final void verify(final String host, final String[] cns,
   153                              final String[] subjectAlts,
   154                              final boolean strictWithSubDomains)
   155           throws SSLException {
   157         // Build the list of names we're going to check.  Our DEFAULT and
   158         // STRICT implementations of the HostnameVerifier only use the
   159         // first CN provided.  All other CNs are ignored.
   160         // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
   161         LinkedList<String> names = new LinkedList<String>();
   162         if(cns != null && cns.length > 0 && cns[0] != null) {
   163             names.add(cns[0]);
   164         }
   165         if(subjectAlts != null) {
   166             for (String subjectAlt : subjectAlts) {
   167                 if (subjectAlt != null) {
   168                     names.add(subjectAlt);
   169                 }
   170             }
   171         }
   173         if(names.isEmpty()) {
   174             String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt";
   175             throw new SSLException(msg);
   176         }
   178         // StringBuilder for building the error message.
   179         StringBuilder buf = new StringBuilder();
   181         // We're can be case-insensitive when comparing the host we used to
   182         // establish the socket to the hostname in the certificate.
   183         String hostName = host.trim().toLowerCase(Locale.ENGLISH);
   184         boolean match = false;
   185         for(Iterator<String> it = names.iterator(); it.hasNext();) {
   186             // Don't trim the CN, though!
   187             String cn = it.next();
   188             cn = cn.toLowerCase(Locale.ENGLISH);
   189             // Store CN in StringBuilder in case we need to report an error.
   190             buf.append(" <");
   191             buf.append(cn);
   192             buf.append('>');
   193             if(it.hasNext()) {
   194                 buf.append(" OR");
   195             }
   197             // The CN better have at least two dots if it wants wildcard
   198             // action.  It also can't be [*.co.uk] or [*.co.jp] or
   199             // [*.org.uk], etc...
   200             String parts[] = cn.split("\\.");
   201             boolean doWildcard = parts.length >= 3 &&
   202                                  parts[0].endsWith("*") &&
   203                                  acceptableCountryWildcard(cn) &&
   204                                  !isIPAddress(host);
   206             if(doWildcard) {
   207                 if (parts[0].length() > 1) { // e.g. server*
   208                     String prefix = parts[0].substring(0, parts.length-2); // e.g. server
   209                     String suffix = cn.substring(parts[0].length()); // skip wildcard part from cn
   210                     String hostSuffix = hostName.substring(prefix.length()); // skip wildcard part from host
   211                     match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix);
   212                 } else {
   213                     match = hostName.endsWith(cn.substring(1));                    
   214                 }
   215                 if(match && strictWithSubDomains) {
   216                     // If we're in strict mode, then [*.foo.com] is not
   217                     // allowed to match [a.b.foo.com]
   218                     match = countDots(hostName) == countDots(cn);
   219                 }
   220             } else {
   221                 match = hostName.equals(cn);
   222             }
   223             if(match) {
   224                 break;
   225             }
   226         }
   227         if(!match) {
   228             throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf);
   229         }
   230     }
   232     public static boolean acceptableCountryWildcard(String cn) {
   233         String parts[] = cn.split("\\.");
   234         if (parts.length != 3 || parts[2].length() != 2) {
   235             return true; // it's not an attempt to wildcard a 2TLD within a country code
   236         }
   237         return Arrays.binarySearch(BAD_COUNTRY_2LDS, parts[1]) < 0;
   238     }
   240     public static String[] getCNs(X509Certificate cert) {
   241         LinkedList<String> cnList = new LinkedList<String>();
   242         /*
   243           Sebastian Hauer's original StrictSSLProtocolSocketFactory used
   244           getName() and had the following comment:
   246                 Parses a X.500 distinguished name for the value of the
   247                 "Common Name" field.  This is done a bit sloppy right
   248                  now and should probably be done a bit more according to
   249                 <code>RFC 2253</code>.
   251            I've noticed that toString() seems to do a better job than
   252            getName() on these X500Principal objects, so I'm hoping that
   253            addresses Sebastian's concern.
   255            For example, getName() gives me this:
   256            1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
   258            whereas toString() gives me this:
   259            EMAILADDRESS=juliusdavies@cucbc.com
   261            Looks like toString() even works with non-ascii domain names!
   262            I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
   263         */
   264         String subjectPrincipal = cert.getSubjectX500Principal().toString();
   265         StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
   266         while(st.hasMoreTokens()) {
   267             String tok = st.nextToken();
   268             int x = tok.indexOf("CN=");
   269             if(x >= 0) {
   270                 cnList.add(tok.substring(x + 3));
   271             }
   272         }
   273         if(!cnList.isEmpty()) {
   274             String[] cns = new String[cnList.size()];
   275             cnList.toArray(cns);
   276             return cns;
   277         } else {
   278             return null;
   279         }
   280     }
   282     /**
   283      * Extracts the array of SubjectAlt DNS or IP names from an X509Certificate.
   284      * Returns null if there aren't any.
   285      *
   286      * @param cert X509Certificate
   287      * @param hostname
   288      * @return Array of SubjectALT DNS or IP names stored in the certificate.
   289      */
   290     private static String[] getSubjectAlts(
   291             final X509Certificate cert, final String hostname) {
   292         int subjectType;
   293         if (isIPAddress(hostname)) {
   294             subjectType = 7;
   295         } else {
   296             subjectType = 2;
   297         }
   299         LinkedList<String> subjectAltList = new LinkedList<String>();
   300         Collection<List<?>> c = null;
   301         try {
   302             c = cert.getSubjectAlternativeNames();
   303         }
   304         catch(CertificateParsingException cpe) {
   305             Logger.getLogger(AbstractVerifier.class.getName())
   306                     .log(Level.FINE, "Error parsing certificate.", cpe);
   307         }
   308         if(c != null) {
   309             for (List<?> aC : c) {
   310                 List<?> list = aC;
   311                 int type = ((Integer) list.get(0)).intValue();
   312                 if (type == subjectType) {
   313                     String s = (String) list.get(1);
   314                     subjectAltList.add(s);
   315                 }
   316             }
   317         }
   318         if(!subjectAltList.isEmpty()) {
   319             String[] subjectAlts = new String[subjectAltList.size()];
   320             subjectAltList.toArray(subjectAlts);
   321             return subjectAlts;
   322         } else {
   323             return null;
   324         }
   325     }
   327     /**
   328      * Extracts the array of SubjectAlt DNS names from an X509Certificate.
   329      * Returns null if there aren't any.
   330      * <p/>
   331      * Note:  Java doesn't appear able to extract international characters
   332      * from the SubjectAlts.  It can only extract international characters
   333      * from the CN field.
   334      * <p/>
   335      * (Or maybe the version of OpenSSL I'm using to test isn't storing the
   336      * international characters correctly in the SubjectAlts?).
   337      *
   338      * @param cert X509Certificate
   339      * @return Array of SubjectALT DNS names stored in the certificate.
   340      */
   341     public static String[] getDNSSubjectAlts(X509Certificate cert) {
   342         return getSubjectAlts(cert, null);
   343     }
   345     /**
   346      * Counts the number of dots "." in a string.
   347      * @param s  string to count dots from
   348      * @return  number of dots
   349      */
   350     public static int countDots(final String s) {
   351         int count = 0;
   352         for(int i = 0; i < s.length(); i++) {
   353             if(s.charAt(i) == '.') {
   354                 count++;
   355             }
   356         }
   357         return count;
   358     }
   360     private static boolean isIPAddress(final String hostname) {
   361         return hostname != null &&
   362             (InetAddressUtils.isIPv4Address(hostname) ||
   363                     InetAddressUtils.isIPv6Address(hostname));
   364     }
   366 }

mercurial