io.netty.handler.ssl.util.InsecureTrustManagerFactory Java Examples

The following examples show how to use io.netty.handler.ssl.util.InsecureTrustManagerFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HelloWorldClient.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	HttpClient client =
			HttpClient.create()
			          .port(PORT)
			          .wiretap(WIRETAP)
			          .compress(COMPRESS);

	if (SECURE) {
		client = client.secure(
				spec -> spec.sslContext(SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)));
	}

	String response =
			client.get()
			      .uri("/hello")
			      .responseContent()
			      .aggregate()
			      .asString()
			      .block();

	System.out.println("Response: " + response);
}
 
Example #2
Source File: EchoClient.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	TcpClient client =
			TcpClient.create()
			         .port(PORT)
			         .wiretap(WIRETAP);

	if (SECURE) {
		client = client.secure(
				spec -> spec.sslContext(SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)));
	}

	Connection connection =
			client.handle((in, out) -> out.send(Flux.concat(ByteBufFlux.fromString(Mono.just("echo")),
			                                                in.receive().retain())))
			      .connectNow();

	connection.onDispose()
	          .block();
}
 
Example #3
Source File: RequestRunner.java    From openshift-elasticsearch-plugin with Apache License 2.0 6 votes vote down vote up
protected final OkHttpClient getHttpClient() throws Exception {
    File ksFile = new File(keyStore);
    KeyStore trusted = KeyStore.getInstance("JKS");
    FileInputStream in = new FileInputStream(ksFile);
    trusted.load(in, password.toCharArray());
    in.close();
    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManagerFactory trustManagerFactory = InsecureTrustManagerFactory.INSTANCE;
    X509TrustManager trustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    OkHttpClient client = new okhttp3.OkHttpClient.Builder()
            .sslSocketFactory(sslContext.getSocketFactory(), trustManager)
            .readTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES)
            .build();
    return client;
}
 
Example #4
Source File: GremlinServerSslIntegrateTest.java    From tinkerpop with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldEnableSslWithSslContextProgrammaticallySpecified() throws Exception {
    // just for testing - this is not good for production use
    final SslContextBuilder builder = SslContextBuilder.forClient();
    builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    builder.sslProvider(SslProvider.JDK);

    final Cluster cluster = TestClientFactory.build().enableSsl(true).sslContext(builder.build()).create();
    final Client client = cluster.connect();

    try {
        // this should return "nothing" - there should be no exception
        assertEquals("test", client.submit("'test'").one().getString());
    } finally {
        cluster.close();
    }
}
 
Example #5
Source File: ExtractorClient.java    From deep-spark with Apache License 2.0 6 votes vote down vote up
public ExtractorClient initialize() throws DeepExtractorInitializationException {
    try {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {

            sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);

        } else {
            sslCtx = null;
        }

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ExtractorClientInitializer<T>(sslCtx));

        // Make a new connection.
        this.ch = b.connect(HOST, PORT).sync().channel();

        // Get the handler instance to initiate the request.
        this.handler = ch.pipeline().get(ExtractorClientHandler.class);
    } catch (SSLException | InterruptedException e) {
        throw new DeepExtractorInitializationException(e);

    }
    return this;
}
 
Example #6
Source File: XrpcClient.java    From xrpc with Apache License 2.0 6 votes vote down vote up
private SslContext buildSslCtx() {
  SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
  try {
    return SslContextBuilder.forClient()
        .sslProvider(provider)
        .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
        .trustManager(InsecureTrustManagerFactory.INSTANCE)
        // TODO(JR): Make a seperate Handler Class for http2 as opposed to autoneg
        //        .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) {
    e.printStackTrace();
  }

  return null;
}
 
