Search in sources :

Example 91 with SslHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler in project bgpcep by opendaylight.

the class AbstractPCEPSessionNegotiator method handleMessageStartTlsWait.

private boolean handleMessageStartTlsWait(final Message msg) {
    if (msg instanceof Starttls) {
        final SslContextFactory sslFactory = new SslContextFactory(this.tlsConfiguration);
        final SSLContext sslContext = sslFactory.getServerContext();
        if (sslContext == null) {
            this.sendErrorMessage(PCEPErrors.NOT_POSSIBLE_WITHOUT_TLS);
            negotiationFailed(new IllegalStateException("Failed to establish a TLS connection."));
            this.state = State.FINISHED;
            return true;
        }
        final SSLEngine engine = sslContext.createSSLEngine();
        engine.setNeedClientAuth(true);
        engine.setUseClientMode(false);
        this.channel.pipeline().addFirst(new SslHandler(engine));
        LOG.info("PCEPS TLS connection with peer: {} established succesfully.", this.channel);
        startNegotiationWithOpen();
        return true;
    } else if (!(msg instanceof Pcerr)) {
        this.sendErrorMessage(PCEPErrors.NON_STARTTLS_MSG_RCVD);
        negotiationFailed(new IllegalStateException("Unexpected message recieved."));
        this.state = State.FINISHED;
        return true;
    }
    return false;
}
Also used : SslContextFactory(org.opendaylight.protocol.pcep.impl.tls.SslContextFactory) SSLEngine(javax.net.ssl.SSLEngine) Pcerr(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Pcerr) SSLContext(javax.net.ssl.SSLContext) Starttls(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.message.rev131007.Starttls) SslHandler(io.netty.handler.ssl.SslHandler)

Example 92 with SslHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler in project drill by axbaretto.

the class UserClient method setupSSL.

@Override
protected void setupSSL(ChannelPipeline pipe, ConnectionMultiListener.SSLHandshakeListener sslHandshakeListener) {
    String peerHost = endpoint.getAddress();
    int peerPort = endpoint.getUserPort();
    SSLEngine sslEngine = sslConfig.createSSLEngine(allocator, peerHost, peerPort);
    // Add SSL handler into pipeline
    SslHandler sslHandler = new SslHandler(sslEngine);
    sslHandler.setHandshakeTimeoutMillis(sslConfig.getHandshakeTimeout());
    // Add a listener for SSL Handshake complete. The Drill client handshake will be enabled only
    // after this is done.
    sslHandler.handshakeFuture().addListener(sslHandshakeListener);
    pipe.addFirst(RpcConstants.SSL_HANDLER, sslHandler);
    logger.debug(sslConfig.toString());
}
Also used : SSLEngine(javax.net.ssl.SSLEngine) DrillbitEndpoint(org.apache.drill.exec.proto.CoordinationProtos.DrillbitEndpoint) SslHandler(io.netty.handler.ssl.SslHandler)

Example 93 with SslHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler in project bookkeeper by apache.

the class PerChannelBookieClient method initTLSHandshake.

