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

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