Example #7
Source File: SecurityUtility.java    From pulsar with Apache License 2.0 6 votes vote down vote up
private static TrustManager[] setupTrustCerts(KeyStoreHolder ksh, boolean allowInsecureConnection,
        Certificate[] trustCertficates) throws NoSuchAlgorithmException, KeyStoreException {
    TrustManager[] trustManagers;
    if (allowInsecureConnection) {
        trustManagers = InsecureTrustManagerFactory.INSTANCE.getTrustManagers();
    } else {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

        if (trustCertficates == null || trustCertficates.length == 0) {
            tmf.init((KeyStore) null);
        } else {
            for (int i = 0; i < trustCertficates.length; i++) {
                ksh.setCertificate("trust" + i, trustCertficates[i]);
            }
            tmf.init(ksh.getKeyStore());
        }

        trustManagers = tmf.getTrustManagers();
    }
    return trustManagers;
}
 
Example #8
Source File: TestUtils.java    From serve with Apache License 2.0 6 votes vote down vote up
public static void init() {
    // set up system properties for local IDE debug
    if (System.getProperty("tsConfigFile") == null) {
        System.setProperty("tsConfigFile", "src/test/resources/config.properties");
    }
    if (System.getProperty("METRICS_LOCATION") == null) {
        System.setProperty("METRICS_LOCATION", "build/logs");
    }
    if (System.getProperty("LOG_LOCATION") == null) {
        System.setProperty("LOG_LOCATION", "build/logs");
    }

    try {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);

        HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());

        HttpsURLConnection.setDefaultHostnameVerifier((s, sslSession) -> true);
    } catch (GeneralSecurityException e) {
        // ignore
    }
}
 
Example #9
Source File: NettyHttp2Client.java    From jmeter-http2-plugin with Apache License 2.0 6 votes vote down vote up
private SslContext getSslContext() {
    SslContext sslCtx = null;

    final SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;

    try {
        sslCtx = SslContextBuilder.forClient()
            .sslProvider(provider)
            .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(
                Protocol.ALPN,
                SelectorFailureBehavior.NO_ADVERTISE,
                SelectedListenerFailureBehavior.ACCEPT,
                ApplicationProtocolNames.HTTP_2))
            .build();
    } catch(SSLException exception) {
        return null;
    }

    return sslCtx;
}
 
Example #10
Source File: BackPoolHandler.java    From api-gateway-core with Apache License 2.0 5 votes vote down vote up
public BackPoolHandler(RequestHolder requestHolder) {
    if (requestHolder.getProtocol().equalsIgnoreCase(HTTPS)) {
        try {
            sslCtx = SslContextBuilder.forClient()
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } catch (SSLException e) {
            logger.error(e.getMessage(), e);
        }
    }
}
 
Example #11
Source File: ObjectEchoClient.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                if (sslCtx != null) {
                    p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                }
                p.addLast(
                        new ObjectEncoder(),
                        new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                        new ObjectEchoClientHandler());
            }
         });

        // Start the connection attempt.
        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #12
Source File: DiscardClient.java    From HttpProxy with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             protected void initChannel(SocketChannel ch) throws Exception {
                 ChannelPipeline p = ch.pipeline();
                 if (sslCtx != null) {
                     p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                 }
                 p.addLast(new DiscardClientHandler());
             }
         });

        // Make the connection attempt.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #13
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpectErrorWhenConnectionClosed() throws Exception {
	SelfSignedCertificate ssc = new SelfSignedCertificate();
	SslContext serverCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
	                                        .build();
	AtomicReference<Throwable> error = new AtomicReference<>();
	CountDownLatch latch = new CountDownLatch(1);
	disposableServer =
			HttpServer.create()
			          .port(0)
			          .secure(spec -> spec.sslContext(serverCtx))
			          .handle((req, res) -> {
			              res.withConnection(DisposableChannel::dispose);
			              return res.sendString(Flux.just("OK").hide())
			                        .then()
			                        .doOnError(t -> {
			                            error.set(t);
			                            latch.countDown();
			                        });
			          })
			          .bindNow();

	SslContext clientCtx = SslContextBuilder.forClient()
	                                        .trustManager(InsecureTrustManagerFactory.INSTANCE)
	                                        .build();
	StepVerifier.create(
			HttpClient.create()
			          .remoteAddress(disposableServer::address)
			          .secure(spec -> spec.sslContext(clientCtx))
			          .get()
			          .uri("/")
			          .responseContent())
			    .verifyError(PrematureCloseException.class);

	assertThat(latch.await(30, TimeUnit.SECONDS)).isTrue();
	assertThat(error.get()).isInstanceOf(AbortedException.class);
}
 
