Search in sources :

Example 71 with SSLException

use of javax.net.ssl.SSLException in project ignite by apache.

the class GridSslBasicContextFactory method loadKeyStore.

/**
 * Loads key store with configured parameters.
 *
 * @param keyStoreType Type of key store.
 * @param storeFilePath Path to key store file.
 * @param keyStorePwd Store password.
 * @return Initialized key store.
 * @throws SSLException If key store could not be initialized.
 */
private KeyStore loadKeyStore(String keyStoreType, String storeFilePath, char[] keyStorePwd) throws SSLException {
    InputStream input = null;
    try {
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        input = openFileInputStream(storeFilePath);
        keyStore.load(input, keyStorePwd);
        return keyStore;
    } catch (GeneralSecurityException e) {
        throw new SSLException("Failed to initialize key store (security exception occurred) [type=" + keyStoreType + ", keyStorePath=" + storeFilePath + ']', e);
    } catch (FileNotFoundException e) {
        throw new SSLException("Failed to initialize key store (key store file was not found): [path=" + storeFilePath + ", msg=" + e.getMessage() + ']');
    } catch (IOException e) {
        throw new SSLException("Failed to initialize key store (I/O error occurred): " + storeFilePath, e);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException ignored) {
            }
        }
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) KeyStore(java.security.KeyStore) SSLException(javax.net.ssl.SSLException)

Example 72 with SSLException

use of javax.net.ssl.SSLException in project ignite by apache.

the class GridSslBasicContextFactory method createSslContext.

/**
 * {@inheritDoc}
 */
@Override
public SSLContext createSslContext() throws SSLException {
    checkParameters();
    try {
        KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(keyAlgorithm);
        KeyStore keyStore = loadKeyStore(keyStoreType, keyStoreFilePath, keyStorePwd);
        keyMgrFactory.init(keyStore, keyStorePwd);
        TrustManager[] mgrs = trustMgrs;
        if (mgrs == null) {
            TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(keyAlgorithm);
            KeyStore trustStore = loadKeyStore(trustStoreType, trustStoreFilePath, trustStorePwd);
            trustMgrFactory.init(trustStore);
            mgrs = trustMgrFactory.getTrustManagers();
        }
        SSLContext ctx = SSLContext.getInstance(proto);
        ctx.init(keyMgrFactory.getKeyManagers(), mgrs, null);
        return ctx;
    } catch (GeneralSecurityException e) {
        throw new SSLException("Failed to initialize SSL context " + parameters(), e);
    }
}
Also used : TrustManagerFactory(javax.net.ssl.TrustManagerFactory) GeneralSecurityException(java.security.GeneralSecurityException) SSLContext(javax.net.ssl.SSLContext) KeyStore(java.security.KeyStore) SSLException(javax.net.ssl.SSLException) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager)

Example 73 with SSLException

use of javax.net.ssl.SSLException in project ignite by apache.

the class GridTcpRestProtocol method start.

/**
 * {@inheritDoc}
 */
