Example usage for io.netty.handler.ssl.util SelfSignedCertificate cert

List of usage examples for io.netty.handler.ssl.util SelfSignedCertificate cert

Introduction

In this page you can find the example usage for io.netty.handler.ssl.util SelfSignedCertificate cert.

Prototype

X509Certificate cert

To view the source code for io.netty.handler.ssl.util SelfSignedCertificate cert.

Click Source Link

Usage

From source file:io.crate.auth.ClientCertAuthTest.java

License:Apache License

@Before
public void setUpSsl() throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    sslSession = mock(SSLSession.class);
    when(sslSession.getPeerCertificates()).thenReturn(new Certificate[] { ssc.cert() });

    sslConnWithCert = new ConnectionProperties(InetAddresses.forString("127.0.0.1"), Protocol.POSTGRES,
            sslSession);/*from  w w  w  .  j av a  2s .c o  m*/
}

From source file:io.crate.protocols.http.HttpAuthUpstreamHandlerTest.java

@Test
public void testClientCertUserHasPreferenceOverTrustAuthDefault() throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SSLSession session = mock(SSLSession.class);
    when(session.getPeerCertificates()).thenReturn(new Certificate[] { ssc.cert() });

    HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/_sql");
    String userName = HttpAuthUpstreamHandler.credentialsFromRequest(request, session, Settings.EMPTY).v1();

    assertThat(userName, is("example.com"));
}

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  va2 s .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:org.apache.drill.exec.rpc.user.security.TestUserBitSSL.java

License:Apache License

@Ignore("This test fails in some cases where the host name may be set up inconsistently.")
@Test/*from  w  ww  .j  a va  2s  .c o  m*/
public void testClientConfigHostnameVerification() {
    String password = "test_password";
    String trustStoreFileName = "drillTestTrustStore";
    String keyStoreFileName = "drillTestKeyStore";
    KeyStore ts, ks;
    File tempFile1, tempFile2;
    String trustStorePath;
    String keyStorePath;

    try {
        String fqdn = InetAddress.getLocalHost().getHostName();
        SelfSignedCertificate certificate = new SelfSignedCertificate(fqdn);

        tempFile1 = File.createTempFile(trustStoreFileName, ".ks");
        tempFile1.deleteOnExit();
        trustStorePath = tempFile1.getAbsolutePath();
        //generate a truststore.
        ts = KeyStore.getInstance(KeyStore.getDefaultType());
        ts.load(null, password.toCharArray());
        ts.setCertificateEntry("drillTest", certificate.cert());
        // Store away the truststore.
        try (FileOutputStream fos1 = new FileOutputStream(tempFile1);) {
            ts.store(fos1, password.toCharArray());
        } catch (Exception e) {
            fail(e.getMessage());
        }

        tempFile2 = File.createTempFile(keyStoreFileName, ".ks");
        tempFile2.deleteOnExit();
        keyStorePath = tempFile2.getAbsolutePath();
        //generate a keystore.
        ts = KeyStore.getInstance(KeyStore.getDefaultType());
        ts.load(null, password.toCharArray());
        ts.setKeyEntry("drillTest", certificate.key(), password.toCharArray(),
                new java.security.cert.Certificate[] { certificate.cert() });
        // Store away the keystore.
        try (FileOutputStream fos2 = new FileOutputStream(tempFile2);) {
            ts.store(fos2, password.toCharArray());
        } catch (Exception e) {
            fail(e.getMessage());
        }

        final Properties connectionProps = new Properties();
        connectionProps.setProperty(DrillProperties.ENABLE_TLS, "true");
        connectionProps.setProperty(DrillProperties.TRUSTSTORE_PATH, trustStorePath);
        connectionProps.setProperty(DrillProperties.TRUSTSTORE_PASSWORD, password);
        connectionProps.setProperty(DrillProperties.DISABLE_HOST_VERIFICATION, "false");

        DrillConfig sslConfig = new DrillConfig(DrillConfig.create(cloneDefaultTestConfigProperties())
                .withValue(ExecConstants.USER_SSL_ENABLED, ConfigValueFactory.fromAnyRef(true))
                .withValue(ExecConstants.SSL_KEYSTORE_TYPE, ConfigValueFactory.fromAnyRef("JKS"))
                .withValue(ExecConstants.SSL_KEYSTORE_PATH, ConfigValueFactory.fromAnyRef(keyStorePath))
                .withValue(ExecConstants.SSL_KEYSTORE_PASSWORD, ConfigValueFactory.fromAnyRef("test_password"))
                .withValue(ExecConstants.SSL_PROTOCOL, ConfigValueFactory.fromAnyRef("TLSv1.2")));

        updateTestCluster(1, sslConfig, connectionProps);

    } catch (Exception e) {
        fail(e.getMessage());
    }
    //reset cluster
    updateTestCluster(1, newConfig, initProps);

}

