Example usage for io.netty.handler.ssl SslContextBuilder forClient

List of usage examples for io.netty.handler.ssl SslContextBuilder forClient

Introduction

In this page you can find the example usage for io.netty.handler.ssl SslContextBuilder forClient.

Prototype

public static SslContextBuilder forClient() 

Source Link

Document

Creates a builder for new client-side SslContext .

Usage

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

License:Apache License

public DefaultHttpClient(HttpClientConfig config) {
    this.config = config;
    try {/*from  ww w.  j  a v  a 2  s .c  om*/
        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

/**
 * Creates an SslContextBuilder with ciphers and APN appropriate for gRPC.
 *
 * @see SslContextBuilder#forClient()//  w  w  w.  j a v  a 2s. c  o  m
 * @see #configure(SslContextBuilder)
 */
public static SslContextBuilder forClient() {
    return configure(SslContextBuilder.forClient());
}

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

License:Apache License

@Test
public void clientTlsHandler_firesNegotiation() throws Exception {
    SelfSignedCertificate cert = new SelfSignedCertificate("authority");
    SslContext clientSslContext = GrpcSslContexts
            .configure(SslContextBuilder.forClient().trustManager(cert.cert())).build();
    SslContext serverSslContext = GrpcSslContexts
            .configure(SslContextBuilder.forServer(cert.key(), cert.cert())).build();
    FakeGrpcHttp2ConnectionHandler gh = FakeGrpcHttp2ConnectionHandler.newHandler();

    ClientTlsProtocolNegotiator pn = new ClientTlsProtocolNegotiator(clientSslContext);
    WriteBufferingAndExceptionHandler clientWbaeh = new WriteBufferingAndExceptionHandler(pn.newHandler(gh));

    SocketAddress addr = new LocalAddress("addr");

    ChannelHandler sh = ProtocolNegotiators.serverTls(serverSslContext)
            .newHandler(FakeGrpcHttp2ConnectionHandler.noopHandler());
    WriteBufferingAndExceptionHandler serverWbaeh = new WriteBufferingAndExceptionHandler(sh);
    Channel s = new ServerBootstrap().childHandler(serverWbaeh).group(group).channel(LocalServerChannel.class)
            .bind(addr).sync().channel();
    Channel c = new Bootstrap().handler(clientWbaeh).channel(LocalChannel.class).group(group).register().sync()
            .channel();/*  w ww. ja v  a 2s  .c om*/
    ChannelFuture write = c.writeAndFlush(NettyClientHandler.NOOP_MESSAGE);
    c.connect(addr).sync();
    write.sync();

    boolean completed = gh.negotiated.await(TIMEOUT_SECONDS, TimeUnit.SECONDS);
    if (!completed) {
        assertTrue("failed to negotiated", write.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
        // sync should fail if we are in this block.
        write.sync();
        throw new AssertionError("neither wrote nor negotiated");
    }
    c.close();
    s.close();

    assertThat(gh.securityInfo).isNotNull();
    assertThat(gh.securityInfo.tls).isNotNull();
    assertThat(gh.attrs.get(GrpcAttributes.ATTR_SECURITY_LEVEL)).isEqualTo(SecurityLevel.PRIVACY_AND_INTEGRITY);
    assertThat(gh.attrs.get(Grpc.TRANSPORT_ATTR_SSL_SESSION)).isInstanceOf(SSLSession.class);
    // This is not part of the ClientTls negotiation, but shows that the negotiation event happens
    // in the right order.
    assertThat(gh.attrs.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)).isEqualTo(addr);
}

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;/*  www.  j  ava 2s  . com*/
    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

/**
 * Builds a new client SSL context./*from  w w  w .  j  a  va2s .c o  m*/
 *
 * @param cfg SSL configuration.
 * @param res Resource service for loading {@link KeyStore}.
 *
 * @return SSL context.
 */
public static SslContext clientContext(NetworkSslConfig cfg, ResourceService res) {
    ConfigCheck check = checkConfig(cfg);

    try {
        return SslContextBuilder.forClient().sslProvider(provider(cfg)).trustManager(trustManager(cfg, res))
                .sessionCacheSize(cfg.getSslSessionCacheSize()).sessionTimeout(cfg.getSslSessionCacheTimeout())
                .build();
    } catch (ResourceLoadingException | GeneralSecurityException | IOException e) {
        throw check.fail(e);
    }
}

From source file:io.netty.example.http.snoop.HttpSnoopClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    URI uri = new URI(URL);
    String scheme = uri.getScheme() == null ? "http" : uri.getScheme();
    String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
    int port = uri.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;/*from w  w w. j av a2  s. co m*/
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    // Configure SSL context if necessary.
    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpSnoopClientInitializer(sslCtx));

        // Make the connection attempt.
        Channel ch = b.connect(host, port).sync().channel();

        // Prepare the HTTP request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getRawPath(),
                Unpooled.EMPTY_BUFFER);
        request.headers().set(HttpHeaderNames.HOST, host);
        request.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Set some example cookies.
        request.headers().set(HttpHeaderNames.COOKIE, ClientCookieEncoder.STRICT
                .encode(new DefaultCookie("my-cookie", "foo"), new DefaultCookie("another-cookie", "bar")));

        // Send the HTTP request.
        ch.writeAndFlush(request);

        // Wait for the server to close the connection.
        ch.closeFuture().sync();
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();
    }
}

