001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied. See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 *
019 */
020 package org.apache.directory.server.ldap.handlers.ssl;
021
022
023 import java.security.KeyStore;
024 import java.security.SecureRandom;
025 import java.security.Security;
026
027 import javax.naming.NamingException;
028 import javax.net.ssl.KeyManagerFactory;
029 import javax.net.ssl.SSLContext;
030 import javax.net.ssl.TrustManager;
031
032 import org.apache.directory.shared.ldap.util.StringTools;
033 import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
034 import org.apache.mina.core.filterchain.IoFilterChainBuilder;
035 import org.apache.mina.filter.ssl.SslFilter;
036
037
038 /**
039 * Loads the certificate file for LDAPS support and creates the appropriate
040 * MINA filter chain.
041 *
042 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
043 * @version $Rev:687105 $, $Date:2008-08-19 19:40:48 +0200 (Tue, 19 Aug 2008) $
044 *
045 */
046 public class LdapsInitializer
047 {
048 public static IoFilterChainBuilder init( KeyStore ks, String certificatePassord ) throws NamingException
049 {
050 SSLContext sslCtx;
051 try
052 {
053 // Set up key manager factory to use our key store
054 String algorithm = Security.getProperty( "ssl.KeyManagerFactory.algorithm" );
055
056 if ( algorithm == null )
057 {
058 algorithm = KeyManagerFactory.getDefaultAlgorithm();
059 }
060
061 KeyManagerFactory kmf = KeyManagerFactory.getInstance( algorithm );
062
063 if ( StringTools.isEmpty( certificatePassord ) )
064 {
065 kmf.init( ks, null );
066 }
067 else
068 {
069 kmf.init( ks, certificatePassord.toCharArray() );
070 }
071
072 // Initialize the SSLContext to work with our key managers.
073 sslCtx = SSLContext.getInstance( "TLS" );
074 sslCtx.init( kmf.getKeyManagers(), new TrustManager[]
075 { new ServerX509TrustManager() }, new SecureRandom() );
076 }
077 catch ( Exception e )
078 {
079 throw ( NamingException ) new NamingException( "Failed to create a SSL context." ).initCause( e );
080 }
081
082 DefaultIoFilterChainBuilder chain = new DefaultIoFilterChainBuilder();
083 chain.addLast( "sslFilter", new SslFilter( sslCtx ) );
084 return chain;
085 }
086 }