Search in sources :

Example 1 with SslFilter

use of org.apache.mina.filter.ssl.SslFilter in project opennms by OpenNMS.

the class AsyncBasicDetectorMinaImpl method isServiceDetected.

/**
 * {@inheritDoc}
 */
@Override
public final DetectFuture isServiceDetected(final InetAddress address) {
    final DetectFutureMinaImpl detectFuture = new DetectFutureMinaImpl(this);
    try {
        // Set this up here because it can throw an Exception, which we want
        // to throw now, not in initializeSession
        final SSLContext c = createClientSSLContext();
        // Create an IoSessionInitializer that will configure this individual
        // session. Previously, all this was done on a new Connector each time
        // but that was leaking file handles all over the place. This way gives
        // us per-connection settings without the overhead of creating new
        // Connectors each time
        IoSessionInitializer<ConnectFuture> init = new IoSessionInitializer<ConnectFuture>() {

            @Override
            public void initializeSession(IoSession session, ConnectFuture future) {
                // Add filters to the session
                if (isUseSSLFilter()) {
                    final SslFilter filter = new SslFilter(c);
                    filter.setUseClientMode(true);
                    session.getFilterChain().addFirst("SSL", filter);
                }
                session.getFilterChain().addLast("logger", getLoggingFilter() != null ? getLoggingFilter() : new SlightlyMoreVerboseLoggingFilter());
                session.getFilterChain().addLast("codec", getProtocolCodecFilter());
                // Make the minimum idle timeout 1 second
                int idleTimeInSeconds = Math.max(1, Math.round(getIdleTime() / 1000.0f));
                // Set all of the idle time limits. Make sure to specify values in
                // seconds!!!
                session.getConfig().setReaderIdleTime(idleTimeInSeconds);
                session.getConfig().setWriterIdleTime(idleTimeInSeconds);
                session.getConfig().setBothIdleTime(idleTimeInSeconds);
            }
        };
        // Start communication
        final InetSocketAddress socketAddress = new InetSocketAddress(address, getPort());
        final ConnectFuture cf = m_connectionFactory.connect(socketAddress, init, createDetectorHandler(detectFuture));
        cf.addListener(retryAttemptListener(detectFuture, socketAddress, init, getRetries()));
    } catch (KeyManagementException e) {
        detectFuture.setException(e);
    } catch (NoSuchAlgorithmException e) {
        detectFuture.setException(e);
    } catch (Throwable e) {
        detectFuture.setException(e);
    }
    return detectFuture;
}
Also used : SslFilter(org.apache.mina.filter.ssl.SslFilter) InetSocketAddress(java.net.InetSocketAddress) SSLContext(javax.net.ssl.SSLContext) ConnectFuture(org.apache.mina.core.future.ConnectFuture) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) IoSessionInitializer(org.apache.mina.core.session.IoSessionInitializer) IoSession(org.apache.mina.core.session.IoSession)

Example 2 with SslFilter

use of org.apache.mina.filter.ssl.SslFilter in project wildfly by wildfly.

the class LdapsInitializer method init.

public static IoFilterChainBuilder init(LdapServer server, TcpTransport transport) throws LdapException {
    if (recorder == null) {
        throw new LdapException("You need to set " + LdapsInitializer.class.getName() + ".recorder before starting the LDAP server");
    }
    SSLContext sslCtx;
    try {
        // Initialize the SSLContext to work with our key managers.
        final SSLContext delegateCtx = SSLContext.getInstance("TLS");
        sslCtx = new WrappedSSLContext(delegateCtx, recorder, delegateCtx.getProvider(), delegateCtx.getProtocol());
        sslCtx.init(server.getKeyManagerFactory().getKeyManagers(), new TrustManager[] { new NoVerificationTrustManager() }, new SecureRandom());
    } catch (Exception e) {
        throw new LdapException(I18n.err(I18n.ERR_683), e);
    }
    DefaultIoFilterChainBuilder chain = new DefaultIoFilterChainBuilder();
    SslFilter sslFilter = new SslFilter(sslCtx);
    List<String> cipherSuites = transport.getCipherSuite();
    if ((cipherSuites != null) && !cipherSuites.isEmpty()) {
        sslFilter.setEnabledCipherSuites(cipherSuites.toArray(new String[cipherSuites.size()]));
    }
    // The protocols
    List<String> enabledProtocols = transport.getEnabledProtocols();
    if ((enabledProtocols != null) && !enabledProtocols.isEmpty()) {
        sslFilter.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
    } else {
        // Be sure we disable SSLV3
        sslFilter.setEnabledProtocols(new String[] { "TLSv1", "TLSv1.1", "TLSv1.2" });
    }
    // The remaining SSL parameters
    sslFilter.setNeedClientAuth(transport.isNeedClientAuth());
    sslFilter.setWantClientAuth(transport.isWantClientAuth());
    chain.addLast("sslFilter", sslFilter);
    return chain;
}
Also used : SslFilter(org.apache.mina.filter.ssl.SslFilter) NoVerificationTrustManager(org.apache.directory.ldap.client.api.NoVerificationTrustManager) SecureRandom(java.security.SecureRandom) DefaultIoFilterChainBuilder(org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder) SSLContext(javax.net.ssl.SSLContext) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) KeyManagementException(java.security.KeyManagementException) SSLException(javax.net.ssl.SSLException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException)

