Example usage for io.netty.handler.ssl SslProvider OPENSSL

List of usage examples for io.netty.handler.ssl SslProvider OPENSSL

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslProvider OPENSSL.

Prototype

SslProvider OPENSSL

To view the source code for io.netty.handler.ssl SslProvider OPENSSL.

Click Source Link

Document

OpenSSL-based implementation.

Usage

From source file:com.linecorp.armeria.server.AbstractVirtualHostBuilder.java

License:Apache License

/**
 * Configures SSL or TLS of this {@link VirtualHost} with the specified {@code keyCertChainFile},
 * {@code keyFile} and {@code keyPassword}.
 *//*from w  w w. j a v a2 s  .  co m*/
public B tls(File keyCertChainFile, File keyFile, @Nullable String keyPassword) throws SSLException {
    if (!keyCertChainFile.exists()) {
        throw new SSLException("non-existent certificate chain file: " + keyCertChainFile);
    }
    if (!keyCertChainFile.canRead()) {
        throw new SSLException("cannot read certificate chain file: " + keyCertChainFile);
    }
    if (!keyFile.exists()) {
        throw new SSLException("non-existent key file: " + keyFile);
    }
    if (!keyFile.canRead()) {
        throw new SSLException("cannot read key file: " + keyFile);
    }

    final SslContext sslCtx;

    try {
        sslCtx = BouncyCastleKeyFactoryProvider.call(() -> {
            final SslContextBuilder builder = SslContextBuilder.forServer(keyCertChainFile, keyFile,
                    keyPassword);

            builder.sslProvider(Flags.useOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK);
            builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE);
            builder.applicationProtocolConfig(HTTPS_ALPN_CFG);

            return builder.build();
        });
    } catch (RuntimeException | SSLException e) {
        throw e;
    } catch (Exception e) {
        throw new SSLException("failed to configure TLS: " + e, e);
    }

    tls(sslCtx);
    return self();
}

From source file:com.linecorp.armeria.server.VirtualHostBuilder.java

License:Apache License

/**
 * Sets the {@link SslContext} of this {@link VirtualHost} from the specified {@link SessionProtocol},
 * {@code keyCertChainFile}, {@code keyFile} and {@code keyPassword}.
 *///from   w w  w.  j  a  v  a2  s  .co  m
public VirtualHostBuilder sslContext(SessionProtocol protocol, File keyCertChainFile, File keyFile,
        String keyPassword) throws SSLException {

    if (requireNonNull(protocol, "protocol") != SessionProtocol.HTTPS) {
        throw new IllegalArgumentException("unsupported protocol: " + protocol);
    }

    final SslContextBuilder builder = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword);

    builder.sslProvider(NativeLibraries.isOpenSslAvailable() ? SslProvider.OPENSSL : SslProvider.JDK);
    builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE);
    builder.applicationProtocolConfig(HTTPS_ALPN_CFG);

    sslContext(builder.build());

    return this;
}

From source file:com.relayrides.pushy.apns.ApnsClientBuilder.java

License:Open Source License

/**
 * Constructs a new {@link ApnsClient} with the previously-set configuration.
 *
 * @return a new ApnsClient instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new client for any reason
 *
 * @since 0.8//from   www  .  jav  a  2s.  c  o m
 */
