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:http.HTTPClient2.java

License:Open Source License

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

    try {/*ww  w . j a  va2  s .  c  o 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();
    }

}

From source file:http2.bench.netty.NettyServerCommand.java

License:Apache License

public void run() throws Exception {
    Server.run(clearText ? null : (openSSL ? SslProvider.OPENSSL : SslProvider.JDK), port, instances,
            soBacklog);
}

From source file:http2.client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*www.ja  v a 2  s  . c  om*/
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().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)
                .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;
    }

    EventLoopGroup workerGroup = new NioEventLoopGroup();
    Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE);

    try {
        // 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 channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to [" + HOST + ':' + PORT + ']');

        // Wait for the HTTP/2 upgrade to occur.
        Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler();
        http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS);

        HttpResponseHandler responseHandler = initializer.responseHandler();

        int streamId = 3;
        HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP;
        AsciiString hostName = new AsciiString(HOST + ':' + PORT);
        System.err.println("Sending request(s)...");

        if (URL2 != null) {
            logger.info("send url2");
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8)));
            request.headers().add(HttpHeaderNames.HOST, hostName);
            request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name());
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
            request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE);
            responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise());
            streamId += 2;
        }

        responseHandler.awaitResponses(5, TimeUnit.SECONDS);

        System.out.println("Finished HTTP/2 request(s)");

        // Wait until the connection is closed.
        channel.close().syncUninterruptibly();
    } finally {
        workerGroup.shutdownGracefully();
    }
}

From source file:http2.server.Http2Server.java

License:Apache License

public static void main(String[] args) throws Exception {
    System.setProperty("jsse.enableSNIExtension", "true");

    // Configure SSL.
    try {//from  ww w  .  j  av a  2s  .  c om
        String password = "http2";
        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        KeyStore ks = KeyStore.getInstance("PKCS12");
        ks.load(null);
        ks.setKeyEntry("alias", ((KeyPair) getPem(Config.getString("privateKey"))).getPrivate(),
                password.toCharArray(), new java.security.cert.Certificate[] {
                        (X509Certificate) getPem(Config.getString("certificate")) });

        kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, password.toCharArray());
    } catch (Exception e) {
        logger.error("transfer from pem file to pkcs12 failed!", e);
    }

    final SslContext sslCtx;
    if (SSL) {
        SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;

        sslCtx = SslContextBuilder.forServer(kmf).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" : "http")
                + "://127.0.0.1:" + PORT + '/');

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

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

License:Apache License