Example #14
Source File: SSLEngineTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
protected void setupHandlers(ApplicationProtocolConfig serverApn, ApplicationProtocolConfig clientApn)
        throws InterruptedException, SSLException, CertificateException {
    SelfSignedCertificate ssc = new SelfSignedCertificate();

    try {
      setupHandlers(SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey(), null)
                      .sslProvider(sslServerProvider())
                      .sslContextProvider(serverSslContextProvider())
                      .ciphers(null, IdentityCipherSuiteFilter.INSTANCE)
                      .applicationProtocolConfig(serverApn)
                      .sessionCacheSize(0)
                      .sessionTimeout(0)
                      .build(),

              SslContextBuilder.forClient()
                      .sslProvider(sslClientProvider())
                      .sslContextProvider(clientSslContextProvider())
                      .applicationProtocolConfig(clientApn)
                      .trustManager(InsecureTrustManagerFactory.INSTANCE)
                      .ciphers(null, IdentityCipherSuiteFilter.INSTANCE)
                      .sessionCacheSize(0)
                      .sessionTimeout(0)
                      .build());
    } finally {
      ssc.delete();
    }
}
 
Example #15
Source File: EchoClient.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.git
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);
    } else {
        sslCtx = null;
    }

    // Configure the client.
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(NioSocketChannel.class)
         .option(ChannelOption.TCP_NODELAY, true)
         .handler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
                 ChannelPipeline p = ch.pipeline();
                 if (sslCtx != null) {
                     p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                 }
                 //p.addLast(new LoggingHandler(LogLevel.INFO));
                 p.addLast(new EchoClientHandler());
             }
         });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}
 
Example #16
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void testExplicitEmptyBodyOnGetWorks() throws Exception {
	SelfSignedCertificate ssc = new SelfSignedCertificate();
	SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
	                                        .build();

	SslContext sslClient = SslContextBuilder.forClient()
	                                        .trustManager(InsecureTrustManagerFactory.INSTANCE)
	                                        .build();

	disposableServer =
			HttpServer.create()
			          .secure(ssl -> ssl.sslContext(sslServer))
			          .port(0)
			          .handle((req, res) -> res.send(req.receive().retain()))
			          .bindNow();

	ConnectionProvider pool = ConnectionProvider.create("testExplicitEmptyBodyOnGetWorks", 1);

	for (int i = 0; i < 4; i++) {
		StepVerifier.create(createHttpClientForContextWithAddress(pool)
		                            .secure(ssl -> ssl.sslContext(sslClient))
		                            .request(HttpMethod.GET)
		                            .uri("/")
		                            .send((req, out) -> out.send(Flux.empty()))
		                            .responseContent())
		            .expectComplete()
		            .verify(Duration.ofSeconds(30));
	}

	pool.dispose();
}
 
Example #17
Source File: NettyClientLatencyTest.java    From Chronicle-Network with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws SSLException, InterruptedException {
    // Configure SSL.git
    @Nullable final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);

    } else {
        sslCtx = null;
    }

    // Configure the client.
    @NotNull EventLoopGroup group = new NioEventLoopGroup();
    try {
        @NotNull Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(@NotNull SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        }
                        //p.addLast(new LoggingHandler(LogLevel.INFO));
                        p.addLast(new MyChannelInboundHandler());
                    }
                });

        // Start the client.
        ChannelFuture f = b.connect(HOST, PORT).sync();

        // Wait until the connection is closed.
        f.channel().closeFuture().sync();
    } finally {
        // Shut down the event loop to terminate all threads.
        group.shutdownGracefully();
    }
}
 
