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