From source file:io.netty.example.http.upload.HttpUploadClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    String postSimple, postFile, get;
    if (BASE_URL.endsWith("/")) {
        postSimple = BASE_URL + "formpost";
        postFile = BASE_URL + "formpostmultipart";
        get = BASE_URL + "formget";
    } else {/*  w w  w .  ja  v  a2s .co m*/
        postSimple = BASE_URL + "/formpost";
        postFile = BASE_URL + "/formpostmultipart";
        get = BASE_URL + "/formget";
    }

    URI uriSimple = new URI(postSimple);
    String scheme = uriSimple.getScheme() == null ? "http" : uriSimple.getScheme();
    String host = uriSimple.getHost() == null ? "127.0.0.1" : uriSimple.getHost();
    int port = uriSimple.getPort();
    if (port == -1) {
        if ("http".equalsIgnoreCase(scheme)) {
            port = 80;
        } else if ("https".equalsIgnoreCase(scheme)) {
            port = 443;
        }
    }

    if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
        System.err.println("Only HTTP(S) is supported.");
        return;
    }

    final boolean ssl = "https".equalsIgnoreCase(scheme);
    final SslContext sslCtx;
    if (ssl) {
        sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    URI uriFile = new URI(postFile);
    File file = new File(FILE);
    if (!file.canRead()) {
        throw new FileNotFoundException(FILE);
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();

    // setup the factory: here using a mixed memory/disk based on size threshold
    HttpDataFactory factory = new DefaultHttpDataFactory(DefaultHttpDataFactory.MINSIZE); // Disk if MINSIZE exceed

    DiskFileUpload.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskFileUpload.baseDirectory = null; // system temp directory
    DiskAttribute.deleteOnExitTemporaryFile = true; // should delete file on exit (in normal exit)
    DiskAttribute.baseDirectory = null; // system temp directory

    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new HttpUploadClientInitializer(sslCtx));

        // Simple Get form: no factory used (not usable)
        List<Entry<String, String>> headers = formget(b, host, port, get, uriSimple);
        if (headers == null) {
            factory.cleanAllHttpData();
            return;
        }

        // Simple Post form: factory used for big attributes
        List<InterfaceHttpData> bodylist = formpost(b, host, port, uriSimple, file, factory, headers);
        if (bodylist == null) {
            factory.cleanAllHttpData();
            return;
        }

        // Multipart Post form: factory used
        formpostmultipart(b, host, port, uriFile, factory, headers, bodylist);
    } finally {
        // Shut down executor threads to exit.
        group.shutdownGracefully();

        // Really clean all temporary files if they still exist
        factory.cleanAllHttpData();
    }
}

From source file:io.netty.example.http2.helloworld.client.Http2Client.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {/*from   w  ww .ja  va  2 s.co m*/
        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 (URL != null) {
            // Create a simple GET request.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL, Unpooled.EMPTY_BUFFER);
            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.write(request), channel.newPromise());
            streamId += 2;
        }
        if (URL2 != null) {
            // Create a simple POST request with a body.
            FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2,
                    wrappedBuffer(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.write(request), channel.newPromise());
        }
        channel.flush();
        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:io.netty.example.ocsp.OcspClientExample.java

License:Apache License

public static void main(String[] args) throws Exception {
    if (!OpenSsl.isAvailable()) {
        throw new IllegalStateException("OpenSSL is not available!");
    }/*from w w w.  j a  v a  2  s. c  om*/

    if (!OpenSsl.isOcspSupported()) {
        throw new IllegalStateException("OCSP is not supported!");
    }

    // Using Wikipedia as an example. I'd rather use Netty's own website
    // but the server (Cloudflare) doesn't support OCSP stapling. A few
    // other examples could be Microsoft or Squarespace. Use OpenSSL's
    // CLI client to assess if a server supports OCSP stapling. E.g.:
    //
    // openssl s_client -tlsextdebug -status -connect www.squarespace.com:443
    //
    String host = "www.wikipedia.org";

    ReferenceCountedOpenSslContext context = (ReferenceCountedOpenSslContext) SslContextBuilder.forClient()
            .sslProvider(SslProvider.OPENSSL).enableOcsp(true).build();

    try {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Promise<FullHttpResponse> promise = group.next().newPromise();

            Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(group)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5 * 1000)
                    .handler(newClientHandler(context, host, promise));

            Channel channel = bootstrap.connect(host, 443).syncUninterruptibly().channel();

            try {
                FullHttpResponse response = promise.get();
                ReferenceCountUtil.release(response);
            } finally {
                channel.close();
            }
        } finally {
            group.shutdownGracefully();
        }
    } finally {
        context.release();
    }
}

From source file:io.netty.example.spdy.client.SpdyClient.java

License:Apache License

public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.NPN,
                    // 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.SPDY_3_1,
                    ApplicationProtocolNames.HTTP_1_1))
            .build();//w  ww.j  a v a 2 s .  c o m

    HttpResponseClientHandler httpResponseHandler = new HttpResponseClientHandler();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.remoteAddress(HOST, PORT);
        b.handler(new SpdyClientInitializer(sslCtx, httpResponseHandler));

        // Start the client.
        Channel channel = b.connect().syncUninterruptibly().channel();
        System.out.println("Connected to " + HOST + ':' + PORT);

        // Create a GET request.
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "",
                Unpooled.EMPTY_BUFFER);
        request.headers().set(HttpHeaderNames.HOST, HOST);
        request.headers().set(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);

        // Send the GET request.
        channel.writeAndFlush(request).sync();

        // Waits for the complete HTTP response
        httpResponseHandler.queue().take().sync();
        System.out.println("Finished SPDY HTTP GET");

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