Example #18
Source File: DefaultClientPool.java    From protools with Apache License 2.0 5 votes vote down vote up
private void setSSlContext(boolean ssl) throws SSLException {
    if (ssl) {
        sslContext = SslContextBuilder.forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslContext = null;
    }
}
 
Example #19
Source File: ObjectEchoClient.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    // Configure SSL.
    final SslContext sslCtx;
    if (SSL) {
        sslCtx = SslContextBuilder.forClient()
                .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    } else {
        sslCtx = null;
    }

    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ChannelPipeline p = ch.pipeline();
                        if (sslCtx != null) {
                            p.addLast(sslCtx.newHandler(ch.alloc(), HOST, PORT));
                        }
                        p.addLast(
                                new ObjectEncoder(),
                                new ObjectDecoder(ClassResolvers.cacheDisabled(null)),
                                new ObjectEchoClientHandler());
                    }
                });

        // Start the connection attempt.
        b.connect(HOST, PORT).sync().channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #20
Source File: SSLContextGenerator.java    From flashback with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Create client side SSLContext {@link javax.net.ssl.SSLContext}
 *
 * */
public static SSLContext createClientContext(KeyStore keyStore, char[] passphrase)
    throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
  String keyManAlg = KeyManagerFactory.getDefaultAlgorithm();
  KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManAlg);
  kmf.init(keyStore, passphrase);
  KeyManager[] keyManagers = kmf.getKeyManagers();
  return create(keyManagers, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(),
      RandomNumberGenerator.getInstance().getSecureRandom());
}
 
Example #21
Source File: ByteBufFluxTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
private void doTestByteBufFluxFromPath(boolean withSecurity) throws Exception {
	final int serverPort = SocketUtils.findAvailableTcpPort();
	HttpServer server = HttpServer.create()
	                              .port(serverPort)
	                              .wiretap(true);
	HttpClient client = HttpClient.create()
	                              .port(serverPort)
	                              .wiretap(true);
	if (withSecurity) {
		SelfSignedCertificate ssc = new SelfSignedCertificate();
		SslContext sslServer = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
		SslContext sslClient = SslContextBuilder.forClient()
		                                        .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
		server = server.secure(ssl -> ssl.sslContext(sslServer));
		client = client.secure(ssl -> ssl.sslContext(sslClient));
	}

	Path path = Paths.get(getClass().getResource("/largeFile.txt").toURI());
	DisposableServer c = server.handle((req, res) ->
	                                      res.send(ByteBufFlux.fromPath(path))
	                                         .then())
	                           .bindNow();

	AtomicLong counter = new AtomicLong(0);
	client.get()
	      .uri("/download")
	      .responseContent()
	      .doOnNext(b -> counter.addAndGet(b.readableBytes()))
	      .blockLast(Duration.ofSeconds(30));

	assertEquals(1245, counter.get());

	c.disposeNow();
}
 
Example #22
Source File: WSSClient.java    From poloniex-api-java with MIT License 5 votes vote down vote up
public WSSClient(String url) throws Exception {
    uri = new URI(url);

    if (!SCHEME_WSS.equalsIgnoreCase(uri.getScheme())) {
        throw new IllegalArgumentException("Only WSS is supported");
    }

    // FIXME: use secure trust manager
    sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
    group = new NioEventLoopGroup();
    subscriptions = new HashMap<>();
}
 
Example #23
Source File: WebSocketIT.java    From qonduit with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    s = new Server(conf);
    s.run();

    Connector con = mac.getConnector("root", "secret");
    con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F"));

    this.sessionId = UUID.randomUUID().toString();
    AuthCache.getCache().put(sessionId, token);
    group = new NioEventLoopGroup();
    SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId);
    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(HttpHeaderNames.COOKIE, cookieVal);

    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,
            WebSocketVersion.V13, (String) null, false, headers);
    handler = new ClientHandler(handshaker);
    Bootstrap boot = new Bootstrap();
    boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT));
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(new HttpObjectAggregator(8192));
            ch.pipeline().addLast(handler);
        }
    });
    ch = boot.connect("127.0.0.1", WS_PORT).sync().channel();
    // Wait until handshake is complete
    while (!handshaker.isHandshakeComplete()) {
        sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
        LOG.debug("Waiting for Handshake to complete");
    }
}
 