public ApnsClient build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (this.preferredSslProvider != null) {
            sslProvider = this.preferredSslProvider;
        } else {
            if (OpenSsl.isAvailable()) {
                if (OpenSsl.isAlpnSupported()) {
                    log.info("Native SSL provider is available and supports ALPN; will use native provider.");
                    sslProvider = SslProvider.OPENSSL;
                } else {
                    log.info(
                            "Native SSL provider is available, but does not support ALPN; will use JDK SSL provider.");
                    sslProvider = SslProvider.JDK;
                }
            } else {
                log.info("Native SSL provider not available; will use JDK SSL provider.");
                sslProvider = SslProvider.JDK;
            }
        }

        final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(
                        new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE,
                                SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2));

        if (this.trustedServerCertificatePemFile != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificatePemFile);
        } else if (this.trustedServerCertificateInputStream != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificateInputStream);
        } else if (this.trustedServerCertificates != null) {
            sslContextBuilder.trustManager(this.trustedServerCertificates);
        }

        sslContext = sslContextBuilder.build();
    }

    final ApnsClient apnsClient = new ApnsClient(sslContext, this.eventLoopGroup);

    apnsClient.setMetricsListener(this.metricsListener);
    apnsClient.setProxyHandlerFactory(this.proxyHandlerFactory);

    if (this.connectionTimeout != null) {
        apnsClient.setConnectionTimeout((int) this.connectionTimeoutUnit.toMillis(this.connectionTimeout));
    }

    if (this.writeTimeout != null) {
        apnsClient.setWriteTimeout(this.writeTimeoutUnit.toMillis(this.writeTimeout));
    }

    if (this.gracefulShutdownTimeout != null) {
        apnsClient.setGracefulShutdownTimeout(
                this.gracefulShutdownTimeoutUnit.toMillis(this.gracefulShutdownTimeout));
    }

    return apnsClient;
}

From source file:com.relayrides.pushy.apns.MockApnsServerBuilder.java

License:Open Source License

/**
 * Constructs a new {@link MockApnsServer} with the previously-set configuration.
 *
 * @return a new MockApnsServer instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new server for any reason
 *
 * @since 0.8//  w  w  w . j  a v  a 2  s. c o m
 */
public MockApnsServer build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (this.preferredSslProvider != null) {
            sslProvider = this.preferredSslProvider;
        } else {
            if (OpenSsl.isAvailable()) {
                if (OpenSsl.isAlpnSupported()) {
                    log.info("Native SSL provider is available and supports ALPN; will use native provider.");
                    sslProvider = SslProvider.OPENSSL;
                } else {
                    log.info(
                            "Native SSL provider is available, but does not support ALPN; will use JDK SSL provider.");
                    sslProvider = SslProvider.JDK;
                }
            } else {
                log.info("Native SSL provider not available; will use JDK SSL provider.");
                sslProvider = SslProvider.JDK;
            }
        }

        final SslContextBuilder sslContextBuilder;

        if (this.certificateChain != null && this.privateKey != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword,
                    this.certificateChain);
        } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile,
                    this.privateKeyPkcs8File, this.privateKeyPassword);
        } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream,
                    this.privateKeyPkcs8InputStream, this.privateKeyPassword);
        } else {
            throw new IllegalStateException("Must specify server credentials before building a mock server.");
        }

        sslContextBuilder.sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL).applicationProtocolConfig(
                        new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE,
                                SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2));

        sslContext = sslContextBuilder.build();
    }

    final MockApnsServer server = new MockApnsServer(sslContext, this.eventLoopGroup);
    server.setEmulateInternalErrors(this.emulateInternalErrors);

    return server;
}

From source file:com.turo.pushy.apns.BenchmarkApnsServer.java

License:Open Source License