void initTLSHandshake() {
    // create TLS handler
    PerChannelBookieClient parentObj = PerChannelBookieClient.this;
    SslHandler handler = parentObj.shFactory.newTLSHandler();
    channel.pipeline().addFirst(parentObj.shFactory.getHandlerName(), handler);
    handler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {

        @Override
        public void operationComplete(Future<Channel> future) throws Exception {
            int rc;
            Queue<GenericCallback<PerChannelBookieClient>> oldPendingOps;
            synchronized (PerChannelBookieClient.this) {
                if (future.isSuccess() && state == ConnectionState.CONNECTING) {
                    LOG.error("Connection state changed before TLS handshake completed {}/{}", addr, state);
                    rc = BKException.Code.BookieHandleNotAvailableException;
                    closeChannel(channel);
                    channel = null;
                    if (state != ConnectionState.CLOSED) {
                        state = ConnectionState.DISCONNECTED;
                    }
                } else if (future.isSuccess() && state == ConnectionState.START_TLS) {
                    rc = BKException.Code.OK;
                    LOG.info("Successfully connected to bookie using TLS: " + addr);
                    state = ConnectionState.CONNECTED;
                    AuthHandler.ClientSideHandler authHandler = future.get().pipeline().get(AuthHandler.ClientSideHandler.class);
                    authHandler.authProvider.onProtocolUpgrade();
                    activeTlsChannelCounter.inc();
                } else if (future.isSuccess() && (state == ConnectionState.CLOSED || state == ConnectionState.DISCONNECTED)) {
                    LOG.warn("Closed before TLS handshake completed, clean up: {}, current state {}", channel, state);
                    closeChannel(channel);
                    rc = BKException.Code.BookieHandleNotAvailableException;
                    channel = null;
                } else if (future.isSuccess() && state == ConnectionState.CONNECTED) {
                    LOG.debug("Already connected with another channel({}), so close the new channel({})", channel, channel);
                    closeChannel(channel);
                    // pendingOps should have been completed when other channel connected
                    return;
                } else {
                    LOG.error("TLS handshake failed with bookie: {}/{}, current state {} : ", channel, addr, state, future.cause());
                    rc = BKException.Code.SecurityException;
                    closeChannel(channel);
                    channel = null;
                    if (state != ConnectionState.CLOSED) {
                        state = ConnectionState.DISCONNECTED;
                    }
                    failedTlsHandshakeCounter.inc();
                }
                // trick to not do operations under the lock, take the list
                // of pending ops and assign it to a new variable, while
                // emptying the pending ops by just assigning it to a new
                // list
                oldPendingOps = pendingOps;
                pendingOps = new ArrayDeque<>();
            }
            for (GenericCallback<PerChannelBookieClient> pendingOp : oldPendingOps) {
                pendingOp.operationComplete(rc, PerChannelBookieClient.this);
            }
        }
    });
}
Also used : EpollSocketChannel(io.netty.channel.epoll.EpollSocketChannel) Channel(io.netty.channel.Channel) LocalChannel(io.netty.channel.local.LocalChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SslHandler(io.netty.handler.ssl.SslHandler) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) DecoderException(io.netty.handler.codec.DecoderException) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) BKException(org.apache.bookkeeper.client.BKException) SecurityException(org.apache.bookkeeper.tls.SecurityException) CorruptedFrameException(io.netty.handler.codec.CorruptedFrameException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) ArrayDeque(java.util.ArrayDeque) Future(io.netty.util.concurrent.Future) ChannelFuture(io.netty.channel.ChannelFuture) Queue(java.util.Queue) GenericCallback(org.apache.bookkeeper.proto.BookkeeperInternalCallbacks.GenericCallback)

Example 94 with SslHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler in project activemq-artemis by apache.

the class NettyAcceptor method getSslHandler.

public synchronized SslHandler getSslHandler(ByteBufAllocator alloc) throws Exception {
    SSLEngine engine;
    if (sslProvider.equals(TransportConstants.OPENSSL_PROVIDER)) {
        engine = loadOpenSslEngine(alloc);
    } else {
        engine = loadJdkSslEngine();
    }
    engine.setUseClientMode(false);
    if (needClientAuth) {
        engine.setNeedClientAuth(true);
    } else if (wantClientAuth) {
        engine.setWantClientAuth(true);
    }
    // setting the enabled cipher suites resets the enabled protocols so we need
    // to save the enabled protocols so that after the customer cipher suite is enabled
    // we can reset the enabled protocols if a customer protocol isn't specified
    String[] originalProtocols = engine.getEnabledProtocols();
    if (enabledCipherSuites != null) {
        try {
            engine.setEnabledCipherSuites(SSLSupport.parseCommaSeparatedListIntoArray(enabledCipherSuites));
        } catch (IllegalArgumentException e) {
            ActiveMQServerLogger.LOGGER.invalidCipherSuite(SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedCipherSuites()));
            throw e;
        }
    }
    if (enabledProtocols != null) {
        try {
            engine.setEnabledProtocols(SSLSupport.parseCommaSeparatedListIntoArray(enabledProtocols));
        } catch (IllegalArgumentException e) {
            ActiveMQServerLogger.LOGGER.invalidProtocol(SSLSupport.parseArrayIntoCommandSeparatedList(engine.getSupportedProtocols()));
            throw e;
        }
    } else {
        engine.setEnabledProtocols(originalProtocols);
    }
    // Strip "SSLv3" from the current enabled protocols to address the POODLE exploit.
    // This recommendation came from http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html
    String[] protocols = engine.getEnabledProtocols();
    Set<String> set = new HashSet<>();
    for (String s : protocols) {
        if (s.equalsIgnoreCase("SSLv3") || s.equals("SSLv2Hello")) {
            if (!warningPrinted.get()) {
                ActiveMQServerLogger.LOGGER.disallowedProtocol(s, name);
            }
            continue;
        }
        set.add(s);
    }
    warningPrinted.set(true);
    engine.setEnabledProtocols(set.toArray(new String[set.size()]));
    if (verifyHost) {
        SSLParameters sslParameters = engine.getSSLParameters();
        sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
        engine.setSSLParameters(sslParameters);
    }
    return new SslHandler(engine);
}
Also used : SSLParameters(javax.net.ssl.SSLParameters) SSLEngine(javax.net.ssl.SSLEngine) SimpleString(org.apache.activemq.artemis.api.core.SimpleString) SslHandler(io.netty.handler.ssl.SslHandler) HashSet(java.util.HashSet)

