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:org.eclipse.californium.elements.tcp.TlsContextUtil.java

License:Open Source License

/**
 * Build endpoint context related to the provided channel.
 * /* www .  j  a va 2s  .  c  o m*/
 * @param channel channel of endpoint context
 * @return endpoint context
 * @throws IllegalStateException if no {@link SslHandler} is available or
 *             the handshake isn't finished yet.
 */
@Override
public EndpointContext buildEndpointContext(Channel channel) {
    InetSocketAddress address = (InetSocketAddress) channel.remoteAddress();
    String id = channel.id().asShortText();
    SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
    if (sslHandler == null) {
        throw new IllegalStateException("Missing SslHandler for " + id + "!");
    }
    SSLEngine sslEngine = sslHandler.engine();
    SSLSession sslSession = sslEngine.getSession();
    if (sslSession != null) {
        boolean checkKerberos = false;
        Principal principal = null;
        try {
            Certificate[] peerCertificateChain = sslSession.getPeerCertificates();
            if (peerCertificateChain != null && peerCertificateChain.length != 0) {
                principal = X509CertPath.fromCertificatesChain(peerCertificateChain);
            } else {
                // maybe kerberos is used and therefore
                // getPeerCertificates fails
                checkKerberos = true;
            }
        } catch (SSLPeerUnverifiedException e1) {
            // maybe kerberos is used and therefore
            // getPeerCertificates fails
            checkKerberos = true;
        } catch (RuntimeException e) {
            LOGGER.warn("TLS({}) failed to extract principal {}", id, e.getMessage());
        }

        if (checkKerberos) {
            try {
                principal = sslSession.getPeerPrincipal();
            } catch (SSLPeerUnverifiedException e2) {
                // still unverified, so also no kerberos
                if (warnMissingPrincipal) {
                    LOGGER.warn("TLS({}) failed to verify principal, {}", id, e2.getMessage());
                } else {
                    LOGGER.trace("TLS({}) failed to verify principal, {}", id, e2.getMessage());
                }
            }
        }

        if (principal != null) {
            LOGGER.debug("TLS({}) Principal {}", id, principal.getName());
        } else if (warnMissingPrincipal) {
            LOGGER.warn("TLS({}) principal missing", id);
        } else {
            LOGGER.trace("TLS({}) principal missing", id);
        }

        byte[] sessionId = sslSession.getId();
        if (sessionId != null && sessionId.length > 0) {
            String sslId = StringUtil.byteArray2HexString(sessionId, StringUtil.NO_SEPARATOR, 0);
            String cipherSuite = sslSession.getCipherSuite();
            LOGGER.debug("TLS({},{},{})", id, StringUtil.trunc(sslId, 14), cipherSuite);
            return new TlsEndpointContext(address, principal, id, sslId, cipherSuite);
        }
    }
    // TLS handshake not finished
    throw new IllegalStateException("TLS handshake " + id + " not ready!");
}

From source file:org.elasticsearch.xpack.security.rest.SecurityRestFilter.java

License:Open Source License

@Override
public void handleRequest(RestRequest request, RestChannel channel, NodeClient client) throws Exception {
    if (licenseState.isSecurityEnabled() && licenseState.isAuthAllowed()
            && request.method() != Method.OPTIONS) {
        // CORS - allow for preflight unauthenticated OPTIONS request
        if (extractClientCertificate) {
            Netty4HttpRequest nettyHttpRequest = (Netty4HttpRequest) request;
            SslHandler handler = nettyHttpRequest.getChannel().pipeline().get(SslHandler.class);
            assert handler != null;
            ServerTransportFilter.extractClientCertificates(logger, threadContext, handler.engine(),
                    nettyHttpRequest.getChannel());
        }//from   www. java 2 s  .  c o  m
        service.authenticate(maybeWrapRestRequest(request), ActionListener.wrap(authentication -> {
            RemoteHostHeader.process(request, threadContext);
            restHandler.handleRequest(request, channel, client);
        }, e -> {
            try {
                channel.sendResponse(new BytesRestResponse(channel, e));
            } catch (Exception inner) {
                inner.addSuppressed(e);
                logger.error((Supplier<?>) () -> new ParameterizedMessage(
                        "failed to send failure response for uri [{}]", request.uri()), inner);
            }
        }));
    } else {
        restHandler.handleRequest(request, channel, client);
    }
}

From source file:org.elasticsearch.xpack.security.transport.SSLEngineUtils.java

License:Open Source License

public static SSLEngine getSSLEngine(HttpChannel httpChannel) {
    if (httpChannel instanceof Netty4HttpChannel) {
        Channel nettyChannel = ((Netty4HttpChannel) httpChannel).getNettyChannel();
        SslHandler handler = nettyChannel.pipeline().get(SslHandler.class);
        assert handler != null : "Must have SslHandler";
        return handler.engine();
    } else if (httpChannel instanceof NioHttpChannel) {
        SocketChannelContext context = ((NioHttpChannel) httpChannel).getContext();
        assert context instanceof SSLChannelContext : "Must be SSLChannelContext.class, found:  "
                + context.getClass();/* w ww .j  a v a 2s . c  o  m*/
        return ((SSLChannelContext) context).getSSLEngine();
    } else {
        throw new AssertionError("Unknown channel class type: " + httpChannel.getClass());
    }
}

From source file:org.elasticsearch.xpack.security.transport.SSLEngineUtils.java

License:Open Source License

