List of usage examples for io.netty.handler.ssl SslContextBuilder forClient
public static SslContextBuilder forClient()
From source file:org.jboss.aerogear.webpush.WebPushClient.java
License:Apache License
private SslContext configureSsl() throws SSLException { if (!ssl) {/*from ww w . j ava 2 s .c o m*/ return null; } return SslContextBuilder.forClient().sslProvider(SslProvider.JDK) .trustManager(InsecureTrustManagerFactory.INSTANCE) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.FATAL_ALERT, SelectedListenerFailureBehavior.FATAL_ALERT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); }
From source file:org.jdiameter.client.impl.transport.tls.netty.SslContextFactory.java
License:Open Source License
public static SslContext getSslContextForClient(Configuration config) throws SSLException, Exception { SslContext sslContext = SslContextBuilder.forClient().keyManager(getKeyManagerFactory(config)) .trustManager(getTrustManagerFactory(config)).build(); return sslContext; }
From source file:org.jfxvnc.net.rfb.codec.ProtocolHandler.java
License:Apache License
@Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception { if (config.sslProperty().get()) { if (sslContext == null) { sslContext = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build();/*from w ww. j a v a 2 s. c o m*/ } ctx.pipeline().addFirst("ssl-handler", sslContext.newHandler(ctx.channel().alloc())); } super.channelRegistered(ctx); }
From source file:org.kaazing.messaging.driver.transport.netty.tcp.NettyTransportContext.java
License:Apache License
public NettyTransportContext() { super();//from w ww. j av a 2 s . com if (USE_SSL) { SelfSignedCertificate ssc = null; try { ssc = new SelfSignedCertificate(); serverSslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); clientSslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE) .build(); } catch (CertificateException e) { LOGGER.error("CertificateException", e); throw new IllegalArgumentException("Error creating transport context", e); } catch (SSLException e) { LOGGER.error("SSLException", e); throw new IllegalArgumentException("Error creating transport context", e); } } else { serverSslCtx = null; clientSslCtx = null; } // Configure the server. serverBossGroup = new NioEventLoopGroup(1); serverWorkerGroup = new NioEventLoopGroup(); serverBootstrap = new ServerBootstrap(); serverBootstrap.group(serverBossGroup, serverWorkerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { final ChannelPipeline p = ch.pipeline(); if (serverSslCtx != null) { p.addLast(serverSslCtx.newHandler(ch.alloc())); } p.addLast(new LengthFieldBasedFrameDecoder(1000000, 0, 4, 0, 4)); serverReceivingTransportsLock.readLock().lock(); try { serverReceivingTransports.forEach((nettyReceivingTransport) -> { if (ch.localAddress().equals(nettyReceivingTransport.getInetSocketAddress()) || nettyReceivingTransport.isInAddrAny() && ch.localAddress().getPort() == nettyReceivingTransport .getInetSocketAddress().getPort()) { p.addLast(nettyReceivingTransport.getNettyChannelHandler()); } }); } finally { serverReceivingTransportsLock.readLock().unlock(); } } }); bootstrap = new Bootstrap(); group = new NioEventLoopGroup(); bootstrap.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 (clientSslCtx != null) { p.addLast(clientSslCtx.newHandler(ch.alloc())); } } }); }
From source file:org.kurento.jsonrpc.client.JsonRpcClientNettyWebSocket.java
License:Apache License
@Override protected void connectNativeClient() throws TimeoutException, Exception { if (channel == null || !channel.isActive() || group == null || group.isShuttingDown() || group.isShutdown()) {//from w ww . jav a 2s. co m log.info("{} Connecting native client", label); final boolean ssl = "wss".equalsIgnoreCase(this.uri.getScheme()); final SslContext sslCtx; try { sslCtx = ssl ? SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build() : null; } catch (SSLException e) { log.error("{} Could not create SSL Context", label, e); throw new IllegalArgumentException("Could not create SSL context. See logs for more details", e); } final String scheme = uri.getScheme() == null ? "ws" : uri.getScheme(); final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final int port; if (uri.getPort() == -1) { if ("ws".equalsIgnoreCase(scheme)) { port = 80; } else if ("wss".equalsIgnoreCase(scheme)) { port = 443; } else { port = -1; } } else { port = uri.getPort(); } if (group == null || group.isShuttingDown() || group.isShutdown() || group.isTerminated()) { log.info("{} Creating new NioEventLoopGroup", label); group = new NioEventLoopGroup(); } if (channel != null) { log.info("{} Closing previously existing channel when connecting native client", label); closeChannel(); } Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { log.info("{} Inititating new Netty channel. Will create new handler too!", label); handler = new JsonRpcWebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders(), maxPacketSize)); ChannelPipeline p = ch.pipeline(); p.addLast("idleStateHandler", new IdleStateHandler(0, 0, idleTimeout / 1000)); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc(), host, port)); } p.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), WebSocketClientCompressionHandler.INSTANCE, handler); } }).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, this.connectionTimeout); int numRetries = 0; final int maxRetries = 5; while (channel == null || !channel.isOpen()) { try { channel = b.connect(host, port).sync().channel(); handler.handshakeFuture().sync(); } catch (InterruptedException e) { // This should never happen log.warn("{} ERROR connecting WS Netty client, opening channel", label, e); } catch (Exception e) { if (e.getCause() instanceof WebSocketHandshakeException && numRetries < maxRetries) { log.warn( "{} Upgrade exception when trying to connect to {}. Try {} of {}. Retrying in 200ms ", label, uri, numRetries + 1, maxRetries); Thread.sleep(200); numRetries++; } else { throw e; } } } channel.closeFuture().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.info("{} channel closed", label); handleReconnectDisconnection(1001, "Channel closed"); } }); } }
From source file:org.ow2.petals.bc.gateway.commons.handlers.AuthenticatorSSLHandler.java
License:Open Source License
private void setUpSslHandlers(final ChannelHandlerContext ctx, final AbstractDomain domain, final @Nullable String certificate, final @Nullable String key, final @Nullable String passphrase, final @Nullable String remoteCertificate) throws SSLException { // TODO could we use certificate only for auth and not encryption? // TODO support openssl final SslHandler sslHandler; if (pdOrAuth.isB() && certificate != null && key != null) { // server side ssl, do not forget startTls so that our accept can be sent after the handler is added final ServiceUnitDataHandler handler = domain.getSUHandler(); final SslContextBuilder builder = SslContextBuilder .forServer(ServiceUnitUtil.getFile(handler.getInstallRoot(), certificate), ServiceUnitUtil.getFile(handler.getInstallRoot(), key), passphrase) .sslProvider(SslProvider.JDK).ciphers(null, IdentityCipherSuiteFilter.INSTANCE) .sessionCacheSize(0).sessionTimeout(0); if (remoteCertificate != null) { builder.trustManager(ServiceUnitUtil.getFile(handler.getInstallRoot(), remoteCertificate)) .clientAuth(ClientAuth.REQUIRE); }//from w ww .j a v a2s. c om // until https://github.com/netty/netty/issues/5170 is accepted // we need to create the handler by hand sslHandler = new SslHandler(builder.build().newEngine(ctx.alloc()), true); } else if (pdOrAuth.isA() && remoteCertificate != null) { // client side final String installRoot = domain.getSUHandler().getInstallRoot(); final SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK) .trustManager(ServiceUnitUtil.getFile(installRoot, remoteCertificate)) .ciphers(null, IdentityCipherSuiteFilter.INSTANCE).sessionCacheSize(0).sessionTimeout(0); if (certificate != null && key != null) { builder.keyManager(ServiceUnitUtil.getFile(installRoot, certificate), ServiceUnitUtil.getFile(installRoot, key), passphrase); } sslHandler = builder.build().newHandler(ctx.alloc()); } else { sslHandler = null; } // For a server, it contains the transporter name and the consumer domain name (it was updated in channelRead0) // For a client, it contains the provider domain name (it was set by the component) final String logName = logger.getName(); // let's replace the debug logger with something specific to this consumer ctx.pipeline().replace(HandlerConstants.LOG_DEBUG_HANDLER, HandlerConstants.LOG_DEBUG_HANDLER, new LoggingHandler(logName, LogLevel.TRACE)); ctx.pipeline().replace(HandlerConstants.LOG_ERRORS_HANDLER, HandlerConstants.LOG_ERRORS_HANDLER, new LastLoggingHandler(logName + ".errors")); if (sslHandler != null) { // if there is a sslHandler, then we can only add the domain handler after the handshake is finished // if not we risk sending things too early in it sslHandler.handshakeFuture().addListener(new FutureListener<Channel>() { @Override public void operationComplete(final @Nullable Future<Channel> future) throws Exception { assert future != null; if (!future.isSuccess()) { authenticationFuture.setFailure(future.cause()); } else { // I must keep the handler here until now in case there is an exception so that I can log it ctx.pipeline().replace(HandlerConstants.DOMAIN_HANDLER, HandlerConstants.DOMAIN_HANDLER, dhb.build(domain)); authenticationFuture.setSuccess(ctx.channel()); } } }); ctx.pipeline().addAfter(HandlerConstants.LOG_DEBUG_HANDLER, HandlerConstants.SSL_HANDLER, sslHandler); } if (pdOrAuth.isB()) { if (logger.isLoggable(Level.FINE)) { logger.fine("Sending an Accept (" + ctx.channel().remoteAddress() + ")"); } // this must be sent after the ssh handler is replaced (when using ssl) so that we are ready to receive ssl data right away // but this must be sent before the domain handler is replaced (when not using ssl), because it will send // data and it must arrive AFTER our Accept ctx.writeAndFlush(new AuthAccept()); } // else it is done in the FutureListener if (sslHandler == null) { ctx.pipeline().replace(HandlerConstants.DOMAIN_HANDLER, HandlerConstants.DOMAIN_HANDLER, dhb.build(domain)); authenticationFuture.setSuccess(ctx.channel()); } }
From source file:org.redisson.client.handler.RedisChannelInitializer.java
License:Apache License
private void initSsl(final RedisClientConfig config, Channel ch) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, SSLException, UnrecoverableKeyException { if (!config.getAddress().isSsl()) { return;// w ww .j ava2 s. co m } io.netty.handler.ssl.SslProvider provided = io.netty.handler.ssl.SslProvider.JDK; if (config.getSslProvider() == SslProvider.OPENSSL) { provided = io.netty.handler.ssl.SslProvider.OPENSSL; } SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(provided); if (config.getSslTruststore() != null) { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream stream = config.getSslTruststore().openStream(); try { char[] password = null; if (config.getSslTruststorePassword() != null) { password = config.getSslTruststorePassword().toCharArray(); } keyStore.load(stream, password); } finally { stream.close(); } TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); sslContextBuilder.trustManager(trustManagerFactory); } if (config.getSslKeystore() != null) { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream stream = config.getSslKeystore().openStream(); char[] password = null; if (config.getSslKeystorePassword() != null) { password = config.getSslKeystorePassword().toCharArray(); } try { keyStore.load(stream, password); } finally { stream.close(); } KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, password); sslContextBuilder.keyManager(keyManagerFactory); } SSLParameters sslParams = new SSLParameters(); if (config.isSslEnableEndpointIdentification()) { // TODO remove for JDK 1.7+ try { Method method = sslParams.getClass().getDeclaredMethod("setEndpointIdentificationAlgorithm", String.class); method.invoke(sslParams, "HTTPS"); } catch (Exception e) { throw new SSLException(e); } } else { if (config.getSslTruststore() == null) { sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); } } SslContext sslContext = sslContextBuilder.build(); String hostname = config.getSslHostname(); if (hostname == null || NetUtil.createByteArrayFromIpAddressString(hostname) != null) { hostname = config.getAddress().getHost(); } SSLEngine sslEngine = sslContext.newEngine(ch.alloc(), hostname, config.getAddress().getPort()); sslEngine.setSSLParameters(sslParams); SslHandler sslHandler = new SslHandler(sslEngine); ch.pipeline().addLast(sslHandler); ch.pipeline().addLast(new ChannelInboundHandlerAdapter() { volatile boolean sslInitDone; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { if (sslInitDone) { super.channelActive(ctx); } } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (!sslInitDone && (evt instanceof SslHandshakeCompletionEvent)) { SslHandshakeCompletionEvent e = (SslHandshakeCompletionEvent) evt; if (e.isSuccess()) { sslInitDone = true; ctx.fireChannelActive(); } else { RedisConnection connection = RedisConnection.getFrom(ctx.channel()); connection.getConnectionPromise().tryFailure(e.cause()); } } super.userEventTriggered(ctx, evt); } }); }
From source file:org.springframework.boot.actuate.autoconfigure.cloudfoundry.reactive.ReactiveCloudFoundrySecurityService.java
License:Apache License
private SslContextBuilder createSslContext() { return SslContextBuilder.forClient().sslProvider(SslProvider.JDK) .trustManager(InsecureTrustManagerFactory.INSTANCE); }
From source file:org.springframework.boot.web.reactive.server.AbstractReactiveWebServerFactoryTests.java
License:Apache License
protected ReactorClientHttpConnector buildTrustAllSslConnector() { SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK) .trustManager(InsecureTrustManagerFactory.INSTANCE); HttpClient client = HttpClient.create().wiretap(true) .secure((sslContextSpec) -> sslContextSpec.sslContext(builder)); return new ReactorClientHttpConnector(client); }
From source file:org.springframework.boot.web.reactive.server.AbstractReactiveWebServerFactoryTests.java
License:Apache License
protected ReactorClientHttpConnector buildTrustAllSslWithClientKeyConnector() throws Exception { KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); clientKeyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray()); KeyManagerFactory clientKeyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); clientKeyManagerFactory.init(clientKeyStore, "password".toCharArray()); for (KeyManager keyManager : clientKeyManagerFactory.getKeyManagers()) { if (keyManager instanceof X509KeyManager) { X509KeyManager x509KeyManager = (X509KeyManager) keyManager; PrivateKey privateKey = x509KeyManager.getPrivateKey("spring-boot"); if (privateKey != null) { X509Certificate[] certificateChain = x509KeyManager.getCertificateChain("spring-boot"); SslContextBuilder builder = SslContextBuilder.forClient().sslProvider(SslProvider.JDK) .trustManager(InsecureTrustManagerFactory.INSTANCE) .keyManager(privateKey, certificateChain); HttpClient client = HttpClient.create().wiretap(true) .secure((sslContextSpec) -> sslContextSpec.sslContext(builder)); return new ReactorClientHttpConnector(client); }/*www .j a v a 2s . co m*/ } } throw new IllegalStateException("Key with alias 'spring-boot' not found"); }