List of usage examples for io.netty.handler.ssl SslContextBuilder trustManager
public SslContextBuilder trustManager(TrustManager trustManager)
From source file:cf.dropsonde.firehose.NettyFirehoseOnSubscribe.java
License:Open Source License
public NettyFirehoseOnSubscribe(URI uri, String token, String subscriptionId, boolean skipTlsValidation, EventLoopGroup eventLoopGroup, Class<? extends SocketChannel> channelClass) { try {/*from w w w. j a va 2s . c o m*/ final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost(); final String scheme = uri.getScheme() == null ? "ws" : uri.getScheme(); final int port = getPort(scheme, uri.getPort()); final URI fullUri = uri.resolve("/firehose/" + subscriptionId); final SslContext sslContext; if ("wss".equalsIgnoreCase(scheme)) { final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient(); if (skipTlsValidation) { sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE); } else { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); sslContextBuilder.trustManager(trustManagerFactory); } sslContext = sslContextBuilder.build(); } else { sslContext = null; } bootstrap = new Bootstrap(); if (eventLoopGroup == null) { this.eventLoopGroup = new NioEventLoopGroup(); bootstrap.group(this.eventLoopGroup); } else { this.eventLoopGroup = null; bootstrap.group(eventLoopGroup); } bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 15000) .channel(channelClass == null ? NioSocketChannel.class : channelClass).remoteAddress(host, port) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel c) throws Exception { final HttpHeaders headers = new DefaultHttpHeaders(); headers.add(HttpHeaders.Names.AUTHORIZATION, token); final WebSocketClientHandler handler = new WebSocketClientHandler( WebSocketClientHandshakerFactory.newHandshaker(fullUri, WebSocketVersion.V13, null, false, headers)); final ChannelPipeline pipeline = c.pipeline(); if (sslContext != null) { pipeline.addLast(sslContext.newHandler(c.alloc(), host, port)); } pipeline.addLast(new ReadTimeoutHandler(30)); pipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192)); pipeline.addLast(HANDLER_NAME, handler); channel = c; } }); } catch (NoSuchAlgorithmException | SSLException | KeyStoreException e) { throw new RuntimeException(e); } }
From source file:com.floragunn.searchguard.ssl.DefaultSearchGuardKeyStore.java
License:Apache License
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); }// w ww .j av a2 s .co m return buildSSLContext0(_sslContextBuilder); }
From source file:com.floragunn.searchguard.ssl.DefaultSearchGuardKeyStore.java
License:Apache License
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); }/* w w w . ja v a2s. c om*/ return buildSSLContext0(_sslContextBuilder); }
From source file:com.floragunn.searchguard.ssl.SearchGuardKeyStore.java
License:Apache License
private void initSSLConfig() { final Environment env = new Environment(settings); log.info("Config directory is {}/, from there the key- and truststore files are resolved relatively", env.configFile().toAbsolutePath()); if (transportSSLEnabled) { final String keystoreFilePath = env.configFile() .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, "")) .toAbsolutePath().toString(); final String keystoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_TYPE, DEFAULT_STORE_TYPE);/*from w w w.ja v a 2 s . c o m*/ final String keystorePassword = settings .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_PASSWORD, DEFAULT_STORE_PASSWORD); final String keystoreAlias = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS, null); final String truststoreFilePath = env.configFile() .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, "")) .toAbsolutePath().toString(); if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH, null) == null) { throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_FILEPATH + " must be set if transport ssl is reqested."); } checkStorePath(keystoreFilePath); if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH, null) == null) { throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_FILEPATH + " must be set if transport ssl is reqested."); } checkStorePath(truststoreFilePath); final String truststoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_TYPE, DEFAULT_STORE_TYPE); final String truststorePassword = settings .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_PASSWORD, DEFAULT_STORE_PASSWORD); final String truststoreAlias = settings .get(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_TRUSTSTORE_ALIAS, null); try { final KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(new FileInputStream(new File(keystoreFilePath)), (keystorePassword == null || keystorePassword.length() == 0) ? null : keystorePassword.toCharArray()); transportKeystoreCert = SSLCertificateHelper.exportCertificateChain(ks, keystoreAlias); transportKeystoreKey = SSLCertificateHelper.exportDecryptedKey(ks, keystoreAlias, (keystorePassword == null || keystorePassword.length() == 0) ? null : keystorePassword.toCharArray()); if (transportKeystoreKey == null) { throw new ElasticsearchException( "No key found in " + keystoreFilePath + " with alias " + keystoreAlias); } if (transportKeystoreCert != null && transportKeystoreCert.length > 0) { //TODO create sensitive log property /*for (int i = 0; i < transportKeystoreCert.length; i++) { X509Certificate x509Certificate = transportKeystoreCert[i]; if(x509Certificate != null) { log.info("Transport keystore subject DN no. {} {}",i,x509Certificate.getSubjectX500Principal()); } }*/ } else { throw new ElasticsearchException( "No certificates found in " + keystoreFilePath + " with alias " + keystoreAlias); } final KeyStore ts = KeyStore.getInstance(truststoreType); ts.load(new FileInputStream(new File(truststoreFilePath)), (truststorePassword == null || truststorePassword.length() == 0) ? null : truststorePassword.toCharArray()); trustedTransportCertificates = SSLCertificateHelper.exportCertificateChain(ts, truststoreAlias); if (trustedTransportCertificates == null) { throw new ElasticsearchException("No truststore configured for server"); } final SslContextBuilder sslServerContextBuilder = SslContextBuilder .forServer(transportKeystoreKey, transportKeystoreCert) .ciphers(getEnabledSSLCiphers(this.sslTransportServerProvider, false)) .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED) .clientAuth(ClientAuth.REQUIRE) // https://github.com/netty/netty/issues/4722 .sessionCacheSize(0).sessionTimeout(0).sslProvider(this.sslTransportServerProvider) .trustManager(trustedTransportCertificates); transportServerSslContext = buildSSLContext(sslServerContextBuilder); if (trustedTransportCertificates == null) { throw new ElasticsearchException("No truststore configured for client"); } final SslContextBuilder sslClientContextBuilder = SslContextBuilder.forClient() .ciphers(getEnabledSSLCiphers(sslTransportClientProvider, false)) .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED).sessionCacheSize(0) .sessionTimeout(0).sslProvider(sslTransportClientProvider) .trustManager(trustedTransportCertificates) .keyManager(transportKeystoreKey, transportKeystoreCert); transportClientSslContext = buildSSLContext(sslClientContextBuilder); } catch (final Exception e) { throw new ElasticsearchSecurityException( "Error while initializing transport SSL layer: " + e.toString(), e); } } final boolean client = !"node".equals(this.settings.get(SearchGuardSSLPlugin.CLIENT_TYPE)); if (!client && httpSSLEnabled) { final String keystoreFilePath = env.configFile() .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH, "")) .toAbsolutePath().toString(); final String keystoreType = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_TYPE, DEFAULT_STORE_TYPE); final String keystorePassword = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_PASSWORD, DEFAULT_STORE_PASSWORD); final String keystoreAlias = settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_ALIAS, null); httpClientAuthMode = ClientAuth.valueOf(settings .get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_CLIENTAUTH_MODE, ClientAuth.OPTIONAL.toString())); //TODO remove with next version String _enforceHTTPClientAuth = settings.get("searchguard.ssl.http.enforce_clientauth"); if (_enforceHTTPClientAuth != null) { log.error("{} is deprecated and replaced by {}", "searchguard.ssl.http.enforce_clientauth", SSLConfigConstants.SEARCHGUARD_SSL_HTTP_CLIENTAUTH_MODE); throw new RuntimeException("searchguard.ssl.http.enforce_clientauth is deprecated"); } log.info("HTTPS client auth mode {}", httpClientAuthMode); final String truststoreFilePath = env.configFile() .resolve(settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, "")) .toAbsolutePath().toString(); if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH, null) == null) { throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_FILEPATH + " must be set if https is reqested."); } checkStorePath(keystoreFilePath); if (httpClientAuthMode == ClientAuth.REQUIRE) { if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, null) == null) { throw new ElasticsearchException(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH + " must be set if http ssl and client auth is reqested."); } } try { final KeyStore ks = KeyStore.getInstance(keystoreType); ks.load(new FileInputStream(new File(keystoreFilePath)), (keystorePassword == null || keystorePassword.length() == 0) ? null : keystorePassword.toCharArray()); httpKeystoreCert = SSLCertificateHelper.exportCertificateChain(ks, keystoreAlias); httpKeystoreKey = SSLCertificateHelper.exportDecryptedKey(ks, keystoreAlias, (keystorePassword == null || keystorePassword.length() == 0) ? null : keystorePassword.toCharArray()); if (httpKeystoreKey == null) { throw new ElasticsearchException( "No key found in " + keystoreFilePath + " with alias " + keystoreAlias); } if (httpKeystoreCert != null && httpKeystoreCert.length > 0) { //TODO create sensitive log property /*for (int i = 0; i < httpKeystoreCert.length; i++) { X509Certificate x509Certificate = httpKeystoreCert[i]; if(x509Certificate != null) { log.info("HTTP keystore subject DN no. {} {}",i,x509Certificate.getSubjectX500Principal()); } }*/ } else { throw new ElasticsearchException( "No certificates found in " + keystoreFilePath + " with alias " + keystoreAlias); } if (settings.get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_FILEPATH, null) != null) { checkStorePath(truststoreFilePath); final String truststoreType = settings .get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_TYPE, DEFAULT_STORE_TYPE); final String truststorePassword = settings.get( SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_PASSWORD, DEFAULT_STORE_PASSWORD); final String truststoreAlias = settings .get(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_TRUSTSTORE_ALIAS, null); final KeyStore ts = KeyStore.getInstance(truststoreType); ts.load(new FileInputStream(new File(truststoreFilePath)), (truststorePassword == null || truststorePassword.length() == 0) ? null : truststorePassword.toCharArray()); trustedHTTPCertificates = SSLCertificateHelper.exportCertificateChain(ts, truststoreAlias); } final SslContextBuilder sslContextBuilder = SslContextBuilder .forServer(httpKeystoreKey, httpKeystoreCert) .ciphers(getEnabledSSLCiphers(this.sslHTTPProvider, true)) .applicationProtocolConfig(ApplicationProtocolConfig.DISABLED) .clientAuth(Objects.requireNonNull(httpClientAuthMode)) // https://github.com/netty/netty/issues/4722 .sessionCacheSize(0).sessionTimeout(0).sslProvider(this.sslHTTPProvider); if (trustedHTTPCertificates != null && trustedHTTPCertificates.length > 0) { sslContextBuilder.trustManager(trustedHTTPCertificates); } httpSslContext = buildSSLContext(sslContextBuilder); } catch (final Exception e) { throw new ElasticsearchSecurityException("Error while initializing HTTP SSL layer: " + e.toString(), e); } } }
From source file:com.liferay.sync.engine.lan.server.file.LanFileServerInitializer.java
License:Open Source License
public void updateDomainNameMapping() { DomainNameMappingBuilder<SslContext> domainNameMappingBuilder = null; for (SyncAccount syncAccount : SyncAccountService.findAll()) { if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) { continue; }//from w w w. j a v a 2s.c o m SslContext sslContext = null; try { X509Certificate x509Certificate = LanPEMParserUtil .parseX509Certificate(syncAccount.getLanCertificate()); SslContextBuilder sslContextBuilder = SslContextBuilder .forServer(LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey()), x509Certificate); sslContextBuilder.clientAuth(ClientAuth.REQUIRE); sslContextBuilder.sslProvider(SslProvider.JDK); sslContextBuilder.trustManager(x509Certificate); sslContext = sslContextBuilder.build(); } catch (Exception e) { _logger.error(e.getMessage(), e); continue; } if (domainNameMappingBuilder == null) { domainNameMappingBuilder = new DomainNameMappingBuilder<>(sslContext); } domainNameMappingBuilder.add(LanClientUtil.getSNIHostname(syncAccount.getLanServerUuid()), sslContext); } if (domainNameMappingBuilder == null) { return; } _domainNameMapping = domainNameMappingBuilder.build(); }
From source file:com.relayrides.pushy.apns.ApnsClientBuilder.java
License:Open Source License
/** * Constructs a new {@link ApnsClient} with the previously-set configuration. * * @return a new ApnsClient instance with the previously-set configuration * * @throws SSLException if an SSL context could not be created for the new client for any reason * * @since 0.8// www . j a v a 2 s . com */ public ApnsClient build() throws SSLException { final SslContext sslContext; { final SslProvider sslProvider; if (this.preferredSslProvider != null) { sslProvider = this.preferredSslProvider; } else { if (OpenSsl.isAvailable()) { if (OpenSsl.isAlpnSupported()) { log.info("Native SSL provider is available and supports ALPN; will use native provider."); sslProvider = SslProvider.OPENSSL; } else { log.info( "Native SSL provider is available, but does not support ALPN; will use JDK SSL provider."); sslProvider = SslProvider.JDK; } } else { log.info("Native SSL provider not available; will use JDK SSL provider."); sslProvider = SslProvider.JDK; } } final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(sslProvider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig( new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2)); if (this.trustedServerCertificatePemFile != null) { sslContextBuilder.trustManager(this.trustedServerCertificatePemFile); } else if (this.trustedServerCertificateInputStream != null) { sslContextBuilder.trustManager(this.trustedServerCertificateInputStream); } else if (this.trustedServerCertificates != null) { sslContextBuilder.trustManager(this.trustedServerCertificates); } sslContext = sslContextBuilder.build(); } final ApnsClient apnsClient = new ApnsClient(sslContext, this.eventLoopGroup); apnsClient.setMetricsListener(this.metricsListener); apnsClient.setProxyHandlerFactory(this.proxyHandlerFactory); if (this.connectionTimeout != null) { apnsClient.setConnectionTimeout((int) this.connectionTimeoutUnit.toMillis(this.connectionTimeout)); } if (this.writeTimeout != null) { apnsClient.setWriteTimeout(this.writeTimeoutUnit.toMillis(this.writeTimeout)); } if (this.gracefulShutdownTimeout != null) { apnsClient.setGracefulShutdownTimeout( this.gracefulShutdownTimeoutUnit.toMillis(this.gracefulShutdownTimeout)); } return apnsClient; }
From source file:com.turo.pushy.apns.ApnsClientBuilder.java
License:Open Source License
/** * Constructs a new {@link ApnsClient} with the previously-set configuration. * * @return a new ApnsClient instance with the previously-set configuration * * @throws SSLException if an SSL context could not be created for the new client for any reason * @throws IllegalStateException if this method is called without specifying an APNs server address, if this method * is called without providing TLS credentials or a signing key, or if this method is called with both TLS * credentials and a signing key/* ww w .ja va 2 s. c om*/ * * @since 0.8 */ public ApnsClient build() throws SSLException { if (this.apnsServerAddress == null) { throw new IllegalStateException("No APNs server address specified."); } if (this.clientCertificate == null && this.privateKey == null && this.signingKey == null) { throw new IllegalStateException("No client credentials specified; either TLS credentials (a " + "certificate/private key) or an APNs signing key must be provided before building a client."); } else if ((this.clientCertificate != null || this.privateKey != null) && this.signingKey != null) { throw new IllegalStateException("Clients may not have both a signing key and TLS credentials."); } final SslContext sslContext; { final SslProvider sslProvider; if (OpenSsl.isAvailable()) { log.info("Native SSL provider is available; will use native provider."); sslProvider = SslProvider.OPENSSL_REFCNT; } else { log.info("Native SSL provider not available; will use JDK SSL provider."); sslProvider = SslProvider.JDK; } final SslContextBuilder sslContextBuilder = SslContextBuilder.forClient().sslProvider(sslProvider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE); if (this.clientCertificate != null && this.privateKey != null) { sslContextBuilder.keyManager(this.privateKey, this.privateKeyPassword, this.clientCertificate); } if (this.trustedServerCertificatePemFile != null) { sslContextBuilder.trustManager(this.trustedServerCertificatePemFile); } else if (this.trustedServerCertificateInputStream != null) { sslContextBuilder.trustManager(this.trustedServerCertificateInputStream); } else if (this.trustedServerCertificates != null) { sslContextBuilder.trustManager(this.trustedServerCertificates); } sslContext = sslContextBuilder.build(); } final ApnsClient client = new ApnsClient(this.apnsServerAddress, sslContext, this.signingKey, this.proxyHandlerFactory, this.connectionTimeoutMillis, this.idlePingIntervalMillis, this.gracefulShutdownTimeoutMillis, this.concurrentConnections, this.metricsListener, this.frameLogger, this.eventLoopGroup); if (sslContext instanceof ReferenceCounted) { ((ReferenceCounted) sslContext).release(); } return client; }
From source file:com.turo.pushy.apns.MockApnsServerBuilder.java
License:Open Source License
/** * Constructs a new {@link MockApnsServer} with the previously-set configuration. * * @return a new MockApnsServer instance with the previously-set configuration * * @throws SSLException if an SSL context could not be created for the new server for any reason * * @since 0.8/* w w w . j a va 2 s . c o m*/ */ public MockApnsServer build() throws SSLException { final SslContext sslContext; { final SslProvider sslProvider = SslUtil.getSslProvider(); final SslContextBuilder sslContextBuilder; if (this.certificateChain != null && this.privateKey != null) { sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword, this.certificateChain); } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) { sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile, this.privateKeyPkcs8File, this.privateKeyPassword); } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) { sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream, this.privateKeyPkcs8InputStream, this.privateKeyPassword); } else { throw new IllegalStateException("Must specify server credentials before building a mock server."); } sslContextBuilder.sslProvider(sslProvider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .clientAuth(ClientAuth.OPTIONAL).applicationProtocolConfig( new ApplicationProtocolConfig(Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2)); if (this.trustedClientCertificatePemFile != null) { sslContextBuilder.trustManager(this.trustedClientCertificatePemFile); } else if (this.trustedClientCertificateInputStream != null) { sslContextBuilder.trustManager(this.trustedClientCertificateInputStream); } else if (this.trustedClientCertificates != null) { sslContextBuilder.trustManager(this.trustedClientCertificates); } sslContext = sslContextBuilder.build(); } final MockApnsServer server = new MockApnsServer(sslContext, this.eventLoopGroup); server.setEmulateInternalErrors(this.emulateInternalErrors); server.setEmulateExpiredFirstToken(this.emulateExpiredFirstToken); return server; }
From source file:com.turo.pushy.apns.server.BaseHttp2ServerBuilder.java
License:Open Source License
/** * Constructs a new server with the previously-set configuration. * * @return a new server instance with the previously-set configuration * * @throws SSLException if an SSL context could not be created for the new server for any reason * * @since 0.8/*from ww w . j a v a2 s . c om*/ */ public T build() throws SSLException { final SslContext sslContext; { final SslProvider sslProvider; if (OpenSsl.isAvailable()) { log.info("Native SSL provider is available; will use native provider."); sslProvider = SslProvider.OPENSSL; } else { log.info("Native SSL provider not available; will use JDK SSL provider."); sslProvider = SslProvider.JDK; } final SslContextBuilder sslContextBuilder; if (this.certificateChain != null && this.privateKey != null) { sslContextBuilder = SslContextBuilder.forServer(this.privateKey, this.privateKeyPassword, this.certificateChain); } else if (this.certificateChainPemFile != null && this.privateKeyPkcs8File != null) { sslContextBuilder = SslContextBuilder.forServer(this.certificateChainPemFile, this.privateKeyPkcs8File, this.privateKeyPassword); } else if (this.certificateChainInputStream != null && this.privateKeyPkcs8InputStream != null) { sslContextBuilder = SslContextBuilder.forServer(this.certificateChainInputStream, this.privateKeyPkcs8InputStream, this.privateKeyPassword); } else { throw new IllegalStateException("Must specify server credentials before building a mock server."); } sslContextBuilder.sslProvider(sslProvider) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .clientAuth(ClientAuth.OPTIONAL); if (this.trustedClientCertificatePemFile != null) { sslContextBuilder.trustManager(this.trustedClientCertificatePemFile); } else if (this.trustedClientCertificateInputStream != null) { sslContextBuilder.trustManager(this.trustedClientCertificateInputStream); } else if (this.trustedClientCertificates != null) { sslContextBuilder.trustManager(this.trustedClientCertificates); } if (this.useAlpn) { sslContextBuilder.applicationProtocolConfig( new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2)); } sslContext = sslContextBuilder.build(); } final T server = this.constructServer(sslContext); if (sslContext instanceof ReferenceCounted) { ((ReferenceCounted) sslContext).release(); } return server; }
From source file:com.yahoo.pulsar.broker.service.PulsarChannelInitializer.java
License:Apache License
@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 {//from w w w . j av a2 s . c om 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 PulsarLengthFieldFrameDecoder(PulsarDecoder.MaxFrameSize, 0, 4, 0, 4)); ch.pipeline().addLast("handler", new ServerCnx(brokerService)); }