public DefaultHttpClient(HttpClientConfig config) {
    this.config = config;
    try {//from w  w w  .  j  ava  2s.c  o  m
        SslContextBuilder sslContextBuilder = SslContextBuilder.forClient();

        if (config.getSslSessionCacheSize() > 0) {
            sslContextBuilder.sessionCacheSize(config.getSslSessionCacheSize());
        }

        if (config.getSslSessionTimeout() > 0) {
            sslContextBuilder.sessionTimeout(config.getSslSessionTimeout());
        }

        if (isNonEmpty(config.getEnabledSslProtocols())) {
            sslContextBuilder.protocols(config.getEnabledSslProtocols());
        }

        if (isNonEmpty(config.getEnabledSslCipherSuites())) {
            sslContextBuilder.ciphers(Arrays.asList(config.getEnabledSslCipherSuites()));
        } else if (!config.isFilterInsecureCipherSuites()) {
            sslContextBuilder.ciphers(null, IdentityCipherSuiteFilter.INSTANCE_DEFAULTING_TO_SUPPORTED_CIPHERS);
        }

        sslContextBuilder.sslProvider(config.isUseOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK)
                .keyManager(config.getKeyManagerFactory()).trustManager(config.getTrustManagerFactory());

        this.sslContext = sslContextBuilder.build();

        this.alpnSslContext = sslContextBuilder.applicationProtocolConfig(
                new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                        // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                        ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                        // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                        ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                        ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
                .build();

    } catch (SSLException e) {
        throw new IllegalArgumentException("Impossible to create SslContext", e);
    }

    DefaultThreadFactory threadFactory = new DefaultThreadFactory(config.getThreadPoolName());
    eventLoopGroup = config.isUseNativeTransport() ? new EpollEventLoopGroup(0, threadFactory)
            : new NioEventLoopGroup(0, threadFactory);
    eventLoopPicker = new AffinityEventLoopPicker(eventLoopGroup);
    channelGroup = new DefaultChannelGroup(eventLoopGroup.next());
}

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

License:Apache License

/**
 * Set ciphers and APN appropriate for gRPC. Precisely what is set is permitted to change, so if
 * an application requires particular settings it should override the options set here.
 *///from w  w  w  .  j  a  va2s.c  o m
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/1784")
@CanIgnoreReturnValue
public static SslContextBuilder configure(SslContextBuilder builder, SslProvider provider) {
    switch (provider) {
    case JDK: {
        Provider jdkProvider = findJdkProvider();
        if (jdkProvider == null) {
            throw new IllegalArgumentException(
                    "Could not find Jetty NPN/ALPN or Conscrypt as installed JDK providers");
        }
        return configure(builder, jdkProvider);
    }
    case OPENSSL: {
        ApplicationProtocolConfig apc;
        if (OpenSsl.isAlpnSupported()) {
            apc = NPN_AND_ALPN;
        } else {
            apc = NPN;
        }
        return builder.sslProvider(SslProvider.OPENSSL)
                .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
                .applicationProtocolConfig(apc);
    }
    default:
        throw new IllegalArgumentException("Unsupported provider: " + provider);
    }
}

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

License:Apache License

/**
 * Returns OpenSSL if available, otherwise returns the JDK provider.
 *//* w  ww  .ja va 2  s. c om*/
private static SslProvider defaultSslProvider() {
    if (OpenSsl.isAvailable()) {
        logger.log(Level.FINE, "Selecting OPENSSL");
        return SslProvider.OPENSSL;
    }
    Provider provider = findJdkProvider();
    if (provider != null) {
        logger.log(Level.FINE, "Selecting JDK with provider {0}", provider);
        return SslProvider.JDK;
    }
    logger.log(Level.INFO, "netty-tcnative unavailable (this may be normal)", OpenSsl.unavailabilityCause());
    logger.log(Level.INFO, "Conscrypt not found (this may be normal)");
    logger.log(Level.INFO, "Jetty ALPN unavailable (this may be normal)",
            JettyTlsUtil.getJettyAlpnUnavailabilityCause());
    throw new IllegalStateException("Could not find TLS ALPN provider; "
            + "no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available");
}

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

License:Apache License

@Before
public void setUp() throws NoSuchAlgorithmException {
    executor = Executors.newSingleThreadScheduledExecutor();
    switch (tlsImpl) {
    case TCNATIVE:
        Assume.assumeTrue(OpenSsl.isAvailable());
        sslProvider = SslProvider.OPENSSL;
        break;/*w w  w.  ja  va  2s .co m*/
    case JDK:
        Assume.assumeTrue(Arrays.asList(SSLContext.getDefault().getSupportedSSLParameters().getCipherSuites())
                .contains("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"));
        sslProvider = SslProvider.JDK;
        jdkProvider = Security.getProvider("SunJSSE");
        Assume.assumeNotNull(jdkProvider);
        try {
            // Check for presence of an (ironic) class added in Java 9
            Class.forName("java.lang.Runtime$Version");
            // Java 9+
        } catch (ClassNotFoundException ignored) {
            // Before Java 9
            try {
                GrpcSslContexts.configure(SslContextBuilder.forClient(), jdkProvider);
            } catch (IllegalArgumentException ex) {
                Assume.assumeNoException("Not Java 9+ and Jetty ALPN does not seem available", ex);
            }
        }
        break;
    case CONSCRYPT:
        sslProvider = SslProvider.JDK;
        jdkProvider = Security.getProvider("Conscrypt");
        Assume.assumeNotNull(jdkProvider);
        break;
    default:
        throw new AssertionError();
    }
    clientContextBuilder = SslContextBuilder.forClient();
    if (sslProvider == SslProvider.JDK) {
        GrpcSslContexts.configure(clientContextBuilder, jdkProvider);
    } else {
        GrpcSslContexts.configure(clientContextBuilder, sslProvider);
    }
}

From source file:io.hekate.network.internal.NettySslUtils.java

License:Apache License

private static KeyManagerFactory keyManager(NetworkSslConfig cfg, ResourceService res)
        throws GeneralSecurityException, IOException, ResourceLoadingException {
    KeyManagerFactory factory;//from  w  w  w. ja  va2s .c  o  m

    if (cfg.getKeyStoreAlgorithm() == null || cfg.getKeyStoreAlgorithm().isEmpty()) {
        if (provider(cfg) == SslProvider.OPENSSL) {
            factory = new OpenSslX509KeyManagerFactory();
        } else {
            factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        }
    } else {
        if (provider(cfg) == SslProvider.OPENSSL) {
            factory = new OpenSslX509KeyManagerFactory(cfg.getKeyStoreAlgorithm(), null);
        } else {
            factory = KeyManagerFactory.getInstance(cfg.getKeyStoreAlgorithm());
        }
    }

    KeyStore store = keyStore(cfg.getKeyStorePath(), cfg.getKeyStorePassword(), cfg.getKeyStoreType(), res);

    factory.init(store, cfg.getKeyStorePassword().toCharArray());

    return factory;
}

From source file:io.hekate.network.internal.NettySslUtils.java

License:Apache License

private static SslProvider provider(NetworkSslConfig cfg) {
    switch (cfg.getProvider()) {
    case AUTO: {/*from ww  w  .  ja  va2s . c o m*/
        return OpenSsl.isAvailable() ? SslProvider.OPENSSL : SslProvider.JDK;
    }
    case JDK: {
        return SslProvider.JDK;
    }
    case OPEN_SSL: {
        return SslProvider.OPENSSL;
    }
    default: {
        throw new IllegalArgumentException("Unexpected SSL provider: " + cfg.getProvider());
    }
    }
}