Coverage Report - org.mule.api.security.tls.TlsConfiguration
 
Classes in this File Line Coverage Branch Coverage Complexity
TlsConfiguration
0%
0/159
0%
0/38
1.571
 
 1  
 /*
 2  
  * $Id: TlsConfiguration.java 19191 2010-08-25 21:05:23Z tcarlson $
 3  
  * --------------------------------------------------------------------------------------
 4  
  * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
 5  
  *
 6  
  * The software in this package is published under the terms of the CPAL v1.0
 7  
  * license, a copy of which has been included with this distribution in the
 8  
  * LICENSE.txt file.
 9  
  */
 10  
 
 11  
 package org.mule.api.security.tls;
 12  
 
 13  
 import org.mule.api.lifecycle.CreateException;
 14  
 import org.mule.api.security.TlsDirectKeyStore;
 15  
 import org.mule.api.security.TlsDirectTrustStore;
 16  
 import org.mule.api.security.TlsIndirectKeyStore;
 17  
 import org.mule.api.security.TlsProtocolHandler;
 18  
 import org.mule.api.security.provider.AutoDiscoverySecurityProviderFactory;
 19  
 import org.mule.api.security.provider.SecurityProviderFactory;
 20  
 import org.mule.api.security.provider.SecurityProviderInfo;
 21  
 import org.mule.config.i18n.CoreMessages;
 22  
 import org.mule.util.FileUtils;
 23  
 import org.mule.util.IOUtils;
 24  
 
 25  
 import java.io.FileNotFoundException;
 26  
 import java.io.IOException;
 27  
 import java.io.InputStream;
 28  
 import java.security.KeyManagementException;
 29  
 import java.security.KeyStore;
 30  
 import java.security.NoSuchAlgorithmException;
 31  
 import java.security.Provider;
 32  
 import java.security.Security;
 33  
 
 34  
 import javax.net.ssl.KeyManager;
 35  
 import javax.net.ssl.KeyManagerFactory;
 36  
 import javax.net.ssl.SSLContext;
 37  
 import javax.net.ssl.SSLServerSocketFactory;
 38  
 import javax.net.ssl.SSLSocketFactory;
 39  
 import javax.net.ssl.TrustManager;
 40  
 import javax.net.ssl.TrustManagerFactory;
 41  
 
 42  
 import org.apache.commons.logging.Log;
 43  
 import org.apache.commons.logging.LogFactory;
 44  
 
 45  
 /**
 46  
  * Support for configuring TLS/SSL connections.
 47  
  * <p/>
 48  
  * <h2>Introduction</h2>
 49  
  * <p/>
 50  
  * This class was introduced to centralise the work of TLS/SSL configuration.  It is intended
 51  
  * to be backwards compatible with earlier code (as much as possible) and so is perhaps more
 52  
  * complex than would be necessary if starting from zero - the main source of confusion is the
 53  
  * distinction between direct and indirect creation of sockets and stores.
 54  
  * <p/>
 55  
  * <h2>Configuration</h2>
 56  
  * <p/>
 57  
  * The documentation in this class is intended more for programmers than end uses.  If you are
 58  
  * configuring a connector the interfaces {@link org.mule.api.security.TlsIndirectTrustStore},
 59  
  * {@link TlsDirectTrustStore},
 60  
  * {@link TlsDirectKeyStore} and {@link TlsIndirectKeyStore} should provide guidance to individual
 61  
  * properties.  In addition you should check the documentation for the specific protocol / connector
 62  
  * used and may also need to read the discussion on direct and indirect socket and store creation
 63  
  * below (or, more simply, just use whichever key store interface your connector implements!).
 64  
  * <p/>
 65  
  * <h2>Programming</h2>
 66  
  * <p/>
 67  
  * This class is intended to be used as a delegate as we typically want to add security to an
 68  
  * already existing connector (so we inherit from that connector, implement the appropriate
 69  
  * interfaces from {@link org.mule.api.security.TlsIndirectTrustStore}, {@link TlsDirectTrustStore},
 70  
  * {@link TlsDirectKeyStore} and {@link TlsIndirectKeyStore}, and then forward calls to the
 71  
  * interfaces to an instance of this class).
 72  
  * <p/>
 73  
  * <p>For setting System properties (and reading them) use {@link TlsPropertiesMapper}.  This
 74  
  * can take a "namespace" which can then be used by {@link TlsPropertiesSocketFactory} to
 75  
  * construct an appropriate socket factory.  This approach (storing to properties and then
 76  
  * retrieving that information later in a socket factory) lets us pass TLS/SSL configuration
 77  
  * into libraries that are configured by specifying on the socket factory class.</p>
 78  
  * <p/>
 79  
  * <h2>Direct and Indirect Socket and Store Creation</h2>
 80  
  * <p/>
 81  
  * For the SSL transport, which historically defined parameters for many different secure
 82  
  * transports, the configuration interfaces worked as follows:
 83  
  * <p/>
 84  
  * <dl>
 85  
  * <dt>{@link TlsDirectTrustStore}</dt><dd>Used to generate trust store directly and indirectly
 86  
  * for all TLS/SSL conections via System properties</dd>
 87  
  * <dt>{@link TlsDirectKeyStore}</dt><dd>Used to generate key store directly</dd>
 88  
  * <dt>{@link TlsIndirectKeyStore}</dt><dd>Used to generate key store indirectly for all
 89  
  * TLS/SSL conections via System properties</dd>
 90  
  * </dl>
 91  
  * <p/>
 92  
  * Historically, many other transports relied on the indirect configurations defined above.
 93  
  * So they implemented {@link org.mule.api.security.TlsIndirectTrustStore}
 94  
  * (a superclass of {@link TlsDirectTrustStore})
 95  
  * and relied on {@link TlsIndirectKeyStore} from the SSL configuration.  For continuity these
 96  
  * interfaces continue to be used, even though
 97  
  * the configurations are now typically (see individual connector/protocol documentation) specific
 98  
  * to a protocol or connector.  <em>Note - these interfaces are new, but the original code had
 99  
  * those methods, used as described.  The new interfaces only make things explicit.</em>
 100  
  * <p/>
 101  
  * <p><em>Note for programmers</em> One way to understand the above is to see that many
 102  
  * protocols are handled by libraries that are configured by providing either properties or
 103  
  * a socket factory.  In both cases (the latter via {@link TlsPropertiesSocketFactory}) we
 104  
  * continue to use properties and the "indirect" interface.  Note also that the mapping
 105  
  * in {@link TlsPropertiesMapper} correctly handles the asymmetry, so an initial call to
 106  
  * {@link TlsConfiguration} uses the keystore defined via {@link TlsDirectKeyStore}, but
 107  
  * when a {@link TlsConfiguration} is retrieved from System proerties using
 108  
  * {@link TlsPropertiesMapper#readFromProperties(TlsConfiguration,java.util.Properties)}
 109  
  * the "indirect" properties are supplied as "direct" values, meaning that the "indirect"
 110  
  * socket factory can be retrieved from {@link #getKeyManagerFactory()}.  It just works.</p>
 111  
  */
 112  
 public final class TlsConfiguration
 113  
         implements TlsDirectTrustStore, TlsDirectKeyStore, TlsIndirectKeyStore, TlsProtocolHandler
 114  
 {
 115  
 
 116  
     public static final String DEFAULT_KEYSTORE = ".keystore";
 117  0
     public static final String DEFAULT_KEYSTORE_TYPE = KeyStore.getDefaultType();
 118  
     public static final String JSSE_NAMESPACE = "javax.net";
 119  
 
 120  0
     private Log logger = LogFactory.getLog(getClass());
 121  
 
 122  0
     private SecurityProviderFactory spFactory = new AutoDiscoverySecurityProviderFactory();
 123  0
     private SecurityProviderInfo spInfo = spFactory.getSecurityProviderInfo();
 124  0
     private Provider provider = spFactory.getProvider();
 125  0
     private String sslType = spInfo.getDefaultSslType();
 126  
 
 127  
     // global
 128  0
     private String protocolHandler = spInfo.getProtocolHandler();
 129  
 
 130  
     // this is the key store that is generated in-memory and available to connectors explicitly.
 131  
     // it is local to the socket.
 132  0
     private String keyStoreName = DEFAULT_KEYSTORE; // was default in https but not ssl
 133  0
     private String keyPassword = null;
 134  0
     private String keyStorePassword = null;
 135  0
     private String keystoreType = DEFAULT_KEYSTORE_TYPE;
 136  0
     private String keyManagerAlgorithm = spInfo.getKeyManagerAlgorithm();
 137  0
     private KeyManagerFactory keyManagerFactory = null;
 138  
 
 139  
     // this is the key store defined in system properties that is used implicitly.
 140  
     // note that some transports use different namespaces within system properties,
 141  
     // so this is typically global across a particular transport.
 142  
     // it is also used as the trust store defined in system properties if no other trust
 143  
     // store is given and explicitTrustStoreOnly is false
 144  0
     private String clientKeyStoreName = null;
 145  0
     private String clientKeyStorePassword = null;
 146  0
     private String clientKeyStoreType = DEFAULT_KEYSTORE_TYPE;
 147  
 
 148  
     // this is the trust store used to construct sockets both explicitly
 149  
     // and globally (if not set, see client key above) via the jvm defaults.
 150  0
     private String trustStoreName = null;
 151  0
     private String trustStorePassword = null;
 152  0
     private String trustStoreType = DEFAULT_KEYSTORE_TYPE;
 153  0
     private String trustManagerAlgorithm = spInfo.getKeyManagerAlgorithm();
 154  0
     private TrustManagerFactory trustManagerFactory = null;
 155  0
     private boolean explicitTrustStoreOnly = false;
 156  0
     private boolean requireClientAuthentication = false;
 157  
 
 158  
     /**
 159  
      * Support for TLS connections with a given initial value for the key store
 160  
      *
 161  
      * @param keyStore initial value for the key store
 162  
      */
 163  
     public TlsConfiguration(String keyStore)
 164  0
     {
 165  0
         this.keyStoreName = keyStore;
 166  0
     }
 167  
 
 168  
     // note - in what follows i'm using "raw" variables rather than accessors because
 169  
     // i think the names are clearer.  the API names for the accessors are historical
 170  
     // and not a close fit to actual use (imho).
 171  
 
 172  
     /**
 173  
      * @param anon      If the connection is anonymous then we don't care about client keys
 174  
      * @param namespace Namespace to use for global properties (for JSSE use JSSE_NAMESPACE)
 175  
      * @throws CreateException ON initialisation problems
 176  
      */
 177  
     public void initialise(boolean anon, String namespace) throws CreateException
 178  
     {
 179  0
         if (logger.isDebugEnabled())
 180  
         {
 181  0
             logger.debug("initialising: anon " + anon);
 182  
         }
 183  0
         validate(anon);
 184  
 
 185  0
         Security.addProvider(provider);
 186  0
         System.setProperty("java.protocol.handler.pkgs", protocolHandler);
 187  
 
 188  0
         if (!anon)
 189  
         {
 190  0
             initKeyManagerFactory();
 191  
         }
 192  0
         initTrustManagerFactory();
 193  
 
 194  0
         if (null != namespace)
 195  
         {
 196  0
             new TlsPropertiesMapper(namespace).writeToProperties(System.getProperties(), this);
 197  
         }
 198  0
     }
 199  
 
 200  
     private void validate(boolean anon) throws CreateException
 201  
     {
 202  0
         assertNotNull(getProvider(), "The security provider cannot be null");
 203  0
         if (!anon)
 204  
         {
 205  0
             assertNotNull(getKeyStore(), "The KeyStore location cannot be null");
 206  0
             assertNotNull(getKeyPassword(), "The Key password cannot be null");
 207  0
             assertNotNull(getKeyStorePassword(), "The KeyStore password cannot be null");
 208  0
             assertNotNull(getKeyManagerAlgorithm(), "The Key Manager Algorithm cannot be null");
 209  
         }
 210  0
     }
 211  
 
 212  
     private void initKeyManagerFactory() throws CreateException
 213  
     {
 214  0
         if (logger.isDebugEnabled())
 215  
         {
 216  0
             logger.debug("initialising key manager factory from keystore data");
 217  
         }
 218  
         KeyStore tempKeyStore;
 219  
         try
 220  
         {
 221  0
             tempKeyStore = KeyStore.getInstance(keystoreType);
 222  0
             InputStream is = IOUtils.getResourceAsStream(keyStoreName, getClass());
 223  0
             if (null == is)
 224  
             {
 225  0
                 throw new FileNotFoundException(
 226  
                     CoreMessages.cannotLoadFromClasspath("Keystore: " + keyStoreName).getMessage());
 227  
             }
 228  0
             tempKeyStore.load(is, keyStorePassword.toCharArray());
 229  
         }
 230  0
         catch (Exception e)
 231  
         {
 232  0
             throw new CreateException(
 233  
                     CoreMessages.failedToLoad("KeyStore: " + keyStoreName), e, this);
 234  0
         }
 235  
         try
 236  
         {
 237  0
             keyManagerFactory = KeyManagerFactory.getInstance(getKeyManagerAlgorithm());
 238  0
             keyManagerFactory.init(tempKeyStore, keyPassword.toCharArray());
 239  
         }
 240  0
         catch (Exception e)
 241  
         {
 242  0
             throw new CreateException(CoreMessages.failedToLoad("Key Manager"), e, this);
 243  0
         }
 244  0
     }
 245  
 
 246  
     private void initTrustManagerFactory() throws CreateException
 247  
     {
 248  0
         if (null != trustStoreName)
 249  
         {
 250  0
             trustStorePassword = null == trustStorePassword ? "" : trustStorePassword;
 251  
 
 252  
             KeyStore trustStore;
 253  
             try
 254  
             {
 255  0
                 trustStore = KeyStore.getInstance(trustStoreType);
 256  0
                 InputStream is = IOUtils.getResourceAsStream(trustStoreName, getClass());
 257  0
                 if (null == is)
 258  
                 {
 259  0
                     throw new FileNotFoundException(
 260  
                             "Failed to load truststore from classpath or local file: " + trustStoreName);
 261  
                 }
 262  0
                 trustStore.load(is, trustStorePassword.toCharArray());
 263  
             }
 264  0
             catch (Exception e)
 265  
             {
 266  0
                 throw new CreateException(
 267  
                         CoreMessages.failedToLoad("TrustStore: " + trustStoreName), e, this);
 268  0
             }
 269  
 
 270  
             try
 271  
             {
 272  0
                 trustManagerFactory = TrustManagerFactory.getInstance(trustManagerAlgorithm);
 273  0
                 trustManagerFactory.init(trustStore);
 274  
             }
 275  0
             catch (Exception e)
 276  
             {
 277  0
                 throw new CreateException(
 278  
                         CoreMessages.failedToLoad("Trust Manager (" + trustManagerAlgorithm + ")"), e, this);
 279  0
             }
 280  
         }
 281  0
     }
 282  
 
 283  
 
 284  
     private static void assertNotNull(Object value, String message)
 285  
     {
 286  0
         if (null == value)
 287  
         {
 288  0
             throw new IllegalArgumentException(message);
 289  
         }
 290  0
     }
 291  
 
 292  
     private static String defaultForNull(String value, String deflt)
 293  
     {
 294  0
         if (null == value)
 295  
         {
 296  0
             return deflt;
 297  
         }
 298  
         else
 299  
         {
 300  0
             return value;
 301  
         }
 302  
     }
 303  
 
 304  
     public SSLSocketFactory getSocketFactory() throws NoSuchAlgorithmException, KeyManagementException
 305  
     {
 306  0
         return getSslContext().getSocketFactory();
 307  
     }
 308  
 
 309  
     public SSLServerSocketFactory getServerSocketFactory()
 310  
             throws NoSuchAlgorithmException, KeyManagementException
 311  
     {
 312  0
         return getSslContext().getServerSocketFactory();
 313  
     }
 314  
 
 315  
     public SSLContext getSslContext() throws NoSuchAlgorithmException, KeyManagementException
 316  
     {
 317  0
         KeyManager[] keyManagers =
 318  
                 null == getKeyManagerFactory() ? null : getKeyManagerFactory().getKeyManagers();
 319  0
         TrustManager[] trustManagers =
 320  
                 null == getTrustManagerFactory() ? null : getTrustManagerFactory().getTrustManagers();
 321  
 
 322  0
         SSLContext context = SSLContext.getInstance(getSslType());
 323  
         // TODO - nice to have a configurable random number source set here
 324  0
         context.init(keyManagers, trustManagers, null);
 325  0
         return context;
 326  
     }
 327  
 
 328  
     public String getSslType()
 329  
     {
 330  0
         return sslType;
 331  
     }
 332  
 
 333  
     public void setSslType(String sslType)
 334  
     {
 335  0
         this.sslType = sslType;
 336  0
     }
 337  
 
 338  
     public Provider getProvider()
 339  
     {
 340  0
         return provider;
 341  
     }
 342  
 
 343  
     public void setProvider(Provider provider)
 344  
     {
 345  0
         this.provider = provider;
 346  0
     }
 347  
 
 348  
     public String getProtocolHandler()
 349  
     {
 350  0
         return protocolHandler;
 351  
     }
 352  
 
 353  
     public void setProtocolHandler(String protocolHandler)
 354  
     {
 355  0
         this.protocolHandler = protocolHandler;
 356  0
     }
 357  
 
 358  
     public SecurityProviderFactory getSecurityProviderFactory()
 359  
     {
 360  0
         return spFactory;
 361  
     }
 362  
 
 363  
     public void setSecurityProviderFactory(SecurityProviderFactory spFactory)
 364  
     {
 365  0
         this.spFactory = spFactory;
 366  0
     }
 367  
 
 368  
     // access to the explicit key store variables
 369  
 
 370  
     public String getKeyStore()
 371  
     {
 372  0
         return keyStoreName;
 373  
     }
 374  
 
 375  
     public void setKeyStore(String name) throws IOException
 376  
     {
 377  0
         keyStoreName = name;
 378  0
         if (null != keyStoreName)
 379  
         {
 380  0
             keyStoreName = FileUtils.getResourcePath(keyStoreName, getClass());
 381  0
             if (logger.isDebugEnabled())
 382  
             {
 383  0
                 logger.debug("Normalised keyStore path to: " + keyStoreName);
 384  
             }
 385  
         }
 386  0
     }
 387  
 
 388  
     public String getKeyPassword()
 389  
     {
 390  0
         return keyPassword;
 391  
     }
 392  
 
 393  
     public void setKeyPassword(String keyPassword)
 394  
     {
 395  0
         this.keyPassword = keyPassword;
 396  0
     }
 397  
 
 398  
     public String getKeyStorePassword()
 399  
     {
 400  0
         return keyStorePassword;
 401  
     }
 402  
 
 403  
     public void setKeyStorePassword(String storePassword)
 404  
     {
 405  0
         this.keyStorePassword = storePassword;
 406  0
     }
 407  
 
 408  
     public String getKeyStoreType()
 409  
     {
 410  0
         return keystoreType;
 411  
     }
 412  
 
 413  
     public void setKeyStoreType(String keystoreType)
 414  
     {
 415  0
         this.keystoreType = keystoreType;
 416  0
     }
 417  
 
 418  
     public String getKeyManagerAlgorithm()
 419  
     {
 420  0
         return keyManagerAlgorithm;
 421  
     }
 422  
 
 423  
     public void setKeyManagerAlgorithm(String keyManagerAlgorithm)
 424  
     {
 425  0
         this.keyManagerAlgorithm = keyManagerAlgorithm;
 426  0
     }
 427  
 
 428  
     public KeyManagerFactory getKeyManagerFactory()
 429  
     {
 430  0
         return keyManagerFactory;
 431  
     }
 432  
 
 433  
     // access to the implicit key store variables
 434  
 
 435  
     public String getClientKeyStore()
 436  
     {
 437  0
         return clientKeyStoreName;
 438  
     }
 439  
 
 440  
     public void setClientKeyStore(String name) throws IOException
 441  
     {
 442  0
         clientKeyStoreName = name;
 443  0
         if (null != clientKeyStoreName)
 444  
         {
 445  0
             clientKeyStoreName = FileUtils.getResourcePath(clientKeyStoreName, getClass());
 446  0
             if (logger.isDebugEnabled())
 447  
             {
 448  0
                 logger.debug("Normalised clientKeyStore path to: " + clientKeyStoreName);
 449  
             }
 450  
         }
 451  0
     }
 452  
 
 453  
     public String getClientKeyStorePassword()
 454  
     {
 455  0
         return clientKeyStorePassword;
 456  
     }
 457  
 
 458  
     public void setClientKeyStorePassword(String clientKeyStorePassword)
 459  
     {
 460  0
         this.clientKeyStorePassword = clientKeyStorePassword;
 461  0
     }
 462  
 
 463  
     public void setClientKeyStoreType(String clientKeyStoreType)
 464  
     {
 465  0
         this.clientKeyStoreType = clientKeyStoreType;
 466  0
     }
 467  
 
 468  
     public String getClientKeyStoreType()
 469  
     {
 470  0
         return clientKeyStoreType;
 471  
     }
 472  
 
 473  
     // access to trust store variables
 474  
 
 475  
     public String getTrustStore()
 476  
     {
 477  0
         return trustStoreName;
 478  
     }
 479  
 
 480  
     public void setTrustStore(String name) throws IOException
 481  
     {
 482  0
         trustStoreName = name;
 483  0
         if (null != trustStoreName)
 484  
         {
 485  0
             trustStoreName = FileUtils.getResourcePath(trustStoreName, getClass());
 486  0
             if (logger.isDebugEnabled())
 487  
             {
 488  0
                 logger.debug("Normalised trustStore path to: " + trustStoreName);
 489  
             }
 490  
         }
 491  0
     }
 492  
 
 493  
     public String getTrustStorePassword()
 494  
     {
 495  0
         return trustStorePassword;
 496  
     }
 497  
 
 498  
     public void setTrustStorePassword(String trustStorePassword)
 499  
     {
 500  0
         this.trustStorePassword = trustStorePassword;
 501  0
     }
 502  
 
 503  
     public String getTrustStoreType()
 504  
     {
 505  0
         return trustStoreType;
 506  
     }
 507  
 
 508  
     public void setTrustStoreType(String trustStoreType)
 509  
     {
 510  0
         this.trustStoreType = trustStoreType;
 511  0
     }
 512  
 
 513  
     public String getTrustManagerAlgorithm()
 514  
     {
 515  0
         return trustManagerAlgorithm;
 516  
     }
 517  
 
 518  
     public void setTrustManagerAlgorithm(String trustManagerAlgorithm)
 519  
     {
 520  0
         this.trustManagerAlgorithm = defaultForNull(trustManagerAlgorithm, spInfo.getKeyManagerAlgorithm());
 521  0
     }
 522  
 
 523  
     public TrustManagerFactory getTrustManagerFactory()
 524  
     {
 525  0
         return trustManagerFactory;
 526  
     }
 527  
 
 528  
     public void setTrustManagerFactory(TrustManagerFactory trustManagerFactory)
 529  
     {
 530  0
         this.trustManagerFactory = trustManagerFactory;
 531  0
     }
 532  
 
 533  
     public boolean isExplicitTrustStoreOnly()
 534  
     {
 535  0
         return explicitTrustStoreOnly;
 536  
     }
 537  
 
 538  
     public void setExplicitTrustStoreOnly(boolean explicitTrustStoreOnly)
 539  
     {
 540  0
         this.explicitTrustStoreOnly = explicitTrustStoreOnly;
 541  0
     }
 542  
 
 543  
     public boolean isRequireClientAuthentication()
 544  
     {
 545  0
         return requireClientAuthentication;
 546  
     }
 547  
 
 548  
     public void setRequireClientAuthentication(boolean requireClientAuthentication)
 549  
     {
 550  0
         this.requireClientAuthentication = requireClientAuthentication;
 551  0
     }
 552  
 
 553  
 }
 554  
 
 555