KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > httpclient > contrib > ssl > AuthSSLProtocolSocketFactory


1 /*
2  * $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/contrib/org/apache/commons/httpclient/contrib/ssl/AuthSSLProtocolSocketFactory.java,v 1.2 2004/06/10 18:25:24 olegk Exp $
3  * $Revision$
4  * $Date$
5  *
6  * ====================================================================
7  *
8  * Copyright 2002-2004 The Apache Software Foundation
9  *
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  *
14  * http://www.apache.org/licenses/LICENSE-2.0
15  *
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ====================================================================
22  *
23  * This software consists of voluntary contributions made by many
24  * individuals on behalf of the Apache Software Foundation. For more
25  * information on the Apache Software Foundation, please see
26  * <http://www.apache.org/>.
27  *
28  */

29
30 package org.apache.commons.httpclient.contrib.ssl;
31
32 import java.io.IOException JavaDoc;
33 import java.net.InetAddress JavaDoc;
34 import java.net.InetSocketAddress JavaDoc;
35 import java.net.Socket JavaDoc;
36 import java.net.SocketAddress JavaDoc;
37 import java.net.URL JavaDoc;
38 import java.net.UnknownHostException JavaDoc;
39 import java.security.GeneralSecurityException JavaDoc;
40 import java.security.KeyStore JavaDoc;
41 import java.security.KeyStoreException JavaDoc;
42 import java.security.NoSuchAlgorithmException JavaDoc;
43 import java.security.UnrecoverableKeyException JavaDoc;
44 import java.security.cert.Certificate JavaDoc;
45 import java.security.cert.CertificateException JavaDoc;
46 import java.security.cert.X509Certificate JavaDoc;
47 import java.util.Enumeration JavaDoc;
48
49 import org.apache.commons.httpclient.ConnectTimeoutException;
50 import org.apache.commons.httpclient.params.HttpConnectionParams;
51 import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
52 import org.apache.commons.logging.Log;
53 import org.apache.commons.logging.LogFactory;
54
55 import javax.net.SocketFactory;
56 import javax.net.ssl.KeyManager;
57 import javax.net.ssl.KeyManagerFactory;
58 import javax.net.ssl.SSLContext;
59 import javax.net.ssl.TrustManager;
60 import javax.net.ssl.TrustManagerFactory;
61 import javax.net.ssl.X509TrustManager;
62
63 /**
64  * <p>
65  * AuthSSLProtocolSocketFactory can be used to validate the identity of the HTTPS
66  * server against a list of trusted certificates and to authenticate to the HTTPS
67  * server using a private key.
68  * </p>
69  *
70  * <p>
71  * AuthSSLProtocolSocketFactory will enable server authentication when supplied with
72  * a {@link KeyStore truststore} file containg one or several trusted certificates.
73  * The client secure socket will reject the connection during the SSL session handshake
74  * if the target HTTPS server attempts to authenticate itself with a non-trusted
75  * certificate.
76  * </p>
77  *
78  * <p>
79  * Use JDK keytool utility to import a trusted certificate and generate a truststore file:
80  * <pre>
81  * keytool -import -alias "my server cert" -file server.crt -keystore my.truststore
82  * </pre>
83  * </p>
84  *
85  * <p>
86  * AuthSSLProtocolSocketFactory will enable client authentication when supplied with
87  * a {@link KeyStore keystore} file containg a private key/public certificate pair.
88  * The client secure socket will use the private key to authenticate itself to the target
89  * HTTPS server during the SSL session handshake if requested to do so by the server.
90  * The target HTTPS server will in its turn verify the certificate presented by the client
91  * in order to establish client's authenticity
92  * </p>
93  *
94  * <p>
95  * Use the following sequence of actions to generate a keystore file
96  * </p>
97  * <ul>
98  * <li>
99  * <p>
100  * Use JDK keytool utility to generate a new key
101  * <pre>keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore</pre>
102  * For simplicity use the same password for the key as that of the keystore
103  * </p>
104  * </li>
105  * <li>
106  * <p>
107  * Issue a certificate signing request (CSR)
108  * <pre>keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore</pre>
109  * </p>
110  * </li>
111  * <li>
112  * <p>
113  * Send the certificate request to the trusted Certificate Authority for signature.
114  * One may choose to act as her own CA and sign the certificate request using a PKI
115  * tool, such as OpenSSL.
116  * </p>
117  * </li>
118  * <li>
119  * <p>
120  * Import the trusted CA root certificate
121  * <pre>keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore</pre>
122  * </p>
123  * </li>
124  * <li>
125  * <p>
126  * Import the PKCS#7 file containg the complete certificate chain
127  * <pre>keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore</pre>
128  * </p>
129  * </li>
130  * <li>
131  * <p>
132  * Verify the content the resultant keystore file
133  * <pre>keytool -list -v -keystore my.keystore</pre>
134  * </p>
135  * </li>
136  * </ul>
137  * <p>
138  * Example of using custom protocol socket factory for a specific host:
139  * <pre>
140  * Protocol authhttps = new Protocol("https",
141  * new AuthSSLProtocolSocketFactory(
142  * new URL("file:my.keystore"), "mypassword",
143  * new URL("file:my.truststore"), "mypassword"), 443);
144  *
145  * HttpClient client = new HttpClient();
146  * client.getHostConfiguration().setHost("localhost", 443, authhttps);
147  * // use relative url only
148  * GetMethod httpget = new GetMethod("/");
149  * client.executeMethod(httpget);
150  * </pre>
151  * </p>
152  * <p>
153  * Example of using custom protocol socket factory per default instead of the standard one:
154  * <pre>
155  * Protocol authhttps = new Protocol("https",
156  * new AuthSSLProtocolSocketFactory(
157  * new URL("file:my.keystore"), "mypassword",
158  * new URL("file:my.truststore"), "mypassword"), 443);
159  * Protocol.registerProtocol("https", authhttps);
160  *
161  * HttpClient client = new HttpClient();
162  * GetMethod httpget = new GetMethod("https://localhost/");
163  * client.executeMethod(httpget);
164  * </pre>
165  * </p>
166  * @author <a HREF="mailto:oleg -at- ural.ru">Oleg Kalnichevski</a>
167  *
168  * <p>
169  * DISCLAIMER: HttpClient developers DO NOT actively support this component.
170  * The component is provided as a reference material, which may be inappropriate
171  * for use without additional customization.
172  * </p>
173  */

