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 org.apache.http.conn.util.InetAddressUtils; 35 36 import java.io.IOException; 37 import java.io.InputStream; 38 import java.security.cert.Certificate; 39 import java.security.cert.CertificateParsingException; 40 import java.security.cert.X509Certificate; 41 import java.util.Arrays; 42 import java.util.Collection; 43 import java.util.Iterator; 44 import java.util.LinkedList; 45 import java.util.List; 46 import java.util.Locale; 47 import java.util.StringTokenizer; 48 import java.util.logging.Logger; 49 import java.util.logging.Level; 50 51 import javax.net.ssl.SSLException; 52 import javax.net.ssl.SSLSession; 53 import javax.net.ssl.SSLSocket; 54 55 /** 56 * Abstract base class for all standard {@link X509HostnameVerifier} 57 * implementations. 58 * 59 * @author Julius Davies 60 */ 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 public AbstractVerifier() { 83 super(); 84 } 85 86 public final void verify(String host, SSLSocket ssl) 87 throws IOException { 88 if(host == null) { 89 throw new NullPointerException("host to verify is null"); 90 } 91 92 ssl.startHandshake(); 93 SSLSession session = ssl.getSession(); 94 if(session == null) { 95 // In our experience this only happens under IBM 1.4.x when 96 // spurious (unrelated) certificates show up in the server' 97 // chain. Hopefully this will unearth the real problem: 98 InputStream in = ssl.getInputStream(); 99 in.available(); 100 /* 101 If you're looking at the 2 lines of code above because 102 you're running into a problem, you probably have two 103 options: 104 105 #1. Clean up the certificate chain that your server 106 is presenting (e.g. edit "/etc/apache2/server.crt" 107 or wherever it is your server's certificate chain 108 is defined). 109 110 OR 111 112 #2. Upgrade to an IBM 1.5.x or greater JVM, or switch 113 to a non-IBM JVM. 114 */ 115 116 // If ssl.getInputStream().available() didn't cause an 117 // exception, maybe at least now the session is available? 118 session = ssl.getSession(); 119 if(session == null) { 120 // If it's still null, probably a startHandshake() will 121 // unearth the real problem. 122 ssl.startHandshake(); 123 124 // Okay, if we still haven't managed to cause an exception, 125 // might as well go for the NPE. Or maybe we're okay now? 126 session = ssl.getSession(); 127 } 128 } 129 130 Certificate[] certs = session.getPeerCertificates(); 131 X509Certificate x509 = (X509Certificate) certs[0]; 132 verify(host, x509); 133 } 134 135 public final boolean verify(String host, SSLSession session) { 136 try { 137 Certificate[] certs = session.getPeerCertificates(); 138 X509Certificate x509 = (X509Certificate) certs[0]; 139 verify(host, x509); 140 return true; 141 } 142 catch(SSLException e) { 143 return false; 144 } 145 } 146 147 public final void verify(String host, X509Certificate cert) 148 throws SSLException { 149 String[] cns = getCNs(cert); 150 String[] subjectAlts = getDNSSubjectAlts(cert); 151 verify(host, cns, subjectAlts); 152 } 153 154 public final void verify(final String host, final String[] cns, 155 final String[] subjectAlts, 156 final boolean strictWithSubDomains) 157 throws SSLException { 158 159 // Build the list of names we're going to check. Our DEFAULT and 160 // STRICT implementations of the HostnameVerifier only use the 161 // first CN provided. All other CNs are ignored. 162 // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way). 163 LinkedList<String> names = new LinkedList<String>(); 164 if(cns != null && cns.length > 0 && cns[0] != null) { 165 names.add(cns[0]); 166 } 167 if(subjectAlts != null) { 168 for (String subjectAlt : subjectAlts) { 169 if (subjectAlt != null) { 170 names.add(subjectAlt); 171 } 172 } 173 } 174 175 if(names.isEmpty()) { 176 String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt"; 177 throw new SSLException(msg); 178 } 179 180 // StringBuffer for building the error message. 181 StringBuffer buf = new StringBuffer(); 182 183 // We're can be case-insensitive when comparing the host we used to 184 // establish the socket to the hostname in the certificate. 185 String hostName = host.trim().toLowerCase(Locale.ENGLISH); 186 boolean match = false; 187 for(Iterator<String> it = names.iterator(); it.hasNext();) { 188 // Don't trim the CN, though! 189 String cn = it.next(); 190 cn = cn.toLowerCase(Locale.ENGLISH); 191 // Store CN in StringBuffer in case we need to report an error. 192 buf.append(" <"); 193 buf.append(cn); 194 buf.append('>'); 195 if(it.hasNext()) { 196 buf.append(" OR"); 197 } 198 199 // The CN better have at least two dots if it wants wildcard 200 // action. It also can't be [*.co.uk] or [*.co.jp] or 201 // [*.org.uk], etc... 202 boolean doWildcard = cn.startsWith("*.") && 203 cn.lastIndexOf('.') >= 0 && 204 acceptableCountryWildcard(cn) && 205 !InetAddressUtils.isIPv4Address(host); 206 207 if(doWildcard) { 208 match = hostName.endsWith(cn.substring(1)); 209 if(match && strictWithSubDomains) { 210 // If we're in strict mode, then [*.foo.com] is not 211 // allowed to match [a.b.foo.com] 212 match = countDots(hostName) == countDots(cn); 213 } 214 } else { 215 match = hostName.equals(cn); 216 } 217 if(match) { 218 break; 219 } 220 } 221 if(!match) { 222 throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf); 223 } 224 } 225 226 public static boolean acceptableCountryWildcard(String cn) { 227 int cnLen = cn.length(); 228 if(cnLen >= 7 && cnLen <= 9) { 229 // Look for the '.' in the 3rd-last position: 230 if(cn.charAt(cnLen - 3) == '.') { 231 // Trim off the [*.] and the [.XX]. 232 String s = cn.substring(2, cnLen - 3); 233 // And test against the sorted array of bad 2lds: 234 int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s); 235 return x < 0; 236 } 237 } 238 return true; 239 } 240 241 public static String[] getCNs(X509Certificate cert) { 242 LinkedList<String> cnList = new LinkedList<String>(); 243 /* 244 Sebastian Hauer's original StrictSSLProtocolSocketFactory used 245 getName() and had the following comment: 246 247 Parses a X.500 distinguished name for the value of the 248 "Common Name" field. This is done a bit sloppy right 249 now and should probably be done a bit more according to 250 <code>RFC 2253</code>. 251 252 I've noticed that toString() seems to do a better job than 253 getName() on these X500Principal objects, so I'm hoping that 254 addresses Sebastian's concern. 255 256 For example, getName() gives me this: 257 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d 258 259 whereas toString() gives me this: 260 EMAILADDRESS=juliusdavies (at) cucbc.com 261 262 Looks like toString() even works with non-ascii domain names! 263 I tested it with "花子.co.jp" and it worked fine. 264 */ 265 String subjectPrincipal = cert.getSubjectX500Principal().toString(); 266 StringTokenizer st = new StringTokenizer(subjectPrincipal, ","); 267 while(st.hasMoreTokens()) { 268 String tok = st.nextToken(); 269 int x = tok.indexOf("CN="); 270 if(x >= 0) { 271 cnList.add(tok.substring(x + 3)); 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 /** 285 * Extracts the array of SubjectAlt DNS names from an X509Certificate. 286 * Returns null if there aren't any. 287 * <p/> 288 * Note: Java doesn't appear able to extract international characters 289 * from the SubjectAlts. It can only extract international characters 290 * from the CN field. 291 * <p/> 292 * (Or maybe the version of OpenSSL I'm using to test isn't storing the 293 * international characters correctly in the SubjectAlts?). 294 * 295 * @param cert X509Certificate 296 * @return Array of SubjectALT DNS names stored in the certificate. 297 */ 298 public static String[] getDNSSubjectAlts(X509Certificate cert) { 299 LinkedList<String> subjectAltList = new LinkedList<String>(); 300 Collection<List<?>> c = null; 301 try { 302 c = cert.getSubjectAlternativeNames(); 303 } 304 catch(CertificateParsingException cpe) { 305 Logger.getLogger(AbstractVerifier.class.getName()) 306 .log(Level.FINE, "Error parsing certificate.", cpe); 307 } 308 if(c != null) { 309 for (List<?> aC : c) { 310 List<?> list = aC; 311 int type = ((Integer) list.get(0)).intValue(); 312 // If type is 2, then we've got a dNSName 313 if (type == 2) { 314 String s = (String) list.get(1); 315 subjectAltList.add(s); 316 } 317 } 318 } 319 if(!subjectAltList.isEmpty()) { 320 String[] subjectAlts = new String[subjectAltList.size()]; 321 subjectAltList.toArray(subjectAlts); 322 return subjectAlts; 323 } else { 324 return null; 325 } 326 } 327 328 /** 329 * Counts the number of dots "." in a string. 330 * @param s string to count dots from 331 * @return number of dots 332 */ 333 public static int countDots(final String s) { 334 int count = 0; 335 for(int i = 0; i < s.length(); i++) { 336 if(s.charAt(i) == '.') { 337 count++; 338 } 339 } 340 return count; 341 } 342 343 } 344