Example #24
Source File: SSLSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private TrustManagerFactory loadTrustManagerFactory() throws Exception {
   if (trustManagerFactoryPlugin != null) {
      return AccessController.doPrivileged((PrivilegedAction<TrustManagerFactory>) () -> ((TrustManagerFactoryPlugin) ClassloadingUtil.newInstanceFromClassLoader(SSLSupport.class, trustManagerFactoryPlugin)).getTrustManagerFactory());
   } else if (trustAll) {
      //This is useful for testing but not should be used outside of that purpose
      return InsecureTrustManagerFactory.INSTANCE;
   } else if (truststorePath == null && (truststoreProvider == null || !"PKCS11".equals(truststoreProvider.toUpperCase()))) {
      return null;
   } else {
      TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      KeyStore trustStore = SSLSupport.loadKeystore(truststoreProvider, truststorePath, truststorePassword);
      boolean ocsp = Boolean.valueOf(Security.getProperty("ocsp.enable"));

      boolean initialized = false;
      if ((ocsp || crlPath != null) && TrustManagerFactory.getDefaultAlgorithm().equalsIgnoreCase("PKIX")) {
         PKIXBuilderParameters pkixParams = new PKIXBuilderParameters(trustStore, new X509CertSelector());
         if (crlPath != null) {
            pkixParams.setRevocationEnabled(true);
            Collection<? extends CRL> crlList = loadCRL();
            if (crlList != null) {
               pkixParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crlList)));
            }
         }
         trustMgrFactory.init(new CertPathTrustManagerParameters(pkixParams));
         initialized = true;
      }

      if (!initialized) {
         trustMgrFactory.init(trustStore);
      }
      return trustMgrFactory;
   }
}
 
Example #25
Source File: SslBridgeHandler.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static SslContextBuilder buildContext(MySqlSslConfiguration ssl, ServerVersion version) {
    SslContextBuilder builder = withTlsVersion(SslContextBuilder.forClient(), ssl, version);
    String sslKey = ssl.getSslKey();

    if (sslKey != null) {
        CharSequence keyPassword = ssl.getSslKeyPassword();
        String sslCert = ssl.getSslCert();

        if (sslCert == null) {
            throw new IllegalStateException("SSL key param requires but SSL cert param to be present");
        }

        builder.keyManager(new File(sslCert), new File(sslKey), keyPassword == null ? null : keyPassword.toString());
    }

    SslMode mode = ssl.getSslMode();
    if (mode.verifyCertificate()) {
        String sslCa = ssl.getSslCa();

        if (sslCa == null) {
            throw new IllegalStateException(String.format("SSL mode %s requires SSL CA parameter", mode));
        }

        builder.trustManager(new File(sslCa));
    } else {
        builder.trustManager(InsecureTrustManagerFactory.INSTANCE);
    }

    return ssl.customizeSslContext(builder);
}
 
Example #26
Source File: ClientAuthIntegrationTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.tls(serverCert.certificateFile(), serverCert.privateKeyFile());
    sb.tlsCustomizer(sslCtxBuilder -> {
        sslCtxBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE)
                     .clientAuth(ClientAuth.REQUIRE);
    });

    sb.service("/", (ctx, req) -> HttpResponse.of("success"));
    sb.decorator(LoggingService.builder().newDecorator());
}
 
