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.vertx.core.net.impl.VertxSniHandler.java

License:Open Source License

@Override
protected void replaceHandler(ChannelHandlerContext ctx, String hostname, SslContext sslContext)
        throws Exception {
    SslHandler sslHandler = null;
    try {/*from w  w w  . j  a  v  a2 s. co  m*/
        SSLEngine engine = helper.createEngine(sslContext);
        sslHandler = new SslHandler(engine);
        ctx.pipeline().replace(this, "ssl", sslHandler);
        Future<Channel> fut = sslHandler.handshakeFuture();
        fut.addListener(future -> {
            if (future.isSuccess()) {
                Attribute<String> val = ctx.channel().attr(SERVER_NAME_ATTR);
                val.set(hostname);
                handshakeFuture.setSuccess(ctx.channel());
            } else {
                handshakeFuture.setFailure(future.cause());
            }
        });
        sslHandler = null;
    } finally {
        // Since the SslHandler was not inserted into the pipeline the ownership of the SSLEngine was not
        // transferred to the SslHandler.
        // See https://github.com/netty/netty/issues/5678
        if (sslHandler != null) {
            ReferenceCountUtil.safeRelease(sslHandler.engine());
        }
    }
}

From source file:me.melchor9000.net.SSLSocket.java

License:Open Source License

/**
 * <p>Creates a SSL socket using the custom options you set in the
 * {@link SSLSocketConfigurator#configure(SslContextBuilder)} method.
 * All methods available can be found in <a href="https://netty.io/4.1/api/io/netty/handler/ssl/SslContextBuilder.html">
 * SslContextBuilder</a>.</p>
 * <p>For enable host identification for HTTPS, you should override
 * {@link SSLSocketConfigurator#changeParameters(SSLParameters)} and set the option
 * {@link SSLParameters#setEndpointIdentificationAlgorithm(String)} to {@code "HTTPS"}</p>
 * @param service {@link IOService} to attach this socket
 * @param conf Custom configuration set in {@link SSLSocketConfigurator}
 *//*from w w w  .j  av a2 s .  c  o m*/
public SSLSocket(@NotNull IOService service, @NotNull final SSLSocketConfigurator conf) {
    super(service);
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            SslContextBuilder ctx = SslContextBuilder.forClient();
            conf.configure(ctx);
            SslHandler handler = ctx.build().newHandler(ch.alloc());
            SSLParameters p = handler.engine().getSSLParameters();
            SSLParameters np = conf.changeParameters(p);
            if (np != null)
                handler.engine().setSSLParameters(np);
            ch.pipeline().addLast("readManager", readManager);
            ch.pipeline().addBefore("readManager", "ssl", handler);
        }
    });
}

From source file:me.melchor9000.net.SSLSocket.java

License:Open Source License

SSLSocket(SSLAcceptor acceptor, SocketChannel socket, SSLAcceptorConfigurator configurator)
        throws SSLException {
    super(acceptor, socket);
    SslContextBuilder builder = SslContextBuilder.forServer(configurator.getFactory());
    configurator.configure(builder);//from w  ww  .  j  ava2  s . c  o m
    SslHandler handler = builder.build().newHandler(socket.alloc());
    SSLParameters p = handler.engine().getSSLParameters();
    SSLParameters np = configurator.changeParameters(p);
    if (np != null)
        handler.engine().setSSLParameters(np);
    socket.pipeline().addBefore("readManager", "ssl", handler);
}

From source file:org.apache.activemq.artemis.core.remoting.CertificateUtil.java

License:Apache License

public static Principal getPeerPrincipalFromConnection(RemotingConnection remotingConnection) {
    Principal result = null;//w  w w. j  a va2 s . c o  m
    if (remotingConnection != null) {
        Connection transportConnection = remotingConnection.getTransportConnection();
        if (transportConnection instanceof NettyConnection) {
            NettyConnection nettyConnection = (NettyConnection) transportConnection;
            ChannelHandler channelHandler = nettyConnection.getChannel().pipeline().get("ssl");
            if (channelHandler != null && channelHandler instanceof SslHandler) {
                SslHandler sslHandler = (SslHandler) channelHandler;
                try {
                    result = sslHandler.engine().getSession().getPeerPrincipal();
                } catch (SSLPeerUnverifiedException ignored) {
                }
            }
        }
    }

    return result;
}

From source file:org.apache.activemq.artemis.utils.CertificateUtil.java

License:Apache License

public static X509Certificate[] getCertsFromChannel(Channel channel) {
    X509Certificate[] certificates = null;
    ChannelHandler channelHandler = channel.pipeline().get("ssl");
    if (channelHandler != null && channelHandler instanceof SslHandler) {
        SslHandler sslHandler = (SslHandler) channelHandler;
        try {/* w  w w.  j  a va2s.co  m*/
            certificates = sslHandler.engine().getSession().getPeerCertificateChain();
        } catch (SSLPeerUnverifiedException e) {
            // ignore
        }
    }

    return certificates;
}

From source file:org.apache.activemq.transport.amqp.client.transport.NettyTcpTransport.java

License:Apache License

