@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)); }
static ClientHttpRequestFactory usingNetty(ClientOptions options) throws IOException, GeneralSecurityException { SslContext sslContext = new JdkSslContext(SSLContext.getDefault(), true, ClientAuth.REQUIRE); final Netty4ClientHttpRequestFactory requestFactory = new Netty4ClientHttpRequestFactory(); requestFactory.setSslContext(sslContext); if (options.getConnectionTimeout() != null) { requestFactory.setConnectTimeout(options.getConnectionTimeout()); } if (options.getReadTimeout() != null) { requestFactory.setReadTimeout(options.getReadTimeout()); } return requestFactory; }
@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)); }
private void initSsl(String addr, NettyRequestFactory factory) throws Exception { SSLContext sslc = SSLContext.getInstance("TLS"); if(!checkSsl) { log.debug("disable any SSL check on {} address", addr); sslc.init(null, new TrustManager[]{new SSLUtil.NullX509TrustManager()}, null); } else if(StringUtils.hasText(keystore)) { log.debug("use SSL trusted store {} on {} address", keystore, addr); final String alg = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory def = TrustManagerFactory.getInstance(alg); def.init((KeyStore)null);// initialize default list of trust managers Resource resource = resourceLoader.getResource(keystore); if(!resource.exists()) { log.warn("Specified JKS {} is not exists.", keystore); return; } KeyStore ks = KeyStore.getInstance("JKS"); try(InputStream is = resource.getInputStream()) { ks.load(is, storepass == null? new char[0] : storepass.toCharArray()); } TrustManagerFactory local = TrustManagerFactory.getInstance(alg); local.init(ks); TrustManager tm = SSLUtil.combineX509TrustManagers(local.getTrustManagers(), def.getTrustManagers()); sslc.init(null, new TrustManager[]{tm}, null); } factory.setSslContext(new JdkSslContext(sslc, true, ClientAuth.OPTIONAL)); }
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 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); } }
/** * 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 TlsConfig(Config config) { useSsl = config.getBoolean("useSsl"); logInsecureConfig = config.getBoolean("logInsecureConfig"); x509TrustedCerts = buildCerts(config.getStringList("x509TrustedCertPaths")); privateKey = parsePrivateKeyFromPem(readPathFromKey("privateKeyPath", config)); certificate = parseX509CertificateFromPem(readPathFromKey("x509CertPath", config)); x509CertChain = new ImmutableList.Builder<X509Certificate>() .add(certificate) .addAll(buildCerts(config.getStringList("x509CertChainPaths"))) .build(); useOpenSsl = config.getBoolean("useOpenSsl"); alpnConfig = buildAlpnConfig(config.getConfig("alpn")); ciphers = config.getStringList("ciphers"); clientAuth = config.getEnum(ClientAuth.class, "clientAuth"); enableOcsp = config.getBoolean("enableOcsp"); protocols = config.getStringList("protocols"); sessionCacheSize = config.getLong("sessionCacheSize"); sessionTimeout = config.getLong("sessionTimeout"); }
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(); }
/** * Creates and starts a new {@link TestServiceImpl} server. */ private Server newServer() throws CertificateException, IOException { File serverCertChainFile = TestUtils.loadCert("server1.pem"); File serverPrivateKeyFile = TestUtils.loadCert("server1.key"); X509Certificate[] serverTrustedCaCerts = { TestUtils.loadX509Cert("ca.pem") }; SslContext sslContext = GrpcSslContexts.forServer(serverCertChainFile, serverPrivateKeyFile) .trustManager(serverTrustedCaCerts) .clientAuth(ClientAuth.REQUIRE) .build(); return NettyServerBuilder.forPort(0) .sslContext(sslContext) .addService(new TestServiceImpl(serverExecutor)) .build() .start(); }
@Override protected AbstractServerImplBuilder<?> getServerBuilder() { // Starts the server with HTTPS. try { return NettyServerBuilder.forPort(0) .flowControlWindow(65 * 1024) .maxMessageSize(AbstractInteropTest.MAX_MESSAGE_SIZE) .sslContext(GrpcSslContexts .forServer(TestUtils.loadCert("server1.pem"), TestUtils.loadCert("server1.key")) .clientAuth(ClientAuth.REQUIRE) .trustManager(TestUtils.loadCert("ca.pem")) .ciphers(TestUtils.preferredTestCiphers(), SupportedCipherSuiteFilter.INSTANCE) .sslProvider(SslProvider.OPENSSL) .build()); } catch (IOException ex) { throw new RuntimeException(ex); } }
@Test public void testNewInstanceLoader() throws Exception { final SslContextReloader reloader = new SslContextReloader(() -> { return new JdkSslContext(SSLContext.getDefault(), true, ClientAuth.REQUIRE); }); assertTrue(reloader.load()); assertEquals(ReloadState.RELOADED, reloader.getReloadState()); assertNull(reloader.getDataVersion()); }
@Test public void testStaticInstanceLoader() throws Exception { final JdkSslContext context = new JdkSslContext(SSLContext.getDefault(), true, ClientAuth.REQUIRE); final SslContextReloader reloader = new SslContextReloader(() -> context); // don't invoke load here because the constructor forces load the first time assertEquals(ReloadState.RELOADED, reloader.getReloadState()); assertNull(reloader.getDataVersion()); assertFalse(reloader.load()); assertEquals(ReloadState.NO_CHANGE, reloader.getReloadState()); assertNull(reloader.getDataVersion()); }
protected SslContext createSSLContext(Configuration config) throws Exception { Configuration.Ssl sslCfg = config.getSecurity().getSsl(); Boolean generate = sslCfg.isUseGeneratedKeypair(); SslContextBuilder ssl; if (generate) { LOG.warn("Using generated self signed server certificate"); Date begin = new Date(); Date end = new Date(begin.getTime() + 86400000); SelfSignedCertificate ssc = new SelfSignedCertificate("localhost", begin, end); ssl = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()); } else { String cert = sslCfg.getCertificateFile(); String key = sslCfg.getKeyFile(); String keyPass = sslCfg.getKeyPassword(); if (null == cert || null == key) { throw new IllegalArgumentException("Check your SSL properties, something is wrong."); } ssl = SslContextBuilder.forServer(new File(cert), new File(key), keyPass); } ssl.ciphers(sslCfg.getUseCiphers()); // Can't set to REQUIRE because the CORS pre-flight requests will fail. ssl.clientAuth(ClientAuth.OPTIONAL); Boolean useOpenSSL = sslCfg.isUseOpenssl(); if (useOpenSSL) { ssl.sslProvider(SslProvider.OPENSSL); } else { ssl.sslProvider(SslProvider.JDK); } String trustStore = sslCfg.getTrustStoreFile(); if (null != trustStore) { if (!trustStore.isEmpty()) { ssl.trustManager(new File(trustStore)); } } return ssl.build(); }
@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)); }
private static ClientAuth parseClientAuthMode(String authMode) { if (null == authMode || authMode.trim().isEmpty()) { return ClientAuth.NONE; } for (ClientAuth clientAuth : ClientAuth.values()) { if (clientAuth.name().equals(authMode.toUpperCase())) { return clientAuth; } } return ClientAuth.NONE; }
@Override protected void initChannel(SocketChannel ch) throws Exception { SslContext sslContext = SslContextBuilder.forServer(config.getKeyMaterialSource().getPrivateKey(), config.getKeyMaterialSource().getCertificateChain()) .sslProvider(SslProvider.JDK) .trustManager(config.getTrustedCertificates().toArray(new X509Certificate[]{})) .clientAuth(ClientAuth.REQUIRE) .build(); ch.pipeline() .addLast(sslContext.newHandler(ch.alloc())) .addLast(new LoggingHandler(NettySslRoutingProxyInitializer.class, LogLevel.DEBUG)) .addLast(new SslInboundHandler(config)) .addLast(new RoutingProxyFrontendHandler()); }
@Test public void sslTrustCert() throws Exception { new MockUnit(HttpHandler.class) .expect(ssl(null)) .expect(unit-> { SslContextBuilder scb = unit.get(SslContextBuilder.class); expect(scb.trustManager(Paths.get("target", "unsecure.crt").toFile())).andReturn(scb); expect(scb.clientAuth(ClientAuth.REQUIRE)).andReturn(scb); }) .run(unit -> { assertNotNull(NettySslContext.build(conf.withValue("ssl.trust.cert", ConfigValueFactory.fromAnyRef("org/jooby/unsecure.crt")))); }); }
private ServerBuilder<?> serverBuilder(int port, File serverCertChainFile, File serverPrivateKeyFile, X509Certificate[] serverTrustedCaCerts) throws IOException { SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(serverCertChainFile, serverPrivateKeyFile); GrpcSslContexts.configure(sslContextBuilder, sslProvider); sslContextBuilder.trustManager(serverTrustedCaCerts) .clientAuth(ClientAuth.REQUIRE); return NettyServerBuilder.forPort(port) .sslContext(sslContextBuilder.build()); }
public SslContext toServerContext() throws SSLException { return GrpcSslContexts.configure(SslContextBuilder.forServer(cert, key), SslProvider.OPENSSL) .trustManager(trustedCerts) .clientAuth(ClientAuth.REQUIRE) .build(); }
/** An {@link SslContext} for use in unit test servers with client certs. Loads our testing certificates. */ public static SslContext serverSslContextWithClientCertsForTesting() throws IOException { return getSslContextBuilder() .clientAuth(ClientAuth.REQUIRE) .build(); }
@Override public void bind(final URI uri, final String subProtocols[], final AcceptListener listener){ final SslContext sslContext; if("wss".equals(uri.getScheme())){ try{ if(sslSettings==null){ SelfSignedCertificate ssc = new SelfSignedCertificate(); sslSettings = new SSLSettings().keyFile(ssc.privateKey()).certificateFile(ssc.certificate()); } ClientAuth clientAuth = ClientAuth.values()[sslSettings.clientAuthentication.ordinal()]; sslContext = SslContextBuilder.forServer(sslSettings.certificateFile, sslSettings.keyFile, sslSettings.keyPassword) .clientAuth(clientAuth) .trustManager(sslSettings.trustCertChainFile) .build(); }catch(Throwable thr){ listener.onError(thr); return; } }else if("ws".equals(uri.getScheme())) sslContext = null; else throw new IllegalArgumentException("invalid protocol: "+uri.getScheme()); int port = uri.getPort(); if(port==-1) port = sslContext==null ? 80 : 443; ServerBootstrap bootstrap = new ServerBootstrap() .group(eventLoopGroup) .channel(NioServerSocketChannel.class) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childOption(ChannelOption.MAX_MESSAGES_PER_READ, 50000) .childOption(ChannelOption.WRITE_SPIN_COUNT, 50000) .childHandler(new ChannelInitializer<SocketChannel>(){ @Override protected void initChannel(SocketChannel ch) throws Exception{ if(sslContext!=null) ch.pipeline().addLast(sslContext.newHandler(ch.alloc())); ch.pipeline().addLast( new HttpServerCodec(), new HttpObjectAggregator(65536), new Handshaker(uri, listener, subProtocols) ); } }); bootstrap.bind(uri.getHost(), port).addListener(new ChannelFutureListener(){ @Override public void operationComplete(ChannelFuture future) throws Exception{ if(future.isSuccess()){ channel = future.channel(); channel.attr(ACCEPT_LISTENER).set(listener); listener.onBind(NettyServerEndpoint.this); }else listener.onError(future.cause()); } }); }
@JsonProperty public ClientAuth getClientAuth() { return clientAuth; }
@JsonProperty public void setClientAuth(ClientAuth clientAuth) { this.clientAuth = clientAuth; }
@ValidationMethod(message = "must define keyManager when clientAuth is REQUIRE") public boolean isClientAuthConfigValid() { return clientAuth != ClientAuth.REQUIRE || keyManager != null; }
/** * Creates instance of Socket.IO server with the given secure port. */ public static SocketIOServer newInstance(int port, SSLContext sslContext) { SslContext nettySslContext = new JdkSslContext(sslContext, false, ClientAuth.NONE); return newInstance(port, nettySslContext); }