public BenchmarkApnsServer(final InputStream certificateChainInputStream,
        final InputStream privateKeyPkcs8InputStream, final NioEventLoopGroup eventLoopGroup)
        throws SSLException {
    final SslContext sslContext;
    {//from   w w w  .  j  ava2  s  .  com
        final SslProvider sslProvider;

        if (OpenSsl.isAvailable()) {
            if (OpenSsl.isAlpnSupported()) {
                sslProvider = SslProvider.OPENSSL;
            } else {
                sslProvider = SslProvider.JDK;
            }
        } else {
            sslProvider = SslProvider.JDK;
        }

        sslContext = SslContextBuilder.forServer(certificateChainInputStream, privateKeyPkcs8InputStream, null)
                .sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL)
                .applicationProtocolConfig(
                        new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                                ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                                ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                                ApplicationProtocolNames.HTTP_2))
                .build();
    }

    this.bootstrap = new ServerBootstrap();
    this.bootstrap.group(eventLoopGroup);

    this.bootstrap.channel(NioServerSocketChannel.class);
    this.bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(final SocketChannel channel) throws Exception {
            final SslHandler sslHandler = sslContext.newHandler(channel.alloc());
            channel.pipeline().addLast(sslHandler);
            channel.pipeline()
                    .addLast(new ApplicationProtocolNegotiationHandler(ApplicationProtocolNames.HTTP_1_1) {

                        @Override
                        protected void configurePipeline(final ChannelHandlerContext context,
                                final String protocol) throws Exception {
                            if (ApplicationProtocolNames.HTTP_2.equals(protocol)) {
                                context.pipeline().addLast(
                                        new BenchmarkApnsServerHandler.BenchmarkApnsServerHandlerBuilder()
                                                .initialSettings(new Http2Settings()
                                                        .maxConcurrentStreams(MAX_CONCURRENT_STREAMS))
                                                .build());

                                BenchmarkApnsServer.this.allChannels.add(context.channel());
                            } else {
                                throw new IllegalStateException("Unexpected protocol: " + protocol);
                            }
                        }
                    });
        }
    });
}

From source file:com.turo.pushy.apns.server.BaseHttp2ServerBuilder.java

License:Open Source License

/**
 * Constructs a new server with the previously-set configuration.
 *
 * @return a new server instance with the previously-set configuration
 *
 * @throws SSLException if an SSL context could not be created for the new server for any reason
 *
 * @since 0.8// w  w w.ja  v  a 2  s .c  o m
 */
public T build() throws SSLException {
    final SslContext sslContext;
    {
        final SslProvider sslProvider;

        if (OpenSsl.isAvailable()) {
            log.info("Native SSL provider is available; will use native provider.");
            sslProvider = SslProvider.OPENSSL;
        } else {
            log.info("Native SSL provider not available; will use JDK SSL provider.");
            sslProvider = SslProvider.JDK;
        }

        final SslContextBuilder sslContextBuilder;

        if (this.certificateChain != null && this.privateKey != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword,
                    this.certificateChain);
        } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile,
                    this.privateKeyPkcs8File, this.privateKeyPassword);
        } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) {
            sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream,
                    this.privateKeyPkcs8InputStream, this.privateKeyPassword);
        } else {
            throw new IllegalStateException("Must specify server credentials before building a mock server.");
        }

        sslContextBuilder.sslProvider(sslProvider)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .clientAuth(ClientAuth.OPTIONAL);

        if (this.trustedClientCertificatePemFile != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificatePemFile);
        } else if (this.trustedClientCertificateInputStream != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificateInputStream);
        } else if (this.trustedClientCertificates != null) {
            sslContextBuilder.trustManager(this.trustedClientCertificates);
        }

        if (this.useAlpn) {
            sslContextBuilder.applicationProtocolConfig(
                    new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                            ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                            ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                            ApplicationProtocolNames.HTTP_2));
        }

        sslContext = sslContextBuilder.build();
    }

    final T server = this.constructServer(sslContext);

    if (sslContext instanceof ReferenceCounted) {
        ((ReferenceCounted) sslContext).release();
    }

    return server;
}

From source file:com.turo.pushy.apns.SslUtil.java

License:Open Source License

/**
 * Selects an SSL provider based on the availability of of an ALPN-capable native provider.
 *
 * @return an ALPN-capable native SSL provider if available, or else the JDK SSL provider
 *//*from  w  w  w .  j a  v  a2s .co  m*/
