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.net.InetAddress;
31  import java.net.UnknownHostException;
32  import java.security.cert.CertificateParsingException;
33  import java.security.cert.X509Certificate;
34  import java.util.Arrays;
35  import java.util.Collection;
36  import java.util.Iterator;
37  import java.util.LinkedList;
38  import java.util.List;
39  import java.util.Locale;
40  import java.util.StringTokenizer;
41  
42  import javax.net.ssl.SSLException;
43  
44  import org.apache.commons.logging.Log;
45  import org.apache.commons.logging.LogFactory;
46  import org.apache.http.annotation.Immutable;
47  import org.apache.http.conn.util.InetAddressUtils;
48  
49  /**
50   /**
51   * Abstract base class for all standard {@link org.apache.http.conn.ssl.X509HostnameVerifier}
52   * implementations that provides methods to extract Common Name (CN) and alternative subjects
53   * (subjectAlt) from {@link java.security.cert.X509Certificate} being validated as well
54   * as {@link #verify(String, String[], String[], boolean)} method that implements common
55   * certificate subject validation logic.
56   *
57   * @since 4.4
58   */
59  @Immutable
60  public abstract class AbstractCommonHostnameVerifier extends AbstractBaseHostnameVerifier {
61  
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" };
75  
76      static {
77          // Just in case developer forgot to manually sort the array.  :-)
78          Arrays.sort(BAD_COUNTRY_2LDS);
79      }
80  
81      private final Log log = LogFactory.getLog(getClass());
82  
83      @Override
84      public final void verify(final String host, final X509Certificate cert)
85            throws SSLException {
86          final String[] cns = getCNs(cert);
87          final String[] subjectAlts = getSubjectAlts(cert, host);
88          verify(host, cns, subjectAlts);
89      }
90  
91      public final void verify(final String host, final String[] cns,
92                               final String[] subjectAlts,
93                               final boolean strictWithSubDomains)
94            throws SSLException {
95  
96          // Build the list of names we're going to check.  Our DEFAULT and
97          // STRICT implementations of the HostnameVerifier only use the
98          // first CN provided.  All other CNs are ignored.
99          // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
100         final LinkedList<String> names = new LinkedList<String>();
101         if(cns != null && cns.length > 0 && cns[0] != null) {
102             names.add(cns[0]);
103         }
104         if(subjectAlts != null) {
105             for (final String subjectAlt : subjectAlts) {
106                 if (subjectAlt != null) {
107                     names.add(subjectAlt);
108                 }
109             }
110         }
111 
112         if(names.isEmpty()) {
113             final String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt";
114             throw new SSLException(msg);
115         }
116 
117         // StringBuilder for building the error message.
118         final StringBuilder buf = new StringBuilder();
119 
120         // We're can be case-insensitive when comparing the host we used to
121         // establish the socket to the hostname in the certificate.
122         final String hostName = normaliseIPv6Address(host.trim().toLowerCase(Locale.ROOT));
123         boolean match = false;
124         for(final Iterator<String> it = names.iterator(); it.hasNext();) {
125             // Don't trim the CN, though!
126             String cn = it.next();
127             cn = cn.toLowerCase(Locale.ROOT);
128             // Store CN in StringBuilder in case we need to report an error.
129             buf.append(" <");
130             buf.append(cn);
131             buf.append('>');
132             if(it.hasNext()) {
133                 buf.append(" OR");
134             }
135 
136             // The CN better have at least two dots if it wants wildcard
137             // action.  It also can't be [*.co.uk] or [*.co.jp] or
138             // [*.org.uk], etc...
139             final String parts[] = cn.split("\\.");
140             final boolean doWildcard =
141                     parts.length >= 3 && parts[0].endsWith("*") &&
142                     validCountryWildcard(cn) && !isIPAddress(host);
143 
144             if(doWildcard) {
145                 final String firstpart = parts[0];
146                 if (firstpart.length() > 1) { // e.g. server*
147                     final String prefix = firstpart.substring(0, firstpart.length() - 1); // e.g. server
148                     final String suffix = cn.substring(firstpart.length()); // skip wildcard part from cn
149                     final String hostSuffix = hostName.substring(prefix.length()); // skip wildcard part from host
150                     match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix);
151                 } else {
152                     match = hostName.endsWith(cn.substring(1));
153                 }
154                 if(match && strictWithSubDomains) {
155                     // If we're in strict mode, then [*.foo.com] is not
156                     // allowed to match [a.b.foo.com]
157                     match = countDots(hostName) == countDots(cn);
158                 }
159             } else {
160                 match = hostName.equals(normaliseIPv6Address(cn));
161             }
162             if(match) {
163                 break;
164             }
165         }
166         if(!match) {
167             throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf);
168         }
169     }
170 
171     /**
172      * @deprecated (4.3.1) should not be a part of public APIs.
173      */
174     @Deprecated
175     public static boolean acceptableCountryWildcard(final String cn) {
176         final String parts[] = cn.split("\\.");
177         if (parts.length != 3 || parts[2].length() != 2) {
178             return true; // it's not an attempt to wildcard a 2TLD within a country code
179         }
180         return Arrays.binarySearch(BAD_COUNTRY_2LDS, parts[1]) < 0;
181     }
182 
183     boolean validCountryWildcard(final String cn) {
184         final String parts[] = cn.split("\\.");
185         if (parts.length != 3 || parts[2].length() != 2) {
186             return true; // it's not an attempt to wildcard a 2TLD within a country code
187         }
188         return Arrays.binarySearch(BAD_COUNTRY_2LDS, parts[1]) < 0;
189     }
190 
191     public static String[] getCNs(final X509Certificate cert) {
192         final LinkedList<String> cnList = new LinkedList<String>();
193         /*
194           Sebastian Hauer's original StrictSSLProtocolSocketFactory used
195           getName() and had the following comment:
196 
197                 Parses a X.500 distinguished name for the value of the
198                 "Common Name" field.  This is done a bit sloppy right
199                  now and should probably be done a bit more according to
200                 <code>RFC 2253</code>.
201 
202            I've noticed that toString() seems to do a better job than
203            getName() on these X500Principal objects, so I'm hoping that
204            addresses Sebastian's concern.
205 
206            For example, getName() gives me this:
207            1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
208 
209            whereas toString() gives me this:
210            EMAILADDRESS=juliusdavies@cucbc.com
211 
212            Looks like toString() even works with non-ascii domain names!
213            I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
214         */
215 
216         final String subjectPrincipal = cert.getSubjectX500Principal().toString();
217         final StringTokenizer st = new StringTokenizer(subjectPrincipal, ",+");
218         while(st.hasMoreTokens()) {
219             final String tok = st.nextToken().trim();
220             if (tok.length() > 3) {
221                 if (tok.substring(0, 3).equalsIgnoreCase("CN=")) {
222                     cnList.add(tok.substring(3));
223                 }
224             }
225         }
226         if(!cnList.isEmpty()) {
227             final String[] cns = new String[cnList.size()];
228             cnList.toArray(cns);
229             return cns;
230         } else {
231             return null;
232         }
233     }
234 
235     /**
236      * Extracts the array of SubjectAlt DNS or IP names from an X509Certificate.
237      * Returns null if there aren't any.
238      *
239      * @param cert X509Certificate
240      * @param hostname
241      * @return Array of SubjectALT DNS or IP names stored in the certificate.
242      */
243     private static String[] getSubjectAlts(
244             final X509Certificate cert, final String hostname) {
245         final int subjectType;
246         if (isIPAddress(hostname)) {
247             subjectType = 7;
248         } else {
249             subjectType = 2;
250         }
251 
252         final LinkedList<String> subjectAltList = new LinkedList<String>();
253         Collection<List<?>> c = null;
254         try {
255             c = cert.getSubjectAlternativeNames();
256         }
257         catch(final CertificateParsingException cpe) {
258         }
259         if(c != null) {
260             for (final List<?> aC : c) {
261                 final List<?> list = aC;
262                 final int type = ((Integer) list.get(0)).intValue();
263                 if (type == subjectType) {
264                     final String s = (String) list.get(1);
265                     subjectAltList.add(s);
266                 }
267             }
268         }
269         if(!subjectAltList.isEmpty()) {
270             final String[] subjectAlts = new String[subjectAltList.size()];
271             subjectAltList.toArray(subjectAlts);
272             return subjectAlts;
273         } else {
274             return null;
275         }
276     }
277 
278     /**
279      * Extracts the array of SubjectAlt DNS names from an X509Certificate.
280      * Returns null if there aren't any.
281      * <p/>
282      * Note:  Java doesn't appear able to extract international characters
283      * from the SubjectAlts.  It can only extract international characters
284      * from the CN field.
285      * <p/>
286      * (Or maybe the version of OpenSSL I'm using to test isn't storing the
287      * international characters correctly in the SubjectAlts?).
288      *
289      * @param cert X509Certificate
290      * @return Array of SubjectALT DNS names stored in the certificate.
291      */
292     public static String[] getDNSSubjectAlts(final X509Certificate cert) {
293         return getSubjectAlts(cert, null);
294     }
295 
296     /**
297      * Counts the number of dots "." in a string.
298      * @param s  string to count dots from
299      * @return  number of dots
300      */
301     public static int countDots(final String s) {
302         int count = 0;
303         for(int i = 0; i < s.length(); i++) {
304             if(s.charAt(i) == '.') {
305                 count++;
306             }
307         }
308         return count;
309     }
310 
311     private static boolean isIPAddress(final String hostname) {
312         return hostname != null &&
313             (InetAddressUtils.isIPv4Address(hostname) ||
314                     InetAddressUtils.isIPv6Address(hostname));
315     }
316 
317     /*
318      * Check if hostname is IPv6, and if so, convert to standard format.
319      */
320     private String normaliseIPv6Address(final String hostname) {
321         if (hostname == null || !InetAddressUtils.isIPv6Address(hostname)) {
322             return hostname;
323         }
324         try {
325             final InetAddress inetAddress = InetAddress.getByName(hostname);
326             return inetAddress.getHostAddress();
327         } catch (final UnknownHostException uhe) { // Should not happen, because we check for IPv6 address above
328             log.error("Unexpected error converting "+hostname, uhe);
329             return hostname;
330         }
331     }
332 }