Example 3 with SslFilter

use of org.apache.mina.filter.ssl.SslFilter in project Openfire by igniterealtime.

the class EncryptionArtifactFactory method createSslFilter.

/**
 * A utility method that implements the shared functionality of getServerModeSslFilter and getClientModeSslFilter.
 *
 * This method is used to initialize and configure an instance of SslFilter for a particular pre-configured
 * SSLContext and SSLEngine. In most cases, developers will want to use getServerModeSslFilter or
 * getClientModeSslFilter instead of this method.
 *
 * @param sslContext a pre-configured SSL Context instance (cannot be null).
 * @param sslEngine a pre-configured SSL Engine instance (cannot be null).
 * @return A SslFilter instance (never null).
 */
private static SslFilter createSslFilter(SSLContext sslContext, SSLEngine sslEngine) {
    final SslFilter filter = new SslFilter(sslContext);
    // Copy configuration from the SSL Engine into the filter.
    filter.setUseClientMode(sslEngine.getUseClientMode());
    filter.setEnabledProtocols(sslEngine.getEnabledProtocols());
    filter.setEnabledCipherSuites(sslEngine.getEnabledCipherSuites());
    // Note that the setters for 'need' and 'want' influence each-other. Invoke only one of them!
    if (sslEngine.getNeedClientAuth()) {
        filter.setNeedClientAuth(true);
    } else if (sslEngine.getWantClientAuth()) {
        filter.setWantClientAuth(true);
    }
    return filter;
}
Also used : SslFilter(org.apache.mina.filter.ssl.SslFilter)

Example 4 with SslFilter

use of org.apache.mina.filter.ssl.SslFilter in project Openfire by igniterealtime.

the class MINAConnectionAcceptor method reconfigure.

@Override
public synchronized void reconfigure(ConnectionConfiguration configuration) {
    this.configuration = configuration;
    if (socketAcceptor == null) {
        // reconfig will occur when acceptor is started.
        return;
    }
    final DefaultIoFilterChainBuilder filterChain = socketAcceptor.getFilterChain();
    if (filterChain.contains(ConnectionManagerImpl.EXECUTOR_FILTER_NAME)) {
        final ExecutorFilter executorFilter = (ExecutorFilter) filterChain.get(ConnectionManagerImpl.EXECUTOR_FILTER_NAME);
        ((ThreadPoolExecutor) executorFilter.getExecutor()).setCorePoolSize((configuration.getMaxThreadPoolSize() / 4) + 1);
        ((ThreadPoolExecutor) executorFilter.getExecutor()).setMaximumPoolSize((configuration.getMaxThreadPoolSize()));
    }
    if (configuration.getTlsPolicy() == Connection.TLSPolicy.legacyMode) {
        // add or replace TLS filter (that's used only for 'direct-TLS')
        try {
            final SslFilter sslFilter = encryptionArtifactFactory.createServerModeSslFilter();
            if (filterChain.contains(ConnectionManagerImpl.TLS_FILTER_NAME)) {
                filterChain.replace(ConnectionManagerImpl.TLS_FILTER_NAME, sslFilter);
            } else {
                filterChain.addAfter(ConnectionManagerImpl.EXECUTOR_FILTER_NAME, ConnectionManagerImpl.TLS_FILTER_NAME, sslFilter);
            }
        } catch (KeyManagementException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException e) {
            Log.error("An exception occurred while reloading the TLS configuration.", e);
        }
    } else {
        // The acceptor is in 'startTLS' mode. Remove TLS filter (that's used only for 'direct-TLS')
        if (filterChain.contains(ConnectionManagerImpl.TLS_FILTER_NAME)) {
            filterChain.remove(ConnectionManagerImpl.TLS_FILTER_NAME);
        }
    }
    if (configuration.getMaxBufferSize() > 0) {
        socketAcceptor.getSessionConfig().setMaxReadBufferSize(configuration.getMaxBufferSize());
        Log.debug("Throttling read buffer for connections to max={} bytes", configuration.getMaxBufferSize());
    }
}
Also used : SslFilter(org.apache.mina.filter.ssl.SslFilter) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ExecutorFilter(org.apache.mina.filter.executor.ExecutorFilter) DefaultIoFilterChainBuilder(org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException)

Example 5 with SslFilter

use of org.apache.mina.filter.ssl.SslFilter in project Openfire by igniterealtime.

the class MINAConnectionAcceptor method start.

/**
 * Starts this acceptor by binding the socket acceptor. When the acceptor is already started, a warning will be
 * logged and the method invocation is otherwise ignored.
 */