@SuppressWarnings("BusyWait")
@Override
public void start(final GridRestProtocolHandler hnd) throws IgniteCheckedException {
    assert hnd != null;
    ConnectorConfiguration cfg = ctx.config().getConnectorConfiguration();
    assert cfg != null;
    lsnr = new GridTcpRestNioListener(log, this, hnd, ctx);
    GridNioParser parser = new GridTcpRestParser(false, ctx.marshallerContext().jdkMarshaller());
    try {
        host = resolveRestTcpHost(ctx.config());
        SSLContext sslCtx = null;
        if (cfg.isSslEnabled()) {
            Factory<SSLContext> igniteFactory = ctx.config().getSslContextFactory();
            Factory<SSLContext> factory = cfg.getSslFactory();
            // This factory deprecated and will be removed.
            GridSslContextFactory depFactory = cfg.getSslContextFactory();
            if (factory == null && depFactory == null && igniteFactory == null)
                // Thrown SSL exception instead of IgniteCheckedException for writing correct warning message into log.
                throw new SSLException("SSL is enabled, but SSL context factory is not specified.");
            if (factory != null)
                sslCtx = factory.create();
            else if (depFactory != null)
                sslCtx = depFactory.createSslContext();
            else
                sslCtx = igniteFactory.create();
        }
        int startPort = cfg.getPort();
        int portRange = cfg.getPortRange();
        int lastPort = portRange == 0 ? startPort : startPort + portRange - 1;
        for (int port0 = startPort; port0 <= lastPort; port0++) {
            if (startTcpServer(host, port0, lsnr, parser, sslCtx, cfg)) {
                port = port0;
                if (log.isInfoEnabled())
                    log.info(startInfo());
                return;
            }
        }
        U.warn(log, "Failed to start TCP binary REST server (possibly all ports in range are in use) " + "[firstPort=" + cfg.getPort() + ", lastPort=" + lastPort + ", host=" + host + ']');
    } catch (SSLException e) {
        U.warn(log, "Failed to start " + name() + " protocol on port " + port + ": " + e.getMessage(), "Failed to start " + name() + " protocol on port " + port + ". Check if SSL context factory is " + "properly configured.");
    } catch (IOException e) {
        U.warn(log, "Failed to start " + name() + " protocol on port " + port + ": " + e.getMessage(), "Failed to start " + name() + " protocol on port " + port + ". " + "Check restTcpHost configuration property.");
    }
}
Also used : GridSslContextFactory(org.apache.ignite.internal.client.ssl.GridSslContextFactory) GridNioParser(org.apache.ignite.internal.util.nio.GridNioParser) ConnectorConfiguration(org.apache.ignite.configuration.ConnectorConfiguration) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) SSLException(javax.net.ssl.SSLException)

Example 74 with SSLException

use of javax.net.ssl.SSLException in project pravega by pravega.

the class ConnectionFactoryImpl method establishConnection.

@Override
public CompletableFuture<ClientConnection> establishConnection(PravegaNodeUri location, ReplyProcessor rp) {
    Preconditions.checkNotNull(location);
    Exceptions.checkNotClosed(closed.get(), this);
    final SslContext sslCtx;
    if (clientConfig.isEnableTls()) {
        try {
            SslContextBuilder sslCtxFactory = SslContextBuilder.forClient();
            if (Strings.isNullOrEmpty(clientConfig.getTrustStore())) {
                sslCtxFactory = sslCtxFactory.trustManager(FingerprintTrustManagerFactory.getInstance(FingerprintTrustManagerFactory.getDefaultAlgorithm()));
            } else {
                sslCtxFactory = SslContextBuilder.forClient().trustManager(new File(clientConfig.getTrustStore()));
            }
            sslCtx = sslCtxFactory.build();
        } catch (SSLException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    AppendBatchSizeTracker batchSizeTracker = new AppendBatchSizeTrackerImpl();
    ClientConnectionInboundHandler handler = new ClientConnectionInboundHandler(location.getEndpoint(), rp, batchSizeTracker);
    Bootstrap b = new Bootstrap();
    b.group(group).channel(nio ? NioSocketChannel.class : EpollSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());
                if (clientConfig.isValidateHostName()) {
                    SSLEngine sslEngine = sslHandler.engine();
                    SSLParameters sslParameters = sslEngine.getSSLParameters();
                    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
                    sslEngine.setSSLParameters(sslParameters);
                }
                p.addLast(sslHandler);
            }
            // p.addLast(new LoggingHandler(LogLevel.INFO));
            p.addLast(new ExceptionLoggingHandler(location.getEndpoint()), new CommandEncoder(batchSizeTracker), new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4), new CommandDecoder(), handler);
        }
    });
    // Start the client.
    CompletableFuture<ClientConnection> connectionComplete = new CompletableFuture<>();
    try {
        b.connect(location.getEndpoint(), location.getPort()).addListener(new ChannelFutureListener() {

            @Override
            public void operationComplete(ChannelFuture future) {
                if (future.isSuccess()) {
                    // since ChannelFuture is complete future.channel() is not a blocking call.
                    Channel ch = future.channel();
                    log.debug("Connect operation completed for channel:{}, local address:{}, remote address:{}", ch.id(), ch.localAddress(), ch.remoteAddress());
                    // Once a channel is closed the channel group implementation removes it.
                    allChannels.add(ch);
                    connectionComplete.complete(handler);
                } else {
                    connectionComplete.completeExceptionally(new ConnectionFailedException(future.cause()));
                }
            }
        });
    } catch (Exception e) {
        connectionComplete.completeExceptionally(new ConnectionFailedException(e));
    }
    // check if channel is registered.
    CompletableFuture<Void> channelRegisteredFuture = new CompletableFuture<>();
    handler.completeWhenRegistered(channelRegisteredFuture);
    return connectionComplete.thenCombine(channelRegisteredFuture, (clientConnection, v) -> clientConnection);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CommandEncoder(io.pravega.shared.protocol.netty.CommandEncoder) SSLException(javax.net.ssl.SSLException) CompletableFuture(java.util.concurrent.CompletableFuture) SSLParameters(javax.net.ssl.SSLParameters) ExceptionLoggingHandler(io.pravega.shared.protocol.netty.ExceptionLoggingHandler) Bootstrap(io.netty.bootstrap.Bootstrap) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) SslContext(io.netty.handler.ssl.SslContext) ChannelFuture(io.netty.channel.ChannelFuture) AppendBatchSizeTracker(io.pravega.shared.protocol.netty.AppendBatchSizeTracker) CommandDecoder(io.pravega.shared.protocol.netty.CommandDecoder) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SslContextBuilder(io.netty.handler.ssl.SslContextBuilder) File(java.io.File) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException)

