1 /*
2  * $HeadURL: http://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk/module-client/src/main/java/org/apache/http/conn/ssl/AbstractVerifier.java $
3  * $Revision: 653041 $
4  * $Date: 2008-05-03 03:39:28 -0700 (Sat, 03 May 2008) $
5  *
6  * ====================================================================
7  * Licensed to the Apache Software Foundation (ASF) under one
8  * or more contributor license agreements.  See the NOTICE file
9  * distributed with this work for additional information
10  * regarding copyright ownership.  The ASF licenses this file
11  * to you under the Apache License, Version 2.0 (the
12  * "License"); you may not use this file except in compliance
13  * with the License.  You may obtain a copy of the License at
14  *
15  *   http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing,
18  * software distributed under the License is distributed on an
19  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
20  * KIND, either express or implied.  See the License for the
21  * specific language governing permissions and limitations
22  * under the License.
23  * ====================================================================
24  *
25  * This software consists of voluntary contributions made by many
26  * individuals on behalf of the Apache Software Foundation.  For more
27  * information on the Apache Software Foundation, please see
28  * <http://www.apache.org/>.
29  *
30  */
31 
32 package org.apache.http.conn.ssl;
33 
34 import android.compat.annotation.UnsupportedAppUsage;
35 
36 import java.io.IOException;
37 import java.security.cert.Certificate;
38 import java.security.cert.CertificateParsingException;
39 import java.security.cert.X509Certificate;
40 import java.util.Arrays;
41 import java.util.Collection;
42 import java.util.Iterator;
43 import java.util.LinkedList;
44 import java.util.List;
45 import java.util.Locale;
46 import java.util.logging.Level;
47 import java.util.logging.Logger;
48 import java.util.regex.Pattern;
49 
50 import javax.net.ssl.SSLException;
51 import javax.net.ssl.SSLSession;
52 import javax.net.ssl.SSLSocket;
53 
54 /**
55  * Abstract base class for all standard {@link X509HostnameVerifier}
56  * implementations.
57  *
58  * @author Julius Davies
59  *
60  * @deprecated Please use {@link java.net.URL#openConnection} instead.
61  *     Please visit <a href="http://android-developers.blogspot.com/2011/09/androids-http-clients.html">this webpage</a>
62  *     for further details.
63  */
64 @Deprecated
65 public abstract class AbstractVerifier implements X509HostnameVerifier {
66 
67     private static final Pattern IPV4_PATTERN = Pattern.compile(
68             "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
69 
70     /**
71      * This contains a list of 2nd-level domains that aren't allowed to
72      * have wildcards when combined with country-codes.
73      * For example: [*.co.uk].
74      * <p/>
75      * The [*.co.uk] problem is an interesting one.  Should we just hope
76      * that CA's would never foolishly allow such a certificate to happen?
77      * Looks like we're the only implementation guarding against this.
78      * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check.
79      */
80     @UnsupportedAppUsage
81     private final static String[] BAD_COUNTRY_2LDS =
82           { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info",
83             "lg", "ne", "net", "or", "org" };
84 
85     static {
86         // Just in case developer forgot to manually sort the array.  :-)
87         Arrays.sort(BAD_COUNTRY_2LDS);
88     }
89 
AbstractVerifier()90     public AbstractVerifier() {
91         super();
92     }
93 
verify(String host, SSLSocket ssl)94     public final void verify(String host, SSLSocket ssl)
95           throws IOException {
96         if(host == null) {
97             throw new NullPointerException("host to verify is null");
98         }
99 
100         SSLSession session = ssl.getSession();
101         Certificate[] certs = session.getPeerCertificates();
102         X509Certificate x509 = (X509Certificate) certs[0];
103         verify(host, x509);
104     }
105 
verify(String host, SSLSession session)106     public final boolean verify(String host, SSLSession session) {
107         try {
108             Certificate[] certs = session.getPeerCertificates();
109             X509Certificate x509 = (X509Certificate) certs[0];
110             verify(host, x509);
111             return true;
112         }
113         catch(SSLException e) {
114             return false;
115         }
116     }
117 
verify(String host, X509Certificate cert)118     public final void verify(String host, X509Certificate cert)
119           throws SSLException {
120         String[] cns = getCNs(cert);
121         String[] subjectAlts = getDNSSubjectAlts(cert);
122         verify(host, cns, subjectAlts);
123     }
124 
verify(final String host, final String[] cns, final String[] subjectAlts, final boolean strictWithSubDomains)125     public final void verify(final String host, final String[] cns,
126                              final String[] subjectAlts,
127                              final boolean strictWithSubDomains)
128           throws SSLException {
129 
130         // Build the list of names we're going to check.  Our DEFAULT and
131         // STRICT implementations of the HostnameVerifier only use the
132         // first CN provided.  All other CNs are ignored.
133         // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
134         LinkedList<String> names = new LinkedList<String>();
135         if(cns != null && cns.length > 0 && cns[0] != null) {
136             names.add(cns[0]);
137         }
138         if(subjectAlts != null) {
139             for (String subjectAlt : subjectAlts) {
140                 if (subjectAlt != null) {
141                     names.add(subjectAlt);
142                 }
143             }
144         }
145 
146         if(names.isEmpty()) {
147             String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt";
148             throw new SSLException(msg);
149         }
150 
151         // StringBuffer for building the error message.
152         StringBuffer buf = new StringBuffer();
153 
154         // We're can be case-insensitive when comparing the host we used to
155         // establish the socket to the hostname in the certificate.
156         String hostName = host.trim().toLowerCase(Locale.ENGLISH);
157         boolean match = false;
158         for(Iterator<String> it = names.iterator(); it.hasNext();) {
159             // Don't trim the CN, though!
160             String cn = it.next();
161             cn = cn.toLowerCase(Locale.ENGLISH);
162             // Store CN in StringBuffer in case we need to report an error.
163             buf.append(" <");
164             buf.append(cn);
165             buf.append('>');
166             if(it.hasNext()) {
167                 buf.append(" OR");
168             }
169 
170             // The CN better have at least two dots if it wants wildcard
171             // action.  It also can't be [*.co.uk] or [*.co.jp] or
172             // [*.org.uk], etc...
173             boolean doWildcard = cn.startsWith("*.") &&
174                                  cn.indexOf('.', 2) != -1 &&
175                                  acceptableCountryWildcard(cn) &&
176                                  !isIPv4Address(host);
177 
178             if(doWildcard) {
179                 match = hostName.endsWith(cn.substring(1));
180                 if(match && strictWithSubDomains) {
181                     // If we're in strict mode, then [*.foo.com] is not
182                     // allowed to match [a.b.foo.com]
183                     match = countDots(hostName) == countDots(cn);
184                 }
185             } else {
186                 match = hostName.equals(cn);
187             }
188             if(match) {
189                 break;
190             }
191         }
192         if(!match) {
193             throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf);
194         }
195     }
196 
acceptableCountryWildcard(String cn)197     public static boolean acceptableCountryWildcard(String cn) {
198         int cnLen = cn.length();
199         if(cnLen >= 7 && cnLen <= 9) {
200             // Look for the '.' in the 3rd-last position:
201             if(cn.charAt(cnLen - 3) == '.') {
202                 // Trim off the [*.] and the [.XX].
203                 String s = cn.substring(2, cnLen - 3);
204                 // And test against the sorted array of bad 2lds:
205                 int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s);
206                 return x < 0;
207             }
208         }
209         return true;
210     }
211 
getCNs(X509Certificate cert)212     public static String[] getCNs(X509Certificate cert) {
213         AndroidDistinguishedNameParser dnParser =
214                 new AndroidDistinguishedNameParser(cert.getSubjectX500Principal());
215         List<String> cnList = dnParser.getAllMostSpecificFirst("cn");
216 
217         if(!cnList.isEmpty()) {
218             String[] cns = new String[cnList.size()];
219             cnList.toArray(cns);
220             return cns;
221         } else {
222             return null;
223         }
224     }
225 
226 
227     /**
228      * Extracts the array of SubjectAlt DNS names from an X509Certificate.
229      * Returns null if there aren't any.
230      * <p/>
231      * Note:  Java doesn't appear able to extract international characters
232      * from the SubjectAlts.  It can only extract international characters
233      * from the CN field.
234      * <p/>
235      * (Or maybe the version of OpenSSL I'm using to test isn't storing the
236      * international characters correctly in the SubjectAlts?).
237      *
238      * @param cert X509Certificate
239      * @return Array of SubjectALT DNS names stored in the certificate.
240      */
getDNSSubjectAlts(X509Certificate cert)241     public static String[] getDNSSubjectAlts(X509Certificate cert) {
242         LinkedList<String> subjectAltList = new LinkedList<String>();
243         Collection<List<?>> c = null;
244         try {
245             c = cert.getSubjectAlternativeNames();
246         }
247         catch(CertificateParsingException cpe) {
248             Logger.getLogger(AbstractVerifier.class.getName())
249                     .log(Level.FINE, "Error parsing certificate.", cpe);
250         }
251         if(c != null) {
252             for (List<?> aC : c) {
253                 List<?> list = aC;
254                 int type = ((Integer) list.get(0)).intValue();
255                 // If type is 2, then we've got a dNSName
256                 if (type == 2) {
257                     String s = (String) list.get(1);
258                     subjectAltList.add(s);
259                 }
260             }
261         }
262         if(!subjectAltList.isEmpty()) {
263             String[] subjectAlts = new String[subjectAltList.size()];
264             subjectAltList.toArray(subjectAlts);
265             return subjectAlts;
266         } else {
267             return null;
268         }
269     }
270 
271     /**
272      * Counts the number of dots "." in a string.
273      * @param s  string to count dots from
274      * @return  number of dots
275      */
countDots(final String s)276     public static int countDots(final String s) {
277         int count = 0;
278         for(int i = 0; i < s.length(); i++) {
279             if(s.charAt(i) == '.') {
280                 count++;
281             }
282         }
283         return count;
284     }
285 
isIPv4Address(final String input)286     private static boolean isIPv4Address(final String input) {
287         return IPV4_PATTERN.matcher(input).matches();
288     }
289 }
290