@Override
public synchronized void start() {
    if (socketAcceptor != null) {
        Log.warn("Unable to start acceptor (it is already started!)");
        return;
    }
    try {
        // Configure the thread pool that is to be used.
        final int initialSize = (configuration.getMaxThreadPoolSize() / 4) + 1;
        final ExecutorFilter executorFilter = new ExecutorFilter(initialSize, configuration.getMaxThreadPoolSize(), 60, TimeUnit.SECONDS);
        final ThreadPoolExecutor eventExecutor = (ThreadPoolExecutor) executorFilter.getExecutor();
        final ThreadFactory threadFactory = new NamedThreadFactory(name + "-thread-", eventExecutor.getThreadFactory(), true, null);
        eventExecutor.setThreadFactory(threadFactory);
        // Construct a new socket acceptor, and configure it.
        socketAcceptor = buildSocketAcceptor();
        if (JMXManager.isEnabled()) {
        // configureJMX( socketAcceptor, name );
        }
        final DefaultIoFilterChainBuilder filterChain = socketAcceptor.getFilterChain();
        filterChain.addFirst(ConnectionManagerImpl.EXECUTOR_FILTER_NAME, executorFilter);
        // Add the XMPP codec filter
        filterChain.addAfter(ConnectionManagerImpl.EXECUTOR_FILTER_NAME, ConnectionManagerImpl.XMPP_CODEC_FILTER_NAME, new ProtocolCodecFilter(new XMPPCodecFactory()));
        // Kill sessions whose outgoing queues keep growing and fail to send traffic
        filterChain.addAfter(ConnectionManagerImpl.XMPP_CODEC_FILTER_NAME, ConnectionManagerImpl.CAPACITY_FILTER_NAME, new StalledSessionsFilter());
        // Ports can be configured to start connections in SSL (as opposed to upgrade a non-encrypted socket to an encrypted one, typically using StartTLS)
        if (configuration.getTlsPolicy() == Connection.TLSPolicy.legacyMode) {
            final SslFilter sslFilter = encryptionArtifactFactory.createServerModeSslFilter();
            filterChain.addAfter(ConnectionManagerImpl.EXECUTOR_FILTER_NAME, ConnectionManagerImpl.TLS_FILTER_NAME, sslFilter);
        }
        // Throttle sessions who send data too fast
        if (configuration.getMaxBufferSize() > 0) {
            socketAcceptor.getSessionConfig().setMaxReadBufferSize(configuration.getMaxBufferSize());
            Log.debug("Throttling read buffer for connections to max={} bytes", configuration.getMaxBufferSize());
        }
        // Start accepting connections
        socketAcceptor.setHandler(connectionHandler);
        socketAcceptor.bind(new InetSocketAddress(configuration.getBindAddress(), configuration.getPort()));
    } catch (Exception e) {
        System.err.println("Error starting " + configuration.getPort() + ": " + e.getMessage());
        Log.error("Error starting: " + configuration.getPort(), e);
        // Reset for future use.
        if (socketAcceptor != null) {
            try {
                socketAcceptor.unbind();
            } finally {
                socketAcceptor = null;
            }
        }
    }
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) NamedThreadFactory(org.jivesoftware.util.NamedThreadFactory) SslFilter(org.apache.mina.filter.ssl.SslFilter) NamedThreadFactory(org.jivesoftware.util.NamedThreadFactory) InetSocketAddress(java.net.InetSocketAddress) ExecutorFilter(org.apache.mina.filter.executor.ExecutorFilter) DefaultIoFilterChainBuilder(org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder) StalledSessionsFilter(org.jivesoftware.openfire.net.StalledSessionsFilter) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ProtocolCodecFilter(org.apache.mina.filter.codec.ProtocolCodecFilter) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) KeyManagementException(java.security.KeyManagementException) MalformedObjectNameException(javax.management.MalformedObjectNameException) JMException(javax.management.JMException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

SslFilter (org.apache.mina.filter.ssl.SslFilter)11 InetSocketAddress (java.net.InetSocketAddress)6 ExecutorFilter (org.apache.mina.filter.executor.ExecutorFilter)6 KeyManagementException (java.security.KeyManagementException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 SSLContext (javax.net.ssl.SSLContext)3 DefaultIoFilterChainBuilder (org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder)3 IoFilter (org.apache.mina.core.filterchain.IoFilter)3 OrderedThreadPoolExecutor (org.apache.mina.filter.executor.OrderedThreadPoolExecutor)3 UnorderedThreadPoolExecutor (org.apache.mina.filter.executor.UnorderedThreadPoolExecutor)3 LoggingFilter (org.apache.mina.filter.logging.LoggingFilter)3 IOException (java.io.IOException)2 KeyStoreException (java.security.KeyStoreException)2 UnrecoverableKeyException (java.security.UnrecoverableKeyException)2 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)2 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)2 ProtocolCodecFilter (org.apache.mina.filter.codec.ProtocolCodecFilter)2 NioSocketAcceptor (org.apache.mina.transport.socket.nio.NioSocketAcceptor)2 NioSocketConnector (org.apache.mina.transport.socket.nio.NioSocketConnector)2 ConnectException (java.net.ConnectException)1