KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > management > agents > IBMSslAdapterServerSocketFactory


1 /*
2  * $Id: IBMSslAdapterServerSocketFactory.java 3937 2006-11-20 16:04:25Z lajos $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.management.agents;
12
13 import java.io.File JavaDoc;
14 import java.io.FileInputStream JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.io.InputStream JavaDoc;
17 import java.net.InetAddress JavaDoc;
18 import java.net.ServerSocket JavaDoc;
19 import java.security.KeyStore JavaDoc;
20 import java.security.Security JavaDoc;
21 import java.security.UnrecoverableKeyException JavaDoc;
22
23 import javax.net.ssl.KeyManagerFactory;
24 import javax.net.ssl.SSLContext;
25 import javax.net.ssl.SSLServerSocket;
26 import javax.net.ssl.SSLServerSocketFactory;
27 import javax.net.ssl.TrustManagerFactory;
28
29 import mx4j.log.Log;
30 import mx4j.log.Logger;
31 import mx4j.tools.adaptor.ssl.SSLAdaptorServerSocketFactoryMBean;
32
33 import org.mule.umo.security.provider.AutoDiscoverySecurityProviderFactory;
34 import org.mule.umo.security.provider.SecurityProviderFactory;
35 import org.mule.umo.security.provider.SecurityProviderInfo;
36 import org.mule.util.IOUtils;
37 import org.mule.util.FileUtils;
38
39 /**
40  * This MBean creates SSLServerSocket instances.
41  * <p>
42  * It can be configured to use a specific keystore and SSL protocol version to create
43  * SSLServerSockets that will use the keystore information to encrypt data. <br>
44  * <p/> A keystore can be created with this command:
45  *
46  * <pre>
47  * keytool -genkey -v -keystore store.key -storepass storepwd -keypass keypwd -dname &quot;CN=Simone Bordet, OU=Project Administrator, O=MX4J, L=Torino, S=TO, C=IT&quot; -validity 365
48  * </pre>
49  *
50  * or with this minimal command (that will prompt you for further information):
51  *
52  * <pre>
53  * keytool -genkey -keystore store.key
54  * </pre>
55  *
56  * <p/> A keystore may contains more than one entry, but only the first entry will be
57  * used for encryption, no matter which is the alias for that entry. <p/> Following
58  * the first example of generation of the keystore, this MBean must be instantiated
59  * and then setup by invoking the following methods:
60  * <ul>
61  * <li> {@link #setKeyStoreName}("store.key");
62  * <li> {@link #setKeyStorePassword}("storepwd");
63  * <li> {@link #setKeyManagerPassword}("keypwd");
64  * </ul>
65  * before {@link #createServerSocket} is called.
66  *
67  * @version $Revision: 3937 $
68  */

