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