Blame SOURCES/jakarta-commons-httpclient-CVE-2012-5783.patch

02831b
Index: oac.hc3x/trunk/src/java/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.java
02831b
===================================================================
02831b
diff -u -N -r608014 -r1422573
02831b
--- oac.hc3x/trunk/src/java/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.java	(.../SSLProtocolSocketFactory.java)	(revision 608014)
02831b
+++ oac.hc3x/trunk/src/java/org/apache/commons/httpclient/protocol/SSLProtocolSocketFactory.java	(.../SSLProtocolSocketFactory.java)	(revision 1422573)
02831b
@@ -31,10 +31,25 @@
02831b
 package org.apache.commons.httpclient.protocol;
02831b
 
02831b
 import java.io.IOException;
02831b
+import java.io.InputStream;
02831b
 import java.net.InetAddress;
02831b
 import java.net.Socket;
02831b
 import java.net.UnknownHostException;
02831b
+import java.security.cert.Certificate;
02831b
+import java.security.cert.CertificateParsingException;
02831b
+import java.security.cert.X509Certificate;
02831b
+import java.util.Arrays;
02831b
+import java.util.Collection;
02831b
+import java.util.Iterator;
02831b
+import java.util.LinkedList;
02831b
+import java.util.List;
02831b
+import java.util.Locale;
02831b
+import java.util.StringTokenizer;
02831b
+import java.util.regex.Pattern;
02831b
 
02831b
+import javax.net.ssl.SSLException;
02831b
+import javax.net.ssl.SSLSession;
02831b
+import javax.net.ssl.SSLSocket;
02831b
 import javax.net.ssl.SSLSocketFactory;
02831b
 
02831b
 import org.apache.commons.httpclient.ConnectTimeoutException;
02831b
@@ -55,6 +70,11 @@
02831b
      */
02831b
     private static final SSLProtocolSocketFactory factory = new SSLProtocolSocketFactory();
02831b
     
02831b
+    // This is a a sorted list, if you insert new elements do it orderdered.
02831b
+    private final static String[] BAD_COUNTRY_2LDS =
02831b
+        {"ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info",
02831b
+            "lg", "ne", "net", "or", "org"};
02831b
+    
02831b
     /**
02831b
      * Gets an singleton instance of the SSLProtocolSocketFactory.
02831b
      * @return a SSLProtocolSocketFactory
02831b
@@ -79,12 +99,14 @@
02831b
         InetAddress clientHost,
02831b
         int clientPort)
02831b
         throws IOException, UnknownHostException {
02831b
-        return SSLSocketFactory.getDefault().createSocket(
02831b
+        Socket sslSocket =  SSLSocketFactory.getDefault().createSocket(
02831b
             host,
02831b
             port,
02831b
             clientHost,
02831b
             clientPort
02831b
         );
02831b
+        verifyHostName(host, (SSLSocket) sslSocket);
02831b
+        return sslSocket;
02831b
     }
02831b
 
02831b
     /**
02831b
@@ -124,16 +146,19 @@
02831b
         }
02831b
         int timeout = params.getConnectionTimeout();
02831b
         if (timeout == 0) {
02831b
-            return createSocket(host, port, localAddress, localPort);
02831b
+            Socket sslSocket =  createSocket(host, port, localAddress, localPort);
02831b
+            verifyHostName(host, (SSLSocket) sslSocket);
02831b
+            return sslSocket;
02831b
         } else {
02831b
             // To be eventually deprecated when migrated to Java 1.4 or above
02831b
-            Socket socket = ReflectionSocketFactory.createSocket(
02831b
+            Socket sslSocket = ReflectionSocketFactory.createSocket(
02831b
                 "javax.net.ssl.SSLSocketFactory", host, port, localAddress, localPort, timeout);
02831b
-            if (socket == null) {
02831b
-                socket = ControllerThreadSocketFactory.createSocket(
02831b
+            if (sslSocket == null) {
02831b
+            	sslSocket = ControllerThreadSocketFactory.createSocket(
02831b
                     this, host, port, localAddress, localPort, timeout);
02831b
             }
02831b
-            return socket;
02831b
+            verifyHostName(host, (SSLSocket) sslSocket);
02831b
+            return sslSocket;
02831b
         }
02831b
     }
02831b
 
02831b
@@ -142,10 +167,12 @@
02831b
      */
