@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(); } }
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); }); }
private static SslContext newNettyClientContext( io.netty.handler.ssl.SslProvider sslProvider, boolean useAlpn) { try { TestKeyStore server = TestKeyStore.getServer(); SslContextBuilder ctx = SslContextBuilder.forClient() .sslProvider(sslProvider) .trustManager((X509Certificate[]) server.getPrivateKey("RSA", "RSA") .getCertificateChain()); if (useAlpn) { ctx.applicationProtocolConfig(OpenJdkEngineFactoryConfig.NETTY_ALPN_CONFIG); } return ctx.build(); } catch (SSLException e) { throw new RuntimeException(e); } }
private static SslContext newNettyServerContext( io.netty.handler.ssl.SslProvider sslProvider, boolean useAlpn) { try { PrivateKeyEntry server = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); SslContextBuilder ctx = SslContextBuilder .forServer(server.getPrivateKey(), (X509Certificate[]) server.getCertificateChain()) .sslProvider(sslProvider); if (useAlpn) { ctx.applicationProtocolConfig(OpenJdkEngineFactoryConfig.NETTY_ALPN_CONFIG); } return ctx.build(); } catch (SSLException e) { throw new RuntimeException(e); } }
private static void configureSsl(SslConfiguration sslConfiguration, SslContextBuilder sslContextBuilder) { try { if (sslConfiguration.getTrustStoreConfiguration().isPresent()) { sslContextBuilder.trustManager(createTrustManagerFactory(sslConfiguration .getTrustStoreConfiguration())); } if (sslConfiguration.getKeyStoreConfiguration().isPresent()) { sslContextBuilder.keyManager(createKeyManagerFactory(sslConfiguration .getKeyStoreConfiguration())); } } catch (GeneralSecurityException | IOException e) { throw new IllegalStateException(e); } }
private static SslContext getSSLContext() throws IOException, GeneralSecurityException { try { final String privateKeyFile = "keys/server.pkcs8.key"; final String certificateFile = "keys/server.crt"; final String rootCAFile = "keys/rootCA.pem"; final PrivateKey privateKey = loadPrivateKey(privateKeyFile); final X509Certificate certificate = loadX509Cert(certificateFile); final X509Certificate rootCA = loadX509Cert(rootCAFile); return SslContextBuilder.forClient() .sslProvider(SslProvider.JDK) .trustManager(rootCA) .keyManager(privateKey, certificate) .build(); } catch (IOException | GeneralSecurityException e) { LOGGER.warn("Failed to establish SSL Context"); LOGGER.debug("Failed to establish SSL Context", e); throw e; } }
@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(); } }
/** * Creates a netty SslContext for use when connecting to upstream servers. Retrieves the list of trusted root CAs * from the trustSource. When trustSource is true, no upstream certificate verification will be performed. * <b>This will make it possible for attackers to MITM communications with the upstream server</b>, so always * supply an appropriate trustSource except in extraordinary circumstances (e.g. testing with dynamically-generated * certificates). * * @param cipherSuites cipher suites to allow when connecting to the upstream server * @param trustSource the trust store that will be used to validate upstream servers' certificates, or null to accept all upstream server certificates * @return an SSLContext to connect to upstream servers with */ public static SslContext getUpstreamServerSslContext(Collection<String> cipherSuites, TrustSource trustSource) { SslContextBuilder sslContextBuilder = SslContextBuilder.forClient(); if (trustSource == null) { log.warn("Disabling upstream server certificate verification. This will allow attackers to intercept communications with upstream servers."); sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); } else { sslContextBuilder.trustManager(trustSource.getTrustedCAs()); } sslContextBuilder.ciphers(cipherSuites, SupportedCipherSuiteFilter.INSTANCE); try { return sslContextBuilder.build(); } catch (SSLException e) { throw new SslContextInitializationException("Error creating new SSL context for connection to upstream server", e); } }
@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 -> applyHostAndPortFromContext(opt, context) .sslContext(sslClient)) .get("/foo").block(); context.dispose(); context.onClose().block(); String responseString = response.receive().aggregate().asString(CharsetUtil.UTF_8).block(); assertThat(responseString).isEqualTo("hello /foo"); }
private SslContext getNettySslContextInner(String host, boolean useH2) throws Exception { long start = System.currentTimeMillis(); PrivateKeyAndCertChain keyAndCertChain = keyStoreGenerator.generateCertChain(host, Settings.certValidityDays); logger.debug("Create certificate for {}, cost {} ms", host, System.currentTimeMillis() - start); SslContextBuilder builder = SslContextBuilder .forServer(keyAndCertChain.getPrivateKey(), keyAndCertChain.getCertificateChain()); if (useH2) { // .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) builder.applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)); } return builder.build(); }
/** * Creates a new SslContext object. * * @param cfg the cfg * @return the ssl context */ private synchronized SslContext createServerSslContext(IConfig cfg){ SslContext ctx = null; try{ SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; if(provider.equals(SslProvider.OPENSSL)){ cfg.print("Using OpenSSL for network encryption."); } ctx = SslContextBuilder .forServer(new File(cfg.getCertFile()), new File(cfg.getKeyFile()), cfg.getKeyPassword()) .sslProvider(provider) .build(); }catch(Exception e){ LOG.log(Level.SEVERE, null, e); } return ctx; }
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new FactorialServerInitializer(sslCtx)); b.bind(PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
public static void main(String[] args) throws Exception { SelfSignedCertificate ssc = new SelfSignedCertificate(); SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) .build(); EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new SecureChatServerInitializer(sslCtx)); b.bind(PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HttpCorsServerInitializer(sslCtx)); b.bind(PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new WorldClockServerInitializer(sslCtx)); b.bind(PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new TelnetServerInitializer(sslCtx)); b.bind(PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
public SslHandler build(ByteBufAllocator bufferAllocator) throws SSLException { SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase); builder.ciphers(Arrays.asList(ciphers)); if(requireClientAuth()) { logger.debug("Certificate Authorities: " + certificateAuthorities); builder.trustManager(new File(certificateAuthorities)); } SslContext context = builder.build(); SslHandler sslHandler = context.newHandler(bufferAllocator); SSLEngine engine = sslHandler.engine(); engine.setEnabledProtocols(protocols); if(requireClientAuth()) { engine.setUseClientMode(false); engine.setNeedClientAuth(true); } return sslHandler; }
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(); }
@Override protected void initChannel(C channel) throws Exception { BackendProtocol protocol = (BackendProtocol) channel.attr(PROTOCOL_KEY).get(); checkNotNull(protocol, "Protocol is not set for channel: %s", channel); SslHandler sslHandler = SslContextBuilder.forClient() .sslProvider(sslProvider) .trustManager(trustedCertificates) .build() .newHandler(channel.alloc(), protocol.host(), protocol.port()); // Enable hostname verification. SSLEngine sslEngine = sslHandler.engine(); SSLParameters sslParameters = sslEngine.getSSLParameters(); sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); sslEngine.setSSLParameters(sslParameters); channel.pipeline().addLast(sslHandler); }
private ChannelInitializer<LocalChannel> getServerInitializer( PrivateKey privateKey, X509Certificate certificate, Lock serverLock, Exception serverException) throws Exception { SslContext sslContext = SslContextBuilder.forServer(privateKey, certificate).build(); return new ChannelInitializer<LocalChannel>() { @Override protected void initChannel(LocalChannel ch) throws Exception { ch.pipeline() .addLast( sslContext.newHandler(ch.alloc()), new EchoHandler(serverLock, serverException)); } }; }
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(); } }
public SslContext buildOpenSslClientContext(final boolean clientAuth) throws IOException { SslContext ctx; if (clientAuth) { ctx = SslContextBuilder.forClient() .sslProvider(SslProvider.OPENSSL) .trustManager(getTrustCertChainPath().toAbsolutePath().normalize().toFile()) .keyManager(getClientCertPath().toAbsolutePath().normalize().toFile(), getClientKeyPath().toAbsolutePath().normalize().toFile()) .build(); } else { ctx = SslContextBuilder.forClient() .sslProvider(SslProvider.OPENSSL) .trustManager(getTrustCertChainPath().toAbsolutePath().normalize().toFile()) .build(); } return ctx; }
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; }
private SslContext buildSSLServerContext(final PrivateKey _key, final X509Certificate[] _cert, final X509Certificate[] _trustedCerts, final Iterable<String> ciphers, final SslProvider sslProvider, final ClientAuth authMode) throws SSLException { final SslContextBuilder _sslContextBuilder = SslContextBuilder .forServer(_key, _cert) .ciphers(ciphers) .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED) .clientAuth(Objects.requireNonNull(authMode)) // https://github.com/netty/netty/issues/4722 .sessionCacheSize(0) .sessionTimeout(0) .sslProvider(sslProvider); if(_trustedCerts != null && _trustedCerts.length > 0) { _sslContextBuilder.trustManager(_trustedCerts); } return buildSSLContext0(_sslContextBuilder); }
private SslContext buildSSLServerContext(final File _key, final File _cert, final File _trustedCerts, final String pwd, final Iterable<String> ciphers, final SslProvider sslProvider, final ClientAuth authMode) throws SSLException { final SslContextBuilder _sslContextBuilder = SslContextBuilder .forServer(_cert, _key, pwd) .ciphers(ciphers) .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED) .clientAuth(Objects.requireNonNull(authMode)) // https://github.com/netty/netty/issues/4722 .sessionCacheSize(0) .sessionTimeout(0) .sslProvider(sslProvider); if(_trustedCerts != null) { _sslContextBuilder.trustManager(_trustedCerts); } return buildSSLContext0(_sslContextBuilder); }
private SslContext buildSSLClientContext(final PrivateKey _key, final X509Certificate[] _cert, final X509Certificate[] _trustedCerts, final Iterable<String> ciphers, final SslProvider sslProvider) throws SSLException { final SslContextBuilder _sslClientContextBuilder = SslContextBuilder .forClient() .ciphers(ciphers) .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED) .sessionCacheSize(0) .sessionTimeout(0) .sslProvider(sslProvider) .trustManager(_trustedCerts) .keyManager(_key, _cert); return buildSSLContext0(_sslClientContextBuilder); }
private SslContext buildSSLClientContext(final File _key, final File _cert, final File _trustedCerts, final String pwd, final Iterable<String> ciphers, final SslProvider sslProvider) throws SSLException { final SslContextBuilder _sslClientContextBuilder = SslContextBuilder .forClient() .ciphers(ciphers) .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED) .sessionCacheSize(0) .sessionTimeout(0) .sslProvider(sslProvider) .trustManager(_trustedCerts) .keyManager(_cert, _key, pwd); return buildSSLContext0(_sslClientContextBuilder); }
private SslContext buildSSLContext0(final SslContextBuilder sslContextBuilder) throws SSLException { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(new SpecialPermission()); } SslContext sslContext = null; try { sslContext = AccessController.doPrivileged(new PrivilegedExceptionAction<SslContext>() { @Override public SslContext run() throws Exception { return sslContextBuilder.build(); } }); } catch (final PrivilegedActionException e) { throw (SSLException) e.getCause(); } return sslContext; }
/** * 私有构造函数 */ private NettyCenter() { int maybeThreadSize = Runtime.getRuntime().availableProcessors(); if (maybeThreadSize == 1) maybeThreadSize += 2; else if (maybeThreadSize == 8) maybeThreadSize = 2; else if (maybeThreadSize > 8) maybeThreadSize /= 2; /** * 构造事件循环组 */ eventLoopGroup = new NioEventLoopGroup(maybeThreadSize, new DefaultThreadFactory("NettyNioLoopGroup")); /** * 构造定时器 */ hashedWheelTimer = new HashedWheelTimer(new DefaultThreadFactory("NettyHashedWheelTimer")); /** * 构造 SSL 环境 */ try { SslContextBuilder sslContextBuilder = SslContextBuilder.forClient(); sslContextBuilder.clientAuth(ClientAuth.OPTIONAL); simpleClientSslContext = sslContextBuilder.build(); } catch (Throwable e) { log.error("NettyCenter :: initialize client sslcontext error!", e); } }
/** * Sets the {@link SslContext} of this {@link VirtualHost} from the specified {@link SessionProtocol}, * {@code keyCertChainFile}, {@code keyFile} and {@code keyPassword}. */ public B sslContext( SessionProtocol protocol, File keyCertChainFile, File keyFile, String keyPassword) throws SSLException { if (requireNonNull(protocol, "protocol") != SessionProtocol.HTTPS) { throw new IllegalArgumentException("unsupported protocol: " + protocol); } final SslContextBuilder builder = SslContextBuilder.forServer(keyCertChainFile, keyFile, keyPassword); builder.sslProvider(Flags.useOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK); builder.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE); builder.applicationProtocolConfig(HTTPS_ALPN_CFG); sslContext(builder.build()); return self(); }
/** * This method will provide netty ssl context which supports HTTP2 over TLS using * Application Layer Protocol Negotiation (ALPN) * * @return instance of {@link SslContext} * @throws SSLException if any error occurred during building SSL context. */ public SslContext createHttp2TLSContext() throws SSLException { // If listener configuration does not include cipher suites , default ciphers required by the HTTP/2 // specification will be added. List<String> ciphers = sslConfig.getCipherSuites() != null && sslConfig.getCipherSuites().length > 0 ? Arrays .asList(sslConfig.getCipherSuites()) : Http2SecurityUtil.CIPHERS; SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; return SslContextBuilder.forServer(this.getKeyManagerFactory()) .trustManager(this.getTrustStoreFactory()) .sslProvider(provider) .ciphers(ciphers, SupportedCipherSuiteFilter.INSTANCE) .clientAuth(needClientAuth ? ClientAuth.REQUIRE : ClientAuth.NONE) .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(); }
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())); }
public static SslContext build(File serverCert, File serverKey, String serverPass, SslProvider sslProvider, File clientCert) throws SSLException { log.info("Creating SSL context for cert '{}', key '{}', key pass '{}'", serverCert.getAbsolutePath(), serverKey.getAbsoluteFile(), serverPass); if (serverPass == null || serverPass.isEmpty()) { return SslContextBuilder.forServer(serverCert, serverKey) .sslProvider(sslProvider) .trustManager(clientCert) .build(); } else { return SslContextBuilder.forServer(serverCert, serverKey, serverPass) .sslProvider(sslProvider) .trustManager(clientCert) .build(); } }
@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(); } }
/** * Builds SslContext using protected keystore file overriding default key manger algorithm. Adequate for non-mutual TLS connections. * * @param keystore Keystore inputstream (file, binaries, etc) * @param keystorePassword Password for protected keystore file * @param keyManagerAlgorithm Algorithm for keyManager used to process keystorefile * @return SslContext ready to use * @throws SecurityContextException for any troubles building the SslContext */ public static SslContext forKeystore(InputStream keystore, String keystorePassword, String keyManagerAlgorithm) throws SecurityContextException { try { final KeyStore ks = KeyStore.getInstance(KEYSTORE_JKS); final KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm); ks.load(keystore, keystorePassword.toCharArray()); kmf.init(ks, keystorePassword.toCharArray()); SslContextBuilder ctxBuilder = SslContextBuilder.forClient().keyManager(kmf); return ctxBuilder.build(); } catch (Exception e) { throw new SecurityContextException(e); } }
/** * Builds SslContext using protected keystore and truststores, overriding default key manger algorithm. Adequate for mutual TLS connections. * @param keystore Keystore inputstream (file, binaries, etc) * @param keystorePassword Password for protected keystore file * @param truststore Truststore inputstream (file, binaries, etc) * @param truststorePassword Password for protected truststore file * @param keyManagerAlgorithm Algorithm for keyManager used to process keystorefile * @return SslContext ready to use * @throws SecurityContextException */ public static SslContext forKeystoreAndTruststore(InputStream keystore, String keystorePassword, InputStream truststore, String truststorePassword, String keyManagerAlgorithm) throws SecurityContextException { try { final KeyStore ks = KeyStore.getInstance(KEYSTORE_JKS); final KeyStore ts = KeyStore.getInstance(KEYSTORE_JKS); final KeyManagerFactory keystoreKmf = KeyManagerFactory.getInstance(keyManagerAlgorithm); final TrustManagerFactory truststoreKmf = TrustManagerFactory.getInstance(keyManagerAlgorithm); ks.load(keystore, keystorePassword.toCharArray()); ts.load(truststore, truststorePassword.toCharArray()); keystoreKmf.init(ks, keystorePassword.toCharArray()); truststoreKmf.init(ts); SslContextBuilder ctxBuilder = SslContextBuilder.forClient().keyManager(keystoreKmf); ctxBuilder.trustManager(truststoreKmf); return ctxBuilder.build(); } catch (Exception e) { throw new SecurityContextException(e); } }
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())); } }; }
static SslContext build(final Config conf) throws IOException, CertificateException { String tmpdir = conf.getString("application.tmpdir"); boolean http2 = conf.getBoolean("server.http2.enabled"); File keyStoreCert = toFile(conf.getString("ssl.keystore.cert"), tmpdir); File keyStoreKey = toFile(conf.getString("ssl.keystore.key"), tmpdir); String keyStorePass = conf.hasPath("ssl.keystore.password") ? conf.getString("ssl.keystore.password") : null; SslContextBuilder scb = SslContextBuilder.forServer(keyStoreCert, keyStoreKey, keyStorePass); if (conf.hasPath("ssl.trust.cert")) { scb.trustManager(toFile(conf.getString("ssl.trust.cert"), tmpdir)) .clientAuth(ClientAuth.REQUIRE); } if (http2) { SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; return scb.sslProvider(provider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig( Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, Arrays.asList(ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))) .build(); } return scb.build(); }