@Override protected void initChannel(SocketChannel ch) throws Exception { if (enableTLS) { File tlsCert = new File(serviceConfig.getTlsCertificateFilePath()); File tlsKey = new File(serviceConfig.getTlsKeyFilePath()); SslContextBuilder builder = SslContextBuilder.forServer(tlsCert, tlsKey); if (serviceConfig.isTlsAllowInsecureConnection()) { builder.trustManager(InsecureTrustManagerFactory.INSTANCE); } else { if (serviceConfig.getTlsTrustCertsFilePath().isEmpty()) { // Use system default builder.trustManager((File) null); } else { File trustCertCollection = new File(serviceConfig.getTlsTrustCertsFilePath()); builder.trustManager(trustCertCollection); } } SslContext sslCtx = builder.clientAuth(ClientAuth.OPTIONAL).build(); ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc())); } ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4)); ch.pipeline().addLast("handler", new ServerConnection(discoveryService)); }
public void start(String ip, int port) 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 FileClientInitializer(sslCtx)); Channel ch = b.connect(ip, port).sync().channel(); ConfigurationContext.propMap.putIfAbsent(SOCKET_CHANNEL, ch); }catch(Exception e){ e.printStackTrace(); } }
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; }
private static TrustManagerFactory trustManager(NetworkSslConfig cfg, ResourceService resources) throws GeneralSecurityException, IOException, ResourceLoadingException { if (cfg.getTrustStorePath() == null || cfg.getTrustStorePath().isEmpty()) { return InsecureTrustManagerFactory.INSTANCE; } else { TrustManagerFactory factory; if (cfg.getTrustStoreAlgorithm() == null || cfg.getTrustStoreAlgorithm().isEmpty()) { factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); } else { factory = TrustManagerFactory.getInstance(cfg.getTrustStoreAlgorithm()); } KeyStore store = keyStore(cfg.getTrustStorePath(), cfg.getTrustStorePassword(), cfg.getTrustStoreType(), resources); factory.init(store); return factory; } }
public void shoot(ShootComplete shootComplete) { Bootstrap b = new Bootstrap(); SslContext sslContext = null; if (ssl) { try { sslContext = SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } catch (SSLException e) { e.printStackTrace(); } } b.group(group) .channel(NioSocketChannel.class) .handler(new HttpClientInitializer(sslContext)); // Make the connection attempt. b.connect(host, port).addListener( (ChannelFutureListener) channelFuture -> { sendHttpRequest(channelFuture, shootComplete); }); }
@Override protected void initChannel(SocketChannel channel) throws SSLException { URI uri = config.getConnectionWebsocketUri(); DefaultHttpHeaders headers = new DefaultHttpHeaders(); headers.add(USER_ID_HEADER, config.getConnectionUserId().toString()); headers.add(USER_PASSWORD_HEADER, config.getConnectionUserPassword()); headers.add(SUPPLIER_ID_HEADER, config.getConnectionServerId()); WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(uri, WS_VERSION, null, false, headers); ChannelPipeline pipeline = channel.pipeline(); if (config.isConnectionSecure()) { try { SslContext sslContext = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); pipeline.addLast(sslContext.newHandler(channel.alloc())); } catch (SSLException e) { logger.log(Level.SEVERE, "Shutting down client due to unexpected failure to create SSL context", e); throw e; } } pipeline.addLast(new HttpClientCodec()); pipeline.addLast(new HttpObjectAggregator(8192)); pipeline.addLast(new AudioConnectClientHandler(handshaker)); }
@Override protected void initChannel(SocketChannel ch) throws Exception { if (enableTLS) { File tlsCert = new File(serviceConfig.getTlsCertificateFilePath()); File tlsKey = new File(serviceConfig.getTlsKeyFilePath()); SslContextBuilder builder = SslContextBuilder.forServer(tlsCert, tlsKey); if (serviceConfig.isTlsAllowInsecureConnection()) { builder.trustManager(InsecureTrustManagerFactory.INSTANCE); } else { if (serviceConfig.getTlsTrustCertsFilePath().isEmpty()) { // Use system default builder.trustManager((File) null); } else { File trustCertCollection = new File(serviceConfig.getTlsTrustCertsFilePath()); builder.trustManager(trustCertCollection); } } SslContext sslCtx = builder.clientAuth(ClientAuth.OPTIONAL).build(); ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc())); } ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4)); ch.pipeline().addLast("handler", new ServerCnx(brokerService)); }
@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 = Cluster.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(); } }
public WebSocketClient(WebSocketConfig config) throws URISyntaxException, SSLException, InterruptedException { final int port = config.serverUri.getPort(); final String scheme = config.serverUri.getScheme().endsWith("s") ? "wss" : "ws"; final boolean isWss = "wss".equalsIgnoreCase(scheme); this.headers = new DefaultHttpHeaders(); if (config.apiKey != null) headers.add("X-Samebug-ApiKey", config.apiKey); if (config.workspaceId != null) headers.add("X-Samebug-WorkspaceId", config.workspaceId); this.port = port == -1 ? (isWss ? 443 : 80) : port; this.host = config.serverUri.getHost(); this.wsEndpoint = new URI(scheme, null, host, port, "/sockets/websocket", null, null); this.eventHandler = config.eventHandler; this.group = config.group; this.sslContext = isWss ? SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build() : null; // IMPROVE the constructor blocks the thread with networking! this.channel = connect(); }
public NettyHttpClient(String authCode, HttpProxy proxy, ClientConfig config) { _maxRetryTimes = config.getMaxRetryTimes(); _readTimeout = config.getReadTimeout(); String message = MessageFormat.format("Created instance with " + "connectionTimeout {0}, readTimeout {1}, maxRetryTimes {2}, SSL Version {3}", config.getConnectionTimeout(), _readTimeout, _maxRetryTimes, config.getSSLVersion()); LOG.debug(message); _authCode = authCode; try { _sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build(); _workerGroup = new NioEventLoopGroup(); b = new Bootstrap(); // (1) b.group(_workerGroup); // (2) b.channel(NioSocketChannel.class); // (3) b.option(ChannelOption.SO_KEEPALIVE, true); // (4) } catch (SSLException e) { e.printStackTrace(); } }
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; }
@Test public void https() throws Exception { ClientFactory clientFactory = new ClientFactoryBuilder() .sslContextCustomizer(b -> b.trustManager(InsecureTrustManagerFactory.INSTANCE)) .build(); HttpClient client = HttpClient.of(clientFactory, server().httpsUri("/")); AggregatedHttpMessage response = client.get("/jsp/index.jsp").aggregate().get(); final String actualContent = CR_OR_LF.matcher(response.content().toStringUtf8()) .replaceAll(""); assertThat(actualContent).isEqualTo( "<html><body>" + "<p>Hello, Armerian World!</p>" + "<p>Have you heard about the class 'io.netty.buffer.ByteBuf'?</p>" + "<p>Context path: </p>" + // ROOT context path "<p>Request URI: /index.jsp</p>" + "<p>Scheme: https</p>" + "</body></html>"); }
public WebSocketClient(String host, int port, String path, boolean isSSL) throws Exception { super(host, port, new Random()); String scheme = isSSL ? "wss://" : "ws://"; URI uri = new URI(scheme + host + ":" + port + path); if (isSSL) { sslCtx = SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(InsecureTrustManagerFactory.INSTANCE).build(); } else { sslCtx = null; } this.handler = new WebSocketClientHandler( WebSocketClientHandshakerFactory.newHandshaker( uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); }
@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(); } }
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; }
public RPCClient(String host, int port) throws Exception { SslContext sslCtx = null ; if(SSL) { sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); } eventLoopGroup = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(eventLoopGroup) .channel(NioSocketChannel.class) .handler(new RPCClientInitializer(sslCtx)); // Make a new connection. channel = b.connect(host, port).sync().channel(); // Get the handler instance to initiate the request. handler = channel.pipeline().get(RPCClientHandler.class); this.rpcChannel = new RPCChannelClient(this) ; }
@Override public void init() { try { WampClientBuilder builder = new WampClientBuilder(); builder.witUri(serverURI) .withRealm(realm) .withSslContext(SslContext.newClientContext( InsecureTrustManagerFactory.INSTANCE)) .withInfiniteReconnects() .withReconnectInterval(5, TimeUnit.SECONDS); client = builder.build(); client.statusChanged().subscribe((WampClient.Status newStatus) -> { if(WampClient.Status.Connected == newStatus) { logger.debug("Connected to WAMP router [{}]", serverURI); } else if(WampClient.Status.Connecting == newStatus) { logger.debug("Connecting to WAMP router [{}]", serverURI); } }); client.open(); } catch(Exception ex) { logger.error(ex.getMessage(), ex); } }
private static void addClientEncryption(ChannelHandlerContext ctx) throws SSLException { SslContext sslCtx; ID id = Modules.getInstance().getConfiguration().getNetMap().getId(); if (id != null) { sslCtx = SslContext.newClientContext(id.getCertificate(), InsecureTrustManagerFactory.INSTANCE); logger.debug("client using certificate {} from configured id to create ssl context", id.getCertificate().getAbsolutePath()); } else { sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE); logger.debug("client creating self signed certificate to create ssl context"); } Channel ch = ctx.pipeline().channel(); InetSocketAddress address = (InetSocketAddress) ch.remoteAddress(); ctx.pipeline().addFirst(sslCtx.newHandler(ch.alloc(), address.getHostString(), address.getPort())); }
ChannelHandler newSslInitiator() { return new ByteToMessageDecoder() { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if(in.readableBytes() < 1) { return; } if('S' != in.readByte()) { ctx.fireExceptionCaught(new IllegalStateException("SSL required but not supported by backend server")); return; } ctx.pipeline().remove(this); ctx.pipeline().addFirst( SslContextBuilder .forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .build() .newHandler(ctx.alloc())); } }; }
public synchronized SSLContext sslContext() { if (sslContext == null || ConfigurationProperties.rebuildKeyStore()) { try { // key manager KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(loadOrCreateKeyStore(), ConfigurationProperties.javaKeyStorePassword().toCharArray()); // ssl context sslContext = getSSLContextInstance(); sslContext.init(keyManagerFactory.getKeyManagers(), InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null); } catch (Exception e) { throw new RuntimeException("Failed to initialize the SSLContext", e); } } return sslContext; }
private void init() throws Exception { //注册BouncyCastleProvider加密库 Security.addProvider(new BouncyCastleProvider()); if (serverConfig == null) { serverConfig = new HttpProxyServerConfig(); serverConfig.setClientSslCtx( SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build()); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); X509Certificate certificate = CertUtil.loadCert(classLoader.getResourceAsStream("ca.crt")); //读取CA证书使用者信息 serverConfig.setIssuer(CertUtil.getSubject(certificate)); //读取CA证书有效时段(server证书有效期超出CA证书的,在手机上会提示证书不安全) serverConfig.setCaNotBefore(certificate.getNotBefore()); serverConfig.setCaNotAfter(certificate.getNotAfter()); //CA私钥用于给动态生成的网站SSL证书签证 serverConfig .setCaPriKey(CertUtil.loadPriKey(classLoader.getResourceAsStream("ca_private.der"))); //生产一对随机公私钥用于网站SSL证书动态创建 KeyPair keyPair = CertUtil.genKeyPair(); serverConfig.setServerPriKey(keyPair.getPrivate()); serverConfig.setServerPubKey(keyPair.getPublic()); serverConfig.setLoopGroup(new NioEventLoopGroup()); } if (proxyInterceptInitializer == null) { proxyInterceptInitializer = new HttpProxyInterceptInitializer(); } if (httpProxyExceptionHandle == null) { httpProxyExceptionHandle = new HttpProxyExceptionHandle(); } }
public static SslContext ctxForClient(NitmProxyConfig config) throws SSLException { SslContextBuilder builder = SslContextBuilder .forClient() .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(applicationProtocolConfig(config, config.isServerHttp2())); if (config.isInsecure()) { builder.trustManager(InsecureTrustManagerFactory.INSTANCE); } return builder.build(); }
@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(Names.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"); } }
public static void main(String[] args) throws Exception { // Configure SSL.git 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) .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(); } }
public static SSLContext createContext() { try { JdkSslContext nettyContext = (JdkSslContext) SslContextBuilder .forServer(getKeyManagerFactory()) .sslProvider(SslProvider.JDK) .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); return nettyContext.context(); } catch (Exception e) { throw new RuntimeException(e); } }
private SslContext sslContext(String scheme) { if (scheme.equalsIgnoreCase("https")) { SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(defaultClientProvider()); if (configuration.trustAllCertificates()) { builder.trustManager(InsecureTrustManagerFactory.INSTANCE); } return invokeSafely(builder::build); } return null; }
@BeforeClass public static void before() throws Exception { sut = new EvaluationServer(9092); sut.start(); X509TrustManager trustManager = (X509TrustManager) InsecureTrustManagerFactory.INSTANCE.getTrustManagers()[0]; SSLSocketFactory sslSocketFactory = createSslSocketFactory(trustManager); client = new OkHttpClient.Builder() // .sslSocketFactory(sslSocketFactory, trustManager) // .build(); }
protected SSLContext initSslContext() throws GeneralSecurityException, IOException { SSLContext context = SSLContext.getInstance("TLS"); TrustManager[] trustManagers = InsecureTrustManagerFactory.INSTANCE .getTrustManagers(); context.init(null, trustManagers, null); return context; }
private SslContext getSslContext(AsyncHttpClientConfig config) throws SSLException { if (config.getSslContext() != null) return config.getSslContext(); SslContextBuilder sslContextBuilder = SslContextBuilder.forClient()// .sslProvider(config.isUseOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK)// .sessionCacheSize(config.getSslSessionCacheSize())// .sessionTimeout(config.getSslSessionTimeout()); if (config.isAcceptAnyCertificate()) sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); return sslContextBuilder.build(); }
public HttpClient(String uri, boolean useInsecureTrustManagerFactory) throws URISyntaxException, UnsupportedOperationException { trustManagerFactory = useInsecureTrustManagerFactory ? InsecureTrustManagerFactory.INSTANCE : null; bootstrap = new Bootstrap(); httpRequest = new HttpRequest(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri)); if (!httpRequest().uriObject().getScheme().equalsIgnoreCase("http") && !httpRequest().uriObject().getScheme().equalsIgnoreCase("https")) { String message = "HTTP(S) is supported only."; logger.error(message); throw new UnsupportedOperationException(message); } }
public MqttClient(String uri, boolean useInsecureTrustManagerFactory) throws URISyntaxException { this.bootstrap = new Bootstrap(); this.uri = new URI(uri); this.trustManagerFactory = useInsecureTrustManagerFactory ? InsecureTrustManagerFactory.INSTANCE : null; this.sharedObject = new SharedObject(); this.options = new ConnectOptions(); this.currentMessageId = 0; }
/** * creates ClientHandler channel to connect and communicate with server * * @param serviceUrl * @param latch * @return * @throws URISyntaxException */ public static NioEventLoopGroup connectToService(String serviceUrl, CountDownLatch latch, boolean tls) throws URISyntaxException { NioEventLoopGroup workerGroup = new NioEventLoopGroup(); Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { if (tls) { SslContextBuilder builder = SslContextBuilder.forClient(); builder.trustManager(InsecureTrustManagerFactory.INSTANCE); X509Certificate[] certificates = SecurityUtility .loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH); PrivateKey privateKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH); builder.keyManager(privateKey, (X509Certificate[]) certificates); SslContext sslCtx = builder.build(); ch.pipeline().addLast("tls", sslCtx.newHandler(ch.alloc())); } ch.pipeline().addLast(new ClientHandler(latch)); } }); URI uri = new URI(serviceUrl); InetSocketAddress serviceAddress = new InetSocketAddress(uri.getHost(), uri.getPort()); b.connect(serviceAddress).addListener((ChannelFuture future) -> { if (!future.isSuccess()) { throw new IllegalStateException(future.cause()); } }); return workerGroup; }
private String makeHttpRequest(boolean useTls, boolean useAuth) throws Exception { InputStream response = null; try { if (useTls) { KeyManager[] keyManagers = null; if (useAuth) { Certificate[] tlsCert = SecurityUtility.loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH); PrivateKey tlsKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setKeyEntry("private", tlsKey, "".toCharArray(), tlsCert); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, "".toCharArray()); keyManagers = kmf.getKeyManagers(); } TrustManager[] trustManagers = InsecureTrustManagerFactory.INSTANCE.getTrustManagers(); SSLContext sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(keyManagers, trustManagers, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory()); response = new URL(BROKER_LOOKUP_URL_TLS).openStream(); } else { response = new URL(BROKER_LOOKUP_URL).openStream(); } String resp = CharStreams.toString(new InputStreamReader(response)); log.info("Response: {}", resp); return resp; } finally { Closeables.close(response, false); } }
@Override protected void initChannel(SocketChannel ch) throws Exception { if (enableTLS) { File tlsCert = new File(serviceConfig.getTlsCertificateFilePath()); File tlsKey = new File(serviceConfig.getTlsKeyFilePath()); SslContextBuilder builder = SslContextBuilder.forServer(tlsCert, tlsKey); // allows insecure connection builder.trustManager(InsecureTrustManagerFactory.INSTANCE); SslContext sslCtx = builder.clientAuth(ClientAuth.OPTIONAL).build(); ch.pipeline().addLast(TLS_HANDLER, sslCtx.newHandler(ch.alloc())); } ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4)); ch.pipeline().addLast("handler", new ProxyConnection(proxyService)); }
public static SslContext createNettySslContext(boolean allowInsecureConnection, String trustCertsFilePath, Certificate[] certificates, PrivateKey privateKey) throws GeneralSecurityException, SSLException, FileNotFoundException { SslContextBuilder builder = SslContextBuilder.forClient(); if (allowInsecureConnection) { builder.trustManager(InsecureTrustManagerFactory.INSTANCE); } else { if (trustCertsFilePath != null && trustCertsFilePath.length() != 0) { builder.trustManager(new FileInputStream(trustCertsFilePath)); } } builder.keyManager(privateKey, (X509Certificate[]) certificates); return builder.build(); }
public static SSLContext createSslContext(boolean allowInsecureConnection, Certificate[] trustCertficates, Certificate[] certificates, PrivateKey privateKey) throws GeneralSecurityException { KeyStoreHolder ksh = new KeyStoreHolder(); TrustManager[] trustManagers = null; KeyManager[] keyManagers = null; // Set trusted certificate 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(); } // Set private key and certificate if (certificates != null && privateKey != null) { ksh.setPrivateKey("private", privateKey, certificates); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ksh.getKeyStore(), "".toCharArray()); keyManagers = kmf.getKeyManagers(); } SSLContext sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(keyManagers, trustManagers, new SecureRandom()); return sslCtx; }
private static SslContext createNettyClientSSlContext() { try { return SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } catch (SSLException e) { throw new SSLContextException(e); } }
@Override public SslContext createInsecureClientSslCtx(IConfig cfg) { SslContext clientCtx = null; try{ clientCtx = SslContextBuilder.forClient() .sslProvider(SslProvider.JDK) .trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); }catch(Exception e){ LOG.log(Level.SEVERE, null, e); } return clientCtx; }
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(); } }