Example 95 with SslHandler

use of org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler in project activemq-artemis by apache.

the class NettyConnectorWithHTTPUpgradeTest method startWebServer.

private void startWebServer(int port) throws Exception {
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    final SSLContext context;
    if (useSSL) {
        context = SSLSupport.createContext("JKS", SERVER_SIDE_KEYSTORE, PASSWORD, null, null, null);
    } else {
        context = null;
    }
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            // create a HTTP server
            ChannelPipeline p = ch.pipeline();
            if (useSSL) {
                SSLEngine engine = context.createSSLEngine();
                engine.setUseClientMode(false);
                SslHandler handler = new SslHandler(engine);
                p.addLast("ssl", handler);
            }
            p.addLast("decoder", new HttpRequestDecoder());
            p.addLast("encoder", new HttpResponseEncoder());
            p.addLast("http-upgrade-handler", new SimpleChannelInboundHandler<Object>() {

                // handle HTTP GET + Upgrade with a handshake specific to ActiveMQ Artemis remoting.
                @Override
                protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof HttpRequest) {
                        HttpRequest request = (HttpRequest) msg;
                        for (Map.Entry<String, String> entry : request.headers()) {
                            System.out.println(entry);
                        }
                        String upgrade = request.headers().get(UPGRADE);
                        String secretKey = request.headers().get(SEC_ACTIVEMQ_REMOTING_KEY);
                        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, SWITCHING_PROTOCOLS);
                        response.headers().set(UPGRADE, upgrade);
                        response.headers().set(SEC_ACTIVEMQ_REMOTING_ACCEPT, createExpectedResponse(MAGIC_NUMBER, secretKey));
                        ctx.writeAndFlush(response);
                        // when the handshake is successful, the HTTP handlers are removed
                        ctx.pipeline().remove("decoder");
                        ctx.pipeline().remove("encoder");
                        ctx.pipeline().remove(this);
                        System.out.println("HTTP handshake sent, transferring channel");
                        // transfer the control of the channel to the Netty Acceptor
                        NettyAcceptor acceptor = (NettyAcceptor) server.getRemotingService().getAcceptor(acceptorName);
                        acceptor.transfer(ctx.channel());
                    // at this point, the HTTP upgrade process is over and the netty acceptor behaves like regular ones.
                    }
                }
            });
        }

        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
            ctx.flush();
        }
    });
    b.bind(port).sync();
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) HttpRequest(io.netty.handler.codec.http.HttpRequest) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) SSLEngine(javax.net.ssl.SSLEngine) NettyAcceptor(org.apache.activemq.artemis.core.remoting.impl.netty.NettyAcceptor) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) SSLContext(javax.net.ssl.SSLContext) RandomUtil.randomString(org.apache.activemq.artemis.tests.util.RandomUtil.randomString) SimpleString(org.apache.activemq.artemis.api.core.SimpleString) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ActiveMQNotConnectedException(org.apache.activemq.artemis.api.core.ActiveMQNotConnectedException) ActiveMQException(org.apache.activemq.artemis.api.core.ActiveMQException) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) Map(java.util.Map) HashMap(java.util.HashMap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

SslHandler (io.netty.handler.ssl.SslHandler)141 SSLEngine (javax.net.ssl.SSLEngine)51 ChannelPipeline (io.netty.channel.ChannelPipeline)37 Channel (io.netty.channel.Channel)29 ChannelHandler (io.netty.channel.ChannelHandler)23 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)23 SslContext (io.netty.handler.ssl.SslContext)21 IOException (java.io.IOException)16 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)15 Test (org.junit.Test)15 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)14 ChannelInitializer (io.netty.channel.ChannelInitializer)13 SocketChannel (io.netty.channel.socket.SocketChannel)13 SSLSession (javax.net.ssl.SSLSession)12 ByteBuf (io.netty.buffer.ByteBuf)11 ChunkedWriteHandler (io.netty.handler.stream.ChunkedWriteHandler)11 IdleStateHandler (io.netty.handler.timeout.IdleStateHandler)11 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)10 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)10 File (java.io.File)10