From source file:org.caffinitas.prometheusmetrics.PrometheusMetricsExporter.java

License:Apache License

private void setupNetty() throws CertificateException, SSLException {
    final SslContext sslCtx;
    if (config.ssl) {
        SelfSignedCertificate ssc = new SelfSignedCertificate();
        LOGGER.info("Setting up SSL context for certificate subject DN {} valid until {}",
                ssc.cert().getSubjectDN(), ssc.cert().getNotAfter());
        sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    } else {/* www.  j a va 2 s .  c o  m*/
        sslCtx = null;
    }

    EventLoopGroup bossGroup = new NioEventLoopGroup(1);
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    this.nettyChannel = new ServerBootstrap().option(ChannelOption.SO_BACKLOG, 1024)
            .group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ServerInitializer(sslCtx)).bind(config.bindAddress, config.httpPort)
            .syncUninterruptibly().channel();

    nettyChannel.closeFuture().addListener(f -> {
        LOGGER.info("Shutting down listener");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    });
}

From source file:reactor.ipc.netty.http.client.HttpClientTest.java

License:Open Source License

@Test
public void sshExchangeRelativeGet() throws CertificateException, SSLException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient()
            //make the client to trust the self signed certificate
            .trustManager(ssc.cert()).build();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newHandler((req, resp) -> resp.sendString(Flux.just("hello ", req.uri()))).block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient)).get("/foo")
            .block(Duration.ofMillis(200));
    context.dispose();//from  w  w w  .  j a v  a  2s  .com
    context.onClose().block();

    String responseString = response.receive().aggregate().asString(CharsetUtil.UTF_8).block();
    assertThat(responseString).isEqualTo("hello /foo");
}

From source file:reactor.ipc.netty.http.client.HttpClientTest.java

License:Open Source License

@Test
public void sshExchangeAbsoluteGet() throws CertificateException, SSLException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newHandler((req, resp) -> resp.sendString(Flux.just("hello ", req.uri()))).block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient))
            .get("https://localhost:" + context.address().getPort() + "/foo").block(Duration.ofMillis(200));
    context.dispose();/*from w w  w .j a  va2  s .  co  m*/
    context.onClose().block();

    String responseString = response.receive().aggregate().asString(CharsetUtil.UTF_8).block();
    assertThat(responseString).isEqualTo("hello /foo");
}

From source file:reactor.ipc.netty.http.client.HttpClientTest.java

License:Open Source License

@Test
public void secureSendFile() throws CertificateException, SSLException, InterruptedException {
    Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").getFile());
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build();
    AtomicReference<String> uploaded = new AtomicReference<>();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newRouter(//from w ww  .  j  av  a  2 s.  com
                    r -> r.post("/upload",
                            (req, resp) -> req.receive().aggregate().asString().doOnNext(uploaded::set)
                                    .then(resp.status(201).sendString(Mono.just("Received File")).then())))
            .block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient))
            .post("/upload", r -> r.sendFile(largeFile)).block(Duration.ofSeconds(120));

    context.dispose();
    context.onClose().block();

    String responseBody = response.receive().aggregate().asString().block();
    assertThat(response.status().code()).isEqualTo(201);
    assertThat(responseBody).isEqualTo("Received File");

    assertThat(uploaded.get())
            .startsWith(
                    "This is an UTF-8 file that is larger than 1024 bytes.\n" + "It contains accents like .")
            .contains("1024 mark here -><- 1024 mark here").endsWith("End of File");
}

From source file:reactor.ipc.netty.http.server.HttpServerTests.java

License:Open Source License

@Test
public void secureSendFile() throws CertificateException, SSLException, InterruptedException {
    Path largeFile = Paths.get(getClass().getResource("/largeFile.txt").getFile());
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
    SslContext sslClient = SslContextBuilder.forClient().trustManager(ssc.cert()).build();

    NettyContext context = HttpServer.create(opt -> opt.sslContext(sslServer))
            .newHandler((req, resp) -> resp.sendFile(largeFile)).block();

    HttpClientResponse response = HttpClient
            .create(opt -> opt.port(context.address().getPort()).sslContext(sslClient)).get("/foo")
            .block(Duration.ofSeconds(120));

    context.dispose();/*from w w  w. j a  v  a 2s. c  om*/
    context.onClose().block();

    String body = response.receive().aggregate().asString().block();

    assertThat(body)
            .startsWith(
                    "This is an UTF-8 file that is larger than 1024 bytes.\n" + "It contains accents like .")
            .contains("1024 mark here -><- 1024 mark here").endsWith("End of File");
}