174
175 public class AuthSSLProtocolSocketFactory implements SecureProtocolSocketFactory {
176
177     /** Log object for this class. */
178     private static final Log LOG = LogFactory.getLog(AuthSSLProtocolSocketFactory.class);
179
180     private URL JavaDoc keystoreUrl = null;
181     private String JavaDoc keystorePassword = null;
182     private URL JavaDoc truststoreUrl = null;
183     private String JavaDoc truststorePassword = null;
184     private SSLContext sslcontext = null;
185
186     /**
187      * Constructor for AuthSSLProtocolSocketFactory. Either a keystore or truststore file
188      * must be given. Otherwise SSL context initialization error will result.
189      *
190      * @param keystoreUrl URL of the keystore file. May be <tt>null</tt> if HTTPS client
191      * authentication is not to be used.
192      * @param keystorePassword Password to unlock the keystore. IMPORTANT: this implementation
193      * assumes that the same password is used to protect the key and the keystore itself.
194      * @param truststoreUrl URL of the truststore file. May be <tt>null</tt> if HTTPS server
195      * authentication is not to be used.
196      * @param truststorePassword Password to unlock the truststore.
197      */

198     public AuthSSLProtocolSocketFactory(
199         final URL JavaDoc keystoreUrl, final String JavaDoc keystorePassword,
200         final URL JavaDoc truststoreUrl, final String JavaDoc truststorePassword)
201     {
202         super();
203         this.keystoreUrl = keystoreUrl;
204         this.keystorePassword = keystorePassword;
205         this.truststoreUrl = truststoreUrl;
206         this.truststorePassword = truststorePassword;
207     }
208
209     private static KeyStore JavaDoc createKeyStore(final URL JavaDoc url, final String JavaDoc password)
210         throws KeyStoreException JavaDoc, NoSuchAlgorithmException JavaDoc, CertificateException JavaDoc, IOException JavaDoc
211     {
212         if (url == null) {
213             throw new IllegalArgumentException JavaDoc("Keystore url may not be null");
214         }
215         LOG.debug("Initializing key store");
216         KeyStore JavaDoc keystore = KeyStore.getInstance("jks");
217         keystore.load(url.openStream(), password != null ? password.toCharArray(): null);
218         return keystore;
219     }
220     
221     private static KeyManager[] createKeyManagers(final KeyStore JavaDoc keystore, final String JavaDoc password)
222         throws KeyStoreException JavaDoc, NoSuchAlgorithmException JavaDoc, UnrecoverableKeyException JavaDoc
223     {
224         if (keystore == null) {
225             throw new IllegalArgumentException JavaDoc("Keystore may not be null");
226         }
227         LOG.debug("Initializing key manager");
228         KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
229             KeyManagerFactory.getDefaultAlgorithm());
230         kmfactory.init(keystore, password != null ? password.toCharArray(): null);
231         return kmfactory.getKeyManagers();
232     }
233
234     private static TrustManager[] createTrustManagers(final KeyStore JavaDoc keystore)
235         throws KeyStoreException JavaDoc, NoSuchAlgorithmException JavaDoc
236     {
237         if (keystore == null) {
238             throw new IllegalArgumentException JavaDoc("Keystore may not be null");
239         }
240         LOG.debug("Initializing trust manager");
241         TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
242             TrustManagerFactory.getDefaultAlgorithm());
243         tmfactory.init(keystore);
244         TrustManager[] trustmanagers = tmfactory.getTrustManagers();
245         for (int i = 0; i < trustmanagers.length; i++) {
246             if (trustmanagers[i] instanceof X509TrustManager) {
247                 trustmanagers[i] = new AuthSSLX509TrustManager(
248                     (X509TrustManager)trustmanagers[i]);
249             }
250         }
251         return trustmanagers;
252     }
253
254     private SSLContext createSSLContext() {
255         try {
256             KeyManager[] keymanagers = null;
257             TrustManager[] trustmanagers = null;
258             if (this.keystoreUrl != null) {
259                 KeyStore JavaDoc keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
260                 if (LOG.isDebugEnabled()) {
261                     Enumeration JavaDoc aliases = keystore.aliases();
262                     while (aliases.hasMoreElements()) {
263                         String JavaDoc alias = (String JavaDoc)aliases.nextElement();
264                         Certificate JavaDoc[] certs = keystore.getCertificateChain(alias);
265                         if (certs != null) {
266                             LOG.debug("Certificate chain '" + alias + "':");
267                             for (int c = 0; c < certs.length; c++) {
268                                 if (certs[c] instanceof X509Certificate JavaDoc) {
269                                     X509Certificate JavaDoc cert = (X509Certificate JavaDoc)certs[c];
270                                     LOG.debug(" Certificate " + (c + 1) + ":");
271                                     LOG.debug(" Subject DN: " + cert.getSubjectDN());
272                                     LOG.debug(" Signature Algorithm: " + cert.getSigAlgName());
273                                     LOG.debug(" Valid from: " + cert.getNotBefore() );
274                                     LOG.debug(" Valid until: " + cert.getNotAfter());
275                                     LOG.debug(" Issuer: " + cert.getIssuerDN());
276                                 }
277                             }
278                         }
279                     }
280                 }
281                 keymanagers = createKeyManagers(keystore, this.keystorePassword);
282             }
283             if (this.truststoreUrl != null) {
284                 KeyStore JavaDoc keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
285                 if (LOG.isDebugEnabled()) {
286                     Enumeration JavaDoc aliases = keystore.aliases();
287                     while (aliases.hasMoreElements()) {
288                         String JavaDoc alias = (String JavaDoc)aliases.nextElement();
289                         LOG.debug("Trusted certificate '" + alias + "':");
290                         Certificate JavaDoc trustedcert = keystore.getCertificate(alias);
291                         if (trustedcert != null && trustedcert instanceof X509Certificate JavaDoc) {
292                             X509Certificate JavaDoc cert = (X509Certificate JavaDoc)trustedcert;
293                             LOG.debug(" Subject DN: " + cert.getSubjectDN());
294                             LOG.debug(" Signature Algorithm: " + cert.getSigAlgName());
295                             LOG.debug(" Valid from: " + cert.getNotBefore() );
296                             LOG.debug(" Valid until: " + cert.getNotAfter());
297                             LOG.debug(" Issuer: " + cert.getIssuerDN());
298                         }
299                     }
300                 }
301                 trustmanagers = createTrustManagers(keystore);
302             }
303             SSLContext sslcontext = SSLContext.getInstance("SSL");
304             sslcontext.init(keymanagers, trustmanagers, null);
305             return sslcontext;
306         } catch (NoSuchAlgorithmException JavaDoc e) {
307             LOG.error(e.getMessage(), e);
308             throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
309         } catch (KeyStoreException JavaDoc e) {
310             LOG.error(e.getMessage(), e);
311             throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
312         } catch (GeneralSecurityException JavaDoc e) {
313             LOG.error(e.getMessage(), e);
314             throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
315         } catch (IOException JavaDoc e) {
316             LOG.error(e.getMessage(), e);
317             throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
318         }
319     }
320
321     private SSLContext getSSLContext() {
322         if (this.sslcontext == null) {
323             this.sslcontext = createSSLContext();
324         }
325         return this.sslcontext;
326     }
327
328     /**
329      * Attempts to get a new socket connection to the given host within the given time limit.
330      * <p>
331      * To circumvent the limitations of older JREs that do not support connect timeout a
332      * controller thread is executed. The controller thread attempts to create a new socket
333      * within the given limit of time. If socket constructor does not return until the
334      * timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
335      * </p>
336      *
337      * @param host the host name/IP
338      * @param port the port on the host
339      * @param clientHost the local host name/IP to bind the socket to
340      * @param clientPort the port on the local machine
341      * @param params {@link HttpConnectionParams Http connection parameters}
342      *
343      * @return Socket a new socket
344      *
345      * @throws IOException if an I/O error occurs while creating the socket
346      * @throws UnknownHostException if the IP address of the host cannot be
347      * determined
348      */

