Example usage for io.netty.handler.ssl SslHandler engine

List of usage examples for io.netty.handler.ssl SslHandler engine

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslHandler engine.

Prototype

SSLEngine engine

To view the source code for io.netty.handler.ssl SslHandler engine.

Click Source Link

Usage

From source file:io.advantageous.conekt.net.impl.ConnectionBase.java

License:Open Source License

public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
    if (isSSL()) {
        ChannelHandlerContext sslHandlerContext = channel.pipeline().context("ssl");
        assert sslHandlerContext != null;
        SslHandler sslHandler = (SslHandler) sslHandlerContext.handler();
        return sslHandler.engine().getSession().getPeerCertificateChain();
    } else {/*from   w  ww .j a  v  a 2s .  c  o m*/
        return null;
    }
}

From source file:io.crate.auth.HostBasedAuthenticationTest.java

@Before
private void setUpTest() throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslHandler sslHandler = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
            .trustManager(InsecureTrustManagerFactory.INSTANCE).startTls(false).build()
            .newHandler(ByteBufAllocator.DEFAULT);
    sslSession = sslHandler.engine().getSession();
}

From source file:io.crate.operation.auth.HostBasedAuthenticationTest.java

@Before
private void setUpTest() throws Exception {
    Settings settings = Settings.builder().put(AuthSettings.AUTH_HOST_BASED_ENABLED_SETTING.getKey(), true)
            .build();//from   ww w. ja v  a  2 s .  com
    authService = new HostBasedAuthentication(settings, null);

    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslHandler sslHandler = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
            .trustManager(InsecureTrustManagerFactory.INSTANCE).startTls(false).build()
            .newHandler(ByteBufAllocator.DEFAULT);
    sslSession = sslHandler.engine().getSession();
}

From source file:io.crate.protocols.SSL.java

License:Apache License

@Nullable
public static SSLSession getSession(Channel channel) {
    SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
    if (sslHandler != null) {
        return sslHandler.engine().getSession();
    }/*  ww  w  .j a v  a 2s  . c o  m*/
    return null;
}

From source file:io.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

private Future<Channel> installSslHandler(HttpTx tx, Channel channel) {

    SslContext sslCtx = tx.request.isAlpnRequired() ? alpnSslContext : sslContext;

    try {/*w  ww . ja va2  s.com*/
        SslHandler sslHandler = SslHandlers.newSslHandler(sslCtx, channel.alloc(), tx.request.getUri(),
                tx.request.getVirtualHost(), config);
        tx.listener.onTlsHandshakeAttempt();

        ChannelPipeline pipeline = channel.pipeline();
        String after = pipeline.get(PROXY_HANDLER) != null ? PROXY_HANDLER : PINNED_HANDLER;
        pipeline.addAfter(after, SSL_HANDLER, sslHandler);

        return sslHandler.handshakeFuture().addListener(f -> {

            SSLSession sslSession = sslHandler.engine().getHandshakeSession();
            if (sslSession != null && sslSession.isValid() && config.isDisableSslSessionResumption()) {
                sslSession.invalidate();
            }

            if (tx.requestTimeout.isDone()) {
                return;
            }

            if (f.isSuccess()) {
                tx.listener.onTlsHandshakeSuccess();
            } else {
                tx.requestTimeout.cancel();
                tx.listener.onTlsHandshakeFailure(f.cause());
                tx.listener.onThrowable(f.cause());
            }
        });
    } catch (RuntimeException e) {
        tx.requestTimeout.cancel();
        tx.listener.onThrowable(e);
        return new DefaultPromise<Channel>(ImmediateEventExecutor.INSTANCE).setFailure(e);
    }
}

From source file:io.gatling.http.client.impl.DefaultHttpClient.java

License:Apache License

private Future<Channel> installHttp2Handler(HttpTx tx, Channel channel, ChannelPool channelPool) {

    Promise<Channel> whenAlpn = channel.eventLoop().newPromise();

    channel.pipeline().addAfter(SSL_HANDLER, ALPN_HANDLER,
            new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {
                @Override/*from   ww w .ja v  a 2  s  .c o m*/
                protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {

                    switch (protocol) {
                    case ApplicationProtocolNames.HTTP_2:
                        LOGGER.debug("ALPN led to HTTP/2 with remote {}", tx.request.getUri().getHost());
                        tx.listener.onProtocolAwareness(true);
                        Http2Connection connection = new DefaultHttp2Connection(false);

                        HttpToHttp2ConnectionHandler http2Handler = new HttpToHttp2ConnectionHandlerBuilder()
                                .initialSettings(Http2Settings.defaultSettings()) // FIXME override?
                                .connection(connection)
                                .frameListener(new DelegatingDecompressorFrameListener(connection,
                                        new ChunkedInboundHttp2ToHttpAdapter(connection, false, true,
                                                whenAlpn)))
                                .build();

                        ctx.pipeline().addLast(HTTP2_HANDLER, http2Handler).addLast(APP_HTTP2_HANDLER,
                                new Http2AppHandler(connection, http2Handler, channelPool, config));

                        channelPool.offer(channel);

                        SslHandler sslHandler = (SslHandler) ctx.pipeline().get(SSL_HANDLER);
                        Set<String> subjectAlternativeNames = Tls
                                .extractSubjectAlternativeNames(sslHandler.engine());
                        if (!subjectAlternativeNames.isEmpty()) {
                            channelPool.addCoalescedChannel(subjectAlternativeNames,
                                    (InetSocketAddress) channel.remoteAddress(), channel, tx.key);
                        }
                        break;

                    case ApplicationProtocolNames.HTTP_1_1:
                        LOGGER.debug("ALPN led to HTTP/1 with remote {}", tx.request.getUri().getHost());
                        if (tx.request.isHttp2PriorKnowledge()) {
                            IllegalStateException e = new IllegalStateException(
                                    "HTTP/2 Prior knowledge was set on host " + tx.request.getUri().getHost()
                                            + " but it only supports HTTP/1");
                            whenAlpn.setFailure(e);
                            throw e;
                        }
                        tx.listener.onProtocolAwareness(false);
                        ctx.pipeline()
                                .addBefore(CHUNKED_WRITER_HANDLER, HTTP_CLIENT_CODEC, newHttpClientCodec())
                                .addBefore(CHUNKED_WRITER_HANDLER, INFLATER_HANDLER,
                                        newHttpContentDecompressor())
                                .addAfter(CHUNKED_WRITER_HANDLER, APP_HTTP_HANDLER,
                                        new HttpAppHandler(DefaultHttpClient.this, channelPool, config));
                        whenAlpn.setSuccess(ctx.channel());
                        break;

                    default:
                        IllegalStateException e = new IllegalStateException("Unknown protocol: " + protocol);
                        whenAlpn.setFailure(e);
                        ctx.close();
                        // FIXME do we really need to throw?
                        throw e;
                    }
                }
            });

    whenAlpn.addListener(f -> {
        if (!f.isSuccess()) {
            tx.listener.onThrowable(f.cause());
        }
    });

    return whenAlpn;
}