public static SslProvider getSslProvider() {
    final SslProvider sslProvider;

    if (OpenSsl.isAvailable()) {
        if (OpenSsl.isAlpnSupported()) {
            log.info("Native SSL provider is available and supports ALPN; will use native provider.");
            sslProvider = SslProvider.OPENSSL;
        } else {
            log.info("Native SSL provider is available, but does not support ALPN; will use JDK SSL provider.");
            sslProvider = SslProvider.JDK;
        }
    } else {
        log.info("Native SSL provider not available; will use JDK SSL provider.");
        sslProvider = SslProvider.JDK;
    }

    return sslProvider;
}

From source file:com.vela.iot.active.netty.http2.server.Http2Server.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  w  ww . j  a  va2s  .  c o  m
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider)
                /*
                * NOTE: the cipher filter may not include all ciphers
                * required by the HTTP/2 specification. Please refer to the
                * HTTP/2 specification for cipher requirements.
                */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode
                        // supported by both OpenSsl and JDK
                        // providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode
                        // supported by both OpenSsl and JDK
                        // providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }
    // Configure the server.
    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup(7);
    try {
        LastInboundHandler serverLastInboundHandler = new SharableLastInboundHandler();
        ServerBootstrap b = new ServerBootstrap();
        // BACKLOG?ServerSocket?????1Java50
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(new Http2Codec(true, serverLastInboundHandler));
                        //p.addLast(new HttpContentCompressor(1));
                        p.addLast(new HelloWorldHttp2HandlerBuilder().build());
                    }
                });

        Channel ch = b.bind(HOST, PORT).sync().channel();

        System.err.println("Open your HTTP/2-enabled web browser and navigate to " + (SSL ? "https" : "http")
                + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }
}

From source file:example.http2.helloworld.frame.server.Http2Server.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {//from  w ww  .j  a v  a  2 s .  c  om
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(provider)
                /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification.
                 * Please refer to the HTTP/2 specification for cipher requirements. */
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                        ApplicationProtocolNames.HTTP_1_1))
                .build();
    } else {
        sslCtx = null;
    }
    // Configure the server.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap();
        b.option(ChannelOption.SO_BACKLOG, 1024);
        b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))
                .childHandler(new Http2ServerInitializer(sslCtx));

        Channel ch = b.bind(PORT).sync().channel();

        System.err.println("Open your HTTP/2-enabled web browser and navigate to "
                + (SSL ? "https" : "example/http") + "://127.0.0.1:" + PORT + '/');

        ch.closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}

From source file:http.HTTPClient.java

License:Open Source License

public HTTPClient(boolean ssl, String host, int port) throws Exception {

    try {/*from ww w.  j  av  a  2 s  .co m*/

        final SslContext sslCtx;
        if (ssl) {
            SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
            sslCtx = SslContextBuilder.forClient().sslProvider(provider)
                    .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE)
                    .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN,
                            // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                            SelectorFailureBehavior.NO_ADVERTISE,
                            // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                            SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2,
                            ApplicationProtocolNames.HTTP_1_1))
                    .build();
        } else {
            sslCtx = null;
        }
        workerGroup = new NioEventLoopGroup();
        HTTPClientInitializer initializer = new HTTPClientInitializer(sslCtx, Integer.MAX_VALUE);

        // Configure the client.
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(host, port);
        b.handler(initializer);

        // Start the client.
        channel = b.connect().syncUninterruptibly().channel();
        log.info("Connected to [" + host + ':' + port + ']');

        // Wait for the HTTP/2 upgrade to occur.
        //            HTTPSettingsHandler http2SettingsHandler = initializer.settingsHandler();
        //            http2SettingsHandler.awaitSettings(TestUtil.HTTP2_RESPONSE_TIME_OUT, TestUtil.HTTP2_RESPONSE_TIME_UNIT);
        //            responseHandler = initializer.responseHandler();
        scheme = ssl ? HttpScheme.HTTPS : HttpScheme.HTTP;
        hostName = new AsciiString(host + ':' + port);

    } catch (Exception ex) {
        log.error("Error while initializing http2 client " + ex);
        this.close();
    }

}