69 public class IBMSslAdapterServerSocketFactory implements SSLAdaptorServerSocketFactoryMBean
70 {
71
72     // it will always be IBM, anyway
73
private SecurityProviderFactory spFactory = new AutoDiscoverySecurityProviderFactory();
74     private SecurityProviderInfo spInfo = spFactory.getSecurityProviderInfo();
75
76     private String JavaDoc m_keyStoreType = "JKS";
77     private String JavaDoc m_trustStoreType = "JKS";
78     private String JavaDoc m_keyStoreName;
79     private String JavaDoc m_trustStoreName;
80     private String JavaDoc m_keyStorePassword;
81     private String JavaDoc m_trustStorePassword;
82     private String JavaDoc m_keyManagerAlgorithm = spInfo.getKeyManagerAlgorithm();
83     // the same?
84
private String JavaDoc m_trustManagerAlgorithm = spInfo.getKeyManagerAlgorithm();
85     private String JavaDoc m_keyManagerPassword;
86     // IMPORTANT Sun-specific version works with TLS protocol,
87
// but fails in Internet Explorer and IBM-specific provider.
88
// SSL works fine though
89
private String JavaDoc m_sslProtocol = "SSL";
90
91     public IBMSslAdapterServerSocketFactory()
92     {
93         Security.addProvider(spFactory.getProvider());
94     }
95
96     public void setKeyStoreType(String JavaDoc keyStoreType)
97     {
98         if (keyStoreType == null || keyStoreType.trim().length() == 0)
99         {
100             throw new IllegalArgumentException JavaDoc("Invalid KeyStore type");
101         }
102         m_keyStoreType = keyStoreType;
103     }
104
105     public void setTrustStoreType(String JavaDoc trustStoreType)
106     {
107         if (trustStoreType == null || trustStoreType.trim().length() == 0)
108         {
109             throw new IllegalArgumentException JavaDoc("Invalid TrustStore type");
110         }
111         m_trustStoreType = trustStoreType;
112     }
113
114     public void setKeyStoreName(String JavaDoc name)
115     {
116         if (name == null || name.trim().length() == 0)
117         {
118             throw new IllegalArgumentException JavaDoc("Invalid KeyStore name");
119         }
120         m_keyStoreName = name;
121     }
122
123     public void setTrustStoreName(String JavaDoc name)
124     {
125         if (name == null || name.trim().length() == 0)
126         {
127             throw new IllegalArgumentException JavaDoc("Invalid TrustStore name");
128         }
129         m_trustStoreName = name;
130     }
131
132     public void setKeyStorePassword(String JavaDoc password)
133     {
134         if (password == null || password.trim().length() == 0)
135         {
136             throw new IllegalArgumentException JavaDoc("Invalid KeyStore password");
137         }
138         m_keyStorePassword = password;
139     }
140
141     public void setTrustStorePassword(String JavaDoc password)
142     {
143         if (password == null || password.trim().length() == 0)
144         {
145             throw new IllegalArgumentException JavaDoc("Invalid TrustStore password");
146         }
147         m_trustStorePassword = password;
148     }
149
150     public void setKeyManagerAlgorithm(String JavaDoc algorithm)
151     {
152         if (algorithm == null || algorithm.trim().length() == 0)
153         {
154             throw new IllegalArgumentException JavaDoc("Invalid KeyManager algorithm");
155         }
156         m_keyManagerAlgorithm = algorithm;
157     }
158
159     public void setTrustManagerAlgorithm(String JavaDoc algorithm)
160     {
161         if (algorithm == null || algorithm.trim().length() == 0)
162         {
163             throw new IllegalArgumentException JavaDoc("Invalid TrustManager algorithm");
164         }
165         m_trustManagerAlgorithm = algorithm;
166     }
167
168     public void setKeyManagerPassword(String JavaDoc password)
169     {
170         if (password == null || password.trim().length() == 0)
171         {
172             throw new IllegalArgumentException JavaDoc("Invalid KeyManager password");
173         }
174         m_keyManagerPassword = password;
175     }
176
177     public void setSSLProtocol(String JavaDoc protocol)
178     {
179         if (protocol == null || protocol.trim().length() == 0)
180         {
181             throw new IllegalArgumentException JavaDoc("Invalid SSL protocol");
182         }
183         m_sslProtocol = protocol;
184     }
185
186     /**
187      * Returns a SSLServerSocket on the given port.
188      */

189     public ServerSocket JavaDoc createServerSocket(int port, int backlog, String JavaDoc host) throws IOException JavaDoc
190     {
191         if (m_keyStoreName == null)
192         {
193             throw new IOException JavaDoc("KeyStore file name cannot be null");
194         }
195         if (m_keyStorePassword == null)
196         {
197             throw new IOException JavaDoc("KeyStore password cannot be null");
198         }
199
200         Logger logger = getLogger();
201         if (logger.isEnabledFor(Logger.TRACE))
202         {
203             logger.trace("Creating SSLServerSocket");
204             logger.trace("\tKeyStore " + m_keyStoreName + ", type " + m_keyStoreType);
205             logger.trace("\tKeyManager algorithm is " + m_keyManagerAlgorithm);
206             logger.trace("\tTrustStore " + m_trustStoreName + ", type " + m_trustStoreType);
207             logger.trace("\tTrustManager algorithm is " + m_trustManagerAlgorithm);
208             logger.trace("\tSSL protocol version is " + m_sslProtocol);
209         }
210
211         try
212         {
213             KeyStore JavaDoc keystore = KeyStore.getInstance(m_keyStoreType);
214             InputStream JavaDoc keyStoreStream = IOUtils.getResourceAsStream(m_keyStoreName, getClass());
215             // Must check for nullity, otherwise a new empty keystore is created by
216
// KeyStore.load
217
if (keyStoreStream == null)
218             {
219                 // Let's look at the file system, maybe that the name provided is in
220
// fact a file path
221
File JavaDoc fle = FileUtils.newFile(m_keyStoreName);
222                 if (fle.exists()) keyStoreStream = new FileInputStream JavaDoc(fle);
223             }
224             if (keyStoreStream == null) throw new IOException JavaDoc("Cannot find KeyStore " + m_keyStoreName);
225             keystore.load(keyStoreStream, m_keyStorePassword.toCharArray());
226             try
227             {
228                 keyStoreStream.close();
229             }
230             catch (IOException JavaDoc x)
231             {
232                 // ignore
233
}
234
235             KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(m_keyManagerAlgorithm);
236             // Use the keystore password as default if not given
237
keyFactory.init(keystore, m_keyManagerPassword == null
238                             ? m_keyStorePassword.toCharArray() : m_keyManagerPassword.toCharArray());
239
240             TrustManagerFactory trustFactory = null;
241             if (m_trustStoreName != null)
242             {
243                 // User specified a trust store, retrieve it
244

245                 if (m_trustStorePassword == null)
246                 {
247                     throw new IOException JavaDoc("TrustStore password cannot be null");
248                 }
249
250                 KeyStore JavaDoc trustStore = KeyStore.getInstance(m_trustStoreType);
251                 InputStream JavaDoc trustStoreStream = IOUtils.getResourceAsStream(m_trustStoreName, getClass());
252                 // Check for nullity
253
if (trustStoreStream == null)
254                 {
255                     throw new IOException JavaDoc("Cannot find TrustStore " + m_trustStoreName);
256                 }
257                 trustStore.load(trustStoreStream, m_trustStorePassword.toCharArray());
258
259                 trustFactory = TrustManagerFactory.getInstance(m_trustManagerAlgorithm);
260                 trustFactory.init(trustStore);
261             }
262
263             SSLContext context = SSLContext.getInstance(m_sslProtocol);
264             // Below call does not handle TrustManagers, needed when server must
265
// authenticate clients.
266
context.init(keyFactory.getKeyManagers(), trustFactory == null
267                             ? null : trustFactory.getTrustManagers(), null);
268
269             SSLServerSocketFactory ssf = context.getServerSocketFactory();
270             SSLServerSocket serverSocket = (SSLServerSocket)ssf.createServerSocket(port, backlog,
271                 InetAddress.getByName(host));
272
273             return serverSocket;
274         }
275         catch (IOException JavaDoc x)
276         {
277             logger.error("", x);
278             throw x;
279         }
280         catch (UnrecoverableKeyException JavaDoc x)
281         {
282             // Wrong password for the key
283
logger.error("Probably a bad key password", x);
284             throw new IOException JavaDoc("Probably a bad key password: " + x.toString());
285         }
286         catch (Exception JavaDoc x)
287         {
288             logger.error("Unexpected exception", x);
289             throw new IOException JavaDoc(x.toString());
290         }
291     }
292
293     private Logger getLogger()
294     {
295         return Log.getLogger(getClass().getName());
296     }
297 }
298
Popular Tags