02831b
     public Socket createSocket(String host, int port)
02831b
         throws IOException, UnknownHostException {
02831b
-        return SSLSocketFactory.getDefault().createSocket(
02831b
+        Socket sslSocket = SSLSocketFactory.getDefault().createSocket(
02831b
             host,
02831b
             port
02831b
         );
02831b
+        verifyHostName(host, (SSLSocket) sslSocket);
02831b
+        return sslSocket;
02831b
     }
02831b
 
02831b
     /**
02831b
@@ -157,15 +184,273 @@
02831b
         int port,
02831b
         boolean autoClose)
02831b
         throws IOException, UnknownHostException {
02831b
-        return ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(
02831b
+        Socket sslSocket = ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(
02831b
             socket,
02831b
             host,
02831b
             port,
02831b
             autoClose
02831b
         );
02831b
+        verifyHostName(host, (SSLSocket) sslSocket);
02831b
+        return sslSocket;
02831b
     }
02831b
+    
02831b
 
02831b
+    
02831b
+    
02831b
     /**
02831b
+     * Verifies that the given hostname in certicifate is the hostname we are trying to connect to
02831b
+     * http://www.cvedetails.com/cve/CVE-2012-5783/
02831b
+     * @param host
02831b
+     * @param ssl
02831b
+     * @throws IOException
02831b
+     */
02831b
+    
02831b
+	private static void verifyHostName(String host, SSLSocket ssl)
02831b
+			throws IOException {
02831b
+		if (host == null) {
02831b
+			throw new IllegalArgumentException("host to verify was null");
02831b
+		}
02831b
+
02831b
+		SSLSession session = ssl.getSession();
02831b
+		if (session == null) {
02831b
+            // In our experience this only happens under IBM 1.4.x when
02831b
+            // spurious (unrelated) certificates show up in the server's chain.
02831b
+            // Hopefully this will unearth the real problem:
02831b
+			InputStream in = ssl.getInputStream();
02831b
+			in.available();
02831b
+            /*
02831b
+                 If you're looking at the 2 lines of code above because you're
02831b
+                 running into a problem, you probably have two options:
02831b
+
02831b
+                    #1.  Clean up the certificate chain that your server
02831b
+                         is presenting (e.g. edit "/etc/apache2/server.crt" or
02831b
+                         wherever it is your server's certificate chain is
02831b
+                         defined).
02831b
+
02831b
+                                             OR
02831b
+
02831b
+                    #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch to a
02831b
+                          non-IBM JVM.
02831b
+              */
02831b
+
02831b
+            // If ssl.getInputStream().available() didn't cause an exception,
02831b
+            // maybe at least now the session is available?
02831b
+			session = ssl.getSession();
02831b
+			if (session == null) {
02831b
+                // If it's still null, probably a startHandshake() will
02831b
+                // unearth the real problem.
02831b
+				ssl.startHandshake();
02831b
+
02831b
+                // Okay, if we still haven't managed to cause an exception,
02831b
+                // might as well go for the NPE.  Or maybe we're okay now?
02831b
+				session = ssl.getSession();
02831b
+			}
02831b
+		}
02831b
+
02831b
+		Certificate[] certs = session.getPeerCertificates();
02831b
+		verifyHostName(host.trim().toLowerCase(Locale.US),  (X509Certificate) certs[0]);
02831b
+	}
02831b
+	/**
02831b
+	 * Extract the names from the certificate and tests host matches one of them
02831b
+	 * @param host
02831b
+	 * @param cert
02831b
+	 * @throws SSLException
02831b
+	 */
02831b
+
02831b
+	private static void verifyHostName(final String host, X509Certificate cert)
02831b
+			throws SSLException {
02831b
+        // I'm okay with being case-insensitive when comparing the host we used
02831b
+        // to establish the socket to the hostname in the certificate.
02831b
+        // Don't trim the CN, though.
02831b
+        
02831b
+		String cn = getCN(cert);
02831b
+		String[] subjectAlts = getDNSSubjectAlts(cert);
02831b
+		verifyHostName(host, cn.toLowerCase(Locale.US), subjectAlts);
02831b
+
02831b
+	}
02831b
+
02831b
+	/**
02831b
+	 * Extract all alternative names from a certificate.
02831b
+	 * @param cert
02831b
+	 * @return
02831b
+	 */
02831b
+	private static String[] getDNSSubjectAlts(X509Certificate cert) {
02831b
+		LinkedList subjectAltList = new LinkedList();
02831b
+		Collection c = null;
02831b
+		try {
02831b
+			c = cert.getSubjectAlternativeNames();
02831b
+		} catch (CertificateParsingException cpe) {
02831b
+			// Should probably log.debug() this?
02831b
+			cpe.printStackTrace();
02831b
+		}
02831b
+		if (c != null) {
02831b
+			Iterator it = c.iterator();
02831b
+			while (it.hasNext()) {
02831b
+				List list = (List) it.next();
02831b
+				int type = ((Integer) list.get(0)).intValue();
02831b
+				// If type is 2, then we've got a dNSName
02831b
+				if (type == 2) {
02831b
+					String s = (String) list.get(1);
02831b
+					subjectAltList.add(s);
02831b
+				}
02831b
+			}
02831b
+		}
02831b
+		if (!subjectAltList.isEmpty()) {
02831b
+			String[] subjectAlts = new String[subjectAltList.size()];
02831b
+			subjectAltList.toArray(subjectAlts);
02831b
+			return subjectAlts;
02831b
+		} else {
02831b
+			return new String[0];
02831b
+		}
02831b
+	        
02831b
+	}
02831b
+	/**
02831b
+	 * Verifies
02831b
+	 * @param host
02831b
+	 * @param cn
02831b
+	 * @param subjectAlts
02831b
+	 * @throws SSLException
02831b
+	 */
02831b
+
02831b
+	private static void verifyHostName(final String host, String cn, String[] subjectAlts)throws SSLException{
02831b
+		StringBuffer cnTested = new StringBuffer();
02831b
+
02831b
+		for (int i = 0; i < subjectAlts.length; i++){
02831b
+			String name = subjectAlts[i];
02831b
+			if (name != null) {
02831b
+				name = name.toLowerCase();
02831b
+				if (verifyHostName(host, name)){
02831b
+					return;
02831b
+				}
02831b
+				cnTested.append("/").append(name);
02831b
+			}				
02831b
+		}
02831b
+		if (cn != null && verifyHostName(host, cn)){
02831b
+			return;
02831b
+		}
02831b
+		cnTested.append("/").append(cn);
02831b
+		throw new SSLException("hostname in certificate didn't match: <"
02831b
+					+ host + "> != <" + cnTested + ">");
02831b
+		
02831b
+	}		
02831b
+	
02831b
+	private static boolean verifyHostName(final String host, final String cn){
02831b
+		if (doWildCard(cn) && !isIPAddress(host)) {
02831b
+			return matchesWildCard(cn, host);
02831b
+		} 
02831b
+		return host.equalsIgnoreCase(cn);		
02831b
+	}
02831b
+    private static boolean doWildCard(String cn) {
02831b
+		// Contains a wildcard
02831b
+		// wildcard in the first block
02831b
+    	// not an ipaddress (ip addres must explicitily be equal)
02831b
+    	// not using 2nd level common tld : ex: not for *.co.uk
02831b
+    	String parts[] = cn.split("\\.");
02831b
+    	return parts.length >= 3 &&
02831b
+    			parts[0].endsWith("*") &&
02831b
+    			acceptableCountryWildcard(cn) &&
02831b
+    			!isIPAddress(cn);
02831b
+    }
02831b
+    
02831b
+    
02831b
+	private static final Pattern IPV4_PATTERN = 
02831b
+			Pattern.compile("^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$");
02831b
+
02831b
+	private static final Pattern IPV6_STD_PATTERN = 
02831b
+			Pattern.compile("^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$");
02831b
+
02831b
+	private static final Pattern IPV6_HEX_COMPRESSED_PATTERN = 
02831b
+			Pattern.compile("^((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)$");
02831b
+
02831b
+
02831b
+	private static boolean isIPAddress(final String hostname) {
02831b
+		return hostname != null
02831b
+				&& (
02831b
+						IPV4_PATTERN.matcher(hostname).matches()
02831b
+						|| IPV6_STD_PATTERN.matcher(hostname).matches() 
02831b
+						|| IPV6_HEX_COMPRESSED_PATTERN.matcher(hostname).matches()
02831b
+		);
02831b
+
02831b
+	}
02831b
+
02831b
+	private static boolean acceptableCountryWildcard(final String cn) {
02831b
+		// The CN better have at least two dots if it wants wildcard action,
02831b
+		// but can't be [*.co.uk] or [*.co.jp] or [*.org.uk], etc...
02831b
+		// The [*.co.uk] problem is an interesting one. Should we just
02831b
+		// hope that CA's would never foolishly allow such a
02831b
+		// certificate to happen?
02831b
+    	
02831b
+		String[] parts = cn.split("\\.");
02831b
+		// Only checks for 3 levels, with country code of 2 letters.
02831b
+		if (parts.length > 3 || parts[parts.length - 1].length() != 2) {
02831b
+			return true;
02831b
+		}
02831b
+		String countryCode = parts[parts.length - 2];
02831b
+		return Arrays.binarySearch(BAD_COUNTRY_2LDS, countryCode) < 0;
02831b
+	}
02831b
+
02831b
+	private static boolean matchesWildCard(final String cn,
02831b
+			final String hostName) {
02831b
+		String parts[] = cn.split("\\.");
02831b
+		boolean match = false;
02831b
+		String firstpart = parts[0];
02831b
+		if (firstpart.length() > 1) {
02831b
+			// server∗
02831b
+			// e.g. server
02831b
+			String prefix =  firstpart.substring(0, firstpart.length() - 1);
02831b
+			// skipwildcard part from cn
02831b
+			String suffix = cn.substring(firstpart.length()); 
02831b
+			// skip wildcard part from host
02831b
+			String hostSuffix = hostName.substring(prefix.length());			
02831b
+			match = hostName.startsWith(prefix) && hostSuffix.endsWith(suffix);
02831b
+		} else {
02831b
+			match = hostName.endsWith(cn.substring(1));
02831b
+		}
02831b
+		if (match) {
02831b
+			// I f we're in strict mode ,
02831b
+			// [ ∗.foo.com] is not allowed to match [a.b.foo.com]
02831b
+			match = countDots(hostName) == countDots(cn);
02831b
+		}
02831b
+		return match;
02831b
+	}
02831b
+
02831b
+	private static int countDots(final String data) {
02831b
+		int dots = 0;
02831b
+		for (int i = 0; i < data.length(); i++) {
02831b
+			if (data.charAt(i) == '.') {
02831b
+				dots += 1;
02831b
+			}
02831b
+		}
02831b
+		return dots;
02831b
+	}
02831b
+
02831b
+	private static String getCN(X509Certificate cert) {
02831b
+        // Note:  toString() seems to do a better job than getName()
02831b
+        //
02831b
+        // For example, getName() gives me this:
02831b
+        // 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
02831b
+        //
02831b
+        // whereas toString() gives me this:
02831b
+        // EMAILADDRESS=juliusdavies@cucbc.com        
02831b
+		String subjectPrincipal = cert.getSubjectX500Principal().toString();
02831b
+		
02831b
+		return getCN(subjectPrincipal);
02831b
+
02831b
+	}
02831b
+	private static String getCN(String subjectPrincipal) {
02831b
+		StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
02831b
+		while(st.hasMoreTokens()) {
02831b
+			String tok = st.nextToken().trim();
02831b
+			if (tok.length() > 3) {
02831b
+				if (tok.substring(0, 3).equalsIgnoreCase("CN=")) {
02831b
+					return tok.substring(3);
02831b
+				}
02831b
+			}
02831b
+		}
02831b
+		return null;
02831b
+	}
02831b
+
02831b
+    /**
02831b
      * All instances of SSLProtocolSocketFactory are the same.
02831b
      */
02831b
     public boolean equals(Object obj) {