Example 75 with SSLException

use of javax.net.ssl.SSLException in project pravega by pravega.

the class ConnectionFactoryImplTest method setUp.

@Before
public void setUp() throws Exception {
    // Configure SSL.
    port = TestUtils.getAvailableListenPort();
    final SslContext sslCtx;
    if (ssl) {
        try {
            sslCtx = SslContextBuilder.forServer(new File("../config/cert.pem"), new File("../config/key.pem")).build();
        } catch (SSLException e) {
            throw new RuntimeException(e);
        }
    } else {
        sslCtx = null;
    }
    boolean nio = false;
    EventLoopGroup bossGroup;
    EventLoopGroup workerGroup;
    try {
        bossGroup = new EpollEventLoopGroup(1);
        workerGroup = new EpollEventLoopGroup();
    } catch (ExceptionInInitializerError | UnsatisfiedLinkError | NoClassDefFoundError e) {
        nio = true;
        bossGroup = new NioEventLoopGroup(1);
        workerGroup = new NioEventLoopGroup();
    }
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(nio ? NioServerSocketChannel.class : EpollServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SslHandler handler = sslCtx.newHandler(ch.alloc());
                SSLEngine sslEngine = handler.engine();
                SSLParameters sslParameters = sslEngine.getSSLParameters();
                sslParameters.setEndpointIdentificationAlgorithm("LDAPS");
                sslEngine.setSSLParameters(sslParameters);
                p.addLast(handler);
            }
        }
    });
    // Start the server.
    serverChannel = b.bind("localhost", port).awaitUninterruptibly().channel();
}
Also used : EpollServerSocketChannel(io.netty.channel.epoll.EpollServerSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) LoggingHandler(io.netty.handler.logging.LoggingHandler) SSLEngine(javax.net.ssl.SSLEngine) SSLException(javax.net.ssl.SSLException) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ConnectionFailedException(io.pravega.shared.protocol.netty.ConnectionFailedException) SSLException(javax.net.ssl.SSLException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SSLParameters(javax.net.ssl.SSLParameters) EpollEventLoopGroup(io.netty.channel.epoll.EpollEventLoopGroup) File(java.io.File) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) SslContext(io.netty.handler.ssl.SslContext) Before(org.junit.Before)

Aggregations

SSLException (javax.net.ssl.SSLException)158 IOException (java.io.IOException)46 X509Certificate (java.security.cert.X509Certificate)26 SSLEngineResult (javax.net.ssl.SSLEngineResult)23 SocketException (java.net.SocketException)20 SSLSocket (javax.net.ssl.SSLSocket)20 ByteBuffer (java.nio.ByteBuffer)19 CertificateException (java.security.cert.CertificateException)19 Test (org.junit.Test)19 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)18 SSLContext (javax.net.ssl.SSLContext)15 SSLPeerUnverifiedException (javax.net.ssl.SSLPeerUnverifiedException)15 SSLSession (javax.net.ssl.SSLSession)15 InetSocketAddress (java.net.InetSocketAddress)14 SSLEngine (javax.net.ssl.SSLEngine)14 X509TrustManager (javax.net.ssl.X509TrustManager)12 Bootstrap (io.netty.bootstrap.Bootstrap)11 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)11 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)11 Socket (java.net.Socket)11