public static SSLEngine getSSLEngine(TcpChannel tcpChannel) {
    if (tcpChannel instanceof Netty4TcpChannel) {
        Channel nettyChannel = ((Netty4TcpChannel) tcpChannel).getNettyChannel();
        SslHandler handler = nettyChannel.pipeline().get(SslHandler.class);
        assert handler != null : "Must have SslHandler";
        return handler.engine();
    } else if (tcpChannel instanceof NioTcpChannel) {
        SocketChannelContext context = ((NioTcpChannel) tcpChannel).getContext();
        assert context instanceof SSLChannelContext : "Must be SSLChannelContext.class, found:  "
                + context.getClass();//from   w w w. j  a v a2 s  .c o m
        return ((SSLChannelContext) context).getSSLEngine();
    } else {
        throw new AssertionError("Unknown channel class type: " + tcpChannel.getClass());
    }
}

From source file:org.opendaylight.ovsdb.lib.impl.OvsdbConnectionService.java

License:Open Source License

private static void handleNewPassiveConnection(final Channel channel) {
    executorService.execute(new Runnable() {
        @Override/*from w  ww  .  jav a2 s  .  c o  m*/
        public void run() {
            OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
                    Executors.newFixedThreadPool(NUM_THREADS));

            SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
            if (sslHandler != null) {
                //Wait until ssl handshake is complete
                int count = 0;
                logger.debug("Check if ssl handshake is done");
                while (sslHandler.engine().getSession().getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL")
                        && count < 10) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        logger.error("Exception while checking if ssl handshake is done", e);
                    }
                    count++;
                }
                if (sslHandler.engine().getSession().getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL")) {
                    logger.debug("Ssl hanshake is not compelete yet");
                    return;
                }
            }
            logger.debug("Notify listener");
            for (OvsdbConnectionListener listener : connectionListeners) {
                listener.connected(client);
            }
        }
    });
}

From source file:org.opendaylight.ovsdb.lib.OvsdbConnectionInfo.java

License:Open Source License

@XmlElement(name = "clientCertificate")
public Certificate getCertificate() throws SSLPeerUnverifiedException {
    SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
    if (sslHandler != null) {
        return sslHandler.engine().getSession().getPeerCertificates()[0];
    }/*from  w  w  w. j  a  va2  s . co  m*/
    return null;
}

From source file:org.springframework.http.server.reactive.ReactorServerHttpRequest.java

License:Apache License

@Override
@Nullable/* w  w  w  . j av  a2s. com*/
protected SslInfo initSslInfo() {
    SslHandler sslHandler = ((Connection) this.request).channel().pipeline().get(SslHandler.class);
    if (sslHandler != null) {
        SSLSession session = sslHandler.engine().getSession();
        return new DefaultSslInfo(session);
    }
    return null;
}

From source file:org.wso2.carbon.transport.http.netty.sender.NettyClientInitializer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    // Add the generic handlers to the pipeline
    // e.g. SSL handler
    if (senderConfiguration.getSslConfig() != null) {
        log.debug("adding ssl handler");
        SslHandler sslHandler = new SSLHandlerFactory(senderConfiguration.getSslConfig()).create();
        sslHandler.engine().setUseClientMode(true);
        ch.pipeline().addLast("ssl", sslHandler);
    }//w  ww.  j a va2  s . c om
    ch.pipeline().addLast("compressor", new HttpContentCompressor());
    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
    ch.pipeline().addLast("chunkWriter", new ChunkedWriteHandler());

    if (senderConfiguration.isDisruptorOn()) {
        log.debug("Register target handler in pipeline which will dispatch events to Disruptor threads");
        handler = new TargetHandler(soTimeOut);
        ch.pipeline().addLast(HANDLER, handler);
    } else {
        log.debug("Register  engine dispatching handler in pipeline ");
        handler = new WorkerPoolDispatchingTargetHandler(soTimeOut, senderConfiguration);
        ch.pipeline().addLast(HANDLER, handler);
    }

}

From source file:reactor.ipc.netty.channel.ContextHandler.java

License:Open Source License

static void addSslAndLogHandlers(NettyOptions<?, ?> options, MonoSink<NettyContext> sink,
        LoggingHandler loggingHandler, boolean secure, ChannelPipeline pipeline) {
    SslHandler sslHandler = secure ? options.getSslHandler(pipeline.channel().alloc()) : null;
    if (sslHandler != null) {
        if (log.isDebugEnabled()) {
            log.debug("SSL enabled using engine {}", sslHandler.engine().getClass().getSimpleName());
        }//from  w w w  . j av  a 2s .c o m
        if (log.isTraceEnabled()) {
            pipeline.addFirst(NettyPipeline.SslLoggingHandler, new LoggingHandler(SslReadHandler.class));
            pipeline.addAfter(NettyPipeline.SslLoggingHandler, NettyPipeline.SslHandler, sslHandler);
        } else {
            pipeline.addFirst(NettyPipeline.SslHandler, sslHandler);
        }
        if (log.isDebugEnabled()) {
            pipeline.addAfter(NettyPipeline.SslHandler, NettyPipeline.LoggingHandler, loggingHandler);
            pipeline.addAfter(NettyPipeline.LoggingHandler, NettyPipeline.SslReader, new SslReadHandler(sink));
        } else {
            pipeline.addAfter(NettyPipeline.SslHandler, NettyPipeline.SslReader, new SslReadHandler(sink));
        }
    } else if (log.isDebugEnabled()) {
        pipeline.addFirst(NettyPipeline.LoggingHandler, loggingHandler);
    }
}