@Override
public Principal getLocalPrincipal() {
    Principal result = null;/*from  www  . jav  a 2s  .c  o m*/

    if (isSSL()) {
        SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
        result = sslHandler.engine().getSession().getLocalPrincipal();
    }

    return result;
}

From source file:org.apache.bookkeeper.proto.BookieRequestProcessor.java

License:Apache License

private void processStartTLSRequestV3(final BookkeeperProtocol.Request r, final Channel c) {
    BookkeeperProtocol.Response.Builder response = BookkeeperProtocol.Response.newBuilder();
    BookkeeperProtocol.BKPacketHeader.Builder header = BookkeeperProtocol.BKPacketHeader.newBuilder();
    header.setVersion(BookkeeperProtocol.ProtocolVersion.VERSION_THREE);
    header.setOperation(r.getHeader().getOperation());
    header.setTxnId(r.getHeader().getTxnId());
    response.setHeader(header.build());/*  w  ww  . j a  va 2  s .  com*/
    if (shFactory == null) {
        LOG.error("Got StartTLS request but TLS not configured");
        response.setStatus(BookkeeperProtocol.StatusCode.EBADREQ);
        c.writeAndFlush(response.build());
    } else {
        // there is no need to execute in a different thread as this operation is light
        SslHandler sslHandler = shFactory.newTLSHandler();
        c.pipeline().addFirst("tls", sslHandler);

        response.setStatus(BookkeeperProtocol.StatusCode.EOK);
        BookkeeperProtocol.StartTLSResponse.Builder builder = BookkeeperProtocol.StartTLSResponse.newBuilder();
        response.setStartTLSResponse(builder.build());
        sslHandler.handshakeFuture().addListener(new GenericFutureListener<Future<Channel>>() {
            @Override
            public void operationComplete(Future<Channel> future) throws Exception {
                // notify the AuthPlugin the completion of the handshake, even in case of failure
                AuthHandler.ServerSideHandler authHandler = c.pipeline()
                        .get(AuthHandler.ServerSideHandler.class);
                authHandler.authProvider.onProtocolUpgrade();
                if (future.isSuccess()) {
                    LOG.info("Session is protected by: {}", sslHandler.engine().getSession().getCipherSuite());
                } else {
                    LOG.error("TLS Handshake failure: {}", future.cause());
                    BookkeeperProtocol.Response.Builder errResponse = BookkeeperProtocol.Response.newBuilder()
                            .setHeader(r.getHeader()).setStatus(BookkeeperProtocol.StatusCode.EIO);
                    c.writeAndFlush(errResponse.build());
                    if (statsEnabled) {
                        bkStats.getOpStats(BKStats.STATS_UNKNOWN).incrementFailedOps();
                    }
                }
            }
        });
        c.writeAndFlush(response.build());
    }
}

From source file:org.apache.bookkeeper.proto.PerChannelBookieClient.java

License:Apache License

