View Javadoc

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