Example #27
Source File: BouncyCastleSslEngineSource.java    From CapturePacket with MIT License 5 votes vote down vote up
private void initializeSSLContext() throws GeneralSecurityException,
        IOException {
    KeyStore ks = loadKeyStore();
    caCert = ks.getCertificate(authority.alias());
    caPrivKey = (PrivateKey) ks.getKey(authority.alias(),
            authority.password());

    TrustManager[] trustManagers;
    if (trustAllServers) {
        trustManagers = InsecureTrustManagerFactory.INSTANCE
                .getTrustManagers();
    } else {
        trustManagers = new TrustManager[] { new MergeTrustManager(ks) };
    }

    KeyManager[] keyManagers;
    if (sendCerts) {
        keyManagers = CertificateHelper.getKeyManagers(ks, authority);
    } else {
        keyManagers = new KeyManager[0];
    }

    sslContext = CertificateHelper.newClientContext(keyManagers,
            trustManagers);
    SSLEngine sslEngine = sslContext.createSSLEngine();
    if (!tryHostNameVerificationJava7(sslEngine)) {
        LOG.warn("Host Name Verification is not supported, causes insecure HTTPS connection to upstream servers.");
    }
}
 
Example #28
Source File: IntegrationTest.java    From NioSmtpClient with Apache License 2.0 5 votes vote down vote up
private SSLEngine createInsecureSSLEngine() {
  try {
    return SslContextBuilder
        .forClient()
        .trustManager(InsecureTrustManagerFactory.INSTANCE)
        .build()
        .newEngine(PooledByteBufAllocator.DEFAULT);
  } catch (Exception e) {
    throw new RuntimeException("Could not create SSLEngine", e);
  }
}
 
Example #29
Source File: SslHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 30000)
public void testRemoval() throws Exception {
    NioEventLoopGroup group = new NioEventLoopGroup();
    Channel sc = null;
    Channel cc = null;
    try {
        final Promise<Void> clientPromise = group.next().newPromise();
        Bootstrap bootstrap = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(newHandler(SslContextBuilder.forClient().trustManager(
                        InsecureTrustManagerFactory.INSTANCE).build(), clientPromise));

        SelfSignedCertificate ssc = new SelfSignedCertificate();
        final Promise<Void> serverPromise = group.next().newPromise();
        ServerBootstrap serverBootstrap = new ServerBootstrap()
                .group(group, group)
                .channel(NioServerSocketChannel.class)
                .childHandler(newHandler(SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(),
                        serverPromise));
        sc = serverBootstrap.bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
        cc = bootstrap.connect(sc.localAddress()).syncUninterruptibly().channel();

        serverPromise.syncUninterruptibly();
        clientPromise.syncUninterruptibly();
    } finally {
        if (cc != null) {
            cc.close().syncUninterruptibly();
        }
        if (sc != null) {
            sc.close().syncUninterruptibly();
        }
        group.shutdownGracefully();
    }
}
 
Example #30
Source File: SSLEngineTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Test
public void testSSLSessionId() throws Exception {
    clientSslCtx = SslContextBuilder.forClient()
            .trustManager(InsecureTrustManagerFactory.INSTANCE)
            .sslProvider(sslClientProvider())
            .sslContextProvider(clientSslContextProvider())
            .build();
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
            .sslProvider(sslServerProvider())
            .sslContextProvider(serverSslContextProvider())
            .build();
    SSLEngine clientEngine = null;
    SSLEngine serverEngine = null;
    try {
        clientEngine = clientSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);
        serverEngine = serverSslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);

        // Before the handshake the id should have length == 0
        assertEquals(0, clientEngine.getSession().getId().length);
        assertEquals(0, serverEngine.getSession().getId().length);

        handshake(clientEngine, serverEngine);

        // After the handshake the id should have length > 0
        assertNotEquals(0, clientEngine.getSession().getId().length);
        assertNotEquals(0, serverEngine.getSession().getId().length);
        assertArrayEquals(clientEngine.getSession().getId(), serverEngine.getSession().getId());
    } finally {
        cleanupClientSslEngine(clientEngine);
        cleanupServerSslEngine(serverEngine);
        ssc.delete();
    }
}