public PerChannelBookieClient(ClientConfiguration conf, OrderedExecutor executor, EventLoopGroup eventLoopGroup,
        ByteBufAllocator allocator, BookieSocketAddress addr, StatsLogger parentStatsLogger,
        ClientAuthProvider.Factory authProviderFactory, ExtensionRegistry extRegistry,
        PerChannelBookieClientPool pcbcPool, SecurityHandlerFactory shFactory) throws SecurityException {
    this.maxFrameSize = conf.getNettyMaxFrameSizeBytes();
    this.conf = conf;
    this.addr = addr;
    this.executor = executor;
    if (LocalBookiesRegistry.isLocalBookie(addr)) {
        this.eventLoopGroup = new DefaultEventLoopGroup();
    } else {//  w  ww.  ja  va 2s . c  om
        this.eventLoopGroup = eventLoopGroup;
    }
    this.allocator = allocator;
    this.state = ConnectionState.DISCONNECTED;
    this.addEntryTimeoutNanos = TimeUnit.SECONDS.toNanos(conf.getAddEntryTimeout());
    this.readEntryTimeoutNanos = TimeUnit.SECONDS.toNanos(conf.getReadEntryTimeout());
    this.getBookieInfoTimeout = conf.getBookieInfoTimeout();
    this.startTLSTimeout = conf.getStartTLSTimeout();
    this.useV2WireProtocol = conf.getUseV2WireProtocol();
    this.preserveMdcForTaskExecution = conf.getPreserveMdcForTaskExecution();

    this.authProviderFactory = authProviderFactory;
    this.extRegistry = extRegistry;
    this.shFactory = shFactory;
    if (shFactory != null) {
        shFactory.init(NodeType.Client, conf, allocator);
    }

    StringBuilder nameBuilder = new StringBuilder();
    nameBuilder.append(addr.getHostName().replace('.', '_').replace('-', '_')).append("_")
            .append(addr.getPort());

    this.statsLogger = parentStatsLogger.scope(BookKeeperClientStats.CHANNEL_SCOPE)
            .scope(nameBuilder.toString());

    readEntryOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_READ_OP);
    addEntryOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_ADD_OP);
    writeLacOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_WRITE_LAC_OP);
    forceLedgerOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_FORCE_OP);
    readLacOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_READ_LAC_OP);
    getBookieInfoOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.GET_BOOKIE_INFO_OP);
    getListOfEntriesOfLedgerCompletionOpLogger = statsLogger
            .getOpStatsLogger(BookKeeperClientStats.GET_LIST_OF_ENTRIES_OF_LEDGER_OP);
    readTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_READ);
    addTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_ADD);
    writeLacTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_WRITE_LAC);
    forceLedgerTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_FORCE);
    readLacTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_READ_LAC);
    getBookieInfoTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.TIMEOUT_GET_BOOKIE_INFO);
    startTLSOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_START_TLS_OP);
    startTLSTimeoutOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.CHANNEL_TIMEOUT_START_TLS_OP);
    getListOfEntriesOfLedgerCompletionTimeoutOpLogger = statsLogger
            .getOpStatsLogger(BookKeeperClientStats.TIMEOUT_GET_LIST_OF_ENTRIES_OF_LEDGER);
    exceptionCounter = statsLogger.getCounter(BookKeeperClientStats.NETTY_EXCEPTION_CNT);
    connectTimer = statsLogger.getOpStatsLogger(BookKeeperClientStats.CLIENT_CONNECT_TIMER);
    addEntryOutstanding = statsLogger.getCounter(BookKeeperClientStats.ADD_OP_OUTSTANDING);
    readEntryOutstanding = statsLogger.getCounter(BookKeeperClientStats.READ_OP_OUTSTANDING);
    nettyOpLogger = statsLogger.getOpStatsLogger(BookKeeperClientStats.NETTY_OPS);
    activeNonTlsChannelCounter = statsLogger.getCounter(BookKeeperClientStats.ACTIVE_NON_TLS_CHANNEL_COUNTER);
    activeTlsChannelCounter = statsLogger.getCounter(BookKeeperClientStats.ACTIVE_TLS_CHANNEL_COUNTER);
    failedConnectionCounter = statsLogger.getCounter(BookKeeperClientStats.FAILED_CONNECTION_COUNTER);
    failedTlsHandshakeCounter = statsLogger.getCounter(BookKeeperClientStats.FAILED_TLS_HANDSHAKE_COUNTER);

    this.pcbcPool = pcbcPool;

    this.connectionPeer = new ClientConnectionPeer() {

        @Override
        public SocketAddress getRemoteAddr() {
            Channel c = channel;
            if (c != null) {
                return c.remoteAddress();
            } else {
                return null;
            }
        }

        @Override
        public Collection<Object> getProtocolPrincipals() {
            Channel c = channel;
            if (c == null) {
                return Collections.emptyList();
            }
            SslHandler ssl = c.pipeline().get(SslHandler.class);
            if (ssl == null) {
                return Collections.emptyList();
            }
            try {
                Certificate[] certificates = ssl.engine().getSession().getPeerCertificates();
                if (certificates == null) {
                    return Collections.emptyList();
                }
                List<Object> result = new ArrayList<>();
                result.addAll(Arrays.asList(certificates));
                return result;
            } catch (SSLPeerUnverifiedException err) {
                return Collections.emptyList();
            }
        }

        @Override
        public void disconnect() {
            Channel c = channel;
            if (c != null) {
                c.close().addListener(x -> makeWritable());
            }
            LOG.info("authplugin disconnected channel {}", channel);
        }

        @Override
        public void setAuthorizedId(BookKeeperPrincipal principal) {
            authorizedId = principal;
            LOG.info("connection {} authenticated as {}", channel, principal);
        }

        @Override
        public BookKeeperPrincipal getAuthorizedId() {
            return authorizedId;
        }

        @Override
        public boolean isSecure() {
            Channel c = channel;
            if (c == null) {
                return false;
            } else {
                return c.pipeline().get(SslHandler.class) != null;
            }
        }

    };
}

From source file:org.apache.bookkeeper.tls.TLSContextFactory.java

License:Apache License

@Override
public SslHandler newTLSHandler() {
    SslHandler sslHandler = sslContext.newHandler(allocator);

    if (protocols != null && protocols.length != 0) {
        sslHandler.engine().setEnabledProtocols(protocols);
    }//from w  ww . java 2s.c om
    if (LOG.isDebugEnabled()) {
        LOG.debug("Enabled cipher protocols: {} ", Arrays.toString(sslHandler.engine().getEnabledProtocols()));
    }

    if (ciphers != null && ciphers.length != 0) {
        sslHandler.engine().setEnabledCipherSuites(ciphers);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Enabled cipher suites: {} ", Arrays.toString(sslHandler.engine().getEnabledCipherSuites()));
    }

    return sslHandler;
}

From source file:org.apache.camel.component.netty4.NettyEndpoint.java

License:Apache License

protected SSLSession getSSLSession(ChannelHandlerContext ctx) {
    final SslHandler sslHandler = ctx.pipeline().get(SslHandler.class);
    SSLSession sslSession = null;
    if (sslHandler != null) {
        sslSession = sslHandler.engine().getSession();
    }/*from ww  w. j  a v a2  s.  co  m*/
    return sslSession;
}