From source file:io.grpc.netty.ProtocolNegotiators.java

License:Apache License

@VisibleForTesting
static void logSslEngineDetails(Level level, ChannelHandlerContext ctx, String msg, @Nullable Throwable t) {
    if (!log.isLoggable(level)) {
        return;/*from w  w w. j av a2 s . co m*/
    }

    SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
    SSLEngine engine = sslHandler.engine();

    StringBuilder builder = new StringBuilder(msg);
    builder.append("\nSSLEngine Details: [\n");
    if (engine instanceof OpenSslEngine) {
        builder.append("    OpenSSL, ");
        builder.append("Version: 0x").append(Integer.toHexString(OpenSsl.version()));
        builder.append(" (").append(OpenSsl.versionString()).append("), ");
        builder.append("ALPN supported: ").append(OpenSsl.isAlpnSupported());
    } else if (JettyTlsUtil.isJettyAlpnConfigured()) {
        builder.append("    Jetty ALPN");
    } else if (JettyTlsUtil.isJettyNpnConfigured()) {
        builder.append("    Jetty NPN");
    } else if (JettyTlsUtil.isJava9AlpnAvailable()) {
        builder.append("    JDK9 ALPN");
    }
    builder.append("\n    TLS Protocol: ");
    builder.append(engine.getSession().getProtocol());
    builder.append("\n    Application Protocol: ");
    builder.append(sslHandler.applicationProtocol());
    builder.append("\n    Need Client Auth: ");
    builder.append(engine.getNeedClientAuth());
    builder.append("\n    Want Client Auth: ");
    builder.append(engine.getWantClientAuth());
    builder.append("\n    Supported protocols=");
    builder.append(Arrays.toString(engine.getSupportedProtocols()));
    builder.append("\n    Enabled protocols=");
    builder.append(Arrays.toString(engine.getEnabledProtocols()));
    builder.append("\n    Supported ciphers=");
    builder.append(Arrays.toString(engine.getSupportedCipherSuites()));
    builder.append("\n    Enabled ciphers=");
    builder.append(Arrays.toString(engine.getEnabledCipherSuites()));
    builder.append("\n]");

    log.log(level, builder.toString(), t);
}

From source file:io.jsync.net.impl.ConnectionBase.java

License:Open Source License

public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
    if (isSSL()) {
        final ChannelHandlerContext sslHandlerContext = channel.pipeline().context("ssl");
        assert sslHandlerContext != null;
        final SslHandler sslHandler = (SslHandler) sslHandlerContext.handler();
        return sslHandler.engine().getSession().getPeerCertificateChain();
    } else {//from  www.  j  av  a2s .  co m
        return null;
    }
}

From source file:io.netty.example.ocsp.OcspClientExample.java

License:Apache License

private static ChannelInitializer<Channel> newClientHandler(final ReferenceCountedOpenSslContext context,
        final String host, final Promise<FullHttpResponse> promise) {

    return new ChannelInitializer<Channel>() {
        @Override//from  w w  w  .  ja va2  s.  c  o  m
        protected void initChannel(Channel ch) throws Exception {
            SslHandler sslHandler = context.newHandler(ch.alloc());
            ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();

            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(sslHandler);
            pipeline.addLast(new ExampleOcspClientHandler(engine));

            pipeline.addLast(new HttpClientCodec());
            pipeline.addLast(new HttpObjectAggregator(1024 * 1024));
            pipeline.addLast(new HttpClientHandler(host, promise));
        }

        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            if (!promise.isDone()) {
                promise.tryFailure(new IllegalStateException("Connection closed and Promise was not done."));
            }
            ctx.fireChannelInactive();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            if (!promise.tryFailure(cause)) {
                ctx.fireExceptionCaught(cause);
            }
        }
    };
}

From source file:io.netty.example.ocsp.OcspServerExample.java

License:Apache License

private static ChannelInitializer<Channel> newServerHandler(final ReferenceCountedOpenSslContext context,
        final OCSPResp response) {
    return new ChannelInitializer<Channel>() {
        @Override/*from w ww.j  av a  2 s. co m*/
        protected void initChannel(Channel ch) throws Exception {
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();

                engine.setOcspResponse(response.getEncoded());
            }

            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(sslHandler);

            // so on and so forth...
        }
    };
}