349     public Socket JavaDoc createSocket(
350         final String JavaDoc host,
351         final int port,
352         final InetAddress JavaDoc localAddress,
353         final int localPort,
354         final HttpConnectionParams params
355     ) throws IOException JavaDoc, UnknownHostException JavaDoc, ConnectTimeoutException {
356         if (params == null) {
357             throw new IllegalArgumentException JavaDoc("Parameters may not be null");
358         }
359         int timeout = params.getConnectionTimeout();
360         SocketFactory socketfactory = getSSLContext().getSocketFactory();
361         if (timeout == 0) {
362             return socketfactory.createSocket(host, port, localAddress, localPort);
363         } else {
364             Socket JavaDoc socket = socketfactory.createSocket();
365             SocketAddress JavaDoc localaddr = new InetSocketAddress JavaDoc(localAddress, localPort);
366             SocketAddress JavaDoc remoteaddr = new InetSocketAddress JavaDoc(host, port);
367             socket.bind(localaddr);
368             socket.connect(remoteaddr, timeout);
369             return socket;
370         }
371     }
372
373     /**
374      * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int)
375      */

376     public Socket JavaDoc createSocket(
377         String JavaDoc host,
378         int port,
379         InetAddress JavaDoc clientHost,
380         int clientPort)
381         throws IOException JavaDoc, UnknownHostException JavaDoc
382    {
383        return getSSLContext().getSocketFactory().createSocket(
384             host,
385             port,
386             clientHost,
387             clientPort
388         );
389     }
390
391     /**
392      * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
393      */

394     public Socket JavaDoc createSocket(String JavaDoc host, int port)
395         throws IOException JavaDoc, UnknownHostException JavaDoc
396     {
397         return getSSLContext().getSocketFactory().createSocket(
398             host,
399             port
400         );
401     }
402
403     /**
404      * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
405      */

406     public Socket JavaDoc createSocket(
407         Socket JavaDoc socket,
408         String JavaDoc host,
409         int port,
410         boolean autoClose)
411         throws IOException JavaDoc, UnknownHostException JavaDoc
412     {
413         return getSSLContext().getSocketFactory().createSocket(
414             socket,
415             host,
416             port,
417             autoClose
418         );
419     }
420 }
Popular Tags